task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
LIS and tree (LISTREE)
You are given a tree with
N
vertices. Every vertex has an unique number from the interval
[1, N]
. Consider all simple paths on this tree. For every simple path you can write the sequence of numbers taken from consecutive vertices on this path. For every such sequence you can find the
Longest Increasing Subsequence
. Find the longest of all Longest Increasing Subsequences and print its length.
Input
The size of each input file is not greater than 2 MB.
In the first line of the input there is an integer
T (1 ≤ T ≤ 1000)
- the number of data sets.
In the first line of each data set there is an integer
N (1 ≤ N ≤ 10
5
)
.
In each of the next
N - 1
lines of the data set you can find two integers
a
and
b (1 ≤ a, b ≤ N)
meaning that there is an edge connecting vertex with number
a
and vertex with number
b
.
Output
For each data set print one number: the length of the longest LIS of all simple paths.
Example
Input:
2
12
3 1
1 4
4 12
12 8
4 5
5 11
5 6
5 2
3 9
9 10
9 7
12
1 8
8 6
8 3
3 12
3 10
3 5
5 4
5 2
1 9
9 11
9 7
Output:
4
5
One of the solutions for the second tree in the example: | 34,100 |
Queue of Soldiers (AR2015PE)
In a planet far away from Earth, there is a deadly war going on between two countries: Bitland and Byteland. The queen of Bitland has an army of
N
soldiers. She has found a strategy to attack the weakest part of the border of Byteland, but to reach there, the soldiers of Bitland has to form a queue and pass through a very narrow valley. Moreover, there is some defense mechanism set in the valley by Byteland: If any soldier
P
with height
v
passes through the valley, then anybody following
P
with height (strictly) greater than
v
will be killed by automatic firing.
The queen of Bitland is also aware of this scenario, but it is not always possible to send her soldiers according to the non-increasing order of heights (so that no soldier dies). She understands that some soldiers have to sacrifice their lives. To find the best possible permutation, she wants your help to calculate the number of different permutations of the heights of her soldiers so that exactly K soldiers die in that valley. A permutation is
X
different from another permutation
Y
if there exists some
i
(1 ≤
i
≤
N
) for which the height of
i-th
soldier is different in these two permutations.
Input
The first line of input file contains the number of test cases,
T
(1 ≤
T
≤ 20). Then
T
cases follow: Each case consists of two lines. The first line contains two integers:
N
(1 ≤
N
≤ 50000) and
K
(0 ≤
K
≤ 1000). Then the second line contains N integers denoting the heights of the soldiers. There will be at most 100 different values of their heights. There will be at most
1000
soldiers with same height. For 80% of the cases,
N
will be less than 10000.
Output
For each case, print “
Case <x>: <y>
” in a separate line, where
x
is the case number and
y
is the number of permutations such that exactly
K
soldiers die. As the number can be very large, print
y modulo 1000000007
Example
Input:
3
3 1
1 2 3
3 1
1 2 2
3 2
1 2 3
Output:
Case 1: 3
Case 2: 1
Case 3: 2 | 34,101 |
Terrorists (AR2015PC)
Terrorists! There are terrorists everywhere!!! I was shouting out loud after I had watched a few news reports about terrorism acts that had happened around my neighborhoods. I started to think that hiding at home wasn’t a good way to go.
I went to police stations and asked around if I could help them prevent these issues. The police gave me pieces of information about terrorists’ plans. I ended up lying on my bed and figuring way to utilize this information. That is why I come to you.
Our neighborhoods could be illustrated with intersections and roads. Terrorists usually meet up at one intersection before moving to another intersection to perform an illegal act. The given information tells us where they will meet and where they will go. Unfortunately, the certain schedules of those plans are not available and too few policemen are available lately. So, the police will not be able to set up efficient defences to all of those acts. What they could do is set up surveillance cameras to all meet up intersections. Once a meet up is detected, policemen will go to that meet up’s destination to catch the terrorists. The policemen rarely accomplish it because they spend too long time travelling between places. Because terrorists are smart, they always use shortest route to travel between intersections. Because the policemen aren’t that smart, they need our help. For each terrorist plan, the police want us to compute the shortest distance between the meet up place and the destination. If the distance is too short, they will not spend their efforts for free.
Input
The first line of the input contains an integer
T
, the number of test sets
(1 ≤ T ≤ 5)
. Each test case consists of many lines. The first line contains
3
integers
N, M, Q
which are the number of intersections, the number of roads, and the number of terrorists’ plans in respective order.
1 ≤ N ≤ 100 000, N - 1 ≤ M ≤ N + 50, 1 ≤ Q ≤ 50 000
Then the next
M
lines describe the roads in our neighborhoods. A road is described by
3
integers:
U, V, D
.
U
i
and
V
i
represent
2
ends of the road
i
.
Di
represents distance of that road.
1 ≤ Ui, Vi ≤ N, 1 ≤ Di ≤ 10 000
. It is possible that many roads might exist between a pair of intersection. Finally the next
Q
lines are the terrorism plans. A plan
j
is described by
2
integers:
Sj
and
Ej
which are the meet-up intersection and the destination intersection respectively.
1 ≤ Sj, Ej ≤ N
.
Output
For each test set, print out "
Case x:
" where
x
is a case number beginning with
1
, and then followed by
Q
lines. For each terrorism plan, output the shortest distance between the meet-up intersection and the destination of the plan.
Example
Input:
1
7 9 5
7 6 6114
5 3 5473
2 4 2601
5 4 8525
7 3 291
2 7 3363
1 6 399
6 4 4477
1 7 3075
6 3
4 4
3 1
2 3
7 3
Output:
Case 1:
3765
0
3366
3654
291 | 34,102 |
Jumping Joey (AR2015PF)
Please read the problem statement carefully. Mathematical notations and bunch of examples are provided to make the statement friendly.
Once upon a time, there lived a frog named Joey. He has a long pond beside his house. There are lots of lily pads there, and he likes to jump from one pad to another. He hates to wet himself. Let’s help Joey to cross the pond. For the sake of simplicity, let’s assume the pond to be a line segment of length
L
. On this line segment there are
n
lily pads. Let’s enumerate the lily pads from left to right, that is the leftmost pad is number
1
, second one from the left is number
2
and so on. At the beginning Joey is at the left end of the pond. Then he moves to the first pad, then to the second pad and so on. At the end he moves from the nth pad to the right end of the pond. There are two ways he can move, jump and swim. He can jump from one place to another if the distance between these two places is no more than
D
unit. He can swim any times he wants. But as we already said he does not like to wet himself, so we need to minimize the number of times he swims for going from the left end to the right end.
However, the situation is not that simple. There are ropes between every two adjacent places. That is, there is rope between:
Left end and first pad.
Last pad and right end.
Between every two adjacent pads.
Let,
P
i
be the
i
’th pad (
1 <= i <= n
),
P
0
be the left end and
P
n+1
be the right end.
R
i
be the length of the rope
R
i
between
P
i
and
P
i+1
(for
0 <= i <= n
).
P
i
be the position of
P
i
(
0 <= i <= n + 1
). Obviously
P
0
= 0
,
P
n+1
= L
and
P
i
<
P
i+1
,
R
i
>=
P
i+1
- P
i
(for
0 <= i <= n
).
When Joey is on
P
i
he can pull
R
i
and then
P
i+1
moves towards Joey. If the rope
R
i+1
is taut (the length of the rope is equal to the distance between the two pads that the rope is tied with) then this also affects
P
i+2
and
P
i+2
moves toward him as well (and so on). However, if a rope is not taut then it does not affect later pads. Also if the ropes are taut till
P
n+1
then there is no movements of the pads at all (since the right end is fixed, that is
P
n+1
is not movable). Let’s try to clarify these statements by some examples.
Example 1
Let Joey be on
P
2
,
P
2
= 10
,
P
3
= 20
,
P
4
= 30
,
P
5
= 40
. Also
R
2
=
R
3
=
R
4
= 15
. Distance between
P
2
-
P
3
,
P
3
-
P
4
and
P
4
-
P
5
are
10
, but the rope lengths are
15
. So none of the ropes are taut. Now if Joey pulls
R
2
say by
1
unit,
P
3
will shift one unit towards
P
2
(new
P
3
= 19
). But this does not affect
P
4
, because
R
3
was not taut. Let Joey pulls rope
R
2
4
more units (
5
units in total). Then
P
3
= 15
,
P
4
= 30
,
P
5
= 40
. Now
R
3
becomes taut since
P
3
-
P
4
distance is now:
P
4
- P
3
= 30 - 15 = 15
which is same as
R
3
. So now, if Joey pulls one more unit,
P
3
and
P
4
moves together (
P
5
does not, since
R
4
is not taut). So the new positions would be:
P
3
= 14
,
P
4
= 29
,
P
5
= 40
.
Example 2
Let Joey be on
P
0
and
n = 1
. Position of the only lily pad
P
1
is at
P
1
= 10
. Let pond length
L = 20
. By definition
P
0
= 0
and
P
2
= L = 20
. Also let’s assume
R
0
= 10
,
R
1
= 11
. If Joey pulls
R
0
by one unit then:
P
1
= 9
. But now
R
1
is taut. If he pulls
R
0
more
P
1
will not move, because the rope between
P
1
and
P
2
is taut and
P
2
is the right end.
Given all the information, you have to figure out minimum number of times Joey has to wet himself in order to go from the left end to the right end. Please note Joey has to move from one place to the next place (he can’t move backward), so he can’t just wet himself once and swim from the left end to the right end.
Input
First line of the input will be a positive integer
T
(
<= 50
), number of test cases. Test cases are separated by blank lines. Each case consists of 3 lines. First line contains two positive integers
n
(
<= 1,000
) and
D
(
<= 10^9
). Second line contains
n + 2
integers:
P
0
,
P
1
...
P
n+1
. Third line contains
n + 1
positive integers
R
0
,
R
1
...
R
n
. None of the
P
i
and
R
i
will be more than
10^9
. You may assume that all of these given values will satisfy all the constraints in the statement. Please note there may be one or more spaces/new lines separating adjacent lines/numbers.
Output
For each of the tests print the case number and the answer.
Example
Input:
5
1 10
0 10 20
10 10
1 10
0 11 20
11 10
1 10
0 11 20
11 9
1 5
0 10 20
20 20
1 5
0 10 20
20 12
Output:
Case 1: 0
Case 2: 0
Case 3: 1
Case 4: 1
Case 5: 2 | 34,103 |
Automatic Scholarship Calculation (AR2015PH)
A university gives scholarship to students based on their current CGPA. This waiver allocation follows some rules. At the beginning of a semester allotted scholarships for certain CGPA range is put on the notice board in tabular form. Two such tables are shown below:
In the table on the left, it is said that students who have CGPA within 3.60 and 3.69 (inclusive) will get 10% of their tuition fee as scholarship. Similarly, those with CGPA range is within 3.90-3.99 will get 40% of their tuition fee as scholarship. Using the two tables above we will try to explain to you the rules and restrictions of allocating waiver:
A fixed Scholarship is given to all the students within a CGPA Range.
The range of each CGPA slab must be equal (Except the topmost one, which can be smaller).
The slabs must go all the way up to 4.00.
The scholarship percentage for the lowest slab is a positive integer. With the increase of CGPA range the amount of scholarship percentage must also increase by a fixed positive integer value. In the table on the left this fixed value is 10% and in the table on the right this fixed value is 30%.
Scholarship percentage for each slab is always a positive integer with a maximum value of 100%.
The scholarship amount that can give 1 student 1 % scholarship is called a unit. So to give 2 students 50% scholarship, 50*2 = 100 units is needed.
All the scholarships given should use up a given amount, P units.
A CGPA range for scholarship cannot start below 2.50. So 2.50-2.55 is a valid CGPA range but 2.45-2.55 is not valid.
There must be at least 2 slabs for scholarship. But of course a slab can contain zero students.
Given the number of students, total available scholarship units and their current CGPA, your job is to find out the number of different possible scholarship allocations that uses up all the scholarship units. Two scholarship allocations are different if their CGPA range is different or scholarship allocation in any slab is different.
Input
Input file contains at most 100 sets of inputs. The description of each set is given below:
Each set starts with two integers
N
(N <= 10000) which indicates the total number of students and
P
which indicates the scholarship units that needs to be used up. Each of the next
N
lines contains the CGPA of one student.
Input is terminated by a line containing two zeroes.
Output
For each test case produce one line of output which contains an integer D. This D denotes the total number of different scholarship allocations that uses up all P units. Input will be such that there will always be at least one possible allocation.
Example
Input:
10 410
3.29
3.96
2.61
2.82
3.93
3.68
3.70
2.91
3.28
3.68
0 0
Output:
79554
Explanation:
a = 10, d = 10, lowest = 2.88, nslab = 8, wslab = 14
One possible solution to the sample input above is:
CGPA Range
Number of students
Waiver %
Total Units needed
3.93 - 4.00
2
80
160
3.78 - 3.92
0
70
3.63 - 3.77
3
60
180
3.48 - 3.62
0
50
3.33 - 3.47
0
40
3.18 - 3.32
2
30
60
3.03 - 3.17
0
20
2.88 - 3.02
1
10
10
Total Units
410
There are another 79553 different allocation which uses up all 410 units exactly. | 34,104 |
Game of Squares (VECTAR11)
Changu and Mangu are playing a game. They are given a number n. They make moves in turn, Changu playing first. Each move consists of subtracting a perfect square(not less than 1) from the number, the player who faces 0 loses. You are given a number n, you have to find out whether Changu can win the game, if both Changu and Mangu play optimally.
Input
The first line contains T (not more than 10
5
), the number of test cases. The next T lines contain a number n (not more than 10
6
).
Output
For each test case output "Win" if Changu can win the game, if he plays optimally or else print "Lose"
Example
Input:
3
1
2
3
Output:
Win
Lose
Win | 34,105 |
Gupta ji Birthday !! (SHUB1307)
It's the 13th of July and it's Shubham Gupta's Birthday. Shubham loves to solve DP problem. Anuj (Shubham's friend) want to wish him uniquely. So he decorate their hostel room number 235 where the floor is divided into
N × M
square tiles, forming a grid with N rows and M columns.
Each square in the grid contains a number of vodka shots that Shubham has to drink if he steps on a particular tile. Shubham enters the room on (1, 1) and has to makes his way to the exit gate on (N, M), drinking the vodka on the way. From the current cell, he can move only to the adjacent cell in East, South or South-East direction i.e. from (i, j) to either (i, j+1) , (i+1, j) or (i+1, j+1).
However, his capacity for the vodka is limited. If he drink more than
K
shots, he will be out of control! Help him find a way to drink as any many shots as he can, without going out of control.
Input
The first line contains
T
.
T
test cases follow.
First line of each test case contains 3 space-separated integers,
N, M, K
.
Each of the following
N
lines contain
M
space-separated integers, describing the grid.
Output
Print the maximum number of vodka shots that he can drink without going out of control or "-1" (without the quotes) if it can not be done i.e. if there does not exist such a path. Print the answer to each test case on a new line. .
Constraints:
1 ≤ T ≤ 10
1 ≤ N, M ≤ 100
1 ≤ K ≤ 500
1 ≤ Values in the Grid ≤ 50
Example
Input:
2
3 3 7
2 3 1
6 1 9
8 2 3
3 4 9
2 3 4 1
6 5 5 3
5 2 3 4
Output:
6
-1
Explanation
In the first test case, he can move on squares (1, 1) , (2, 2) and (3, 3) to complete his journey with 6 shots. In the second test case, every possible path leads to the drinks of more than 9 shots. | 34,106 |
Garden of Mangu (VECTAR12)
Mangu bought a new garden for himself. The garden is shown below in the image. The garden is semi infinite i.e. infinite in two directions (+x direction and +y direction). Garden's square cells are indexed as in the diagram. Changu comes to visit Mangu and see his garden. He is standing initially on (0, 0). From a particular cell he can travel in 8 directions if possible. His task is to go from (0, 0) to (n, k) in n steps. Your task is to calculate the number of possible paths he can take.
Input
The first line contains the number of test cases, T. The next T lines contain two integers n and k separated by a single space.
Output
You have to print the number of possible paths modulus 1000000007.
Example
Input:
2
1 1
2 0
Output:
1
2
Explanation
The possible paths for two case are shown below:
Case 1:
Case 2:
Constraints:
T<10^5
0<=N<7000
0<=K<=N | 34,107 |
Bono v3 (BLBONO)
Kang and Kung are board games enthusiast. However, they only like to play deterministic games, such as chess. Since there are only a few deterministic games, they decided to create a new one. This game is called 'Bono'.
The rule of Bono is simple. The board consist of a 3x3 grid. The game is turn based with 2 players. On each turn, the current player must fill an empty cell with a piece of water spinach. Players may not move any water spinaches that have been placed. The board will destroy itself if there is a row or column or diagonal consisting of 3 pieces of water spinach. A player loses if he can't make a move in his turn.
Of course, the first player will always win the game if he plays optimally. That is why they created Bono v2. In Bono v2, the number of boards used in a game is N (N
<
1000). On each turn, the current player must fill an empty cell on an undestroyed board with the same ruling as Bono. A player loses if he can't make a move in his turn.
Bono v2 is still too easy since if they both play optimally, player 1 will always win if N is odd, and player 2 will always win if N is even. To solve this matter, Bono v3 is created. In Bono v3, the initial state of each board might not be empty. Some cells might already be occupied with a piece of water spinach. Other than that, the rules are same as Bono v2.
Kang and Kung decide to play Bono v3 T times (T
<
1000). Kang always moves first and they both play optimally. For each game, who will win?
Input
First line of input is T, the number of games (T
<
1000).
For each game, first line is N, the number of boards (N
<
1000). Next N lines consists of the starting boards. A board is represented with a 9 digit binary string. Cell in (r, c) position is represented by (r-1)x3+c th character in the string. 0 means the cell is empty, 1 means the cell is filled.
Output
For each game, output a line containing the winner's name.
Example
Input:
3
1
000000000
2
000000000
000000000
2
100010000
001010000
Output:
Kang
Kung
Kung | 34,108 |
Legend of Heta (BLHETA)
Heta is a conventional name for the historical Greek alphabet letter Eta (Η) and several of its variants, when used in their original function of denoting the consonant /h/ (Wikipedia). Because of whispers of N'Zoth the corruptor, Heta now wants to destroy all existing alphabets (fiction).
Heta has a spell book containing spells to delete a string. There are several spells in that book. Armed with the spell book, Heta starts his journey to complete his mission. On his way, Heta found a very long string. To delete that string, Heta reads that string letter by letter from the first letter. If at any point he found a substring that's present in his spell book, that spell will be cast and that substring will be destroyed. Then he continues until he reach the end of that string and no more spell can be used. If there are multiple spells that can be used in one time, the spell that appears first in the book is used. Determine what's left of the very long string after Heta is done!
Input
First line is a string containing A-Z. String can contain from 1 to 100000 characters. Next line of input is N, the number of spells in the spell book (1 ≤ N ≤ 100). Next N lines contain spells sorted by appearance in the spell book. Each spell is a string containing A-Z with a length from 1 to 100.
Output
One line containing the string after Heta is done doing his magic.
Example
Input:
KUKUKAKIKUKAKEKKUKAKAKKUKAKUKAKU
2
KEK
UK
Output:
KAKIKAKAKAKKAKAKU
Input:
HEATHLEDGER
2
HEATH
LEDGER
Output:
Input:
KAPKAPPAPAK
1
KAPPA
Output:
K
Input:
CABAI
3
ABA
AB
B
Output:
CAI | 34,109 |
Unique Code (BLUNIQ)
In Lapak City, every tourist is given a unique code based on their favorite number. If their favorite number is already used as a unique code, that tourist will be given the smallest unused unique code that is larger than his favorite number. For example, a tourist with 42 as his favorite number visits Lapak City. However, unique code 42 is already used. So that tourist is given the unique code 43. If 43 is also used, then that tourist is given the unique code 44, etc.
Every tourist that leaves Lapak City will delete their unique code, that means their code can be used for other newcomer if needed. Continuing the previous example, if the tourist with unique code 43 left Lapak City, and a tourist with favorite number 43 enters, that new tourist will be given the unique code 43.
Initially, all code is unused and no tourist is in Lapak City. On one day, there are N tourist event on Lapak City. Help Lapak City to determine unique code for the tourist.
Input
First line of input is N, the number of event (1 ≤ N ≤ 100000). Next N lines contain the events. For every tourist that visits Lapak City, the input is "1 x", with x is the favorite number of that tourist (1 ≤ x ≤ 1 000 000 000). For every tourist that leaves Lapak City, the input is "2 x", with x is the unique code of that tourist.
Output
For each visiting tourist, output their unique code.
Example
Input:
5
1 42
1 42
1 43
2 43
1 42
Output:
42
43
44
43 | 34,110 |
Painting Hat (BLCONE)
In preparations for Joffrey's birthday party, his mom, named Cersei, assigns her employees to paint the hats to be used in the party. Each hat is cone shaped with height H and radius R. Cersei and her employees then go to the store to buy the paint. Since there is no container for the paint, all bought paint will be stored inside each hat.
Here is how the paint is stored:
It is known that 1 unit of paint volume is enough to paint exactly 1 unit of hat area. To be as efficient as possible, all bought paint must be used to paint the hat. Each hat will be filled with paint until it reaches a height h. All the paint inside the hat must be used to paint that hat inside and out (ignore depth). Part of the hat that have been submerged in paint don't need to be painted. If the hat can't contain enough paint, it's filled until it's full.
Input
First line is N, number of birthday parties (1 ≤ N ≤ 10000). Next N line contains the hat used in each birthday party, containing 2 integers R and H (1 ≤ R, H ≤ 100)
Output
For each birthday party, output h, the height of paint that Cersei bought. Output until 6 digit after decimal point.
Example
Input:
3
4 6
6 4
2 10
Output:
5.874692
3.916461
10.000000 | 34,111 |
Emoticon (BLKEK)
When internet become popular, instant messaging is used by many people. Legend says that chat used to not be able to send image or stickers. So, users that want to express themself with more than word will have to use something called "smiley" or "emoticon" (it's called emoji now). Example of emoticons are :), :(, :v, XD, and :p.
Some people don't like that kind of emote because they have to be rotated, so they used something like ^_^, T_T, x_x, and >=< (it's a giant enemy crab). Creativity rises as times passed, and emoticon starts using weird symbol that's not on a typical keyboard like ( ≧Д≦), (ノಠ益ಠ)ノ彡┻━┻, ( ͡° ͜ʖ ͡°), щ(゚д゚щ), and (っ˘ڡ˘)っ─∈. With hard to type emotes, some chatting site use word replace to change word into picture. For example, if someone types "Kappa" the site will change it to
.
Henrik plans to create a chatting site that changes "KEK" to
.
To increase that emote's appearance, Henrik will change every message containing the subsequence "KEK". For example, if someone types "BUKAHEHELAPAK" it will be changed because the subsequence "KEK" exists in that message. Henrik wants to know how many ways he can take the subsequence "KEK" in a message. For example, in "BUKAHEHELAPAK" there are 2 ways to get the subsequence "KEK", using the bold letters in "BU
K
AH
E
HELAPA
K
" and "BU
K
AHEH
E
LAPA
K
".
Input
First line is N, number of messages that need to be processed (N ≤ 1000). Next N line each contains a string containing the letter A-Z not more than 2000 letters in length.
Output
For each message, output the number of way subsequence "KEK" can be obtained.
Example
Input:
3
BUKAHEHELAPAK
KEKEK
KKE
Output:
2
4
0 | 34,112 |
Changu Mangu in a Football Team (VECTAR13)
Changu and Mangu are part of a football team which is going to participate in a tournament. In the tournament there are n teams in total. Each team plays twice against every other team (home and away fixture). The team that wins, is awarded 3 points. The team that draws, gets 1 point, while the team that loses gets no points.
At the end of the tournament, the teams are ranked 1 to n according to total points. The rank of each team
t
having
p
points is one plus the number of teams having more than
p
points. It is possible that more than one team have the same ranks.
In addition to the team that has rank 1, the
Lucky
team is also awarded, if it exists. The
Lucky
team is the one that has absolutely the highest number of wins (absolutely means no other teams has the same number of wins), absolutely the highest number of goals scored, and absolutely the lowest number of goals conceded, is called the
Lucky team.
(
Lucky
Team should have all these properties.)
Changu keeps dreaming about being a part of the Lucky team. Your task is to find out the worst possible rank for the
Lucky
Team.
Input
The first line contains T, the number of test cases. The next T lines contain a number n, the number of teams participating in the tournament.
Output
For each test case, print on a separate line, the worst possible rank for the
Lucky
Team
Example
Input:
2
1
3
Output:
1
1
Constraints:
T <= 10^5
1 <= N <= 10^18 | 34,113 |
Divisible Fibonacci Numbers (DIVFIBS2)
The Fibonacci sequence is defined by :
f
n
=
n
for
n
< 2, and
f
n
=
f
n-1
+
f
n-2
for
n
> 1.
f
= (0, 1, 1, 2, 3, 5, 8, ...)
You have to count how many terms are divisible by a given integer in the beginning of the sequence.
Input
The first line of input contains one integer:
T
the number of test cases.
On each of the next
T
lines, your are given
three integers:
a
,
b
, and
k
.
Output
For each test case, you have to print the number of term
f
n
that are divisible by
k
, for
n
in [0..
a
b
].
As the result may be a big number, simply output your result modulo 10
9
+7
Example
Input:
3
3 2 3
2 3 8
9 1 6
Output:
3
2
1
Explanation: For the first case,
a
b
= 3
2
= 9, and the terms with rank 0 to 9 are :
0
, 1, 1, 2,
3
, 5, 8, 13,
21
, 34.
There are
3
numbers divisible by
k
=3.
Constraints
0 < T < 10^4
0 < a < 10^18
0 < b < 10^18
1 < k < 10^18
To give more interest in the best part of the problem,
you can assume that the maximum prime factor of
k
is less than or equal to 10
6
.
Time limit is approx 4x the time for my 1.4kB PY3.4 submission (based on my old code for problem ??? you should find).
Good luck, and have fun ;-)
Edit(2017-02-11) : New time limit (after compiler changes). | 34,114 |
Changu with subsequences (VECTAR14)
Changu likes to play with string and subsequences. He has thought of a puzzle for you. Can you answer him?
He gives you a sequence of '(' and ')'. Your task is to find out the number of its
different subsequences
that are regular bracket sequences.
For example, the sequence “()()” has 3 such subsequences: “()()”, “()”, and “”. As the number can be large, you have to output answer modulus 1000000007.
Input
The first line contains T, the number of test cases. T lines follow, each containing a sequence of '(' and ')'.
Output
For each test case, print the required answer.
Sample
Input
2
()
()()
Output:
2
3
Constraints
T < 10
0 < |S| <= 1000 | 34,115 |
Counting Words (REDRONESIA)
On the islands of Redronesia, there are many languages spoken. Each language is made up of a number of words. And some of the islands are very particular about how the words are formed in their language.
Each language specifies how long a word can be, and how many letters there will be in the alphabet. But they all insist:
that each letter in the word must be at least as big as the previous letter
that doubles of any letter are allowed, but 3 or more of the same letter are not allowed.
The aim of the problem is to count the number of possible words. Since the number may be large, please give the answer mod 1000000007.
As an example, on the island of Imosua, they have an alphabet of 4 letters (we'll call them a, b, c and d), and 6 letters in each word. The following words are not allowed on Imosua:
aabbc (not 6 letters long)
aabbab (each letter is not at least as big as the previous letter)
aaabbc and aaaabc (triples and longer are not allowed)
Some of the 10 allowable words are:
aabbcc
aabcdd
bbccdd
Input
The first line of input contains one integer: T the number of test cases.
On each of the next T lines, your are given two integers: S (the length of each word) and C (the number of characters in the alphabet).
Output
For each test case, you have to print the number of possible words.
As the result may be a big number, simply output your result modulo 10^9+7
Example
Input:
3
6 4
6 3
6 2
Output:
10
1
0
Constraints
1 < T < 100
1 < S, C < 500 | 34,116 |
Zeros in Fibonacci period (Z124)
Perhaps the first thing one notices when the Fibonacci sequence is reduced mod
p
is that
it seems periodic.
For example :
F (mod 2) =
0
1 1
0 1 1 0 1 ...
F (mod 3) =
0
1 1 2
0
2 2 1
0 1 1 2 ...
F (mod 5) =
0
1 1 2 3
0
3 3 1 4
0
4 4 3 2
0
2 2 4 1
0 1 1 2 3 ...
We define
Z
(
p
) the number of zeros in fundamental period of Fibonacci numbers mod
p
(if it is periodic).
We just saw that
Z
(2) = 1,
Z
(3) = 2, and
Z
(5) = 4.
Input
The first line contains
T
, the number of test cases.
Each of the next
T
lines contains a prime number
p
.
Output
For each test case, print
Z
(
p
), or "Not periodic." without quotes if need.
Example
Input:
3
2
3
5
Output:
1
2
4
Constraints
1 < T < 10^5
1 < p < 10^18, a prime number
There's two input files, in the first one you are given all primes under 10^6, in the second one lot of uniform randomly chosen primes.
Warning
: Time limit had been changed, and could not allows slow languages to get AC here. This problem allows easy coding using languages without bigNum library, but you need to be able to get at least some few points at
FIB64
.
My best C-timing is 0.12s. (Edit : 0.03s with cluster change)
For other languages, take a look at
Z124H
with higher constraints.
Good luck, and have fun ;-) | 34,117 |
Police Men (POLICEMEN)
There is a country of
n
cities and
n-1
bidirectional roads you can go from any city to another using its roads
You are a police man and there is a theif who is going to escape from the country using an airport in city 1 you are given
m
queries which of type "
a b"
which means the thief is in city
a
and you are in city
b
you should find if it's possible to catch him before he escape or not and find the city which you will catch him in if it's possible.
You are moving at the same speed the thief moving at and the thief is taking the shortest path to city 1.
If you arrived in a city in the same time as the thief you can catch him in it if you arrived before him you can wait for him.
If there is more than one city you can catch him in print the nearest one to you.
Input
The first line contains an integer
n
(
1
≤
n
≤
10
4
) then
n-1
lines each contains two integers which means there is a road between city
u
and
v
Then an integer
q
(
1 ≤ q
≤
10
4
)
and
q
lines of form a b (
1 ≤
a , b
≤
n
) which are the thief's position and your position.
Output
For each query print YES then a space then the city which you will catch him in if it's possible otherwise print NO.
Example
Input:
5
1 2
1 3
2 4
4 5
4
1 2
1 1
5 4
2 3
Output:
NO
YES 1
YES 4
YES 1 | 34,118 |
Bidding Game (BIDGAME)
Alice and Bob are two of the richest businessmen in the city. Both of them have a passion for antique collection. So much so that they always compete with each other regarding who can collect more antiques.
There is a news about a fresh new collection of valuable antique items have arriving in the city. These items will be sold in an auction coming Friday. Both Alice and Bob are going there as well.
There will be N items sold in the auction one after the other. Each item has a starting bidding price S and a target price T. The first bidder needs to bid a higher price than the S. Next bidder will bid a higher price and it will go on like this until the price reaches at least T. In such case the last bidder wins that item. Then bidding of the next item starts.
There is however one more restriction regarding how much any of them can increase the bidding. If the latest bid is B, then the bidder has to increase the price by at least L%, but can not increase the bid by more than H%. For the first bid the increase in bid is counted against the starting price S. The bid amount must always be an integer.
As there is no other person as rich as Alice and Bob the bidding is only limited between them. Alice starts the bidding with the first item and then bidding continues by turn between Alice and Bob. The last bidder for an item (i.e. the winner of an item) would bid second for the next item.
If both Alice and Bob bid sensibly to win most items, you have figure out who will win most items among the N items. If both win the same number of items, then it is a draw between them.
Input
The first line contains an integer representing number of test cases to follow.
Each test case starts with line containing 3 integers, N, L, and H. Here L is the minimum increase in bid amount and H is the maximum increase in bid amount. Both L and H are represented as percentage.
Next N lines represent the starting bid and target bid of N items. Each of those lines contains two integers S and T where S is the starting price and T is the target price.
Output
For each test case print a single line with the name of the winner "Alice" or "Bob". If both of them wins the same number of items then print "Draw".
Constraints
Test <= 100
N <= 100
10 <= S <= 100
100 <= T <= 100000
S <= T
10 <= L < H <= 50
H - L >= 10
Example
Input:
3
1 10 50
100 150
2 10 50
100 120
100 130
3 10 20
100 120
100 130
100 150
Output:
Alice
Draw
Alice
Problem Setter: Md Imrul Hasan. Used in Eid 2016 contest. More about Eid 2016 contest:
Click Here | 34,119 |
Even Frequency (EVENFRQ)
Kutus loves even number. Girl friend of Kutus, name Putus makes an interesting problem for Kutus to testing his even number knowledge. Putus gives an integer array A, consisting of N number.
Putus asked Kutus to process the following three types of queries on this array accurately and efficiently.
0 X V: add V to the Xth element of array. i.e. AX = AX + V.
1 L R V: replace all the element in range L to R with V.
2 L R: Find out whether all elements frequency in the range L to R is/are even or not
Input
Input start with an integer T, which denotes the number of test case. Each case contains 2 space separated integer N and Q denoting the size of array A and the number of queries to be performed.
Next line contains N space separated integers denoting the elements of array A. Each of the next Q lines of input contains a query having one of the mentioned three types. There will be no more than fifty update operation (type 0 and type 1).
Output
For each case print the case number and print the answer. If all elements frequency in the range L to R is/are even, then answer will be ‘Yes’ otherwise answer will be ‘No’.
Constraints
T <= 10
1 <= N <= 100000
1 <= Q <= 100000
0 <= Ai , V <= 100000
1 <= L <= R <= N
Example
Input:
1
5 6
1 2 2 3 2
2 2 3
0 5 1
2 2 5
2 1 5
1 1 3 2
2 1 5
Output:
Case 1:
Yes
Yes
No
No | 34,120 |
Happiness (HAPPINESS)
You are given an array on N elements a[1], a[2], a[3], ... a[N].
Now you will have to answer some queries.
In every query, you will be given an interval, [l, r]. For this interval you have to print the total summation of happiness of all the elements of the given array between the interval [l, r].
The happiness of an element a[i] between interval [l, r] is: the number of sub-array [l
j
, r
j
] where the minimum value between [l
j
, r
j
] is equal to a[i]. Here,
l <= l
j
<= i and i <= r
j
<= r.
Now, you have to print the total summation of happiness of all the elements between [l, r].
Input
The first line of the input contains the number of test cases T. The first line of each test case contains two numbers, N and M. N is the number of elements in array a and M is the number of queries you need to perform.
The next line contains N integers, the array a: a[1], a[2], a[3], ... a[N].
Next M lines contains two integers, l and r.
Constraints
1 <= T <= 5
1 <= N, M <= 50000
1 <= a[i] <= 1000000000
1 <= l <= r <= N
Output
For each test case, you need to print the case number on the first line in this format: Case X: where X is the case number.
In the next M lines, you need to print the total summation of happiness of all the elements between [l, r] of the given array.
Example
Input:
2
5 2
1 3 2 4 3
1 3
2 4
5 2
5 3 7 6 8
1 4
2 5
Output:
Case 1:
6
6
Case 2:
10
10
Problem Setter: Raihat Zaman Neloy. Used in Eid 2016 contest. For more about Eid 2016 contest:
Click Here | 34,121 |
Again Eid Salami (EIDSALAMI2)
Mahbub has N-1 cousins. Mahbub is the oldest among them. Now they come to their uncle for "EID SALAMI". But they decided that the older one will strictly get more money than the younger. But their uncle has another plan. He told them that he will give them an amount of money and they have to tell them how many ways they can collect money so that the elder gets more money than the younger and they have to take all the money.
As they have to meet with their other relatives, so they come to you, as they know that you are a great programmer, and if you can solve their problem they will give you some SALAMI :)
Input
Input starts with an integer T, denoting the number of test cases.
Each case starts with a line containing two integers M and N. M denotes the amount of money their uncle wants to give them. N denotes the number of cousins of Mahbub (including himself).
Output
For each case, print the case number and the total number of ways. As the result can be very big, you need to output the answer module 10^9 + 7 (1000000007). See the samples for exact formatting.
Constraints
1<=T<=100
1<=M<=1000000
2<=N<=1000000
M*N <= 1000000
Example
Input:
2
40 3
12 3
Output:
Case 1: 114
Case 2: 7
Problem Setter: Raihat Zaman Neloy. Used in Eid 2016 contest. For more about Eid 2016 contest:
Click Here | 34,122 |
Binary Protean Number (BINPRNUM)
Little Rumon is an enthusiast lad. One day while he was exploring the basement of their house for old garbage to find out any usable tool, he suddenly found an interesting device which had a display and a button. He found that if the button is pressed for t seconds, t random binary digits are displayed.
It always had two property:
The binary number generated has no leading zeros.
There are no consecutive 1’s in the number.
Suppose, t = 4, then the possible outcomes are 1000, 1001, 1010.
Rumon instantly rushed to his elder brother Shovon to show him what he had found. After testing the device, Shovon also got interested because the device was generating some number that is equal to the decimal representation of some Cricket South African player’s jersey number.
As for example, the device generated 1, 10001 and 1000 respectively which decimal representations are 1, 17 and 8, which are Hashim Amla, AB de Villiers and Dale Steyn’s jersey numbers respectively.
They started to call such numbers “Binary Protean Number”.
By the time, Rumon wondered if he writes down a binary protean number on a paper, what will be it’s position in all possible binary protean number’s sorted list.
Shovon wanted to write a C program to answer Rumon’s question, but then he thought that there is an upcoming Programming Contest arranged by “Programming Problem in Bengali” Facebook group. So he decided to set it as a programming problem.
Now it’s your job to help little Rumon.
Formally, given K’th Binary Protean Number, you have to find the value of K.
Input
The first line of the input file contains an integer T. 1 ≤ T ≤ 75000. Then follows T cases. Every case consists of one line. The line contains a Binary Protean Number. It has no leading zeros and no consecutive ones in it. If the length of the Binary Protean Number is L then 1 ≤ L ≤ 90.
Output
For every case, you should output a line containing the case number and the value of K. The output format is: Case X: K Where X is the case number. It is guaranteed that K will fit in 64 bit long long integer.
See Sample input/output section for better understanding.
Sample
Input:
3
1
100
1010
Output:
Case 1: 1
Case 2: 3
Case 3: 7 | 34,123 |
Votka and String (VOTAS)
Votka loves string very much. Recently he learned prefixes and suffixes. A prefix of a string S is any leading contiguous part of S and a suffix of string S is any trailing contiguous part of S, e.g., the prefixes of string “abc” are { “a”, “ab”, “abc” } and the suffixes are { “abc”, “bc”, “c” }. Votka considers a suffix Si of string S beautiful, if Si has at least b prefixes which are also prefixes of S.
Formally,
let, P = the set of prefixes of the string S
Pi = the set of prefixes of the suffix Si
Then, Si is a beautiful suffix if |P ∩ Pi| ≥ b.
For example, consider S = “abcabcd” and b = 3, then suffix S3 i.e. “abcd” is a beautiful suffix because it has 3 (≥ b) prefixes { “a”, “ab”, “abc” } which are also prefixes of S. Note that, S itself is a beautiful suffix for all b ≤ |S|.
Now Votka thinks about a problem. The problem is, you are given a string S and m numbers {K1, K2, … , Km }. For each number K
i
, you have to find the number of beautiful suffixes of S considering b = K
i
.
Votka announces that he will give a treat to the first solver of this problem. Luffy, a close friend of Votka, wants to have that treat. As Luffy is very dumb, he asks for your help. Can you help him? :)
Input
Input starts with an integer
T (≤ 10)
, denoting the number of test cases. The first line of each case contains a string
S (1 ≤ |S| ≤ 100000)
. S contains only lowercase English letters. The next line contains an integer
m (1 ≤ m ≤ 100000)
. The following line contains m space separated integers K1, K2, … , Km
(0 ≤ K
i
≤ 100000)
.
Output
For each test case, print m space separated integers (number of beautiful suffixes of S considering b = K
i
) in a single line. (Caution: Dataset is large. Use faster I/O. )
Sample
Input:
2
abcabcd
3
3 7 8
aaaaa
5
1 2 3 4 5
Output:
2 1 0
5 4 3 2 1 | 34,124 |
Zeros of the fundamental Fibonacci period (Z124H)
Perhaps the first thing one notices when the Fibonacci sequence is reduced mod
p
is that
it seems periodic.
For example :
F (mod 2) =
0
1 1
0 1 1 0 1 ...
F (mod 3) =
0
1 1 2
0
2 2 1
0 1 1 2 ...
F (mod 5) =
0
1 1 2 3
0
3 3 1 4
0
4 4 3 2
0
2 2 4 1
0 1 1 2 3 ...
We define
Z
(
p
) the number of zeros in fundamental period of Fibonacci numbers mod
p
(if it is periodic).
We just saw that
Z
(2) = 1,
Z
(3) = 2, and
Z
(5) = 4.
Input
The first line contains
T
, the number of test cases.
Each of the next
T
lines contains a prime number
p
.
Output
For each test case, print
Z
(
p
), or "Not periodic." without quotes if need.
Example
Input:
3
2
3
5
Output:
1
2
4
Constraints
You have four input files. The first two ones are those of
Z124
, the two others have higher constraints.
1 < T < 10^4
1 < p < 10^100, a prime number
Time limit is 2 times my unoptimized PY3.4 code time.
Good luck, and have fun ;-) | 34,125 |
Laser (LAS)
There is a grid with
n
rows and
m
columns, consisting of 1x1 squares. There is exactly one square with a laser and one (different) square with a sensor. The laser emits a beam of concentrated light from the middle of its square, in one of the four directions (north, south, east or west). Some squares are blocked, so they don't let the light through. (In that sense, square with a laser is also considered blocked).
We have a number of two-sided mirrors. We can place them on the middle of a square, in one of the two configurations (45 degrees). Mirrors placed in such a way reflect the light, making a right angle (90 degrees).
Your task is to guide the light to the sensor, using the minimum number of mirrors.
Input
The first line contains a single integer
t
, denoting the number of test cases. Then, testcases follow.
The description of a single test case begins with two integers
n
,
m
(1 ≤
n
,
m
≤ 200) - number of rows and columns, respectively. Then,
n
lines follow, each containing
m
characters.
j
-th character in
i
-th line denotes a square in
i
-th row nad
j
-th column. "." (a dot) denotes free square, "#" denotes blocked square. There is exactly one laser on the grid, represented by one of these four characters: "<", ">", "v" or "^" (it depends on the direction of the laser). There is also exactly one sensor, represented by "C". No other characters can appear in a line.
Output
For every testcase you should print
n
lines with
m
characters, denoting the grid from the input, but with mirrors placed on some of the fields. Mirrors are represented by "\" and "/" characters. Arrangement of mirrors should make the light reach the sensor, while using minimum possible number of mirrors. You can't place mirrors on blocked fields, as well as on field with the laser and on field with the sensor. There is always a way for the light to reach the sensor.
Example
Input:
2
3 4
>...
###.
C...
5 5
v#...
.#.#.
.#.#.
.#.#.
...#C
Output:
>..\
###.
C../
v#/.\
.#.#.
.#.#.
.#.#.
\./#C | 34,126 |
Domino's effect (DOM)
Dominik "Domino" Domański is a scientist. He's conducting research on quantum physics. Lately, he started taking a closer look at certain very interesting effect, which can be observed when some quantum objects interact.
In his next experiment, he placed
n
infinitely thin lines on the table, perpendicularly to the surface, in a row. Lines have different heights, distances between the lines can also differ. (Dominik calls these lines "domino tiles"). Looking from the front, they look like
n
segments, standing vertically on the X axis of the Cartesian coordinate system.
Domino tiles can be toppled. If a tile has a height of
h
, it will topple other tiles at most
h
units away. More precisely, if tile is placed at the position
x
, and is knocked over to the right, it will topple the tiles placed at positions
x
+1,
x
+2, ...,
x
+
h
. If this tile is knocked over to the left, it will topple the tiles at positions
x
-1,
x
-2, ...,
x
-
h
.
Dominik observed a very interesting phenomenon, which he called "Domino's effect" - toppling one domino tile can cause other tiles to topple, which can in turn topple other tiles. He started to wonder how to take advantage of this effect in a best possible way. What is the minimum number of tiles that need to be toppled, in order for all the dominoes to fall?
Input
The first line contains a single integer
t
, denoting the number of testcases. Then, testcases follow.
The description of a single testcase begins with a single integer
n
(1 <=
n
<= 1000) - the number of domino tiles in an arrangement.
It is followed by
n
integers
h
i
- heights of subsequent tiles.
It ends with
n
-1 integers
d
i
- distances between neighboring tiles.
(1 <=
h
i
,
d
i
<= 10
6
).
Output
For every testcase you should find a sequence of domino tiles, that will knock down the whole arrangement. It should begin with an integer
k
(1 <=
k
<=
n
), denoting the number of tiles to be pushed. Then, descriptions of moves should follow. One move is described by one integer
x
i
(1 <=
x
i
<=
n
) and one letter (either L or P). It means that during the
i
-th move, we topple a tile number
x
i
(counting from 1, according to original arrangement). L means that we knock it over to the left, P means knocking over to the right.
The sequence should knock over all the tiles, while using as few moves as possible.
Example
Input:
1
6
1 5 1 1 1 1
2 1 2 1 1
Output:
2
2 P
1 L
Explanation
First we topple the domino tile number 2 (of length 5) to the right, which knocks over everything to the right of that tile. Then, we topple tile number 1 - the only one that remains. | 34,127 |
Greatest Common Divisor Of Three Integers (GDCOFTI)
It is said that the greatest common divisor (GCD) of two or more whole integers, is the largest integer that divides them without leaving residue. Euclid's algorithm is famous for allowing to find the GCD between two integers. This challenge asks you, you find the GCD between three integers.
The entry consists of 3 whole non-negative integers (< 2
64
), one per line and the output will be the GCD of the three integers.
Examples
Input:
426
132
120
Output:
6
Input:
100
60
120
Output:
20
Input:
4
8
12
Output:
4 | 34,128 |
Inquire (UFPR14D)
(EN:)
Every tourist visiting our city must visit the May 4 avenue. There are
N
houses, numbered from 1 to
N
. There are
P
i
people living at house
i
.
The statistic institute is proceeding with the survey this year. They will make many queries about the avenue's population. For each query, two numbers
A
and
B
, with
A
<=
B
, are given. You must determine the total number of people living in all houses from house
A
to house
B
, inclusive.
Input
First line contains the number
N
(1 <=
N
<= 10
5
). Second line contains
N
integers
P
1
,
P
2
, ...,
P
N
, indicating how many people live at each house (for each 1 <= i <=
N
, 0 <=
P
i
<= 100). Next line contains the integer
Q
(1 <=
Q
<= 10
4
), the number of queries to be processed. Each of the next
Q
lines describes a query with two integers
A
and
B
(1 <=
A
<=
B
<=
N
).
Output
For each query, print a line with its result.
(PT-BR:)
Todo turista que visita a cidade deve conhecer a Avenida Quatro de Maio. Há
N
casas na avenida, numeradas sequencialmente de 1 a
N
. Há
P
i
pessoas morando na casa de número
i
da avenida.
O instituto de estatística está realizando o censo deste ano. Para tal, o instituto irá realizar diversas consultas sobre a população da avenida. Em cada consulta, são dados dois números
A
e
B
, com
A
<=
B
. Para cada consulta, é necessário determinar o número total de pessoas que moram entre as casas
A
e
B
, inclusive.
Sua tarefa é, dada a população de cada casa e as consultas que o instituto irá fazer, determinar a resposta para cada consulta dada.
Entrada
A primeira linha da entrada contém o inteiro
N
(1 <=
N
<= 10
5
). A segunda linha contém
N
inteiros
P
1
,
P
2
, ...,
P
N
, indicando a população de cada casa da avenida (Para cada 1 <= i <=
N
, 0 <=
P
i
<= 100). A terceira linha contém um inteiro
Q
(1 <=
Q
<= 10
4
), indicando o número de consultas a serem realizadas. Por fim, cada uma das próximas
Q
linhas descreve uma consulta. Cada linha contém dois inteiros
A
e
B
(1 <=
A
<=
B
<=
N
).
Saida
Para cada consulta, imprima uma linha contendo sua resposta.
Example
Input:
4
10 2 8 72
3
4 4
1 3
2 4
Output:
72
20
82
Input:
5
1 2 3 4 5
2
1 5
1 1
Output:
15
1 | 34,129 |
Product it again (PROD1GCD)
The problem is very simple. given two integers n and m, find the product GCD(1, 1) × GCD(1, 2) × ... × GCD(1, M) × GCD(2, 1) × GCD(2, 2) × ... × GCD(2, M) × ... × GCD(N, 1) × GCD(N, 2) × ... × GCD(N, M).
Input
The first line will be the number of test cases t, followed by t lines, each having two numbers n and m (1 ≤ n, m ≤ 10000000) (1 ≤ t ≤ 5).
Output
Output the required solution modulo 10
9
+7.
Example
Input:
1
5 6
Output:
5760 | 34,130 |
Balance the parentheses (BALANCE1PARA)
You are provided with a sequence of parentheses, that are balanced. A balanced parentheses sequence it that sequence in which every opening bracket has a unique closing bracket (nearest to it) to the right of it and every closing bracket has a unique opening bracket to the left of it (nearest). Any other sequence is not balanced. For example, (()), ()(), ((()())()), (), etc are balanced, but )(), ()), (()(, ()( are unbalanced.
You are then provided with q queries, i
th
query is of form x
i
, representing an index. The bracket at that index is flipped that is, if it was an opening bracket then it is replaced by a closing one and vice versa. You have to give the left most index whose bracket has to be flipped so that the sequence remains balanced.
The subsequent queries have to be applied on new sequence formed!
Input
The first line will contain two integers, n and q. Next line will give you the sequence (n characters) consisting of opening and closing parenthesis only. Next q lines will represent q queries, x
i
.
Output
For each query, output the required answer in different lines.
Constraints
1 ≤ n ≤ 4×10
5
1 ≤ q ≤ 2×10
5
Example
Input:
10 10
()(((())))
2
7
9
4
5
1
4
3
5
4
Output:
2
4
6
4
2
1
2
2
4
4
Input:
6 9
((()))
6
2
2
6
4
6
3
2
4
Output:
6
2
2
6
2
6
2
2
3 | 34,131 |
Maximum Child Sum (MAXCHILDSUM)
A rooted tree is being built. Initially, there is only one node in the tree, having number 1 and value 0. You are to perform Q (Q ≤ 200000) queries, each of them is one of the following two types:
1 X Y - Add a new vertex to the tree with parent X (It's guaranteed that node X is already in the tree) and value Y (1 ≤ Y ≤ 10
9
). Its number will be the smallest positive integer that is not a number of a node yet. For example, the first query of this type will add a vertex with number 2, then 3, then 4 and so on.
2 X - Consider the children of node X. For each of them, let's sum up the values of all nodes in their subtrees. You are asked to print the maximum of those sums.
Input
The first line contains an integer Q - the number of queries. Each of the next Q lines contains one of the queries.
Output
Print the answers for all queries of the second type, one answer per line.
Example
Input:
7
1 1 3
2 1
2 2
1 2 5
2 1
1 1 4
2 1
Output:
3
0
8
8 | 34,132 |
OR (EXPOR)
Given an array of N integers A
1
, A
2
, A
3
…A
N
. If you randomly choose two indexes i, j such that 1 ≤ i < j ≤ N, what is the expected value of A
i
| A
j
?
Input
First line contains an integer T, the number of test cases. Each test case consists of two lines. First line denotes the size of array, N and second line contains N integers forming the array.
1 ≤ T ≤ 10
2 ≤ N ≤ 100,000
0 ≤ Ai < 2
31
Output
For each test case, print the answer as an irreducible fraction. Follow the format of the sample output.
The fraction p/q (p and q are integers, and both p ≥ 0 and q > 0 holds) is called irreducible, if there is no such integer d > 1 that divides both p and q separately.
Example
Input:
2
2
0 0
3
1 2 3
Output:
0/1
3/1 | 34,133 |
Cats Invitation (CATINV)
In Kutus and Putus' first marriage anniversary, they planned to invite all of their cat friends. So they invited all cats in a hall room. Due to business, all of the cats couldn't attend the party at the same time. Different cats attended party at different times and some of them couldn't stay till the end. Kutus wanted to make Putus as much happy as possible. If at any moment, there were 'L' cats present in the hall room, then happiness level of Putus were 'L' at that moment. Now Kutus gave you a list of every cats' arrival and departure time at the party and asked you few queries: Maximum time segment where the happiness level of Putus was 'L'.
Input
Input starts with an integer
T
, which denotes the number of test cases. Each case contains
2
space separated integer
N
and
Q
denoting the number of cats came to the party and the number of queries to be performed. Next
N
lines contains space separated integers '
X
' and '
Y
' denoting the arrival time and departure time of
i
th
cat. Each of the next
Q
lines contains an integer '
L
' as described above.
Output
For each case print the case number and print the time segment '
X
' and '
Y
' that is Putus' level of happiness. If there are multiple solution, print the time segment that comes earliest. If there is no possible answer, print -1.
Constraints
T ≤ 10
1 ≤ N ≤ 100000
1 ≤ Q ≤ 100000
1 ≤ X
i
≤ Y
i
≤ 100000
1 ≤ L ≤ 100000
Example
Input:
1
5 5
1 2
2 3
1 3
2 4
3 5
1
2
3
4
5
Output:
Case 1:
4 4
1 1
2 2
-1
-1 | 34,134 |
Appending String (GOC11A)
You are given a string S, you need to build another string T by expanding S according to the steps below (traversing left to right):
If current character is a letter, append it to T.
If current character is a digit, suppose the digit is N, then do T = N*T. Here N*T means appending T N times. See sample for better understanding.
Go to next character if exists then restart from step 1.
Upon expanding S, you will be given Q queries. For each query you have to print the i
th
character of the string T.
Hint: After expanding the string S = "a3b2c1" T will be = "aaabaaabc"
Input
The first line will be the number of test cases (t <= 10).
In the first line of each test you will be given a string consisting of lowercase letters and digits. And it is guaranteed that length of T will be no more than 1000.
Next line will contain an integer Q (<= 100000) denoting total numbers of queries. Following Q lines each contains an integer X.
Output
For each query X, you have to print the X
th
character of T in a line. If X is greater than the length of T, print -1.
Example
Input:
1
a3b2c1
2
4
5
Output:
b
a | 34,135 |
Sanvi Hates Palindrome (GOC11B)
Sanvi is very busy girl. So you have been given enough time (1000 milliseconds) to help him.
Sanvi has a bag of marbles with different letters written on them. And she has become busy on playing with these marbles by putting them in N boxes placed in a row. There are exactly M distinct type of marbles, N of each type.
Now she puts only N marbles (out of M*N) in N boxes, one by one and upon completion she writes down the letters on the marbles on a paper to form a string. As Sanvi hates palindrome strings (strings which read same from both sides e.g. MADAM), she erases palindrome string from the paper as soon as she finds one.
Now she is wondering how many different strings she might get on her paper if she could try all possible combination of putting the marbles in the boxes. So you have to help her by answering. As there could be many strings so print it modulo 1,000,000,007.
Input
Input starts with an integer TC (<=10), denoting the number of test cases. Each case starts with two non negative integers N (<=100000) and M (<=26) as described above.
Output
For each case, print the case number and total number of strings written on the paper modulo 1000000007.
Example
Input:
2
2 2
2 3
Output:
Case 1: 2
Case 2: 6 | 34,136 |
Ada and Rain (ADARAIN)
Ada the Ladybug is currently growing plants. She has a very long furrow, in
which she does so. It is so long, that most of water falling from rains drops
just onto a part (segment) of the furrow. Ada doesn't want the plants to
wither, so she records all rains to know, how much water every particular plant
got. Sadly, there are so many rains that she couldn't handle
this alone!
At first, you will be given
N
queries with
[L,R]
segments
telling you, where all of the
N
rains fallen. Afterward
M
queries
follows, with number
i
- the i-th plant for which you want to know, the
number of rains, which has fallen onto it.
Input
The first line will contain
0< N,M ≤ 10
5
,
0< W ≤ 10
6
, number of
rains, number of questions and size of furrow respectively.
Then
N
lines follow, each containing two integers
0 ≤ L ≤ R <W
, symbolizing left and right plant in segment on which
i-th rain has fallen.
Afterward
M
lines follow, each containing a number
0 ≤ a < W
, asking for number of rains which has fallen on plant number
a
Output
Print
M
lines (for each query of second type), with integer indicating
number of rains, which has fallen on the plant in query.
Example Input
6 7 10
0 9
3 5
4 6
4 8
1 8
5 5
1
5
9
4
9
6
7
Example Output
2
6
1
5
1
4
3 | 34,137 |
Archery Training (BLMIRINA)
Mirana is an archer with superpower. Every arrow she shoots will get stronger the further it travels. Mirana is currently on the way to warzone.
Since the road is still a long way, Mirana remembers about when she's still in training. In each of her training, Mirana stands on the (0, 0) point in a cartesian scale. From that point, she must shoot a circle centered in (
x
,
y
) with radius
r
. Everything happens in z = 0.
To maximize the arrow's power, Mirana must shoot the furthest point of the enemy possible. Her arrow travels at the speed of light and will instantly stops the moment it touches the target. On the target, determine the coordinate point that Mirana has to shoot to get maximum power. If multiple coordinate exists, choose the one with the lower x value.
Input
First line is T, number of training (T ≤ 100000). Next T lines each contains 3 space separated integers x, y, and r for each training (1 ≤ r ≤ x, y ≤ 1000)
Output
For each training, output a line containing the coordinate of the arrow's destination separated by space. Output until 6 digit after decimal point.
Example
Input:
3
1 1 1
2 2 1
4 5 2
Output:
0.000000 1.000000
1.088562 2.411438
2.126155 5.699076 | 34,138 |
Mayonnaise Arrow (BLMIRANA)
Mirana is an archer with superpower. Every arrow she shoots will get stronger the further it travels. Mirana is currently on a warzone.
Coincidentally, there's a guy selling mayonnaise. With the power of mayonnaise, Mirana's arrow can pierce every obstacle in its way. Unfortunately, there's only enough mayonnaise to power one arrow.
Mirana stands on the (0, 0) point in cartesian scale. From that point she must shoot as many enemies as possible with one arrow. Each enemy has a circle shaped hitbox. An enemy dies if the arrow travels through its hitbox. Determine the maximum number of enemies that can be shot with one arrow!
Input
First line contains T, number of wars. On the i-th war, first line contains N
i
, number of enemies. Next N
i
lines each contains 3 space separated integers x, y, and r, the position and radius of the hitbox of each enemy.
N
i
≤ 125000
N
1
+ N
2
+ ... + N
T
≤ 500000
1 ≤ r ≤ x ≤ 1000
-1000 ≤ y ≤ 1000
Output
For each war, output a line containing the maximum number of enemies that can be shot with one arrow.
Example
Input:
2
3
1 1 1
2 2 1
4 5 2
3
5 -4 1
10 -5 1
20 -10 1
Output:
3
2 | 34,139 |
Super Amoeba (BLAMOEBA)
Peter has an amoeba farm with pretty much unlimited amoebae. After years of research, Peter created a device to convert some amoebae to super amoebae. However, his device can only be used once. Every day, a super amoeba will split into M super amoebae (2 ≤ M ≤ 100000).
Now, Peter plan his amoeba selling business. Initially, Peter converts X amoebae to super amoebae (X ≥ 1). Every day after the amoebae split, Peter will take Y super amoebae for sale (Y ≥ 1). After N days, Peter want all of his amoebae to be completely sold out (1 ≤ N ≤ 100000). Since the energy needed to convert amoebae is quite massive, X must be as small as possible. Help Peter plan his business!
Input
First line is T, number of test cases (T ≤ 100000). Next T lines each contains M and N separated by space.
Output
For each case, output X and Y separated by space. Since X and Y can be very large, output them with modulo 1000000007.
Example
Input:
1
4 3
Output:
21 64
Explanation
Initially, Peter has 21 super amoebae.
After day 1, there are 4 × 21 - 64 = 20 super amoebae
After day 2, there are 4 × 20 - 64 = 16 super amoebae
After day 3, there are 4 × 16 - 64 = 0 super amoeba
All the super amoebae are sold out after the 3rd day just as planned. | 34,140 |
Ada and Plus (ADAPLUS)
Ada the Ladybug has decided to move to other city. She was deciding where
to live - she wanted the city which would be the biggest PLUS to live in. You
will be given a map with
N×N
cities. Size of PLUS is the number of cities in each of four direction (+ the city itself).
Input
The first line contains
T
, the number of test-cases.
The first line of each test-case will contain
0 < N ≤ 2000
, the size of the map.
N
lines will follow, each containing
N
characters. Characters
will be either '#' (indicating a city) or '.' (indicating free space).
Output
For each test-case, print exactly one number - the size of biggest '+' (PLUS).
Example Input
4
5
..#..
..#.#
#####
..#.#
..#..
3
..#
#.#
#.#
4
##.#
####
##.#
#..#
4
####
####
####
####
Example Output
3
1
2
2
Explanation of test-cases
1st test-case
..
#
..
..
#
.#
#####
..
#
.#
..
#
..
2nd test-case
..#
#.
#
#.#
3rd test-case
#
#
.#
###
#
#
#
.#
#..#
4th test-case
#
#
##
###
#
#
#
##
#### | 34,141 |
Ada and Plants (ADAPLANT)
Ada the Ladybug has grown many plants. She was trying to grow all plants
with equal size. Now she is wondering about the biggest difference between
heights of two plants which are near each other. Plants are near each other, if there are at most
K
plants between them.
Input
The first line contains
T
, the number of test-cases.
The first line of each test-case will contain
N, K
,
1 < N ≤
10
5
,
0 ≤ K ≤
10
5
where
N
indicates number of plants.
Next line will contain
N
integers
0 ≤ h
i
≤
10
9
indicating height
of i-th plant.
Sum of all
N
among all test-cases won't exceed
3*10
6
Output
For each test-case, print exactly one number - the biggest difference of plants
near each other (biggest
h
i
-h
j
such that
|i-j|-1 ≤ K
).
Example Input
3
5 0
1 2 3 5 6
4 6
1 10 2 9
10 1
1 7 8 9 19 11 21 8 11 0
Example Output
2
9
13 | 34,142 |
Ada and Teams (ADATEAMS)
Ada the Ladybug is a well known mathematician. Next week she is going to represent her school in Mathematic Olympiad. There are many schools participating and each of them has many students. Anyway only some of the students and only some of the schools will be available to participate in the Olympiad. Question is, how many combinations of students can participate in the Olympiad?
More specifically: There are
N
schools from which exactly
A
will participate. Moreover there are
B
students in each school and exactly
D
of them will participate in the Olympiad.
Ada could count it herself. But this process takes too much time and the limits for schools and students are changing every moment so she has decided to make a program for it (in fact she has decided that you will make the program for her)!
Input
The input contains up to
10
4
lines, each containing four integers
N,A,B,D
,
1 ≤ A ≤ N ≤ 10
6
,
1 ≤ D ≤ B ≤ 10
6
Output
For each line print the number of combination of students, which can participate in the Olympiad. All students and universities are distinguishable, but their order doesn't matter.
Since the answer might be huge, print it modulo
10
9
+7
(
1000000007
)
Example Input
2 1 2 2
2 2 2 1
2 1 2 1
4 3 3 2
4 2 1 1
10 4 12 7
50 30 44 20
Example Output
2
4
4
108
6
625817778
154746653 | 34,143 |
Ada and Indexing (ADAINDEX)
Ada the Ladybug has many things to do and almost no time. She wants to to save time while searching for something so she have decided to make a search engine.
She has many words in her TODO list. It costs her precious time to find out, whether a word is in it so she seeks your help. You will get list and some queries. You will be asked, to find out how many words in TODO list have a word as
prefix
.
Input
The first line contains
N, Q
: the number words in TODO list and number of queries.
N
lines follow, with words (of TODO list) consisting of lowercase letters. The sum of their lengths won't be greater than
10
6
Q
lines follow, with words (queries) consisting of lowercase letters. The sum of their lengths won't be greater than
10
6
Output
For each query print the number of words in TODO list which have actual word as prefix.
Example Input
12 6
bulldog
dog
dogged
doggedly
doggerel
dogma
dogmatic
dogmatism
dogs
catastroph
catastroph
doctor
cat
dog
dogg
do
doctrinography
dogge
Example Output
2
8
3
9
0
3 | 34,144 |
Ada and Queue (ADAQUEUE)
Ada the Ladybug has many things to do. She puts them into her queue. Anyway she is very indecisive, so sometime she uses the top, sometime the back and sometime she decides to reverses it.
Input
The first line consists of
1 ≤ Q ≤ 10
6
, number of queries. Each of them contains one of following commands
back - Print number from back and then erase it
front - Print number from front and then erase it
reverse - Reverses all elements in queue
push_back
N
- Add element
N
to back
toFront
N
- Put element
N
to front
All numbers will be
0 ≤ N ≤ 100
Output
For each back/front query print appropriate number.
If you would get this type of query and the queue would be empty, print "
No job for Ada?
" instead.
Example Input
15
toFront 93
front
back
reverse
back
reverse
toFront 80
push_back 53
push_back 50
front
front
reverse
push_back 66
reverse
front
Example Output
93
No job for Ada?
No job for Ada?
80
53
66 | 34,145 |
Ada and Game (ADAGAME)
Ada the Ladybug is playing
Game of Digits
against her friend Velvet Mite Vinit. The game is played in following manner: At first, there is a four-digit number and a number of moves. Both Ada and Vinit take turns alternately (beginning with Ada). Both of them must increase ANY digit of the number, but if the digit was 9 it will become 0.
For example number 3590 can be expanded to: 4590, 3690, 3500 or 3591. If after all turns the number is greater than the original number, Ada wins - otherwise Vinit is the winner. Both of them play optimally - can you decide who is the winner?
PS: It is possible, that Ada will have one more turn (if number of turns is odd)
Input
First line of input will consist
T ≤ 200
number of test-cases. Each testcase will consist of four digit number
0 ≤ N < 10
4
[the original number] and
0 ≤ M ≤ 100
[the number of turns].
Output
For each test-case, print the name of winner ("
Ada
" or "
Vinit
").
Example Input
5
0000 0
5566 3
3333 10
9999 9
1234 30
Example Output
Vinit
Ada
Ada
Vinit
Ada | 34,146 |
Ada and Spring Cleaning (ADACLEAN)
Ada the Ladybug has decided to do some "Spring Cleaning". As you might know, she keeps a TODO list. She is very sparing so she keeps all her activities as one string. You might get very confused while reading the string but she has a system - every activity has length exactly
K
characters. Sadly, as new activities were added to the list many duplicities appeared. Now it is time to find out how many
unique
activities are in her TODO list.
Input
First line contains
T
, number of test-cases.
Each test-case begins with
N, K
,
1 ≤ K ≤ N ≤ 10
5
, length of string and length of activities respectively.
Next line consists of string of length
N
, consisting of lowercase letters.
The sum of lengths of strings among all test-cases won't exceed
3*10
5
Output
For each test-case, print the number of unique substrings of length
K
Example Input
5
3 2
aaa
5 1
abcba
4 2
abac
10 2
abbaaaabba
7 3
dogodog
Example Output
1
3
3
4
4 | 34,147 |
Shoumiks Weakness (WEAKSMK)
Shoumik loves problem solving but he is weak in string related problems. So he is practicing string related problems. But he thought that creating a string related problem and solving that would be a great idea to be strong in strings. So he thought of a problem.
Given a string S of N lower case letters how many distinct substrings T are there with length L (L = |T|) and S contains exactly X occurrences of T.
In the string S=“abcbcb” the substring T=“bcb” has length L=3 and S has X=2 occurrences of T. (See hints for more clarification)
But as Shoumik is weak in string, he is stuck with this problem. You have to help him answering Q queries for a given string S.
Input
First line of input will contain the number of test cases T. Then T test cases follows.
Every test case contains two integers N and Q in the first line. Next line will contain a string S, consisting of N lowercase characters.
The next Q lines will contain Q queries with two integers L, length of T for this query and X, occurrences of T in S.
1 <= T <= 15
1 <= N <= 10000
1 <= Q <= 100000
1 <= L < 2^31
0 <= X < 2^31
Sum of N over all test cases <= 60000 (6*10^4)
Number of queries Q over all test cases <= 600000 (6*10^5)
Output
For every query print the number of distinct substrings T in the string S which are of length L and have exactly X occurrences in S.
Example
Input:
1
6 5
abcbcb
3 2
4 1
6 2
6 1
1 2
Output:
1
3
0
1
1
Hints
For the 2nd query we have 3 distinct substrings of length 4 “abcb”, “bcbc”, “cbcb” and all of them have 1 occurrence in S. So the answer is 3.
For the 5th query we have 3 distinct substrings of length 1 “a”, “b”, “c” but only “c” has 2 occurrences in S. So the answer is 1. | 34,148 |
Friend Zoned (FRNDZND)
Pavel proposed a girl. Of course, she didn’t say yes, rather she gave him an array having N integers and asked him M queries over the array. Each query can be represented as two integers L and R.
For each query, Pavel should do the following:
First, he has to insert the numbers at index L, L+1, L+2 ... R of the given array into a multi-set. Multi-set is a set where an element can appear multiple times. Suppose that the size of this multi-set after inserting the numbers is k. Formally, k is equal to R-L+1.
Then he has to generate all possible subset of the multi-set which he constructed in step 1. Then for each subset he needs to xor the numbers of that subset. In this way, he will get 2
k
values. Note that, for the empty set he will get 0.
Finally, he has to xor the 2
k
values which he got at step 2 and say this value to his dream girl.
If Pavel can answer all the queries correctly then she will reconsider his proposal. Can you help him to answer the queries?
Input
The first line of input contains two integers N and Q. The next line contains N integers, the numbers in the array. Then each of the following Q lines contains 2 integers L and R.
Output
For each query output an integer in a separate line, the answer for that query. Queries should be answered in the order given in the input.
Constraints
1 ≤ N ≤ 100000
1 ≤ Q ≤ 100000
0 ≤ Value of a number in the array ≤ 1000000000
1 ≤ L ≤ N
1 ≤ R ≤ N
L ≤ R
Example
Input:
4 2
1 3 3 3
1 1
2 4
Output:
1
0
Explanation:
In the first query, there will be only 1 element in the multi-set: {1}. There are 2 possible subset of this multi-set. They are: { }, {1}. If we xor the numbers of each subset we get 0 and 1 respectively. Xor of theses two values is equal to 1.
In the second query, there are 3 elements in the multi-set: {3,3,3}. There are 8 possible subset of this multi-set. They are: { }, {3}, {3}, {3}, {3,3}, {3,3}, {3,3}, {3,3,3}. By applying xor operation on the numbers of each subset we get 0, 3, 3, 3, 0, 0, 0, 3 respectively. Xor of these values is equal to 0. | 34,149 |
Ada and Field (ADAFIELD)
Ada the Ladybug owns a beautiful field where she grows vegetables. She often visits local Farmers Market, where she buys new seeds. Since two types of vegetable can't share same field, she always divide the field, by either vertical or horizontal line (she is very precise, so the width of line is negligible). Since she visits Farmers Market almost every day, she has already made a lot of such lines, so she needs your help with finding out the area of biggest field.
Input
The first line will contain
0 < T ≤ 200
, the number of test-cases.
Then
T
test-cases follow, each beginning with three integers
1 ≤ N, M ≤ 2×10
9
,
1 ≤ Q ≤ 10
5
, top right corner of field (field goes from
[0, 0]
to
[N, M]
) and number of field divisions.
Afterward
Q
lines follows:
0 x (0 ≤ x ≤ N)
, meaning that line was made vertically, on coordinate
x
.
1 y (0 ≤ y ≤ M)
, meaning that line was made horizontally, on coordinate
y
.
Sum of
Q
over all test-cases won't exceed
10
6
.
Output
Print
Q
lines, the area of biggest field after each line was made.
Example Input
2
10 10 5
0 5
0 8
1 1
1 9
1 5
10 10 5
0 5
1 4
1 6
1 8
0 5
Example Output
50
50
45
40
20
50
30
20
20
20 | 34,150 |
Ada and Cycle (ADACYCLE)
Ada the Ladybug is on a trip in Bugindia. There are many cities and some uni-directional roads connecting them. Ada is wondering about the shortest path, which begins in a city and ends in the same city. Since Ada likes short trips, she asked you to find the length of such path for each city in Bugindia.
Input
The first line will contain
0 < N ≤ 2000
, the number of cities.
Then
N
lines follow, each containing
N
integers
0 ≤ H
ij
≤ 1
. One means, that there is a road between
i
and
j
(zero means there isn't a road).
Output
Print
N
lines, the length of shortest path which begins in city
i
and ends in city
i
. If the path doesn't exist, print "
NO WAY
" instead.
Example Input
5
0 1 1 1 1
1 0 0 0 1
0 0 1 1 0
0 0 1 0 0
0 0 0 1 0
Example Output
2
2
1
2
NO WAY
Example Input
5
0 1 0 0 1
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
1 0 0 0 0
Example Output
2
5
5
5
2 | 34,151 |
Ada and Fence (ADAFENCE)
Ada the Ladybug owns a circular land. She wants to enclose it with fence.
Anyway since nobody sells round planks, she has decided to fence it to shape of
regular
k-gon
. Problem is, that there is only limited number or places
(on circle) where pillars can be built. Ada has asked you, to find out the
number of different regular
k-gon
shaped fences which can be built on her
land (two
k-gon
's are considered different if they share NO common pillar).
Input
The first line will contain
T
, the number of test-cases.
Then
T
test-cases follow, each beginning with two integers
3
≤ K ≤ N ≤ 10
5
,
3 ≤ K ≤ 100
, the number
of places where pillar can be built and number of edges of regular
k-gon
.
Afterward a line with
N
integers
1 ≤ D
i
≤ 100
follow, meaning the length of arc between two consecutive points where
pillar can be built. The sum of all lengths will be divisible by
K
.
Sum of
N
over all test-cases won't exceed
2×10
6
.
Output
For each test-case print the number of different regular
k-gon
shaped fences which can be
built.
Example Input
3
5 3
1 2 3 2 1
15 4
1 2 2 2 1 2 2 1 1 2 1 2 1 2 2
10 5
1 1 1 1 1 1 1 1 1 1
Example Output
1
1
2 | 34,152 |
Ada and List (ADALIST)
Ada the Ladybug has a TODO-list (containing only numbers - for simplicity). She is still doing something, so she sometimes erases
k
th
number, sometimes she inserts something on
k
th
position and sometime she asks for
k
th
number.
Sadly, she is now searching for a work at position
k
so she doesn't have time to do this herself. Can you help her?
Input
The first line will contain
0 < N ≤ 10
5
,0 < Q < 5*10
5
, the number of elements in TODO-list and number of queries.
Then a line with
N
numbers follows. Each number
0 ≤ A
k
≤ 10
9
means
k
th
number in her TODO-list.
Afterward,
Q
lines follow, each beginning with number
1 ≤ a ≤ 3
1
k x
means that you will add number
x
to position
k
2
k
means that you will erase number from position
k
3
k
means that you will print number from position
k
For all queries, it is true that
1 ≤ k ≤ #SizeOfList
,
0 ≤ x ≤ 10
9
(for query
1
, it can be also put to position
#SizeOfList + 1
)
You will never get query of type
2
or
3
if the list is empty
Output
For each query of type
3
, print
k
th
numbers
Example Input
6 10
1 2 4 8 16 32
3 4
1 1 7
3 2
2 2
2 2
3 2
1 6 666
3 6
2 1
3 1
Example Output
8
1
4
666
4
Queries explanations
1 2 4
8
16 32
7 1 2 4 8 16 32
7
1
2 4 8 16 32
7 2 4 8 16 32
7 4 8 16 32
7
4
8 16 32
7 4 8 16 32 666
7 4 8 16 32
666
4 8 16 32 666
4
8 16 32 666 | 34,153 |
Ada and Path (ADAPATH)
Ada the Ladybug loves Crosswords, Sudoku's and all other similar games. She has found an interesting game in the latest issue of Magazine Bug.
The game is simple - you will be given a square full of numbers. Each number must be part of exactly one path. Path must begin at number
1
and can only continue to neighboring number (left, right, up, down), which is larger by 1.
Ada's friend is working as a director of Magazine Bug. He wants to surprise her and add few more games to following issues of the magazine. Anyway, he wants you to check, whether the games are valid (i.e. if all the numbers can be part of a path).
Input
The first line will contain
T
, the number of test-cases.
Then
T
test-cases follow, each beginning with an integer
1 ≤ N ≤ 100
, the size of the game board.
Afterward,
N
lines follow with
N
integers
1 ≤ A
ij
< 10
Output
For each test-case print either "
YES
" if board is valid or "
NO
" if it isn't.
Example Input
4
4
1 2 3 4
4 3 2 1
1 2 2 1
1 1 1 2
3
1 2 3
4 5 6
1 2 1
2
1 2
4 3
2
1 2
2 2
Example Output
YES
NO
YES
NO | 34,154 |
Ada and Cities (ADACITY)
Ada the Ladybug and her friends are on trip in Bugraine. Most of them are in different cities at the moment. They want to spread as much as possible, make hologram-skype to show all others the city. They have agreed, to make this call in time
T
.
The cities are connected with bi-directional roads. Each of the road has some length (which equals to time it takes to travel between two cities).
Input
The first line will contain the number of test-cases.
The first line of each test-case begins with four integers:
N, M, F, T
, number of cities, number of roads, number of friends (Ada inclusive) and time they have:
1 ≤ N, F ≤ 500
,
0 ≤ M ≤ 10
5
, 0 ≤ T ≤ 5*10
8
Then a line with
F
integers follows,
1 ≤ H
i
≤ N
, the city, where
i
th
friend currently is.
Afterward
M
lines follow, with three integers
A, B, L
,
1 ≤ A, B ≤ N, 1 ≤ L ≤ 10
6
, indicating a road, which connect cities
A, B
with length of
L
PS: There might exist multiple roads between two cities and there might also be a "circular route" which begins and ends in the same city!
Output
For each test-case, print maximal number of different cities Ada and her friends can end up at after
T
time!
Example Input
3
5 5 4 3
1 1 1 1
1 2 3
1 5 2
5 4 2
4 3 1
2 3 2
7 7 6 3
6 6 2 2 2 2
1 7 5
1 2 5
7 2 4
2 3 2
3 4 3
5 4 1
2 5 2
5 5 4 4
1 1 1 1
1 2 3
1 5 2
5 4 2
4 3 1
2 3 2
Example Output
3
5
4
Output Explanation
In
first
test-case, all 4 friends begin in same node. From this node, one can get to nodes
2
and
5
, or stay in the node (in time ≤ 3). Since everyone is in node 1, best they can do is to choose one friend who goes to 5, one who goes to 2 and the rest of them can stay so with "1, 1, 2, 5" they can occupy 3 different nodes (at most).
In
second
test-case, friends on
6
can go nowhere (just stay in 6). Friends on 2 can go to
3, 4, 5
or stay on
2
. So with friends in
6, 6, 2, 3, 4, 5
we get maximum of 5 different cities.
Last (
third
) test-case is same as first - except for time. This one additional time-unit will let friends go to
4
(or to nodes which they can go in first test-case). "1, 2, 4, 5" would make 4 different cities! | 34,155 |
Finding the way (TAP2016B)
The baking festival has arrived in town. This is a great opportunity for small businesses in the baking industry to collect some money and promote themselves. Each small business wanting to take part in the festival can do so by setting up a small stand in the hall where it takes place. For security reasons, each stand should be placed against one of the hall's walls. In its stall, each business can show its products and make the necessary arrangements to sell them to the public attending the festival. One important characteristic of the stands is that they offer a free sample of some products to whomever may want one. The goal is to show the great quality of the recipes and thus tempt passersby to buy at that stand.
The free samples bring a lot of people to the festival, wanting to eat the delicious desserts for no cost at all as they move around the hall. Most attendees buy some of the products to help the business who really deserve recognition. One of the festival's most famous visitors is Mr. Belly, who always goes by every single stand checking out the free samples, even going as far as giving a prize to the best of them all.
Mr. Belly doesn't want to waste too much time at the festival, so he would like to taste the free samples in all of the stands walking the least possible distance. In order to do this, he has the map printed on the festival's brochure, which was published in advance by the organizers. The map has a drawing of the shape of the hall, which in this case is a convex polygon. It also has markings for
N
important sites, two of which correspond to the entrance and exit of the hall, the other
N-2
being the festival's stands. Each important site is represented by a point on the boundary of the polygon representing the hall's walls.
Mr. Belly is now asking for you to help him complete his mission. He will provide you with the coordinates in the Cartesian
(X, Y)
plane of the
N
important sites in the hall, in counter-clockwise order (
i.e.
in the order in which he would visit them if he were to go through the hall keeping his right hand on its interior wall). He would like to know what's the minimum distance he must travel in order to visit all the stands, if he is to start at the entrance of the hall, finish at its exit and choose optimally the order in which he visits the stands.
Input
There are multiple test cases in the input file. For each test case, the first line contains three integer numbers
N
,
E
and
S
. The integer
N
represents the number of important sites marked on the map, which are numbered from
1
to
N
(
2 ≤ N
≤
4000
). The integers
E
and
S
represent the numbers of the sites corresponding to the hall's entrance and its exit, respectively (
1
≤
E, S
≤
N
with
E ≠ S
). Each of the following
N
lines contains two integers
X
and
Y
, representing the numbers on the
i
-th line the coordinates
(X, Y)
of the
i
-th important site (
-10
4
≤
X, Y
≤
10
4
). All the important sites are located in different points, and there always exists a convex polygon containing all of them in its boundary.
Output
For each test case, print one line containing one rational number, representing the minimum distance Mr. Belly needs to walk in order to visit all of the festival's stands, starting at the entrance of the hall and finishing at its exit. Print the result with exactly
6
digits after the decimal marker, rounding if necessary.
Example
Input:
6 1 6
1 0
2 0
3 1
2 2
1 2
0 1
6 1 4
0 0
10 0
20 0
20 1
10 1
0 1
Output:
6.242641
23.000000 | 34,156 |
Correlations (TAP2016C)
Finishing your studies in a university is not only a matter of studying and learning. To obtain that prized degree, each student has to prove that he has learned, and in order to do that he needs to pass
N
subjects. However, it is often also necessary to abide by uncountable and deliberately complicated regulatory labyrinths.
At the
Institute With Few Correlations
(IWFC) there are antiquated norms which forbid students from passing some subjects without having first passed certain other subjects. The latter are called "correlation" subjects for the first ones. Each subject may have one or more correlation subjects, but there are no cyclic correlations, so that it is always possible to obtain the desired degree.
Gabina is a student of Happiness Sciences, and fortunately her professors are very understanding people. They therefore allow her to pass her subjects without actually having passed their correlation subjects before. The problem with this is that IWFC's electronic system can only register a subject as being passed abiding by the correlation rules. Thus, a subject will be registered in the system if and only if it was passed and all its correlation subjects are also already registered.
Seeing her progress keeps Gabina motivated, and helps her to push forward with her studies. For this reason, each time she passes a subject she checks the electronic system to see how many subjects have been registered in it. Sometimes she sees the number has not changed, which happens whenever the subject she just passed didn't have all its correlation subjects registered in the system. In other cases, she receives the delightful news that the number of registered subjects has increased. Moreover, it may happen that this increase was in more than one, which happens whenever the subject she just passed could be registered, and doing so unlocked the registration of a series of subjects passed beforehand.
Gabina has already planned the order in which she will pass all the subjects for her degree. She would now like to know the number of subjects which will be registered in the electronic system after she passes each one of them. Your task is to write a program to help Gabina predict this, so that she can joyfully finish her Happiness Sciences studies.
Input
There are multiple test cases in the input file. The first line contains two integer numbers
N
and
M
, representing the number of subjects in her degree and the number of correlation relations between pairs of subjects, respectively (
1
≤
N,M ≤ 5 × 10
4
). The subjects are numbered from
1
to
N
. Each of the following
M
lines contains two integer numbers
A
and
B
, indicating that subject
A
is a correlation subject for subject
B
(
1
≤
A, B
≤
N
with
A ≠ B
). This means that subject
A
must be registered in the electronic system before subject
B
can be registered. There are no repeated or cyclic correlation relations in the input. The last line contains
N
integer numbers
P
1
, P
2
, ..., P
N
, representing the subjects in the order Gabina will pass them (
1
≤
P
i
≤
N
for
i = 1, ..., N
, with
P
i
≠ P
j
for
i ≠ j
).
Output
For each test case, print
N
lines, each with a single integer number. The number printed in the
i
-th line represents the number of subjects registered in the electronic system immediately after Gabina passes the
i
-th subject for her degree in the order giver in the input.
Example
Input:
3 2
1 2
2 3
1 2 3
3 2
1 2
2 3
3 2 1
4 4
1 2
2 3
4 3
1 4
2 3 1 4
Output:
1
2
3
0
0
3
0
0
2
4 | 34,157 |
Drawing triangles (TAP2016D)
Daniela was offered a
Game of Thrones
coloring book. Each of the book's pages has
N
points marked on it, being these points numbered from
1
to
N
. The challenge is meant to be joining these points with lines in such a way that the figure of a dragon is formed. This problem would be a lot of fun if it was titled "Drawing dragons" and the main character was Daenerys Targaryen, but this is not so. The main character is not
Daenerys Stormborn of the House Targaryen
the first of her name
Queen of the Andals, the Rhoynar and the First Men
Lady of the Seven Kingdoms and Protector of the Realm
Khaleesi of the Great Grass Sea
the Unburnt
Breaker of Chains
Mother of Dragons
Queen of Meereen
but it's Daniela, who likes to draw triangles and study their properties. This is definitely a lot more fun than drawing dragons!
Daniela is interested in similar triangles. A triangle is the figure that is formed by joining with line segments three unaligned points. Two triangles are said to be similar if the ratio between their corresponding sides' lengths are always the same. In the figure, triangles
ABC
and
DEF
are similar because
AB/DE = BC/EF = CA/FD
.
Daniela has been looking at one of the books' pages for a while, thinking about the triangle formed by the first three points marked on it. She is wondering how many triangles similar to the one formed by these points can be formed using any three of the
N
points marked on the page. There are many points so it's going to take a while to find out the answer. She is now very sleepy, but she knows she won't be able to go to bed without knowing it. Can you help her by counting how many triangles similar to the one formed by the first three points (counting this triangle itself) can be formed by joining three points marked on the book's page? This way, she can go to bed and sleep peacefully during the long night.
Input
There are multiple test cases in the input file. For each test case, the first line contains an integer number
N
, representing the number of points marked on the book's page (
3 ≤ N ≤ 1000
). Each of the following
N
lines contains two integer numbers, corresponding to one point marked on the page. The integer numbers in the
i
-th of these lines are
X
i
and
Y
i
, and they represent the coordinates of the
i
-th point in a cartesian coordinate system (
-100 ≤ X
i
, Y
i
≤ 100
for
i = 1, 2, ..., N
). All points given in the input for a test case are distinct, and the first three points always form a triangle.
Output
For each test case, print a single line containing an integer number, representing the number of triangles similar to the one formed by the first three points in the input, which can be formed by joining three of the points marked on the page (counting the triangle formed by the first three points itself).
Example
Input:
6
0 0
1 1
-2 1
5 2
5 0
2 3
3
0 0
1 0
1 1
4
0 0
12 12
3 21
28 -4
4
-100 -100
-100 100
100 -100
100 100
Output:
2
1
3
4 | 34,158 |
Grumpy uncle (TAP2016E)
Winters in Nlogonia are very hard, so uncle Ernie decided to buy a heater to keep himself warm this year. Although it was terribly difficult, he managed to follow his friends' advice and buy an intelligent heater, which can be controlled from his smartphone. However, uncle Ernie doesn't fully understand his smartphone, so he has trouble finding the app which is used to set the heater's temperature.
Uncle Ernie has installed on his smartphone
N
apps numbered from
1
to
N
, corresponding number
1
to the app controlling the heater. His smartphone has
M
buttons numbered from
1
to
M
, which are used to switch from one app to another. More specifically, if the smartphone has currently app number
i
opened and uncle Ernie presses button number
j
, then app
i
is closed and app
T
i,j
is then opened. The problem is uncle Ernie cannot distinguish one app from the other, so he never knows if he has opened the correct app.
Uncle Ernie is very grumpy, so you have decided to help him in order to avoid having to listen to his complaints every time the heater's temperature is not quite right for him. Your task is to provide him with a list of buttons which he can use as instructions, such that if he presses the buttons in the list in the order in which they appear there, his phone will have opened the app controlling the heater. Because you don't want to provide him with more than one list, you should create one that works as explained above independently of which app is opened at the time when uncle Ernie begins executing its instructions.
Take for example the case where the phone has
N = 3
apps and
M = 2
buttons, being
T
1,1
= T
2,1
= 3
,
T
3,1
= T
1,2
= 2
and
T
2,2
= T
3,2
= 1
. In this case, a sequence of buttons that could be provided to uncle Ernie would be
{1,2}
, because one of the following situations would take place:
If uncle Ernie starts with app
1
being open, pressing button
1
will leave him with app
3
being open; then pressing button
2
would result in a final state where app
1
is again opened.
On the other hand, if uncle Ernie starts with app
2
being open, pressing button
1
will leave him with app
3
being open; then pressing button
2
would result in a final state where app
1
is open.
Finally, if he starts with app
3
being open, pressing button
1
will leave him with app
2
being open; then pressing button
2
would reslut in a final state where app
1
is open.
Therefore, independently of which app was open at the beginning of the sequence of button presses, uncle Ernie will always reach app
1
by the end of the sequence.
Now again, there are times when it is impossible to find a sequence of buttons that can be pressed by uncle Ernie such that the app being open when he finishes to do so is always app number
1
. For example, in the case with
N = 3
and
M = 2
if we have
T
1,1
= T
1,2
= 2
,
T
2,1
= T
2,2
= 3
and
T
3,1
= T
3,2
= 1
the application opened at the end of any sequence of button presses always depends on which application was open at the time the sequence was started. Therefore, in this case it is impossible to find a sequence that will always leave uncle Ernie's phone with app number
1
opened.
In order not to waste time looking for sequences of button presses that do not exist, you would like to first find out if it is possible to satisfy uncle Ernie by finding a sequence as described above. If so, uncle Ernie will be happy knowing that he can turn the heater on at level 2, his favorite, whenever he wants... and will thus be eternally grateful.
Input
There are multiple test cases in the input file. The first line contains two integer numbers
N
and
M
, representing the number of applications and the number of buttons in uncle Ernie's smartphone, respectively (
1
≤
N,M ≤ 1000
with
1
≤
N × M
≤
10
4
). Each of the following
N
lines contains
M
integer numbers, being the
j
-th number in the
i
-th line
T
i,j
, representing the app which is opened when button
j
is pressed while app number
i
was open (
1
≤
T
i,j
≤
N
for
i = 1, 2, ..., N
and
j = 1, 2, ..., M
).
Output
For each test case, print a single line containing a character, representing if it is possible to find a sequence of buttons as described in the problem statement. The character should be an
'
S
'
if the sequence can be found, and an
'
N
'
otherwise.
Example
Input:
3 2
3 2
3 1
2 1
3 2
2 2
3 3
1 1
Output:
S
N | 34,159 |
Congratulations, Fidel! (TAP2016F)
Fidel has finished a fruitful stage of his academic formation by achieving his PhD in Physics. This was mainly the result of his firm attitude towards the formalization of the fabulous results in his fantastic investigation.
Fidel has always spread happiness among his friends and family, and that is why we have all agreed to sign a congratulation letter addressed to our favourite doctor. Having finished writing the letter, the only remaining task is to include the fervent signature of the F signers. For that purpose, we have bought two markers, one of which is French blue and the other fuchsia. Each of the signers will write their name using these markers.
It is our intention to emphasize the doctor title that Fidel has just achieved, and so we want that the abbreviation of such title ("DR") can be seen many times disguised within our signatures. To that end, we will sign using both colors, and write some letters in blue and others in fuchsia, in such a way that by reading only the fuchsia letters, Fidel may read the "DR" abbreviation.
More precisely, our goal is that by reading only those letters written in fuchsia, Fidel only reads 'D' and 'R' letters, in an alternating fashion. Consequently, the first fuchsia letter must be a 'D', and for every 'D' written in fuchsia, the next letter written in that same colour will have to be an 'R'. Similarly, for each 'R' written in fuchsia, the next letter written in that same colour will have to be a 'D', and the very last letter written in fuchsia will have to be an 'R'.
We want to write the fuchsia letters in such a way that Fidel reads the letters 'D' and 'R' written in that colour as many times as possible. In order to accomplish our goal, we can choose in which order we will write our names, and which letters we will write using each colour. Since there are many different ways to do so, we need your help to find out what is the maximum number of times that we can write the "DR" abbreviation in fuchsia, by following the rules that were explained in the previous paragraph.
Fidel has finished a fruitful stage of his academic formation by achieving his PhD in Physics. This was mainly the result of his firm attitude towards the formalization of the fabulous results in his fantastic investigation.
Fidel has always spread happiness among his friends and family, and that is why we have all agreed to sign a congratulation letter addressed to our favourite doctor. Having finished writing the letter, the only remaining task is to include the fervent signature of the
F
signers. For that purpose, we have bought two markers, one of which is French blue and the other fuchsia. Each of the signers will write their name using these markers.
It is our intention to emphasize the doctor title that Fidel has just achieved, and so we want that the abbreviation of such title ("DR") can be seen many times disguised within our signatures. To that end, we will sign using both colors, and write some letters in blue and others in fuchsia, in such a way that by reading only the fuchsia letters, Fidel may read the "DR" abbreviation.
More precisely, our goal is that by reading only those letters written in fuchsia, Fidel only reads '
D
' and '
R
' letters, in an alternating fashion. Consequently, the first fuchsia letter must be a '
D
', and for every '
D
' written in fuchsia, the next letter written in that same colour will have to be an '
R
'. Similarly, for each '
R
' written in fuchsia, the next letter written in that same colour will have to be a '
D
', and the very last letter written in fuchsia will have to be an '
R
'.
We want to write the fuchsia letters in such a way that Fidel reads the letters '
D
' and '
R
' written in that colour as many times as possible. In order to accomplish our goal, we can choose in which order we will write our names, and which letters we will write using each colour. Since there are many different ways to do so, we need your help to find out what is the maximum number of times that we can write the "DR" abbreviation in fuchsia, by following the rules that were explained in the previous paragraph.
Input
There are multiple test cases in the input file. For each test case, the first line contains an integer
F
, representing the number of signers (
1 ≤ F
≤
1000
). Each of the next
F
lines will contain the name of one of Fidel's friends. The name of each friend is formed by no more than
100
characters from '
A
' to '
Z
'.
Output
For each test case, you must write a single line containing an integer, indicating the maximum number of times that the "DR" abbreviation can appear in fuchsia once we sign our letter, if we follow the rules explained in this problem statement.
Example
Input:
10
RAMIRO
AUGUSTO
JOAQUIN
JACINTO
NICOLAS
ALEJANDRO
DIJKSTRA
KAJITA
MCDONALD
SCHRODINGE
4
DDD
RRR
DRDR
RDRD
12
MELANIE
DAMIAN
RAMIRO
AUGUSTO
JOAQUIN
JACINTO
NICOLAS
ALEJANDRO
DIJKSTRA
KAJITA
MCDONALD
SCHRODINGER
4
ABCEFG
HIJKLM
NOPQST
UVWXYZ
Output:
4
5
5
0 | 34,160 |
Efficient managing (TAP2016G)
Nlogonia's train network consists of
N
stations, each of them strategically placed in a different city of the kingdom. Certain pairs of stations are connected by railways, and on each railway there is a train service going on both directions. For centuries the
Institute for the Cities' Perfect Connection
(ICPC) has been in charge of optimizing public transportation in Nlogonia, so today the train network is so efficient there is exactly one way to travel between any pair of cities using trains. Note that it may be necessary for a traveller to successively take several trains, in case there is no direct connection between the pair of stations he is traveling to/from. In other realms this might be considered an inconvenience, but Nlogonia's inhabitants are happy knowing that they will not waste a single minute thinking about which route to take from one city to another.
The ticket for each train service has certain price, so that a passenger taking one or more trains to travel between two cities has to buy the corresponding tickets before boarding each train. Nlogonia's currency is also extremely efficient, as there are bills with values corresponding to every non-negative power of two. This is, the denomination of bills in Nlogonia is of
2
0
= 1
unit,
2
1
= 2
units,
2
2
= 4
units, and so on. As a result of this monetary efficiency, Nlogonians always pay their tickets by providing the minimum number of bills with which it is possible to reach the exact amount of the ticket they are buying.
To speed up ticket buying, the
Agency for Counting Money
(ACM) would like to introduce the following offer. When a passenger is going to make a trip, he can pay all the tickets he will be needing in advance. When doing so, he must present all the bills he would use along his journey, and the ACM will only take one bill of each denomination for which the passenger provided an odd amount of bills. In this way, if for example a passenger wants to buy three tickets with prices of
3
,
7
and
10
units, he will present two bills for the first ticket (with denominations
1
and
2
), three bills for the second one (with denominations
1
,
2
and
4
) and two bills for the third (with denominations
2
and
8
). The ACM would then take only one of the bills with denomination
2
, along with each of the bills with denominations
4
and
8
, returning to the passenger two bills of denomination
1
, as well as two bills with denomination
2
.
Now the ACM's steering committee is worried because this offer might be too expensive for the kingdom's treasury. There is certainly good cause for this, as one should note that it is even possible to travel for free (
e.g.
any round trip will be free, as an even number of tickets of each value will always be required). Your job is to evaluate the extent of the problem, for which the ACM has commanded you to determine the maximum price a passenger might have to pay when starting his journey from each of the
N
train stations in Nlogonia.
Input
There are multiple test cases in the input file. The first line contains an integer number
N
, representing the number of train stations in Nlogonia (
2 ≤ N
≤
10
5
). Train stations in Nlogonia are numbered from
1
to
N
. Each of the following
N-1
lines contains three integer numbers
A
,
B
and
C
, indicating there is a railway directly connecting stations
A
and
B
, being
C
the price of the ticket for the train service operating on said railway (
1
≤
A, B
≤
N
and
1
≤
C
≤
10
9
, with
A ≠ B
). The description of the railway network is always such that for each pair of distinct stations there exists one and only one sequence of train services connecting them.
Output
For each test case, print
N
lines each containing one integer number. The number printed on the
i
-th line should correspond to the maximum value of the tickets that may be payed by a passenger starting his journey at the station identified by the number
i
, when the offer described in the problem statement is applied.
Example
Input #1:
4
1 2 3
2 3 7
3 4 10
Output #1:
14
13
10
14
Input #2:
6
1 2 1
3 2 2
2 4 3
4 5 4
4 6 5
Output #2:
7
7
5
5
7
7
Input #3:
7
1 2 1
1 3 2
1 4 3
1 5 4
1 6 5
1 7 6
Output #3:
6
7
7
7
7
7
7 | 34,161 |
New TAP (TAP2016H)
We are considering changing the rules for the Argentinian Programming Tournament starting next year. Before doing that, we would like to evaluate whether the new system is fair, and we need your help to do that.
The new tournament will have
N
teams competing in
N-1
rounds. In each round two teams will face each other competing in order to be the first to solve a problem, the losing team being eliminated. In the first round, two teams will be chosen at random, and the losing team will be placed in the last place of the scoreboard, while the winner remains in the competition. In each of the following rounds, two teams still in the competition will be chosen at random, and the losing team shall be placed in the last remaining place of the scoreboard, being thus eliminated from the tournament.
For example, if the tournament has
N=4
teams named "
aWArush
", "
Buen Kilo de Pan Flauta
", "
Melarita
" and "
Type Mismatch
", the tournament will be held in three rounds. Suppose that in the first round "
Buen Kilo de Pan Flauta
" faces "
Melarita
", the former being the winner; in the second round "
aWArush
" beats "
Buen Kilo de Pan Flauta
"; and finally in the last round "
aWArush
" beats "
Type Mismatch
". Then the placement of the teams in the final scoreboard will be in the following order: 1
st
"
aWArush
", 2
nd
"
Type Mismatch
", 3
rd
"
Buen Kilo de Pan Flauta
" and 4
th
"
Melarita
".
To analize just how fair the new tournament format is, we will consider the teams to be numbered from
1
to
N
, in such a way that lower numbers represent better teams. We will assume that whenever two teams face each other in a given round, the one with the smallest number will invariably win. We would like you to help us answer the following question: What is the probability for team
X
to be placed at position
Y
in the final scoreboard?
Input
There are multiple test cases in the input file. Each test case consists of a single line containing three integer numbers
N
,
X
and
Y
. The number
N
represents the number of teams taking part in the tournament, (
2 ≤ N
≤
1000
),
X
represents the number of the team we are interested in, and
Y
represents its final position (
1
≤
X,Y
≤
N
).
Output
For each test case, print a single line containing a rational number, representing the probability for team number
X
to be placed at position
Y
in the final scoreboard. Print the result with exactly
4
digits after the decimal marker, rounding if necessary.
Example
Input:
3 2 2
10 3 6
10 1 5
1000 1 1
1000 1000 1000
Output:
0.6667
0.0946
0.0000
1.0000
0.0020 | 34,162 |
Insect invasion (TAP2016I)
Ignacio liked to take part in programming competitions such as the Argentinian Programming Tournament during his years as a university student. He was very happy, and when he graduated he got a good job. However, with time routine and life in the big city started to make him feel uneasy. So one day he decided to move to the countryside and start a new life as a farmer. He hadn't saved a lot of money, but it was enough to buy a circular field.
His life as a farmer didn't have a good start, as tragedy came before being able to enjoy his first crop. In the middle of his field a scarecrow was in charge of keeping birds at bay, but for some strange reason it was connected to a radioactive gas pipe coming from a nuclear plant close by. One morning the pipe broke and the gas escaped, destroying most of his field. Ignacio couldn't do anything about it, so only a thin strip on the border of his field remained intact. But that was not all, as the few surviving plants were soon attacked by a swarm of mutant insects. This time Ignacio wouldn't stand still, so he decided to fight the insect invasion with trained frogs.
On the perimeter of his circular field he created $N$ ponds for the frogs, which he numberd from $1$ to $N$ in clockwise order. Then he bought $R$ frogs in a shop specializing in trained circus frogs, and numbered them from $1$ to $R$. During the night he put the frogs in the ponds, placing the $i$-th frog in pond number $B_i$. The frogs are very well trained, so at first light they will start to jump at a rate of one jump per minute. Each frog repeats a pattern of jumps every $K$ minutes. The $i$-th frog will jump advancing $A_{i,1}$ ponds in clockwise order during the first minute; it will then jump advancing $A_{i,2}$ ponds in the same direction, and so on until the $K$-th minute, in which it will jump advancing $A_{i,K}$ ponds. After that, the same pattern will be repeated, advancing $A_{i,1}$ ponds in the $K+1$-th minute, $A_{i,2}$ ponds in the $K+2$-th minute, etc. For example, let's consider the case with $N=5$ ponds and $K=3$. In this case, if frog number $1$ starts in pond $B_1 = 2$, being its jumping pattern $A_{1,1}=1$, $A_{1,2}=2$ and $A_{1,3}=1$, during its fist few jumps it will land in the ponds in the following order: $2$, $3$, $5$, $1$, $2$, $4$, $5$, $1$, $3$, $4$, $5$, \dots.
Ignacio is really quite unlucky, because the first frog suffers from an contagious disease which has turned it into a vegetarian. When the sun comes out and all the frogs start jumping, if a sick frog meets a healthy one in some pond, it will transmit it with this disease. In our example with $N = 5$ and $K = 3$ if there are $R = 2$ frogs and the second frog starts at pond $B_2 = 4$ with a jumping pattern given by $A_{2,1}=1$, $A_{2,2}=1$ and $A_{2,3}=1$, it will visit the ponds in the order 4, 5, 1, 2, 3, 4, $\ldots$. Therefore, the first frog will transmit its disease to the second one after $5$ minutes, when both meet at pond number $4$. Generically, more and more frogs will get infected until either all of them are sick, or the remaining healthy frogs never meet with the sick ones, reaching at that point the maximum number of infected frogs.
While writing this story the night has gone by, and even if Ignacio noticed that the first frog is sick, he is now unable to catch it because it is trained so well. He will have to go directly to the trained circus frog shop to complain. As he wants to ask for a refund, he should wait until the disease spreads completely, reaching the maximum number of infected frogs. Ignacio doesn't want to wait longer than necessary, so in order to help him you should answer two questions: What is the maximum number of infected frogs? In which minute will the last transmission of the sickness take pla
Ignacio liked to take part in programming competitions such as the Argentinian Programming Tournament during his years as a university student. He was very happy, and when he graduated he got a good job. However, with time routine and life in the big city started to make him feel uneasy. So one day he decided to move to the countryside and start a new life as a farmer. He hadn't saved a lot of money, but it was enough to buy a circular field.
His life as a farmer didn't have a good start, as tragedy came before being able to enjoy his first crop. In the middle of his field a scarecrow was in charge of keeping birds at bay, but for some strange reason it was connected to a radioactive gas pipe coming from a nuclear plant close by. One morning the pipe broke and the gas escaped, destroying most of his field. Ignacio couldn't do anything about it, so only a thin strip on the border of his field remained intact. But that was not all, as the few surviving plants were soon attacked by a swarm of mutant insects. This time Ignacio wouldn't stand still, so he decided to fight the insect invasion with trained frogs.
On the perimeter of his circular field he created
N
ponds for the frogs, which he numbered from
1
to
N
in clockwise order. Then he bought
R
frogs in a shop specializing in trained circus frogs, and numbered them from
1
to
R
. During the night he put the frogs in the ponds, placing the
i
-th frog in pond number
B
i
. The frogs are very well trained, so at first light they will start to jump at a rate of one jump per minute. Each frog repeats a pattern of jumps every
K
minutes. The
i
-th frog will jump advancing
A
i,1
ponds in clockwise direction during the first minute; it will then jump advancing
A
i,2
ponds in the same direction, and so on until the
K
-th minute, in which it will jump advancing
A
i,K
ponds. After that, the same pattern will be repeated, advancing
A
i,1
ponds in the
K+1
-th minute,
A
i,2
ponds in the
K+2
-th minute, etc. For example, let's consider the case with
N = 5
ponds and
K = 3
. In this case, if frog number
1
starts in pond
B
1
= 2
, being its jumping pattern
A
1,1
= 1
,
A
1,2
= 2
and
A
1,3
= 1
, during its fist few jumps it will land in the ponds in the following order:
2
,
3
,
5
,
1
,
2
,
4
,
5
,
1
,
3
,
4
,
5
, ...
Ignacio is really quite unlucky, because the first frog suffers from a contagious disease which has turned it into a vegetarian. When the sun comes out and all the frogs start jumping, if a sick frog meets a healthy one in some pond, it will transmit it this disease. In our example with
N = 5
and
K = 3
if there are
R = 2
frogs and the second frog starts at pond
B
2
= 4
with a jumping pattern given by
A
2,1
= 1
,
A
2,2
= 1
and
A
2,3
= 1
, it will visit the ponds in the order
4
,
5
,
1
,
2
,
3
,
4
, ... . Therefore, the first frog will transmit its disease to the second one after
5
minutes, when both meet at pond number
4
. Generically, more and more frogs will get infected until either all of them are sick, or the remaining healthy frogs never meet with the sick ones, reaching at that point the maximum number of infected frogs.
While writing this story the night has gone by, and even if Ignacio noticed that the first frog is sick, he is now unable to catch it because it is trained so well. He will have to go directly to the trained circus frog shop to complain. As he wants to ask for a refund, he should wait until the disease spreads completely, reaching the maximum number of infected frogs. Ignacio doesn't want to wait longer than necessary, so in order to help him you should answer two questions: What is the maximum number of infected frogs? In which minute will the last transmission of the sickness take place?
Input
There are multiple test cases in the input file. For each test case, the first line contains three integer numbers
N
,
R
and
K
. The integer
N
represents the number of ponds in the field (
2 ≤ N
≤
10
9
),
R
represents the number of frogs (
2
≤
R
≤
200
) and
K
represents the number of minutes after which the frogs repeat their jumping pattern (
1
≤
K
≤
200
). The second line contains
R
integer numbers
B
1
,
B
2
, ...,
B
R
, representing the
i
-th number the initial position of the
i
-th frog (
1
≤
B_i
≤
N
for
i = 1, ..., R
, with
B
i
≠ B
j
if
i
≠
j
). The following
R
lines describe the behavior of the frogs. The
i
-th of these lines contains
K
integer numbers
A
i,1
,
A
i,2
, ...,
A
i,K
, representing the number of ponds the
i
-th frog advances in each of its
K
jumps, in the order in which they occur (
1
≤
A
i,j
< N
for
i = 1, 2, ..., R
and
j = 1, 2, ..., K
).
Output
For each test case, print a single line containing two integer numbers, representing the maximum number of infected frogs and the minute in which the last transmission of the disease takes place, respectively.
Example
Input:
5 2 3
2 4
1 2 1
1 1 1
1234 4 4
23 25 1000 67
20 4 26 222
18 28 1232 222
2 4 6 222
2 2 2 2
2 2 1
1 2
1
1
Output:
2 5
3 2
1 0 | 34,163 |
Joining lines (TAP2016J)
Two years ago we had a setback when Joaquín, a member of the jury, had an accident which prevented us from including the problem "Playing with lists" in that year's problem set for the Argentinian Programming Tournament. Thanks to the contest's participants, who kindly helped us solve that problem, we planned to include it in today's problem set. Unfortunately, we had a new inconvenience with Jacinto, another jury member.
As it happens, Jacinto doesn't like it when the sample test cases included along with the problem statements span more than one page. For the problem "Playing with lists", each test case consists of a single line with the description of a list. We don't want to say too much about them because the problem is definitely going to be used next year, so for now we'll just provide you with the total number of characters for each test case, clarifying that it's not allowed to "split" a test case in order to write it in multiple lines.
We would like to write the input for the
N
sample test cases in a single page, in which we can fit at most
L
lines of
C
characters each. The inconvenience appears when there are more sample test cases than there are lines available in the page, so that we cannot write each of them in a separate line. In order to circumvent this problem, Jacinto suggested drawing vertical segments spanning the whole height of the page, dividing it in two or more columns. These segments should have negligible width, so that the number of characters we can write in each line is not reduced, and will act as visual separators splitting each of the lines they cross. In this way, we can write each sample test case in a different line belonging to some column, as long as it doesn't cross the vertical segments. For the purposes of this problem, the order of the sample test cases is considered to be irrelevant.
For example, let's consider the situation in which there are
N = 5
sample test cases in a page fitting
L = 3
lines of
C = 11
characters each. If the test cases have
K
1
= 3
,
K
2
= 4
,
K
3
= 5
,
K
4
= 6
and
K
5
= 7
characters, we can split the page in two columns in such a way that one column has a width of
7
characters, while the other one has a width of
4
characters. In the larger column we may write the test cases with
K
3
= 5
,
K
4
= 6
and
K
5
= 7
characters in any order, whereas in the other column we can write the remaining sample test cases, having
K
1
= 3
and
K
2
= 4
characters, again in any order.
Thus, two possible ways in which we can fit the sample test cases in this example are
where for example
5/7
means we have used
5
of the
7
available characters in the corresponding column.
In an analogous situation for which the number of characters fitting in a single line is
C = 10
, we would need a column of at least
7
characters of width in order to write in it the larger sample test case. Therefore, it would be impossible to have any other column of width greater than
3
characters, which in turn means that
4
of the
N = 5
sample test cases should be written in the largest column. But this is clearly impossible, as there are only
L = 3
lines in the page. On the other hand, let us also note that although the sample test cases with
K
1
= 3
and
K
5
= 7
characters can in principle be written in a single line, as well as the sample tests cases with
K
2
= 4
and
K
4
= 6
characters, it is impossible to simultaneously put both pairs in one page in this way, as the width of each column should be the same along all the lines in the page.
Now we would like your help in order to determine if it is possible to make Jacinto happy by putting all the sample test cases in a single page as described above.
Input
There are multiple test cases in the input file. For each test case, the first line contains three integer numbers
N
,
L
and
C
. The integer
N
represents the number of sample test cases,
L
represents the maximum number of lines fitting in a page, and
C
represents the maximum number of characters fitting in a line (
1 ≤ N, L, C
≤
5000
). The second line contains
N
integer numbers
K
1
,
K
2
, ...
K
N
, representing the total number of characters in each sample test case (
1
≤
K
i
≤
C
for
i = 1, 2, ... N
).
Output
For each test case, print a single line containing a character representing if it is possible to write all sample test cases in a single page as described in the problem statement. The printed character should be an
'
S
'
if this is possible, and an
'
N
'
otherwise.
Example
Input:
5 3 11
3 4 5 6 7
5 3 10
3 4 5 6 7
3 3 4
1 3 2
6 3 4
1 3 1 2 1 1
Output:
S
N
S
S | 34,164 |
Koalas (TAP2016K)
Mabel Eucaliptos ha pasado toda la noche entren\'andose en el arte de comer hojas de eucalipto. Finalmente est\'a preparada para enfrentar a su malvada archin\'emesis, Pac\'ifica, en un \'ultimo juego que intentar\'a decidir de una vez por todas qui\'en de las dos es la mejor koala.
El juego se llevar\'a a cabo en un bosque constituido por $N$ \'arboles de eucalipto numerados del $1$ al $N$. Los \'arboles est\'an conectados por $N - 1$ cuerdas. Cada cuerda conecta dos \'arboles diferentes, y permite a las koalas desplazarse de cualquiera de ellos al otro. El bosque de eucaliptos es tal que es posible ir de cualquier \'arbol a cualquier otro usando sucesivamente estas cuerdas.
Los \'arboles de eucalipto contienen una cantidad no negativa de hojas. Cuando un \'arbol contiene cero hojas, se dice que est\'a vac\'io. Inicialmente ninguno de los $N$ \'arboles en los que se desarrollar\'a el juego se encuentra vac\'io.
Antes de empezar el juego, a cada koala se le asigna un \'arbol diferente. Al principio de la partida cada jugadora sube al \'arbol que le fue asignado y come todas las hojas que este contiene, dej\'andolo vac\'io. A continuaci\'on, juegan alternadamente, siendo Mabel la encargada de realizar el primer movimiento. En cada turno la jugadora correspondiente se mueve a un \'arbol no vac\'io que est\'e conectado por una cuerda con el \'arbol en el que se encuentra ella. Seguidamente come todas las hojas que este nuevo \'arbol contiene, dej\'andolo vac\'io. En caso de no poder realizar un movimiento v\'alido, permanece donde est\'a y pasa a ser el turno de la otra jugadora. El juego termina cuando ninguna de las dos puede hacer un movimiento v\'alido.
Una vez finalizada la partida, se cuentan las hojas que comi\'o cada koala, y se calcula la diferencia entre la cantidad que comi\'o Mabel y la cantidad que comi\'o Pac\'ifica. Mabel jugar\'a tratando de maximizar dicha diferencia, mientras que Pac\'ifica lo har\'a intentando minimizarla. Su tarea es determinar cu\'al ser\'a el resultado del juego, suponiendo que ambas juegan de manera \'optima.
Mabel Eucalyptus spent last night training in the art of eucalyptus leaf eating. She is finally ready to face her evil arch-nemesis, Peaceful, in a last game which will decide once and for all which of them is the best koala.
The game will take place in a forest containing
N
eucalyptus trees numbered from
1
to
N
. The trees are connected by
N-1
ropes, each of which joins two different trees. These ropes allow koalas to move from one tree to the other, and the eucalyptus forest is such that it is possible to go from a given tree to any other successively using the ropes.
The eucalyptus trees contain a non-negative amount of leaves. When a tree contains no leaves, we say it is empty. Initially, none of the
N
trees in the forest is empty.
Before commencing the game, each koala is assigned a different tree. At the beginning of the game, each player climbs the tree that was assigned to her and eats all the leaves it contains. After that both players take turns, Mabel being in charge of making the first move. In each turn, the corresponding player moves to a non-empty tree connected by a rope to the tree she is currently in. Then, she eats all the leaves this tree contains, thus leaving it empty. If a player can't make a valid move in her turn, she forfeits her turn staying wherever she is, and the other player gets to move again. The game ends when both players cannot make a valid move.
Once the game has finished, the number of leaves eaten by each koala is counted, and the difference between the amount eaten by Mabel and the amount eaten by Peaceful is calculated. Mabel will play aiming to maximize this difference, whereas Peaceful will play to minimize it. Your task is to determine what the result of the game will be, assuming that both koalas play optimally.
Input
There are multiple test cases in the input file. For each test case, the first line contains three integer numbers
N
,
M
y
P
, representing the number of trees in the forest, the tree where Mabel starts, and the tree where Peaceful starts, respectively (
2 ≤ N
≤
10
5
and
1
≤
M, P
≤
N
with
M ≠ P
). The second line contains
N
integer numbers
C
1
, C
2
, ..., C
N
, representing
C
i
the number of leaves contained in the
i
-th tree (
1
≤
C
i
≤
100
for
i = 1, 2, ..., N
). Each of the following
N-1
lines contains two integer numbers
U
and
V
, representing that there is a rope connecting trees number
U
and
V
(
1
≤
U, V
≤
N
with
U ≠ V
).
Output
For each test case, output a single line containing an integer number, representing the difference between the number of leaves eaten by Mabel and the number of leaves eaten by Peaceful if both of them play optimally.
Example
Input:
2 1 2
5 3
1 2
6 2 3
1 6 4 3 2 2
1 2
2 3
3 4
3 5
5 6
Output:
2
-1 | 34,165 |
Leonardo de Pisa (TAP2016L)
Leonardo de Pisa is a very cautious man, and even though Christmas is still many months away, he has already bought his Christmas tree. It is a very, very high tree, even higher than the Tower of Pisa. Leonardo wishes to decorate his tree by using colored balls and lights. To that end, he has bought many balls of each possible integer diameter between 1 and N. In fact, he has bought so many balls that he has no idea of what to do with all of them.
In Pisa, each ball has two cords hanging from it, to which other balls can be attached. By doing so, they make sure that the balls never fall from the tree and roll all the way across the floor, until finally stopping underneath a big piece of furniture where they cannot easily be found. All of the cords hanging from all of the balls have a length of 20 centimeters.
Just like any good Christmas tree, Leonardo's tree has a top. On it, Leonardo will place a ball of diameter N, as those are the most alluring. All of the other balls in the tree will hang from this top ball either directly, or indirectly by means of other balls. Leonardo has carefully studied the way in which he must hang the balls so that his tree is the most beautiful tree in all of Pisa, and he has arrived at the following conclusions:
* No ball of diameter 1 or 2 must have another ball hanging from it.
* Every ball of diameter k >= 3 must have two balls hanging from it: one of diameter k-1, and the other of diameter k-2.
The following pictures show two examples of how Leonardo's tree would look after decorating it with balls. The left figure corresponds to the case in which he buys every ball up to diameter N = 4, while the right figure corresponds to the case with balls of diameter up to N = 5 (the number written on each ball indicates its diameter).
There is always enough room for Leonardo to add as many balls as he wants, for his tree is incredibly tall. However, he still feels that his tree is not the most beautiful tree in the city: It is missing colored lights!
Leonardo has bought a special string of lights suitable for trees with balls. The string has K lights tied together by cord, such that the lights are separated from each other by 20 centimeters of cord. Each light fits perfectly onto some balls, depending solely on their size: a light of type i only fits onto balls of diameter i, for each i between 1 and N. If the diameter of the ball is larger than i, the ball will not fit, and if it is smaller than i, the light will fall to the floor. Two lights can never be attached to the same ball, and the cord between the lights must always be perfectly tight. In particular, that means that if there is no cord in the tree between two balls, then their distance will not be exactly 20 centimeters, and so it will not be possible to place two consecutive lights on top of them.
The following picture shows four different strings of lights, colored gray.
By the time that Leonardo bought the string of lights, he had already finished decorating his tree with balls. It was such an effort to do so, that he is completely determined not to add, remove, or move any ball from the tree. Now he does not know if he will be able to use the string of lights that he bought, as he needs to find a sequence of balls in the tree that are adequately hanging from each other, and that have precisely the diameters that the lights fit onto.
For example, the first string previously shown can be placed on each of the two trees; the second one can only be placed in the second tree; the third and fourth strings cannot be placed on any tree. The following picture shows the first string placed on the first tree, and the second string placed on the second tree.
Help Leonardo to know, given the string of lights and the diameter N of the largest ball that he bought, whether it is possible to place the string of lights on his tree
Leonardo de Pisa is a very cautious man, and even though Christmas is still many months away, he has already bought his Christmas tree. It is a very, very high tree, even higher than the Tower of Pisa. Leonardo wishes to decorate his tree by using colored balls and lights. To that end, he has bought many balls of each possible integer diameter between
1
and
N
. In fact, he has bought so many balls that he has no idea of what to do with all of them.
In Pisa, each ball has two cords hanging from it, to which other balls can be attached. By doing so, they make sure that the balls never fall from the tree and roll all the way across the floor, until finally stopping underneath a big piece of furniture where they cannot easily be found. All of the cords hanging from all of the balls have a length of 20 centimeters.
Just like any good Christmas tree, Leonardo's tree has a top. On it, Leonardo will place a ball of diameter
N
, as those are the most alluring. All of the other balls in the tree will hang from this top ball either directly, or indirectly by means of other balls. Leonardo has carefully studied the way in which he must hang the balls so that his tree is the most beautiful tree in all of Pisa, and he has arrived at the following conclusions:
No ball of diameter
1
or
2
must have another ball hanging from it.
Every ball of diameter
k ≥ 3
must have two balls hanging from it: one of diameter
k-1
, and the other of diameter
k-2
.
The following pictures show two examples of how Leonardo's tree would look after decorating it with balls. The left figure corresponds to the case in which he buys every ball up to diameter
N = 4
, while the right figure corresponds to the case with balls of diameter up to
N = 5
(the number written on each ball indicates its diameter).
There is always enough room for Leonardo to add as many balls as he wants, for his tree is incredibly tall. However, he still feels that his tree is not the most beautiful tree in the city: It is missing colored lights!
Leonardo has bought a special string of lights suitable for trees with balls. The string has
K
lights tied together by cord, such that the lights are separated from each other by 20 centimeters of cord. Each light fits perfectly onto some balls, depending solely on their size: a light of type
i
only fits onto balls of diameter
i
, for each
i
between
1
and
N
. If the diameter of the ball is larger than
i
, the ball will not fit, and if it is smaller than
i
, the light will fall to the floor. Two lights can never be attached to the same ball, and the cord between the lights must always be perfectly tight. In particular, that means that if there is no cord in the tree between two balls, then their distance will not be exactly 20 centimeters, and so it will not be possible to place two consecutive lights on top of them.
The following picture shows four different strings of lights, colored gray.
By the time that Leonardo bought the string of lights, he had already finished decorating his tree with balls. It was such an effort to do so, that he is completely determined not to add, remove, or move any ball from the tree. Now he does not know if he will be able to use the string of lights that he bought, as he needs to find a sequence of balls in the tree that are adequately hanging from each other, and that have precisely the diameters that the lights fit onto.
For example, the first string previously shown can be placed on each of the two trees; the second one can only be placed in the second tree; the third and fourth strings cannot be placed on any tree. The following picture shows the first string placed on the first tree, and the second string placed on the second tree.
Help Leonardo to know, given the string of lights and the diameter
N
of the largest ball that he bought, whether it is possible to place the string of lights on his tree.
Input
There are multiple test cases in the input file. For each test case, the first line contains two integers
N
and
K
, with
N
representing the maximum diameter of the balls, and
K
representing the number of lights in the string (
2 ≤ N, K
≤
10
5
). The second line contains
K
integers
L
1
, L
2
, ..., L
k
describing the string of lights. The ith integer
L
i
represents the type of the
i-
th light in the string (
1
≤
L
i
≤
N
for
i
between
1
and
K
).
Output
For each test case, write a single line containing a single character, indicating whether Leonardo can place the string of lights or not. The character must be an '
S
' if Leonardo can place the string of lights, and an '
N
' otherwise.
Example
Input:
3 2
2 3
4 4
1 3 4 2
5 2
3 5
4 2
4 1
6 3
2 3 2
8 4
2 3 3 1
10 10
2 3 4 5 6 8 7 5 3 1
Output:
S
S
S
N
N
N
S | 34,166 |
Single substitutions (REDSUBLIA)
In the land of Redsublia, they always write words with exactly one letter changed. All words are 6 letters long, made up of lower-case characters from a-z. So if the word was abcdef, they might write gbcdef or azcdef.
Of course, this means that sometimes when they write a word, it might be ambiguous.
In school, they are given some words to learn, and then tested on them. Of course, in the tests, the words are written with one letter changed for another. Sometimes, they are tested with words that don't exist, or are ambiguous. They are asked to find the lexicographically smallest word that matches out of the words that they have learned so far.
Bugsy is struggling at school. Please help him.
Input
The first line contains N, the number of test cases.
The next line contains L the number of lines in the input for this test-case.
Each line will either add a word to the dictionary
W
<word>
Or suggest a word to look up in the dictionary so far.
Q
<query>
Output
The first line should contain:
Test
<test case>
Then for each line of input that is a query, print the (lexicographically smallest) word. If there are no possible words, print 0.
Example
Input:
1
6
W abcdef
Q bacdef
Q abcdef
W abadef
Q abcdeg
Q abgdef
Output:
Test 1
0
0
abcdef
abadef
Notes on example
In the first query, bacdef does not match abcdef as 2 characters have changed.
In the second query, abcdef does not match abcdef as 0 characters have changed.
In the third query, abcdeg matches abcdef as 1 character has changed - the last.
In the fourth query, abgdef matches both abcdef and abadef. abadef is lexicographically smaller.
Constraints
1 ≤ N ≤ 10
1 ≤ L ≤ 70000
words and queries are all 6 characters long, using lower-case a-z. | 34,167 |
Ada and Easy Game (ADAGAME2)
Ada the Ladybug is frequently playing board games against her friend Velvet Mite Vinit. Last time, they were playing
Game of Digits
. Anyway Vinit is slightly mad at Ada, because she "cheated". She let one of her good friends to make program which helped her significantly. As Vinit wants to avoid this, he created
Game of Piles
with his own rules. He puts many piles with many nuts on the table. He then chooses a few numbers (rules), which are possible moves. Ada and Vinit play alternately (as Vinit is gentleman, Ada starts). In each move one can choose a pile, any number from rules (not greater than the number of nuts in the pile) and eats that many nuts from pile. The one who can't move looses. Vinit is very excited to play since he is ensured Ada can't cheat this time.
Well that was just a fun fact from world of bugs and now lets solve some completely different problem. Your good friend Ada has asked you to help her win a game against one of her friends...
Input
First line of input will consist
T ≤ 200
number of test-cases.
Each testcase will begin with two numbers
0 < N ≤ 10
5
[number of piles] and
0 < M ≤ 30
[number of rules].
The next line will consist of
M
numbers,
1 ≤ R
i
≤ 10
5
[rules]
The last line of each test-case will consist of
N
numbers,
1 ≤ P
i
≤ 10
5
[sizes of pile]
Output
For each test-case, print the name of winner ("
Ada
" or "
Vinit
") [if both played optimally].
Example Input
6
4 1
2
1 2 3 4
4 2
1 2
4 4 3 5
1 3
2 3 5
20
2 2
1 3
4 7
5 5
1 2 7 13 15
10 20 30 40 50
1 2
1 2
98997
Example Output
Vinit
Ada
Ada
Ada
Ada
Vinit | 34,168 |
Guess the Queue (BDOI16A)
Busland is a city where the only means of transportation are buses. To get on a bus in Busland, people have to wait in a queue. Each person has a
unique
bus
ID
. The person at the front is considered the first person and the person at the back is considered the last person in the queue. Trivially, the first person will get on the bus first and the last person will get on last.
It is well known that you should enter at the back of the queue. However, some people are very late and even though it is considered very rude, they try to enter in an alternative way. Since the sides of the queue are barricaded, the only alternative way is to enter from the front of the queue. Sometimes there are also people at the back of the queue, who become tired of waiting. They exit the queue from the back and just start walking to their destination instead.
Your task is to deal with three types of operations as follows:
'
1
x y
' The person with
ID
y
enters from the back or front, if
x
is '
B
' or '
F
' respectively.
'
2
x
' The person in the back or front exits the queue, if
x
is '
B
' or '
F
' respectively.
'
3
x y
' Find the
ID
of the person in the
y
th position of the queue or the position of the queue, where the person with
ID
y
is currently situated, if
x
is '
D
' or '
P
' respectively.
Input
The first line of input will contain the number of test cases,
T
(1 <=
T
<= 5)
. Then
T
cases follow.
Each case starts with an integer
N
, denoting the total number of operations. The following
N
lines will contain one of the three types described previously. The operations are in chronological order.
It is guaranteed that the given input is always valid. Thus, for the second type operation, the queue will always be non-empty and for the third type, the given position or
ID
will always exist in the queue. Also, a person who has already exited, will not enter the queue again.
Constraints
For the
easy
version,
1 <=
N
<= 2000
For the
hard
version,
1 <=
N
<= 200000
In general,
1 <= each ID <= 10^9,
IDs are
unique
for each person.
1 <= each position <= current size of the queue
.
Output
For each case, print the case number on a single line, in the format “
Case x:
”, where
x
is the case number.
For each operation of the third type, output a single integer, which denotes the answer of the query.
Example
Input:
1
7
1 B 1
1 B 2
1 F 3
3 D 3
2 B
1 F 4
3 D 2
Output:
Case 1:
2
3
Explanation of the Sample
There is only 1 test case, in which we have to perform a total of 7 operations.
At first, the queue is empty. A person with
ID 1
and
2
enters from the back. After that, a person with
ID 3
enters from the front. Now there are
3
people in the queue and the
ID
of the
3
rd
person in the queue is
2
.
The person in the back (who has
ID 2
) exits the queue. This leaves only two people remaining.
Finally, a person with
ID 4
enters from the front. Now there are again
3
people in the queue and the
ID
of the
2
nd
person of the queue is
3
.
Problem Setter: Aninda Majumder | 34,169 |
Beautiful Factorial Game (BDOI16B)
The statement of this problem is very simple. Given two number n and k, you need to find the maximum power of k (i.e. x) such that n! % k
x
= 0. Here n! is the notation of n factorial. If you are not familiar with the notation,
n! = 1 * 2 * 3 * 4 * 5 * 6 ... * n
Input
First line of the input will contain an integer t (1 ≤ t ≤ 20) denoting the number of test case. The next t lines contain two integer number n and k as described above.
Constraints
For easy version, 1 ≤ n ≤ 10, 2 ≤ k ≤ 10
For harder version, 1 ≤ n ≤ 100000000, 2 ≤ k ≤ 100000000
Output
For each test case, print “Case t: x” where t is the test case number and x is the maximum power of k for which n! % k
x
= 0.
Example
Input:
2
5 2
1000 2
Output:
Case 1: 3
Case 2: 994
Explanation
In the first test case, n = 5 and k = 2. So, n! = 120.
120 % 2
0
= 0
120 % 2
1
= 0
120 % 2
2
= 0
120 % 2
3
= 0
120 % 2
4
= 8
120 % 2
5
= 24
120 % 2
6
= 56
120 % 2
7
= 120
So, the answer should be 3.
Problem Setter: Rakibul Islam | 34,170 |
Counting Magical Permutatitons (BDOI16C)
In a planet far away from Earth, there is a beautiful country named Magicland. The children of this country play a lot of interesting games with numbers. One of the most popular games is called Inversion. In this game, you will be given numbers from 1 to N. They are given in a certain order. You need to calculate all the inversions in the given permutation of the numbers. S/he who can say it first correctly wins the game. An inversion occurs when there exists a pair of indices i and j such that i < j and given number at i-th position is greater than the number at j-th position.
For example, let us consider a permutation of numbers 1 to 5: 5, 1, 4, 2, 3. This permutation has the following inversions: (5, 1), (5, 4), (5, 2), (5, 3), (4, 2), (4, 3). Therefore, the number of inversion will be 6. The first person to tell this number correctly will win this game.
For this problem, we want to know how many permutations of the numbers 1, 2, ... N will have at least K inversions.
A permutation X is different from another permutation Y if there exists some
i
(1 <= i <= N) for which the number in i-th position is different in these two permutations.
Input
The first line of input file contains the number of test cases,
T
(1 <= T <= 50). Then
T
cases follow:
Each case consists of one line which contains two integers:
N
and
K
.
Constraint
For Easy version,
1 <= N <= 200
and
0 <= K <= 300
.
For Hard version,
1 <= N <= 2000
and
0 <= K <= 3000
.
Output
For each case, print “
Case x: y
” in a separate line, where
x
is the case number and
y
is the number of permutations with at least
K
inversions. As the number can be very large, print
y modulo 10,007
.
sample
Input:
3
3 1
2 1
3 2
Output:
Case 1: 5
Case 2: 1
Case 3: 3
Problem Setter: Anindya Das | 34,171 |
One Punch Man (BDOI16D)
Saitama is the most powerful hero alive. Having apparently trained himself to superhuman conditions, Saitama faces a self-imposed existential crisis, as he is now too powerful to gain any thrill from his heroic deeds. Every monster he faces, is killed with only one of his punch.
There are
N
groups of monsters on a line,
i
th of them is positioned at distance
X
i
from the beginning of that line and has
V
i
members. When Saitama punches the ground at
P
, all monsters within
R
vicinity of that punch (meaning from
P-R
to
P+R
both inclusive) are killed by the shockwave. Saitama is tired after all his hero duties. So he will punch at most
K
times. Can you help him figure out, what is the maximum number of monsters he can kill.
Input
The first line contains number of test cases
T
. Then
T
test cases follow. First line of each test case contains three integers
N
,
R
and
k
. Following
N
lines contains two space separated integers
X
i
and
V
i
.
Output
For each test case, print a line "Case t: m" where t is the test case number and m is the the maximum number of monsters Saitama can kill.
Limits
T
≤ 10
1 ≤
N
≤ 10
5
1 ≤
V
i
≤ 10
4
1 ≤
K
≤ 50
For
Easy
Version: 0 ≤
R, X
i
≤ 10
4
For
Hard
Version: 0 ≤
R, X
i
≤ 10
8
Sample
Input:
2
4 3 1
6 10
12 110
19 100
24 30
5 3 2
3 3
5 2
3 8
10 5
0 5
Output:
Case 1: 130
Case 2: 23
Explanation of Sample
In sample 1, Saitama can punch at position 21 or 22 to kill 130 monsters. If he punches at position 21 then the shockwave ranges from 18 to 24, killing monsters at 19 and 24. Similarly if he punches at 22 then then shockwave will kill from 19 to 25. Punch at no other position will kill more monsters.
In Sample 2, Saitama can kill all monsters with 2 punches.
Problem Setter: Moinul Shaon | 34,172 |
Village Fair (BDOI16E)
There are N houses in a village far away from here. They are numbered from 1 to N. For this problem lets assume, the houses each can accommodate infinite amount of people.
From each house there is a directed path to exactly one other house
. One of the houses is a grand house. There is a fair going on currently in the grand house. From this house there is no exit, and everybody can enjoy the festival here. Initially there is a little kid in each of the houses of the village. Each kid has some non-negative amount of joy (they are all pretty excited about the fair). It is guaranteed that there is exactly one simple way from each house to the grand house.
Every kid from their house starts their journey to the grand house. When they go from a house to some other house, their joy changes by some positive or negative amount. This change depends on the path.
Now, for each houses, you have to count the number of distinct joy values that will come to this house at some point of time. Note that if two or more persons with the same joy value will be counted only once. See the sample explanation for details.
Input
You are given an integer N in the first line. The next line will contain N integers, the initial joy value of the kids in the houses. The next line also contains N integers, where the kth integer is the id of the house where the kids can go to from the kth house or 0 if it is the grand house. The fourth line will contain N integers, the amount of change of joy that will occur if one person goes through the path from starting at kth house or 0 if it is the grand house.
Output
Print N lines, each containing the number of distinct joy values that will come to this house at some point of time.
Sample
Input
5
7 3 2 5 1
0 1 1 3 3
0 4 1 0 4
Output
3
1
2
1
1
Explanation of Sample
Initially each house will contain the kids with joy { 7, 3, 2, 5, 1 }. The first kid always stays in the grand house. The second kid will go to the grand house with joy 7. The third kid will go to the grand house with joy 3. The fourth kid will go to third house with joy 5 and from there he will make it to grand house with 6 joy. Same goes for fifth person.
So the first house will see { 7, 7, 3, 6, 6}. The second house will see {3}. The third house will see {2, 5, 5} The fourth house will see { 5 } and the fifth house will see { 1 }.
So the number of distinct joy values of each house is { 3, 1, 2, 1, 1}.
Limits: Easy (1 <= N <= 1000), Hard (1 <= N <= 100000).
Problem Setter:
Nafis Sadique | 34,173 |
Sinha and Eggs (SINEGGS)
Sinha is a naughty kid, who always irritates Shukla with his activities. One day Sinha bought some eggs, but indulged in his pranks, forgets them in Shukla's room. Shukla being a considerate friend wanted to teach Sinha a lesson. He puts a condition in front of Sinha, he will give him a number and Sinha has to tell if it has an "Odd" number of factors. If Sinha answers the questions correctly, he shall return the eggs. Since, Sinha can't focus on the problem due to his mischievous nature, he asks you to help him.
Input
You are given a number 't' in first line depicting number of test cases. The next n lines contain a number 'n' each.
Input Constraints:
1 < =T <= 100000
1<= N <= 10^11
Output
You have to print "YES" if the number 'n' has an odd number of factors, else print "NO".
Example
Input:
3
10
4
6
Output:
NO
YES
NO | 34,174 |
Descending Alternating Sums (DALTSUM)
Given an array
A
of
k
integers (not necessarily distinct), we define the
descending alternating sum
of this array, denoted
F(A)
the following way. First, we sort the array in descending order. Suppose the elements, after sorting, are
A
1
≥
A
2
≥ ... ≥
A
k
respectively. Then the descending alternating sum of array
A
is
F(A) =
A
1
- A
2
+ A
3
- ... + (-1)
k+1
A
k
.
For example, if
A = [5, -3, 8, 2, 0, -5]
then after sorting it in descending order, we find
A = [8, 5, 2, 0, -3, -5]
. So the descending alternating sum of this array is
8 - 5 + 2 - 0 + (-3) - (-5) = 7
. In particular, the descending alternating sum of an empty array is
0
.
You are given an array
A
of
n
integers where
1 ≤ n ≤ 10
5
and
|A
i
| ≤ 10
18
. You have to print the sum of the descending alternating sums of all subsets of this array
A
(there are
2
n
of them) modulo
M = 10
9
+ 7
. In other words, if the subsets of array
A
are
S
1
, S
2,
..., S
2
n
then you have to print the sum
F(
S
1
) + F(
S
2
) + ... + F(
S
2
n
)
modulo
M =
10
9
+ 7
.
Note: we consider some integer modulo a positive integer to be non-negative. In the other words, the output
R
must satisfy the inequality
0 ≤
R < M
.
Input
The first line of the input file contains a single integer
n
, denoting the size of the array
A
.
The second line contains
n
integers
A
1
, A
2
, ..., A
n
, the elements of the array
A
.
Output
Print a single integer, the sum of descending alternating sums of all subsets of the array
A
.
Example
Input:
3
-1 9 3
Output:
36 | 34,175 |
Boat Burglary (BURGLARY)
Rachid lives on a boat, and owns only a few items, n to be precise. He takes big care of his items, and measured the weight of each of them with high precision. Item i weights W
i
micrograms. One night a thief visits his boat and steels some items. Rachid notices that the next morning, because the boat is lighter, and he could measure from the water level that this difference is D micrograms. He would like to know how many items are missing, just by examining these weights, and asks you for help.
Input
The first line of the input consists of the number of test cases, T. T test cases follow. Each case consists of two lines, the first one containing two integers N and D, separated by a space. Then second line contains n integers, representing the weights of all items, separated by space.
The input satisfies the following limits.
1 ≤ T ≤ 20
1 ≤ N ≤ 30
0 ≤ D ≤ 3*10
10
0 ≤ W
i
≤ 10
9
Output
For each test case output one line containing "Case #x: y", where x is the case number (starting from 1). If the number of missing items could be determined, then y is this number. If there are several answers to the problem y is the string "AMBIGIOUS" and if there is no answer y is the string "IMPOSSIBLE" (quotes added for clarity and are not part of the output).
Example
Input:
4
5 10
2 3 6 9 5
5 20
1 4 2 3 15
5 20
1 4 5 15 27
5 16
1 2 4 8 32
Output:
Case #1: 3
Case #2: 3
Case #3: AMBIGIOUS
Case #4: IMPOSSIBLE | 34,176 |
Ghost Town (COUNT1IT)
You are given
n
numbers initially. You have to maintain a
multiset
for those
n
numbers. Then you are given
q
queries. Queries will be one of the following types:
1 x
: Let
a
be the count of elements smaller than or equal to
x
. Add
x+a
into the multiset.
2 y
: report the number of numbers in the multiset that are smaller than or equal to
y
.
3 z
: report the
z
th smallest number of the multiset. Note that if any number
d
appears more than once, it is to be counted as many times it appears! Also, if z exceeds the number of elements in the
multiset
, that is answer for this query doesn't exist, print "
invalid
". Look at the sample input for clarification.
Note
Since it is a
multiset
, it will also store duplicates. Also, lets say our multiset has elements 1, 2, 2, 3, 3, 3. then for z=3, answer would be
2
.
Constraints
1 ≤ n ≤ 100000
1 ≤ q ≤ 100000
1 ≤ x ≤ (10
9
- 2 × 10
5
)
1 ≤ y, z ≤ 10
9
1 ≤ Initial elements of the multiset ≤ (10
9
- 2 × 10
5
)
Input
The first line will contain two integers, n and q, denoting the number of initial members of the multiset and the number of queries.
Next q lines will be of he form:
Type D :
That is, the queries will be of the one of given 3 types and accordingly, you will be given an integer D.
Output
You have to print the output for query numbers
2
and
3
.
Example
Input:
10 20
7 35 44 25 15 10 21 42 12 33
1 6
1 39
2 47
2 96
1 29
2 40
3 27
3 5
1 22
1 44
3 32
1 28
3 2
2 39
3 23
2 31
1 13
1 50
3 38
2 26
Output:
11
12
10
invalid
15
invalid
7
12
invalid
8
invalid
8 | 34,177 |
Urinals (URI)
Anyone that ever went to men's restroom knows about International Choice of Urinal Protocol. It reads as follows:
This protocol specifies the rules of choosing a urinal, for a given row of urinals (some of them may be already taken).
One should choose a urinal that maximizes the distance to the closest urinal that is already taken.
If there is more than one urinal satisfying the condition above, one should choose a urinal that is the farthest from the door.
One must not take a urinal that is adjacent to an already taken urinal. This rule is introduced in order to avoid Awkwardness.
There is a row of
n
urinals, numbered with consecutive integers, from left to right, starting with 1. The door is located to the right of the urinal number
n
. At first, the restroom is empty. Let's assume that people are coming in, one by one, taking the urinals according to the Protocol, without freeing them up in the meantime. Which urinal will be chosen by the
k
-th person?
Input
The first line contains a single integer
t
, denoting the number of test cases. Then t test cases follow.
Each test case is a single line, containing two natural numbers
n
and
k
.
(1 ≤
k
≤
n
≤ 10
18
)
Output
For every test case you should print one line containing the number that corresponds to a urinal taken by the
k
-th person coming to the restroom with
n
urinals. If there is no way for that person to pick a urinal without violating the Protocol, you should print "OOPS" instead.
Example
Input:
10
5 1
5 2
5 3
5 4
5 5
9 5
9 6
19 8
23 6
27 12
Output:
1
5
3
OOPS
OOPS
7
OOPS
12
9
OOPS | 34,178 |
Try to complete (TRYCOMP)
You are given hundreds of thousands of words from a book.
For each query you are given a string S. Find the most occurring word in the book with S as prefix.
Input
The first line consists of an integer n, the number of words in the text book. The next n lines consists of the words in the book. The next line consists of an integer q, the number of queries. Next q lines consists a string S.
Output
For each query String S, print the most occurring word in the book with S as prefix along with the number of occurrences of that word.
If there are many such words, print the lexicographically smallest word. If there is no such word, print -1.
Constraints
1 ≤ n ≤ 5×10
5
1 ≤ q ≤ 10
5
1 ≤ word length ≤ 10
All the characters in the word are lowercase letters of the English alphabet.
Sample
Input
10
apple
banana
orange
applet
banana
oriental
orange
oriental
applet
bangalore
8
ban
bang
app
or
oriental
apple
hobbits
oranges
Output
banana 2
bangalore 1
applet 2
orange 2
oriental 2
applet 2
-1
-1
Problem source: Inspired from autocomplete feature on Google keyboard. | 34,179 |
Pizza Store and Gasoline (GASOLINE)
A pizza delivery company owner gives you a map which contains n locations and m connecting roads. (vertices and edges). The locations are numbered from 0 to n-1. You are also given the length of each road. To travel, one unit distance, the motor bike needs 1 unit of gasoline. The company owner neither has the delivery location of the pizza nor the location of the stores.
Now the company owner asks you "What is the minimum amount of Gasoline needed in a motor bike to deliver one pizza order?". Can you answer him?
Input
The first line consists of an integer t, the number of test cases. For each test case, the first line consists of two integers n and m denoting the number of locations and roads respectively. The next m lines consists of 3 integers a, b and l denoting the road that connects two locations a and b with length l.
Output
For each test case, find the minimum amount of gasoline needed in order to deliver one pizza order.
If it is impossible to deliver the order, print -1.
Constraints
1 ≤ t ≤ 50
1 ≤ n ≤ 500
0 ≤ m ≤ 500
a ≠ b
1 ≤ l ≤ 100
Sample
Input:
1
12 12
0 1 2
1 3 3
1 6 2
6 7 8
7 10 1
10 11 1
11 5 5
2 3 7
5 2 6
4 5 2
8 5 4
8 9 2
Output:
24
Explanation
For the given test case, 24 units of gasoline is sufficient to deliver a pizza regardless of the store location and delivery location.
Note
There can be more than one road between a pair of locations. | 34,180 |
Game of Iron Thrones (GOIT)
You and your friends are playing Game of Iron Thrones. When you play the Game of Iron Thrones, you roll n biased dice together. You know how biased the dice are on each face.
Find the probability that you will get at least K 6's.
Input
The first line consists of an integer t, the number of test cases. For each test case, the first line consists of two integers n - the number of dice and K - as defined above. The next n lines consists of 6 decimal numbers denoting the probability of getting the corresponding face. (Face 1 to 6)
Output:
For each test case, find the probability to get at least K 6's when you roll all the n dice at once. Your solution's absolute or relative error must be strictly less than 10
-2
. (i.e. your solution can make mistakes up to 0.01)
Constraints
1 ≤ t ≤ 100
1 ≤ n ≤ 1000
1 ≤ K ≤ 1000
Example
Input:
4
6 6
0 0 0 0 0 1
0 0 0 0 0.5 0.5
0 0 0 0 0 1
0 0 0 0 0 1
0 0 0 0.5 0 0.5
0 0 0 0 0 1
3 1
0.2 0.2 0.2 0.2 0.2 0
0.2 0.2 0.2 0.2 0.2 0
0 0 0 0 0 1
3 2
0.2 0.2 0.2 0.2 0.2 0
0.2 0.2 0.2 0.2 0.2 0
0 0 0 0 0 1
2 1
0.2 0.2 0.2 0.2 0 0.2
0 0 0 0.5 0.25 0.25
Output:
0.25
1
0
0.4
Explanation
Case 1:
There are 6 dice and we need at least 6 sixes. The probability to get 6 in all dice = 1 × 0.5 × 1 × 1 × 0.5 × 1 = 0.25.
Case 2:
There are 3 dice and we need exactly one 6. No matter how many times you throw the dice, you will always get at least one 6.
Case 3:
There are 3 dice and we need at least two 6s. For the given biased dice in which two of them never turns 6 the probability will be 0.
Case 4:
Note that there can be more than K 6's. The probability in this case would be 0.2 × 0.25 + 0.2 × (1 - 0.25) + (1 - 0.2) × 0.25 = 0.4.
Note:
Avoid COUT for this problem as it will print the result in scientific notation. | 34,181 |
Coin Fight (KATHTHI2)
Sathish and Kathiresan are known for Coin Fight. Kathiresan kept on tossing a biased coin repeatedly. Then he decided to solve the following problem.
Find the number of tosses for which the probability of getting exactly K heads is maximum. In case of a tie, return the minimum number of tosses.
In other words, find the minimum n such that probability (exactly K heads with n tosses) >= probability (exactly K heads with m tosses) for any m!=n.
Input:
The first line consists of an integer t, the number of test cases. For each test case you are given an integer K, the number of heads required and a float p, the probability to get a head when the coin is tossed.
Output:
For each test case find the number of tosses required as defined.
Input Constraints:
1 <= t <= 100
1 <= K <= 100
0.00 < p <= 1.00
p will always contain a maximum of 2 decimal places
Sample
Input:
3
5 1.00
1 0.50
2 0.30
Output:
5
1
6 | 34,182 |
IIITM Student (IIITMSTUD)
There are N groups students in IIITM each group numbered 1 to n. The ith group contains a[i] number of students.
There are some classroom in IIITM and each classroom has some seats.
All the students of same group have to be in same class and there shouldn't be any seat left.
Moreover group shouldn't change their relative position while taken their seats in class room i.e. group 3 take their seat if and only if group 1 and 2 took their seats.
Find size x of class room and number of class room y such that there is no empty seats in class room (i.e. the total number of student present inside the class room is equal to x)?
Input
The first line contains an integer (1 <= n <= 10^5). The second line contains n space-separated integers a[0], a[1], ... a[n-1] (1 <= a[i] <= 10^4).
Output
Print all possible sizes of the class room in an increasing order with total number of class rooms in new line.
Example:
Input
3
2 2 4
Output
4 2
8 1 | 34,183 |
Yet Another Xor Sequence (YAXS)
Fizz have an array
A
of n integers which ranges between [1, 5] inclusive. Let
f(i)
denote number of times
i
occurs in the array.
Fizz wants to maximize the value of
max(f(1), f(2), f(3), f(4), f(5))
. To achieve it, he can perform one operation in the array as many time as he likes.
In each step Fizz can choose two integers A
i
and A
j
such that:
i ≠ j
1 ≤ (A
i
⊕ A
j
) ≤ 5, where ⊕ is the symbol for bitwise xor.
After choosing the integers, Fizz will remove them from the array and he will insert a new element (A
i
⊕ A
j
).
Fizz is very good in cricket but not so in programming, so please help him to find the maximum possible value of
max(f(1), f(2), f(3), f(4), f(5))
.
Input
First line will contain an integer T (1 ≤ T ≤ 3000) denoting number of testcases. Each test case will contain two lines. First line will consist n (1 ≤ n ≤ 1000) and second line will consist n space separated integers between 1 to 5.
Output
For each case, print the case number and the expected answer.
Sample
Input:
8
2 3 4 2 3 5 1 2
Output:
Case 1: 5 | 34,184 |
Movie Fan (MOVIFAN)
Alice is a cinephile. She wanted to watch a recently released movie. There are many movie shows whose start time and length are given. Your task is to help Alice count the number of ways she can watch the movie. Since she is a cinephile, she can watch many shows as long as they do not overlap.
Input
First line contains an integer t denoting the number of test cases.
Each test case contains n, l denoting number of shows and length of the shows.
n integer follows denoting start time of each show.
1 <= t <= 10
1 <= n, l <= 300000
Output
Print the number of ways Alice can watch shows if she wants to watch at least one show modulo 1000000007.
Example
Input:
3
3 4
3 8 12
3 1
1 2 3
3 3
3 5 9
Output:
7
7
5
For test case 1, Alice can watch 1 show in 3 ways, 2 shows in 3 ways and 3 show in 1 way total ways = 7.
For test case 3, Alice can watch 1 show in 3 ways, 2 shows in 2 ways, total ways = 5. | 34,185 |
How many can you sort? (SORTMUCH)
You have invented a new sorting algorithm which can sort n integers in exactly n log3 n time. (which is faster than almost every sorting algorithm till date). You have proved the correctness of your algorithm to your professor.
The professor now asks you what is the maximum number of integers that you can sort in a given time T.
Note
: log3 = (log to the base 3)
Proper usage of type casting is required to solve this problem. For testing purposes you can use this
high precision calculator
.
Input:
The first line consists of an integer t. For each test case, you are given an integer T, the time to sort the integers.
Output:
For each test case, print the maximum number of integers that you can sort in T time.
Constraints:
1 <= t <= 10^5
3 <= T <= 10^10
Time limit: 1 second
Example:
Input:
4
3
10
10000000000
4374
Output:
3
6
546076908
729 | 34,186 |
VEGETABLE SHOPKEEPER 3 (WEIGHT3)
The cost of the vegetables is directly proportional to its weight. The vegetable shopkeeper wants to minimize the loss and maximize his profit.
At first, the customer picks n number of vegetables with their sum of weight >= target weight. This is given as input.
Then the shopkeeper can choose any combination of the vegetables picked by the customer. But the sum of weight must remain ≥ target weight.
The shopkeeper is experienced enough to estimate the weight of any vegetable by looking at it.
Given the target weight and the individual weights of all the vegetables, find the minimum weight loss for the shopkeeper.
weight loss = sum of weight of vegetables chosen by shopkeeper - target weight.
Input
The first line consists of an integer t, the number of test cases. For each test case the first line consists of two integers n and W, the number of vegetables picked by the customer and the target weight respectively. The next line consists of n integers denoting the weights of each vegetable.
Output
For each test case, find the minimum weight loss for the shopkeeper.
Constraints
1 ≤ t ≤ 100
1 ≤ n ≤ 100
1 ≤ weight of each vegetable ≤ 1000
1 ≤ W ≤ 50000
Sample
Input
3
3 40
20 15 15
5 24
5 9 7 10 10
4 40
20 15 15 8
Output
10
0
3
See also tutorial version (
easy test cases
):
VEGETABLE SHOPKEEPER 1 | 34,187 |
Counting WOW-Substrings (WOWSUBSTR)
You are given a string. You have to
count the total length
of all
WOW
substrings.
WOW
substrings are defined as a contiguous substring of a string where there is not any character occurring more than one times. That means, all the characters of substring are unique.
As the answer could be very large, print it modulo
100007
. (Note: 100007 is
not
a prime number.)
Input
Input starts with an integer
T
, denoting the number of test cases. Each case starts with a string
S
. All the characters in the string will be lowercase letters of the English alphabet.
Output
For each case, print the case number and total length of all WOW substrings of given string modulo
100007
.
Constraints
1 ≤ T ≤ 50.
1 ≤ |S| ≤ 500000. (Length of string)
Example
Input:
2
aaa
ab
Output:
Case 1: 3
Case 2: 4 | 34,188 |
Counting WOW-Substrings2 (WOWSUBSTR2)
You are given a string. You have to count the total lengths of all
WOW
substrings.
WOW
substrings are defined as a contiguous substring of a string where there is no any character occurring more than one times. That means, all the characters of substring are unique. As answer could be very large, so print it modulo
100007
. (Note: 100007 is
not
a prime number.)
Input
Input starts with an integer
T
, denoting the number of test cases. Each case starts with
N
and
M
, denoting respectively length of string and total number of characters of string represented as integers from 1 to M. Then, follows a line with space separated N integers (each in the range 1 to M).
Output
For each case, print the case number and total lengths of all WOW substrings of given string modulo
100007
.
Constraints
1 <= T <= 50.
1 <= N <= 500000. (Length of string)
1 <= M <= 1000000. (Character id range)
Example
Input:
2
3 2
1 2 1
4 3
2 1 3 2
Output:
Case 1: 7
Case 2: 16 | 34,189 |
Coincidence (BLLUCK)
Toriel is planning to create a game with prize. In this game, there are N players and N boxes each containing a piece of paper with a player's name written on it. Each player has a unique name and each box contains a different name. There are at most 1000 players playing.
Then, each player take 1 box at random such that every player got a different box. The more player got a box containing their name, the bigger the prize is. To prepare the prize, Toriel needs your help to calculate the expected number of player to get their own name.
Input.
First line is T, number of games (T
<
1000). Next T lines each contains N for each game.
Output
For each game, output the expected number of players to get the box containing their own name. Output exactly 6 digits after decimal points.
Example
Input:
1
1
Output:
1.000000 | 34,190 |
Width of The Lost Box (LOSTBOX)
Minas had a box of marble which is lost last week. About that box Minas only know that length and height of the box was
L
and
H
, and box contains
K
marbles. But he forget the width of the box. But he remember that
width = 2 * radius
of marble and width is also an integer. You can assume that all marble are same.
Now, Minas will give you
L, H
and
K
. You need to tell him the width of the box. If the width is less than 1 then print
-1
.
Input
Input starts with an integer
T (1<=T<=1000)
, denoting the number of test cases.
Each case contains 3 integer
L (1 ≤ L ≤ 10^9)
,
H (1 ≤ H ≤ 10^9)
and
K (1 ≤ K ≤ 10^9)
.
Output
For each case of input, print the case number as
"Case #: x"
,
#
is replaced by the case number starting from 1 and
x
is replaced by the
maximum possible
width of the box.
Example
Input:
1
2 2 4
Output:
Case 1: 1 | 34,191 |
Martian Colony (MARSCOL)
Martian Colony is one of the best single player strategy games developed by a renowned game development company. The player has to destroy several colonies on Mars while playing the game.
The planet Mars has
N
villages numbered from
1
to
N
. Among the villages, the village numbered
i
has
di
amount of Diamonds. There are
E
one-way roads between some pair of villages, that is, if there is a road from village
u
to village
v
, Martians can only move from village
u
to village
v
. A number of villages make a colony when for every pair of villages
u
and
v
of that colony, there is a path from village
u
to the village
v
and the opposite. A path is a sequence of several roads. Each colony has some hit points which is the sum of the lengths of the roads inside that colony. A colony can be destroyed by using marsa points equal to the hit points of that colony. Destroying a colony will add the total number of diamonds of the villages of that colony to the player’s score.
Alon is your best friend. He loves to play strategy games and trying this new one. He loves to score the maximum always. At some stage of the game he is stuck with
M
amount of marsa points. He wonders, what is the highest score he can gain using maximum
M
marsa points. As a best friend of Alon, he seeks your help to calculate the exact score.
Input
The first line of input will contain
T
denoting the number of test cases. Before every test case there will be a blank line. The first line of the test cases will contain 3 integers
N, E
and
M (1 ≤ N ≤ 100, 0 ≤ E ≤ N^2, 1 ≤ M ≤ 5000)
. The next line will contain
N
integers
di (-100 ≤ di ≤ 100)
that represent the number of diamonds in the ith village. Each of the next E lines will contain three integers
u
,
v
and
w
(1 ≤ u, v ≤ N, 1 ≤ w ≤ 1000)
which means there is a road from village
u
to village
v
of length
w
.
Output
For each test case print a single line containing
“Case X: S”
, where X is the case number and
S
is the maximum score Alon can score.
Example
Input:
1
3 3 3
3 3 3
1 2 3
2 3 3
2 1 3
Output:
Case 1: 3 | 34,192 |
Alphabetic Rope (AROPE)
The Alphabetic Rope is now available in the market. The Alphabetic Rope consists of alphabetic characters in each stripe which looks like string. You are given an Alphabetic Rope consisting of lowercase alphabetic characters only. You have to perform some operations on rope and answers some queries on it.
Queries are of 3 types:
1 X Y
: Cut the rope segment from X to Y and join at the front of rope.
2 X Y
: Cut the rope segment from X to Y and join at the back of rope.
3 Y
: Print on a new line the character at Yth position of current rope.
Input
There is only one input. Input begins with single line giving Alphabetic Rope as a string
S
. Next line contains
Q
, following Q lines give Queries as mentioned above. (Index used are 0-based.)
Output
For each query of type 3, print a single character in a new line.
Constraints
1 <= |S| <= 100000. (Length of string)
1 <= Q <= 100000. (Number of queries)
Example
Input:
gautambishal
3
3 1
2 0 5
3 0
Output:
a
b | 34,193 |
Alphabetic Rope2 (AROPE2)
The Alphabetic Rope is now available in the market. The Alphabetic Rope consists of alphabetic characters in each stripe which looks like string. You are given an Alphabetic Rope consisting of lowercase alphabetic characters only. You have to perform some operations on the rope and answers some queries on it and Time is increases by 1. Initial time is 0 and queries are of 4 types:
1 X Y: Cut the rope segment from X to Y and join at the front of rope.
2 X Y: Cut the rope segment from X to Y and join at the back of rope.
3 Y: Print on a new line the character at the Yth position of current rope.
4 X Y: Print on a new line the character on Yth position of rope configuration at Xth time.
Input
There is only one input. Input begins with single line giving Alphabetic Rope as a string S. Next line contains Q, following Q lines giving queries as mentioned above. (Index used are 0-based)
Output
For each query of type 3 and type 4, print a single character in a new line.
Constraints
1 <= |S| <= 10000. (Length of string)
1 <= Q <= 10000. (Number of Queries)
Example
Input:
gautambishal
5
3 0
2 0 5
3 1
4 0 0
4 3 0
Output:
g
i
g
b | 34,194 |
Alphabetic Rope3 (AROPE3)
The Alphabetic Rope is now available in the market. The Alphabetic Rope consists of alphabetic characters in each stripe which looks like string. You are given an Alphabetic Rope consisting of lowercase alphabetic characters. You have to perform some operations on the rope and answers some queries on it. Queries are of 3 types:
1 X Y: Cut the rope segment from X to Y and Reverse it then join at the front of the rope.
2 X Y: Cut the rope segment from X to Y and Reverse it then join at the back of the rope.
3 Y: Print on a new line the character at Yth position of the current rope.
Input
There is only one input. Input begins with single line giving Alphabetic Rope as a string S. Next line contains Q, following Q lines giving Queries as mentioned above. (Index used are 0-based)
Output
For each query of type 3, print a single character in a new line.
Constraints
1 <= |S| <= 100000. (Length of string)
1 <= Q <= 100000. (Number of queries)
Example
Input:
gautambishal
5
1 3 5
3 0
3 3
2 2 4
3 9
Output:
m
g
a | 34,195 |
GO GOA GONE (ALCATRAZ2)
So, it was winter and Me and 8 of my friends decided to plan a trip to GOA. Since the Bars and Clubs are too Expensive out there, we decided to pool money together for our whole trip expenses. Now since every group has some internal politics going on, same applies to our group also :P. 2 Members that are having a cold war between them won't go to the trip if the other one is going. But Since we want to enjoy a lavish party, we want to maximize the pooled money. So, for this task I've chosen my marwari friend Mohit to solve this problem (He's good at money matters). Your task is to help Mohit achieve the maximum pooled money.
Input
First Line will contain 8 space separated integers denoting the money contributed by each member in order.
The next line will contain the total number of pairs having a cold war in between them. Let us denote this by P.
The next P lines will contain 2 numbers separated by a space showing the members having a cold war. Numbers used to denote members will be (1 - 8) for each of the 8 members.
Constraints
Everything is guaranteed to easily fit in 32 bit integer type.
Output
Output will give the maximum amount of money that can be pooled.
Example
Input:
3 14 5 2 3 4 1 9
4
1 2
2 3
4 5
7 8
Output:
30 | 34,196 |
Game of MODs (GMMOD)
Big MOD is a very intelligent boy. He likes mathematics and mathematical games. He often challenge his friends in various mathematical games. But all his friends are not god at mathematics and when Big MOD challenges his friends and they can’t answer the problem properly he feel very proud. But today his friend Little MOD who is a great programmer challenge him and give him a problem like this-
Little MOD give him two integer number N and K and ask him what is the maximum and minimum number can be get from N after deleting exactly K digits from N without changing the order of the digits.
Though Big MOD is good at mathematics but he is not good in programming and he wants to win this challenge so he wants your help to solve this problem. Can you help Big MOD to defeat Little MOD in this game ?
Input
Input starts with an integer (T ≤ 200) which denotes the number of test case. Each test case consists of two integers N and Q (0 ≤ N ≤ 10
18
and 1 ≤ Q ≤ 100) Where N is the given Number by Little MOD and Q is the number of query. The next line contains Q space separated integers which denotes the value of K (0 ≤ K ≤ |N|) Here |N| denotes the number of digits in N.
Output
For each test case, print the case number at first then for each K given in query print the maximum and the minimum integer number which are the answer for Big MOD in the above game. Keep in mind that for an empty number Big MOD need to say 0.
See the sample input and output for better understanding.
Example
Input:
2
1234 2
1 2
1578 1
3
Output:
Case 1:
234 123
34 12
Case 2:
8 1 | 34,197 |
Can you draw it or not? (DRAWIT)
Given a graph, you have to find if the graph can be drawn without taking the hands away. Assume that you are going to draw the given graph on a paper and you have to find whether you can draw it at a single stroke, i.e, without taking the hands away. And also, you are allowed to draw the graph only once. That is, you can't draw a single edge more than once. The given graph will have N nodes, numbered from 1 to N.
Consider the following graphs. For input clarity of the graphs, refer to the sample input
Input
The first line has the number of test cases, T.
Then for each test case, the first line has the integer N, the number of nodes.
The second line has the integer K.
Then K lines follow that, each line having three integers S, D, M denoting that there are M edges between the two nodes S and D.
Constraints
1 <= T <= 50
1 <= N <= 100
1 <= K <= (N * ( N – 1) ) / 2
1 <= S, D <= N
1 <= M <= 100
Output
For each test case, if the graph can be drawn so, print "YES" followed by a single space and the node from which you have to start drawing. If there are more than one node from where it's right to start drawing, print the node with the least value.
If the graph can't be drawn so, just print "NO".
Example
Input:
2
4
6
1 2 2
1 3 1
1 4 2
2 3 2
2 4 1
3 4 2
5
10
1 2 1
1 3 1
1 4 1
1 5 1
2 3 1
2 4 1
2 5 1
3 4 1
3 5 1
4 5 1
Output:
NO
YES 1
Note:
1) If there are more than one edge between two nodes, assume that those edges are of different forms. See the above picture for more clarity.
2) If there are M edges from S to D, then there are also M edges from D to S. | 34,198 |
Runner Game (NPC2016A)
Today, Waca will play runner game. In this game, the player will be placed in a square-shaped arena where they will run to checkpoints of the arena.
Arena of the game is a square with a side length of N. The player will be placed in a coordinate (X, Y) inside the arena. The following are the rules of the game:
Player will be initially at coordinate (X, Y), where coordinate (0, 0) is the bottom left corner of the arena.
Then, player should run to the side of the arena to get the checkpoints.
Checkpoints are located in each side of the arena (top, left, bottom, right) and player should take all the checkpoints (i.e. they have to visit all sides), then go back to the initial position of the player (X, Y).
If the player reach the corner of the arena, he can take 2 checkpoints. For example, if a player reach coordinate (0, 0), he is considered to get the left and bottom checkpoints.
Now, Waca is curious, what is the minimum distance to get all the checkpoints and go back to his initial position? The image below is one of the possible moves for the runner game. (The red circle is Waca's initial position (X, Y).
Input
The input will contain 3 integers, X, Y, and N.
Output
Print the minimum distance Waca need to finish the game. Your answer is considered to be correct if the difference is no more than 10
-6
Example
Input:
6 4 10
Output:
28.284271
Constraints:
1 ≤ N ≤ 10
6
0 ≤ X,Y ≤ N | 34,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.