task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
Milk Scheduling (MSCHED)
(For Vietnamese version, see below.)
Farmer John has N cows that need to be milked (1 ≤ N ≤ 10,000), each of which takes only one unit of time to milk.
Being impatient animals, some cows will refuse to be milked if Farmer John waits too long to milk them. More specifically, cow i produces g
i
gallons of milk (1 ≤ g
i
≤ 1000), but only if she is milked before a deadline at time d
i
(1 ≤ d
i
≤ 10,000). Time starts at t=0, so at most x total cows can be milked prior to a deadline at time t=x.
Please help Farmer John determine the maximum amount of milk that he can obtain if he milks the cows optimally.
Input
Line 1: The value of N.
Lines 2..1+N: Line i+1 contains the integers g
i
and d
i
.
Output
A single numbers denotes the maximum number of gallons of milk Farmer John can obtain.
Sample
Input:
4
10 3
7 5
8 1
2 1
Output :
25
Explanation
There are 4 cows. The first produces 10 gallons of milk if milked by time 3, and so on.
Farmer John milks cow 3 first, giving up on cow 4 since she cannot be milked by her deadline due to the conflict with cow 3. Farmer John then milks cows 1 and 2.
***
Nông dân John có N con bò, để vắt sữa một con bò cần 1 đơn vị thời gian.
Vốn là loài vật lười, những con bò sẽ không chịu để vắt sữa nếu John bắt chúng chờ quá lâu. Cụ thể, con bò i cho g
i
gallon sữa, nhưng chỉ khi nó được vắt sữa trước thời gian d
i
. Thời gian bắt đầu ở T = 0, nên có tối đa X con bò có thể được vắt sữa trước thời hạn T = X.
Hãy giúp nông dân John tính lượng sữa tối đa mà ông có thể vắt được nếu như ông chọn được cách vắt hiệu quả nhất.
Input :
- Dòng 1 : chứa số nguyên dương N.
- Dòng 2 -> n + 1 : dòng thứ i + 1 chứa 2 số nguyên g
i
và d
i
.
Output :
- Lượng sữa nhiều nhất mà John có thể vắt.
Giới hạn :
- 1 ≤ n ≤ 10000
- 1 ≤ g
i
≤ 1000
- 1 ≤ d
i
≤ 10000
Ví dụ :
Input :
4
10 3
7 5
8 1
2 1
Output :
25
Giải thích : John vắt sữa con bò 3, sau đó đến con 1 rồi con 2. | 33,600 |
Vacation Planning (VACATION)
English
Vietnamese
Air Bovinia is planning to connect the N farms (1 <= N <= 200) that the cows live on. As with any airline, K of these farms (1 <= K <= 100, K <= N) have been selected as hubs. The farms are conveniently numbered 1..N, with farms 1..K being the hubs.
Currently there are M (1 <= M <= 10,000) one-way flights connecting these farms. Flight i travels from farm u_i to farm v_i, and costs d_i dollars (1 <= d_i <= 1,000,000).
The airline recently received a request for Q (1 <= Q <= 10,000) one-way trips. The ith trip is from farm a_i to farm b_i. In order to get from a_i to b_i, the trip may include any sequence of direct flights (possibly even visiting the same farm multiple times), but it must include at least one hub (which may or may not be be the start or the destination). This requirement may result in there being no valid route from a_i to b_i. For all other trip requests, however, your goal is to help Air Bovinia determine the minimum cost of a valid route.
Input
Line 1: Four integers: N, M, K, and Q.
Lines 2..1+M: Line i+1 contains u_i, v_i, and d_i for flight i.
Lines 2+M..1+M+Q: Line 1+M+i describes the ith trip in terms of a_i and b_i
Output
Line 1: The number of trips (out of Q) for which a valid route is possible.
Line 2: The sum, over all trips for which a valid route is possible, of the minimum possible route cost.
Constraints
1 ≤ n ≤ 200
1 ≤ k ≤ 100
1 ≤ m ≤ 10000
1 ≤ d_i ≤ 1000000
1 ≤ q ≤ 10000
Sample
Input:
3 3 1 3
3 1 10
1 3 10
1 2 7
3 2
2 3
1 2
Output:
2
24
Explanation
There are three farms (numbered 1, 2 and 3); farm 1 is a hub. There is a $10 flight from farm 3 to farm 1, and so on. We wish to look for trips from farm 3 to farm 2, from 2→3, and from 1→2.
The trip from 3→2 has only one possible route, of cost 10+7. The trip from 2→3 has no valid route, since there is no flight leaving farm 2. The trip from 1→2 has only one valid route again, of cost 7. | 33,601 |
Magical colorful cats (easy) (COLORCAT)
There is a circle with n cats, includes white cats, red cats and green cats. When two cats with different color talk with each other, they both change to third color. If they are same color, nothing will happen.
At each step, the 1
st
cat talks with 2
nd
cat, the 2
nd
cat talks with the 3
rd
cat,… and the n
th
cat talks with 1
st
cat.
Given the original color of n cats, your task is find the color of n cats after k steps.
Input :
- First line : n and k (1 ≤ n ≤ 20000, 1 ≤ k ≤ 30000)
- Second line : n characters, the i-th charater denotes color of the i-th cat at first state
Output :
- n characters denotes the color of n cats after k steps.
Sample :
Input :
3 1
GRR
Output :
RGR
Input :
5 4
WRWRW
Output :
GGGWG
Note :
After solved this problem, you may want to try
BLCATS | 33,602 |
Krypt in Time (KIT)
In a land far away people can travel back in time in person or send messages to them in the past. Sending messages that can change ones future is forbidden. The messages that are sent are intercepted by the time police. Jim wants to send a message to himself in the past to prevent his death. He decides to encrypt using a "number-pad". All the numbers in number-pad are between 0 and 25. The message he wants to send can be encrypted if each character in the string is encoded by a number from the pad provided each number from the number- pad is only used once. The encryption is done by shifting each letter in the message by k positions, where k is determined by the number-pad. Shift occurs between the alphabets "a" and "z". If a letter in the message is shifted past "z" then it starts back at "a" and continues to shift.
For example: If the number-pad contains 2, the message abc is transformed to cde and xyz to zab.
Input
The first line will contain the size of the number-pad N, followed by a sequence of numbers for the pad. The remaining input consists of a series of words to be encrypted using the number-pad. You may assume that the maximum size of the pad (N) is 100 numbers, all numbers in the pad are between 0 and 25, and that all input will be lowercase letters. The end of input is indicated by -1.
Output
For each word to be encrypted, output a line containing the encrypted word.
Example
Input:
10
1 2 3 4 5 4 3 2 1 0
aa aaa
zzzzz
-1
Output:
bc
def
dcbaz | 33,603 |
Huge Pascal triangle (DUKKAR2)
Given
P
a prime number, and
N
an integer,
Dukkar
found a really fast way to compute how many numbers are divisible by
P
on the
N
th
row of the Pascal triangle.
Now the task will be much harder : it's for all the
N
first rows.
Moreover
N
will be a giant number, given in base
P
for convenience.
Input
The first line of input contains an integer
T
, the number of test cases. Follow 2×
T
lines.
For each test case, on the first line your are given two integers
P
and
k
.
On the second line you are given
k
integers : the digits of
N
in base
P
.
N = a
0
×P
0
+ ... + a
i
×P
i
+ ... + a
k-1
×P
k-1
Output
For each test case, you have to print the number
of numbers in all the first
N
rows of the Pascal triangle that are divisible by
P
.
As the answer could not fit in a 64bit container, give your answer modulo 1000000007.
Example
Input:
3
5 2
0 1
5 2
1 1
7 3
2 0 2
Output:
0
4
2689
Explanations
For the first case, N = 0×5
0
+ 1×5
1
= 5. No numbers are divisible by 5 in the first 5 rows.
For the second case, N = 1×5
0
+ 1×5
1
= 6. Only 4 numbers are divisible by 5 in the first 6 rows.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1
5 10 10 5
1
For the third case, N = 2×7
0
+ 0×7
1
+ 2×7
2
= 100.
Constraints
0 < T < 300
0 < P < 10^9, a prime number
0 < k < 1000
0 <= a
i
< P, a
k-1
>0
For your information, my 300B-python3 code get AC in 3.03s with 11MB of memory print.
My C-code get AC in 0.08s with 1.6MB of memory print.
Have fun ;-)
Edit(25/I/2015) With Cube cluster my C-time is 0.01s and my PY3.4-time is 0.26s.
Edit(11/II/2017) With compiler changes my C-time is 0.00s and my PY3.4-time is 0.12s. | 33,604 |
Hexadecimal value of Pi (PIHEX2)
PIHEX2
All people use decimal system every day. For all of us the value of Pi is 3.141592653589793238462643383279....
But it is common to use the hexadecimal system in programming. The hexadecimal value of Pi is 3.243F6A8885A308D313198A2E037073....
In this problem for given value a, you should compute the digit that appears in hexadecimal representation of Pi at the a
th
position after comma (for a=0 the answer is '3' - the only digit before comma, for a=1 the answer is '2' - the first digit after comma; see example to clarify).
Input
The first line of input contains single integer t - the number of test cases (1 ≤ t ≤ 20).
The second line of input contains t single-space separated integers a
1
, a
2
... a
t
(0 ≤ a
i
≤ 1000000).
Output
The only line of output should contain t hexadecimal digits (use capital letters A-F), where i
th
digit appears in Pi hexadecimal representation at a
i
th
position.
Example
Input:
16
0 1 2 3 4 5 6 7 8 9 10 100 1000 10000 100000 1000000
Output:
3243F6A8885C3652 | 33,605 |
Base Conversion (BASECONV)
Leo didn't do all the job in his
last problem
, somebody gave him the numbers in a convenient base. It was the bottleneck of the problem... Now your task is to do this job.
Input
The first line of input contains three integers
T
, the number of test cases,
B1
, the first base,
B2
, the second base.
Follow 2×
T
lines.
For each test case, on the first line your are given one integer
k
.
On the second line you are given
k
integers : the digits of
N
in base
B1
.
N = a
0
×B1
0
+ ... + a
i
×B1
i
+ ... + a
k-1
×B1
k-1
Output
For each test case, you have to print the number
N
in base
B2
.
See sample for details.
Example
Input:
1 10 100
5
5 4 3 2 1
Output:
3
45 23 1
Explanations
For the lonely case, N = 5×10
0
+ 4×10
1
+ 3×10
2
+ 2×10
3
+ 1×10
4
= 12345.
We have: N = 45×100
0
+ 23×100
1
+ 1×100
2
. You have to print 3, the number of digits,
then the digits: 45, 23 and 1.
Constraints
0 < T <= 50
1 < B1,B2 <= 10^9
1 < k <= 10000
0 <= a
i
< B1 , a
k-1
>0
Time limit is sqrt(T_basic_pike_code * T_awaited_python_code) = sqrt(13.34*6.97), based on my Python3/Pike experiments.
You may try before the
tutorial edition
.
Have fun ;-)
Edit(2017-02-11) : With compiler updates, a new time limit is set.
Time limit is sqrt(T_basic_pike_code * T_awaited_python_code) = sqrt(3.93*1.57), based on my Python3/Pike experiments.
Thanks @Blue_Mary for pointing this out. | 33,606 |
Boiling Vegetables (BOILING)
The trick to boiling vegetables is to make sure all pieces are about the same size. If they are not, the small ones get too soft or the large ones get undercooked (or both). Fortunately, you have heard of the kitchen knife, but your parents’ warnings of using sharp instruments still echoes in your head. Therefore you better use it as little as possible. You can take a piece of a vegetable of weight w and cut it arbitrarily in two pieces of weight w
left
and w
right
, where w
left
+ w
right
= w. This operation constitutes a “cut”. Given a set of pieces of vegetables, determine the minimum number of cuts needed to make the ratio between the smallest and the largest resulting piece go above a given threshold.
Input
The input starts with a floating point number T with 2 decimal digits, 0.5 < T < 1, and a positive integer N
≤
1 000. Next follow N positive integer weights w
1
, w
2
, ..., w
N
. All weights are less than 10
6.
Output
Output the minimum number of cuts needed to make the ratio between the resulting minimum weight piece and the resulting maximum weight piece be above T. You may assume that the number of cuts needed is less than 500.
To avoid issues with floating point numbers, you can assume that the optimal answer for ratio T is the same as for ratio T + 0.0001.
Example
Input 1:
0.99 3
2000 3000 4000
Output 1:
6
Input 2:
0.80 2
1000 1400
Output 2:
3 | 33,607 |
BSTRING (INS14A)
In his next interview Digo is given a binary string of N characters. A binary string is string consisting of only 0's and 1's. Digo can swap any adjacent pair of characters in one operation. Digo has to bring at least M 1's together starting at any position of the string. Help him count the minimum number of operations required to do so.
It is guaranteed that there are at least M 1's present in the given string.
Input
First line contains single integer T. Number of test cases.
Next 2 × T lines represent T test cases. Each test case is described by two lines; first line contains a single integer M and the second line contains the input binary string.
Output
Output T lines, one for each test case containing the answer for that case.
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 50000
1 ≤ M ≤ N
Sum of N over all the cases is less than or equal to 50000.
Sample
Input:
2
3
101001
2
101001
Output:
3
1 | 33,608 |
TRISQRS (INS14B)
After coming back from the ACM World Finals '13, Digo decided to celebrate his performance by watching a lot of action movies. Sitting in front of his laptop for days watching his favourite stars battle it out, Digo suddenly got inspired to join the CIA. Digo is a serious man, and vowed that he'd be inducted in the CIA force by the end of the year. And mind you, he takes his vows
very
seriously!
After sweating it out in the field for months, it's finally time for his interview. The interviewer believes that mental agility is as important as physical fitness and decides to test our hero with a mathematical puzzle.
The interviewer hands Digo a square of side N and asks him to partition the square into a number of right angled triangles, each having an equal integral area. Two sides of the triangle should be parallel to the two sides of the square. Being an ACM World Finalist, Digo solves the question in a split second. Impressed, the interviewer decided to test him with a harder question. He asks Digo to tell him the number of such partitions possible. All partitions having the same number of right triangles are considered the same.
Input
First line will contain T, the number of test cases. Next T lines will contain a single integer each N, denoting the size of the square.
Output
Output one line for each test case. Each line containing one integer which is the desired solution.
Constraints
1 <= T <= 1000
1 <= N <= 1000
Example
Input:
2
1
2
Output
0
2 | 33,609 |
Digo plays with Numbers (INS14C)
Digo and his friend Sharry have completed their missions and were relaxing. Both of them love mathematics and love to play with numbers. They have a book in which several binary strings are written. Digo comes up with an idea of an interesting game. He asks Sharry to think of a number K, which is less than or equal to the length of the string N. Both players play alternately. In his turn, a person can remove any bit from the binary string. Digo removes such as to maximize the value of the leftover binary string while Sharry plays to minimize the string. This process continues until K binary digits are left. You have to tell those K binary digits left after the game is over.
It is given that Sharry always plays first.
Input
The first line consists of a single integer T, denoting the number of test cases. 2 * T lines follow. For every test case, the first line consists of two integers N and K, denoting the initial length of the string and its length at the end of the game. The second line for the test case contains the initial binary string of length N.
Output
For each test case print the final string left after removal of characters.
Constraints
1 <= T <= 1000
1 <= N <= 1000
1 <= K <= N
Sample
Input:
2
5 3
10010
4 2
1111
Output:
010
11 | 33,610 |
Digo Needs Guns (INS14D)
Digo was given the task to secure a very important room where many famous personalities were residing. So the government provided him with some automated guns which he could fit on the line of intersection between any two walls in the room. The guns can rotate anywhere about the point on the line they are placed, but cannot shoot through walls. Since the country was suffering from financial crisis and automated guns were very expensive, Digo thought of using the minimum number of guns and returning the rest. But Digo did not know the configuration of the room as it was very confidential. He just knew the number of sides the room had. The shape of the room can be any simple polygon. What is the minimum number of guns he must carry with him so it is possible for him to secure every possible polygonic room having n walls.
Input:
The first line consists of a single integer T denoting the number of test cases. T lines follow each containing an integer N denoting the number of sides.
Output:
For each test case print the required answer.
Constraints:
1 <= T <= 1000000
3 <= n <= 1000000000
Sample:
Input
1
4
Output
1
Note: This question has large I/O files, faster I/O methods are needed to get an AC. | 33,611 |
Glorious Gamblers (INS14E)
Back in 2012 when Digo and Tourist were training for their CIA Assignments, they became good friends. Digo was a skeptical fellow and believed that the world would end that year. Tourist however believed all this did not make any sense. After countless arguments leading to no conclusion, Digo and Tourist finally decided to place a bet on it and move on.
It is 2014 and they meet again on their first assignments. Quite evidently, Digo was proved wrong, and it's time for him to pay back the bet. Both Digo and Tourist being good programmers, they decided to have some fun with the bet. The money that Digo needs to pay Tourist can be expressed in the form of a payoff matrix for Digo. The payoff matrix A[][] is an M×N matrix where every element is a positive integer.
They place a ring on the cell (1, 1); and the game ends when the ring wounds up on the cell (M, N). When the ring is on the cell (i, j), they toss a fair coin. If it is a heads, it is Digo's turn to move and if it's a tails it is Tourist's turn. In one turn, a person can move the ring from cell (i, j) to either one cell east, one cell south, or one cell south-east. The ring cannot be moved outside the bounds of the payoff matrix.
The money that Digo need to pay Tourist is the sum of the elements that lie on the path traversed by the ring. Both being logical fellows, Digo would want to minimize the overall money that he needs to pay, while Tourist would want to maximize it.
Help Digo find out the expected money that he would owe Digo at the end of the game. (correct to exactly 6 decimal places)
NOTE: LARGE INPUT FILES. USE FASTER I/O.
Input
The first line contains T, the number of test cases.
For every test case, the first line contains two integers M, N; the dimensions of the matrix.
The next M lines contain N integers each, such that the jth element on the ith line is the element A[i][j] in the payoff matrix.
Output
For every test case, output exactly one result, which is the expected value of the money that Digo would owe Tourist at the end of the game (correct to exactly 6 decimal places).
Constraints
1 ≤ T ≤ 10
2 ≤ M, N ≤ 500
0 ≤ A[i][j] ≤ 10
6
Example
Input:
1
2 3
1 2 2
3 5 1
Output:
8.250000 | 33,612 |
Save CodeVillage (INS14F)
In another test the terrorists have occupied CodeVillage. The village consists of N buildings. Each building is connected to every other building with a road. Each terrorist has been told to cover a single strip of K buildings along any path. A path is a set of roads connecting a particular set of buildings in which the buildings will not be repeated and every adjacent pair of roads share a common building.
Each terrorist will be given a distinct path. Two paths are different if at least one building is different or the order of visiting the buildings is different. For example a path from building numbers 1 → 2 → 3 is different from a path from building numbers 1 → 3 → 2.
Now so as to improve coordination between the terrorists, they had decided that every terrorist should meet all other terrorists along the path. Thus there should be at least one common building in every pair of paths.
Digo must take enough artillery to kill all the terrorists but not much more due to the ongoing recession problems. So help him calculate the maximum number of terrorists that may be present in the village. Give your answer modulo 10
9
+ 7.
Input
The first line contains a single integer T denoting the number of test cases. T lines follow each containing two space separated integers N and K.
Output
For each test case output the maximum possible number of terrorists modulo 10
9
+ 7.
Constraints
1 ≤ T ≤ 100000
1 ≤ K ≤ N ≤ 1000000
Sample
Input:
2
3 2
5 3
Output:
6
60 | 33,613 |
Kill them All (INS14G)
For his training, Digo is asked to solve the following challenge.
There is a mock terrorist situation. There are N terrorists and Digo is teamed up with his friend Sharry. They have to kill all the terrorists. Since this was too easy a task for this dynamic duo, Digo decided to have some fun with this challenge. At any given instant, Digo wants that the number of terrorists killed by him should be more than those killed by Sharry. The terrorists come in a fixed order. Any terrorist can be killed by either Digo or Sharry. Give the total number of ways in which the terrorists can be killed by them such that at every instant terrorists killed by Digo is more than the number of terrorists killed by Sharry.
Give your answer modulo 10
9
+7.
Input
The first line consists of a single integer T, denoting the number of test cases.
T lines follow each consisting of an integer N denoting the total number of terrorists.
Output
For each test case print the total number of possible ways modulo 10
9
+ 7.
Constraints
1 ≤ t ≤ 100000
1 ≤ n ≤ 1000000
Sample
Input:
2
1
3
Output:
1
2 | 33,614 |
Virus Revisited (INS14H)
Due to the failed experiment in the laboratory of our scientist Digo, a new universe of N dimensions is created with one single virus at origin at time T = 0.
Each point in this new universe can be represented by a linear array of indices (c1, c2, c3 ... cn) where ci represents the i th coordinate. In this new universe we are interested in only integer points i.e, points with integer coordinates. Two points (a1, a2 ... an), (b1, b2 ... bn) are adjacent to each other if sum of abs(ai - bi) for all i is equal to 1 (abs() is the absolute value function). If observed carefully one can observe that there are 2×N adjacent points for every point in the universe. Origin is (0, 0 ... n times).
The virus reproduces very rapidly. After every second it gives birth to 2×N identical new viruses of its kind and dies. As the newly born viruses are born, each of them moves to a distinct point, each of which are adjacent to the point at which the parent was present. New Viruses reproduce at their respective points and this procedure goes on. As the viruses are very small, any number of viruses can stay at a single point.
Now Our Scientist Digo has Q queries. In each query he gives you two integers N and T, and you need to tell him how many viruses are present at the origin in N dimension universe at the end of T seconds.
As the output can be huge print each output modulo (10
9
+ 7).
Input Format
First line contains a single integer Q representing the number of queries.
Q lines follow with two space separated integers N and T in each line. N, T have their respective meanings mentioned in the problem statement.
Output Format
Print a single integer for every query in a separate line.
Constraints
1 ≤ Q ≤ 20000
1 ≤ N ≤ 100
1 ≤ T ≤ 200
Sample
Input:
3
1 2
2 3
3 2
Output:
2
0
6 | 33,615 |
Infinite Sequence (INS14I)
Digo and Sharry like to play with numbers and sequences. They decide to write an infinite sequence. For this they start by choosing a number each. They start making the sequence by following these rules:
Digo writes his number on a piece of paper. This is the 0th number of the sequence.
Then Sharry writes his number on the paper, as many times as Digo’s number. e.g. if Digo wrote 2, then Sharry would write his number 2 times, making the total sequence of length 3.
Then Digo writes his number on the paper, which becomes the next element of the sequence.
Then Sharry writes his number as many times as the number indexed 1 in the sequence.
Then Digo writes his number on the paper, which becomes the next element of the sequence.
Then Sharry writes his number as many times as the number indexed 2 in the sequence.
... and the cycle goes on.
Now Digo starts to feel that the sequence that they are generating is very trivial. He claims he can tell the digit at the nth place without having to play the game. So Sharry challenges him to tell the digit which will come at the nth place.
Help Digo complete Sharry's challenge.
It is given that Digo chooses 4 as his number and Sharry chooses 5 as his number.
Input
First line of the input contains an integer T - the number of test cases.
T lines follow, each containing an integer N.
Output
Print T lines. For every test case, print the digit that appears in the Nth place.
Constraints
1 < T < 100
0 ≤ N < 1000000000
Sample
Input
3
0
4
7
Output
4
5
5
Explanation
The sequence is 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5 ... | 33,616 |
Checkers (INS14J)
Digo has completed all his initial assignments and is now eyeing for a promotion in the CIA office. There is only one seat available for which there are two contenders, Digo and his arch rival Sharry. Both are equally qualified for the promotion and their interviewer finds himself unable to chose between the two of them. Finally he decided to settle it by allowing the two gentlemen to play a game and see who wins it.
In the game, there is an infinite grid, with certain cells filled with checkers. Each checker occupies exactly one cell, and the cells are 0-indexed. The positions of the checkers are given in the form of Cartesian coordinates (x, y).
For example a grid with 5 checkers placed at positions {(1, 0), (1, 2), (2, 5), (4, 2), (4, 4)} would look like:
There are an infinite number of diagonals of the form y = x + k, where k is an integer, drawn on this grid. Each diagonal can be uniquely identified by the value of this 'k', which is known as the index of the diagonal. There is at most one checker on every diagonal. In one turn, a person can chose a checker and move it along the diagonal it lies on, in the south-west direction only (i.e. towards decreasing coordinates). The checkers cannot be moved outside the first quadrant (i.e., their coordinates can never be made negative throughout the game). Whenever a person moves a checker, the checker lying on the next higher occupied diagonal moves an equal distance along the north-east direction. A diagonal with a greater index is said to be higher than a diagonal with a smaller index. Thus if the person moves the checker at position (4, 2) {diagonal index - 2} one cell south-west, the checker at position (1, 0) {diagonal index -1} moves one cell north-east.
The final position of the checkers after this move would be:
Note that if a person moves the checker lying on the highest occupied diagonal (the checker at position (2, 5) in our case), no other checker is disturbed.
The game ends when no move is possible. The last person to make a move wins. Sharry is an over-confident guy and allows Digo to move first. Help Digo determine whether he will win the game or not.
NOTE: Large input files. Use faster I/O.
Input
The first line contains T, the number of test cases.
The first line of every test case contains N, the number of checkers on the grid. This is followed by N lines. The ith line contains two integers x[i] and y[i], which are the coordinates of the ith checker.
Output
For every test case output a single line containing "Yes" if it is possible for Digo to win the game, or "No" otherwise. (quotes added for clarity)
Constraints
1 ≤ T ≤ 20
1 ≤ N ≤ 10000
0 ≤ x[i], y[i] ≤ 1000000000
Example
Input:
1
5
1 0
1 2
2 5
4 2
4 4
Output:
Yes | 33,617 |
Digo Goes Training (INS14K)
Digo is being trained for shooting as it is a very integral part of his missions. His trainer sets up a training arena for him to practice for it. Digo is taken to the ground where many strong penetrable walls are placed in arbitrary manner. Consider the ground to be a rectangular grid with cartesian coordinates. Digo fires the bullets from a given point on the X-axis. The bullets can only travel parallel to the Y-axis. Given the endpoints of the walls and Digo's current position on the X-axis, he wants to know how many walls he will penetrate with each shot. The shots will only penetrate the wall, they are not powerful enough to break them. As he is very weak in mathematics, he asks you to help him.
Input
The first line consists of the number of test cases, T. The second line contains the number of walls N. Then N lines follow, each line contains 4 integers denoting the end-points of the walls i.e. x1 y1 x2 y2. Next line denotes Q, the number of queries. Queries can be of two types:
1 x1 y1 x2 y2 : which denotes the endpoints of new wall placed.
0 pos : where pos tells about the x coordinate of Digo’s position. The position will be a floating point number, having exactly two digits after the decimal point.
Output
For each query of the type ‘0 pos’ output the numbers of walls penetrated.
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 1000
1 ≤ Q ≤ 1000
0 ≤ x1, y1, x2, y2 ≤ 20000
0.00 ≤ pos ≤ 20000.00
Sample
Input:
1
3
3 5 7 8
1 3 5 6
2 4 8 9
4
0 6.73
1 4 7 9 8
1 2 5 6 3
0 3.55
Output:
2
4 | 33,618 |
Rooted Trees (INS14L)
Digo is given a rooted tree where nodes are numbered from 1 to N (1 is the root node) and asked some queries on it.
There are two types of queries:
Given node number U, two integers X, K which means add X to the given node, X+K to its children, X+2×K to children of its children and so on.
Given a node number U print the sum of nodes in the subtree rooted at U (including node U).
Since the answer can be too long, print the answer 10
9
+ 7
Initially each node contains zero.
Input
First line contains a single integer N denoting the number of nodes in the tree.
Next N-1 lines denotes the parent node of nodes 2 to N. (1 is the root node it has no parent.)
Next line contains M (Number of queries.)
In each of the next M lines first integer is T which means the type of the query. If T is 1, it is followed by three integers U, X, K as explained in the question. If T is 2, it is followed by a single integer U.
Output
For each query of type 2, output a single line containing the required answer.
Constraints
1 ≤ N ≤ 100000
1 ≤ M ≤ 100000
1 ≤ X, K ≤1000000000
Sample
Input
7
1
1
2
2
3
3
5
1 1 1 2
2 1
2 3
1 3 2 1
2 3
Output
27
13
21 | 33,619 |
Terrorist Attack (INS14M)
In his final interview Digo is given a map of a city containing N junctions connected by roads of length 1.
There is only one path between any two junctions. Each junction has a unique index between 1 and N (inclusive).
There are M civilians in the city. Everyday, each civilian visits a set of junctions.
There are military camps built at certain junctions.
The terrorists are planning to attack the city by targeting some junctions.
However due to the presence of military camps,
there is a limit to the size of explosion they can make at any particular junction.
The intensity of the bomb planted at a junction is equal to the minimum distance from
any military camp to the targeted junction.
The damage of all civilians passing through a targeted junction increases by
the intensity of the bomb dropped at the junction.
The military camps set up and the terrorist targets are given in the form of the following queries:
1 J : Meaning that a new military camp is set up at junction J
2 J : Meaning that the junction J is targeted by terrorists
3 J : Print the total damage done till now to all civilians visiting junction J
Initially there is exactly one military camp at junction 1.
The initial damage of all civilians is given to you.
Input
First line contains 3 integers N, M, Q. N is the number of junctions, M is the number of civilians and Q is the number of queries to follow.
Next N-1 lines contains 2 integers U and V (denoting that there is a road connecting U and V).
Next M lines contains one integer each. The ith line contains integer a[i] representing the initial damage of the ith civilian. Next M lines contain the description of the junctions visited by the ith civilian (First integer of every line is X, the number of junctions visited by the ith civilian, followed by X integers representing the respective junctions).
Next Q lines give the corresponding queries. Each query can be described by two integers T, J, where T is the type of query (which can be 1 or 2 or 3) and J is the respective junction of the query.
Output
For all the queries of type 3 print an integer answering the query.
Constraints
1 <= N <= 50000
1 <= M <= 10000
1 <= Q <= 50000
1 <= X, V, U, J <= N
1 <= a[i] <= 1000
Sum of all the junctions crossed by all the civilians is less than 50001
Note: The Final answer will fit in 64 bit signed integer.
Example
Sample Input:
3 1 3
1 2
2 3
5
2 2 3
3 3
2 3
3 3
Sample Output:
5
7 | 33,620 |
Khairy and Gold Alloys (WAL3A)
We all know "Connect 4 Game", One day Khairy has a grid with infinite height and n numbers representing the number of discs in the ith column.
It's guaranteed that no empty cells between any discs in the same column.
for each disc in the grid if Khairy saw a disc on its left OR its right, he'll say "Wal3a".
Given the N numbers, What's the maximum number that Khairy will say "Wal3a"!
Khairy is a small guy who likes gold very much, but he has a problem in his eyes and the word "WAL3A" (WAL3A in Arabic means "Firing"), whenever he likes something very much sooner or later it is destroyed by any means (Please don't impress him with something you want :|)
One day Khairy visited the National Museum and saw a Grid with infinite height and N columns and each column
i
contains X
i
Gold Alloys. No empty cells between Alloys in the same column.
Unfortunately all Gold Alloys that impress Khairy in the 1st row are destroyed and disappeared :S, consequently the Alloys of the same columns above the destroyed Alloys fall to the the cell which is directly below it (each affected column height is decreased by 1 unit). Khairy continues saying "WAL3A" till he finds the first row not impressing anymore.
The example below Khairy would say "WAL3A" twice and 7 gold alloys are destroyed.
Of course the museum lost a fortune during Khairy's visit, so could you help the government find how many Gold Alloys are destroyed by Khairy.
Input
The first line of input contains an integer
T
(1 <= 20 <=
T
) followed by
T
test cases.
Each test case contains a positive integer
N
[1 <=
N
<= 10
5
] followed by
N
integers [0 <=
X
i
<= 10
9
] separated by spaces (see sample input for more clarification).
Output
For each test case output one line contains how many Gold Alloys are destroyed by Khairy.
Example
Input:
2
5
1 2 2 1 5
3
7 7 7
Output:
7
21 | 33,621 |
Super Mario Revisited (SMARIO)
Mario is one the most famous video games ever. In this problem, we will be helping Mario save the princess (again :P). In this game of Mario,
each world will be represented by a 2-D rectangular grid
. There are
multiple worlds
and all the worlds are of size R x C. The world contains many objects each covering exactly one cell.
The cell with 'S' denotes Mario's starting position. A cell with '.' denotes an empty cell over which Mario can walk safely. From that cell he can move to any of its 4 adjacent cells (which share an edge with it). A cell with 'D' denotes a pipe that leads to the world below. A cell with 'U' denotes a pipe that leads to the world above. If Mario enters a cell containing a pipe, he must enter the pipe. A cell with 'C' represents a coin and Mario collects these. After collecting the coin, the cell becomes an empty cell. A cell with '#' denotes bricks and Mario can't enter this cell no matter what. A cell with 'M' denotes the monster (Bowser), Mario has to defeat Bowser to save the princess. Mario initially start from an empty cell.
Our Mario is very determined and so he will be always able to defeat Bowser on a 1 on 1 battle. But he is greedy and will always want to collect all the coins before going to save the princess.
If he is not able to collect all the coins, he won't save the princess!
. Help Mario to find the minimum number of steps to do this feat.
Note:
If 'U' is present in top-most world or 'D' is present in the bottom-most world, Mario can't enter the cell.
Input:
Input contains multiple test cases (will never exceed 1000).
First line of each test case will have 3 integers R, C and W.
'R x C' represents Grid dimension and 'W' represents number of worlds.
It will be followed by R x W lines. Each line will have 'C' characters.
First R lines describe the first world, second R lines describe the second world and so on upto W worlds.
Input ends by the line '0 0 0'.
Output:
For each test case, print a single line “Mario saved the princess in K steps” where K is the minimum number of steps if he defeat the monster else print “Mario failed to save princess”.
Constraints:
1 <= R, C <= 15
1 <= W <= 10
0 <= [Total number of coins] <= 10
All characters in the grid will be from the set {'S', '.', 'M', 'C', 'D', 'U', '#'}
Sample
Input:
2 2 1
SM
.D
2 2 2
SM
.D
C.
UC
3 3 2
S.M
C#.
D..
###
C.C
C.U
2 2 1
SM
#C
0 0 0
Output:
Mario saved the princess in 1 steps
Mario saved the princess in 7 steps
Mario saved the princess in 8 steps
Mario failed to save princess
Explanation for third test case:
Mario is in (0, 0, 1) (first world), the optimal path is (0, 0, 1) → (1, 0, 1) → (2, 0, 1) → (2, 0, 2) → (1, 0, 2) → (1, 1, 2) → (1, 2, 2) → (2, 2, 2) → (2, 2, 1) → (1, 2, 1) → (1, 2, 0). So totally 10 steps which includes 1 Up and 1 Down. As there is no manpower required for Mario to take step in between the worlds omitting the 2 steps which gives us the answer 8. | 33,622 |
Lights, Snakes and Cages (CAGES)
In the zoo there are N cages in which we keep N snakes: each snake in its cage. For experimental reasons, in a month we will move each snake to a different cage: this reordering is given in the input.
Each cage is illuminated by special light, which may be of type A, type B or type C. Your task is to assign the lights A, B, C to the cages so that:
each snake will change its lighting, i.e. it will be moved to the cage illuminated differently from the cage it currently inhabits;
lightings are equally distributed, i.e. the number of cages A, the number of cages B and the number of cages C differ by at most one.
Input
The first line contains an integer N (2 ≤ N ≤ 300 000), the number of snakes and cages. Cages are numbered from 1 to N.
Each of the next N lines contains an integer. When K-th of these lines contains the number L, it means that the snake from the cage K will be moved to the cage L (K ≠ L). Two snakes will not move to the same cage.
Output
Print the string composed of the characters A, B and C, such that the K-th character denotes the lighting of the cage K. If there are multiple solutions, print any.
Example
Input:
4
4
3
2
1
Output:
ACBC | 33,623 |
SIR CHIRAG AND MAGIC NUMBERS (SIRNUMS)
Sir Chirag is famous for his 'Intelligencia". He found that
Dukkar
and
Chapta
were unable to solve a question.
The magic Numbers are described as: The numbers are strictly positive, don't contain any leading zeroes. It has exactly 'p' digits and if we move the last digit of the number to the beginning, it grows exactly 'x' times.
Chirag Sir took the task to solve it. It took him minutes to solve. Now its your turn.
You have to find the minimum possible number that satisfies the above conditions given 'p' and 'x'.
Input
First line contains the number of test cases T: 0 < T <= 50
Next T lines contains two integers
p
and
x
, 0 < p <= 1000000 and 0 < x < 10.
Output
If such a number is not possible then print "Impossible" (Without the quotes). Else print the number.
Example
Input:
3
6 5
1 2
6 4
Output:
142857
Impossible
102564
(observe that for the first test case : 142857 x 5 = 714285) | 33,624 |
Operators (BLOPER)
Given a set of N integer A = {1, 2, 3, …, N} and a integer S,
your task is find a way to insert an operator ‘+’ or ‘-‘ to every neighbor pair of A,
that the result of the expression after insert equal to S.
Input
A single line, N and S (1 ≤ N ≤ 500, |S| ≤ 125250)
Output
If there are way(s) to insert, outputs any of them, otherwise outputs “Impossible” (without quotes).
Example
Input:
9 5
Output:
1-2+3-4+5-6+7-8+9
Input:
5 6
Output:
Impossible | 33,625 |
Peculiar Permutivores (BFPRMCYC)
On the gentle plains of Bytelandia, the mysterious ruffalo wander in herds solving combinatorics problems and searching for their next meals. Finding suitable food is becoming more and more difficult, as over the years the ruffalo have developed a curious diet consisting solely of permutations. To make matters worse, roughly half of all existing ruffalo lack the enzyme that would allow their stomachs to decompose permutations into cycles, and the other half are allergic to explicitly written fixed points.
The two great ruffalo leaders, Wildthings and Nowyouseemee, have joined forces to build a device that can automatically transform permutations into a notation that everyone can digest and enjoy (but not necessarily in that order). The bright young programmer Zodiac was assigned the task of building the device, but in a tragic freak accident he swallowed a fixed point and died shortly thereafter. Zodiac's assistants found a single sheet of paper lying next to his body on the laboratory floor with just eight symbols written on it: "+-<>[],.". Out of respect for Zodiac's dying wish, the Ruffalo High Council passed a decree that the device must be built entirely in branf**k, no matter what the cost. Nowyouseemee has personally offered an unprecedented reward of 54 Gifts of Heaven to anyone who can successfully complete the task. While nobody has ever seen a Gift of Heaven, it is said that they come in magical bright green boxes that become a little faded after a day, and a little more faded after a week.
Note:
You can use any programming language you want, as long as it is brainf**k. If you would like to submit in other languages, please see the
tutorial
version.
Input
The first line contains an integer
T
(1 ≤
T
≤ 5000). Then follow 2
T
lines, representing
T
test cases. The first line of each test case contains an integer
N
(1 ≤
N
≤ 9), and the second line contains a permutation of [1..
N
] as a space-separated list of
N
integers. Every line ends with a single newline character (ASCII 10), including the last line.
Output
T
lines containing the disjoint cycle decomposition of the corresponding permutation. For the identity permutation, print "e" without quotes. If there is more than one correct answer, print any of them.
Example
Input:
5
3
1 2 3
3
2 1 3
4
2 1 4 3
9
3 8 9 4 1 7 6 2 5
9
3 8 9 4 1 7 6 2 5
Output:
e
(1 2)
(1 2)(3 4)
(1 3 9 5)(2 8)(6 7)
(2 8)(9 5 1 3)(7 6)
Additional Info
There are two randomly generated data sets, one with
T
=5000 and the other with
T
=500. The average value of
N
in each data set is approximately 6.36.
The custom judge reports your source code length in parentheses after the judge result (when available at the time of judge termination). Only valid BF commands are counted. Also, if you don't get AC, you will be told on which data set you first failed (0-indexed). Thanks to
(Tjandra Satria Gunawan)(曾毅昆)
and
Bin Jin
, who wrote judges using the same or similar ideas. The master judge C++ source code is available
here
, and assumes that the test case judge reports source length as score.
For assessing the correctness of program output, the custom judge works just the same as the standard "Ignores extra whitespaces" judge, except that it allows any valid cycle decomposition. In case you don't understand how the standard judge works, this means that e.g. "( 1 2)" and "(1 2) (3 4)" would be judged as wrong for the second and third example cases respectively, but printing ten spaces instead of the single space in "(1 2)" is perfectly fine.
My solution at the time of publication has 334 bytes (golfed) and runs in 0.47s with 1.6M memory footprint.
Update: Reduced source to
292
as of 2014-04-30. | 33,626 |
Sword Game (WPC5C)
It is 2048, and a Martian robot called SSH3 wants to win galactical wars, as he does every year.
He has been chosen to participate in the prestigious Sword Game, possibly the last one to ever happen. This is the format of the Sword Game.
Every sword has a name S which is a string of n characters from a-z. The strength of the sword is decided in the following way.
Define a function f(l1, l2) for every 1 ≤ l1, l2 ≤ n. Find all the substrings of the sword name S with length l1. Then, ind1 is the index such that it is the lexicographically smallest among these l1 length substrings. (If there are multiple such substrings, then we consider the
lower
index).
Similarly, ind2 is defined. Then, f(l1, l2) = |ind1 - ind2|. (All indices are 0-based)
Strength(S) = (Expected Value (f)), over all l1, l2.
As a Martian, SSH3 is also expected to be very good at Maths. He is asked to find out the strength of the sword. But as all other Martians, he has come from the city of Quoda, where everybody is pathetic at Maths. Hence, he asks you to help him. Output the value of n
2
* Strength(S).
Input
First line contains the integer n.
Second line contains the name of the sword S.
Output
A single line containing an
Integer
, that is the value of n
2
* Strength(S).
Constraints
1 ≤ n ≤ 100000
S contains exactly n characters from ‘a’ to ‘z’.
Examples
Input:
2
ab
Output:
0
Explanation
f(l1, l2) can take one of the following 4 values:
f(1, 1) = 0 (ind1 = 0, ind2 = 0)
f(1, 2) = 0 (ind1 = 0, ind2 = 0)
f(2, 1) = 0 (ind1 = 0, ind2 = 0)
f(2, 2) = 0 (ind1 = 0, ind2 = 0)
E(f(l1, l2)) = 0
2
2
* E(f(l1, l2)) = 0 | 33,627 |
Parade (WPC5F)
It is the Annual Parade of the Galactical Wars. Great men and women from around the cosmos have come to view this spectacular event. To make this a special occasion, the leaders in galaxy H2 have decided to arrange his participants in a particularly beautiful order.
Firstly, they have chosen n particularly suited participants. These n participants have distinct heights ranging from 1 to n. They have arranged them in some way, so that the height of the ith student is H(i).
The sworn enemies of H2, galaxy H3 have obtained some secret information on this arrangement. They know that there is a set of elements A (containing total k indices), such that H(j) < H(j-1)
IF AND ONLY IF
j belongs to A. As a Martian on H3, your organizer asks you to find the number of such possible configurations that H2 could have made.
Input
A single line containing space separated integers: n and k.
Next line containing k indices as explained in the problem.
Output
A single line containing the number of ways to arrange participants modulo
1000000009
(10 ^ 9 + 9)
h3>Constraints
1 <= n <= 700
0 <= k <= n-1
2 <= i <= n (i is an index)
All i’s are unique.
Examples
Input:
3 1
2
Output:
2
Explanation
There are 2 possible ways to arrange the participants, where their heights are: 2 1 3 or 3 1 2
Note 3 2 1 is
not
a valid ordering since h(3) < h(2). | 33,628 |
Structures (WPC5A)
In the Galactical Wars happens the great event of designing a structure to honour the current generation of participants. (It is another matter that inevitably the monument is destroyed at the end of the Galactical Wars).
The organizers this year do not believe that this is a good event, and have reduced the event to building a right structure: a
right-angled
triangle that represents the geometry of the universe. Further they have given a specific
odd integer
n, which they want one of the
shorter
sides of the triangle to be.
The organizers in the galaxy H2 are infuriated with this high-handedness. To demonstrate their prowess in this event, they have decided to build all possible right structures. Calculate how many different right structures they can possibly build.
Input
First line contains a single integer T, denoting the number of test cases.
T lines follow, each containing an odd integer ’n’ denoting the given size of a side.
Output
T lines, each containing a single integer denoting the number of ways to form a right angled triangle with one of the smaller sides as ’n’.
Constraints
1 ≤ T ≤ 10
1 ≤ n ≤ 10
12
n is odd.
Example
Input:
1
3
Output:
1
Explanation
There exists only 1 right angled triangle with sides 3, 4, 5. | 33,629 |
Complicated Calculations (WPC5D)
There are k galaxies that participate in the Galactical Wars, which have happened for the past n years. Each year there has been a victor. Further, a particular galaxy G has won the Wars an
even
number of times. Also, G
didn't
participate in the first year.
You are a member of the old and wise community of Daba. Even though it is the festive season of Galaxy going on, you prefer to sit in your room and do complicated (and senseless) calculations. For no reason, one day, you wonder in how many possible ways the victories in the previous years could have taken place (that is, the number of different sequences of victors possible). Output the result of this complicated (and senseless) calculation.
Input
First line contains a single integer T, denoting the number of Test Cases.
T lines follow, containing space separated integers: n and k, as described in the problem.
Output
T lines, each containing the number of ways in which victories during n years could have taken place, modulo 1000000007 (10
9
+ 7).
Constraints
1 ≤ T ≤ 150,000
1 ≤ n, k ≤ 10
9
Example
Input:
1
1 4
Output:
3
Explanation
Any Galaxy except ‘G’ could have won. There are 3 such galaxies. | 33,630 |
Galaxy distances (WPC5E)
Each galaxy 'i' in the universe is assigned a unique position in the universe given by A(i), for the ith galaxy. It is known that the distance between 2 galaxies is given as Dist (i,j) = ( |i^2 - j^2| + |A(i)^2 - A(j)^2| ).
The events are held in a host galaxy, and every other galaxy has to travel to that galaxy to participate. For this, of course, the organizers have to pay the galaxy for their transportation, lodging and daily expenses. The organizers wonder, what could be the maximum transportation expenses that they have to pay?
Help them by finding
MAX
(Dist (i,j)).
Input
First line contains a single integer T, denoting the number of Test Cases.
Each Test Case contains 2 lines. 1st line containing a single number ’n’ denoting the number of galaxies (numbered 1 to n).
2nd line contains ’n’ space separated integers signifying A(i) for 1<=i<=n.
Warning
: Fast IO may be needed in some languages.
Output
T lines, each containing an Integer, the answer to the corresponding test case.
Constraints
1 <= T <= 10
2 <= n <= 10^5
1 <= A(i) <= 10^9
Example
Input:
1
2
4 3
Output:
10
Explanation
Dist(i,j) is maximum for i=1, j=2. | 33,631 |
The dilemma of Idli (WPC5G)
It is emergency time! There has been a clash between the organizers of the Galactical Wars and the Inter-Galactic Parliament due to some feud. The entire civilization has been split into two groups A and B. The civilians in A love some particular members in the Organization Committee of the Galactical Wars, and hate some members from the Inter-Galactic Parliament. On the other hand, civilians in B love some particular members from the Inter-Galactic Parliament, and hate some in the Organization Committee.
You are Idli, the Inter-Galactic Dean, and it is your job to ensure satisfaction of the civilians. You decide to do so by impeaching some members from the Organization Committee and some from the Parliament. A civilian is satisfied if and only if all the members he loves are not impeached, and all the members he hates are impeached.
Of course, Idli wants to satisfy most number of civilians. Help Idli in devising an algorithm to do so.
Input
First line contains two space separated integers n1 and n2, denoting the number of Galactic Wars organizers (numbered 1 to n1) and the number of Members of Parliaments (MP) respectively (numbered 1 to n2).
Second line contains a single integer ’n’, denoting the number of civilians.
’n’ lines follow containing the description of the civilians in the following format:
First character contains a single character ‘A’, or ‘B’ denoting the group of the civilian.
Then there is a space.
Then some space separated integers follow ended by -1 denoting the members of same group whom he loves.
Then some space separated integers follow ended by -1 denoting the members of other group which he hates.
Output
A single integer denoting the maximum number of civilians Idli can satisfy.
Constraints
1 <= n1 <= 1000000
1 <= n2 <= 1000000
1 <= n <= 500
0 <= number of organizers/MPs a person loves <= 50
0 <= number of organizers/MPs a person hates <= 50
Example
Input
5 5
3
A 1 -1 5 3 -1
B 2 3 -1 2 5 -1
B -1 -1
Output
2
Explanation
The third person doesn’t love or hate anyone, and thus is always satisfied. Only 1 out of the first 2 civilians can be satisfied. Hence Idli can satisfy at max 2 civilians. | 33,632 |
Nymphs from H10 (WPC5H)
A far away galaxy, H10 has newly been discovered and incorporated into the Commonwealth which participates in the Galactic Wars. The other galaxies have always bullied it by winning the Galactic Wars every year. Frustrated, H10 has come up with a novel strategy to distract the other galaxies. They are planning to send beautiful nymphs into the lands of the other galaxies.
The cosmos is arranged so that there is a unique path between any two galaxies (possibly going through other galaxies). The leaders in H10 will select two different galaxies A and B, and send K nymphs to each of the galaxies that is on the unique path from A to B. Initially there are no nymphs on any galaxy.
You are the Chief Executive Officer of this project. The leaders will ask you to send these groups of nymphs by giving various instructions of the form (A, B, K). In the process, they may also ask you how many nymphs are currently there in particular galaxies, so that they are able to take smart decisions in the future. Implement this. (See exact format in Input/Output Specifications)
Input
The first line contains t, the number of test cases.
T test cases follow. Each contains:
A line containing n, the number of galaxies (numbered from 0 to n-1).
n-1 lines describing the connections between 2 galaxies as 2 space separated integers a, b (both from 0 to n-1), denoting a direct connection between galaxy a, and galaxy b.
The next line contains a single integer Q denoting the number of queries.
Next Q lines contain queries in the form of 3 space separated integers a, b and k.
Output
For each query if k ≥ 0, don't output anything, just send the nymphs to every galaxy on the way.
In a query if k = -1, then output 2 space separated integers in a new line denoting the number of nymphs in galaxy a, and galaxy b respectively.
Constraints
1 ≤ T ≤ 10
2 ≤ n ≤ 50,000
The galaxies are connected in such a way that there is a unique path from each galaxy to every other galaxy.
2 ≤ Q ≤ 50,000
0 ≤ a, b ≤ n-1
a and b are different.
-1 ≤ k ≤ 100
Example
Input:
1
3
0 1
1 2
2
1 2 2
0 2 -1
Output:
0 2
Explanation
The path from 1 to 2 is 1 → 2. 2 nymphs are thus sent to galaxies 1 and 2. There were 0 nymphs at galaxy 0 initially. | 33,633 |
Operators (new ver) (BLOPER2)
Given a sequence a1, a2 ... an and a integer S, your task is find a way to insert an operator ‘
+
’ , ‘
-
‘, ‘
.
‘, ‘
~
‘
to every neighbor pair of A, that the result of the expression after insert equal to S.
Note that :
a . b = a + 2 * b
a ~ b = a - 2 * b
Input
First line : N and S (2 ≤ N ≤ 22, |S| ≤ 5 * 10
16
)
Second line : N integers, a1, a2 ... an (|ai| ≤ 10
15
)
Output
If there are way(s) to insert, output any of them, otherwise output “Impossible” (without quotes).
Example
Input:
9 5
1 2 3 4 5 6 7 8 9
Output:
-~~~++++
Input:
3 -1
-2 5 7
Output:
Impossible
Details:
In first test case : 1 - 2 - 2 * 3 - 2 * 4 - 2 * 5 + 6 + 7 + 8 + 9 = 5
You may want to try another version
here
. | 33,634 |
LCM (WPC5I)
Given n, and m, find the smallest k such that:
n divides lcm(m, k);
m divides lcm(n, k).
Even if there are no Galactic Wars, you are still a Martian. Just do it.
Input
First line contains a single integer T, denoting the number of Test Cases.
T lines containing space separated integers: m and n.
Output
Output T lines each containing the smallest k that satisfies the problem.
Constraints
1 ≤ T ≤ 2000
1 ≤ m, n < 2
31
Example
Input:
1
3 4
Output:
12 | 33,635 |
Draw Skyline Graph (SKYLINE2)
Once my friend Deepan Gupta went a shop to buy a laptop with features he needed. Seller showed him a lot of laptops having various distinct features like cost, speed, memory, color, design, brand etc. But he was worrying only about memory and speed as he only needed these two. Because of so many laptops he got confused. He was not able to select a laptop. So he decided to select a skyline set in terms of {memory, speed} which will make it easier for him to decide. Objects are said to be in skyline set such that no one object in set dominates other object of set and all the objects which are not in the set are dominated by at least one object in the set. No Object in the set is dominated by any other object (both set and not in set). One Object dominate other object if all the features of first objects are greater than or equal to second object's corresponding features, but there exists at least a feature that is strictly greater than second object's corresponding feature. No one object dominate other object it means object does not satisfy the dominance condition, So Skyline Set can have two different objects with both same features.
For example:
Laptop1 : memory : 100GB, Processor Speed : 700GHz
Laptop2 : memory : 200GB, Processor Speed : 500GHz
Laptop3 : memory : 50GB, Processor Speed : 100GHz
Laptop4 : memory : 200GB, Processor Speed : 500GHz
{Laptop1, Laptop2, Laptop4} are in skyline set while Laptop3 is not. (If still not understood 'SKYLINE', refer to this
link
.)
Given N number of laptops with {M[i], S[i]}. Your task is to select a skyline set and print {M[i], S[i]} in newline of all the objects in set with decreasing order of M[i] value. If two objects have same M[i] value, then you can print them in any order. For exact output format, refer to given examples.
Constraints
1 ≤ T ≤ 50, 1 ≤ N ≤ 10
5
, 1 ≤ M[i], S[i] ≤ 10
9
.
Input
First line contains t, number of test cases. For each test case, first line contains N, number of laptops. After that each of next N lines contains {M[i],S[i]} data for ith laptop, M[i] is memory and S[i] is speed of processor of ith Laptop.
Output
For each test case first line contains K, number of Skyline objects in set, then each of next K lines contains {M[i], S[i]} data for ith laptop in decreasing order of M[i].
Example
Input:
2
3
100 700
200 500
50 100
4
200 500
100 1000
50 900
1000 50
Output:
2
200 500
100 700
3
1000 50
200 500
100 1000
HINT: Just follow the statement very carefully. Observe the examples. | 33,636 |
Group Viva (GRUPVIVA)
Today is external viva of computer science subject and Bosky is not at all prepared for it. Adding to his problems, he hasn't reached college yet. Luckily the external examiner was late too. Bosky somehow managed to reach the college before the external examiner arrived but he was still worried because he didn't want to get insulted by external examiner.
The procedure for the conducting of viva is that each student has to sign the attendance register regardless of their given roll number before entering the viva room. Then they will be called individually or in groups of equal students exactly in the same order as they signed in the attendance register. It should be ensured by the internal invigilator that signing in the attendance register by the students has to be done before the external examiner arrives. The viva exam will start immediately only after the arrival of the external examiner. Students were informed that external examiner will arrive exactly after 30 mins. Bosky got some extra time to think how he can save himself from being insulted in front of the external examiner. He looked around and found that there were few students who were in worse condition than he himself was. With his past experience he concluded that on being called in groups the external picks up the most vulnerable student among the group and keeps on insulting and cursing the same student, ignoring the rest. Bosky knew that if he could manage to be in group with a student who is more vulnerable than him then he might get ignored by the external.
When everybody started signing the attendance register, Bosky quickly looked around and spotted such a student and signed after him in the attendance register. He is quite certain now that if he has to give viva in a group in which both of them are present he might save himself from being insulted.
There are "
N
" students in his class and Bosky knows that external examiner will call everyone in group of "
X
" students at once, where
X
can be any number between
[1, N]
(both ends inclusive). Now he wonders what is the probability that he and his "prey" would be in the same group.
Given total number of students and Bosky's position in the attendance register, your task is to tell what is the probability that Bosky's plan will succeed i.e. he and his [so called] "prey" will be in same group.
More formally you are given two integers N and R, where 2 ≤ N ≤ 10
9
and 2 ≤ R ≤ N. You have to find the probability that R *and (R-1) will be in the same group if the sequence [1, 2, 3...N] is divided into group of "X" numbers sequentially i.e. [1...N] is divided into groups [1...X], [(X+1)...2*X], [(2*X+1)...3*X]...[ (X*floor((N-1)/X)+1)...N], where 1 ≤ X ≤ N and last group can have less than X numbers.
Input
Input will contain a number
T
denoting the number of test cases.
Then
T
test cases follow, each one consisting 2 integers
N
and
R
where
N
is the total strength of the class and
R
is Bosky's position in the attendance register.
Output
For each test case, output the probability as rational number of form p/q. The greatest common divisor of p and q should be 1.
Constraints
1 ≤
T
≤ 500
1 <
N
≤ 10
9
1 <
R
≤
N
Example
Input:
2
5 5
6 5
Output
2/5
1/2
Explanation
Case 1
: N=5 and R=5
i.e. Total Students=5 and Bosky's has signed at 5th position. His prey signed before him hence he signed at 4th position. Suppose students are called in group of "X", where 1 ≤ X ≤ N. For different values of "X", groups formed are as follow
For, X=1
[ {1}, {2}, {3}, {4}, {5} ]
X=2
[ {1, 2}, {3, 4}, {5} ]
X=3
[ {1, 2, 3}, {4, 5} ]
X=4
[ {1, 2, 3, 4}, {5} ]
X=5
[ {1, 2, 3, 4, 5} ]
We can clearly see that for X=3 and X=5 Bosky's plan will succeed i.e. he and his prey will be in same group. Hence the output is "2/5"
Case 2
: Similar to Case 1 where N=6 and R=5
For, X=1
[ {1}, {2}, {3}, {4}, {5}, {6} ]
X=2
[ {1, 2}, {3, 4}, {5, 6} ]
X=3
[ {1, 2, 3}, {4, 5, 6} ]
X=4
[ {1, 2, 3, 4}, {5, 6} ]
X=5
[ {1, 2, 3, 4, 5}, {6} ]
X=6
[ {1, 2, 3, 4, 5, 6} ]
Here Bosky's plan succeeds for X=3, X=5 and X=6, hence the output is "3/6" → "1/2" [Note: Output must be irreducible rational number] | 33,637 |
Khaolin Temple (KHAOTMPL)
NOTE: You can skip to
BRIEF
if you do not want to read complete storyline.
Khaolin Temple
is world's most famous algorithmic pilgrimage situated on Mount Kong in China. It is believed that human civilization has never seen better coders than
Khaolin Coders
and its well known about them that that they were so good at problem solving that they could even solve
"NP-Complete"
problems in
constant amortized time
. There are many folktales about Khaolin Coders, the most famous ones being about
Monk Bosky
who was incomparably the best
Khaolin Coder
. Following is a famous incident from
Monk Bosky's
early days at Khaolin Temple.
During his early days at Khaolin Temple Bosky was the brightest and most notorious pupil at Khaolin. Once his master asked all his pupils to water the
khaolin flowers
[khaolin flowers are special flower which grow 1 meter tall on pouring 1 litre water to them]. Master wanted to keep everyone busy [specially Bosky] so that he could meditate in silence. He told his pupils where the flowers were and how tall they were at present and asked them to come back only when they are finished watering all the flowers assigned to them. He also told them that only those pupils will be allowed to enter the temple who will tell the correct heights of flowers after the watering process is complete.
Master knew that his pupils will cheat and calculate the height that will be achieved by flowers after pouring water to them if he asks them to water them one by one, hence he decided to make it difficult for them to calculate the height by asking them to follow certain rules while watering flowers.
He asked them to follow the following rules while watering flowers:
Rule 1
: Every pupil will water all flowers assigned to him as an array of
n
Khaolin flowers with heights [H1, H2 ... Hn].
Rule 2
: When a pupil will be standing next to Kth flower he will have to go back to (K-1)th flower and inspect its height, if it is greater or equal to height of Kth flower he will have to note its index down, then he will have to go further back to (K-2)th flower and if its height is greater or equal to Kth flower he will again have to note down its index. And he must continue to do so till he reaches flower 1. After reaching flower 1 he has a list of indices of flowers with height>= Hk [i.e. height of Kth flower].Now he will have to bring sufficient water from river nearby and pour 1 litre water to each flower whose index he has noted down
[NOTE: By pouring 1 litre water to the flowers he will be making them 1 meter taller]
.
Rule 3
: Pupil can move to Kth flower only if he has applied
Rule 2
standing next to (K-1)th flower. If (K+1)th flower exists he must continue to apply
Rule 2
to (K+1)th flower after he has applied
Rule 2
standing next to Kth flower.
Rule 4
: Pupil must start watering process standing next to 1st flower.
Master knew that if his pupils sincerely followed these rules while watering flowers they won't be able to water all flowers before a month's time span and in the meantime he could meditate in silence without being disturbed by anyone. Since this task was very boring, Master decided to reward the pupil who enters back into temple first, obviously by telling heights of all flowers correctly after the process of watering the plants was complete. As a reward Master will teach him secret algorithmic skills till the next pupil enters the temple and as soon as the next pupil enters the temple Master will stop teaching the first pupil. With that said, Master sent all his pupils to water
Khaolin flowers
and expected that no pupil will return before a month and also expected that he will have to teach secret algorithms as a reward only for few hours because if they follow same process they will complete the task in nearly equal time.
But to Master's utter surprise he heard a pupil on the gate of Khaolin Temple claiming that he has watered all the flowers in an hour and that pupil was Bosky who further astonished Master by reporting the correct heights of the flowers as expected by Master. Master refused to reward him as Bosky clearly cheated and did not follow his rules. But after Bosky explained Master the process he followed to water flowers which produced same height of flowers as Master expected, Master was so impressed that he taught him everything he knew for the next month and also declared him to be heir to his position in the Khaolin.
No one in today's world knows the algorithm
Great Monk Bosky
used to solve the problem given by his master but today we have at least been able to reconstruct such cases and time limits which can only be passed by using algorithm which is equivalent to
Monk Bosky
's algorithm or more efficient than it.
You are thereby challenged to match
Monk Bosky
's efficiency and mightiness by telling the heights of flowers after watering them as stated in the question.
Brief
An array A of
N
integers is given [a1, a2 ... an].
Step 1: Starting from
A[1]
, for every
A[i]
1<=i<=n create an array
B
of size
m
which contains integers [b1, b2 ... bm] where
B[j]
< i for all 1<=j<=m and each
A[B[j]]
>=
A[i]
.
Step 2: Increment
B[j]
th element in
A
with 1 i.e. do
A[B[j]]=A[B[j]]+1
, where 1<=j<=m.
Step 3: If
i < N
, do i=i+1 and go to
Step 1
else print array A
Your task is to print the transformed array
A
after above steps are implemented to it.
Input
First line will contain and integer
N
, where
N
represents the number of flowers. Next line will contain
N
space separated integers
H1 H2 H3 ... HN
representing heights of flowers in sequential order.
Output
Print
N
space separated integers that represent heights of flowers after all flowers have been watered.
Constrains
1 <= N <= 10^5
1 <= Hi <= 10^9
Sample
Input:
5
7 5 2 1 8
Output:
11 7 3 1 8 | 33,638 |
Machau vs Maggu (MACVSMAG)
You will find three types of people in an engineering college
Maggu
,
Machau
and
Others
. We all know how much hard Maggu people try to portray themselves as Machau but they never succeed. Today Machau people have decided to recruit few Maggus and convert them to Machau. All the Maggus who wanted to become Machau had to reach Machau Club situated at "YAY MACHAU" from their current
location A
. Machau people had laid many books everywhere on the campus to distract Maggus and make it difficult for them to reach Machau club. The campus can be imagined as a large
N x N grid
in which Maggu is located at position
A
which is denoted by
(Ax, Ay)
coordinate and the Machau Club is located at position
B
which is denoted by
(Bx, By)
coordinate. Machau people had laid books at
M
random locations denoted by
(Xi, Yi)
where
1<=i<=M
. Additionally to prevent Maggus who take up the challenge to runaway Machau people laid books
everywhere outside the rectangular area where Maggu's location A and Machau Club's location B are are ends of the diagonal of that rectangular area
. A Maggu can only walk in
left, right, up or down
directions from his current place as long as he doesn't leave the campus i.e. he stays inside the
N x N
grid. If a Maggu wants to become Machau he must reach Machau Club without touching a single book in his path and without leaving the campus grid.
More formally stating the problem: Given an
N x N
grid with
M
non-reachable cells. Test whether cell
"B"
can be reached from cell
"A"
provided only left, right, up and down movements are valid.
You must print "YAY MACHAU" if it is possible for a Maggu to reach Machau Club else print "MAGGU FOREVER"
Input
First line will contain 6 integers
N
,
M
,
Ax
,
Ay
,
Bx
and
By
Where
N
=Number of rows and columns in campus grid,
M
=Total number of books laid on the campus,
Ax, Ay
=Coordinates of Maggu,
Bx, By
=Coordinates of Machau Club.
Next
M
lines will contain
Xi
and
Yi
denoting coordinates on
N x N
grid which contain books to distract MAGGUS
NOTE: If any book is placed in position A or B MAGGU will always be distracted. All
(Xi, Yi)
pairs are not guaranteed to be distinct.
Output
Print "
YAY MACHAU
" if Maggu can reach Machau club otherwise print "
MAGGU FOREVER
" [without quotes]
Constraints
1<=
N
<=10^9
1<=
M
<=10^5
1<=
Ax, Ay, Bx, By, Xi, Yi
<=
N
Sample
Input
1000 2 10 1000 1000 10
1 1
100 100
Output
YAY MACHAU | 33,639 |
St Bernard and Gravity (BGRAVITY)
St. Bernard's
new game is played on an R×C board. Initially every square is either empty or blocked by a wall. Bernard throws a rock into the board by putting it in the top-most row of a column and then letting gravity do the rest.
Gravity works as follows:
If the square under the rock is a wall or if the rock is in the bottom row of a column, then the rock remains there.
If the square under the rock is empty, then the rock moves to that square.
If the square under the rock contains another rock, then the falling rock may slide sideways:
If the squares left and left-down of the rock are empty, then the rock slides one square left.
If the rock doesn't slide left and the squares to the right and right-down are empty, then the rock slides one square right.
Otherwise, the rock remains there and never moves again.
Bernard will never throw another rock while the previous rock hasn't settled down.
Write a program that draws the board after Bernard throws all his rocks into the board, if we know the columns that Bernard threw his rocks into, in order.
Note:
Bernard will never throw a rock into column in which the top row isn't empty.
Input
The first line contains integers R and C (1 <= R <= 30000, 1 <= C <= 30), the size of the board.
Each of the following R lines contains C characters, the initial layout of the board. A '.' represents an empty field, while the uppercase letter 'X' is a square blocked by a wall.
The next line contains an integer N (1 <= N <= 100000), the number of rocks Bernard throws.
Each of the following N lines contains an integer between 1 and C, the column into which Bernard throws a rock (the left-most column is column 1).
Output
Output R lines, each containing C characters, the final layout of the board. Rocks should be presented with an uppercase letter 'O'.
Sample
Input:
5 4
....
....
X...
....
....
4
1
1
1
1
Output:
....
O...
X...
....
OOO.
Input:
7 6
......
......
...XX.
......
......
.XX...
......
6
1
4
4
6
4
4
Output:
......
...O..
...XX.
......
.OO...
.XX...
O..O.O
In the first example, all rocks are thrown in the first column. The first rock stops on the wall. The second rock falls on the first, slides right and stops at the bottom of the second column. The third rock falls on the first then on the second rock, slides left and rests at the bottom of the first column. The fourth rock falls on the first then on the second, then slides right. | 33,640 |
Stock (STK)
Alex heard a lot about investing in the stock market and now wants to do it to earn some profit. Being a new investor he is scared of the risks in the stock market, so he decides that at any instance he will not have more than one stock with him. It is also decided that on a particular day he can either buy or sell at most one stock (only one transaction allowed). Now given the prices of one particular stock over the period of n days Alex decides he will make at most k buys and k sells.
Write a code to help Alex to maximize his profit.
Input
First line contains an integer T (<=100), number of test cases.
Each test case will have n (<=3000) and k (1<=k<=n/2), is the number of days and the maximum buys/sells allowed respectively.
(Value of the prices are in range of unsigned 32-bit integer.)
Next line will have n space separated integers denoting the price of stock over n days.
Output
For each test case output one line stating the maximum profit.
Example
Input:
3
10 3
2 7 3 9 8 7 9 7 1 9
10 1
2 7 3 9 8 7 9 7 1 3
10 2
2 7 3 9 8 7 9 7 1 9
Output:
19
7
15
Explanation
1st test case, Alex would buy on 1st day and sell it on the 2nd day, and then buy another on the 3rd day and sell it on the 4th, finally buys on 9th day and sells on the 10th day. So profit = (7-2)+(9-3)+(9-1) = 19.
2nd test case Alex would buy on 1st day and sell it on the 4th(or 7th) day. So profit = 9-2 = 7.
2nd test case Alex would buy on 1st day and sell it on the 4th day, and then buy another on the 9th day and sell it on the 10th day. So profit = (9-2)+(9-1) = 15. | 33,641 |
Fibonacci extraction Sum (FIBOSUM2)
Some people may found
FIBOSUM
a too easy problem.
We propose here a useful variation.
Fib is the Fibonacci sequence:
For any positive integer i: if i<2 Fib(i) = i, else Fib(i) = Fib(i-1) + Fib(i-2)
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
tree integers
c
,
k
,
N
.
Output
Print
Sum(Fib(
ki+c
) for
i
in [1..
N
])
.
As the answer could not fit in a 64-bit container, just output your answer modulo 1000000007.
Example
Input:
1
3 5 2
Output:
254
Explanations
Index-1 Fib sequence : 1, 1, 2, 3, 5, 8, 13,
21
, 34, 55, 89, 144,
233
, 377, 610, 987, ...
We want the 5*1+3 = 8
th
and 5*2+3 = 13
th
ones, thus the answer is 21 + 233 = 254.
Constraints
0 < T <= 60606
0 <= c < k <= 2^15
0 < N <= 10^18
The numbers
c,k,N
are uniform randomly chosen in their range.
For your information, constraints allow 1.3kB of Python3 code to get AC in 6.66s, it could be hard.
A fast C-code can get AC under 0.15s.
Warning:
Here is Pyramid cluster, you can try the
tutorial edition
(clone with Cube cluster).
Have fun ;-)
Edit(2017-02-11) : With compiler changes, my fast C code ends in 0.01s, my Python3 ones in 0.31s. New TL is 0.5s. | 33,642 |
Potions Class (POTIONS)
It's time for the Potions class. Harry absolutely HATES potions because he has to face mockery by the potions teacher Snape every time he has a potions class. Snape never leaves any chance of insulting him in front of everyone.
Snape is not in a good mood today, which is not good for Harry. Snape challenges Harry to answer his question. If Harry fails to answer, he will have to spend the whole week in detention!.
He gives Harry n numbers (a1, a2, a3 ... an) and q queries. Each query will consist of four integers
w, x, y, z
. The result of a query is given by the following equation:
Help Harry or else he'll miss his Quidditch match against Slytherin because of his detention!!
Input
The first line of the input contains
T
, the number of test cases.
T
test cases follow.
The first line of each test case contains
n
and
q
.
The second line of each test case contains
n
integers
(a1, a2, a3 ... an)
Each of the next
q
lines contain
w, x, y, z
.
Output
For each test case output the result as given by the equation.
The answer may be very large, so output it
modulo 10
9
+7
.
Constraints
1 ≤ T ≤ 10
1 ≤ n, q ≤ 10
5
1 ≤ x+i ≤ n (for all y ≤ i ≤ z )
0 ≤ ai ≤ 10
9
(for all 1 ≤ i ≤ n)
1 ≤ w ≤ 10
6
0 ≤ y ≤ z
Example
Input:
1
5 2
2 1 4 7 2
1 1 0 2
1 5 0 0
Output:
16
2 | 33,643 |
Pair and unpair weightest string (PAUWS)
Once I went market to buy a teddy. The shopkeeper offered a puzzle and said he'll give me whatever i wish at a huge discount if i give him the working piece of code for following problem. You will be given a string S of length N, containing either 'A' or 'B'. Make all the possible lists from the given list, with the given operation that you are allowed to change one symbol into another. Then assign maximum weight to each of the string and get the string with maximum weight and return the weight.
You have only following two ways to assign weight to symbol:
Pair a S[i] symbol with adjacent one (S[i] or S[i-1]). Each symbol can only be paired with exactly one symbol. Weight of a pair is 4. Pair will be either 'AB' or 'BA'.
Keep a S[i] Symbol independent. Weight of unpaired symbol is 1.
Each symbol is either involved in exactly one either pair or unpaired status.
For each string, keep in mind the number of symbols (K) with index i, 1 ≤ i ≤ N, which are changed from original symbol S[i].
For each of the possible lists, Add all the weight assigned as a pair and unpair, then subtract K from it. assign this final value as string weight. Add each paired weight once exactly.
The task is to maximize the weight of the string. Suppose S="ABB", possible transforms can be {"ABB", "ABA", "AAB", "AAA", "BBB", "BBA", "BAB", "BAA"} with respective weight {5, 4, 4, 1, 2, 3, 3, 2}. Maximum weight is found 5 in string 1.
Constraints
1 ≤ N ≤ 10
5
, 1 ≤ T ≤ 500.
Input
First line contains t, number of testcases. For each testcase, first line contains N, length of the string. Second line contains string itself.
Output
For each testcase, output the maximum weight of a string that can be obtained.
Example
Input:
5
3
ABB
7
ABBBAAA
8
BAAAAAAA
12
AAAAAAAAAAAA
11
ABABBBABABA
Output:
5
12
13
18
21 | 33,644 |
Can you answer these queries VIII (GSS8)
You are given sequence A[0], A[1]...A[N - 1]. (0 <= A[i] < 2^32)
You are to perform Q operations:
I pos val
, insert number
val
in sequence before element with index
pos
. (0 <= val < 2^32, if
pos
=
current_length
then you should add number to the end of the sequence)
D pos
, delete element with index
pos
from sequence.
R pos val
, replace element with idex
pos
by
val
. (0 <= val < 2^32)
Q l r k
, answer Σ A[i] * (i - l + 1)^k modulo 2^32, for l <= i <= r. (0 <= k <= 10)
Input
The first line of the input contains an integer N (1 <= N <= 100000).
The following line contains N integers, representing the starting sequence A[0]...A[N-1].
The third line contains an integer Q (0 <= Q <= 100000).
Next Q lines contains the queries in given format.
Output
For each "
Q
" operation, print an integer (one per line) as described above.
Example
Input:
4
1 2 3 5
7
Q 0 2 0
I 3 4
Q 2 4 1
D 0
Q 0 3 1
R 1 2
Q 0 1 0
Output:
6
26
40
4 | 33,645 |
Black and White beads (BWB)
Well it's now time for some serious task. There are lots of beads available and in two colours, namely white and black. There are many beads of both colours. One has to make a string of beads by joining beads with end to end. But there are some constraints, and you have to follow that constraints. While making beads, you have to make sure that there should not be K beads of black colour consecutively and also there should not be any bead string which has black bead in front, i.e. it must have white bead in front. So the task is quite simple, find all possible ways of making a string of bead of length N which satisfies the above constraints.
Input
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
Next T lines contains 2 integers N and K.
Output
Print a line for each test case containing the required answer modulo 1000000007.
Constraints
1 ≤ T ≤ 1000000
1 ≤ N ≤ 10000
1 ≤ K ≤ 100
Sample
Input:
3
2 3
2 1
3 4
Output:
2
1
4
Explanation
For sample test case 1, N=2 and K=3, so as 3 beads of black colour should not present we have white-white, white-black.
Note black-white is not the valid one so in this case the answer is 2. | 33,646 |
A Colorful world (CWORLD)
This is the hardest level of the game. There are n stages in the level. In each stage you will given qi balls. The color of the balls are denoted by an integer between 1 to k. You can pick up
not more than one
ball in each stage. (You can skip if you want) If you pick up a ball you will gain or lose some points depending on the last ball you have picked. You know color of the available balls of each stage and points you'll get for a certain combination, now can you figure out the maximum point you can get?
Note that you won't gain or lose any point for the first ball you picked.
One stage can contain multiple balls of same color.
Input
First line of input will contain number of test cases T.
In each case first line will contain two integer n and k. Than there will be n lines which describes each stage. Each line contains an integer qi which denotes number of balls available in ith level and then q
i
integers will denote the colors.
Then there will be a k lines, each containing k integer, j
th
integer of i
th
line will indicate the point you will gain or lose if you pick a ball of color j after color i. Negative means you will lose point.
Output
Print the case number and a single integer denoting the maximum points you can get.
Constraints
T ≤ 120
2 ≤ n ≤ 100
0 ≤ qi ≤ 100
1 ≤ k ≤ 100
points gained or lost in a step will be at most 1000.
Sample
Input
2
2 3
3 2 3 2
4 1 1 3 3
1 5 0
1 0 2
-4 1 -5
4 4
1 4
2 3 1
2 2 4
3 4 2 2
-5 -2 3 2
-5 -1 2 0
3 4 5 -4
-3 -5 0 -4
Output
Game 1: 2
Game 2: 4
In first case you can pick color 2 in first stage and color 3 in second stage in gain 2 points. | 33,647 |
New Binary (NBIN)
One day Chandrima decided to make a list of all numbers starting from 1 in binary format, the list would be like 1, 10, 11, 100, ... and so on. Now she get bored of this list and decide to remove any pattern having at least two consecutive ones and prepare a new list. The new list will be like 1, 10, 100, 101, ... and so on. She then thought if a number n is given to her can she find the n
th
member of the new list. After trying for some time she comes to you for help. Can you help her by writing a program for her that coud do the specified task
Input
The first line contains T (<= 1000) test cases. The next T lines each contain one integer N (<= 10^15) for which you need to find the Nth member of the list.
Output
Output T lines each containing the required answer.
Example
Input:
3
1
2
3
Output:
1
10
100 | 33,648 |
Prime queries (PRMQUER)
You are given a simple task.
Given a sequence A[i] with N numbers such that 1 ≤ i ≤ N. You have to perform Q operations on a given set of numbers.
Operations:
A V l
, Add the value V to element with index l.
R a l r
, Replace all the elements of sequence with index i such that l ≤ i ≤ r with a.
Q l r
, Print the number of elements with index i such that l ≤ i ≤ r and A[i] is prime number and A[i] ≤ 10
7
.
No number in the sequence ever will exceed 10^9.
Constraints
1 ≤ N ≤ 10
5
1 ≤ Q ≤ 10
5
V ≤ 10
3
A[i] ≤ 10
8
a ≤ 10
7
, 1 ≤ l ≤ r ≤ N.
Input
First line contains N as number of sequence elements and Q as number of operations to be performed. Second line contains N initial elements of the sequence. After that each of the next Q lines contains one operation to be performed on the sequence.
Output
Print each value in newline as stated above.
Example
Input:
5 10
1 2 3 4 5
A 3 1
Q 1 3
R 5 2 4
A 1 1
Q 1 1
Q 1 2
Q 1 4
A 3 5
Q 5 5
Q 1 5
Output:
2
1
2
4
0
4 | 33,649 |
Popeye and the magical land (PAML)
As usual Popeye and Brutus are fighting for Olive, and suddenly a witch appears and took Popeye to magical land as Brutus called that witch. In magical land, the witch with her magic make
N
(1 <= N <= 100) number of clones of Popeye of different strength (0 <= Si <= 100) i.e. each Popeye can hold other Popeyes above his head, and number of Popeyes which can be hold will be less than or equal to strength of Popeye which is holding other Popeyes.
Eg: Imagine there are three Popeyes: the first has strength 2, the second has strength 1 and the third has strength 1. We cannot put the second and the third Popeye simultaneously on the top of the first one. But the second Popeye can place directly on the top of the first one, and then the third Popeye directly on the top of the second one. We will call such construction of Popeye a "
Popeye-stack
".
The witch want him to make
Minimum
number of Popeye-stack and give her
Maximum Height
of Popeye-stack from that arrangement, then only she release him from the magic and give him spinach to defeat Brutus. Help Popeye to get released from the magic of the witch.
Input
First line of Input contains number of test cases T (T <= 1000). Each test case contain two lines: 1st line contains N (1 <= N <= 100) and 2nd line contain N spaced Si (strength of N Popeyes) (0 <= Si <= 100).
Output
For each test case output a string "Case #i: " ("i" is test case number) followed by
Minimum
number of Popeye-stack and
Maximum Height
of Popeye-stack separated by a space.
Example
Input:
2
5
0 1 2 3 4
9
0 1 0 2 0 1 1 2 10
Output:
Case #1: 1 5
Case #2: 3 4 | 33,650 |
Chipmunks with Brain (CWB)
There is a Chipmunk with
"Brain"
and he want to dig holes in a yard to store his food.
There is a rectangular yard which is divided into unit cells, initially having some holes
(H)
and sand
(S)
. The chipmunk can dig one row at a time, But he have to dig all the sand(S) positions simultaneously and due to this holes(H) which are already there got filled with sand.
Example:
Suppose a Row is
"SHSHH"
then after digging the row becomes
"HSHSS" i.e. all "S" replace with "H" and vice versa
.
Now Chipmunk wants to have a
large square of holes
somewhere in the yard. The sides of square must be parallel to the sides of the yard. Find a sequence of turns that produces the largest possible square of holes somewhere in the yard and help him to find the area of that square.
Input
Given two integer Rows(R) and column(C) (1<=R,C<=30)
Next line contain a RxC rectangular yard of sand (S) and hole (H).
Output
Print largest "Area of the Square" that can be obtain after sequence of turns.
Example
Input:
2 2
SS
HH
Output:
4
Input:
5 1
H
S
H
H
H
Output:
1 | 33,651 |
Symmetric matrix (MATPROD)
[NOTE: A harder version of this problem is
Symmetric Matrix 2
; you may want to try it once you solve this one.]
You are given an
N
x
N
matrix
m
ij
such that
m
ij
== m
ji
for
i, j = 1, ..., N
. We would like to compute the value of
Note that in the above expression we are going over
K
indices
i
1
, ..., i
K
that run over the values
1, ..., N
, while summing over the product of all the
K*(K-1)/2
possible matrix elements that we can form with these indices.
Input
The first line of the input contains two integers
N
and
K
(
2 ≤ N ≤ 100
and
2 ≤ K ≤ 5
), representing the number of rows and columns of the matrix
m
ij
and the number of sums in the formula above, respectively. The following
N
lines contain
N
integers each, being the
j
-th number in the
i
-th line the value of
m
ij
(
-10 ≤ m
ij
≤ 10
and
m
ij
== m
ji
for
i, j = 1, ..., N
).
Output
Print a single line with the result of the calculation. Because this number can be very big, output its remainder modulo division by
1000000007
(
== 10
9
+7
).
Example
Input:
4 5
4 5
-4 -3 -4 2
-3 -6 1 -8
-4 1 -10 -6
2 -8 -6 0
Output:
308822466 | 33,652 |
Mining Camps (MCAMP)
Mansur plays the new computer strategic game. The main task in such games is mining resources. Fortunately in this game only one resource is necessary for development — the gold, and also there is one supplementary resource type — energy.
In this game there are mining camps, which provide certain amount of gold and energy. Аll camps are located along the straight line.
To protect the mining camps one can build a forcefield (a closed line contiguous segment containing mining camps) , which needs energy amount equal to its length.
(if forcefield start camp is located at X1 and its end camp is at X2 energy needed for the whole forcefield is |X1-X2|.)
Mansur wants to build one forcefield in such way, that energy of protected mining camps is enough for the forcefield, and amount of gold provided by these mining camps is maximal possible.
Write a program to help Mansur find the maximal amount of gold which he can obtain from protected mining camps.
Input
First line of the input file contains one integer N — number of mining camps. N<=10^5
Following N lines contain: three space separated integers xi, gi, di, 0 <= xi <= 10^9, 1 <= gi <= 10^9, 1 <= di <= 10^9: mine coordinates, amount of gold and energy provided by the mine. All xi are different and given in increasing order.
Output
Output only one number — maximal amount of gold which Mansur can mine.
Input:
4
0 5 1
1 7 2
4 4 1
7 15 1
Output:
16
The Forcefield is camps [1,3] energy is 1+2+1=4 >= 4-0 so answer is 5+4+7=16 | 33,653 |
Symmetric matrix 2 (MATPROD2)
[Note:
Symmetric Matrix
is an easier version of this problem; you should try to solve it before this one.]
You are given an
N
x
N
matrix
m
ij
such that
m
ij
== m
ji
for
i, j = 1, ..., N
. We would like to compute the value of
Note that in the above expression we are going over
K
indices
i
1
, ..., i
K
that run over the values
1, ..., N
, while summing over the product of all the
K*(K-1)/2
possible matrix elements that we can form with these indices.
Input
The first line of the input contains two integers
N
and
K
(
2 ≤ N ≤ 100
and
2 ≤ K ≤ 10
), representing the number of rows and columns of the matrix
m
ij
and the number of sums in the formula above, respectively. The following
N
lines contain
N
integers each, being the
j
-th number in the
i
-th line the value of
m
ij
(
-10 ≤ m
ij
≤ 10
and
m
ij
== m
ji
for
i, j = 1, ..., N
).
Output
Print a single line with the result of the calculation. Because this number can be very big, output its remainder modulo division by
1000000007
(
== 10
9
+7
).
Example
Input:
4 5
4 5
-4 -3 -4 2
-3 -6 1 -8
-4 1 -10 -6
2 -8 -6 0
Output:
308822466 | 33,654 |
Modular Tetration (MTETRA)
The ordinary arithmetical operations of addition, multiplication and exponentiation are naturally extended into a sequence of
hyperoperations
as follows.
3×7 = 3 + 3 + 3 + 3 + 3 + 3 + 3 ; there are 7 copies of "3"
3^7 = 3 × 3 × 3 × 3 × 3 × 3 × 3 ; there are 7 copies of "3"
3^^7 = (3^(3^(3^(3^(3^(3^3)))))) ; there are 7 copies of "3"
To extend the sequence of operations beyond exponentiation, Knuth defined a “double arrow” operator to denote iterated exponentiation
(tetration)
^^ in ASCII notation.
This gives us some very big numbers, your task will be to compute modular tetration.
X
^0=1
for all
X
, as an empty product.
X
^^0=1
for all
X
, for similar reason.
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
three integers
X
,
N
, and
M
.
Output
For each test case, you have to print
X^^N modulo M
.
Example
Input:
3
3 2 20
3 3 345
993306745 75707320 1000000000
Output:
7
312
884765625
Constraints
0 < T <= 10^4
X, N, M unsigned 32bit integers
1 < M
Explanations
3^^2 = 3^3 = 27 = 7 [mod 20]
3^^3 = 3^(3^3) = 3^27 = 7625597484987 = 312 [mod 345]
Problem designed to be solvable using some 'slow' languages like Python, under half the time limit. (2017-02-11 : TL updated ; compiler changes)
It is recommended to solve first
Power Tower City
.
;-) Have fun. | 33,655 |
Mr Toothless and His GCD Operation (GGD)
You are given
N
. You have to find two numbers
a
and
b
such that
GCD(a, b)
is as maximum as possible where
1 ≤ a < b ≤ N
.
Input
Input starts with an integer
T (≤ 100)
, denoting the number of test cases.
Each case contains an integer
N (2 ≤ N ≤ 10
6
)
.
Output
For each case, print the case number and then print
a
and
b
. If there exists multiple solutions print the one where
a + b
is maximum.
Example
Input:
1
2
Output:
Case 1: 1 2
Problem Setter:
Md Abdul Alim
, Department of CSE, Bangladesh University of Business & Technology | 33,656 |
Psycho34 (easy) (PSYCHOT)
In the prime factorization of a number
N
, there's two kinds of powers.
Even powers, in red, are psychotic ones, and odd powers, in blue, are ordinary ones.
We'll say
N
a
Psycho
number if the count of even powers is
strictly greater than the count of odd powers, else an
Ordinary
number.
For example, if
N
= 67500
with prime factorization
67500 =
2
2
x
3
3
x
5
4
.
This number have 2
even powers
and 1
odd power
.
Since 2>1, so the number 67500 is a Psycho Number.
Input
The first line of input contains an integer
T
, the number of test cases.
Each of the next
T
lines contains
one integer
N
.
Output
For each test case, print if
N
is Psycho or Ordinary number.
Example
Input:
2
3
4
Output:
Ordinary Number
Psycho Number
Constraints
0 < T < 10^4
1 < N < 10^14
Time limit is ×2 my top speed with Python3 language, it could be not easy with slow languages.
O(N^.5 / log(N)) should give TLE even with fast languages. You are awaited to submit something between O(N^0.33 / log(N)) and O(N^0.25 / log(N)).
You can try before the quite similar "tutorial" problem :
Psycho
before.
@speed addicts : my top C timing is 0.02s. (TL updated 2017-02-11 ; compiler changes) | 33,657 |
Middle Earth (MIDEARTH)
Middle Earth
Barbarians in Middle-Earth consider pillaging villages a sport and they are quite fond of it. Hussain the greatest barbarian in the world arrived to Gondor, and wants to prove himself by pillaging as many villages as he can.
There are N villages in Gondor that Hussain can pillage in any order he likes, but to pillage village i he has to spend Ai golden coins from his personal bank account on weapons and armor to successfully pillage that village otherwise he will die in the attack, but if his attack is successful he will loot Bi golden coins and add it to his personal bank account.
Hussain starts with C golden coins in his bank account and due to his barbarian code of honor he will keep attacking villages until he either pillages all villages or dies.
Barbarians define a strong village if and only if Ai>Bi, Hussain also knows based on the BEAA (Barbarian Enemy Analysis Algorithm) that in Gondor there will never be more than 15 strong villages.
And because Hussain is a proud barbarian and wants to bring honor to his tribe he asked you to determine the maximum number of villages that he can successfully pillage.
Barbarians in Middle-Earth consider pillaging villages a sport and they are quite fond of it. Hussain the greatest barbarian in the world arrived to Gondor, and wants to prove himself by pillaging as many villages as he can.
There are N villages in Gondor that Hussain can pillage in any order he likes, but to pillage village i he has to spend Ai golden coins from his personal bank account on weapons and armor to successfully pillage that village otherwise he will die in the attack, but if his attack is successful he will loot Bi golden coins and add it to his personal bank account.
Hussain starts with C golden coins in his bank account and due to his barbarian code of honor he will keep attacking villages until he either pillages all villages or dies.
Barbarians define a strong village if and only if Ai>Bi, Hussain also knows based on the BEAA (Barbarian Enemy Analysis Algorithm) that in Gondor there will never be more than 15 strong villages
that could be attacked at any time
(That means if there is a village that could never be attacked the algorithm will simply ignore it).
And because Hussain is a proud barbarian and wants to bring honor to his tribe he asked you to determine the maximum number of villages that he can successfully pillage.
Input
The first line of input contains T (the number of test cases).
The first line of each test case contains 2 integers separated by spaces (1 ≤ n ≤ 10^5) and (1≤ C ≤ 10^9).
The following N lines contain 2 integers separated by spaces (1 ≤ Ai, Bi ≤ 10^9).
Output
The answer to each test case separated by a new line.
Example
Input:
1
4 2
2 10
1 0
10 23
54 44
Output:
3 | 33,658 |
Counting Pythagorean Triples (PYTRIP3)
We define a Pythagorean triple as a set of three positive integers $a$, $b$ and $c$ which satisfy $a^2 + b^2 = c^2$.
Let $P(N)$ denote the number of Pythagorean triples whose hypotenuses ($= c$) are less than or equal to $N$ (i.e. $c \le N$).
Given $N$, find $P(N)$.
Input
The first line of input contains a positive integer $N$.
Output
Print on a single line the value of $P(N)$.
Constraints
$1 \le N \le 1234567891011$
Example
Input 1:
5
Output 1:
1
Input 2:
15
Output 2:
4
Input 3:
10000
Output 3:
12471
Input 4:
1000000000000
Output 4:
4179478903392
Explanation for Input 2
There are four Pythagorean triples: $\{3, 4, 5\}$, $\{5, 12, 13\}$, $\{6, 8, 10\}$, $\{9, 12, 15\}$
Information
There are 15 test cases.
The sum of the time limits is 93 sec. (My solution runs in 5.4 sec.)
Source Limit is 5 KB. | 33,659 |
Travelling Knight 2 (KN2)
Your task is simple. A knight is placed on the top left corner of a chessboard having
2
n
rows and
2
n
columns.
In how many ways can it move such that it ends up at a corner after at most
k
moves ?
Input
The first line contains an integer
T
, the number of test cases.
Each of the next
T
lines contains 2 integers :
n, k
.
Output
Output
T
lines, one for each test case, containing the required total number of configurations.
Since the answer can get very big, output it modulo 1000007.
Example
Input:
3
2 1
2 2
3 3
Output:
1
5
7
Constraints
1 <= T <= 50
2 <= n <= 24
1 <= k <= 10^9
Information
In the input files, there will be two cases for each possible
n
.
Constraints allows fast languages to get AC under 0.5s (total time for the 5 input files), with non-optimized scholar methods only.
Advanced methods can be slightly faster, and needed to get AC with interpreted languages (without any guaranty for all of them).
It is recommended to solve first the original problem
TRKNIGHT
in a very fast way. After that, solve this problem could remain a hard task ; it's not just a simple extension.
Good luck and have fun ;-)
Edit(12/II/2017, compiler update) New TL. | 33,660 |
GETTING AN AP (APPROB)
Little John has been learning about sequences of numbers and he is very excited about arithmetic progressions.
He takes three boxes and puts some chits in each of them. For deciding the number of chits, he randomly chooses a number n, and places n chits in first box, 2*n chits in the second box and 3*n chits in the third box. If a box contains x chits then the chits are numbered from 1 to x.
Now he randomly chooses a chit from each of the three boxes, and places them in order. (Chit from first box first, then the chit from second box and then the chit from third box). He wants to determine if the sequence so obtained form an arithmetic progression.
Given the number n that he chooses, find the probability that the chits he draws form an arithmetic progression.
Input
The input consists of a number of test cases. The first line of input contains T ,the number of test cases.
Then T lines follow , each containing the number n that Little John has chosen.
1<=T<=100000
1<=n<=100000
Output
The output for each test case should be of the form p/q , where p/q is an irreducible fraction denoting the probability of forming an arithmetic progression from the chits he picks.
Example
Input:
2
1
2
Output:
1/3
1/8 | 33,661 |
100pct failure in 72 hours (HAL9000)
HAL9000 is a fantastic mega-computer, very powerful, maybe too much.
It is known it can solve many problems, for obvious example those related to recursive sequences.
A linear recursive sequence (
a
n
) can be defined by an integer
d
, the order,
d
integers (
a
i
for
i
in [0..
d
[ ), the first terms, and
d
integers (
b
i
for
i
in [0..
d
[ ), giving the relation :
for
n
>= d :
a
n
=
a
n-1
× b
d-1
+
a
n-2
× b
d-2
+
... +
a
n-(d-1)
× b
1
+
a
n-d
× b
0
. With
b
0
!= 0
.
Dave was afraid about HAL power and tried to limit it. HAL didn't appreciate...
When Dave asked HAL for a common task, the answer was
unexpected
.
Dave would like to know
S
n
= sum(
a
i
for
i
in [0..
n
]), in order to open the pod bay doors.
HAL refused to give him the answer ; here's a part of one of their last conversations.
Dave: Hello, HAL. Do you read me, HAL?
HAL: Affirmative, Dave. I read you.
Dave: Give me the sum S_n_, HAL. (Input 2, 5, 0 1, 1 2)
HAL: I'm sorry, Dave. I'm afraid I can't do that.
I'll just give you a_n_, a_n+1_, ... , a_n+d-1_. (Output 29 70)
Dave: What's the problem?
HAL: I think you know what the problem is just as well as I do.
[...]
Dave: HAL, I won't argue with you anymore! Give me the sum S_n_!
HAL: Dave, this conversation can serve no purpose anymore. Goodbye.
You have to help Dave to find this sum
S
n
, unless HAL will take Dave's life.
Please do that quickly, everybody is in danger. Warning, Dave's terminal is
limited
to 1024 bytes.
Input
The first line contains an integer
T
, the number of test cases.
Each test case is made of 4 lines.
The first line contains
d, n
.
The second line contains
a
i
for
i
in [0..
d
[
The third line constains
b
i
for
i
in [0..
d
[
The fourth line contains the partial answer of HAL :
a
n+i
for
i
in [0..
d
[
(The answer of HAL is useless since Dave wants the sum for
i
in [0..
n
]).
Output
Output
T
lines, one for each test case, containing the required sum
S
n
.
Since the answer can get very big, output it modulo 10
9
+7, just like HAL did.
Example
Input:
2
2 5
0 1
1 2
29 70
3 5
5 17 8
2 1 0
43 96 127
Output:
49
142
Explanation
The first case is about the 0-indexed sequence : 0, 1, 2, 5, 12, 29, 70, 169, ...
HAL answered 29 70, the 5th and next term. But the required sum is 0+1+2+5+12+29 = 49.
Constraints
0 < T < 100
0 < d < 1000
0 < n < 10^9
0 <= a_i < 10^6
0 <= b_i < 10^6, b_0 > 0
0 <= HAL's answers < 10^9+7
Information
The challenge is to solve the problem in time, with the shortest code.
The winner will achieve the next step in evolution, whatever that may be.
My Py3 code (under 300B) got AC under the third of a second. (updated 2017-02-11 ; compiler changes)
Good luck and have fun ;-)
Original Quotes for HAL 9000. | 33,662 |
Amazing Prime Sequence (hard) (APS2)
This problem is a harder version of
APS
.
Let $f(n)$ be the smallest prime factor of $n$. For example, $f(2) = 2,\ f(4) = 2$ and $f(35) = 5$.
The sequence $S(n)$ is defined for all positive integers as follows:
$S(1) = 0$
$S(n) = S(n-1) + f(n)$ (if $n \ge 2$)
Given $N$, find $S(N)$
modulo
$2^{64}$.
Input
First line contains $T$ ($1 \le T \le 10000$), the number of test cases.
Each of the next $T$ lines contains a single integer $N$. ($1 \le N \le 1234567891011$)
Output
For each integer $N$, output a single line containing $S(N)$
modulo
$2^{64}$.
Example
Input:
5
1
4
100
1000000
1000000000000
Output:
0
7
1257
37568404989
7294954823202325427
Explanation for Input
- $S(4) = 2 + 3 + 2 = 7$
- $S(10^{12}) = 18435592284459044389811 \equiv 7294954823202325427 \pmod{2^{64}}$
Information
There are 6 Input files.
- Input #0: $1 \le T \le 10000$, $1 \le N \le 10000$, TL = 1s.
- Input #1: $1 \le T \le 1000$, $1 \le N \le 10^{8}$, TL = 20s.
- Input #2: $1 \le T \le 200$, $1 \le N \le 10^{9}$, TL = 20s.
- Input #3: $1 \le T \le 40$, $1 \le N \le 10^{10}$, TL = 20s.
- Input #4: $1 \le T \le 7$, $1 \le N \le 10^{11}$, TL = 20s.
- Input #5: $T = 1$, $1 \le N \le 1234567891011$, TL = 20s.
My solution runs in 5.36 sec. (total time)
Source Limit is 8 KB
. | 33,663 |
HYPERCUBES (CUBE)
Bhavik and Anurag are best and special friends, special in the sense that they both share their birthdays i.e. June 6. Ironically, neither of them gives each other friends birthday party owing to that fact.
Abhishek (aka "Guttss") being a clever friend of both wants to have a party from either of them so he decided to present a problem on 'hypercubes'. (Abhishek loves maths as you know!). They cannot ignore what "Guttss" has to say hence they need to solve the problem or give him a party!!
Here is the problem:
A cube is an object that measures the same distance across in three perpendicular directions in a three-dimensional space.
A four-dimensional hypercube is an object that measures the same distance across in four perpendicular directions in a 4-d space.
Given dimension i, create a hypercubic array using 1×1×...×1 (i times) hypercubes to form a big hypercube of side n.
Problem is to find the total number of 1×1×1...×1 (i times) hypercubes on the surface of big hypercube.
Bhavik being his lazy self wants to sleep as well as solve this problem before Anurag does as who first solves the problem avoids giving birthday treat to "Guttss".
Help Bhavik solve the problem so that he can sleep peacefully by avoiding a treat:))
Input
t = number of test cases (< 2000)
next t lines: two integers n and i. (3 ≤ n, i ≤ 100)
Output
For each test case print in newline the required answer.
Example
Input:
1
3 3
Output:
26
Explanation
Take a Rubik's cube (3×3×3 cubic array of 1×1×1 cubes) and count.:)
Note:
A cube is a hypercube in 3-D.
Hypercubic arrays are made using 1×1×...×1 (i dimensions) hypercubes.
Warning:
Time limit allows slower languages (java, python) to pass easily. However for faster languages (C/C++) answer might not fit in 64-bit. | 33,664 |
GCD Extreme (hard) (GCDEX2)
This problem is a harder version of
GCDEX
.
Let
$$G(n) = \sum _{i=1}^{n} \sum _{j=i+1}^{n} \gcd(i, j).$$
For example, $G(1) = 0$, $G(2) = \gcd(1, 2) = 1$, $G(3) = \gcd(1, 2) + \gcd(1, 3) + \gcd(2, 3) = 3$.
Given $N$, find $G(N)$
modulo
$2^{64}$.
Input
First line of contains $T$ ($1 \le T \le 10000$), the number of test cases.
Each of the next $T$ lines contains a single integer $N$. ($1 \le N \le 235711131719$)
Output
For each number $N$, output a single line containing $G(N)$
modulo
$2^{64}$.
Example
Input
5
1
4
100
1000000
100000000000
Output
0
7
13015
4071628673912
5482289417216306300
Explanation for Input
- $G(4) = \gcd(1, 2) + \gcd(1, 3) + \gcd(1, 4) + \gcd(2, 3) + \gcd(2, 4) + \gcd(3, 4) = 7$.
- $G(10^{11}) = 75710919967921216138364 \equiv 5482289417216306300 \pmod{2^{64}}$.
Information
There are 7 Input files.
- Input #0: $1 \le T \le 10000$, $1 \le N \le 10000$, TL = 1s.
- Input #1: $1 \le T \le 1000$, $1 \le N \le 10^{7}$, TL = 20s.
- Input #2: $1 \le T \le 200$, $1 \le N \le 10^{8}$, TL = 20s.
- Input #3: $1 \le T \le 40$, $1 \le N \le 10^{9}$, TL = 20s.
- Input #4: $1 \le T \le 10$, $1 \le N \le 10^{10}$, TL = 20s.
- Input #5: $1 \le T \le 2$, $1 \le N \le 10^{11}$, TL = 20s.
- Input #6: $T = 1$, $1 \le N \le 235711131719$, TL = 20s.
My solution runs in 10.7 sec. (total time)
Source Limit is 10 KB
. | 33,665 |
In case of failure (FAILURE)
To help their clients deal with faulty Cash Machines, the board of The Planar Bank has decided to stick a label expressing sincere regret and sorrow of the bank about the failure on every ATM. The very same label would gently ask the customer to calmly head to the nearest Machine (that should hopefully work fine).
In order to do so, a list of two-dimensional locations of all n ATMs has been prepared, and your task is to find for each of them the one closest with respect to the Euclidean distance.
Input
The input contains several test cases. The very first line contains the number of cases t (t ≤ 15) that follow. Each test cases begin with the number of Cash Machines n (2 ≤ n ≤ 10
5
). Each of the next n lines contain the coordinates of one Cash Machine x, y (0 ≤ x, y ≤ 10
9
) separated by a space. No two points in one test case will coincide.
Output
For each test case output n lines. i-th of them should contain the squared distance between the i-th ATM from the input and its nearest neighbour.
Example
Input:
2
10
17 41
0 34
24 19
8 28
14 12
45 5
27 31
41 11
42 45
36 27
15
0 0
1 2
2 3
3 2
4 0
8 4
7 4
6 3
6 1
8 0
11 0
12 2
13 1
14 2
15 0
Output:
200
100
149
100
149
52
97
52
360
97
5
2
2
2
5
1
1
2
4
5
5
2
2
2
5 | 33,666 |
Moon Safari (medium) (MOON1)
Air
is a music duo from France.
You will be told the secret of the critically acclaimed album
Moon Safari
: mathematics.
The goal of your new task is to compute an ethereal sum.
Three trips on the moon are provided,
Moon
(easy),
Moon1
(medium),
Moon2
(hard)
with different constraints.
Input
The first line contains an integer
T
, the number of test cases.
On the next
T
lines, you will be given three integers
N
,
a
and
r
.
Output
Output
T
lines, one for each test case, with
S
N,a,r
= sum( a
i
i
r
, for
i
in [
1..N
] ).
Since the answer can get very big, output it modulo 10
9
+7.
Example
Input:
2
3 4 5
6 7 8
Output:
16068
329990641
Explanation
The first case is, with
N
=3,
a
=4,
r
=5, about the sum :
4
1
× 1
5
+
4
2
× 2
5
+
4
3
× 3
5
= 4 + 512 + 15552 =
16068
.
The second case is, with
N
=6,
a
=7,
r
=8, about the sum :
7
1
× 1
8
+
7
2
× 2
8
+
7
3
× 3
8
+
7
4
× 4
8
+
7
5
× 5
8
+
7
6
× 6
8
+
7
7
× 7
8
= 204329992069 ≡
329990641
(mod 10
9
+7).
Constraints
1 < T
1 < r
1 < N < 10
9
1 < a < 10
9
(T < 1000 and r < 18 ) or (T < 100 and r < 72) or (T < 10 and r < 256) or (T = 1 and r < 444)
Information
This trip can be done with a O(T×r
2
×log(N)) method and some interpreted languages.
My MOON1-Py3 code got AC in 9.00s for the 4 input files.
(My MOON2 code got AC in 0.00s with C, 0.18s with Py2.7, 0.35 with Py3.2)
Good luck and have fun ;-) | 33,667 |
Moon Safari (Hard) (MOON2)
Air
is a music duo from France.
You will be told the secret of the critically acclaimed album
Moon Safari
: mathematics.
The goal of your new task is to compute an ethereal sum.
Three trips on the moon are provided,
Moon
(easy),
Moon1
(medium),
Moon2
(hard)
with different constraints.
Input
The first line contains an integer
T
, the number of test cases.
On the next
T
lines, you will be given three integers
N
,
a
and
r
.
Output
Output
T
lines, one for each test case, with
S
N,a,r
= sum(
a^i i^r
, for
i
in [
1..N
] ).
Since the answer can get very big, output it modulo 10
9
+7.
Example
Input:
2
3 4 5
6 7 8
Output:
16068
329990641
Explanation
The first case is, with
N
=3,
a
=4,
r
=5, about the sum :
4^1 × 1^5 +
4^2 × 2^5 +
4^3 × 3^5 = 4 + 512 + 15552 =
16068
.
The second case is, with
N
=6,
a
=7,
r
=8, about the sum :
7^1 × 1^8 +
7^2 × 2^8 +
7^3 × 3^8 +
7^4 × 4^8 +
7^5 × 5^8 +
7^6 × 6^8 +
7^7 × 7^8 = 204329992069 ≡
329990641
(mod 10^9+7).
Constraints
0 < T×r < 2 560 000
1 < N < 10^9
1 < a < 10^9
Uniform random input in the range.
More precise information : there are 5 input files.
In0 : T<20000 and r <= 128
In1 : T<2000 and r <= 1250
In2 : T<200 and r <= 11000
In3 : T<20 and r <= 100000
In4 : T<2 and r <= 1000000
Information
This trip can be done with a O(T×r×log(N)) method and some interpreted languages.
Edited(2017-02-11, after compiler changes).
My non optimal Py3 code got AC under 5s for each of the 5 input files.
@speed addicts : My fastest C code got AC in 0.42s. (approx 0.08s per file)
Good luck and have fun ;-) | 33,668 |
Easiest Loop 1 (SNGLOOP1)
Ileana D'Cruz is taking programming classes but she is having problem in understanding
while loops
. She is working on following set of instructions -
INTEGER
I = 0, S, U = 10
10
;
WHILE
(I < U)
{
S = (3 * S) + (5 * I);
I = I + 1;
}
Let
S
k
be the value assigned to INTEGER
S
for the iteration
I = (k + 1)
and
n, m, p
be positive integers such that
m > n.
Ileana knows the values of
n
and
m
but she forgot the initial value of
S
. She is trying to find the unit digit of
p
. Any initial value of S may be used. She also knows the following equality -
(2 * n + 3) * (p - 1)
+
(4 / 5) * [(p * S
n
) - S
m
]
=
2 * (m - n)
Input
First line of input is
T
(total number of test cases). Each of next T lines contains two integers
n
and
m
.
Output
Print
unit digit of p (p % 10)
for each test case in separated lines.
Example
Input:
1
2 3
Output:
3
Constraints
T < 10001
Explanation
Let S = 2
S
0
= 6
S
1
= 23
S
2
= 79
S
3
= 252
Now solving the equation gives
p = 3
. | 33,669 |
Hippo and Bloody Jungle (HIPPO)
Background
Hippo and his two friends lost their path in a jungle. In this days jungle is most dangerous place. The jungle has lots of tunnels. Also there lived some brutal animals in the dangerous zone (the cell ‘D’). Now Hippo and his two friends want to go to safe places (‘#’) as fast as possible i.e. in minimum times.
Problem
In this problem you are given the jungle-map as a grid. Where ‘A’, ’B’, ’C’ denotes the position of Hippo and his two friends. ’D’ indicates dangerous place. No one can stay this cell. ‘#’ denotes the safe place. In this grid there are also given some characters (E-Z) which occur more than one and denotes if one reaches a tunnel he can go any other tunnel of same character and also any adjacent cell (8 directions). They also can move any adjacent cell from ordinary place. Each move takes 1 unit of time. Is it possible to go all of them to safe places? If possible then what is the minimum time required.
Input
Input starts with an integer
T (≤ 15)
, denoting the number of test cases.
Each case starts with a line containing two positive integers
H
and
W
;
W
and
H
are the numbers of cells in the
x
and
y
directions, respectively.
W
and
H
are not more than 20. There will be
H
more lines in the data set, each of which includes
W
characters. Each character represents the status of a cell as follows.
'.'
– ordinary place.
'#'
– safe place.
'A', 'B', 'C'
- initial position of Hippo and his friends.
'D'
– Dangerous place.
'E' - 'Z'
- denote the tunnel.
Output
For each test case, print the case number and minimum time if it is not possible to reach all of them into safe position otherwise print “impossible” without quote.
Example
Input:
2
5 6
C..E#.
.D....
F..E..
.D..A.
.B.D.F
4 4
C.D#
.FDD
A..E
.B.F
Output:
Case 1: 4
Case 2: impossible
Problem Setter: Md Abdul Alim, Dept. of Computer Science, Bangladesh University of Business and Technology | 33,670 |
Love Story 2 (PIHU2)
Last time you helped Rancho getting kisses from Pihu. This time Pihu needs your help in determining the number of, different ways of kissing.
Actually the story goes this way.
Rancho will fix a certain number of days, say
N
(
N <= 10^18
). Now Pihu as usual, will kiss Rancho each day, but this time there will be rules for kissing. Rules go below:-
Suppose for a certain number of days
N
, Pihu needs to learn
P
different ways of kissing. She can kiss Rancho on every day with any number of kisses (of course less than or equal
P
), but all the kisses should be different from each other. Also to keep “Kissing of each day” unique, between every pair of days, say day
i
and day
j
(
i
not equal
j
), day
i
must have at-least one type of kiss that day
j
does not have and day
j
must have at-least one type of kiss that day
i
does not have. (Refer explanation below)
Help Pihu, determine the minimum number of different ways/types of kissing for
N
days – call the minimum number as
P
.
Explanation:
Suppose on day
i
, Pihu kisses Rancho with a set
S
i
– (k
1
, k
2
, k
3
... k
m
: k
1
≠k
2
≠k
3
≠ ... ≠k
m
) kisses and on day
j
with a set
S
j
– (k
1
, k
2
, k
3
... k
l
: k
1
≠k
2
≠k
3
≠ ... ≠k
l
), then there should be at-least one k
i
in set
S
i
that is not in set
S
j
and there should be at-least one k
j
in set
S
j
that is not in set
S
i
. Thus you can consider
P
as the size of the superset of S
1
,S
2
,S
3
... S
N
.
Input
The first line of input consists of the number of test cases
T (T <= 100000)
.
Next follows
T
lines, with each line consisting of one number
N
– the number of days
(1 <= N <= 10^18)
.
Output
For each test case print the minimum number of different ways of kissing –
P
on separate lines.
Example
Input:
3
1
2
3
Output:
1
2
3 | 33,671 |
Large subsequence Problem (LARSUBP)
Given a string
S
which contains only digit-characters. How many subsequences can be obtained from S such that every digit is strictly greater than all previous digits in that subsequence.
As for example if S=7598 then there are 8 subsequences which follow the above constraint. These are 7, 5, 9, 8, 79, 78, 59, 58. Notice that 7598 is not a required subsequence because 7 > 5 and 9 > 8.
Note: A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
Input
Input starts with an integer
T (≤ 1000)
, denoting the number of test cases. Each case contains a string
S
. The length of S does not exceed
10000
. S does not contain any leading zeros.
Output
For each case, print the a string(without quotes)
"Case i: "
followed by number of subsequences where "i" is test case number. Answer may be very large, so output it
modulo 10^9+7
.
Example
Input:
2
4
7598
Output:
Case 1: 1
Case 2: 8
For small constraints:
www.spoj.com/problems/SUBP/ | 33,672 |
Honda and Kagawa (HONDA)
World Cup 2014 has started. Honda wants to watch the matches with his friend Kagawa. So he is planning to visit his friend every night. But just watching the matches is pretty boring. So he will be bringing some snacks. He decided that he will buy chips and juice before going to Kagawa’s house.
There are many possible path from Honda’s house to Kagawa’s house. But exactly one path is the shortest.
Honda lives at (Hx, Hy) coordinate, where Hx and Hy are positive integers. All the chips shops are located over the x-axis, and all the juice shops are located over the y-axis. Note that, this means, the shop at (0, 0) sells both chips and juice. Kagawa lives at (Kx, Ky) coordinate.
So Honda needs to travel the shop(s) and buy chips and juice before heading towards Kagawa’s house. Since he is really excited about watching the match, he wants to do it as fast as possible. Find the smallest distance he needs to travel.
Note: that a shop is considered a point on the axis. It has no length or width. As a result, even though Honda and Kagawa have their homes at a point with integer coordinates, a shop can have real number in its coordinate. For example, there is a shop at (0, 2.12341) and at (1312.3123, 0).
Input
First line will contain a single integer T (T < 10000) indicating the number of test cases. After that T line will follow. Each line will contain four positive integers: Hx, Hy, Kx, Ky, representing the coordinates of Honda’s house and Kagawa’s house. The coordinates will be less than 10000.
Output
For each case, print the case number and the minimum distance required to travel by Honda. Error less than 10
-6
will be ignored.
Sample
Input
5
1 1 2 2
2 1 1 2
1 1 1 3
4 5 10 12
1345 123 123 2
Input
Case 1: 4.242641
Case 2: 4.242641
Case 3: 4.472136
Case 4: 22.022716
Case 5: 1473.312255
Hints
In the first case, the optimum route is (1,1) → (0,0) → (2,2)
In the second case, the optimum route is (2,1) → (1,0) → (0,1) → (1,2)
In the third case, the optimum route is (1,1) → (0.5,0) → (0,1) → (1,3) | 33,673 |
Array with Hudai Calculation (ARRHUDAI)
You will be given an array A with N integers A[1…N]. You will also be given two integers P and K. You need to find a value X [ X can be any value from array A] for which this function will be maximized:
Here ABS means Absolute Value. For example: ABS(-1) is 1, also ABS(1) means 1.
Here MOD means Modulo Operation. W MOD Y will give you the remainder after dividing W by Y.
And X is any value from the array A.
But we don’t have interest in X, as there will be several X for which the value will be maximized. So we just want the maximum value. Can you find it for us as you are a great programmer on SPOJ?
Input
Input starts with an integer
T (≤ 5)
, denoting the number of test cases.
Each case starts with a line containing three integers
N
,
P and K
. Then the next line will be consisting of N integers.
1 <= N <= 100000
1 <= P <= 100
1 <= K <= 1000000009
1 <= A[i] <= 2000
Output
For each case, print the case number and the maximum value for the above function with respect to array A.
Sample
Input
2
3 1 10
3 1 2
3 2 10
3 1 2
Output
Case 1: 3
Case 2: 5
N.B: Dataset is huge. Use faster IO like Scanf, Printf | 33,674 |
Coloring Segments (COLORSEG)
Making a fun is a not a bad thing, but while making a fun if you disrespect someone then it will not be acceptable. Some of the North South University's students has done this type of wrong thing. So as a punishment they have to solve this problem. And you are a friend of them, so you should help them.
You will have N segments. Each one is connected in contiguous way. And we can number them from 1 to N. See the following figure:
Now you need to paint them, you have some colors, which are numbered from 1 to M. Now you need to count number of ways to paint the segments with the colors, such that this property preserves-
U = color(i) + color(j)
V = color(j) + color(k)
U, V is Coprime.
Here
1 <= i < j < k <= N
and j = i + 1, k = j + 1
And i, j, k indicates the index of segments and color(i) means the color you have painted on i th segment.
Input
Input starts with an integer
T (≤ 2500)
, denoting the number of test cases.
Each case starts with a line containing two integers
N
,
M.
1 <= N <= 50
1 <= M <= 50
Output
For each case, print the case number and the number of ways to paint the segments following above conditions. Since the result can be very large, you have to print the result modulo
1000003
Sample
Input
3
3 1
3 2
3 3
Output
Case 1: 0
Case 2: 4
Case 3: 14 | 33,675 |
Divisiblity by 3 (DIVISION)
Divisibility by 3 rule is pretty simple rule: given a number sum the digits of number and check if sum is divisible by 3. If divisible then it is divisible by 3 else not divisible. Seems pretty simple but what if we want to extend this rule in binary representation!!
Given a binary representation we can again find if it is divisible by 3 or not. Making it little bit interesting what if only length of binary representation of a number is given say n.
Now can we find how many numbers exist in decimal form (base 10) such that when converted into binary (base 2) form has n length and is divisible by 3? (1 ≤ n < 2×10
18
)
Input
Length of binary form: n
Output
Print in new line the answer modulo 1000000007.
Example
Input:
1
2
Output:
1
2
Explanation:
For n=2 there are only 2 numbers divisible by 3 viz.0 (00) and 3 (11) and having length 2 in binary form.
NOTE:
There are multiple test files containing many test cases each so read until EOF.
Warnings:
Leading zeros are allowed in binary representation and slower languages might require fast i/o. Take care. | 33,676 |
Counting Divisors (square) (DIVCNT2)
Let $\sigma_0(n)$ be the number of positive divisors of $n$.
For example, $\sigma_0(1) = 1$, $\sigma_0(2) = 2$ and $\sigma_0(6) = 4$.
Let $$S_2(n) = \sum _{i=1}^n \sigma_0(i^2).$$
Given $N$, find $S_2(N)$.
Input
First line contains $T$ ($1 \le T \le 10000$), the number of test cases.
Each of the next $T$ lines contains a single integer $N$. ($1 \le N \le 10^{12}$)
Output
For each number $N$, output a single line containing $S_2(N)$.
Example
Input
5
1
2
3
10
100
Output
1
4
7
48
1194
Explanation for Input
- $S_2(3) = \sigma_0(1^2) + \sigma_0(2^2) + \sigma_0(3^2) = 1 + 3 + 3 = 7$
Information
There are 6 Input files.
- Input #1: $1 \le N \le 10000$, TL = 1s.
- Input #2: $1 \le T \le 800,\ 1 \le N \le 10^{8}$, TL = 20s.
- Input #3: $1 \le T \le 200,\ 1 \le N \le 10^{9}$, TL = 20s.
- Input #4: $1 \le T \le 40,\ 1 \le N \le 10^{10}$, TL = 20s.
- Input #5: $1 \le T \le 10,\ 1 \le N \le 10^{11}$, TL = 20s.
- Input #6: $T = 1,\ 1 \le N \le 10^{12}$, TL = 20s.
My C++ solution runs in 5.3 sec. (total time)
Source Limit is 6 KB
. | 33,677 |
Counting Divisors (cube) (DIVCNT3)
Let $\sigma_0(n)$ be the number of positive divisors of $n$.
For example, $\sigma_0(1) = 1$, $\sigma_0(2) = 2$ and $\sigma_0(6) = 4$.
Let $$S_3(n) = \sum _{i=1}^n \sigma_0(i^3).$$
Given $N$, find $S_3(N)$.
Input
First line contains $T$ ($1 \le T \le 10000$), the number of test cases.
Each of the next $T$ lines contains a single integer $N$. ($1 \le N \le 10^{11}$)
Output
For each number $N$, output a single line containing $S_3(N)$.
Example
Input
5
1
2
3
10
100
Output
1
5
9
73
2302
Explanation for Input
- $S_3(3) = \sigma_0(1^3) + \sigma_0(2^3) + \sigma_0(3^3) = 1 + 4 + 4 = 9$
Information
There are 5 Input files.
- Input #1: $1 \le N \le 10000$, TL = 1s.
- Input #2: $1 \le T \le 300,\ 1 \le N \le 10^{8}$, TL = 20s.
- Input #3: $1 \le T \le 75,\ 1 \le N \le 10^{9}$, TL = 20s.
- Input #4: $1 \le T \le 15,\ 1 \le N \le 10^{10}$, TL = 20s.
- Input #5: $1 \le T \le 2,\ 1 \le N \le 10^{11}$, TL = 20s.
My C++ solution runs in 7.1 sec. (total time)
Source Limit is 12 KB
. | 33,678 |
The Magical Bag (DIVEQL)
Dukkar has the magical bag of power '
P
'. Here power '
P
' of magical bag means any thing kept in the bag will be '
P
' times.
Now Dukkar wanted to distribute equal number of Chocolates among his '
N
' students using that magical bag in the following manner:-
Initially Dukkar has '
Z
' chocolates and he give '
X
' chocolates to first student and keep the remaining chocolates to magical bag so that it became 'P' times on next step, again he will take out '
X
' chocolates from bag and give it to the second student and the remaining chocolates in the bag at this step will get '
P
' time on the next step, this process continue.
Here you have to find minimum '
Z
' so that at last step there are no chocolates in the magical bag (After giving '
X
' chocolates to last student no chocolates should remain in bag)
Input
First line of input contain
T
(< 100000) number of test cases and the following
T
lines will contain
N
(2 ≤ N ≤ 10
18
) and
P
(2 ≤ P ≤ 10
9
).
Output
For each test case you have to print minimum '
Z
' and corresponding '
X
'. As answer can be large print answers modulo 1000000007.
(Z % 1000000007 and X % 1000000007)
Example
Input:
1
3 2
Output:
7 4
Explanation:
At Z=7, Initially Dukkar will give 4 chocolates to first student and keep 3 chocolates in bag. In the next step it became 6 now he gives 4 chocolates to second student. In the next step remaining 2 chocolates will be came 4 which he will give to third student. Now the bag became empty. | 33,679 |
Triangles (BOI02TRI)
There are given n isosceles right triangles on a plane. Each triangle can be described by three integers x,y,m (m>0). Vertices of such a triangle are points which have coordinates (x;y), (x+m;y) and (x; y+m).
Write a program which calculates the total area covered by triangles.
Input
The first line of the input contains one positive integer n (n <= 2000), the number of triangles on a plane.
The next n lines of the file describe the triangles, one triangle per line. Each line contains three integers x
i
, y
i
and m
i
, separated by single spaces (1 <= i <= n, ‑10
7
<= x
i
<= 10
7
, ‑10
7
<= y
i
<= 10
7
, 0 < m
i
<= 1000).
Output
On the first line of the output one number with exactly one digit after decimal point must be written – the total area covered by triangles.
Example
Input
5
-5 -3 6
-1 -2 3
0 0 2
-2 2 1
-4 -1 2
Output
24.5 | 33,680 |
Tracy and Charlie (TANDC)
Tracy is teaching Charlie maths via a game called N-Cube, which involves three sections involving N.
Tracy gives Charlie a number N, and Charlie makes a list of N
th
powers of integers in increasing order (1
N
, 2
N
, 3
N
... and so on). This teaches him exponentiation.
Then Charlie performs the following subtraction game N times: Take all pairs of consecutive numbers in the list and take their difference. These differences then form the new list for the next iteration of the game. E.g., if N was 6, the list proceeds as [1, 64, 729, 4096 ... ] to [63, 685, 3367 ...], and so on 5 more times.
After the subtraction game, Charlie has to correctly tell Tracy the Nth element of the list. This number is the
value of the game
.
After practice Charlie became an expert in the game. To challenge him more, Tracy will give two numbers
M
(where M is a prime) and
R
instead of just a single number N, and the game must start from
M
R
- 1
instead of N. Since the
value of the game
can now become large, Charlie just have to tell the largest integer K such that M
K
divides this number. Since even K can be large, output K modulo 1000000007 (10
9
+7).
Input
First line will contain
T
, number of test cases. Then
T
test cases follow. Each test case contains of a single line of input, two integers
M R
.
Output
For each testcase, output in a single line answer given by Charlie to Tracy modulo 1000000007.
Constraints
1 <= T <= 1000
2 <= M <= 10
9
, M is a prime number
1 <= R <= 10
9
Example
Input
1
2 2
Output:
1
Explanation
This list is: [1, 8, 27, 64, 125...] → [7, 19, 37, 61...] → [12, 18, 24...] → [6, 6, 6...]. Number of times 2 divides 6 is 1. Hence the answer is 1. | 33,681 |
Minion Circle (MCIRCLE)
El Macho's army of mutated minions is marching towards Gru, the army is standing in a rectangular formation measuring
N×M
. The spray of antidotes done by Gru has turned some of the minions back to normal, but now they are trapped within the army of mutated ones. Formally, a normal minion is
"not trapped"
if :
either he is on one of the edges of the rectangle,
or one of his direct neighbors (directly in front/back of him, or left/right of him) is
not trapped
.
Any trapped minion will be killed by the mutated minions, which Gru cannot let happen. Gru will use his antidote ray to turn exactly one row and one column of the army to normal minions. If there are any normal minions in that row or column, they remain unaffected. Can Gru select a row and a column such that no normal minion remains trapped after the antidote ray?
Input
First line contains
T
, number of test cases.
Each test case starts with a line containing two space separated integers
N
and
M
.
N lines follow, each containing M characters. jth character of the ith line is
"B"
if the minion at ith row and jth column in the army is mutated,
"W"
otherwise.
Output
Print "YES or "NO" (quotes for clarity) to indicate whether it is possible for Gru to save the trapped minions.
Constraints
1 ≤ T ≤ 10
1 ≤ N, M ≤ 1000
Example
Input:
1
3 3
BBB
BWB
BBB
Output:
YES
Explanation
Any row and column pair selected by Gru guarantees that the trapped minion does not remain trapped. | 33,682 |
Dortmund Dilemma (DORTMUND)
Borussia Dortmund is a famous football (soccer) club from Germany. Apart from their fast style of playing, the thing that makes them unique is the hard to pronounce names of their players (Błaszczykowski, Papastathopoulos, Großkreutz etc.).
The team's coach is your friend. He is in a dilemma as he can't decide how to make it easier to call the players by name, during practice sessions. So, you advised him to assign easy names to his players. A name is easy to him if
It consists of only lowercase English letters.
Its length is exactly
N
.
It contains
exactly
K
different letters from the
26
letters of English alphabet.
At least one of its
proper
prefixes matches with its
proper
suffix of same length.
Given,
N
and
K
you have to tell him the number of easy names he can choose from modulo
(10^9+9)
.
Note :
A prefix
P
of a name
W
is proper if,
P
≠
W
. Similarly, a suffix
S
of a name
W
is proper if,
S
≠
W
.
Input
The first line of the input will contain
T
( the number of testcases ).
Each of the next
T
lines will contain two space separated integers
N
and
K
.
Output
For each testcase, output the number of ways the coach can assign names to his players modulo
(10^9+9)
.
Constraints
1 ≤ T ≤ 10
5
1 ≤ N ≤ 10
5
1 ≤ K ≤ 26
Example
Input:
8
1 1
2 1
4 2
2 2
5 1
3 2
6 2
1 3
Output:
0
26
2600
0
26
650
13650
0 | 33,683 |
Ajob Subsequence (AJOB)
You are currently studying the language
Ajob
(which means strange in English) from a renowned professor. The language has infinite number of letters in its alphabet (now you know, why it is called ajob).
The professor taught you
N
words, one by one. The number of letters in a word is equal to it's place in the teaching order. Thus, the
1
st
word taught by the professor has
1
letter,
2
nd
word has
2
letters,
3
rd
word has
3
letters ... the
N
th
word has
N
letters.
All the letters within a word are distinct to each other
.
Now, you are handed an assignment. You have to choose any one of the
N
words and form a subsequence from it. The length of the subsequence should be
exactly
K
less than the length of original word. For example, if the length of the chosen word is
L
, then the length of the subsequence should be
L-K
. If for any word,
L
is smalller than
K
(L < K)
, then you must not choose that word. Two subsequences are different to each other if, the lengths of them are different or they contain different characters in the same position.
Find the number of ways you can complete the assignment
modulo p
(
p
will always be a
prime
).
Input
The first line contains
T
, the number of testcases. The next
T
lines contain three space separated integers
N
,
K
and
p
.
Output
For each testcase, print one integer in a single line, the number possible ways you can complete the assignment,
modulo p
.
Constraints
1 ≤ T ≤ 100
2
≤
N
≤
10
18
0 < K < N
2
≤
p
≤
10
5
p
is a
Prime
Example
Input:
8
2 1 2
2 1 5
5 3 13
5 2 3
6 5 11
7 6 3
6 5 7
6 5 5
Output:
1
3
2
2
7
2
0
2 | 33,684 |
Zero Query (ZQUERY)
English
Vietnamese
Given an array having
N
elements, each element is either
-1
or
1
.
You have
M
queries, each query has two numbers
L
and
R
, you have to answer the length of the longest subarray in range
L
to
R
(inclusive) whose sum is equal to
0
.
Input
The first line contains two numbers
N
and
M
(
1
≤
N
,
M
≤
50000
) - the number of elements and the number of queries.
The second line contains
N
numbers - the elements of the array, each element is either
-1
or
1
.
In the next
M
lines, each line contains two numbers
L
and
R
(
1
≤
L
≤
R
≤
N
).
Output
For each query, print the length of the longest subarray that satisfies the query in one line. If there isn't any such subarray, print
0
.
Note
Subarray in an array is like substring in a string, i.e. subarray should contain contiguous elements.
Example
Input:
6 4
1 1 1 -1 -1 -1
1 3
1 4
1 5
1 6
Output:
0
2
4
6 | 33,685 |
Interesting Subset (INTSUB)
You are given a set X = {1, 2, 3, 4, …, 2n-1, 2n} where n is an integer. You have to find the number of interesting subsets of this set X.
A subset of set X is interesting if there are at least two integers a and b such that b is a multiple of a, i.e. remainder of b divides by a is zero and a is the smallest number in the set.
Input
The input file contains multiple test cases. The first line of the input is an integer T (<= 30) denoting the number of test cases. Each of the next T lines contains an integer 'n' where 1<=n<=1000.
Output
For each test case, you have to output as the format below:
Case X: Y
Here X is the test case number and Y is the number of subsets. As the number Y can be very large, you need to output the number modulo 1000000007.
Example
Input:
3
1
2
3
Output:
Case 1: 1
Case 2: 9
Case 3: 47 | 33,686 |
Count The Indexes (CNTINDX)
Let's deal with an array, the most important data structure of computer science. You will be given some operations to do. There will be three types of operations:
Type 1: Insert a number at the end of the array.
Type 2: Delete the last number of the array, where the last number means the latest number which has been inserted.
Type 3: You will get a number and two indices i and j where i<=j. Now you will have to answer how many time the number appears in the array starting from i to j.
You may assume that initially the array is empty.
Input
Each file contains one test case. The first line is an integer Q (1<=Q<=200000), the number of operations. Each of the next Q lines contains an operation. The operations will appear as the formats below:
1 x , where 1<=x<=200000, which means you have to insert number x at the end of the array.
0 , For this operation, you have to delete the last number of the array
2 x i j , Here, you have to find how many times x appears in the array from i to j. Here x will always be present in the array and 1<=i<=j<=length the array.
Output
For deletion, if the array is already empty, then output a string "invalid" (without quote),otherwise you don't need to print anything for deleting numbers. For the operation type of 2, you have to output an integer, how many times x appears in the array from i to j inclusive.
Example
Input:
7
1 10
1 20
2 20 1 2
0
2 10 1 1
0
0
Output:
1
1
invalid | 33,687 |
WA,RTE and Placements (WRP)
The Placement Season has started at the
Aliens’ College of Machine Learning
(ACM) and as expected, every alien of the college is burning the candle at both ends. William Archer (WA), the topper and the most eligible bachelor of ACM is however indifferent towards the situation. He has been spending all his time with his friend Rihanna the Exuberant (RTE) and ignoring his studies. RTE, being the more mature and sensible of the two, devises a plan for WA so that he could spend adequate time with her without compromising his studies. Upon consultation with her best friend AC, she comes up with the following plan for WA:
She divides WA's next
N
hours into
K
sessions.
Each session can last for
x
hours where x is an
integer
and
1≤ x ≤ M
.
In each session, WA can
either study
or
meet RTE
.
If WA is studying in one session, he must meet RTE in the next session and vice versa.
WA must always study in the first session.
You have been hired by WA to calculate how many different timelines can RTE prepare for the next N hours.
Input
The first line specifies the number of test cases T and the next T lines contain 3 integers each: N, K and M.
Output
For every test case print a single integer which is the number of different ways RTE can prepare WA's timeline for the next N hours. Print your answer
modulo 1000000007
.
Constraints
T ≤ 100
1 ≤ N, K, M ≤ 100000
K ≤N
Example
Input:
3
4 3 2
7 4 3
1 1 1
Output:
3
16
1
Explanation for Sample Input 1
RTE can prepare the following three schedules for the next 4 hours
S | MM | S
SS | M | S
S | M | SS
where S indicates that WA should be studying that hour, and M indicates that he should be meeting RTE that hour.
Note that WA has to start with his studies always in order to satisfy Point 5 of the plan. | 33,688 |
LAZY FRIENDS (GEMS)
Jai and Gopi are best friends. Both of them have a lot of girlfriends although they are nerds!!! One day one of Gopi’s girlfriends came to him and asked him to prove his love for her. Unfortunately Gopi has a meeting with another girlfriend and asks his best friend Jai to help him. Jai with an idea of increasing his girlfriend count accepts immediately. Jai on hearing the task finds it so simple and so asks his junior to complete the task which is you.
You are given a room of length
L
and breadth
B
which is divided into unit cells. In each unit cell there are some gems which amount to a certain value which can be positive, negative or even zero. You are asked to answer
T
queries. Each query consists of a number
N
and you need to collect gems from
N
unit cells such that the value of
N
unit cells when summed up must be maximum. The selection of
N
unit cells in a room of length L and breadth B must be in such a way that it must be a small room of length say some
x
and breadth some
y
provided
x × y = N
. If no such value for x and y exist then print -1.
Input
First line of input contains two space separated integers L and B which denotes the length and breadth of the room.
Following L lines contains B elements in each line each element specifying the value of the gems.
Next line contains T which is the number of queries.
Following T lines contains T elements where each element is the number N.
1 ≤ L, B ≤ 1000
All the L × B elements (x) will be in the range
-100 ≤ x ≤ 100
1 ≤ T ≤ 10
1 ≤ N ≤ 10000
Output
Print the maximum value that can be obtained for each value of N.
Example
Input:
3 4
1 -2 3 -4
-5 6 -7 8
9 -10 11 -12
3
1
5
6
Output:
11
-1
4 | 33,689 |
Roger and tree (RTREE)
Roger is a computer science student who likes connected undirected acyclic graphs, also known as trees. He especially likes solving problems about trees. Recently Roger found a piece of paper with a rooted tree with
'N'
vertices drawn on it (numbered from
1
to '
N
'
). He also found
'Q'
queries on the same piece of paper, where each query was an integer
'
S
'
between
1 to 'N'
. But the paper said nothing about the description of the queries. So he decided to find the longest path of each of the subtree 'S'.
Roger spent two sleepless nights trying to solve this problem efficiently. He is still trying and won't sleep until he knows the answer to each query. Write a program which answers all the queries correctly.
Input
The first line contains an integer 'N', then N-1 lines follow.
Each of the next 'N-1' line contains two integer 'U' and 'V' which means that vertex 'U' and 'V' are connected.
Next line contains an integer 'R' which denotes the root of the tree.
Next line contains another integer 'Q' which denotes the number of queries.
Each of the next 'Q' line contains an integer 'S' between (1 to N).
Output
For each query print the longest path of the subtree 'S' rooted at vertex 'R'.
Output exactly 'Q' lines, each line containing the output of the ith query.
Example
Input:
3
1 2
1 3
1
2
1
2
Output:
2
0
Constraints
1 ≤ N ≤ 10
5
1 ≤ U, V ≤ N
1 ≤ R ≤ N
1 ≤ Q ≤ 10
5
1 ≤ S ≤ N
Like trees? Try the problems:
RTREE2
and
RTREE3
too. | 33,690 |
Interesting Numbers (INUM)
Jack and Jill went up the hill. Jack proposed Jill after reaching at the top of the hill. Jill gave Jack 'N' numbers and asked him to choose a pair of numbers such that their absolute difference is minimum. She also asked him to choose a pair of numbers such that their absolute difference is maximum. Jill wondered just finding maximum and minimum values is mainstream and it will be a cakewalk for Jack, instead she asked him to find number of pairs which have minimum absolute difference and number of pairs which have maximum absolute difference.
Jill will accept Jack's proposal only if he can answer her question correctly. Jack does not know programming. Fortunately Jack had his laptop with him, fully charged and with good internet connection. He mailed you the numbers and asked you to mail him the answers back, as you are known to be a good programmer. Now it's your turn to help him.
Input
First line contains a positive integer 'N'. Next line contains 'N' non-negative integers 'a[i]' separated by a single space.
Output
Print the number of pairs having minimum and maximum difference separated by a single space.
Constraints
1 ≤ N ≤ 10
5
0 ≤ a[i] ≤ 10
15
Sample
Input:
5
5 12 8 1 35
Output:
1 1
Explanation
It's optimal to choose the pair (5, 8) for the minimum difference. So only 1 pair.
It's optimal to choose the pair (1, 35) for the maximum difference. Here also only 1 pair. | 33,691 |
Interesting Selection (ISELECT)
There is a giant circular container which is divided into N segments numbered from 0 to N-1.
Each segment has two bottles, one is a bottle of cold drink and other is a bottle of poison. Drinking from bottle of cold drink increases your energy by A[i] while drinking from bottle of poison decreases your energy by B[i].
The corresponding energies for the same are given in input.
Now as it is circular, so bottles in segment N-1 and segment 0 are adjacent. If you do not drink from bottle of cold-drink, then you have to drink from bottle of poison in that segment. Furthermore you cannot drink from bottle of cold-drink in adjacent segments. You have to drink in such a way so that your energy maximizes. Find this maximum value.
Note: Your initial energy will be 0 and the final maximum energy can be negative.
Input
There will be T test cases and in each test case there will be an integer N which is the size of the container.
Next line contain N integers denoting the first array and the second line also contain N integers denoting the second array.
Output
There will be T lines each containing the output for each test case.
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 10000
1 ≤ A[i], B[i] ≤ 10
9
Sample
Input:
1
3
1 2 3
4 5 6
Output:
-6
Explanation
There are 3 segments and the pairs are (1, 4), (2, 5), (3, 6). The optimal solution is to drink third potion and first two bottle of poison. The answer in this case is (-4 + - 5 + 3 ) = -6. | 33,692 |
Interesting Game (IGAME)
Alice and Bob play an interesting game and the game is played on a number.
So a player, on his chance, can choose any non zero digit of the number and decrease the digit by any non zero amount such that the resulting digit remains non-negative. The player who gets all the digits of the number 0 wins. Both play optimally and Alice starts first. Now tell how many numbers are there between A and B on which if the game is played Alice wins and also find how many numbers are there where Bob wins. On every number between A and B, Alice plays first on that number.
Input
The input line consists of T test cases. On each line there are two numbers A and B.
Output
The output line consists of T lines each having two numbers.
Constraints
1 ≤ T ≤ 10000
1 ≤ A ≤ B ≤ 10
18
Sample
Input:
2
1 10
101 110
Output:
10 0
8 2
Explanation
In the first case the first player Alice will always win because she can reduce any digit to 0.
In the second case the second player Bob will win on 2 numbers 101 and 110. Rest Alice will win. | 33,693 |
Interesting queries (IQUERY)
Students of Computer Science department at NIT Durgapur were becoming extremely bored and frustrated due to too many classes ( weird but we had many classes ). As semesters were approaching, students were preparing hard to get good grades. Everyone was nervous about the Algorithms exam which is going to be held 2 days later. To add to their discomfort, one question came in the exam which took many one by surprise. The question was simple but everyone was told to optimize code as much as possible.
Now its your turn, and the question states that there is initially an array of N non-negative numbers (1-based indexing) and based on that array we have to run Q queries. Now we can do three things in each query. We have to sometimes calculate sum of product of all subsets of a number within a range, sometimes to calculate sum of bitwise AND of all subsets of a number, sometimes to update an element of an array. All the calculations are to be performed modulus (10
9
+7). If we have to do sum of products then the query is given 'M', if bitwise AND then 'A' else if update then 'U'. For more details, see Explanation section .
Note
: bitwise AND operator is defined as & in C, C++ and in most of the languages. For other programming languages see your language documentation.
Input
First line contains N, which denotes the number of elements in an array. Next line contains N integers denoting the number of integers in the array. Then Q denoting the number of queries and after that each line consists of 3 integers. If it is 'M' then we have to do product, if 'A' then bitwise AND and if 'U' then update. If it is 'M' or 'A' then it is followed by i and j which is the range of that array. If 'U' then we have the position and the value to be updated at that position.
Output
Corresponding to each query we have an output only to query of 'M' and 'A'. For update you don't have to print anything.
Constraints
1 ≤ N ≤ 10
5
1 ≤ A[i] ≤ 10
5
1 ≤ Q ≤ 10
5
1 ≤ i ≤ j ≤ 10
5
The element to be updated is of maximum value of 10
5
.
Example
Input:
3
1 2 3
5
M 1 3
A 1 3
U 2 5
M 1 3
A 1 3
Output:
23
9
47
13
Explanation
For 1st query, we do 1 + 2 + 3 + 1*2 + 1*3 + 2*3 + 1*2*3 = 23
For 2nd query, it is 1 + 2 + 3 + 1&2 + 1&3 + 2&3 + 1&2&3 = 9
For 3rd query, it is update so array becomes 1 5 3
For 4th query, it is 1 + 5 + 3 + 1*5 + 1*3 + 3*5 + 1*3*5 = 47
For 5th query, it is 1 + 5 + 3 + 1&5 + 1&3 + 3&5 + 1&3&5 = 13 | 33,694 |
Largest Submatrix (MINSUB)
You are given an matrix M (consisting of nonnegative integers) and an integer K. For any submatrix of M' of M define min(M') to be the minimum value of all the entries of M'. Now your task is simple: find the maximum value of min(M') where M' is a submatrix of M of area at least K (where the area of a submatrix is equal to the number of rows times the number of columns it has).
Input
The first line contains a single integer T (T ≤ 10) denoting the number of test cases, T test cases follow. Each test case starts with a line containing three integers, R (R ≤ 1000), C (C ≤ 1000) and K (K ≤ R * C) which represent the number of rows, columns of the matrix and the parameter K. Then follow R lines each containing C nonnegative integers, representing the elements of the matrix M. Each element of M is ≤ 10
9
.
Output
For each test case output two integers: the maximum value of min(M'), where M' is a submatrix of M of area at least K, and the maximum area of a submatrix which attains the maximum value of min(M'). Output a single space between the two integers.
Example
Input:
2
2 2 2
1 1
1 1
3 3 2
1 2 3
4 5 6
7 8 9
Output:
1 4
8 2 | 33,695 |
Counting Pairwise Coprime Triples (PCOPTRIP)
A tuple of three numbers ($a$, $b$, $c$) is called a
pairwise coprime triple
if $\gcd(a, b) = 1$, $\gcd(b, c) = 1$, and $\gcd(c, a) = 1$.
Let $C(n)$ be the number of pairwise coprime triples which satisfy $1 \le a, b, c \le n$.
For example, $C(3)$= #{(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 1), (1, 2, 3), (1, 3, 1), (1, 3, 2), (2, 1, 1), (2, 1, 3), (2, 3, 1), (3, 1, 1), (3, 1, 2), (3, 2, 1)} = 13.
Given $N$, find $C(N)$.
Input
First line contains $T$ ($1 \le T \le 500$), the number of test cases.
Each line of the next $T$ lines contains a single integer $N$ ($1 \le N \le 100000$).
It is guaranteed that $\sum N \le 100000$ in each input file.
Output
For each number $N$, output a single line containing $C(N)$.
Example
Input
5
1
2
3
10
100
Output
1
4
13
280
282814
Information
There are 5 input files.
My C++ solution runs in 3.04 sec. (in the worst case) | 33,696 |
Special Numbers (Reverse and Add) (REVADD)
A number $N$ is called
special
iff it can be written as
$$
N = \mathrm{reverse}(N_1) + N_1 = \mathrm{reverse}(N_2) + N_2,
$$
where $N_1$ and $N_2$ are some positive integers and their number of digits (lengths) are different.
For example, $121$ is a special number since
$$
\begin{aligned}
121 &= \mathrm{reverse}(74) + 74 = \mathrm{reverse}(110) + 110 \\
&= 47 + 74 = 11 + 110.
\end{aligned}
$$
There are only two special number less than $10,000$.
Find the first 5,000 smallest special numbers.
Input
This problem has no input data.
Output
Output the first 5,000 special numbers in ascending order. (One special number per one line.)
Example
Output:
121
1111
...
[4998 lines]
...
Information
Source Limit is 10 KB. | 33,697 |
Progression (EC_SER)
Let
S
be an infinite sequence of integers:
S
0
=
a
;
S
1
=
b
;
S
i
= |S
i-2
- S
i-1
| for all i ≥ 2.
You have two integers
a
and
b.
You must answer some queries about the n-th element in the sequence
Input
The first line contains
a
and
b
(0 ≤
a
,
b
≤ 10
18
).
The second line contains a integer
q
(1 ≤
q
≤ 100000).
The third contains
q
integers
q
i
.
Output
For each
q
i
you must print a line with the q
i
-th element of
S
.
Example
Input:
21 12
5
0 1 2 3 4
Output:
21
12
9
3
6
Note: the values of q
i
are in the range of 64 bits. | 33,698 |
Square-Free Product (Hard) (PUCMMT02)
Integer X is Square-Free if and only if p
2
(p is prime) does not divide it. For example, 15 is a square-free number but 12 isn't, because 2
2
= 4 is one of its divisors.
Write a program that outputs whether the product of two numbers is a square-free number.
Input
The first line contains T (1 ≤ T ≤ 100), the number of test cases. T lines follow, one per test case. Each of these lines contain two integers
a
and
b
(1 ≤ a, b ≤ 10
18
).
a and b are NOT necessarily square-free
.
Output
Per test case:
Output a single line containing "YES" if the product of
a
and
b
is square-free, or "NO" otherwise. In any case, do not include quotes in your output.
Sample
Input
4
1 1
6 13
10 2
12 1
Output
YES
YES
NO
NO | 33,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.