task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Madotsuki Pattern (MDT1)
Madotsuki is the main character of the surreal adventure game Yumenikki. The poor girl ended her life after discard all of her properties that have been found in the dream. Every year there are some small celebrations among people. The most symbolic sign of Madotsuki is the pattern on her clothes ...
(image taken from
github.com/madotsuki
)
You have been given a n*m design. Each element is one of the following character '1', '0', '?'. You can freely choose each '?' to become '0' or '1', to maximizate the number madotsuki pattern in the design.
which the madotsuki pattern is somethings like this:
101
010
Remark
010
101
is not a madotsuki pattern.
Input
(Multiply test cases, for each test case)
n m ( n <= 1000, m <= 10)
[n*m '0', '1' or '?']
Output
For each test case, output the maximum answer, and how many design can reach the answer in total. Since the answer can be very huge, you only need to output it after mod 1,000,000,007.
Example
Input:
2 4
2 4
????
????
4 6
??????
?1010?
?0101?
??????
Output:
1 8
6 4 | 33,100 |
Determine the vismin value ! (KOSPC13B)
There are N students in a class. The teacher wants to test the acuity of the students' vision as well as mind in an entertaining way. She comes up with an idea.
The students were made to stand in a line and are numbered from 1 to N, each carrying a board with a number K on it. The test is as follows: the teacher calls out a student X; the student can look at either sides and choose a student Y who carries a board with a number greater than or equal to the number on the board carried by X and calculates a value called as "vismin value". "vismin value" is defined as the product of the difference between the positions of X and Y and the smallest of the numbers on the boards carried by X and Y. If it is not possible to choose Y, "vismin value" will be 0.
Now, the way the students are tested is how far the students maximise the "vismin value". For each student called, he/she answers with a "vismin value". If it is maximum, teacher says "Maximum". If there is a greater value possible, the teacher says the value which the student is running short of, to attain the maximum value. If the value said by the student is greater than the maximum value possible, the teacher says "Not possible".
Consider yourself as the teacher and print the output accordingly.
Input
The first line of the input consists of N, the number of students in the class.
The second line consists of N space separated integers K representing the numbers on the boards carried by the respective students.
Then, each line/query consists of a student number separated by the vismin value determined by the student.
Input ends with both student number and vismin value equal to 0.
Output:
For each query, print what the teacher would have said.
Constraints
1 <= N <= 100000
1 <= k <= 10^9
Number of queries <= 10000
Sample
Input:
5
5 3 6 7 1
1 13
1 18
1 15
4 5
5 4
0 0
Output:
2
Not possible
Maximum
Not possible
Maximum | 33,101 |
Card Meets (medium) (GUMATH2)
Guardian is very weak at maths but still to compete in a certain exam he has to get good grades in mathematics this time. In the first class of the semester the Prof. asked students to find the number of ways deck (having N cards) could be shuffled that exactly one card is at the same position as before, and the students who successfully do this will be awarded with good marks in mid terms. Help Guardian solve this problem.
Input
The input begins with the number T of test cases. In each of the next T lines there are one integer N.
Output
For each test case you have to output on a single line the number of ways possible meeting the Prof.'s requirements.
As the answer can be a huge number, output it modulo 10000009.
Example
Input:
1
3
Output:
3
Let's say the initial deck configuration was {1, 2, 3}, then three possible shuffles are {1, 3, 2}, {2, 1, 3}, {3, 2, 1}.
Constraints
1 < T < 10
4
0 < N < 10
18
@speed addicts : my C code ran in 0.08s, and my python3 code ran in 3.2s. (Total time with Pyramid cluster)
Edit 19/I/2015 : Now the problem use Cube cluster, rejudge of my old code gave 0.01s with C, and 0.57s with Py3.2 (this last one ends in 0.42s with PY3.4)
Edit 11-02-2017, after compiler changes : 0.00s with C, 0.22s with PY3.5. New TL. | 33,102 |
Special Graph (SPECIALG)
You are given a directed graph with N vertices. The special thing about the graph is that each vertex has at most one outgoing edge. Your task is to answer the following two types of queries:
1 a
delete the only edge outgoing from vertex a. It is guaranteed that the edge exists. 1 ≤ a ≤ N.
2 a b
output the length of the shortest path from vertex a to vertex b, if the path exists. Otherwise output "-1" without quotes. 1 ≤ a, b ≤ N.
Input
First line of input contains a natural number N ≤ 10
5
the number of vertices in the graph.
The following line contains N integer numbers, i-th number is next[i] (0 ≤ next[i] ≤ N), meaning that there is an edge from vertex i to vertex next[i]. If next[i] = 0, assume that there is no outgoing edge from vertex i.
Third line contains a natural number M ≤ 10
5
the number of queries.
The following M lines contain a query each. Queries are given in the manner described above.
Output
On the i-th line output the answer for the i-th query of type 2 a b.
Example
Input:
6
3 3 4 5 6 4
6
2 1 6
2 1 4
2 1 2
1 3
2 1 6
2 1 4
Output:
4
2
-1
-1
-1 | 33,103 |
Room Change (CHGROOM)
It's the end of the semester and best friends Anne and Marian have finally gotten permission from the hostel supervisor to swap rooms and become room mates. Both of them are extremely happy to hear this, but one problem still remains. Although Anne and Marian definitely want to be room mates, both of them are also very attached to their current rooms and neither of them wants to move out.
After a lot of discussion regarding who should be the one to shift rooms, they decide to settle the matter in the following manner:
Both Anne and Marian write down, independently, 2 positive integers k1 and k2. Then, the value q = ( k1 + k2 - 1 ) is written down on a piece of a paper. Anne is the first person to make a move. During each move, the current player writes down any integer number that is a non-trivial divisor of the last written number.
The first person who can't make a move wins
, and the other person is the one who needs to shift into the winner's room.
Given that both players play optimally, output the name of the person who wins the game for a given value of q.
NOTE
: A number's divisor is said to be non-trivial if it is different from one and from the divided number itself.
Input
The input contains a single integer q (1 <= q <= 10
13
).
Output
On a single line output "ANNE" if Anne wins. Else output "MARIAN". Note that the quotes are just for clarity, and that the output is case-sensitive.
Example
Input #1:
6
Output #1:
MARIAN
Input #2:
30
Output #2:
ANNE
Input #3:
1
Output #3:
ANNE
Explanation
Input #1
: 6 has exactly 2 non-trivial divisors - { 2, 3 }. But neither of these numbers have any non-trivial divisors. So no matter which one Anne writes down, Marian will win since she cannot make any move
Input #2
: Since 6 is a non-trivial divisor of 30, Anne writes down 6. Now, as can be seen from input #1, no matter what move Marian makes, Anne will win.
Input #3
: Since 1 has no non-trivial divisors, Anne wins. | 33,104 |
Card Game (HC12)
John is playing a game with his friends. The game's rules are as follows: There is deck of
N
cards from which each person is dealt a hand of
K
cards. Each card has an integer value representing its strength. A hand's strength is determined by the value of the highest card in the hand. The person with the strongest hand wins the round. Bets are placed before each player reveals the strength of their hand.
John needs your help to decide when to bet. He decides he wants to bet when the strength of his hand is higher than the average hand strength. Hence John wants to calculate the average strength of ALL possible sets of hands. John is very good at division, but he needs your help in calculating the sum of the strengths of all possible hands.
Problem
You are given an array
a
with
N ≤ 10 000
different integer numbers and a number,
K
, where
1 ≤ K ≤ N
. For all possible subsets of
a
of size
K
find the sum of their maximal elements modulo
1 000 000 007
.
Input
The first line contains the number of test cases
T
, where
1 ≤ T ≤ 25
Each case begins with a line containing integers
N
and
K
. The next line contains
N
space-separated numbers
0 ≤ a [i] ≤ 2 000 000 000
, which describe the array
a
.
Output
For test case
i
, numbered from
1
to
T
, output "Case #i: ", followed by a single integer, the sum of maximal elements for all subsets of size
K
modulo 1 000 000 007.
Sample
Input:
5
4 3
3 6 2 8
5 2
10 20 30 40 50
6 4
0 1 2 3 5 8
2 2
1069 1122
10 5
10386 10257 10432 10087 10381 10035 10167 10206 10347 10088
Output:
Case #1: 30
Case #2: 400
Case #3: 103
Case #4: 1122
Case #5: 2621483 | 33,105 |
One X LIS (ONEXLIS)
For a given sequence a[1], a[2] ... a[n], lets call a subsequence a[k
1
] ... a[k
i
] ... a[k
m
] (where 1 <= k
i
<= n and k
i
i+1
) as
"one X increasing subsequence
" if there is exactly one i between 1 and m-1 (inclusive) for which a[k
i
]>a[k
i+1
]. Given a sequence find the length of the longest "one X increasing subsequence".
Input
First line contains t, which denotes the number of test cases. 2×T lines follow. Each test case is described using 2 lines.
First line of a test case contains an integer- n, which denotes the number of elements in the array.
Second lines contains n integers, which represent a[i] 1 ≤ i ≤ n.
1 ≤ t ≤ 20
1 ≤ n ≤ 100000
1 ≤ a[i] ≤ 10
9
Output
For each test case, print one integer which represents the number of integers in the One X LIS. The output for each test case should be printed on a new line.
Example
Input:
2
5
4 3 3 4 1
5
5 4 3 2 1
Output:
4
2
Explanation
In the first test case, the Longest Increasing Subsequence is 3.3.4 whereas the longest One X Subsequence is 4.3.3.4 whose length is 4.
In the second example, any two elements can be chosen to form the longest One X Subsequence, which gives us an answer of 2. | 33,106 |
Factor y Hell (FCTRHELL)
Factorial(N) in base B : The number of trailing zeros.
Factorial(
19
) in base
9
×10^
0
=9 can be written 72573550063508
0000
, ending with
4
zeros.
Factorial(
43
) in base
2
×10^
1
=20 can be written 59HHHFECFCCEGH5G7I7A3A8G88F8CD8G
000000000
, ending with
9
zeros.
What about working with serious constraints and tricky cases ?
Factorial(
N
) will be a huge one, the base will be dummy too and have the special form :
B
×10^
E
.
Input
The input begins with the number T of test cases in a single line.
In each of the next T lines there are three integers : N, B, E.
Output
For each test case, print the number of zeros at the end of Factorial(N) written in base B×10^E.
Example
Input:
3
19 9 0
43 2 1
10000 100 10
Output:
4
9
208
Constraints
1 <= T < 2000
1 <= N < 10^1000
1 <= B < 10^9
0 <= E < 10^9
Informations
Don't worry about the 'special' base 1 (B=1 and E=0), it is absent from input.
About distribution : random input (N : log-uniform, B : uniform, E : uniform) in their range. Some tricky cases are added.
It is recommended to solve
FACTBASE
first, and find a way to solve
FCTRL
much faster than common solutions.
Time limit is ×13.6 my best Python3 time, or ×1.33 my "basic" one. | 33,107 |
Expected Time to Love (PRLOVE)
Alice has a problem. She loves Bob but is unable to face up to him. So she decides to send a letter to Bob expressing her feelings. She wants to send it from her computer to Bob's computer through the internet.
The internet consists of $N$ computers, numbered from $1$ to $N$. Alice's computer has the number $1$ and Bob's computer has the number $N$.
Due to some faulty coding, the computers start behaving in unexpected ways. On recieving the file, computer $i$ will forward it to computer $j$ with probability $P_{ij}$. The time taken to transfer the file from computer $i$ to computer $j$ is $T_{ij}$.
Find the expected time before Bob finds out about Alice's undying love for him.
Note:
Once the letter is recieved by Bob's computer, his computer will just deliver it to Bob and stop forwarding it.
Input
First line contains $T$, the total test cases.
Each test case looks as follows:
First line contains $N$, the total number of computers in the network.
The next $N$ lines contain $N$ numbers each. The $j$'th number on the $i$'th line is the value $P_{ij}$ in percents.
The next $N$ lines contain $N$ numbers each. The $j$'th number on the $i$'th line is the value $T_{ij}$.
Output
Output a single line with a real number - The expected time of the transfer.
Your output will be considered correct if each number has an absolute or relative error less than $10^{-6}$.
Constraints
$N \le 100$
$T \le 5$
For all $i$, $P_{i1} + P_{i2} + \ldots + P_{iN} = 100$
$P_{NN} = 100$
For all $i$, $j$, $0 \le T_{ij} \le 10000$
You can safely assume that from every computer, the probability of eventually reaching Bob's computer is greater than $0$.
Example
Sample Input:
2
4
0 50 50 0
0 0 0 100
0 0 0 100
0 0 0 100
0 2 10 0
0 0 0 0
0 0 0 0
0 0 0 0
2
99 1
0 100
10 2
0 0
Sample Output:
6.000000
992.000000 | 33,108 |
Security (HC12II)
You are designing a new encryption system that works in the following way:
For server-client communication you need a key
k
, composed of
m
sections, each of length
l
, and the key consists only of lowercase characters in the set {a, b, c, d, e, f}. The server has a key
k1
and the client has a key
k2
where:
k1 = f(k).
f
is a function that receives a key and replace some random letters by ? indicating that those characters can be any lowercase letter of the set described before.
k2 = f(g(k)).
g
is a function that takes a key and produces a random permutation of its m sections. And
f
is the function defined above.
For example: let m = 3, l = 2
f('abacbc') = '?ba??c'
g('abacbc') = 'acbcab' (each section was moved one place to the left).
Your task is given
k1
and
k2
, find key
k
. If there are several solutions, print the lexicographically smallest key. And if there is no solution at all, print "IMPOSSIBLE" (without the quotes).
Input
The first line has a single integer
T
, which corresponds to the number of test cases.
T
test cases follows: the first line of the test case corresponds to the integer
m
, the second line contains the string
k1
and the third line contains the string
k2
.
Output
For test case
i
, numbered from
1
to
T
, output "Case #i: ", followed by the lexicographically smallest key or "IMPOSSIBLE".
Example
Input:
5
2
abcd
c?ab
3
ab?c?c
ac?c??
3
ab?c?c
aabbdd
2
aa
bb
2
abcd
cdab
Output:
Case #1: abcd
Case #2: abacac
Case #3: IMPOSSIBLE
Case #4: IMPOSSIBLE
Case #5: abcd
Constraints:
T <= 20
0 < |k1| <= 100
0 < m <= 50
|k2| = |k1|
It is guaranteed that m is always a divisor of |k1|
k1 and k2 consist of {a, b, c, d, e, f, ?} | 33,109 |
Dead Pixels (HC12III)
John's friend Peter purchases a new high resolution monitor with dimension
W
*
H
where
W
is the number of pixels in each row (i.e. width) and
H
is the number of pixels in each column (i.e. height).
However, there are
N
dead pixels on the monitor. The
i
-th dead pixel is located at (
x
[
i
],
y
[
i
]). (0, 0) is the top-left pixel and (
W
- 1,
H
- 1) is the bottom-right pixel. The locations of the dead pixels could be generated by 6 given integers
X
,
Y
,
a
,
b
,
c
and
d
by the following rules. If 2 pixels are at the same location, they are considered the same. It is possible that there are less than
N
distinct
dead pixels.
x[0] = X
y[0] = Y
x[i] = (x[i - 1] * a + y[i - 1] * b + 1) % W (for 0 < i < N)
y[i] = (x[i - 1] * c + y[i - 1] * d + 1) % H (for 0 < i < N)
Peter connects his monitor to his computer and opens an image with dimension
P
(width) *
Q
(height). How many unique positions can the image be placed so that it can be displayed perfectly (i.e. all pixels of the picture are shown on the monitor)? The image cannot be rotated.
Input
The first line contains an integer
T
, which is the number of test cases. Then
T
test cases follow. Each test case contains 11 integers
W
,
H
,
P
,
Q
,
N
,
X
,
Y
,
a
,
b
,
c
,
d
.
Output
For each of the test cases numbered in order from 1 to
T
, output "Case #", followed by the case number (with 1 being the first test case), followed by ": ", followed by an integer which is the number of different possible positions for the image.
Example
Input:
5
4 4 2 2 1 0 2 1 2 3 4
4 4 1 1 3 1 1 2 2 2 2
6 10 3 2 2 0 0 5 4 3 2
16 18 5 1 5 10 8 21 27 29 87
14 15 12 4 4 3 5 84 74 53 68
Output:
Case #1: 7
Case #2: 15
Case #3: 32
Case #4: 197
Case #5: 16
Constraints
1 ≤ T ≤ 20
1 ≤ W, H ≤ 40 000
1 ≤ P ≤ W
1 ≤ Q ≤ H
1 ≤ N ≤ min(1 000 000, W * H)
1 ≤ a, b, c, d ≤ 100
0 ≤ X < W
0 ≤ Y < H | 33,110 |
Charu and Coin Distribution (CBANK)
One day Charu went to deposit his pocket money in the Bank. But there was one problem that he wanted to deposit exactly "N" rupees, and he has coins of 0.25, 0.50, 1.0, and 2.0 rupees; and number of coins of each type are "4*N"; So he wants to know how many ways are there such that he can deposit exactly "N" rupees in bank using any number of coins of each type. As Charu is poor in counting he wants your help, Given input "N", give the number of ways of depositing "N" rupees using coins of 0.25, 0.50, 1.0, and 2.0 rupees. Since the answer can be really large, output the remainder when the answer is divided by 1000000007.
Input
First line will be t, number of test cases (T <= 10000). The next t lines, each line contains N (N <= 1e9).
Output
The output should contain one line per test case, representing the answer to the given problem.
Example
Input:
2
1
2
Output:
4
10
Explanation
In first case {.25, .25, .25, .25}, {.50, .25, .25}, {1}, {.50, .50} | 33,111 |
BATMAN1 (BAT1)
Lucius Fox:
This conversation used to end with an unusual request.
Bruce Wayne:
I'm retired
.
Lucius Fox:
Well let me show you some stuff anyway. Just for old time's sake
.
Eight years after Harvey Dent's death, the Dent Act allowed eradication of organized crime. BATMAN has disappeared. Wayne enterprises is unprofitable after Bruce discontinued his fusion reactor project. A masked man called Bane who was trained under Ra's al Ghul captures Gordon. Bane attacks the Gotham Stock Exchange, using Bruce's fingerprints in a transaction that bankrupts Wayne.
Now that Gotham City was heading into deep deep trouble, Its time for BATMAN to return.
However, since the company no longer belongs to Bruce Wayne, Mr. Wayne has very little funds to spend on buying his weapons. Mr Fox head him to the place where all weapons are stored.
Now these weapons come in batches properly sealed for safety. Each of these batches will have an unbounded number of weapons of different types. To buy these weapons Wayne initially need to pay the price for opening the seal. Then each of these weapons have a cost and a power rating associated with it. Mr Wayne needs to spend wisely on it to maximize the power rating using limited amount of money.
People of Gotham, he needs your help for choosing his weapons.
Lucius Fox:
It has a long uninteresting name. I just took to calling it... The Bat, and yes, Mr. Wayne, it does come in black.
Input
t, number of test cases
integers n m k, n: number of batches, m: number of weapons per batch, k : Money Wayne can spend on weapons
n integers giving cost of opening the ith batch
n × m numbers denoting cost of jth object from ith batch
n × m numbers denoting the rating of jth object from ith batch
Output
The maximum power rating Wayne could afford
Constraint:
1 ≤ n, m ≤ 20
k ≤ 1000
cost[i] ≤ 20
rating[i] ≤ 100
Example
Input:
1
2 4 20
3 4
3 2 3 2
3 2 3 5
3 2 3 2
4 5 6 5
Output:
40 | 33,112 |
BATMAN2 (BAT2)
Alfred: "
I'll get this to Mr. Fox, but no more. I've sewn you up, I've set your bones, but I won't bury you. I've buried enough members of the Wayne family.
"
After being promised the software to erase her criminal record, Catwoman agrees to take Batman to Bane. They manage to defeat all of Bane's men but ended up heading into a MAZE trap. Bane would call this maze as the LIS MAZE. He would hide himself in one of the rooms. Each of these rooms have a number (tag) associated with it. The speciality of the maze is that once you enter any room it will only lead you to rooms with a higher tag in the direction you move. Batman and Catwoman decide to move in opposite directions trying their luck to maximize the number of rooms they search. (They can start with any room, need not be the same)
Catwoman: "
Never steal from someone you can't outrun, kid.
"
Input
t, number of testcases.
n, number of rooms.
n integers giving the tag associated with the rooms.
Output
The maximum number of rooms searched.
Constraints
1 ≤ n ≤ 100
Example
Input:
1
6
5 3 4 6 1 2
Output:
5 | 33,113 |
BATMAN3 (BAT3)
Bruce Wayne:
I do fear death. I fear dying in here while my city burns.
Blind Prisoner:
Then make the climb.
Bruce Wayne:
How?
Blind Prisoner:
As the child did. Without the rope. Then fear will find you again.
The Epic fight between BANE and BATMAN saw BATMAN on the losing side. Bane delivers a crippling blow to Batman's back, then takes him to a foreign, well-like prison where escape is virtually impossible.
The prison as we know is a place from where no man ever escaped, except for the child of Ra's al Ghul himself.
The heroics of BATMAN saw him escape the prison, however after the prison came the Valleys. To reach the city, He needed to cross these valleys. Meanwhile, BANE's army has surrounded the city and trapped all the policemen underground. Each of these peaks contain exactly one policeman held captive by Bane's men. Since, BATMAN needs to build his own army, he decides to free some of the policemen on his way.
Also BATMAN needed to save his energy before his battle with Bane, so he decided to take only downhill (strictly) jumps. Detective John Blake (now called as ROBIN) is standing in one of these peaks with a mini-BAT. This will allow BATMAN to take a maximum one jump uphill ahead. BATMAN can choose to flee ROBIN and use the BAT or rather cross over without his help.
The task in hand is to maximize the army strength to face BANE as BATMAN crosses over. (BATMAN can take his first jump on any of these peaks)
Bane:
So, you came back to die with your city.
Batman:
No. I came back to stop you.
Input
t: number of test cases.
n: number of peaks.
m: (zero based) index of the peak where ROBIN is standing.
n integers denoting the height of the peaks.
Output
The maximum strength of the army.
Constraints
1 ≤ n ≤ 1000
Example
Input:
1
6 4
6 3 5 2 4 5
Output:
4 | 33,114 |
BATMAN4 (BAT4)
Batman: "
A hero can be anyone. Even a man doing something as simple and reassuring as putting a coat around a little boy's shoulder to let him know that the world hadn't ended.
"
THE BOMB IS TRIGGERED !!, IT WOULD BLOW UP IN A FEW MINUTES !!
BATMAN resorts to his BAT and decides to head towards the ocean with the bomb.
However in front of him lies a huge grid of tall buildings. Starting from the top-leftmost grid he needs to move to the bottom right-most grid to reach the ocean. Since the fuel of BAT has nearly exhausted, BATMAN decides to chose a path where the maximum up distance travelled at a time is minimized. However, each movement of the BAT up or down the building takes one unit of time. (Horizontal movements can be made in no time). The clock keeps ticking, So BATMAN decides to choose a path reaching the destination minimizing the maximum up distance and with as much time left as possible.
Every Hero Has a Journey. Every Journey Has an End !
CatWoman : "
You don't owe these people anymore. You've given them everything.
"
BatMan : "
Not everything, not yet
."
NOTES :
BatMan requires to take the first jump on (1, 1)
Print NO is no time is left.
Minimum max up-distance is the first priority.
Input
The first line contains T, the number of test cases.
In each test case, the first line contains N (the size of the grid) and M (the time left).
The next N lines contain N integers, denoting the heights of the building.
Output
If BATMAN could reach the destination, print "
YES
", the maximum up distance travelled and the maximum time left with BATMAN.
If he could not reach the destination within time, print "
NO
".
Constraints
1 ≤ N ≤ 20
1 ≤ M ≤ 100
Example
Input:
1
3 40
2 4 3
4 5 3
2 4 6
Output:
YES : 2 32 | 33,115 |
Tjandra 19th birthday (EASY) (TJANDRAS)
This day (7 February 2013) is my 19th birthday
So, I want to celebrate it on SPOJ by making this EASY puzzle problem.
This game/puzzle is about matches, given
n
matches, your task is to arrange the matches (not necessarily all) such that number of rectangle (any size) is maximum.
Input
First line there is an integer
T
≤ 100 then
T
lines follow, each line contain an integer
n
< 1.000.000.000.
Output
For each test case, output required answer (maximum number of rectangles)
Example
Input:
5
3
4
8
12
15
Output:
0
1
3
9
12
Explanation
-->First test case: No rectangle can be formed with only 3 matches
-->Second test case: Only one rectangle can be formed with 4 matches
-->Third test case:
there are max 3 rectangles (2 size 1×1, 1 size 2×1) can be formed with number of matches ≤ 8, here is one of the matches formation:
-->Fourth test case:
there are max 9 rectangles (4 size 1×1, 2 size 2×1, 2 size 1×2, 1 size 2×2) can be formed with number of matches ≤ 12, here is one of the formation:
-->Fifth test case:
there are max 12 rectangles (5 size 1×1, 3 size 2×1, 1 size 3×1, 2 size 1×2, 1 size 2×2) can be formed with number of matches ≤ 15, here is one of the formation:
Information
Time limit≈150x my program speed, Enjoy this birthday party game, I set this problem such that semi naive solution will pass..
See also:
Another problem added by Tjandra Satria Gunawan | 33,116 |
Check (KNGCHECK)
Chess is a two-player strategy board game played on a chessboard, a square checkered game board with 64 squares arranged in an eight-by-eight grid. It is one of the world's most popular games, played by millions of people worldwide at home, in clubs, online, by correspondence, and in tournaments. Each player begins the game with 16 pieces: one king, one queen, two rooks, two knights, two bishops, and eight pawns. Each of the six piece types moves differently. Pieces are used to attack and capture the opponent's pieces, with the objective to 'checkmate' the opponent's king by placing it under an inescapable threat of capture. In addition to checkmate, the game can be won by the voluntary resignation of the opponent, which typically occurs when too much material is lost, or if checkmate appears unavoidable. A game may also result in a draw in several ways, where neither player wins. The course of the game is divided into three phases: opening, middle game, and endgame. Source Wikipedia
To simplify this problem you will only deal with kings, knights and pawns of the black and the white players. Assume that the white player starts at the lower half of the board and the black player starts at the upper half. Given the state of the board, your task is to determine whether the black king is checked or not. For clarity a 'Check' occurs when the King's square can be attacked by any of the opponent's pieces for his next move, and note that in this problem we will ignore the consequences which will follow, we don’t even care whose turn is now but only consider the board state (out of chess rules).
The knight moves like an "L", it moves from cell (r1, c1) to cell (r2, c2) if and only if (r1 - r2)
2
+ (c1-c2)
2
= 5 (8 possible moves).
The king can move only one move in its four main directions and its four diagonals (8 possible moves).
The pawn attacks only one move diagonally and only to the opponent direction (2 possible moves).
This problem is
NOT
following all chess rules, for example in real chess third case in the sample is INVALID, so please assume that the given board is always valid, just check the black king state.
Input
You are given an 8×8 board with chess pieces denoted as following: BK = black king, WK = white king, BH = black knight, WH = white knight, BP = black pawn, WP = white pawn. We ensure that there is one and only one black king in the chess board. Blank fields are denoted by “-”. Cases are separated by blank lines.
Output
You should output “Check” if a check exists or “Not Check” if no check exists. Follow the output format described in the sample tests.
Example
Input:
3
- - - - - - - -
- - - - - - - -
- - - - - - - -
- BH - - - - - -
- - - BK - - - -
- - WP - - - - -
- - - - - - - -
- - - - - - - -
- - - - - - - -
BH - - BH - - - -
- - - - - - - -
- - - - - - - -
- - - BK - - - -
- - - - - - - -
- WP - - - - WH -
- - - WK - - - -
- - - - - - - -
- - - - - - - -
- - - - - - - -
- - - - - - - -
- - - BK - - - -
- - - WK - - - -
- - - - - - WH -
- - - - - - - -
Output:
Case #1: Check
Case #2: Not Check
Case #3: Check | 33,117 |
Transitive Closure (TRANCLS)
In mathematics, a set S is transitive if whenever an element a is related to an element b, and b is in turn related to an element c, then a is also related to c. In other words, any set of pairs is transitive if and only if you have (a, b) and (b, c) then you also must have (a, c). Check this example: S = { (1, 2), (2, 3), (3, 4), (2, 4) }. Is set S is transitive relation ? No, Because you have (1, 2) and (2, 3) but you don’t have (1, 3) If we add (1, 3) will it be transitive ? ((S = { (1, 2), (2, 3), (3, 4), (2, 4), (1, 3) } )) No, Because you have (1, 3) and (3, 4) but you don’t have (1, 4) If we add (1, 4) will it be transitive ? ((S = { (1, 2), (2, 3), (3, 4), (2, 4), (1, 3), (1, 4) } )) Yes, Now the set S is now transitive after we added 2 pairs { (1, 3), (1, 4) } These pairs called transitive closure (which means the minimal pairs that convert set S into a transitive set). Your task is given the set S you have to output the minimal pairs have to be added to make the set S transitive.
Input
The first line of input is the number of test cases T where (0 < T ≤ 100), Each test case you'll be given the number of pairs in the set N where (0 < N ≤ 100), followed by N pairs (a, b) where (0 ≤ a, b < N).
Output
For each test case print "Case_#i:_X" where "i" is the case number, "X" is the minimal number of pairs have to be added to make the set transitive and "_" is a white space. Each test case should be in a separate line.
Example
Input:
3
4
0 1
1 2
2 3
1 3
2
0 1
1 0
1
0 0
Output:
Case #1: 2
Case #2: 2
Case #3: 0 | 33,118 |
finding maximum possible number (MAX_NUM)
Given a number n, find the maximum possible number you can make by deleting exactly k digits.
T : number of test cases ≤ 10
3
.
1 ≤ number of digits in n ≤ 10
5
. (n might contain leading zeros.)
0 ≤ k ≤ n
if value of n is equal to k. then just print a new line.
Input
T: number of test cases.
T lines follow each with n and k.
Output
The maximum possible number.
Example
Input:
2
1223 2
8756 2
Output:
23
87
Explanation
Note that left to right order should be maintained. As in the example given answer is 23 not 32. | 33,119 |
SHAHBAG (SHAHBG)
They say "History repeats itself" and this is what happening in Bangladesh on Feb 2013. Mass people fought the war in 1971 and now they are rising again to fight war criminals who betrayed the country. In "Shahbag" you can hear the voice of people wanting justice.
If you go to shahbag you can see many human chains. For this problem we imagine a straight line going through middle of shahbag. Each position of the line is marked from 1 to 20000.
People are forming human chains along the line. Initially every position is empty. When someone stands in i
th
position he holds hand of people who are standing in his left and right(if there any) and join there group. If there are no people beside him, he forms a new group.
When a new people come your job is to mark his position and count currently how many groups are there in shahbag.
For example suppose:
a man came first and stood in postion 2. Currently there are only 1 group.
then another man stood in position 4. Currently there are 2 groups.
another man stood in position 3. Now there are only 1 group.
And yes, people won't leave until they get justice, so no need to worry about that. mi
Input
There will be a single case. First line will contain an integer Q which denotes number of people. Next line will contain Q (1 <= Q <= 20000) integers p
i
which denotes position of i-th people that joined the chain. Each p
i
will be distinct and at most 20000.
Output
For each pi print number of groups currently in shahbag. In last line print the string "
Justice
" with a newline. Do not print any extra spaces.
Example
Sample Input:
6
2 4 3 6 7 5
Sample output:
1
2
1
2
2
1
Justice
Note:
This problem is based on true event. You can find the details
here.
Alternate writer: Rashedul Hasan Rijul | 33,120 |
Happy Valentine Day (Valentine Maze Game) (A_W_S_N)
Happy Valentine Day!
Picture Source:
http://www.printactivities.com/Mazes/Shape_Mazes/Heart_Maze.html
In this valentine day, Tjandra Satria Gunawan (TSG) have a mission to date with A** W****** S****** N******(AWSN), Before TSG meet AWSN, TSG want to collect all the chocolate in entire land/maze then share all the chocolate with AWSN later, but AWSN doesn't like to wait, so TSG must collect all chocolate as fast as possible before meet AWSN. Please help TSG to complete this mission. Given a map size
m
×
n
(1<
m
,
n
≤100), and the map:
'
#
' denoting wall (TSG can't walk to this area)
'
.
' denoting road (TSG can walk to this area)
'
C
' denoting chocolate (also walkable area, appear less than 10 times on the map)
'
T
' denoting
T
SG (also walkable area, only appear once on the map)
'
W
' denoting A
W
SN (also walkable area, only appear once on the map)
Tjandra can move up, down, left or right, and cost one unit of time every movement.
Input
The first line of input, there's one integer
T
(
T
≤30) denoting number of test case, then
T
case(s) follow,
For each test case:
--> First line contains two integers
m
and
n
denoting size of map
--> next
m
line(s) contains
n
characters that's the map description.
Output
For each test case, output minimum of time required to complete this mission, if it's impossible to complete this mission, output "
Mission Failed!
" without quotes.
Example
Input:
8
3 3
T..
...
..W
3 6
######
#T..W#
######
3 6
######
#T#.W#
######
3 6
##C###
#T..W#
######
3 6
C#C###
.T..W#
######
5 10
##########
#T.#.C#..#
#..#..#..#
#..W..#..#
##########
5 10
##########
#T.#.C#.C#
#..#..#..#
#..W..#..#
##########
5 10
##########
#C.#.C#.C#
#..#..#..#
#..T..W..#
##########
Output:
4
3
Mission Failed!
5
9
12
Mission Failed!
23
Time Limit ≈ 5*(My Program (Semi Bruteforce) Speed)
See also:
Another problem added by Tjandra Satria Gunawan | 33,121 |
Crack the Safe (SAFECRAC)
Johnny (not little anymore) is a super agent .He is been following up on leads against the world’s worst terrorists. He got a intel that a terrorist is staying at an expensive hotel. Only thing that stops LJ is the secure door in the room entrance.
The secure door had a lock which resembled this,
1
2
3
4
5
6
7
8
9
0
Enter
The enter key cannot be a part of the pass-code
When Johnny did some spy work on it, he found out that every pair of neighbouring digits in the pass code is adjacent on the keypad. Adjacent means that the digits share a common edge.
Now he wants to know how many different possibilities are there for the pass code so that he can bring a computer accordingly to hack the lock.
Input
Input begins with single integer ‘T’ denoting number of test cases and T lines follow. Each line contains the number ‘N’ denoting the length of the pass code.
Output
For each test case T, output the number of different possibilities in a new line. Since the answer can be huge output the number mod 1000000007.
Constraints:
1 <= T <= 1,000
1 <= N <= 100,000
Sample
Input:
2
3
25
Output:
74
478325846 | 33,122 |
Amazing Prime Sequence (APS)
Bablu is very fond of Series and Sequences...
After studying Fibonacci Series in Class IX, he was impressed and he designed his own sequence as follows...
a[0] = a[1] = 0
For n > 1, a[n] = a[n - 1] + f(n), where f(n) is smallest prime factor of n.
He is also very fond of programming and thus made a small program to find a[n], but since he is in Class IX, he is not very good at programming. So, he asks you for help. Your task is to find a[n] for the above sequence....
Input
Your code will be checked for multiple test cases.
First line of Input contains T (≤ 100), the number of test cases.
Next T lines contain a single number N. (1 < N < 10
7
).
Output
Single line containing a[n] i.e. nth number of the sequence for each test case.
Example
Input:
3
2
3
4
Output:
2
5
7 | 33,123 |
An Experiment by Penny (CRAN01)
Penny started studying in a community college. However she did not tell Leonard about this because she did not want Leonard helping her at every point in her studies. This went well until the professor ordered her to perform an advanced experiment. In this experiment she was given an advanced microbiological specimen. This specimen is placed in an n × m size grid which is divided into 1 × 1 cells.
It expands according to following rules.
If at time t, the specimen occupies (x, y), then at time t + 1 it can expand to at most any two cells out of (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1).
For example if at t = 0 sec if the specimen occupies (4, 5), then at time t = 1 sec, the state of the grid can be any of the following:
specimen at (4, 5), (5, 5) and (3, 5).
specimen at (4, 5), (5, 5) and (4, 6).
specimen at (4, 5), (5, 5) and (3, 4).
specimen at (4, 5), (3, 5) and (4, 6).
specimen at (4, 5), (3, 5) and (4, 4).
specimen at (4, 5), (4, 6) and (4, 4).
Note -
At t = 2 sec, it can expand from all the points that the specimen occupied at t = 1.
The professor asks penny to find the minimum time it takes for the specimen to fill the entire grid.
Since penny is not so smart at math and she can't ask Leonard to help her, she turns to you for help and to find the solution to above problem.
Input
T - The number of test cases.
n m - number of row and columns in the grid.
x y - coordinate of the initial position of the specimen.
Output
The minimum time in seconds it takes for specimen to fill in the entire grid.
Constraints
1 <= T <= 50
1 <= n, m <= 500
1 <= x <= n
1 <= y <= m
Example
Input:
2
1 1
1 1
10 10
6 4
Output:
0
11 | 33,124 |
Roommate Agreement (CRAN02)
Leonard was always sickened by how Sheldon considered himself better than him. To decide once and for all who is better among them they decided to ask each other a puzzle. Sheldon pointed out that according to Roommate Agreement Sheldon will ask first. Leonard seeing an opportunity decided that the winner will get to rewrite the Roommate Agreement.
Sheldon thought for a moment then agreed to the terms thinking that Leonard will never be able to answer right. For Leonard, Sheldon thought of a puzzle which is as follows. He gave Leonard n numbers, which can be both positive and negative. Leonard had to find the number of continuous sequence of numbers such that their sum is zero.
For example if the sequence is: 5, 2, -2, 5, -5, 9, there are 3 such sequences:
2, -2
5, -5
2, -2, 5, -5
Since this is a golden opportunity for Leonard to rewrite the Roommate Agreement and get rid of Sheldon's ridiculous clauses, he can't afford to lose. So he turns to you for help. Don't let him down.
Input
First line contains T - number of test cases
Second line contains n - the number of elements in a particular test case.
Next line contain n elements, a
i
(1 ≤ i ≤ n) separated by spaces.
Output
The number of such sequences whose sum if zero.
Constraints
1 ≤ t ≤ 5
1 ≤ n ≤ 10
6
-10 ≤ a
i
≤ 10
Example
Input:
2
4
0 1 -1 0
6
5 2 -2 5 -5 9
Output:
6
3 | 33,125 |
Audition (CRAN04)
Penny is a terrible waitress and even worse actress, however recently she applied for a role in an upcoming TV series. Even though she thought she had no chance, she was called for an audition. She was very happy about it until she found out that her character in this new series will be a studious, high IQ girl named Megan. Producer told her that to get the role of Megan she had to prove that her mind can handle a bit of mathematics and reasoning. If she passed the test then she will be given the role of Megan. The test was as follow.
The people (Boys and Girls) who came for audition are standing in a line in a random order. Producer has to select exactly K boys for the show. So he asks Penny to tell how many ways can he select two numbers i and j such that the number of boys standing between these (including I and j) indexes is exactly K.
Penny desperately needs this role. Everybody knows that Penny is not a very smart and requests you to help her.
Input
First line contains T – The number of test cases.
Next line contains space separated N and K.
N – The total number of boys and girls who came to audition.
K – The number of the boys who must be there between each (i, j) pair.
Next line contains a non-empty string consisting of '1' and '0'.
1 represents Boy.
0 represents Girl.
Output
The number of (i, j) pairs such that the number of boys between index i and j, both inclusive is equal to K.
Constraints
1<=T<=10
1<=N<=10^6
0<=K<=10^6
Example
Input:
3
4 1
0101
5 2
01010
5 4
01010
Output:
6
4
0 | 33,126 |
Loving Power (LOVINGPW)
Angel Luis is now getting math class. His teacher is teaching to him the XOR operation:
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
When a number has more than one bit, the operation is applied to all bits. The teacher write two numbers x, y (0 <= x, y <= N) and make the XOR operation between x and y, Angel Luis would like to know how many pairs x, y such x XOR y = 2
z
where z >= 0.
See that for N = 3:
0 XOR 1 = 2
0
0 XOR 2 = 2
1
3 XOR 1 = 2
1
2 XOR 3 = 2
0
So there are 4 pairs.
Given N you should return the number of pairs modulo 1000000007.
Input
First line contains number t - the number of cases. Following t lines will each have a number N.
t <= 100
N <= 1000000000000000 (10
15
).
Output
For each case the number of pairs modulo 1000000007.
Example
Input:
3
1
2
3
Output:
1
2
4 | 33,127 |
Naive Loki (NAIVELOK)
Loki has succeeded in his devilish scheme and opened the portal to Asgard to summon his army to Earth.
To protect Earth from this predicament, Iron Man must find a way to close this portal. He notices that the passcode on the portal is a
palindromic
string S. Also no character in this string occurs more than
2
times. Iron man can remove any number of characters from this string. Genius that he is, he deduces that the portal will close whenever the string is not a palindrome. But that is too easy for him. So he waits and wonders how many different ways there are to achieve this. Two ways are considered different if there exists an i such that character at index i is removed in one way and not removed in another.
Input
The first line of input contains a single line T, which represents the number of test cases. Then T lines will follow, and each contains a palindromic string S.
Output
Print the required answer for each test case in a new line. Since the number can be large print it modulo 1000000007.
Constraints
1 <= T <= 1000
1 <= |S| <= 100, where |S| represents the length of the string S.
The string S is case-sensitive, and will contain only characters in the range [a-z], [A-Z], [0-9].
There would be at most two positions in S which will contain same character.
Example
Input:
2
AA
b99b
Output:
0
6
Explanation
In the first sample case there is no way in which string can be converted to non-palindrome.
In the second sample case there are 6 ways to convert string to non-palindromic namely:
Remove 1
st
character: 99b
Remove 1
st
, 2
nd
characters: 9b
Remove 1
st
, 3
rd
characters: 9b
Remove 2
nd
, 4
th
characters: b9
Remove 3
rd
, 4
th
characters: b9
Remove 4
th
character: b99 | 33,128 |
Dexter Rank (DEXTER)
Dexter just participated in a coding contest and is now waiting for judge to give final result. He is very bored of waiting every time for result and now wants to find his expected rank based on current scoreboard and chances of failure for problems. Formally there are M problems in the contest and there are N coders in the contest. Dexter knows that coder i has submitted problem j with penalty of penalty[i][j]. Dexter knows that problem j will pass with probability prob[j] (this also applies for Dexter himself.) This is independent for each coder and problem. Now Dexter wants to know what would be his expected rank after system test.
Note: Coders are ranked based on number of correct solution, then total penalty for correct solutions. If there is tie even after that, all coders with same problems and penalty are given same rank.
Example: After system test if the score board is like this:
Coder 1:
300
-1
-1
Score: 1
Penalty: 300
Coder 2:
100
-1
200
Score: 2
Penalty: 300
Coder 3:
-1
300
-1
Score: 1
Penalty: 300
Coder 4:
-1
-1
400
Score: 1
Penalty: 400
Ranks would be: 2 1 2 4
Input
The first line of input contains a single line
T
, which represents the number of test cases. For each test case first line contains two space separated integers
N
and
M
.
Then Next
N
lines contains
M
integers, j
th
integer on i
th
is penalty[i][j] which means penalty for i
th
coder on problem j, if he submitted j
th
problem, otherwise it is -1.
Dexter is first coder in the list.
Then next line contains
M
space separated integers, where i
th
integer denotes probability of passing problem i in system test, if submitted.
Output
Print the expected rank of the Dexter after system test with exactly
4
decimal places.
Constraints
1 ≤ T ≤ 16
2 ≤ N ≤ 256
1 ≤ M ≤ 12
1 ≤ penalty[i][j] ≤ 1000000 or penalty[i][j] = -1
0 ≤ prob[i] ≤ 100
Example
Input:
3
2 1
100
150
50
2 2
-1 -1
10 -1
0 100
3 2
100 200
-1 199
99 -1
50 50
Output:
1.2500
1.0000
1.6250
Explanation
For sample case 1, Dexter would have first rank if his solution passes or coder-2’s solution fails system test which has probability 0.75, otherwise he would have rank 2.
answer = 1×0.75 + 0.25×2 = 1.2500
For sample case 2, all coders would be on rank 1 with 0 problem solved and 0 penalty in all cases, so answer = 1.0000. | 33,129 |
X-MEN (XMEN)
Dr. Charles Xavier is trying to check the correlation between the DNA samples of Magneto and Wolverine. Both the DNAs are of length
N
, and can be described by using all integers between
1
to
N
exactly once. The correlation between two DNAs is defined as the Longest Common Subsequence of both the DNAs.
Help Dr. Xavier find the correlation between the two DNAs.
Input
First line of input contains number of test cases
T
. Each test case starts with an integer
N
, size of DNA. The next two lines contains
N
integers each, first line depicting the sequence of Magneto's DNA and second line depicting Wolverine's DNA.
Output
For each test case print one integer, the correlation between the two DNAs.
Example
Input:
2
2
1 2
2 1
3
1 2 3
1 3 2
Output:
1
2
Constraints
1 ≤
T
≤ 10
1 ≤
N
≤ 100000 | 33,130 |
Chaos In Arkham (CHAOS_CC)
Mayhem has struck Arkham Asylum!
Both Bane and Joker are running free in Arkham and rescuing other prisoners. The prison of Arkham consists of
N
cells in a row. To decide who is superior, they play the following game: Both take turns alternately, and in each turn a player can open any one cell of the prison. They define a block of
3
consecutive open prison cells as a "crime hole". The first one to create a "crime hole" wins and is declared as the Ultimate Villain of Gotham. Joker plays first.
As we know Bruce Wayne always keeps track of his enemies. In this situation he needs a program to decide who will emerge as the Ultimate Villain if both play optimally.
Input
First line of input contains number of Test Cases T, followed by T lines. On each line you are given a single integer N, depicting the number of prison cells.
Output
For each N, print "Bane" if Bane wins, else print "Joker". (Quotes for clarity)
Constraints
1 <=
T
<= 3333
3 <=
N
<= 3333
Example
Input:
3
3
5
6
Output:
Joker
Joker
Bane
Explanation
Let us denote the open cells by 'o' and closed cells by '-'.
Case one:
Initially all cells are closed(---), if Joker opens first cell configuration is (o--). Bane can either open second cell leading to configuration (oo-) or third cell (o-o). In both cases Joker wins on his next turn.
Case two:
Joker wins by opening the 3rd cell first i.e. configuration (--o--). | 33,131 |
Rage Drug (RDRUG)
Dr. Banner (a.k.a. The Hulk) is synthesizing a drug that will help him control his rage. There are a total of N atoms of various atomic masses.
Banner knows that to create a bond between two atoms the energy required is equal to the sum of the atomic masses of the two atoms.
Currently some of the atoms are connected to one another forming compounds.
Banner wants to join all separate atoms and compounds into a single compound by creating chemical bonds. Each atom can form at max one more bond. Help Dr. Banner to find out the minimum energy required to synthesize his drug.
Input
Input starts with an integer T, the number of test cases. Each test case starts with a line containing integers N, M denoting the number of atoms and the number of bonds already formed respectively. M lines contain 2 integers i and j denoting a chemical bond between the ith and the jth atom. The next N lines contains one integer each where the integer on ith line denotes the atomic mass of the ith atom.
Output
Print T lines, where the ith line is the answer to the ith test case. If it is not possible to link the atoms print -1;
PS: If you mislead Dr. Banner, he might lose his temper and SMASH you to bits.
Constraints
1 ≤ T ≤ 12
1 ≤ N ≤ 100000
1 ≤ AtomicMass ≤ 10000
0 ≤ M ≤ 10
6
(1000000)
1 ≤ i, j ≤ N
Example
Input:
2
6 6
1 2
2 3
1 3
4 5
5 6
4 6
1
3
5
2
4
6
4 0
1
2
3
4
Output:
3
-1 | 33,132 |
Colors (COLOR_CC)
Given a Bipartite graph with N nodes, you have to colour each node in a way such that no two adjacent nodes have the same colour. Each node is allowed to choose colour from a subset of colours. Print the possible number of ways.
You are given a symmetric matrix i.e. matrix[i][j] is always equal to matrix[j][i]. If matrix[i][j] == 'Y' then nodes i and j are connected by an edge matrix[i][j] == 'N' then nodes i and j are not connected.
Input
T number of test cases (T test cases follow).
N number of nodes in graph. N lines corresponding to matrix. N line follows: each line contains xi -- total colours ith node can take, followed by i colours.
Output
Print the possible number of ways to colour the graph.
Constraints
T will be less than 20
0 <= N <= 13, size of matrix will be N * N, and each element of matrix would be either 'Y' or 'N'.
Number of colours a node can take would be greater than equal to 0 and less than equal to 8. Colour number would be less than 100000.
Example
Input
1
4
NYNN
YNNN
NNNY
NNYN
3 1 2 3
2 4 5
3 4 5 6
3 1 2 3
Output
54 | 33,133 |
ISRANK (ISRANK)
There are
N
schools, with i th school having
S
i
students. There is a inter-school programming contest
IPC
in which all the schools participate. As
IPC
is a very prestigious event, the schools conduct a test run within themselves. They assign a predicted rank for students within the school for all students, based on the rank they got in the test run. Let
P
ij
be the predicted rank of
j
th student of
i
th school. The predicted rank will be unique within the school, i.e. formally:
It should be noted that students of different schools may have the same predicted rank.
At the end of IPC, the IPC committee has given each school the result card containing the marks of all students of that school. Let
M
ij
represent the actual marks obtained by the
j
th student of
i
th school. IPC follows a strict rule of giving unique marks to all students taking part in IPC, i.e. formally:
You are to design a system, which will efficiently answer queries of the following form:
L
- the number of schools to be considered
A1 A2 A3 .... AL
- the list of schools
P1 P2
- The range of predicted ranks
K
- desired rank
You are to answer - among all the students who attended the given list of schools and with predicted ranks between
P1
and
P2
both inclusive, the marks of the student with
K
th highest marks. (The first highest marks would the the maximum marks, and second would be the next and so on)
Input
First line contains a single integer
N
, the number of schools.
The next line contains
N
space separated integers
S
i
.
The next
N
lines, the
i
th line contains
S
i
space separated integers,
j
th of which is denoting
P
ij
.
The next
N
lines, the
i
th line contains
S
i
space separated integers,
j
th of which is denoting
M
ij
.
The next line contains a single integer
Q
, denoting the number of queries.
Whats follows are
Q
sets of queries. Each query is structured as follows.
First line of the query is
L
, the list of schools.
Followed by
L
integers denoting the
1 based
indices of schools.
Next are
P1
and
P2
, the range of ranks we are interested in.
Next is the integer
K
.
Output
For each query on a separate line print a single integer answering the query. If answer is not possible print -1
Constraints
1 ≤
N
≤ 10
1 ≤
S
i
≤ 10000
1 ≤
P
ij
≤
S
i
1 ≤
M
ij
≤ 1000000000
1 ≤
Q
≤ 10000
1 ≤ P1 ≤ P2 ≤ max(S[i])
1 ≤ K ≤ sum of all S[i]
Sample Input
4
1 3 4 1
1
1 2 3
2 3 1 4
1
28
20 11 8
6 18 22 26
7
4
1
2
3 3
1
1
2
3 3
1
3
1 3 4
4 4
1
4
1 2 3 4
4 4
4
Sample Output
8
8
26
-1 | 33,134 |
India in Box (INBOX)
There is a well-known challenge in India. The challenge is as follows:
A merchant had some boxes. The boxes had weight and cost. He wants to give K boxes to one guy and the rest to other guy. Each guy has an average that is calculated by taking (Sum of Weights) / (Sum of Costs) of this guy. He wants to know what the smallest possible sum of the averages of the two guys he can achieve by making the distribution of the boxes.
Your task is to solve the challenge.
Input
The input contains several test cases. A test case begins with a line containing two integers N and K (1 ≤ K < N ≤ 100) representing the total number of boxes and the value of K, respectively. The next N lines contains two integers each, w
i
and c
i
(1 ≤ w
i
, c
i
≤ 50), indicating the weight and cost of the ith box, respectively.
The last test case is followed by a line containing a single 0.
Output
For each test case, print a line containing a single value, the smallest possible sum of the averages, accurate to 5 decimal places.
Example
Input:
8 4
2 1
3 2
4 3
5 4
6 5
7 6
8 7
10 8
0
Output:
2.49845 | 33,135 |
Pheversos Game (PGAME)
Pheverso's Game
Matheus Pheverso is a well-known rogue, as everyone knows he used to be very mean with the couple in love, Danilo Ghyei and Raphael Boboleta. But now he's trying to change into being a better person. In order to do that, he will call some friends over to play his newest game and throw a game party next year.
The game “Pheverso's Game” is played in rounds by two contestants in which each one must pick one cell from a M×N board, add its number to the group's total score and then throw it away. Also, in order to avoid cheating, each cell is previously chosen and no one is allowed to choose a cell if it isn't at the beginning or at the end of some row. You also have to notice that when one cell is dropped, the row from where the cell has been taken gets a new configuration, resulting in a new beginning or a new end.
Pheverso was playing that game with some friends and realized it's way too easy, so he decided to choose some rows and block their beginnings. When a row is blocked, a group is only able to choose a cell from the end of this row.
The goal of the game for each contestant is to hoard as much as they can, so the winner of the game is the one who holds the maximum amount of points in the end of the game. The game finishes when there are no remaining cells.
Assuming that they both plays optimally and given the N, M dimensions, the initial state of the board, the rows that are blocked, which player wins the game and what's the score of the winner.
Input
The input contains several test cases. A test case begins with a line containing integers N (1 ≤ N ≤ 1000), M (1 ≤ M ≤ 1000) and K (0 ≤ K < N), where N, M stands for the board dimensions and K for the total number of rows blocked. On the second line there are K integers, the rows that are blocked. Then follow N lines, each containing M integers representing the initial state of the board.
Every number in the board is a 32 bit signed integer. The last test case is followed by a line containing three zeros.
Output
For each test case, print a line containing “first” (without the quotes) if the first player will win the game or “second” (without the quotes) if the second player will win the game, followed by an integer representing the amount achieved by the winner when both of them plays optimally. The game always has a winner.
Example
Input
2 2 2
1 2
500 10
3 10
3 3 2
1 3
0 1 2
3 7 4
0 0 9
0 0 0
Output
second 503
first 17
Explanation:
First Case – At first the two rows are blocked, so both players aren't able to choose either cell A[1][1] = 500 or A[2][1] = 3. Thus, the first player isn't able to grab the cell A[1][2] either, cause he would unlock to his opponent the greatest piece in the board, A[1][1] = 500. So he choose the cell A[2][2] = 10. Afterward his opponent grabs the cell A[2][1] = 3, force the first player to choose A[1][2] and set free the greatest piece in the board, therefore the second player is the winner achieving 503 total points (A[1][1] + A[2][1]) against 20 from the first player.
Second Case – The game is as follows:
First player: 9
Second player: 2
First player: 1
Second player: 3
First player: 7
Second player: 4
First player: 17 (Winner)
Second player: 9
Remember, both contestants plays optimally. | 33,136 |
The Grandslam of Grandslams! (WIMB)
My boss hates me. He hates me to the extent where he plans meetings which clash with a Wimbledon match, almost all the time. Now, to give myself some inner peace, I decided to play well - while also trying to at least pray, that the matches I want to watch stretch enough for me to watch when I get back home.
But hey, wait! I may have a shot here! At Wimbledon, matches are played only at day light, so maybe if players were not ready to give up easily on each point, then the match will extend until sunset - just for my convenience!
So what I need to know is how long on average a game between two players will last, and to help me feel better you should write a computer program to determine that!
The result of a tennis match is determined by the number of “sets” each player wins, the first player to win three sets wins the match. Accordingly, all possible match results are 3-0, 3-1 and 3-2. The result of each set is determined by the number of “games” in the set each player wins, the first player to win six or more games with two or more game difference from the opponent wins the set, however if the result of a set (including the last set) leveled at 6-6 then a tie-break game is played to determine the set winner, Accordingly all possible set results are 6-0, 6-1, 6-2, 6-3, 6-4, 7-5 and 7-6 using a tie breaker game!
During each game (including tie-break), one player has the serve, this means that this player must start the play for all points of the game by hitting the ball, serving the ball is considered a big advantage. Assume that the serve starts at the first player and then alternates after each game till the end. Given the probability of winning a game on serve for each player against his opponent, and assuming that each game lasts for five minutes, calculate the expected duration of the match.
Input:
The first line of input contains an integer T, the number of test cases. The first line of each test case contains the first and last names of the first player, followed by an integer (0 <= A <= 100) where A/100 is the probability that the first player wins a game on his serve against the second player. The second line contains the first and last names of the second player, followed by an integer (0 <= B <= 100) where B/100 is the probability that the second player wins a game on his serve against the first player.
Output:
For each test case, print the duration of the match in minutes rounded to six decimal digits.
Sample
Input:
2
Pete Sampras 50
Rafael Nadal 50
Roger Federer 100
Arjit Srivastava 0
Output:
199.281006
90.000000
How?
In the second test case, I don’t stand a chance against Pete! He always wins all games on his serve (probability 100/100) and he also always wins all games on my serve (as I win with probability 0/100), so he always wins the match with three straight sets (6-0, 6-0, 6-0), a total of 18 games played, each lasting five minutes for a total of 90 minutes match. | 33,137 |
Tjandra 19th birthday present (HARD) (TJANDRA2)
The 07 February 2013 was Tjandra's 19th birthday,
I want to make a present to him and all other great SPOJ solvers by the way.
So I set this HARD puzzle problem extension of the yet good
TJANDRAS
.
Warning :
To solve the 'easy' task, you need a O(N^0.5) algorithm,
but to solve this 'harder' task, you need something around O(N^0.34),
so it's not about optimization tricks!!!
Please note that I checked my data with my 'semi-brute-force'-O(N^0.5)-Python3-solution and it took me 16 hours.
Don't forget to have fun with that problem!
The Game
This game/puzzle is about matches, given N matches,
your task is to arrange the matches (not necessarily all)
such that the number of rectangles (any size) is maximum.
Input
The input begins with the number T of test cases in a single line.
In each of the next T lines there are one integer N.
Output
For each test case, on a single line, print the required answer
(maximum number of rectangles).
Example
Input:
6
3
4
8
12
15
987654321123456789
Output:
0
1
3
9
12
60966316127114768913148159571503206
Constraints
1 < T ≤ 100
1 < N ≤ 10^18
The T numbers N are uniform-randomly chosen in the range.
Explanations
First test case:
No rectangle can be formed with only 3 matches.
Second test case:
Only one rectangle can be formed with 4 matches.
Third test case:
There are max 3 rectangles.
(2 size 1x1, 1 size 2x1) can be formed with number of matches ≤ 8,
here is one of the matches formation:
Fourth test case:
There are max 9 rectangles.
(4 size 1x1, 2 size 2x1, 2 size 1x2, 1 size 2x2) can be formed with number of matches ≤ 12, here is one of the formation:
Fifth test case:
there are max 12 rectangles.
(5 size 1x1, 3 size 2x1, 1 size 3x1, 2 size 1x2, 1 size 2x2) can be formed with number of matches ≤ 15, here is one of the formation:
Sixth test case:
You have to figure by yourself how to compute that in the required time. | 33,138 |
Super Borboletas World (SBW)
Raphaell is a well-known programmer who created the biggest game development company in the world, BGM (Boboleta's GameMaker). As recently one of its game – S.B.W (Super Borboleta's World) - has became very popular, Raphaell decided to make an online version of S.B.W's game. In order to do this he'll expose the source code and the mechanism of that game so anyone is able to improve it.
At first the game is made of three main operations in which the user is able to call as much as necessary. As the game is composed by K arrays of lists where each list has at most N integers on it, the three operations can be described in the following way:
Operation <2> <x> <y>: Insert the integer <y> to the end of the <x>-th list.
Operation <1> <x> <y>: Clean every list whose index lie on the range between <x> and <y> (inclusive).
Operation <0> <x> <y>: In each list between <x> and <y> calculate all the possible consecutive XOR sum's, where XOR stands for the operation Exclusive OR, and return the maximum value of all possible XOR sum's.
Raphaell has access to the original pseudocode which is given below:
m ← array( array() )
def
insert(x, y):
insert y to m[x]
def
clear(x, y):
for
i←x to y:
clear m[i]
def
max_xor(x, y):
best ← 0
for
i←0 to sizeOf m[x]:
sum_xor ← 0
for
j←i to sizeOf m[x]:
sum_xor ← sum_xor (xor) m[x][j]
best ←
max
(best, sum_xor)
if
x < y:
best ←
max
(best, max_xor(x + 1, y))
return
best
This implementation was efficient to the offline version of the game. However, as the online version may receive a thousands of players at once, it's necessary for many optimizations to run the game properly. Even though his friend has already tried really hard to figure a way to improve the performance, he hasn't got any good results till now.
Input
The input contains several test cases. A test case begins with a line containing an integer Q (1 ≤ Q ≤ 10^5), where Q represents the number of operations that are going to be performed. Then follow Q lines, each containing an operation. All the operations are as described above:
0 x y: In each list between x and y calculate all the possible consecutive XOR sum's and return the maximum possible value.
1 x y: Clean every list whose index lie on the range between x and y inclusive.
2 x y: Insert the integer y to the end of the x-th list.
Both x and y in every operation will never exceed 10^14. The last test case is followed by a line containing a single 0.
Output
For each query <0> <x> <y> print a line containing a single integer representing the maximum possible XOR as described above.
Example
Input:
14
2 2 1
2 2 2
2 2 1
2 2 1
2 2 2
2 3 1
2 3 2
2 3 7
0 1 2
0 2 3
1 3 3
0 1 3
1 1 3
0 1 3
0
Output:
3
7
3
0 | 33,139 |
Mosty! Find Gn (M_SEQ)
Omar want to examine Mostafa in math, Mostafa asked to give G(n) that defined as:
while:
Mostafa need your help to find G(n) (n : given integer)
assume that : F(1) = 8, F(2) = 8;
Input
T number of test cases in the first line, T line follow with an integer n.
Output
Print G(n) for each test case with 8 decimal digits after the point (0 < G(n) < 3)
Example
Input:
3
5
7
42
Output:
2.20000000
2.14285714
2.02380952
Constraints
T < 10
4
2 < n < 10
9 | 33,140 |
Discrete Roots (DISCRT)
In this problem, we try to compute discrete k
th
root modulo n; given n, k, a; find all the solutions for x such that x
k
= a (mod n) and x is coprime with n.
Input
For each input file, there are 3 space separated integers n, k, a.
n = p
e
for some odd prime p, integer e > 0; 0 <= a < n <= 10
9
, 0 <= k < phi(n), where phi is Euler's totient function; the numbers n, a are coprimes.
Output
The first line of the output contains a single integer m, the number of solutions in the range [0, n - 1] that are coprimes with n, followed by m lines that contain the m solutions in ascending order. It is guaranteed that m <= 10
4
.
Example
Input:
5 1 3
Output:
1
3 | 33,141 |
Roads of NITT (NITTROAD)
The Institute of NITT believes in frugality. So when they made the plan for interconnecting the N hostels, they decided to construct as few bidirectional roads as possible. The hostels are interconnected with roads in such a way that every pair of hostels is connected by exactly one path.
Moreover, they were so frugal that they used low quality tar in making the roads. As a result, the roads start to crack and cannot be used anymore.
Now Alpa has a set of queries. At the time of each query, he knows the roads that are unusable. He wants to find the number of pairs of hostels that are disconnected, i.e., the number of pairs (x, y) such that 1 <= x < y <= N and there exists no path between hostels x and y.
Help him find the result for each query.
Constraints
Test cases <= 5.
Number of hostels, N <= 20000.
Number of queries, Q <= 20000.
Input
First line contains t, the total test cases. Each test case looks as follows:
First line contains N, total number of hostels.
Next N - 1 lines contain two integers x and y, indicating that there is a road between x and y. (1 <= x < y <= N). The roads are numbered from 1 to N - 1.
Next line contains Q, total number of queries.
Next Q lines contain the Q queries.
Each query may be of the following two forms:
R x - Remove the road numbered x. It is guaranteed that this road exists and hasn't already been removed.
Q - Output the total number of pairs (x, y) such that 1 <= x < y <= N and there exists no path between hostels x and y.
Output
For each test case,
Output a line for each query with the required value.
Print a blank line after each test case.
Example
Input:
2
3
1 2
1 3
5
Q
R 1
Q
R 2
Q
4
1 2
1 3
1 4
7
Q
R 1
Q
R 2
Q
R 3
Q
Output:
0
2
3
0
3
5
6 | 33,142 |
Knifes Are Fun (JOKER1)
"
Do you know, why I use a knife? Guns are too quick. You can't savor all the little emotions. You see, in their last moments, people show you who they really are. So in a way, I know your friends better than you ever did. Would you like to know which of them were cowards?"
Joker has many knifes, and he wants to assign a distinct integer to each knife so he can easily identify them. The i-th knife can have an integer between 1 and maxNumber[i], inclusive.
Return the number of ways he can assign numbers to his knifes, modulo 1,000,000,007. If it's impossible to assign distinct integers to the knifes, print 0.
Input
The first line contains the number of test cases T (1 <= T <= 666)
Each test case has 2 lines - 1st line denotes number of knifes N (1 <= N <= 66) Joker has and the 2nd line denotes the numbers {maxNumber[0]....maxNumber[N-1]} Joker has.
1 <= maxNumber[i] <= 3000
Output
Print the number of ways Joker can assign numbers to his knifes, modulo 1,000,000,007. If it's impossible to assign distinct integers to the knifes, print 0. In last line print the string "
KILL BATMAN
".
Don't print any extra spaces.
Example
Input:
3
1
7
2
5 8
3
2 1 2
Output:
7
35
0
KILL BATMAN
Explanation
Test case 1 : Joker can assign any number between 1 and 7, inclusive, to the only knife.
Test case 2 : Joker wants you too think !
Test case 3 : (1,1,1) (1,1,2) (2,1,1) (2,1,2) are the possible combinations . As the numbering of knifes is not unique so the output is 0. | 33,143 |
FUN WITH LETTERS (FUNNUMS)
Mr. Bean’s uncle gifted him 15 English letter toys from 'a' to 'o'. As Mr. Bean is a joker, no one was willing to play with him. So he sat on the floor and arranged these toys in ascending order i.e. “abcdefghijklmno”. Then he figured out the next greatest string in lexicographic order that can be formed by rearranging the toys is “abcdefghijklmon”. Now he is learning programming and wants to write a program to solve the following problem: Given a string S which can be formed by rearranging the toys, find the N-th greater string in lexicographic order. You can safely assume that such a string always exists.
Input
The first line contains a natural number T denoting the number of test cases. Next T lines contain the description of T test cases, each with string S and value N.
Output
For each test case print the answer in a separate line.
Constraints
1 <= t <= 1000
2 <= S.length() <= 15
'a' <= S[i] <= 'a' + S.length() - 1
All letters in S are unique.
Sample
Input:
3
abdc 2
adcb 3
badc 7
Output:
acdb
bcad
cbad | 33,144 |
THE WITTY BOY (WITTYBOY)
The television at the boy's home contains the channels from 1 to n inclusive. The father wanted to avoid his son to watch some channels in the Television. You are given k unique channels that are banned by the father. For example assume that the TV contains 25 channels and the father bans the channels 15, 17 and 18 and you are currently at channel 16. If you press the 'down' button in the remote, you will move to channel 14 and if you press the 'up' button in the remote, you will move to channel 19. Also if you press up button from channel 25 you will move to channel 1 and if you press down button from channel 1 you will move to channel 25. There are 13 buttons in the remote as shown in the figure.
To move to a channel you can press the digits of the channel or you can use Up/Down/Previous buttons. The previous button will take you to the immediately previous channel you watched. (The previous button does not take effect until you have moved to some other channel after the first one.)
The remote control responds to delays. So you can take the button presses "1" and "9" either as a way to go to channel 1 and then to channel 9, or to channel 19 directly.
You are given the sequence of channels that the boy wanted to watch. Find the minimum number of remote button presses required by the boy. It's not necessary to watch the given channels consecutively, but it is necessary to watch them in the order specified. (In other words, the given sequence must be a subsequence of the optimal channel series the boy chooses to watch.)
To watch the first channel in the sequence, you must press the digits of the channel.
Input
The first line consists of and integer t, the number of test cases. Each test case consists of 4 lines. The first line consists of 2 integers n and k, the number of channels in the remote and the number of channels blocked. The next line consists of k unique integers - the id of the blocked channels. The next line consists of an integer m the number of channels the boy wants to watch followed by a line with m integers - the channel id's of the channels that the boy wants to watch.
Output
For each test case print the minimum number of remote button clicks required.
Input Constraints:
1 ≤ t ≤ 100
1 ≤ n ≤ 1000
0 ≤ k ≤ n-1
1 ≤ m ≤ 1000
ChannelToWatch[i] ≠ ChannelToWatch[i-1]
ChannelToWatch[any] ≠ BannedChannel[any]
Input:
3
5 0
5
1 2 3 4 5
500 0
4
140 160 139 160
5 2
2 4
5
1 3 5 3 5
Output:
Case #1: 5
Case #2: 9
Case #3: 5
Note:
Suppose you are currently at channel 6 and press up button twice you will move to channel 8. Now if you click on previous button, you will move to channel 7 and not channel 6.
Explanation of Case #2:
The moves are "1", "4", "0", "down", "1", "6", "0", "previous", "previous"
Congrats and thanks to
Mitch Schwartz
for solving this problem first and for helping on setting test cases for this problem. | 33,145 |
FLING1 (FLING1)
Fling! is a popular puzzle game created by the well-known developers at Candy Cane LLC.
The premise of the game is simple. You are given a certain number of balls on the screen to start. The goal is to fling one into another in order to knock the other off the screen. The puzzle is considered solved if you can do so while leaving only one ball remaining on the screen. Some might read this and think that it might not be too difficult, but the game gets challenging quickly. The problem is that you cannot fling two balls that are adjacent (i.e. next to each other.)
The first ball you choose can fling the 2nd ball if and only if:
The two balls exist in same row or same column.
The two balls are not adjacent.
There is no other ball in between the two balls.
If there exist a 3rd ball after the 2nd ball in the same line of action, the 2nd ball takes the position just before the third ball, pushes the 3rd ball and the 3rd ball gets flinged. (This continues until a ball gets knocked off the screen. Note that 2nd ball and 3rd ball can be adjacent).
Given a Fling! puzzle, just print "Yes" if it is a valid puzzle (solvable) or "No" otherwise.
For better understanding of gameplay you may have a look at this
video
. (optional)
Input
The first line of the input consists of an integer t, the number of test cases. For each test case, the first line consists of two integers m and n, the number of rows and columns of the puzzle. Then follows the description of the board. A[i][j] is '.' if the cell is empty or 'B' if the cell has a ball.
Output
For each test case print "Yes" if the puzzle is valid or "No" otherwise. (case-sensitive).
Constraints
1 ≤ t ≤ 100
1 ≤ m, n ≤ 10
You can assume that the number of balls in the board is approximately equal to (m × n) / 10.
Sample
Input:
4
5 5
.....
.....
..B..
.....
.B..B
5 4
....
B...
B...
....
B...
3 4
BB..
....
.B..
1 1
B
Output:
Yes
Yes
No
Yes | 33,146 |
BLOCK_D SOLVER (BLOCK_D)
You are given a board of order m×n full of coloured blocks.
At each move, you have to select a block of any colour which has atleast one of it's immediate neighbours of same colour. If you select a block, all the connected blocks(not just the immediate neighbours) of same colour gets destroyed. A block is connected to all the blocks that share an edge with it. Any block will fall directly down if there is no block immediately below it. If a complete column becomes empty, you must either push all the columns to it's left once in the right side or push all the columns to it's right once in the left side(These pushes are not considered as a moves. At each move, you will destroy more than one block).
You will win the game if the remaining number of blocks becomes zero after making the moves. Find the minimum number of moves to win the game. If it is impossible to win the game, print -1.
For better understanding of gameplay you may have a look at this
video
. (optional)
Input:
The first line consists of an integer t, the number of test cases. For each test case the first line consists of two integers m, n the number of rows and columns respectively followed by the matrix representing the coloured blocks. Colour[i][j] contains any character between 'a' and 'e' inclusive.
Output:
For each test case print the minimum number of moves to win the game. If it is impossible to win, print -1.
Input Constraints:
1<=t<=10
1<=m,n<=8
'a'<=Colour[i][j]<='e'
Sample Input:
2
5 5
aaaba
aaaba
aaaba
aaaba
aaaba
5 5
bbbbb
baabb
bbbab
bbbaa
aabab
Sample Output:
2
3 | 33,147 |
Party Time (PARTYTIM)
In a n-storey resort a grand party is arranged in the nth floor of the building and two magical elevators A and B are stationed at the ground floor (zero th floor).
There are people waiting in all floors from to 0 to n-1 for attending the party. These two magical elevators are used for getting these people to the party. These elevators can be moved from one floor to any other floor. The time it takes to move any elevator from i th floor to j th floor is abs(j - i) time units.
Also there is a cost associated with moving the elevator from i th floor to j th floor.
If the elevator A moves from floor i to floor j with x people, then cost equals A[i] ^ A[j] ^ x, where '^' is the bitwise XOR operator. Similarly for the elevator B, it is B[i] ^ B[j] ^ x. However, if the lift stops on the k'th floor and 'a' people get on the elevator and 'b' people get off the elevator, to make a new count of 'y' people, then new cost is (A[i] ^ A[k] ^ x) + (A[k] ^ A[j] ^ y). (see notes).
People who are inside the elevator can be made to get down from it at any floor that it stops. It takes zero time for people to get into or out of the elevator.
All persons who are waiting have to be taken to the nth floor. As the party is going to start immediately the resort manager wants everyone to be there in the party in the least time possible. It is your job to control these elevators in such a way that everyone is there in the party in the least time possible and also minimize the cost of controlling these elevators.
Notes:
The objective is to get all the people waiting in floors 0, 1 ... n - 1 to floor n.
The elevators can move up or down.
It takes zero time for the elevator to stop at any floor and for people to get down or get into the elevator.
If Lift A carries 5 persons from 2nd floor to 6th floor, cost = A[2] ^ A[6] ^ 5
If 1 more person enters Lift A on the 4th floor, the cost will be (A[2] ^ A[4] ^ 5) + (A[4] ^ A[6] ^ 6)
Constraints:
1 ≤ n ≤ 30;
The sum of people waiting in all floors won't exceed 1000 and there is at least one person waiting in every floor from 0 to n-1.
All values of the array A and B are non-negative numbers lesser than or equal to 1000.
Input
First Line consists of an integer denoting the number of test cases(at most 10).
Every test case will be of the following form.
First line contains n the number of floors in the building.
Second line contains n+1 integers: A[0], A[1] ... A[n].
Third line contains n+1 integers: B[0], B[1] ... B[n].
Fourth line contains n integers: The number of persons waiting in each floor from 0 to n - 1.
Output
For every test case output one integer on a new line: the minimum cost for operating the elevators and ensuring that all people reach the n'th floor.
Example
Input:
2
2
0 1 3
0 1 5
2 1
4
1 3 5 7 9
2 4 6 8 10
1 2 3 4
Output:
1
16
Explanation
In the first test case:
Lift A carries 1 person from 0th floor to 1st floor. Cost = A[0] ^ A[1] ^ 1 = 0
Lift B carries 1 person from 0th floor to 1st floor. Cost = B[0] ^ B[1] ^ 1 = 0
The person waiting in 1st floor and person from Lift A both move to Lift B. Lift B carries 3 people from 1st floor to 2nd floor. Cost = B[1] ^ B[2] ^ 3 = 1
All persons have reached the party in 2 time units and incurring a cost of 1. | 33,148 |
Real Mangoes for Ranjith (MANGOES)
Ranjith is very fond of mangoes. One fine sunny day, he goes to market to get some mangoes. In the market place, he finds
N
boxes (indexed from 1 to
N
), filled with mangoes kept infront of him. Each box indexed
i
is denoted by
b
i
and contains exactly
i
mangoes. The number of mangoes in
b
i
is denoted by
m
i
and
m_i
=
i
. Let
t
i
denotes the type of mangoes in box
b
i
(
t
i
is either "real" or "fake"). He can choose any box
b
i
(
i
<=
N-2
), but he doesn't know if the box contains "real" mangoes or "fake" mangoes i.e. type of box
b
i
.
The type of mangoes in
b
i
depends on the number of mangoes in boxes
b
i
,
b
i+1
,
b
i+2
i.e. {
m
i
,
m
i+1
,
m
i+2
}. Mangoes in box
b
i
are "real" if for each pair of numbers taken from set {
m
i
,
m
i+1
,
m
i+2
}, Greatest common divisor(GCD) equals 1. Otherwise, "fake". Note that
t
i
is not defined for
i
=
N-1
and
i
=
N
and assumed to be "fake".
Given
N
, Ranjith wants to know the total number of "real" mangoes he will get from all boxes. As Ranjith cannot count beyond
N
, output the result modulo
N
.
Input
Test File starts with number of test cases -
T
;
T
lines follows, each containing
N
, number of boxes.
Output
Output
T
lines Number of "real" mangoes Ranjith gets (modulo
N
) in each one of the
T
cases.
Constraints
2 <
N
<= 10^8
T
<= 10000
Example
Input:
2
9
5
Output:
7
4 | 33,149 |
String Queries (STRINGQ)
Consider a string S, consisting of lowercase letters.
You are given a list of queries, each of which belong to one of the following two types:
Q a b: Returns the number of ways of rearranging the letters in the substring [a, b] such that for each substring X in the resulting string A, Reverse(X) is also present in A. Reverse(X) reverses the string X.
U a b: Sorts the substring [a, b] lexicographically.
Thus, given the string S and a list of queries, print the answer for each query of type 1. Since the answer can be huge, print the result modulo 106109099.
Finally, output the string S, with the updates made, if any.
Note: Two ways of rearranging the letters are considered different if, for two resulting strings A, B you can find an index i such that A[i] != B[i].
Input
First line contains T, the number of test cases.
For each test case, first line contains S, the input string.
Next line contains N, the number of queries. Each of the next N lines contains a string of the form "X a b" where X is one of {"Q", "U"} and a and b are positive integers such that 1 ≤ a ≤ b ≤ |S|.
Output
For each test case, print X + 1 lines, where X is the number of queries of type Q.
For each query of type Q, print one number which is the answer to the query.
(X + 1)th line for each test case, should contain the updated string S.
Constraints
1 ≤ T ≤ 10
1 ≤ |S| ≤ 50000
1 ≤ N ≤ 2000
Example
Input:
2
nittirichy
3
Q 2 5
U 1 4
Q 1 5
shabba
5
Q 2 3
Q 2 6
U 1 4
Q 2 5
Q 1 6
Output:
2
2
inttirichy
0
2
0
0
abhsba | 33,150 |
ZEROES IN RANGE V2 (RANGZER2)
You are given two integers a and b. Find the number of zeroes in the digits of all the numbers in the range [a, b] inclusive.
Input
The first line consists of an integer t, the number of test cases. For each test case you will be given two integers a and b (a <= b).
Output
For each test case print the required answer.
Constraints
1<=t<=1000
1<=a<=b<=10^9
Example
Input:
2
1 10
1 100
Sample Output:
1
11 | 33,151 |
Flipping Slipping of grids (GRIDFLIP)
Given two grids of characters, consists of characters from 'a' to 'z' only. we name two grids 'A' and 'B'.
Now, we need to find the lexicographically largest triplet
(Assuming that one such solution does always exists.)
Given that:
f(A, i, j, k) = B, 0 <= j < k < n and 1 <= i <= n - 2 (where 'n * n' is the size of grids)
(i.e. function 'f' operated on matrix 'A' with 'i', 'j' and 'k' parameters gives matrix 'B'.
Description of function 'f':
f(M, i, j, k) : function operated on matrix 'M' does following operations in the given order.
1) Take rows from index '0' to 'i' of the given grid M and flip it, i.e.
for( each column Ci ) reverse(A[0..i][Ci])
2) Take colums from index '0' to 'j' of the grid and flip it, i.e.
for( each row Ri ) reverse(A[Ri][0..j])
3) Take colums from index 'k' to 'n-1' of the grid and flip it, i.e.
for( each row Rj ) reverse(A[Rj][k...n-1]
4) Remove columns indexed '0' to 'j' and concatenate on the right of the grid in the same order, making new grid.
Input
First line contains one integer 'n' (n*n is size of grid)
Following n lines (i.e. line numbers 2 to n+1 ) contains strings each of size 'n' for grid 'A'.
Following n lines (i.e. line numbers n+2 to 2n+1) contains strings each of size 'n' for grid 'B'.
Constraints
5 <= n <= 1000
String contains only lower case letters.
Output
Three integers (space separated) in one line representing i, j and k respectively (lexicographically largest solution).
Example
Input:
5
ooscz
hkaea
nnzth
khdlf
rejtf
fldhk
htznn
aeakh
zcsoo
ftjer
Output:
3 3 4 | 33,152 |
Fibonacci vs Polynomial (HARD) (PIBO2)
Define a sequence
Pib
(n) as following
Pib
(0) = 1
Pib
(1) = 1
otherwise,
Pib
(n) =
Pib
(n-1) +
Pib
(n-2) +
P
(n)
Here
P
is a polynomial.
Given
n
and
P
, find
Pib
(n) modulo 1,111,111,111.
Maybe you should solve
PIBO
before this task, it has lower constraints.
Input
First line of input contains two integer
n
and
d
(0 ≤
n
≤ 10
9
, 0 ≤
d
≤ 10000),
d
is the degree of polynomial.
The second line contains
d
+1 integers
c
0
,
c
1
…
c
d
, represent the coefficient of the polynomial (Thus
P
(x) can be written as Σ
c
i
x
i
). 0 ≤
c
i
< 1,111,111,111 and
c
d
≠ 0 unless d = 0.
Output
A single integer represents the answer.
Example
Input:
10 0
0
Output:
89
Input:
10 0
1
Output:
177
Input:
100 1
1 1
Output:
343742333 | 33,153 |
The AMSCO cipher (AMSCO1)
Due to A.M.SCOtt in the 19th century, it's an incomplete columnar transposition cipher
with alternating single letters and digraphs. The first entry must be a digraph.
In both even and odd periods the first column and the first row always alternate:
4
1
3
2
5
IN
C
OM
P
LE
T
EC
O
LU
M
NA
R
WI
T
HA
L
TE
R
NA
T
IN
G
SI
N
GL
E
LE
T
TE
R
SA
N
DD
I
GR
A
PH
S
Input
N lines (N<1000)
Each line of the input contains the numeric key (permutation order of the columns)
and a plaintext. Plaintext letters are in [A-Z] only with no punctuation.
The keylength max is 9 and the length of the plaintext is limited to 250.
The last line ends with EOF.
Output
Output consist of exactly N lines of ciphertexts with letters in [A-Z] with no spaces.
Example
Input:
41325 INCOMPLETECOLUMNARWITHALTERNATINGSINGLELETTERSANDDIGRAPHS
Output:
CECRTEGLENPHPLUTNANTEIOMOWIRSITDDSINTNALINESAALEMHATGLRGR | 33,154 |
GHALIBS CHALLENGE (GHALIBC)
"har ek baat pe kehte ho tum ke 'too kya hai?'
tumheen kaho ke yeh andaaz-e-guftgoo kya hai?"
Ghalib was a great poet and was very highly regarded by the emperor. Some of the nobles did not like this, so concocted a plan to reduce his influence on the emperor. They gave him a challenge, he could be given n bags of marbles. The first bag has 1 marble, second bag has 2 marbles and so on. Each of the marble has a unique radius between 1 and i, where i is the number of the bag. Ghalib has to tell the number of ways arranging these marbles. (The marbles in each of the bag have to be arranged separately and the number of ways summed up for all the bags).
Ghalib complained to the king that this task is too difficult. So the king tried to help him a bit. (n+1) will only be divisible by a single prime - p (i.e. (n + 1) = p
a
) and he has to only find ways of rearranging those bags of marbles whose size is equal to r mod(p - 1) and (p + 1) / 2 ≤ r ≤ p-1. Also he doesn't need to count any arrangement of marbles containing a subsequence of 3 marbles with increasing length.
Ghalib still finds this task too difficult and is asking for your help. Since the answer can be very big, output the remainder when the answer is divided by p × p.
Input
1 ≤ t ≤ 10 :- the number of test cases
followed by t lines of
r p a :- as given in the question
(p + 1) / 2 ≤ r ≤ p-1
5 ≤ p ≤ 1000
1 ≤ a ≤ 10
8
Output
A single number representing the required answer
Example
Input:
2
5 7 2
5 7 1
Output:
42
42 | 33,155 |
Disjoint Subtrees (KAYKAY)
The CSE Department of NIT Trichy is not particularly renowned for its eye-candy. Noticing this, Paarth decides to distribute some candies throughout the department. The department consists of n rooms. There are corridors connecting certain pairs of rooms. Being very frugal, the corridors are designed in such a way that every pair of rooms are connected by exactly one path. Now Alpa and Syed are let loose in the department and they want to collect as many candies as possible. Alpa has hired you to help him maximize the difference between the number of candies obtained by him and Syed based on the constraint that he shall never enter any room that is visited by Syed.
More formally, you are given a tree - A connected and acyclic graph with n vertices.
Each vertex in the tree has a value associated with it (the number of candies). Note that the number of candies may be negative as well (bullies waiting to snatch your candies away.)
Given a set of vertices S, value(S) = sum of values of all vertices in set S.
Your task is to select two sets of vertices A and B such that:
A and B are disjoint (they have no vertex in common)
Every vertex in A is connected to every other vertex in A through some path;
Every vertex in B is connected to every other vertex in B through some path;
A has k1 vertices; i.e. | A | = k1
B has k2 vertices; i.e. | B | = k2
value(A) - value(B) is maximized.
If it is not possible to select two such components, print -1.
Constraints
2 ≤ n ≤ 200
0 < k1, k2 ≤ n
The values of all vertices are between -10
5
and 10
5
Input
First line contains t, the number of test cases. Each test case is as follows:
First line contains three integers: n, k1 and k2.
Next line contains n integers, the values of the n vertices.
Next n - 1 lines contain 2 integers a and b, indicating that there is an edge between vertices a and b; 0 <= a < b < n
Output
For each test case, print one line containing an integer = value(A) - value(B) .
Sample
Input:
2
7 3 3
0 1 -1 2 3 -2 -3
0 1
0 2
1 3
1 4
2 5
2 6
3 2 2
1 2 3
0 1
0 2
Output:
12
-1
Explanation:
In the first case, A = {1, 3, 4} and B = {2, 5, 6}. | 33,156 |
Divide Polygon (HARD) (DTPOLY2)
This is hard version of
DTPOLY
.
Determine the number of ways to cut a convex polygon with
N
vertices if the only cuts allowed are from vertex to vertex, each cut divides exactly one polygon into exactly two polygons, and you must end up with exactly
K
polygons. Consider each vertex distinct. For example, there are three ways to cut a square - the two diagonals and not cutting at all - but only two ways to cut it to form 2 polygons, and only one way to cut it to form 1 polygon. The order of cuts does not matter. Since the number of ways can be very large, you should return the number taken modulo
M
.
Input
Input contains several test cases, i-th line consists of 3 integers:
N
i
(3 ≤
N
i
,
Σ
N
i
≤ 10
8
over all test cases),
K
i
(1 ≤
K
i
≤
N
i
- 2) and
M
i
(1 <
M
i
< 2
60
), all pairs (
N
i
,
K
i
) are different.
Output
On the i-th line print the number of different ways to cut the polygon with
N
i
vertices into
K
i
pieces modulo
M
i
.
Example
Input:
4 2 100
6 3 100
10000000 2 1000000007
10000000 5000000 1000000014000000049
Output:
2
21
984650007
780127215155143528 | 33,157 |
Thousands ByteMan March (TMB)
Leo invited all his friends to a giant meeting for peace in byteland.
All people came in bus which were all full.
Last year, they were only 4 people : A, B, C, D.
As Leo likes structured things, he thought to form groups.
All the ways to form homogeneous teams were :
{{A,B,C,D}} : one team of 4 (one way),
{{A}, {B}, {C}, {D}} : four 'teams' of 1 (one way more),
{{A,B}, {C,D}} or {{A,C}, {B,D}} or {{A,D}, {B,C}} : two teams of 2 (3 ways more).
for a total of 5 ways. But this year many people are awaited.
Input
The input begins with the number T of test cases in a single line.
In each of the next T lines there are two integers : N, K.
N is the quantity of bus that came to the meeting.
K is the common capacity of each bus.
Output
For each test case, your task is to calculate the number of ways people
can form homogeneous teams.
The answer can be a big number and could not fit in a 64bit container.
Example
Input:
3
2 2
1 6
2 3
Output:
5
27
27
Explanations
With lower letters, here are 27 ways for 2×3 people.
{{a,c,e},{b,d,f}}, {{a,c,d},{b,e,f}}, {{a,b},{c,e},{d,f}}, {{a,f},{b,e},{c,d}},
{{a,b,f},{c,d,e}}, {{a,c},{b,f},{d,e}}, {{a,e},{b,f},{c,d}}, {{a,b},{c,d},{e,f}},
{{a,e},{b,d},{c,f}}, {{a,e,f},{b,c,d}}, {{a,b,e},{c,d,f}}, {{a,d,e},{b,c,f}},
{{a,d},{b,e},{c,f}}, {{a,d},{b,c},{e,f}}, {{a,d},{b,f},{c,e}},
{{a,c,f},{b,d,e}}, {{a,b,c},{d,e,f}}, {{a},{b},{c},{d},{e},{f}},
{{a,b,c,d,e,f}}, {{a,c},{b,d},{e,f}}, {{a,c},{b,e},{d,f}}, {{a,b},{c,f},{d,e}},
{{a,f},{b,d},{c,e}}, {{a,f},{b,c},{d,e}}, {{a,e},{b,c},{d,f}},
{{a,d,f},{b,c,e}}, {{a,b,d},{c,e,f}}
Constraints
0 < T ≤ 100
0 < K ≤ 100
0 < N ≤ 100
Uniform-random input in the range.
Basic 1/6kB Python code can get AC under 1.5s, around 0.18s using PIKE (quite my first PIKE code), (timings edited 2017-02-11 after compiler changes). | 33,158 |
Billion ByteMan March (BBM)
Warning:
Source code size limit is 2048B (half is enough) and time limit could not allow all language to get AC ; I got AC in 0.41s with language C. (Timing edited, 2017-02-11, after compiler changes).
The
main
difficulty of the problem is to manage efficiently the given precomputed
values
and
the memory available, in the given time. Have fun ;-)
The March
Leo invited all his friends to a giant meeting for peace in byteland.
All people came in bus which were all full.
Last year, they were
thousands of people
.
As Leo like structured things, he thought to form groups.
Two years ago, all the ways to form homogeneous team with the 4 people (A,B,C,D) were :
{{A,B,C,D}} : one team of 4 (one way),
{{A}, {B}, {C}, {D}} : four 'teams' of 1 (one way more),
{{A,B}, {C,D}} or {{A,C}, {B,D}} or {{A,D}, {B,C}} : two teams of 2 (3 ways more).
for a total of 5 ways. But this year many more people are awaited.
As the answer should not fit in a 64-bit container, you should give your answer modulo M7=1000000007.
Input
The input starts with 2^12 useful precomputed values:
factorial(i) MOD M7 for i in [0 ; 2^30[ with a step of 2^18, each one on one line.
The input continues with the number T of test cases in a single line.
In each of the next T lines there are two integers : N, K.
N is the quantity of bus that came to the meeting.
K is the common capacity of each bus.
Output
For each test case, your task is to calculate the number of ways people
can form homogeneous teams.
Example
Input:
1 <--- 0! mod M7
639926614 <--- (2^18)! mod M7
[...] ( 4093 lines more)
0 <--- (2^30 - 2^18)! mod M7
3
2 2
1 6
2 3
Output:
5
27
27
Constraints
0 < T ≤ 300
0 < K ≤ 30000
0 < N ≤ 30000
Uniform-random input in the range. | 33,159 |
Sudoku goblin (SUDOGOB)
A sudoku goblin has read your book with sudoku problems. He has erased or added some numbers from settings. Your task is to write a program that can detect modified settings.
For every sudoku setting you have to count number of possible solutions and in the case that it is equal to 1 print
the unique solution.
Input
There is a number T of the test cases on the first line followed by T sudoku tables separated by one empty line. One sudoku table consists of 9 lines of 9 numbers 0-9 separated by one space. Zero in the table marks the empty field.
Output
For every test case, one line with number of possible solutions optionally followed by solved sudoku in the same format as on the input.
Example
Input:
3
3 0 6 0 0 2 5 0 0
0 0 0 0 3 8 0 0 0
7 0 8 0 1 6 0 9 0
0 0 7 0 0 3 8 6 0
8 2 0 0 7 0 0 4 5
0 6 3 1 0 0 9 0 0
0 7 0 3 5 0 6 0 2
0 0 0 8 2 0 0 0 0
0 0 2 9 0 0 7 0 4
3 0 6 0 0 2 5 0 3
0 0 0 0 3 8 0 0 0
7 0 8 0 1 6 0 9 0
0 0 7 0 0 3 8 6 0
8 2 0 0 7 0 0 4 5
0 6 3 1 0 0 9 0 0
0 7 0 3 5 0 6 0 2
0 0 0 8 2 0 0 0 0
0 0 2 9 0 0 7 0 4
3 0 6 0 0 2 0 0 0
0 0 0 0 3 8 0 0 0
7 0 8 0 1 6 0 9 0
0 0 7 0 0 3 8 6 0
8 2 0 0 7 0 0 4 5
0 6 3 1 0 0 9 0 0
0 7 0 3 5 0 6 0 2
0 0 0 8 2 0 0 0 0
0 0 2 9 0 0 7 0 4
Output:
1
3 1 6 4 9 2 5 7 8
2 9 5 7 3 8 4 1 6
7 4 8 5 1 6 2 9 3
9 5 7 2 4 3 8 6 1
8 2 1 6 7 9 3 4 5
4 6 3 1 8 5 9 2 7
1 7 9 3 5 4 6 8 2
6 3 4 8 2 7 1 5 9
5 8 2 9 6 1 7 3 4
0
2 | 33,160 |
Helping Susy (SUSY)
Susy is a beautiful and smart student. She is an expert solving puzzle games, specially mazes, and such talent has given her several prizes from various competitions, where her speed and skills are tested.
Right now, she is participating in an special puzzle contests, and her jealous rival, Angelica, is participating too.
At this moment, they are in a tie, and in order to break this tie the judges have prepared a special round with a special game. The rules of this game are the following:
The game consists of a table with walls, like a maze. Also, there are some special objects, the Magic Stones. To win the game, the player must take all the stones present in the table.
There are four valid movements: Up, Down, Left and Right. Nevertheless, once the player choose a movement from his current position, he cannot stop moving in that direction until he crash with a wall in the maze. Obviously, the player cannot leave the table, so the limits of the table are considered walls too.
As there can be many solutions, the judges want the optimal one, which mean the least number of moves.
This is not problem for Susy, but Angelica is having a really bad time with this game. Jealously, Angelica secretly took Susy's solution and cut it in many pieces (She is not very intelligent. She could copy the solution instead but her anger blinded her).
Time is running out, and Susy doesn't have the time required to solve the puzzle again. Fortunately, the participants can ask a friend to help with just one puzzle, and she knows something the judges don't, your programming skills.
Now, she is calling you! Write a program to solve the maze with the least moves possible! Help Susy!
Input
The input begins with two integer numbers, R and C, the number of rows and columns of the table respectively.
Next, there will be R lines with C characters each, representing the maze. Each maze will contain only following characters:
"." - free space,
"#" - wall,
"S" - initial position of the player,
"*" - magic stone.
Output
The output consists of 2 lines. The first must contain one only number S. S is the optimal solution of the game.
The next line consists of S strings separated with a "-". These strings are "Up", "Down", "Left" and "Right". The full string represents the movements done in the optimal solution.
If there is more than one optimal solution, you must print the lexicographically smallest one.
Example
Input:
5 6
*S....
....#.
.##...
**....
.#.*#.
Output:
7
Down-Right-Down-Left-Up-Left-Up
Constraints:
2 <= (r, c) <= 20. There will be no more than 13 magic stones in the maze.
NOTE
: There will always be a solution for the given maze. | 33,161 |
Web islands (WEBISL)
For a given set of web pages, we want to find largest subsets such that from every page in a subset you can follow links to any other page in the same subset.
Input
On the first line, there are two numbers, number of the pages N, and total number of links M. Pages are numbered from 0 up to N-1. On lines 2 up to M+1, there are two numbers per line. The first is the source page and the second is the target page of a link.
Output
On N lines there is a component ID for every single page. The component ID is the smallest page index on the component.
Example
Input:
3 3
0 1
1 0
1 2
Output:
0
0
2 | 33,162 |
Spring Primality (VPL1_AA)
Dickie was playing with his friend some day in the spring season, he bought some cards, each card contains a number, that can be a prime or not. The game that Dickie plays consists to count what is the longest segment of contiguous cards that contains a prime, by instance, if the cards are: 2 5 8 14 11 15, the longest contiguous segment will be of length 2 as the cards 2,5 are primes, while the 11 is automatically discarded as it is isolated.
Nevertheless, Dickie’s friends are evil and they challenged him to do another task, that goes as follows, for every card that is not a prime, you subtract every of its prime factors to the prime count of the factor and for every card that is a prime, you will add a unit to its prime count, i.e.: 2 5 8 14 11 15, primes = 2, 5, 11, 8 = 2 * 2 * 2, 14 = 2 * 7, 15 = 3 * 5, so, prime count [2] = 1 - 3 - 1, prime count [5] = 1 - 1, prime count [11] = 1. There is no consideration for the other numbers.
After doing this, Dickie will count another time the longest contiguous segment, however, if the prime count is less or equal than zero, you can’t count that prime card. Help Dickie to find the longest contiguous segment of cards according to his rules, and the longest contiguous segment of cards according to his friends rules.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
The first line of each case will contain a number N, then, in the next line, N numbers will follow.
Output
For each test case you should print the string "Scenario #i: " where i represents the test case you are analyzing (starting from 1), followed by the longest segment of contiguous prime cards, then, a single space, a "greater than-sign" and another single space will follows and after that, the segment of contiguous cards according to the rules proposed by Dickie’s friends.
Sample
Input:
3
7
7 9 11 2 5 7 6
3
2 3 4
5
8 16 32 64 7
Output:
Scenario #1: 4 > 2
Scenario #2: 2 > 1
Scenario #3: 1 > 1
Constraints
Subtask 1 (20%)
1 ≤ T ≤ 100
1 ≤ N ≤ 100
2 ≤ Ni ≤ 1000
Subtask 2 (30%)
1 ≤ T ≤ 10
1 ≤ N ≤ 1000
2 ≤ Ni ≤ 100000
Subtask 3 (50%)
1 ≤ T ≤ 5
1 ≤ N ≤ 100000
2 ≤ Ni ≤ 10000000 | 33,163 |
Summer Game (VPL1_AB)
Beto, Dickie, Luis, Maxx, Charlie and Ricky like to play some wicked games in the summer. These games can easily be found in any social network. They like to play by drinking some strange liquid they call ”Aquameister” that can make you dizzy if you drink too much! Beto is tired of losing every time they play, but Charlie is the most capable to resist these games. That’s why Beto asked for your help! He wants to make Charlie feel dizzy before he does! The game consists on winning (clearly), and is given by a large row. He starts from position 1. For each row you must drink one small cup of Aquameister. If you repeat the same movement of dice he threw in his last turn, he drink again, for simplicity, we define the "same movement" with the same dice that Beto threw the last turn, by instance, if Beto threw (2, 1, 2), then Beto can throw (1, 2, 2), however, Beto may not throw the same (2, 1, 2), and so on for each roll. This goes on until Beto reach the position N. Being the last position, if Beto passes out, he lose the game and will drink twice and start again. However, for the sake of Beto, if he goes out he drinks twice and stops drinking.
Beto wants to know how many different ways he can end the game perfectly (that is arriving to the N position in the game) starting from the position 1. As this number can be very big, we ask you to output the answer modulo 1,000,000,007
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
Each case contains two integers N and D, being the size of the row and the number of dice you will throw per round (The dice are six-sided dice).
Output
For each input case you must print the string "Scenario #i:" where i is the case you are analyzing (starting from 1) then, the answer to the question described above.
Example
Input:
3
3 1
4 1
6 1
Output:
Scenario #1: 1
Scenario #2: 3
Scenario #3: 7
Constraints
Subtask 1 (10%)
1 ≤ T ≤ 50
1 ≤ N ≤ 5
1 ≤ D ≤ 2
Subtask 2 (30%)
1 ≤ T ≤ 100
1 ≤ N ≤ 100
D = 1
Subtask 3 (60%)
1 ≤ T ≤ 50
1 ≤ N ≤ 100
1 ≤ D ≤ 3 | 33,164 |
Late Summer Searching (VPL1_AC)
Summer is late! Summer is late! For a very important date! The VPL programming contest is about to start and Summer is nowhere to be found. Without Summer, you cannot have a contest based on seasons, so you have to find her quickly!
A system of antennas is placed on the top of the tallest buildings. You can use them to try to detect Summer's position, so you can finally go and get her. However, the antennas are very sensitive to noise, so unless every antenna is visible from every other antenna, the system will not work. Every antenna has an interference radius R, that will block the visibility between two other antennas if their signal passes through it.
Even if the system works, using it is very energy-consuming and quite expensive. Given the positions of the antennas, the cost of using the system is equal to the minimal possible area that encloses every antenna (along with their lines of sight with every other antenna). For simplicity, you can suppose that the physical radius of each antenna is negligible.
You are located in the VPL headquarters building (which has its own antenna), where every other building with an antenna has a position relative to yours. Knowing these positions, and the interference radius for the antennas, your job is to decide whether the system can work or not. And if it can, what will be the cost (in terms of the minimal area covered).
Input
The first line of the input will contain a single integer
T
, which is the number of test cases that follow. Each test case will begin with a line containing two integers
N
(the number of antennas) and
R
(Radius of interference of the antennas).
N-1
lines follow, each one containing two integers
X
i
and
Y
i
, being the relative position of the
i
-th building with respect to VPL headquarters (which is assumed to be placed at position (0, 0)).
Output
The output of your program should consist of T lines, one for each test case. For each of these test cases you should output a single number, representing the minimum area covered by the system, (Rounded to two decimal places). If the system cannot be used, you should output only the text "NO CONTEST" (quotes for clarity).
Sample
Input
2
4 1
2 0
2 2
0 2
5 1
2 0
2 2
0 2
1 1
Output
4.00
NO CONTEST
Constraints
General Constraints
1 ≤ T ≤ 100
1 ≤ R ≤ 10
-500 ≤ X
i
, Y
i
≤ 500
Constraints - Subtask 1 (20%)
N = 3
Constraints - Subtask 1 (80%)
3 ≤ N ≤ 100 | 33,165 |
Autumn Leaves (VPL1_AD)
Autumn is a particular season, because it’s the season when all leaves fall down. Sometimes, the leaves fall in places that are not convenient, such as the ants garden. Andy the ant was playing one day at his garden when Autumn season started. All leaves started to fall down on Andy’s garden, Andy ran to his house and when the leaves stopped falling he went out. He realized that there were not only leaves but sticks on his garden. It is proved that an ant can carry at most ten times his weight, but a stick is much more than that, so Andy decided to clean the leaves and leave the sticks. This, of course, is a problem, because Andy can only jump over K sticks. Andy is very lazy, so he wants the better way to remove all leaves of his garden, but he doesn’t know how to figure out that, so he ask for your help in order to know that path. Andy always start at point (0,0) (his house), and he doesn’t need to come back to his house, so the last leaf is the last point on his path, but he has visit at least one time each leaf. For simplicity, leaves will be indexed from 1 to N, and Andy’s house will be assumed as point 0. Please note that Andy, like all ants, can’t break his walk line, so he can’t go around any stick, he can only jump over them.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
Each test case starts with 3 integers, N, M and K, these are the number of leaves, the number of sticks and the total number of sticks that Andy can jump on his path. N lines will follow, each one with 2 integers, Xi and Yi, separated by spaces, indicating the position of the leaf i in Andy’s garden. Then M lines will follow, each one with 4 integers, X1i, Y1i, X2i and Y2i, separated by spaces, indicating the position of the start and ending point of stick i on Andy’s garden.
Output
For each input case you must print the string "Scenario #i: " where i represents the test case you are analyzing (starting from 1), followed by the minimum distance that Andy have to walk in order to clean the leaves of his garden. Then one line with Andy’s path, if there are more than one path that has the minimal distance, print the first one when ordered lexicographically. If there exist no path then you should print "-1".
Sample
Input:
2
6 3 1
1 6
2 2
5 1
5 5
5 9
10 2
2 5 4 3
3 7 8 7
6 0 8 3
4 3 2
-2 -2
2 2
5 -1
6 6
0 3 1 0
-2 -5 5 2
0 5 7 0
Output:
Scenario #1: 26.044
0 2 3 6 4 1 5
Scenario #2: -1
Constraints - Subtask 1 (10%)
1 ≤ T, N, K ≤ 4
M = 0
-1000 ≤ Xi, Yi ≤ 1000
-1000 ≤ X1i, Y1i, X2i, Y2i ≤ 1000
Constraints - Subtask 2 (15%)
1 ≤ T, N, K ≤ 10
M = 0
-1000 ≤ Xi, Yi ≤ 1000
-1000 ≤ X1i, Y1i, X2i, Y2i ≤ 1000
Constraints - Subtask 3 (25%)
1 ≤ T, N, M, K ≤ 4
-1000 ≤ Xi, Yi ≤ 1000
-1000 ≤ X1i, Y1i, X2i, Y2i ≤ 1000
Constraints - Subtask 4 (50%)
1 ≤ T, N, M, K ≤ 10
-1000 ≤ Xi, Yi ≤ 1000
-1000 ≤ X1i, Y1i, X2i, Y2i ≤ 1000 | 33,166 |
Winter Crush (VPL1_AE)
Winter is a sad season, specially if you have nobody to share your time with. Valentine’s day is coming and Dickie is crushed for Elizabeth, but she has already friendzoned him with the classic “You’re my best friend” and other silly phrases used by girls in order to keep the “friend” neutralized but at the same time, keep him close.
Nevertheless, Dickie ain’t gonna to take any more stools. He’s thinking about an ultimate move to gain Elizabeth heart! He has called this ”No more stools operation!”, and will take place on Valentine’s day. He hasn’t clearly decided what to do, because that heavily depends on Elizabeth’s position on Valentine’s day. Even so, Dickie has been smart enough to figured out a way to know Elizabeth’s position in terms of probability based on the time elapsed from the beginning of the day.
As Elizabeth’s “best friend”, Dickie knows her preferences and tastes. He knows that if she’s at a given position x, she will move to any adjacent position y with a probability p
xy
depending on the joy attained going there and the amount of snow on the path. The joy j
xy
is being measured in joysons and the snow s
xy
by centimeters, and the choice will be taken by the relation j
xy
/ s
xy
. Some properties shall hold:
The set of all positions is to be named V.
For any given x ∈ V, the set of all positions y ∈ V adjacent to x is to be named Ex. A position y is to be called adjacent if there is a path from x to y. Paths are bidirectional, so j
xy
/s
xy
= j
yx
/s
yx
.
∀x ∈ V ∧ ∀y ∈ Ex:
Dickie has some places in mind where he can find Elizabeth, but he’s aware that she could depart that morning from either her house or any of hers friends’ houses, so he wants to know which is the position with the highest probability to find Elizabeth given an elapsed time and the position she’s departing. Dickie wants to evaluate several possible scenarios, so a query will be formed by a time Ti and several possible initial positions Pi.
Input
The first line contains an integer C, which specifies the number of test cases. Then, will follow the descriptions of C test cases.
Each case will start with two integers, N and M, denoting the number of positions and the number of paths respectively. Next M will describe each of the paths between positions with four integers x, y, j
xy
, s
xy
, with the significance given above in the statement. All position indexes are 0-based. The line M + 1 will contain an integer Q denoting the number of Dickie’s queries. Each query will start with two integers, Ti and qi denoting the elapsed time and the number Elizabeth’s possible starting positions. Next qi lines will contain an integer will represent Elizabeth’s starting positions Pi.
Output
For each test case you should print the string "Scenario #i:" where i represents the test case you are analyzing (starting from 1), followed by a blank line. For each query Qi in the input, you must output a line with qi integers representing the position with the highest probability to find Elizabeth given the elapsed time Ti and the starting position Pi of her. If there are several positions with the highest probability, print the smallest one. If there are no positions with higher probability than 0, print -1.
Sample
Input:
2
3 3
0 1 10 2
0 2 1 8
1 2 100 1
2
1 1 0
2 1 0
4 5
0 1 10 2
1 3 2 3
0 2 4 8
2 1 1 10
2 3 1 1
2
2 1 2
10 2 0 3
Output:
Scenario #1:
1
2
Scenario #2:
1
0 0
Constraints
0 < j
xy
, s
xy
≤ 100
0 ≤ M ≤ (N * (N - 1)) / 2
Subtask 1 (30%)
1 ≤ C ≤ 50
1 ≤ N ≤ 20
0 ≤ | Ex | ≤ 3, ∀ x ∈ V
1 ≤ Ti ≤ 20
1 ≤ Q ≤ 10
qi = 1
0 ≤ Pi ≤ N
Subtask 2 (70%)
1 ≤ C ≤ 20
1 ≤ N ≤ 100
1 ≤ Q ≤ 10
2 ≤ Ti ≤ 2000
1 ≤ qi ≤ 100
0 ≤ Pi ≤ N | 33,167 |
Annual Day (VOLNTEER)
The kids at DACT elementary school are very excited since they have their annual day coming up. On this occasion, the students get a chance to display all their projects and art work, as well as perform on stage for all the parents and other guests who will be coming. Since organizing an event so big requires a lot of effort, the poor teachers alone cannot handle it all. So, they decide to ask some of the students to volunteer to lend a hand.
You are the class teacher of one such kindergarten class with N students, and you need to select exactly k of your students for the volunteer group. Luckily for you, all the kids are very enthusiastic and excited and everyone wants to help out! But you also know that many of these students are very naughty and may start playing with each other halfway through instead of doing work. So you want to select this group of students in a smart manner to avoid such a scenario.
Since you have been their class teacher for nearly a year, you know beforehand how naughty each kid is, and have assigned "goodness" scores to each of the students accordingly. The higher the score for a student, the less naughty he/she is. You can also use this individual goodness score to calculate the score for a group of students as follows :
Goodness(a
1
, a
2
... a
n
) = (|a
1
|+|a
2
| ... |a
n
|) * (-1)
r
Where a
1
, a
2
... an are the goodness scores of the n students in that group, and r is the number of naughty students in that group. (
Note: A naughty student is one with a negative goodness score
)
Also |x| refers to the absolute value of x. (|x|=x if x>0. Else |x|=-x).
Given the goodness scores of all the students in your class, it is up to you to select exactly k students such that their group goodness score is maximum.
Input
The first line contains 2 space separated integers N and k. (1 <= k <= N <= 10
5
). Here N is the total number of students in your class, and k is the number of students to be selected.
This is followed by N space separated integers a
1
, a
2
... a
N
, where a
i
is the goodness score of the i
th
student. (|a
i
| <= 10
9
)
Output
On a single line output the maximum possible goodness value of any group of exactly k students that you may select.
Example
Input #1:
10 1
1 2 3 4 5 6 7 8 -9 9
Output #1:
9
Input #2:
10 3
1 2 3 4 5 6 7 -8 -9 9
Output #2:
26
Input #3:
3 3
12 78 2
Output #3:
92
Explanation
Input #1
: Since you need to select exactly one student, you will select the one with the maximum individual goodness score, so the answer is 9.
Input #2
: Here, the maximum score is obtained by selecting the students with scores of { -8, -9, 9 }, so the corresponding final value is: (|-8|+|-9|+|9|)*(-1)
2
= 26*1 = 26
Input #3
: Here you have no choice but to select all the students. So the answer is 92. | 33,168 |
The Wind Waker (WWAKER)
The world is in danger once again, and Link is the hero who will save us! In order to save the world, Link must travel overseas and collect some legendary items.
The sea can be described as an infinite 2D plane with a Cartesian coordinate system, in which the point (0,0) denotes the center of the sea. Also, the cardinal directions are defined as usual:
Link must use his boat to travel. Unfortunately, Link's boat has a limitation: the boat can only move in the same direction as the Wind. So, for instance, if the wind is blowing North, Link can only travel to the North. If the wind is not blowing at all, Link doesn't move at all, too.
Fortunately, Link has the
wind waker
, the magical baton. With this baton, Link can conduct the
Wind's Requiem
, a mystical melody that allows Link to control the wind. Each time the wind waker is used, Link can either make the wind stop blowing (this action is represented by the letter X) or make the wind blow in one of the 8 cardinal directions (North (N), South (S), East (E), West (W), Northeast (NE), Southeast (SE), Southwest (SW), Northwest(NW)).
Link using the wind waker
Link must go to the position (x
2
,y
2
) and stop there, to collect a legendary item. Right now, Link is at the position (x
1
,y
1
) and the wind is not blowing. You must find a trajectory from (x
1
,y
1
) to (x
2
,y
2
). A trajectory consists of a sequence of uses of the wind waker at certain positions. For example, to go from (0,0) to (1,1), a possible trajectory is:
At point (0,0), make the wind blow north;
At point (0,1), make the wind blow east;
At point (1,1), make the wind stop blowing.
You must find a trajectory that:
Minimizes the number of times Link uses the wind waker;
In case of a tie, minimizes the total distance traveled;
In case of a tie, uses the lexicographically smaller sequence of wind direction changes. Use
E < N < NE < NW < S < SE < SW < W < X
. For example, a trajectory that changes the wind to N, then to SW, then to W is preferable over a trajectory that changes the wind to N, then to W, then to E, because
(N,NW,W)
is lexicographically smaller than
(N,W,E)
(because
N=N, NW < W
).
Check the sample input and output.
Note: The names "Link", "The Wind Waker" and some images above are copyrighted by
Nintendo (r)
.
The author just wanted to make the problem more interesting. The author supports
Nintendo
!
Input
The input file consists of one or more test cases. Each test case is described by a line containing four integers x
1
, y
1
, x
2
, y
2
(|x
1
|, |y
1
|, |x
2
|, |y
2
| ≤ 5 × 10
4
, (x
1
, y
1
)
≠
(x
2
, y
2
)).
The file ends with EOF.
Output
For each test case, print a line containing K, the number of times the wind waker is used. In the next K lines print
x
i
y
i
D
, meaning that the wind waker must be used to change the wind direction to
D
at the position
(x
i
,y
i
)
. Print the coordinates rounded to exactly two fractional digits, and use
D
=
'S',N','W','E','SE','SW','NE','NW'
or
'X'
. Print the events in the order they occur in the trajectory.
After the
K
lines, print the total distance traveled, rounded to exactly three fractional digits. Print a blank line after each test case. Check the sample output.
Example
Input:
0 0 0 1
0 0 3 2
Output:
2
0.00 0.00 N
0.00 1.00 X
1.000
3
0.00 0.00 E
1.00 0.00 NE
3.00 2.00 X
3.828 | 33,169 |
Inverse of Recurrence Problem With a Square Root (IRECSQRT)
Given this recurrence formula (be careful, it's in inverse form):
Given
n
(0 ≤
n
< 2
64
) and
m
(0 <
m
< 2
64
), your task is to compute
a
n
modulo
m
.
It's guaranteed that
a
n
is always an integer.
Input
First line containing an integer
T
(0 <
T
≤ 5×10
4
), than
T
cases follow.
For each test case there are two integers
n
and
m
, written in one line, separated by a space.
Output
For each test case, output the required answer:
a
n
modulo
m
.
Example
Input:
10
0 10
1 10
2 10
3 10
10 10
100 100
1000 1000
10000 10000
100000 100000
9876543210123456789 1234567890987654321
Output:
1
2
5
5
5
51
251
6251
6251
657422418465782775
Time limit ~7x My program speed:
Click here to see my submission history and time record for this problem
See also:
Another problem added by Tjandra Satria Gunawan | 33,170 |
Amazing Factor Sequence (AFS)
Bhelu is the classmate of Bablu who made the
Amazing Prime Sequence
.
He felt jealous of his classmate and decides to make his own sequence. Since he was not very imaginative, he came up with almost the same definition just making a difference in f(n):
a[0] = a[1] = 0.
For n > 1, a[n] = a[n - 1] + f(n), where f(n) is the sum of positive integers in the following set S.
S = {x | x < n and n % x = 0}.
Now, Bablu asked him to make a code to find f(n) as he already had the code of his sequence. So, Bhelu asks for your help since he doesn't know programming. Your task is very simple, just find a[n] for a given value of n (< 10^6).
Input
Your code will be checked for multiple test cases.
First Line of Input contains T (<= 100), the number of test cases.
Next T lines contain a single positive integer N. (1 < N < 10^6).
Output
Single line containing a[n] i.e. n-th number of the sequence for each test case.
Example
Input:
3
3
4
5
Output:
2
5
6
Explanation
f(2) = 1 {1}
f(3) = 1 {1}
f(4) = 3 {1, 2}
f(5) = 1 {1} | 33,171 |
Movie Theatre Madness (THEATRE)
A group of friends have gone to watch the first day first show of an awesome new movie. However, since they did not book the tickets well in advance, they have ended up with crazy seats. To be more specific, rather than getting seats such that all the friends are seated in the same row, they have ended up with seats such that all of them are seated in the same column! Now this is very inconvenient since they won't be able to chat with each other during the movie or have any kind of fun, but they are okay with this since they'd rather watch the movie like this, than not watch the movie at all.
But there is another problem apart from this. Now we know that all the friends are seated in a single column, one behind the other. Since all of them reached the theatre just in time for the movie, they rushed and occupied the first of the booked seats that they could find. However all the friends have different heights, and due to the lack of planning, there is no guarantee that a shorter person is always seated in front of a taller person. But this would mean that the shorter person would struggle to see the screen throughout the movie!
But the movie has started and it's too late now to do anything.
What you need to do is the following: For every person, find the height of the closest person seated in front of him/her who is blocking his/her view (that is, the
person closest in front with a greater height
). If no such person exists, take this height as 1. Print the product of all such values modulo 1000000007.
Input
On the first line you have a single integer N (2 <= N <= 10
5
), the total number of friends.
This is followed by N space separated integers a
1
, a
2
, ... a
N
, which correspond to the
height of the people from back to front.
That is, a
1
is the height of the person seated on the last row, a
2
is the height of the person seated on the second last row (just in front of a
1
) and so on, up to a
N
which is the height of the person seated right at the very front (1 <= a
i
<= 10
9
).
Note that all these integers are distinct.
Output
On a single line, output the result. (For every person, find the height of the closest blocking person.
This value is 1 if no such person exists
. Print the product of all these values modulo 1000000007).
NOTE
: By closest blocking person to a
i
we mean find a
j
, such that a
j
> a
i
, j > i, and (j-i) is minimum. (Please look at sample test cases for further clarity.)
Example
Input #1:
5
5 2 1 4 3
Output #1:
16
Input #2:
5
9 8 3 5 7
Output #2:
35
Input #3:
10
30 10 50 70 11 60 20 80 31 12
Output #3:
999962375
Explanation
Input #1:
blockingHeight(5) = 1 (since 5 is the tallest, no one is blocking him)
blockingHeight(2) = 4
blockingHeight(1) = 4 (although 3 is also taller that 1, 4 is closer to 1)
blockingHeight(4) = 1 (No one blocking 4)
blockingHeight(3) = 1 (No one blocking 3)
Answer=1*4*4*1*1=16 | 33,172 |
Amazing Factor Sequence (medium) (AFS2)
Warning
Here is a harder version of
Amazing Factor Sequence
.
To make things clear, you'll need a O(n^0.5) method to solve this problem.
You'll need to be careful with container of C-like language,
and/or you'll need to find some little optimizations with slower language.
The factor sequence
We define our factor sequence with:
a[0] = a[1] = 0
, and
for
n > 1, a[n] = a[n - 1] + sum({x | x < n and n % x = 0})
.
Input
First line of input contains an integer
T
, the number of test cases.
Each of the next
T
lines contains
a single integer
n
.
Output
For each test case, print
a[n]
on a single line.
Example
Input:
3
3
4
5
Output:
2
5
6
Constraints
0 < T < 101
0 < n < 12148001999
Numbers
n
are uniform-randomly chosen.
Nmax
was carefully chosen ;-)
Time limit is ×2.5 my python one (2.56s). (Edited 2017-02-11, after compiler changes) | 33,173 |
Power Factor Sum Sum (hard) (AFSK)
Here is a mixed edition of
Divisor Summation Powered
and
Amazing Factor Sequence (medium)
.
The powered factor sequence
For
k
an integer number, we define our powered factor sequence with:
a
k
[0] = 0; a
k
[1] = 1
, and
for
n > 1, a
k
[n] = a
k
[n - 1] + sum({x^k | 0 < x ≤ n and n % x = 0})
.
Input
First line of input contains an integer
T
, the number of test cases.
Each of the next
T
lines contains three integers
n, k, m
.
Output
For each test case, print
a
k
[n]
on a single line.
As the answer could be a big number, you just have to output it modulo
m
.
Example
Input:
3
3 1 10
4 2 55
5 3 97
Output:
8
37
43
Constraints
0 < T < 101
0 < n < 10
9
0 < k < 11
1 < m < 10
17
Numbers
n, k, m
are uniform-randomly chosen.
For your information, there's two input files, the first one is 'easy' with n≤100.
My (1kB)-python code get AC around 0.96s. I have a much slower basic PIKE AC (4.8s).
(Edit 2017-02-11 ; timings and TL updated after compiler changes) | 33,174 |
LIFE IS A RACE (LIFERACE)
Life is a race with hard working humans. Assume a hypothetical situation in which God has to send many humans on earth with some level of intelligence. Level of intelligence is measured in a whole number. God has to take care that person arriving later on earth should have more level of intelligence so as to cope with the competitive world. God’s assistant suggested him a non-decreasing sequence called S. Lets see the sequence.
Description of Sequence
Any natural number n occurs exactly S[n] times and all n occurs consecutively. The first few terms are stated below.
n 1 2 3 4 5 6 7 8 9 10 11 12 ...
S(n) 1 2 2 3 3 4 4 4 5 5 5 6 ...
S[1000] = 86
So, Person 1 arrives on earth with level of intelligence = 1.
Person 2 arrives on earth with level of intelligence = 2.
Person 3 arrives on earth with level of intelligence = 2.
Person 4 arrives on earth with level of intelligence = 3.
And so on.
But God sends some good hearted person (Person who not only lives for themselves but for the world) when n's cube root is a positive integer. But there is a SuperGod which rarely opens his eyes and as he opens his eyes, he increases the level of intelligence of some of the good hearted persons. Now God needs to know the total level of intelligence of some of the good hearted people.
Good hearted person 1: person 1
Good hearted person 2: person 8
Good hearted person 3: person 27
Good hearted person 4: person 64
And so on.
God needs a programmer to solve his queries. God’s input data format is explained below.
Will You help God?? (He might increase your lifetime :) )
Input
First line of input contains 2 integers, x and y, where x denotes the number of time the SuperGod opened his eyes and y denotes the number of queries of God.
Next x lines follows 3 integers L, R, I, which denote that SuperGod has increased the level of intelligence of good hearted people ranging between L and R (inclusive both) by a constant I.
Next y lines follows 2 integers L, R, which denotes that God needs to know the total level of intelligence of good hearted persons ranging between L and R (both inclusive).
Note:
Good hearted person L is person L*L*L.
Good hearted person L+1 is person (L+1)*(L+1)*(L+1)
Good hearted person R is person R*R*R.
Output
Output should contain exactly y lines, each containing the answer.
Example
Input:
1 1
1 1 1
1 2
Output:
6
Explanation of Example
Answer is S[1] + S[2*2*2] + 1 = 6
Constraints
x <= 100000
y <= 100000
1 <= L, R <= 999999
I <= 10
Click here to see my set of problems at Spoj. | 33,175 |
Magic of the locker (LOCKER)
Vertu, the clever businessman, sells the ropes to his customers at the rate of 1 rupee per meter. He can only sell an integer length of a rope to a customer. Also, he has a magic locker which functions this way:
Suppose the locker has 'x' rupees. Now if 'y' rupees more are put into this locker, it multiplies them and total money in the locker now is 'x × y'.
This morning, Vertu starts his bussiness with 'n' meters of rope. He puts 1 rupee in the locker as to have good luck.
Find the maximum money he can earn today considering that he sold all of his rope at the end of the day.
NOTE: Vertu has to put all rupees into the locker as soon as he gets it, and can get rupees from locker only at the end of the day.
Input and Output
The first line contains t, the number of test cases. t lines follow, each containing one positive integer n. For each of these integers, print the required answer modulo (10
9
+7).
Constraints
t < 10
5
0 < n < 10
12
Example
Input:
2
4
5
Output:
4
6 | 33,176 |
Power of Phi(medium) (POWERPHI)
Vertu was very impressed by the golden ratio φ=(1+√5)/2 and about it occurring in nature and all that. He now begins to wonder if any non negative integral power of φ is also special. Since he does not like working with decimals, he decided to approximate the positive integral power of φ to its closest integer. Help him by printing the closest integer to φ
n
, given
n
.
Input
The first line contains
T
, the number of test cases.
T
lines follow, each containing one positive integer
n
.
Output
For each of these integers, print the closest integer to φ
n
.
If you think there are two closest possible integers, print either of them.
Print the answer modulo (10
9
+7).
Constraints
T
≤ 100000
0 ≤
n
≤ 10
9
Example
Input:
2
1
3
Output:
2
4 | 33,177 |
Evil Overlord Cypher (DIXIE001)
You have been imprisoned by an evil, but stupid alien overlord. You told them it was a trap. It's not your fault. IT'S NOT YOUR FAULT.
You can pass notes containing information to other prisoners to coordinate your escape. You want to use an algorithm that can be easily deciphered by your fellow prisoners, in between torture sessions of forced “Buffy the Vampire Slayer” marathons. But you also want the notes to remain unreadable to evil alien overlord and his minions should the notes be discovered.
Therefore, you choose to implement a simple Caesar cypher given the following rule:
When the characters in the document are sorted by frequency, then by ASCII code (case sensitive), each character is replaced by the character in the same position in the reversely sorted set.
Make a single character frequency lookup for ENTIRE file.
Given an arbitrary body of text as input, produce the appropriate output based on the cypher.
The first line of the input will contain a count of all the remaining lines, the remaining line are all part of the text to be encrypted.
Note:
The
¶
symbol in the examples below represents a newline character. You may also ignore (strip/pop off) the first line of the input. It was added for languages that have difficulty (or lack of ability) detecting EOF.
Also note that the newlines in the input text are treated as any other character and are encoded with the rest of the text. Note in particular that the last line of output may not end with a newline character.
THIS IS WHITESPACE SENSITIVE.
The sample input contains no whitespace characters at the end of a line unless marked with ¶ symbol at which point there is a newline character.
Examples
Input 1:
1
¶
Aliens are dumb
¶
Output 1:
mn
¶
ibAud
¶
Aralse
Input 2:
1
¶
Mississippi
Output 2:
spMMpMMpiip
Input 3:
2
¶
Missi
¶
ssippi
Output 3:
iM
¶
¶
Ms
¶
¶
MppM | 33,178 |
Science (SCIENCE)
Welcome, ladies and gentlemen, to Aperture Science. Astronauts, war heroes, Olympians -- you're here because we want the best, and you are it. That said it's time to make some science.
Now I want each of you to stand on one of these buttons. Well done, we're making great progress here. Now let's do it again. Oh come on, don't stand on the same button. Move people! No, no, that button's only for the astronauts, you know who you are. What?! You say you can't do everything I ask. Ok let's start over. You there, the Olympian, figure out how many times we can do this. And make it quick, we have a lot more science to get through.
Input
The first line will contain N (2 ≤ N ≤ 200) giving the number of people (and the number of buttons) in the experiment. The next N lines will contain N characters each. If the jth character of the ith line is 'Y' it indicates that the ith person can stand on the jth button (it is 'N' otherwise). The last line of input will be a 0.
Output
If it is impossible to get everyone on the buttons at once output "NO SCIENCE" (quotes for clarity). Otherwise first output K, the maximum number of times everyone can be standing on buttons such that nobody stands on the same button more than once. After that output K lines. Each line should contain N integers separated by a space where the ith integer describes who is on the ith button. All of the lines should be valid and none of them should put the same person on the same button. If there are multiple solutions, output any of them.
Examples
Input:
3
YYY
NYY
YNY
Output:
2
1 2 3
3 1 2
Input:
2
YN
YN
Output:
NO SCIENCE | 33,179 |
Decipher the AMSCO cipher (AMSCO2)
Here you have to decipher the AMSCO cipher:
Due to A.M.SCOtt in the 19th century,
it's an incomplete columnar transposition cipher with alternating single letters and digraphs
. The first entry must be a digraph. In both even and odd periods the first column and the first row always alternate:
7
4
5
6
3
2
1
RI
D
ER
S
ON
T
HE
S
TO
R
MI
N
TO
T
HI
S
HO
U
SE
W
EA
R
EB
O
RN
J
IM
M
OR
R
IS
O
N
Input
N lines (N < 1000) Each line of the input contains the numeric key (permutation order of the columns) and a ciphertext. Ciphertext letters are in [A-Z] only with no punctuation. The keylength max is 9 and the length of the ciphertext is limited to 250. The last line ends with EOF.
Output
Output consist of exactly N lines of plaintexts with letters in [A-Z] with no spaces.
Example
Input:
7456321 HETEAMTTOWIMONNSEJNDTOSEBRERRHOOISSMIURNORISHIROR
Output:
RIDERSONTHESTORMINTOTHISHOUSEWEAREBORNJIMMORRISON
Input:
41325 CECRTEGLENPHPLUTNANTEIOMOWIRSITDDSINTNALINESAALEMHATGLRGR
Output:
INCOMPLETECOLUMNARWITHALTERNATINGSINGLELETTERSANDDIGRAPHS | 33,180 |
Three Circle Problem (EASY) (CIRCLE_E)
Given 3 distinct circles with positive integer radius
R1
,
R2
, and
R3
, and arranged like in the picture below:
Now, your task is to compute radius of small circle that can be created like yellow circle in the picture above. All circles in the picture above tangent each other.
Input
The first line in the input data, there is an integer
T
(0 <
T
≤ 10
3
) denoting number of test cases, than
T
lines follow.
For each lines, there are three integer
R1
,
R2
, and
R3
, (0 < {
R1
,
R2
,
R3
} < 10
9
) denoting radius of each circle like in the picture above.
Output
For each test case, output radius of small circle that can be made, like in the picture above. Any output with absolute error less than 10
-6
is accepted.
Example
Input:
3
1 1 1
10 10 10
23 46 69
Output:
0.154701
1.547005
6.000000
You can see my submission history and time record for this problem
:
here
See also:
Another problem added by Tjandra Satria Gunawan | 33,181 |
Three Circle Problem (HARD) (CIRCLE_H)
Given 3 distinct circles with positive integer radius
R1
,
R2
, and
R3
, and arranged like in the picture below:
Now, your task is to compute radius of small circle that can be created like yellow circle in the picture above. All circles in the picture above tangent each other.
Input
The first line in the input data, there is an integer
T
(0 <
T
≤ 10
5
) denoting number of test cases, than
T
lines follow.
For each lines, there are three integer
R1
,
R2
, and
R3
, (0 < {
R1
,
R2
,
R3
} < 10
30
) denoting radius of each circle like in the picture above.
Output
For each test case, output radius of small circle that can be made, like in the picture above. Truncate the output to 50 digit after decimal point.
Example
Input:
3
1 1 1
10 10 10
23 46 69
Output:
0.15470053837925152901829756100391491129520350254025
1.54700538379251529018297561003914911295203502540253
6.00000000000000000000000000000000000000000000000000
You can see my submission history and time record for this problem
:
here
See also:
Another problem added by Tjandra Satria Gunawan | 33,182 |
GAME2 (AUTOMATA)
Bob is playing Hide and Seek with alphabets and he is amazed by the properties of '?' and '*' in the language. He is given a language 'L'. He has to check whether the given string 'S' is present in the language 'L'. He needs your help. Print "Yes" if S is present in L, else print "No".
Definition for L :
L consists of 28 characters, a-z and '?' and '*'.
? denotes 0 or 1 character(s).
* denotes 0 or any number of characters.
Example:
String "adb" is present in language L = {a?b}
String "adb" is present in language L = {a*b}
String "ab" is present in language L = {a?*b*}
Input
First line of input consists of T (T<=50). Every test case consists of two strings, first line consists of 'L' and second line consists of 'S'. L consists characters among the 28 characters 'a'-'z', '?', '*' only. S consists of only lower case letters.
Output
Print "Yes" if String 'S' is present in language 'L', else print "No".
Example
Input:
5
a?b
acb
a?b
abbb
a*b
abbbb
a*b
asbdfuisdhfsbdfsdfb
abb
bb
Output:
Yes
No
Yes
Yes
No | 33,183 |
Pythagorean triples (medium) (PYTRIP2)
Pythagoras is credited, by tradition, for the first proof of the relation
a
2
+
b
2
=
c
2
in any right angled triangle where
c
is hypotenuse and
a
and
b
are the
catheti
.
We define a Pythagorean triple as a set of three positive integers
a
,
b
, and
c
which satisfy the above equation , ie ,
a
2
+
b
2
=
c
2
.
{3,4,5} is the most common example of such triples.
Input
The first line of input contains an integer
T
, the number of test cases.
Each of the next
T
lines contains
two integers
N
,
M
.
Output
For each test case, print on a single line the number of Pythagorean triplet
{a,b,c}
such that
N ≤ a,b,c ≤ M
.
Example
Input:
3
1 5
4 10
10 100
Output:
1
1
45
Constraints
0 < T < 100
0 < N < M
0 < T × M < 1.21×10^8
There are several input files.
Time limit is ×20 my top speed with C language (1kB of code).
For your information, my total best time is 0.59s for the 6 input files. (Edit 2017-02-11, after compiler changes).
Warning, it could be hard with interpreted languages.
You can try before the quite similar tutorial problem :
PYTRIP
before.
Information
This problem is part of the
Bubble Cup competition
qualification round (April 2014).
@students: good luck. GNU_salutations. | 33,184 |
Range Sum (RANGESUM)
You are initially given an array of N integers ( 1<=N<=10
5
). Given this array, you have to perform 2 kinds of operations :
(i) Operation 1 : Op1( l, r )
You are given 2 integers l and r. ( 1 <= l <= r <= current size of the array ). You need to return the sum of all the elements with indices between l and r ( both inclusive ). That is, if the elements currently in the array are a
1
, a
2
, a
3
.... a
n
, you need to return the following sum : a
l
+ a
l+1
+ a
l+2
... + a
r
.
(ii) Operation 2 : Op2( x )
You are given a single integer x ( |x| <= 10
9
). Add this element to the
beginning
of the array. After this operation, x will now become a
1
, the old a
1
will now become a
2
, and so on. The size of the array will increase by 1.
Input
The first line contains a single integer N ( 1 <= N <= 10
5
), the number of elements initially in the array.
This is followed by a line containing N space separated integers, a
1
a
2
.... a
N
. ( |a
i
| <= 10
9
)
The next line contains a single integer Q, the number of operations you will be asked to perform. ( 1 <= Q <= 10
5
)
Q lines of input follow. Each such line starts with either the number 1 or the number 2. This indicates the type of operation that you are required to perform. The format of these queries are as follows :
1 l r : Carry out operation 1 with arguments l and r. ( 1 <= l <= r <= current size of the array )
That is, return the sum of the following array elements : a
l
+ a
l+1
... + a
r
2 x : Carry out operation 2 with the argument x. ( |x| <= 10
9
)
That is, add the value x at the beginning of the array.
Output
For each query of type 1, output the return value on a new line. No output needs to be printed for queries of type 2.
Example
Input #1:
10
1 2 3 4 5 6 7 8 9 10
4
1 1 10
1 1 1
1 10 10
1 2 7
Output #1:
55
1
10
27
Input #2:
5
6 7 8 9 10
9
2 5
2 4
1 2 7
2 3
2 2
2 1
1 1 10
1 1 1
1 10 10
Output #2:
45
55
1
10 | 33,185 |
Play with Binary Numbers (HAP01)
Let S be the binary representation of an integer. We define two functions a(i) and b(i) such that:
a(i) = Number of occurrences of '1' at odd positions of S,
b(i) = Number of occurrences of '1' at even positions of S.
For example: for integer 19, S = 10011, so a(19) = 2 and b(19) = 1.
Input
First line contains an integer T, the number of test cases. Then T lines follow. On each line, you will be given three integers M, N, K.
Output
For each test case output a single integer R, where R is the number of integers 'i' between M and N (both inclusive) such that absolute difference of a(i) and b(i) is equal to K. The answer to each each test case should be on a separate line.
Constraints
T ≤ 50
1 ≤ M < N ≤ 10
19
1 ≤ N - M ≤ 10
6
0 ≤ K ≤ 50
Example
Input:
1
1 10 2
Output:
2 | 33,186 |
Shared cathetus (easy) (CATHETEN)
For any integer
n
,
we define
F
(
n
)
as the number of ways
in which
n
can be the cathetus (leg) of a Pythagorean triangle.
For example, there is exactly four Pythagorean triangles with 15 as a length for a cathetus.
(8
15
17),
(
15
20 25),
(
15
36 39),
(
15
112 113)
Thus
F
(15) = 4
.
Input
The first line of input contains an integer
T
, the number of test cases.
Each of the next
T
lines contains
a single integer
n
.
Output
For each test case, print
F
(
n
)
on a single line.
Example
Input:
3
5
10
15
Output:
1
1
4
Constraints
0 < T < 10^5
0 < n < 10^9
For your information, my C code ran in 0.08s, whereas my python3 one ran in 0.90s. (Edit 2017-02-11, after compiler changes) | 33,187 |
Delta catheti (hard) (DELTACAT)
(3, 4, 5)
is a famous Pythagorean triple,
it gives a quick answer to the question:
For a given integer
d
, is there a Pythagorean triple
(
a, b, c
)
such that
b - a = d
?
A solution is
(3
d
, 4
d
, 5
d
)
,
and in fact one can easily prove that the set of solutions is infinite, and
that there is an obvious total order on those solutions.
Given
n
, you'll have to find the
n
th term of the sequence of solutions.
Geometrically, it is the study of right triangles for which the difference of the
catheti are equal to
d
.
Input
The first line of input contains an integer
T
, the number of test cases.
Each of the next
T
lines contains
three integers
n, d, m
.
Output
For each test case, compute the
n
th term amongst
the solutions
(
a, b, c
)
for the problem :
a
2
+ b
2
= c
2
with
b - a = d
and
0 < a < b < c
.
As the answer could not fit in a 64-bit container, simply output your answer modulo
m
.
Example
Input:
3
1 1 235813
3 21 1000
9 119 11
Output:
3 4 5
63 84 105
5 3 1
Explanations
For the first case, the first solution is
(3, 4, 5)
, as 4 - 3 = 1.
For the second case, the firsts solutions are:
(15, 36, 39), (24, 45, 51), (63, 84, 105), (144, 165, 219), (195, 216, 291), (420, 441, 609), ...
The third one is
(63, 84, 105)
.
For the third case, the first solutions are:
(24, 143, 145), (49, 168, 175), (57, 176, 185), (85, 204, 221), (136, 255, 289),
(180, 299, 349), (196, 315, 371), (261, 380, 461), (357, 476, 595), (481, 600, 769),
(616, 735, 959), ...
The 9th solution is
(357, 476, 595)
, reduced modulo 11, we get
(5, 3, 1)
.
Constraints
0 < T < 10^5
0 < n < 10^7
0 < d < 10^8
1 < m < 10^9
n, d, m
: Uniform randomly chosen in their range.
Constraints allow some interpreted languages to get AC, but it could be hard.
For your information, I have two distinct solutions.
My first python3 code get AC under 17s.
My second python3 code get AC under 8s.
(Timing updated, 2017-02-11 ; after compiler changes)
With a compiled language, it should be at least 20× faster. Have fun ;-) | 33,188 |
Loop Expectation (LOOPEXP)
Consider the following pseudo-code:
int a[1..N];
int max = -1;
for i = 1..N:
if(a[i] > max):
max = a[i];
Your task is to calculate the expected number of times the '
if
' block of the above pseudo-code executes. The array 'a' is a random permutation of numbers from 1..N chosen uniformly at random.
Input
First line contains t, the number of test cases. t lines follow, each containing N, the number of elements in the array.
1 ≤ t ≤ 100
1 ≤ n ≤ 100,000
Output
For each test case, output a single decimal. Your answer should be within 10
-6
of the correct answer.
Example
Input:
1
2
Output:
1.5
Explanation
For N = 2, you can have the following two permutations: [1, 2] and [2, 1].
In the first case the
if
block gets executed 2 times, and in the second case the
if
block gets executed 1 time. So the expected value is (2 + 1) / 2 = 1.5 | 33,189 |
Delta catheti II (Hard) (DELTACA2)
(3, 4, 5)
is a famous Pythagorean triple,
it gives a quick answer to the question:
For a given integer
d
, is there a Pythagorean triple
(
a, b, c
)
such that
b - a = d
?
A solution is
(3
d
, 4
d
, 5
d
)
,
and in fact one can easily prove that the set of solutions is infinite, and
that there is an obvious total order on those solutions.
Given
n
, you'll have to find the
n
th term of the sequence of solutions.
Geometrically, it is the study of right angle triangles for which the difference of the
catheti is equal to
d
.
Input
The first line of input contains an integer
T
, the number of test cases.
2
T
lines follow. Each case is on two lines.
The first line of the case contains
three integers
n, d, m
.
The second line contains an integer
L
and
2
L
other integers (p, e) ; this gives the prime factorization of
d
in standard format (d = product p^e).
Output
For each test case, compute the
n
th term amongst
the solutions
(
a, b, c
)
for the problem :
a
2
+ b
2
= c
2
with
b - a = d
and
0 < a < b < c
.
As the answer could not fit in a 64-bit container, simply output your answer modulo
m
.
Example
Input:
3
1 1 235813
0
3 21 1000
2 3 1 7 1
9 119 11
2 7 1 17 1
Output:
3 4 5
63 84 105
5 3 1
Explanations
For the first case, the first solution is
(3, 4, 5)
, as 4 - 3 = 1.
For the second case, the first solutions are:
(15, 36, 39), (24, 45, 51), (63, 84, 105), (144, 165, 219), (195, 216, 291), (420, 441, 609), ...
The third one is
(63, 84, 105)
.
For the third case, the first solutions are:
(24, 143, 145), (49, 168, 175), (57, 176, 185), (85, 204, 221), (136, 255, 289),
(180, 299, 349), (196, 315, 371), (261, 380, 461), (357, 476, 595), (481, 600, 769),
(616, 735, 959), ...
The 9th solution is
(357, 476, 595)
, reduced modulo 11, we get
(5, 3, 1)
.
Constraints
0 < T < 10^4
0 < n < 10^18
0 < d < 10^14
1 < m < 10^9
d
is the product of two integers lower than 10^7.
n, d
1
, d
2
, m
: Uniform randomly chosen in their range.
Those constraints are set to allow C-like users to work only with 64bit containers.
For your information, my 3kB-python3 code get AC in 1.22s. (Edit 2017-02-11, after compiler change)
It should be much faster with a compiled language.
Warning
: It's my hardest problem.
Have fun ;-) | 33,190 |
Building Bridges(HARD) (BRDGHRD)
The tribe soon discovers that just communication is not enough and wants to meet each other to form a joint force against the terminator. But there is a deep canyon that needs to crossed. Points have been identified on both sides on which bridge ends can be made. But before the construction could be started, a witch Chudael predicted that a bridge can only be built between corresponding end points, i.e. a bridge starting from the i
th
end point on one side can only end on the i
th
end point on the other side, where the position of end points is seen in the order in which the points were identified. If not, it would lead to the end of the tribe. The tribe just wants to make as many non-overlapping bridges as possible, with the constraint in mind.
Input
The first line of the input contains test cases t. It is followed by 3×t lines, 3 for each test case. The first line of input for each test case contains the number of end points identified on each side, n (1 ≤ n ≤ 10
5
). The second line contains x-coordinates of end points identified on the first side and similarly the third line contains the x-coordinates of corresponding end points identified on the other side. The end points are inputted in the order in which they were identified. The x-coordinates can range between -10
6
to 10
6
.
Output
You are required to output a single line for each test case. The line contains a single integer – the maximum number of bridges possible with the constraints explained above.
Example
Input:
3
4
2 5 8 10
6 4 1 2
3
5 3 10
6 4 1
6
1 2 3 4 5 6
3 4 5 6 1 2
Output:
2
2
4
Explanation
For the first test case, two non-overlapping bridges can be formed between the 3rd and 4th end points on each side.
(This problem is based on
BRIDGE
.) | 33,191 |
Self Descriptive Number (SELFDESN)
A positive integer
m
is called "self-descriptive" in base
b
, where
b
≥2 and
b
is an integer, if:
i) The representation of
m
in base
b
is of the form (a
0
a
1
...a
b-1
)
b
(that is
m
=a
0
b
b-1
+a
1
b
b-2
+...+a
b-2
b+a
b-1
, where 0≤a
i
≤b-1 are integer)
ii) a
i
is equal to the number of occurrences of number i in the sequence (a
0
a
1
...a
b-1
).
For example, (21200)
5
is "self-descriptive" in base 5, because it has five digits and contains two 0s, one 1s, two 2s, and no (3s or 4s).
(21200)
5
= (1425)
10
so 1425 is "self-descriptive" number.
Given
n
(1 ≤
n
≤10
18
) and
m
(1 ≤
m
≤ 10
9
), your task is to find the
n
-th smallest "self-descriptive" number.
Input
The first line there is an integer
T
(1 ≤
T
≤ 10
5
).
For each test case there are two integers
n
and
m
written in one line, separated by a space.
Output
For each test case, output the
n
-th smallest "self-descriptive" number, (output the number in base 10) modulo
m
.
Example
Input:
2
1 1000
2 1000
Output:
100
136
Explanation
100 is "self descriptive" number in base 4: (1210)
4
136 is "self descriptive" number in base 4: (2020)
4
Time limit ~230x My program speed:
Click here to see my submission history and time record for this problem
See also:
Another problem added by Tjandra Satria Gunawan | 33,192 |
Almost-isosceles Pythagorean triple (easy) (ALMISPY)
(3, 4, 5)
is the smallest almost-isosceles Pythagorean triple,
as
4 - 3 = 1
.
Let
S = { (
a
,
a
+1,
c
) |
a
2
+ (
a
+1)
2
=
c
2
with
a
and
c
positive integers}
.
One can prove that the set
S
of almost-isosceles Pythagorean triples is infinite.
There is an obvious total order on this set.
Input
The first line of input contains an integer
T
, the number of test cases.
On each of the next
T
lines, your are given
two integers
n
and
m
.
Output
For each test case,
you have to find the
n
th triple
(
a
,
a
+1,
c
)
in the ordered set
S
,
and print
a
and
c
.
As the answer could not fit in a 64-bit container, simply output your answer modulo
m
.
Example
Input:
3
1 10
2 123
4 289
Output:
3 5
20 29
118 118
Constraints
0 < T < 10^4
0 < n < 10^18
1 < m < 10^9
For your information, my 500B-python3 code get AC in 1.61s with 12MB of memory print.
In Python2.7 : (2.49s, 4.0MB), in Python2+psyco (2.04s, 36MB).
My 1kB C code ran in (0.04s, 1.6MB), and time limit is ×125 this one.
Have fun ;-)
(edit) With wisfaq observation, all my best timings are divided by exactly two!!!
(Edit 2017-02-11, new TL with new compiler. TL 1.11s, in the third (0.37s) my Python3 code ends.) | 33,193 |
Permutation Generator (PERMTGEN)
Hasan Jaddouh has invented a new algorithm for generating permutations this algorithm takes an array with length N as input and generate a permutation with length N from this array.
The array must satisfy (1 ≤ Ai ≤ i) in order for the resulting array to be a permutation. Here is the pseudo code of the algorithm:
read N
for i=1 to N do
read A[i]
for i=1 to N do
for j=1 to i-1 do
if A[j] >= A[i] do
A[j] = A[j]+1
for i=1 to N do
print A[i]
but unfortunately for Hasan Jaddouh, his algorithm is too slow for big arrays so he asked you to help him to find a fast way to implement his algorithm.
your program should read input same as the pseudocode and output the new array.
Input
first line contains integer N (1 ≤ N ≤ 10
5
).
second line contains N integers separated by spaces each integer is between 1 and 10
9
inclusive.
Note
: in order for Hasan Jaddouh's algorithm to work and generate a permutation the constraint (1 ≤ Ai ≤ i) must be satisfied but to make this problem harder this constraint is
not
guaranteed so it's also not necessary that the output is a permutation.
Output
Output N integers separated by spaces, the new array after applying Hasan Jaddouh's algorithm.
Example
Input:
4
4 2 1 3
Output:
7 4 1 3 | 33,194 |
Return of the Digger (RETDIG)
The adventures of “Digger” continue as he once again searches for treasure. This time, his money senses detect it underground. His plan is to dig down to it using an automatic pickaxe and his souped-up pneumatic drill.
The treasure is within a thin stretch of land, running West to East, that is made up of dirt and some rocks. This stretch is $L$ ($1 \leq L \leq 200$) metres long. Digger’s money senses are very exact, and he knows the location of the treasure he seeks – it is no more than $10000$ metres below the surface. In addition to money senses, he apparently also has rock senses, which can pinpoint $N$ ($1 \leq N \leq 5000$) rocks among the dirt, none of which will be at a depth of more than $10000$ metres.
Digger’s specially-designed pneumatic drill can only go straight down, and it can tunnel through dirt easily – however, it isn’t equipped with brakes, so it keeps on going until it hits a rock. When this happens, it stops just above the rock, but the drill bit also breaks. This time, Digger doesn’t have to worry about fuel – instead, he just wants to avoid breaking his drill bits! Once stationary, Digger can also use his pickaxe to dig left and right (yes, even through rocks!), but he can’t dig up or down with it.
The treasure is pretty fragile, so Digger definitely doesn’t want to drill right into it. Instead, he can either get to the same depth as it and use his pickaxe to dig to it, or he can use his pneumatic drill to go right past it (either 1 metre to the left or right of it). However, once he gets his hands on the treasure, Digger’s plan isn’t complete – he intends to keep drilling down until he gets to China. As such, he must first navigate past the deepest of the $N$ rocks – at that point, it’s all dirt (or so he hopes...).
Digger can start anywhere on the surface. Determine the minimum amount of drill bits that he must break in order to retrieve the treasure and dig down past all the rocks, if it’s possible at all.
Input
Line $1$: $L$ and $N$ – respectively, the length of the stretch of land (in metres) and the number of rocks.
Lines $2..N+1$: $A$ and $B$ – the $i$th line gives the location of the ($i-1$)th rock, where $A$ is its depth, and $B$ is its distance from the West edge of the stretch of land (both in metres).
Line $N+2$: $Y$ and $X$ – the location of the treasure, where $Y$ is its depth, and $X$ is its distance from the West edge of the stretch of land (both in metres). The treasure will not be within a rock.
Output
If it’s impossible for Digger to reach the treasure and dig down past all the rocks, output “Use dynamite”.
Otherwise, output a single number – the minimum number of drill bits Digger must break to accomplish this.
Example
Input:
10 20
1 5
2 1
2 2
2 4
2 5
2 6
2 8
2 9
3 3
4 7
4 8
4 9
5 3
5 4
5 5
5 6
6 3
10 1
10 2
10 7
8 6
Output:
3
Explanation of Sample:
Digger starts on the surface, 7 metres from the West edge of the stretch of land. He drills down for 3 metres until he hits a rock and breaks his first drill bit. He then uses his pickaxe to walk to the left, and drills down another metre, hitting another rock and breaking his second drill bit. He then walks to the right (through a rock), and drills down for 5 metres, picking up the treasure on the way, until he hits another rock and breaks his third and final drill bit. He then walks to the right and drills down past the last rock. This route is shown below (‘.’: dirt, ‘x’: rock, ‘T’: treasure, ‘D’: drill, ’<’ or ‘>’: pickaxe):
.....x.D..
.xx.xxxDxx
...x..
......D>xx
...xxxxD..
...x...D..
.......D..
......TD..
.......D>.
.xx....xD.
........D. | 33,195 |
Traffic Lights (TLIGHTS)
Jim-Bob lives in a strange city where the streets don’t necessarily run NS or EW. Instead, the $N$ ($1 \leq N \leq 10^5$) streets run seemingly at random, sometimes crossing over each other by bridges, and intersecting with one another at exactly $K$ ($1 \leq K \leq 1000$) intersections. Each intersection consists of some streets coming together, as well as a traffic light.
Street $i$ starts at intersection $s_i$ ($1 \leq s_i \leq K$), and ends at a different intersection $e_i$ ($1 \leq e_i \leq K$), going through no other intersections in between. It takes $t_i$ ($1 \leq t_i \leq 1000$) minutes to travel down street $i$ (this number is derived from the length, the average pothole size, and the amount of roadkill). Each road can be travelled in either direction in the same amount of time.
The traffic lights in this city are also strange. First of all, each one only alternates between green and red. Each light also cycles through these colours at a different rate – the traffic light located at intersection $i$ stays green for $g_i$ ($1 \leq g_i \leq 1000$) minutes, then stays red for $r_i$ ($1 \leq r_i \leq 1000$) minutes, then goes back to green, and so on.
Jim-Bob always obeys the law, and will never run a red light. If he arrives at an intersection while the light is green, he can pass right through it. Otherwise, he must wait there until the light turns green. If he gets to an intersection just as the traffic light is turning red, he must wait. It takes no time to drive through an intersection, so the light will never turn red on him as he drives through.
Jim-Bob starts at his house, also known as intersection $1$. As soon as he leaves his house, all the traffic lights turn green, starting their green-red-green cycle. He wishes to drive to Billy-Bob’s house (which is right at intersection $K$) as fast as possible. Neither the starting nor the finishing intersections have traffic lights, so their $g$ and $r$ values will be given as 0. Find the minimum number of minutes Jim-Bob can take to drive from his house to Billy-Bob’s.
Input
Line $1$: 2 integers, $N$ and $K$
Next $N$ lines: 3 integers, $s_i$, $e_i$, and $t_i$, for $i=1..N$
Next $K$ lines: 2 integers, $g_i$ and $r_i$, for $i=1..K$
Output
A single integer – the minimum number of minutes it takes to drive from Jim-Bob’s house to Billy-Bob’s. It will always be possible to do this.
Example
Input:
7 6
1 2 4
1 3 1
3 5 2
2 4 2
2 5 6
5 4 2
5 6 10
0 0
5 5
1 20
2 5
10 2
0 0
Output:
19
Explanation of Sample:
Jim-Bob can drive to intersection 2 (4 min), drive on to intersection 4 (2 min), wait for the green light (1 min), drive down to intersection 5 (2 min), and finally drive to Billy-Bob’s house (10 min). This is a total of 19 minutes.
Note: The traffic light at intersection 3 only stays green for 1 minute, which means that Jim-Bob would just miss it if he drove directly there. On the other hand, he makes the green lights at intersections 2 and 5 just in time, as they turn red 1 minute after he passes. | 33,196 |
Battleships (BSHIP)
You and a friend are playing the classic game of Battleships. You each have a grid consisting of $M$ rows of $N$ cells each ($1 \leq M,N \leq 2000$). Each cell is either empty or contains a player’s ship (in this version of the game, all ships are the size of one cell). The goal of the game is to destroy all of the opponent’s ships by hitting individual cells.
You and your friend have bet tons of Internet Points on this game. Unfortunately, your friend is completely owning you. So desperate times call for desperate measures.
You know for a fact that you can distract your friend for a brief moment by telling him that a famous programmer is behind him, but this trick will only work exactly once (programmers are so predictable). While he isn’t looking, you’ll have time to snatch up some of his ships with one hand. Your hand can cover a square of exactly $S$x$S$ cells ($1 \leq S \leq min\{M,N\}$), and you can gather all the ships within such a square at once.
Of course, your friend is no fool, so he’s got his grid well concealed. As such, you don’t know anything about it except its size, so when the time comes, you’ll just choose a random square of size $S$x$S$ that’s completely within the grid.
As usual, these bets attract large crowds. One of the bystanders who can see your opponent’s grid knows your plan, and is curious as to the expected number of ships that you will grab (in other words, the average number of ships out of all the possible snatches you could make). Nerdy though he is, he can’t calculate it in his head, so he runs over to a computer and codes up a program...
Input
Line 1: 3 integers, $M$, $N$, and $S$.
Next $M$ lines: $N$ characters each, representing your opponent’s grid – an ‘X’ represents a ship, while a ‘.’ represents an empty cell.
Output
A single number – the expected number of ships that you’ll grab, rounded to 6 decimal places.
Example
Input:
3 4 2
XX.X
XX..
.X..
Output:
2.000000
Explanation of Sample
There are 6 possible areas you could pick, yielding this many ships each:
4 2 1
3 2 0
This is a total of 12 ships, for an average of exactly 2 per grab. | 33,197 |
Advanced Battleships (ABSHIP)
You managed to beat your friend in Battleships and take his Internet Points! Perfectly legitimately, of course. However, for some strange reason he’s upset, and now challenges you to a rematch - this time at the game of Advanced Battleships, and with even higher stakes!
You each have a grid consisting of $M$ rows of $N$ cells each ($1 \leq M, N \leq 500$). Each cell is either empty or contains part of a player’s ship. What makes this game so “advanced” is the fact that each ship consists of a maximal set of 1 or more adjacent, nonempty cells. Two cells are considered adjacent if they share a common side. Of course, this means that ships can have some very strange shapes. No two ships can be adjacent to one another, of course.
You know for a fact that you can distract your friend for a brief moment, this time by telling him that someone proved that P = NP, but this trick will again only work exactly once. While he isn’t looking, you’ll have time to snatch up some of his ships with one hand. Your hand can cover a square of exactly $S$x$S$ cells ($1 \leq S \leq min\{M, N\}$), and you can gather all the ships that are at least partially within such a square at once.
Of course, your friend is no fool, so he’s got his grid well concealed. As such, you don’t know anything about it except its size, so when the time comes, you’ll just choose a random square of size $S$x$S$ that’s completely within the grid.
As usual, these bets attract large crowds. One of the bystanders who can see your opponent’s grid knows your plan, and is curious as to the expected number of ships that you will grab (in other words, the average number of ships out of all the possible snatches you could make). Nerdy though he is, he can’t calculate it in his head, so he runs over to a computer and codes up a program...
Input
Line $1$: 3 integers, $M$, $N$, and $S$
Next $M$ lines: $N$ characters each, representing your opponent’s grid – an ‘X’ represents a ship, while a ‘.’ represents an empty cell
Output
A single number – the expected number of ships that you’ll grab, rounded to 6 decimal places.
Example
Input:
5 5 2
XXXX.
X..X.
X..X.
X....
.XX..
Output:
0.875000
Explanation of Sample:
There are 16 possible areas you could pick, yielding this many ships each:
1 1 1 1
1 0 1 1
1 0 1 1
2 1 1 0
This is a total of 14 ships, for an average of 0.875 per grab. | 33,198 |
The Codefather (CFATHER)
The computer science mafia, headed of course by the Codefather, have control of the computer science course points spreadsheet. The Codefather has the power to transfer points from one person to another.
The Codefather’s daughter is getting married, and he wants to give a gift to his future son-in-law, who happens to be taking this computer science course. Since only the person with the most points can get a mark of 100% in this course, the Codefather wants to insure that his future son-in-law will have strictly more points than anyone else by performing a number of point transfers. However, he’s a cautious man (in his business, you have to be), so he follows the following rules:
1. None of the transfers will involve his future son-in-law.
2. For each pair of people, he will only perform up to one point transfer, though this transfer can involve any number of points.
3. No person can be involved in both transfers in which they lose and gain points - only one or the other (or neither).
4. After all the transfers are completed, no student can have a negative amount of points.
There are $N$ ($1 \leq N \leq 5000$) students in this course, each with a unique student number from $1$ to $N$, inclusive. Student $i$ starts off with $P_i$ ($1 \leq P_i \leq 10^6$) points. The Codefather’s future son-in-law is student $1$.
Though the Codefather is a powerful man, he’s still wary of the authorities, and wants to remain as inconspicuous as possible. Therefore, he wants to minimize the number of points in the largest transfer he makes, while still ensuring that his future son-in-law will get 100%.
Input
Line $1$: 1 integer, $N$
Next $N$ lines: 1 integer, $P_i$, for $i=1..N$
Output
If it’s possible for the Codefather to observe the rules and give his future son-in-law more points than anyone else, minimize the number of points in the largest transfer he must make and output this value.
Otherwise, output “impossible”.
Example
Input:
4
500
300
900
100
Output:
202
Explanation of Sample:
The future son-in-law only has 500 points, so the Codefather must make student 3 lose at least 401. However, the other students must also stay strictly below 500. His best strategy is to transfer 199 points from student 3 to student 2, and 202 points from student 3 to student 4. This will result in the following point distribution:
Student 1: 500
Student 2: 499
Student 3: 499
Student 4: 302 | 33,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.