task stringlengths 0 154k | __index_level_0__ int64 0 39.2k |
|---|---|
A Classic Myth - Flatland Superhero (FLATAND)
Flatland needs a superhero! Recently swarms of killer ants have been invading Flatland, and nobody in Flatland can figure out how to stop these dastardly denizens. Fortunately, you (as a higher dimensional being) have the opportunity to become a superhero in the eyes of the Flatland citizens! Your job is to “freeze” swarms of ants using parallelograms. You will do this by writing a program that finds a minimal area enclosing parallelogram for each swarm of ants. Once a minimal area parallelogram is placed around the ant swarm, they are effectively frozen in place and can no longer inflict terror on planar inhabitants.
Input
The input will consist of the following:
A line containing a single integer, s (1<=s<=20), which denotes the number of killer ant swarms.
Each swarm will start with a single line containing an integer, n (4 <= n <= 1000), which indicates the number of killer ants in the swarm.
The next n lines contain the current location of each killer ant in the swarm.
Each killer ant is represented by a single line containing two numbers: x and y (−1000 <= x, y <= 1000) separated by a space.
Only one killer ant will occupy each (x, y) location in a particular swarm. Each swarm should be dealt with independently of other swarms.
All data inputs are in fixed point decimal format with four digits after the decimal (e.g., dddd.dddd).
There may be multiple parallelograms with the same minimum area.
Output
For each swarm, your algorithm should output a line that contains “Swarm i Parallelogram Area: ”, where i (1 <= i <= s) is the swarm number, followed by the minimum area (rounded to 4 decimal digits and using fixed point format) of an enclosing parallelogram for that swarm. All computations should be done using 64 bit IEEE floating point numbers, and the final answers displayed in fixed point decimal notation and rounded to four decimal digits of accuracy as shown in the sample input and output.
Example
Input:
2
6
0.0000 0.0000
-0.5000 -0.5000
-1.0000 0.0000
-0.7000 -7.0000
-1.0000 -1.0000
0.0000 -1.0000
5
2.0000 2.0000
0.0000 0.0000
0.5000 2.0000
1.0000 1.0000
1.5000 0.0000
Output:
Swarm 1 Parallelogram Area: 7.0000
Swarm 2 Parallelogram Area: 3.0000 | 32,900 |
Tree Count (TRECOUNT)
Our superhero Carry Adder has uncovered the secret method that the evil Head Crash uses to generate the entrance code to his fortress in Oakland. The code is always the number of distinct binary search trees with some number of nodes, that have a specific property. To keep this code short, he only uses the least significant nine digits. The property is that, for each node, the height of the right subtree of that node is within one of the height of the left subtree of that node. Here, the height of a subtree is the length of the longest path from the root of that subtree to any leaf of that subtree. A subtree with a single node has a height of 0, and by convention, a subtree containing no nodes is considered to have a height of −1.
Input
Input will be formatted as follows. Each test case will occur on its own line. Each line will contain only a single integer, N, the number of nodes. The value of N will be between 1 and 1427, inclusive.
Output
Your output is one line per test case, containing only the nine-digit code (note that you must print leading zeros).
Example
Input:
1
3
6
21
Output:
000000001
000000001
000000004
000036900 | 32,901 |
Rescue On Time (ROT)
In the future there is an agency that works on rescuing people from the “bad guys”, those guys are a super secret evil agency that is on a super secret bunker that everybody knows, especially the agency we mentioned before. This agency (the good one) has a very particular thing, they can do time travel either to the future or to the past and they can do it how many times they want, but only one minute to the future or one minute to the past, or even stay in the present, it is impossible to go for example three minutes to the future or two minutes to the past; our agency wants to rescue only one hostage since the “bad guys” are really dumb and they can kidnap only one person and keep it hidden (it is dumb because the bunker is huge), now here is the deal, the agency has contracted us to do a program that tells the minimum number of time steps the agent of our agency should make to save the hostage (I am so lazy that you will do it all by yourself). It is important to know that at some point after certain amount of time the hostage will be killed so we don´t want to go over that time, never! And also we don´t want to get back on a time where the hostage isn´t in the bunker yet so remember that!, he can take a step into any adjacent direction but not in diagonals, and it is no meaning into wait on a position because the agent can use time as he wants.
‘X’ represents the place where the agent starts, it is guaranteed that the agent starts at the time 1.
‘#’ represents a wall.
‘s’ represents a free space.
‘!’ represents a “bad guy”.
‘O’ represents our objective.
Input
The first line of input is T the number of test cases, there will be several test cases T <= 10. Next line of input contains C, R, Time, which are Columns <= 15, Rows <= 15 and of course the Time <= 10 (Right after that maximum time the hostage will be killed and before time 1 there will be no hostage to save so is useless to go there) Time is measured in minutes, after that, Time lines will follow with a matrix of RxC Representing the actual position of guards and new free spaces after time traveling (Obviously walls will not move, and neither does the hostage because he is tied up.)
Output
Just output the minimum number of time steps that takes to our agent to get to the hostage, if it is impossible to get to the Hostage then should output: “Hostage is death, destroy the bunker”
Example
Input:
2
3 3 1
sss
ssX
Oss
3 3 3
Xss
#s!
s!O
sss
#!s
!sO
ss!
#s!
ssO
Output:
3
4 | 32,902 |
C You and Me (PUCMM223)
You and Me is a board game between two players, the board is M x N, with 1 = M, N = 20. Initially each player has one piece, piece 'a' and piece 'b', both players move at the same time its piece, a valid move is to move the piece one square on each of the 4 cardinal directions (North, South, East, West),or stay in the same square, that is, if a piece is at x, y it can move to (x-1, y), (x, y-1), (x, y), (x, y+1), (x+1, y), so with the two pieces combined there are 5 × 5 = 25 possibilities in one move. The game has a goal, piece 'a' must finish at position initially occupied by 'b', and vice-versa. To make this game more interesting the cells can be occupied by a block ('#'), or can be unoccupied ('.'). What is the minimum number of moves required to achieve this goal, if the pieces cannot occupy the same square at a given time and can't cross each other. See examples for further details.
Input
For each test case the first line contains two separated integers, M and N, the number of rows and columns on the board.
Then M strings of N characters follow.
Each character could be '.', '#', 'a', 'b'.
Just one 'a' and one 'b' exists.
The last case is followed by 0 0.
Output
Output the minimum number of moves required to achieve the goal. Output IMPOSSIBLE if it is not possible.
Example
Input:
3 4
#..#
a..b
####
3 7
#######
#a...b#
#######
4 4
a...
###.
##..
b...
0 0
Output:
5
IMPOSSIBLE
11
Note: 1st case: one possibility is
#..# #..# #.b# #..# #..# #..#
a..b--->.ab.--->..a.--->..ba--->.b.a--->b..a
#### #### #### #### #### #### | 32,903 |
Ball Stack (BALLLSTA)
The XYZ TV channel is developing a new game show, where a contestant has to make some choices in order to get a prize. The game consists of a triangular stack of balls, each of them having an integer value, as the example shows.
The contestant must choose which balls he is going to take and his prize is the sum of the values of those balls. However, the contestant can take any given ball only if he also takes the balls directly on top of it. This may require taking additional balls using the same rule. Notice that the contestant may choose not to take any ball, in which case the prize is zero.
The TV show director is concerned about the maximum prize a contestant can make for a given stack. Since he is your boss and he does not know how to answer this question, he assigned this task to you.
Input:
Each test case is described using several lines. The first line contains an integer
N
representing the number of rows of the stack (1 ≤
N
≤ 1000). The
i
-th of the next
N
lines contains
i
integers
B
ij
(-10
5
≤
B
ij
≤ 10
5
for 1 ≤
j
≤
i
≤
N
); the number
B
ij
is the value of the
j
-th ball in the
i
-th row of the stack (the first row is the topmost one, and within each row the first ball if the leftmost one).
The last test case is followed by a line containing one zero.
Output:
For each test case output a line with an integer representing the maximum prize a contestant can make from the stack.
Sample
Input
4
3
-5 3
-8 2 -8
3 9 -2 7
2
-2
1 -10
3
1
-5 3
6 -4 1
0
Output
7
0
6 | 32,904 |
AMZ Word (AMZSEQ)
AmzMohammad is a novice problem setter in Spoj. for start of his work he decided to write a classical and sample problem. (for UI ACM summer program )
How many N-words (words with N letters) from the alphabet {0, 1, 2} are such that neighbors differ at most by 1?
Input
A positive integer N.
Output
Number of N-words with told conditions.
Answer is less than 1000000000. it is the only constraint :)
Example
Input:
2
Output:
7 | 32,905 |
Amz Rock (AMZRCK)
To many people in many cultures, music is an important part of their way of life.
AmzMohammad is a fan of rock music. and he have n rock tracks (labelled from 1 to n) now he wants to select a playlist.
In his opinion a good playlist is one that have no two successive tracks.
In how many ways?
Input
First line is the number of test cases.
Each test case in an integer n (number of tracks.)
Output
Output number of good playlists he can make.
Answer is less than 1000000000. it is the only constraint :)
Example
Input:
2
1
2
Output:
2
3
note: a good play list may consist 0 track :)
note 2: how many Persian rock tracks we have? | 32,906 |
DIAGONAL (DIG)
You are a given a n sided convex polygon. Find total number of intersections of all diagonals.
Assume that all the intersection points are different.
If in case answer exceeds 10
9
+ 7 , take modulo 10
9
+ 7
1 ≤ n ≤ 10
8
Input
First Line : T (number of test cases.)
Next T line will contain N number of vertices.
Output
Number of intersections of diagonals as specified.
Example
Input:
2
4
5
Output:
1
5 | 32,907 |
Decorating the Palace (DEC123)
The King of DragonLand likes decorating towers. So one day he decided to decorate a tower with flowers.
The highest floor of a tower contains only one room and floor just below every floor except the base floor will have two of its child buildings on which it is built.
Note that its structure is like a binary tree.
for height = 3
*
* *
* * * *
You are given the task of decorating it, but there is a constraint in decorating it: sum of child floors of a floor will have be equal to number of flowers in parent building and your child floors will have a small a difference between number of flowers in them as possible to make your tower look beautiful.
Given that top building contains N flowers and height of tower is H, find out number of ways of decorating it, As this value may be large, output it modulo 10
9
+ 7.
Two decorations are considered different if any floor in them contains different number of flowers
Input
T: number of test cases (≤ 10), then next T lines contain H, N.
Output
Output the number of different decorations % (10
9
+ 7)
Constraints
1 ≤ H ≤ 50
1 ≤ N ≤ 50000
Example
Input
2
1 1
2 1
Output
1
2
Explanation
for 1 1, it is obvious.
for 2 1,
There can be two ways:
1
1 0
OR
1
0 1 | 32,908 |
Zig-Zag Permutation 2 (ZZPERM2)
See
ZZPERM
problem description. This an improved version with more demanding test cases.
Input
The input consists of at most 15 test cases. Each case contains a word (W) not longer than 64 letters and one positive number (D <= 1000000000). The letters of each word are in increasing order. Input is terminated by EOF.
Output
For each case output all of the zig-zag permutations of W whose rank is divisible by D, in increasing lexicographic order, one word per line. In the next line print the total number of zig-zag permutations of W. There is no case that produces more than 365 lines of output. Print an empty line after each case.
Example
Input:
j 1
abc 2
aaabc 1
aaabb 2
aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbcccdd 123456
aaaaaaaaabbbbbbbbbcccccccccddddddddd 1000000000
Output:
j
1
bac
cab
4
abaca
acaba
2
1
babacbcabacabadabababababababababadab
213216
abacbcacbdadcdbcadbdacbdacbdadbcbcad
abadadcdcdcdbdbdadbcabacacbdbcbcacab
acabacbcbdbcbdcdadadacbcadbcbcadadbd
acacbcbdacbdcdacbcadbdbcbcadadbdabad
acadbcadbdbcacadbdbcacbdbdacbdbcadac
acbcacbcadbdadadadbcbdcdabacacbdbdbc
acbcbdadbdcdbcbcbcacbdadadadadbcacab
acbdadcdcdadadbdababacbcbcbcacbdbdac
acbdcdbdbcacbcbcadabadbcabadbdcdacad
adacbcacbcbcbdcdcdbdadadabadbdbcacab
adadbcbcadbcabacadbdbcbdabadcdcdacbc
adbcadbcabacbdacacbcbcbdcdadbdadbdac
adbdacababacadadcdbcbcadbdacbcbdcdbc
adbdcdacbdbcbdbcadadadbcadacbcacbcab
adcdbdacadacbdbcbdadacbcbcadbdbcacab
babacbdcdbdcdbcadcdbcabacacadadbdacb
bacacadbdcdbcbdbdcdacbdacabacadbcadb
bacadcdbcbdabacbcacacadadadcdbdbdbcb
bacbdadacabacadacbdcdbcadbcbdbcbdadc
badacadbcadacbcbdadbdbcacbcbdcdabadc
badbcacbdabadcdbcadbdacabacbdacbdcdc
badbdcdbdadacbcbcacacbdbdacbdadbcaca
bcabacadbdbdacacbdadcdadbcbcbcadacbd
bcacadacbcbdcdbdbcbdbdadadabacbdacac
bcacbdbdcdcdababadacbcadacacbdbdbcad
bcadbcadbdbdcdcdadbcbcacbcababadacad
bcbcabadacadcdadacbdadbcbdcdbcacbdab
bcbcbcadbcadbcadbdadbcbcadabacadadcd
bcbdacbdacbdbcbdadacacbdcdbdadacabac
bcbdbdbdcdacacacbdbcadadbcababacadcd
bdabadcdbdadbcadcdbcbdcdbcabacabacac
bdacbcbcbcadadbcadcdabadbcacbdcdabad
bdadbcabacbcbcababadacadcdcdbdcdacbd
bdbcacacbdbcadbcbdabacbcadacadadbdcd
bdbcbdacacbdadbdcdababadadcdbcacbcac
bdbdbcadbcacadbcadacadbdbdcdbcacacab
bdcdacbdadadbcbcacacbcacabadbdbcadbd
bdcdcdadacadcdbdbcababadbcacbcadbcab
cabacbdcdbdadacacadbcbcacadbcbdbdadb
cacabadcdbdbdbcbcbdacabadbdacbdacadc
cacadcdbcbcbdcdacababacbcadbdbdbdada
cacbdadbdadacbdababacbcbdcdcdcdabacb
cadacadbdabacbcacbdbdcdadbcadadbcbcb
cadbcacbcbdcdbdbcadbcbdadabacbdacada
cadbdbcbdacadbdacadacbdbcbcadbcabadc
cbcabacbcbdadabacbcadbdadcdcdadacbdb
cbcadacadadbdbcacbcadbdbdacbcabadcdb
cbcbcadacbcadadadbcbdacadbcbdbdacadb
cbcbdbcadcdacbdadacbdbcacadacbdabadb
cbdacadacbcbdcdbdabadbcbcacabadcdadb
cbdadbdadabadcdabadcdacbcbcabacbcbdc
cbdbcbdcdbcbdacacbdadadcdababacabadc
cbdcdacbdbcbdadacacadbcabababadcdbdc
cdabadacabadcdbdcdbdbcabadbcbcacadbc
cdacbcbcadabadcdbdbcbcacbdadadabadbc
cdadbcacacbcadadbdbdbcabadbcbcbcadad
cdbcacadbcbdbcadbdadadbdbcacbcadabac
cdbcbdadadacbdbcabacbcbcabadacadcdbd
cdbdbcabadcdbdbdcdacacababadbdacacbc
cdcdacacbcadbcabadbdcdbcbcabadadbdab
dababacbcbcadbdacacbcacbdbdcdadcdadb
dabadbdcdacacadabadcdbdbcbcbcacbdbca
dacadacbdbdbcacbcadbdbcacbcadbdcdaba
dacbcbdadadcdbdacadcdababacbcacbdbcb
dadabadbcbcadcdbdacbcadacadbcbcbdbca
dadbcadadbdcdcdabacbcbdbcacbdbcabaca
dadcdbcacabadadbcabadbcadcdadbcbcbcb
dbcacbcadacadbcacbdadacbcbdacbdbdadb
dbcadcdbcbdbdadbdadbcacbcacacbcabada
dbcbdacbcadbdacbdadbdacbcadbcacadacb
dbdacacbdadbcbcbcbcadbdadbcadbcadaca
dbdbcacadacabacbcadacbdadcdbdbdbcbca
dbdcdabacadadbcbdcdbcacacbcbdbdacaba
dcdacadadbcbcabacbcacbdbcbdbcadadadb
dcdbcadadbcbcadbcbcadabadbdcdbcacaba
dcdcdacabadbdbdacacbcacbdababadbcbdc
76317369490 | 32,909 |
Counting Words (GSWORDS)
Supervin likes counting. In this problem, he invites you to count together
.
Supervin defines a
word
as "a string only consist of 'o' or 'x'", and additional requirement, for each substring with prime-length, the number of 'o' is not less than the number of 'x'.
Supervin gives you an integer
N
(1 <=
N
<= 10^12). Supervin challenges you to determine how many
words
can be made with exactly
N
-length.
You are having difficulties, make a program to determine how many
N
-length
words
. Because the output can be too big, output the number of
words
modulo 1 000 000 007.
Input
One line, an integer
N
Output
One line, an integer indicates how many
N
-length
words
modulo 1 000 000 007
Example
Input:
2
Output:
3
Input:
3
Output:
4
Explanation
In the first sample, the
words
can be made are: "oo", "ox", "xo".
In the second sample, the
words
can be made are: "ooo", "oox", "oxo", "xoo" | 32,910 |
Dark Assault (DARKASLT)
Original statement
Rainbowland is a planet full of life and adorable beings, however, this night, the spies Andreina, Marge and Teresa agreed to breakdown the security of a building led by a teddy bear, this teddy bear is mean! Don't get the wrong idea, the rainbowland spies agency (RSA) just want to make things go right in they colorful and lovable world.
Andreina offered a plan to take control of the building, she and Teresa will go to the roof of another building, seeing the target building, they will tell Marge to take down N rivals on a building of F floors, as she won't use the stairs, there are a series of E elevators that are in the building, the elevator can only go up or down P floors (more explanation on input details).
While Andreina and Teresa sees from outside, Marge must take down immediately the rivals, so they cannot leave them alive, otherwise, they will alert the others and the mission will be failed, when fighting a rival, the rival loses K points of life during each second using normal abilities, you can always assume that Marge won't fail at any fight, in addition, Marge can use some special abilities, these abilities allow Marge to deliver powerful blows, however, these special abilities can only be used
once
, so she must use it wisely, as Marge doesn't want to waste energy on a single enemy, she will give two special ability punches at most, if she can do it. She can always combine, so at last, she will choose between what is best (If normal attacking, if using one special ability or two and normal attacking).
Help the spies Andreina, Teresa and Marge to find the minimum time so they can take the building and defeat all the rivals, having in consideration that:
Marge takes one minute to use the elevator.
Each round of fight lasts one minute.
Marge starts from floor 1 and she can go from floor 1 to F, never lower nor higher.
If Marge uses an special ability or two special abilities, it will still count as she uses on one round (see point 2).
There will be
from 1 to
7
rivals in all the building.
The floor 1 will be always rival free, therefore, the
floor 1
will have a value of zero (0).
INPUT DETAILS:
First line will contain an integer T denoting T description of the test cases.
For each T you will have four integers F, N, K, E denoting, respectively, the number of floors in the building, the number of special ability that Marge can use, the damage K that Marge delivers after a single blow and the number E of elevators.
Then, in the next line, F integers separated by a single space will follow, denoting the description of the building, a number 0 means that there are no rivals at the floor, a positive number will represent the life points that the rival has at the moment of the assault.
The next line will contain N integers separated by a single space representing the values of a special blow given by Marge, remember that she can only deliver two blows at most for each rivals and she can use only once the special blow.
The next line will contain E integers separated by a single space, meaning the description of the elevators, for each positive number means that the elevator will go up P floors, if the number is negative, means that the elevator will go down P floors, you can always asume that P will never be 0.
OUTPUT DETAILS:
For each test case, print the string “Scenario #i: V“ where i denotes the i-th test case you're analyzing (starting from 1) and V is the minimum time that the team can defeat the all rivals, print -1 if the mission will fail.
INPUT
OUTPUT
3
4 2 3 2
0 10 0 15
10 5
2 -1
10 4 2 5
0 0 0 10 0 8 7 8 10 100
10 10 10 80
2 -1 5 -3 1
3 3 2 1
0 100 100
150 200 150
2
Scenario #1: 8
Scenario #2: 26
Scenario #3: -1
Explanation of the first test case:
At time
1
, Marge goes from floor 1 to floor 3, then, from floor 3 to floor 2, she choose to beat the rival with life 10 with normal blows (it will take
4
units of time to beat it), at this time Marge has already wasted
6
minutes of time, then, she will take the elevator up to floor 4, then will use her two special abilities to deliver a powerful blow on rival at floor 4 with 15 life points (15-10-5 = 0) beating it. Final time of the mission,
8
.
CONSTRAINTS:
1<=T<=10
2<=F<=128
1<=N<=7
1<=K<=1000
1<=E<=50
0<=Fi<=1000
1<=Ni<=1000
-F<=Ei<=F with Ei != 0
Clarification: There is no blank lines between Scenarios in the output. | 32,911 |
Intergalactic Highways (IGALAXY)
ORIGINAL STATEMENT
.
The world is on constant evolution, the humans evolved to a galactic civilization at the year 700,000, they are now capable of going instantly to any other planet in 1 unit of time, however, they must stop sometimes in a planet to avoid a horrible collision against an asteroid.
Rudolph-X3000, a single humanoid, wants to visit his family visiting as few planets as possible from planet A to planet B inclusive without repeating any planet, he is in a hurry so he need the answer quickly. Can you determine how many planets is going to visit?
As Rudolph-X3000 is an intergalactic traveler, he want to determine the planets he is going to visit as well, if there exists more than one single shortest path between planet A and B, print the one lexicographically smallest, if there is no such route, print -1.
The human race knows now the Delta Velocity, this velocity allows to move in a single unit of time at a very fast speed from a place i to place j. So you can consider the distance between planets will be always of 1.
Input
The first line will contain an integer T representing T test cases.
Then, in the next line, there will be an integer R denoting the number of relations between planet, a relation is considered so that from a planet i you can go to planet j, this relation is symmetric, so the path between (i, j) is the same as (j, i)
The next R lines will contain two strings P and Q, these strings will denote the name of a planet P and a name of a planet Q and their relation.
The last line will contain two strings S and D, representing the origin planet and the destination planet.
Note: All the strings will have the combination of uppercase and lowercase letters [A-Z] [a-z].
Output
For each test case you shall print the string "Scenario #i: " where i is the test case you're analyzing (starting from 1) followed by the minimum number of planets, then, in the next line, you should list each planet visit (including origin and destination), each one separated by a single space.
Example
Input:
3
8
Mercury Venus
Venus Earth
Earth Mars
Mars Jupiter
Jupiter Saturn
Saturn Uranus
Uranus Neptune
Neptune Pluto
Earth Pluto
7
Mesopotamia Merrick
Merian Earth
Earth Venus
Merian Merrick
Venus Mesopotamia
Pluto Earth
Mesopotamia Pluto
Mesopotamia Earth
2
Earth Sun
Moon Venus
Earth Moon
Output:
Scenario #1: 7
Earth Mars Jupiter Saturn Uranus Neptune Pluto
Scenario #2: 3
Mesopotamia Pluto Earth
Scenario #3: -1
Explanation of the Second Case
There are two possible routes for going from Mesopotamia to Earth, one is "Mesopotamia → Pluto → Earth”, the other one is "Mesopotamia → Venus → Earth”, we select the lexicographically smaller.
Constraints
1 ≤ T ≤ 100
1 ≤ R ≤ 100,000
1 ≤ |{P.Q.S.D}| ≤ 50
It is safe to say that there will be no more than 10,000 distinct planets. | 32,912 |
Addicted (TLL237)
Jhon is compulsive saver, he keeps a number "n" of piggy banks locked in his room.
He has a list which he wrote with a sequence of 1's and 2's that indicate the way that Jhon will
deposit his money on the piggy banks. Every time Jhon gets a penny he rushes to his room and
picks the 2 piggy banks who have the least amount of money, then he looks at the next number
on the sequence. If that number is one (1) he deposits the penny on the piggy bank with the least
amount of money. If that number is two (2) he deposits the penny on the next piggy bank with
the least amount of money.
Your task is to write a program to help Jhon to determine what is the amount in the 2 piggy
banks with least amount of money once the sequence is over.
If more than two have the least amount of money choose those with lowest indexes.
You can assume that n ≤ s.
Input
The input is a single data set.
n is the number of piggy banks, 2 ≤ n ≤ 10
5
s is the sequence with 1's and 2's, 1 ≤ size(s) ≤ 10
5
Output
A line containing what is the amount in the 2 piggy banks with least money once the sequence is over, sorted from lowest to highest.
Example
Input:
3
111112
Output:
1 2 | 32,913 |
Arya Rage (MNNITAR)
Arya is very fond of Fibonacci numbers. He claimed he can solve any problem on Fibonacci number. His clever friend Golu gave him a challenge to prove his skills. He gave him a sequence which he called exponacci. The sequence is given by:
g(n) = 2
f(n-1)
for n > 0
g(0) = 1
for n == 0
f(n) denotes the nth Fibonacci number where
f(0) = 1 (Obviously Golu is not as good as Arya in Fibonacci numbers so he believes f(0) = 1, anyways we have chosen not to disturb him.)
f(1) = 1
f(n) = f(n-1) + f(n-2) for n > 1
Help Arya to find the nth exponacci number. Since the numbers can be very large take mod 10
9
+7.
Input
The first line of the input will be the number of test cases (T ≤ 2000). For each test case first line contains one integer n (0 ≤ n ≤ 10
15
)
Warning: value of n won't fit in int, use long long int instead.
Output
The value of g(n) % (10
9
+7)
Sample
Input:
2
3
5
Output:
4
32 | 32,914 |
Packing Rectangles (PACKRECT)
Four rectangles are given. Find the smallest enclosing (new) rectangle into which these four may be fitted without overlapping. By smallest rectangle, we mean the one with the smallest area.
All four rectangles should have their sides parallel to the corresponding sides of the enclosing rectangle.
Rectangles may be rotated 90 degrees during packing.
There may exist several different enclosing rectangles fulfilling the requirements, all with the same area. You must produce all such enclosing rectangles.
Input
Four lines, each containing two positive space-separated integers that represent the lengths of a rectangle's two sides. Each side of a rectangle is at least 1 and at most 50.
Output
The output file contains one line more than the number of solutions. The first line contains a single integer: the minimum area of the enclosing rectangles. Each of the following lines contains one solution described by two numbers p and q with p<=q. These lines must be sorted in ascending order of p, and must all be different.
Example
Input:
1 2
2 3
3 4
4 5
Output:
40
4 10
5 8 | 32,915 |
Dome of Circus (DOMECIR)
A travelling circus faces a tough challenge in designing the dome for its performances. The circus has a number of shows that happen above the stage in the air under the dome. Various rigs, supports, and anchors must be installed over the stage, but under the dome. The dome itself must rise above the center of the stage and has a conical shape. The space under the dome must be air-conditioned, so the goal is to design the dome that contains minimal volume.
You are given a set of n points in the space; (x
i
, y
i
, z
i
) for 1 ≤ i ≤ n are the coordinates of the points in the air above the stage that must be covered by the dome. The ground is denoted by the plane z = 0, with positive z coordinates going up. The center of the stage is on the ground at the point (0, 0, 0).
The tip of the dome must be located at some point with coordinates (0, 0, h) with h > 0. The dome must have a conical shape that touches the ground at the circle with the center in the point (0, 0, 0) and with the radius of r. The dome must contain or touch all the n given points. The dome must have the minimal volume, given the above constraints.
Input
The first line of the input file contains a single integer number n (1 ≤ n ≤ 10 000) — the number of points under the dome. The following n lines describe points with three floating point numbers x
i
, y
i
, and z
i
per line — the coordinates of i-th point. All coordinates do not exceed 1000 by their absolute value and have at most 2 digits after decimal point. All zi are positive. There is at least one point with non-zero x
i
or y
i
.
Output
Write to the output file a single line with two floating point numbers h and r — the height and the base radius of the dome. The numbers must be precise up to 3 digits after decimal point.
Sample
Input #1
1
1.00 0.00 1.00
Output #1
3.000 1.500
Input #2
2
1.00 0.00 1.00
0.00 1.50 0.50
Output #2
2.000 2.000
Input #3
3
1.00 0.00 1.00
0.00 1.50 0.50
-0.50 -0.50 1.00
Output #3
2.000 2.000 | 32,916 |
Gao on a tree (GOT)
There's a tree, with each vertex assigned a number. For each query (a, b, c), you are asked whether there is a vertex on the path from a to b, which is assigned number c?
Input
There are multiple cases, end by EOF.
For each case, the first line contains n (n <= 100000) and m (m <= 200000), representing the number of vertexes (numbered from 1 to n) and the number of queries.
Then n integers follows, representing the number assigned to the i-th vertex.
Then n-1 lines, each of which contains a edge of the tree.
Then m lines, each of which contains three integers a, b and c (0 <= c <= n), representing a query.
Output
You should output "
Find
" or "
NotFind
" for every query on one line.
Output a blank line AFTER every case.
Example
Input:
5 5
1 2 3 4 5
1 2
1 3
3 4
3 5
2 3 4
2 4 3
2 4 5
4 5 1
4 5 3
Output:
NotFind
Find
NotFind
NotFind
Find | 32,917 |
ROMAN NUMERALS (ROMAN008)
You are given two numbers in Roman system (modern Roman Numerals) and an operator. Output is the result in Roman system.
Input
You are given two space separated numbers in roman system and after space an operator on the same line. Operator can be +, -, /, *, %.
Numbers a, b: 1 <= a, b<5000
eg: 4000=MMMM, for numbers >=4000, you should use MMMM.....
for others as per definition.
Input consists of 5 testcases.
Output
Output is the result < 5000 of performing the operation. Print on a separate line
Example
Input:
LX XV +
X V *
Output:
LXXV
L | 32,918 |
Trip To London (DCEPC803)
Mary and Saina participated in London Olympics 2012 and won medals for India. After these historic moments, they planned to travel and see various places in London. Since it was their first time in the city, they bought a map to various connecting routes across London. However, the map was not proper as it had a missing entry for one route. They asked the tour planning authorities to get the correct map but all they could get was the shortest distance route map rather than the original map which gives direct distance between any 2 places in London. Mary and Saina prefer taking the direct route rather than the shortest route for travelling. Can you help them calculate the number of possible values of direct distance which is unknown in the original map? Assume that the places are never more than 100km apart (i.e. direct distance).
Input
First line contains N, the number of places in London.
Next N lines contains total N^2 integers, N space separated integers per line (the direct distance map). The jth column in the ith line contains either a non-negative integer (the distance from ith place to jth place), or -1 indicating the missing entry in the map.
Next N lines contains total N^2 integers, N space separated integers per line (the shortest distance map). The jth column in the ith line contains a non-negative integer (the shortest distance from ith place to jth place).
Note that direct distance from ith to jth city is not always equal to direct distance between jth to ith city and distance between a city to itself is always 0.
Output
Output the number of possible values the missing entry (marked -1 in the original map) takes assuming that shortest distance map is correct.
Output
2<=N<=20
All distances are between 0 to 100 (including both).
Example
Input:
4
0 51 61 63
-1 0 66 24
80 83 0 71
60 64 52 0
0 51 61 63
84 0 66 24
80 83 0 71
60 64 52 0
Output:
17 | 32,919 |
Totient Fever (DCEPC804)
Another Totient problem by Ankur Sir J. He is madly in love with totient. Let’s see what he has prepared this time.
Recently he was studying integral properties of Quadratic functions. He found some interesting notions of real and complex numbers through Quadratic functions. But as you know he is a big totient fan, he mixed totient with quadratic functions this time and that resulted into a nice problem. He wants to find out if there exists a real root ‘x’ in the equation below:
Totient(a*x^2 + b*x + c) = k
Given ‘a’, ‘b’, ‘c’ and ‘k’, output “Yes” if a real root exists or “No” if no real root exists.
Input
First line contains T, the no. of test cases.
Each of the next T lines contains a, b, c and k.
Output
Output T lines, each for a single test case, containing either a “Yes” or a “No” corresponding to the test case.
Constraints
0 < T <= 100
0 < a <= 10^6
0 < b <= 10^6
0 < c <= 10^6
0 < k <= 10^6
b^2 >= 4*a*c
Example
Input:
2
1 4 3 4
1 21 11 10
Output:
Yes
Yes | 32,920 |
Bit by Bit (DCEPC807)
Alice and Bob play an interesting game. They start with a number “n” and follow some rules until the game ends. The rules for the game are:
Let F(n) denotes the total number of set bits in binary representation of numbers from 0 to 2
n
- 1.
Each player plays alternatively until the game ends and one of them wins the game.
In each turn a player either unsets a single set bit from binary representation of “n” or unsets 2 consecutive set bits from the binary representation of “n”. Let’s call the resulting number after such move as “x”.
The game ends when F(x) is a power of 2. (0 is also a power of 2).
The player with no move loses the game and so other player wins the game.
Alice starts the game always.
Both of them play optimally.
Given “n” can you predict the winner of the game?
Input
First line contains T, the number of test cases.
Next T lines contains one integer per line, “n” (quotes for clarity).
Output
Output T lines, each containing either “Alice” if Alice wins the game or “Bob” if Bob wins the game.
Constraints
1 ≤ T ≤ 10
0 ≤ n ≤ 10
6
Example
Input:
2
4
10
Output:
Bob
Alice | 32,921 |
Cousin Wars (DCEPC810)
Sunny is fond of words. He got a new game to play with his cousin Sonali. He gives her a long string and two other smaller strings (A and B). Now he asks Sonali to find the number of all the subsequences of the long string that are greater than equal to smaller string A and less than equal to smaller string B.
Help Sonali to find the answer.
Note: Comparison of two strings is regarded same as that done by the
string:compare
function.
Empty string is not regarded as a subsequence.
Input
Each input consists of 3 lines. First line has the TEXT string.
2nd and 3rd line contain two smaller strings A and B.
Output
One number which gives the count such that A ≤ subsequence of (TEXT) ≤ B.
Constraints
Input will consist of all lowercase characters.
1 ≤ Length of TEXT ≤ 25
1≤ Length of A and B ≤ Length of TEXT
Example
Input:
coforc
co
fc
Output:
24 | 32,922 |
Grass Planting (GRASSPLA)
Problem description
Farmer John has N barren pastures (2 ≤ N ≤ 100,000) connected by N-1 bidirectional roads, such that there is exactly one path between any two pastures. Bessie, a cow who loves her grazing time, often complains about how there is no grass on the roads between pastures. Farmer John loves Bessie very much, and today he is finally going to plant grass on the roads. He will do so using a procedure consisting of M steps (1 ≤ M ≤100,000).
At each step one of two things will happen:
FJ will choose two pastures, and plant a patch of grass along each road in between the two pastures, or,
Bessie will ask about how many patches of grass on a particular road, and Farmer John must answer her question.
Farmer John is a very poor counter -- help him answer Bessie's questions!
Input
* Line 1: Two space-separated integers N and M
* Lines 2..N: Two space-separated integers describing the endpoints of a road.
* Lines N+1..N+M: Line i+1 describes step i. The first character of the line is either P or Q, which describes whether or not FJ is planting grass or simply querying. This is followed by two space-separated integers A
i
and B
i
(1 ≤ A
i
, B
i
≤ N) which describe FJ's action or query.
Output
* Lines 1..???: Each line has the answer to a query, appearing in the same order as the queries appear in the input.
Example
Input:
4 6
1 4
2 4
3 4
P 2 3
P 1 3
Q 3 4
P 1 4
Q 2 4
Q 1 4
Output:
2
1
2
[ Edited by EB ]
Warning:
Some input files are broken. | 32,923 |
Fibonaccibonacci (easy) (FRS2)
Leo would like to play with some really big numbers, OK...
Let FIB the Fibonacci function :
FIB(0)=0 ; FIB(1)=1
and
for N>=2 FIB(N) = FIB(N-1) + FIB(N-2)
Example : we have FIB(6)=8, and FIB(8)=21, so FIB(FIB(6))=21
Input
The input begins with the number T of test cases in a single line.
In each of the next T lines there are an integer N.
Output
For each test case, print FIB(FIB(N)) ,
as the answer could not fit in a 64bit container,
give your answer modulo 1000000007.
Example
Input:
3
0
5
6
Output:
0
5
21
Constraints
1 <= T <= 10^4
0 <= N <= 10^100
Time limit is set to allow (sub-optimal) 500B of python3 code to get AC.
A near optimal solution is within 0.02 and 0.04s with a fast language, and around 1s in Python2 without psyco.
Edit(20/I/2015) With Cube cluster, it is not hard to get 0.0s with fast languages, and my old code ended in 0.08s using PY3.4.
Edit(11-2-2017) With compiler update, new TL. My old Python code ends in 0.04s, and it's easy to get 0.00s using a fast language. | 32,924 |
Fibonacci recursive sequences (medium) (FRSKT)
Let FIB the Fibonacci function :
FIB(0)=0 ; FIB(1)=1
and
for N>=2 FIB(N) = FIB(N-1) + FIB(N-2)
Example : we have FIB(6)=8, and FIB(8)=21.
Let F(K, N) a new function:
F(0, N) = N for all integers N.
F(K, N) = F(K-1, FIB(N) ) for K>0 and all integers N.
Example : F(2, 6) = F(1, FIB(6) ) = F(0, FIB( FIB(6) ) ) = FIB( FIB(6) ) = FIB(8) = 21
Input
The input begins with the number T of test cases in a single line.
In each of the next T lines there are three integers: K, N, M.
Output
For each test case, print F(K, N),
as the answer could not fit in a 64bit container,
give your answer modulo M.
Example
Input:
3
4 5 1000
3 4 1000
2 6 1000
Output:
5
1
21
Constraints
1 <= T <= 10^3
0 <= K <= 10^2
0 <= N <= 10^9
2 <= M <= 10^9
You would perhaps have a look, after, at the
hard edition
with more difficult constraints.
Edit 2017-02-11, after compiler update. My old Python code ends in 0.08s. New TL. | 32,925 |
Fibonacci recursive sequences (hard) (FRSKH)
Leo searched for a new fib-like problem, and ...
it's not a fib-like problem that he found !!! Here it is.
Let FIB the Fibonacci function :
FIB(0)=0 ; FIB(1)=1
and
for N>=2 FIB(N) = FIB(N-1) + FIB(N-2)
Example : we have FIB(6)=8, and FIB(8)=21.
Let F(K, N) a new function:
F(0, N) = N for all integers N.
F(K, N) = F(K-1, FIB(N) ) for K>0 and all integers N.
Example : F(2, 6) = F(1, FIB(6) ) = F(0, FIB( FIB(6) ) ) = FIB( FIB(6) ) = FIB(8) = 21
Input
The input begins with the number T of test cases in a single line.
In each of the next T lines there are three integers: K, N, M.
Output
For each test case, print F(K, N),
as the answer could not fit in a 64bit container,
give your answer modulo M.
Example
Input:
3
4 5 1000
3 4 1000
2 6 1000
Output:
5
1
21
Constraints
1 <= T <= 10^3
0 <= K <= 10^18
0 <= N <= 10^18
2 <= M <= 10^18
K, N, M are uniform randomly chosen.
You would perhaps have a look, before, at the
medium edition
with easier constraints.
Edit(12/I/2015) My old Python code now ends in 2.19s using PY3.4 and cube cluster.
Edit(11/2/2017) Compiler updates ; my old Python3.5 code ends in 0.98s. New TL. | 32,926 |
grace marks (MTHUR)
In earlier days, grading in BITS used to be absolute, instead of relative grading scheme. Once Professor Mathur decided to conduct a surprise quiz, and many students were caught unaware of it. Their scores of the students came out to be much worse than the previous years scores.
Professor Mathur really believed that true test of talent comes in difficult situations and continued such horrifying sequences of tests. But finally poor placements of his students turned the heat up for the professor and he decided to revise everyone's marks.
Now being a qualified mathematician, professor Mathur applied a simple strategy to this. He decided to award some constant grace marks to each and every student. He took every students last year marks and then added up the absolute difference with the revised current year marks. And he decided to choose the grace marks with the least sum of absolute difference. I.e. sum(abs (a[i] - (b[i]+grace))) should be minimum. Also, professor Mathur had a knack of choosing the grace value from his set of favourite numbers.
Now that our students are happily placed in 'Microsoft', 'Adobe' for the good
, credit finally goes to Professor Mathur.
Now, decide for each input, what grace marks were given by Mathur. (If there are many such grace marks, choose the lowest one).
Input
First line, t for number of test cases. Next 5*t line for each test case.
First line of every testcase: integer n.
Second line: n integers showing previous years marks of every student.
Third line: n integers showing present years marks of every student.
Fourth line: integer m.
Fifth line: m integers showing the possible values for grace marks.
Output
Output the expected grace marks.
Example
Input:
1
5
9 10 7 3 10
4 1 4 1 3
6
0 1 2 3 4 5
Output:
5
Constraints
number of testcases, t < 20
maximum number of students: n < 10000
1 <= m, marks[i] <= 50000 | 32,927 |
Blackout (BLACKOUT)
Caracas, as any other city, never sleeps, however, this is about to change as the Chief Officer Marcos “the little one” is scheduling some blackouts to search an important criminal and bring it to justice (If you like to know the criminal is known as “El Pran Malandroso”), the criminal is known for fainting when he doesn't see any source of light, so this is a perfect plan for Marcos “the little one” to trap him and capture him.
Marcos will give you the map where he is searching the criminal, the zone is given in a matrix and each value represents a block, surrounded by streets, where the number at the i-th row and j-th column denotes the number of people living in this block.
As Marcos “the little one” is a good officer, he doesn't wants to bother more than a specific number of people, as when he darken the zone, the people will going to be mad. That's what he called you for, Marcos will give you the north-west corner and the south-east corner, he will search in this specific area, causing a blackout.
Marcos will perform a series of blackouts in the city during the night, he will perform each blackout in a given zone, he will return the city all of its light and then he will perform another blackout, so on until he does Q blackouts, as the criminal is constantly moving in the city, the blackout will be independent and the area of searching will be always considered different.
Knowing this, can you maximize the area searched without exceeding the limit that Marcos gives you? (Citizens will be going mad when a blackout occurs)
INPUT:
The first line will contain 4 integers N, M, Q and K, denoting, respectively the N and M matrix size denoting an aerial view of the city, Q blackouts that Marcos the little one will do and K people that he wants to bother as much.
Then, N lines follow, each containing M integers, representing the people living in the block.
After that, Q lines will follow, each one containing four integers denoting the (i,j) point of the north-west corner and the (i,j) point of the south-east corner.
OUTPUT:
The first and only line of output should contain a number, representing the maximum area that Marcos can look for the criminal.
SAMPLE1:
INPUT
OUTPUT
3 3 2 20
1 2 3
4 5 6
7 8 9
1 1 3 3
1 1 2 2
4
Is important to note that each blackout is independent from the other, so, blackout affecting the zone (1,1) to (3,3) will lead to 45 people angry and 9 units of area, while a blackout from the zone (1,1) to (2,2) will get 12 people angry and 4 units of area. If the limit were 57, you could perform the two blackouts, giving a total result of 13.
SAMPLE2:
INPUT
OUTPUT
4 3 3 76
1 4 9
5 5 2
2 1 9
9 1 9
2 1 4 3
1 1 4 3
2 1 3 2
16
CONSTRAINTS:
1 <= N,M <= 2000
1 <= Q <= 1000
1 <= K <= 1000
0 <= (Ni,Mj) <= 1000
It is safe to say that there will be always an answer to this problem. (You will always find at least one blackout that doesn't bother more than K citizens) | 32,928 |
Nubulsa Expo (FZ10B)
English
Vietnamese
You may not hear about Nubulsa, an island country on the Pacific Ocean. Nubulsa is an undeveloped country and it is threatened by the rising of sea level. Scientists predict that Nubulsa will disappear by the year of 2012. Nubulsa government wants to host the 2011 Expo in their country so that even in the future, all the people in the world will remember that there was a country named "Nubulsa".
As you know, the Expo garden is made up of many museums of different countries. In the Expo garden, there are a lot of bi-directional roads connecting those museums, and all museums are directly or indirectly connected with others. Each road has a tourist capacity which means the maximum number of people who can pass the road per second.
Because Nubulsa is not a rich country and the ticket checking machine is very expensive, the government decides that there must be only one entrance and one exit. The president has already chosen a museum as the entrance of the whole Expo garden, and it's the Expo chief directory Wuzula's job to choose a museum as the exit.
Wuzula has been to the Shanghai Expo, and he was frightened by the tremendous "people mountain people sea" there. He wants to control the number of people in his Expo garden. So Wuzula wants to find a suitable museum as the exit so that the "max tourists flow" of the Expo garden is the minimum. If the "max tourist flow" is
W
, it means that when the Expo garden comes to "stable status", the number of tourists who enter the entrance per second is at most
W
. When the Expo garden is in "stable status", it means that the number of people in the Expo garden remains unchanged.
Because there are only some posters in every museum, so Wuzula assume that all tourists just keep walking and even when they come to a museum, they just walk through, never stay.
Input
There are several test cases, and the input ends with a line of "
0 0 0
".
For each test case:
The first line contains three integers
N
,
M
and
S
, representing the number of the museums, the number of roads and the number of the museum which is chosen as the entrance (the museums are numbered from 1 to
N
). For example,
5 5 1
means that there are 5 museums and 5 roads connecting them, and the number 1 museum is the entrance.
The next
M
lines describe the roads. Each line contains three integers
X
,
Y
and
K
, representing the road connects museum
X
with museum
Y
directly and its tourist capacity is
K
.
Please note:
1 <
N
≤ 300, 0 <
M
≤ 50000, 0 <
S
,
X
,
Y
≤
N
, 0 <
K
≤ 1000000
Output
For each test case, print a line with only an integer
W
, representing the "max tourist flow" of the Expo garden if Wuzula makes the right choice.
Sample
Input:
5 5 1
1 2 5
2 4 6
1 3 7
3 4 3
5 1 10
0 0 0
Output:
8 | 32,929 |
Longest Common Subsequence (LCS0)
No imagination at the moment.
Input
You will be given two lines. The first line will contain the string A, the second line will contain the string B. Both strings consist of no more than 50000 lowercase Latin letters.
Output
Output the length of the longest common subsequence of strings A and B.
Example
Input
abababab
bcbb
Output
3 | 32,930 |
All Possible Barns (ALLBARN2)
Farmer John is going to build a new rectangular barn. But the 4 corners of the barn mustn't be on soft soil. He examined the ground and found that there are only N (4 <= N <= 1,000) appropriate points for the corners. He wants to know the number of possible ways to build the new barn.
Given the points, help him find the answer.
Input:
Input exactly contains 10 test cases each of them as follows:
Line 1: A single integer, N.
Lines 2..N+1: Each line has two space-separated integers x, y which are the coordinates of a point. The magnitude of the coordinates is not more than 16,000. All points will be distinct.
Output:
For each Test case print one line contains:
Line 1: The number of possible ways to build the new barn.
Sample:
Input
8
1 2
1 -2
2 1
2 -1
-1 2
-1 -2
-2 1
-2 -1
[and 9 more Test cases ...]
Output
6
[and 9 more Test cases ...]
Output Details:
The possible answers are: {1, 2, 6, 5}, {1, 3, 6, 8}, {1, 4, 6, 7}, {2, 3, 5, 8}, {2, 4, 5, 7}, {3, 4, 8, 7} | 32,931 |
Linear Garden (LINEGAR)
Ramesses II has just returned victorious from battle. To commemorate his
victory, he has decided to build a majestic garden. The garden will contain
a long line of plants that will run all the way from his palace at Luxor to
the temple of Karnak. It will consist only of lotus plants and papyrus
plants, since they symbolize Upper and Lower Egypt respectively.
The garden must contain exactly N plants. Also, it must be balanced: in any
contiguous section of the garden, the numbers of lotus and papyrus plants
must not differ by more than 2.
A garden can be represented as a string of letters ‘L’ (lotus) and ‘P’
(papyrus). For example, for N=5 there are 14 possible balanced gardens. In
alphabetical order, these are: LLPLP, LLPPL, LPLLP, LPLPL, LPLPP, LPPLL,
LPPLP, PLLPL, PLLPP, PLPLL, PLPLP, PLPPL, PPLLP, and PPLPL.
The possible balanced gardens of a certain length can be ordered
alphabetically, and then numbered starting from 1. For example, for N=5,
garden number 12 is the garden PLPPL.
Task
Write a program that, given the number of plants N and a string that
represents a balanced garden, calculates the number assigned to this garden
modulo some given integer M. Note that for solving the task, the value of M
has no importance other than simplifying computations.
Constraints
1 <= N <= 1,000,000
7 <= M <= 10,000,000
Input Format:
Line 1: N, the number of plants in the garden
Line 2: M
Line 3: A string of N characters ‘L’ (lotus) or ‘P’ (papyrus) that represents a balanced garden.
Output Format:
Line 1: Your program must write to the standard output a single line
containing one integer between 0 and M-1 (inclusive), the
number assigned to the garden described in the input, modulo
M.
Example:
Input:
5
7
PLPPL
Output:
5
Explanation:
The actual number assigned to PLPPL is 12. So, the output is 12 modulo 7,
which is 5. | 32,932 |
Fibonacci With a Square Root (FIBOSQRT)
FIBONACCI is the recursive sequence that is given by: F(n)=F(n-1)+F(n-2) with F(0)=0 and F(1)=1.
In this problem we define FIBOSQRT that is given by: Fs(n)=Fs(n-1)+Fs(n-2)+2*SQRT(3+Fs(n-1)*Fs(n-2)) with Fs(0) and Fs(1) are given in the input file.
It's guaranteed that SQRT(3+Fs(n-1)*Fs(n-2)) is always an integer.
I've proved it by math theorem.
Now your task is to find Fs(n). Since the number can be big you have to find the result mod M.
Input
The first line is an integer T(1 ≤
T
≤ 111,111), denoting the number of test cases. Then, T test cases follow.
For each test case, there are four integers
Fs(0)
,
Fs(1)
(1 ≤
Fs(0)
≤
Fs(1)
< 10
6
),
M
(1 ≤
M
< 10
9
), and
n
(0 ≤
n
< 10
18
) written in one line, separated by space.
Output
For each test case, output Fs(
n
) mod
M
.
Example
Input:
2
1 1 10 5
2 3 100 6
Output:
4
82
Explanation:
Case #1:
Fs(0)=1
Fs(1)=1
Fs(2)=1+1+2*SQRT(3+1*1)=6
Fs(3)=6+1+2*SQRT(3+6*1)=13
Fs(4)=13+6+2*SQRT(3+13*6)=37
Fs(5)=37+13+2*SQRT(3+37*13)=94
The answer is: 94 mod 10 =
4
.
Case #2:
Fs(0)=2
Fs(1)=3
Fs(2)=3+2+2*SQRT(3+3*2)=11
Fs(3)=11+3+2*SQRT(3+11*3)=26
Fs(4)=26+11+2*SQRT(3+26*11)=71
Fs(5)=71+26+2*SQRT(3+71*26)=183
Fs(6)=183+71+2*SQRT(3+183*71)=482
The answer is: 482 mod 100 =
82
.
Notes
File #1: More than 100,000 random test cases (test your program speed
)
File #2: Less than 10 test cases (tricky test cases that might give you WA
)
Time Limit ≈ 8*(My Program Top Speed)
Warning: large Input/Output data, be careful with certain languages
See also:
Another problem added by Tjandra Satria Gunawan | 32,933 |
Just Next !!! (JNEXT)
DevG likes too much fun to do with numbers.
Once his friend Arya came and gave him a challenge,
he gave DevG an array of digits which is forming a number currently (will be called as given number).
DevG was challenged to find the just next greater number which can be formed using digits of given number.
Now DevG needs your help to find that just next greater number and win the challenge.
Input
The first line have t number of test cases (1 ≤ t ≤ 100).
In next 2×t lines for each test case first there is number n (1 ≤ n ≤ 1000000)
which denotes the number of digits in given number and
next line contains n digits of given number separated by space.
Output
Print the just next greater number if possible else print -1 in one line for each test case.
Note :
There will be no test case which contains zero in starting digits of any given number.
Example
Input:
2
5
1 5 4 8 3
10
1 4 7 4 5 8 4 1 2 6
Output:
15834
1474584162 | 32,934 |
Pizzamania (OPCPIZZA)
Singham and his friends are fond of pizza. But this time they short of money. So they decided to help each other. They all decided to bring pizza in pairs. Our task is to find the total number of pairs possible which can buy pizza, given the cost of pizza. As pizza boy don't have any cash for change, if the pair adds up to more money than required, than also they are unable to buy the pizza. Each friend is guaranteed to have distinct amount of money. As it is Singham's world, money can also be negative ;).
Input
The first line consist of t (1 <= t <= 100) test cases. In the following 2*t lines, for each test case first there is n and m, where n (1 <= n <= 100000) is number of Singham's friend and m is the price of pizza. The next line consist of n integers, separated by space, which is the money each friend have.
The value of m and money is within the limits of int in C, C++.
Output
A single integer representing the number of pairs which can eat pizza.
Example
Input:
2
4 12
9 -3 4 3
5 -9
-7 3 -2 8 7
Output:
1
1 | 32,935 |
Help the Commander in Chief (KFSTB)
The Country of byteland is in a state of war with its neighboring nation bitland which is a small island. The king of byteland needs to send his soldiers across the sea to attack bitland. It is not easy for bytelandian soldiers to cross the sea between the two countries as there are soldiers of bitland who are constantly on patrol.
But, The commander of byteland through his secret sources has gathered some information about the camping spots in between, It is as follows. There are
C
camping spots in the sea between the two countries. There are
B
one way
bridges, each bridge is between two camps. Bytelandian army can use these bridges without any danger of being attacked. The commander also knows that if the army leaves a camping spot along a bridge safely it is not possible to return back safely to the same camping spot.
The camping spot closest to the bytelandian shore is
S
and the camping spot closest to the bitlandian shore is
T
. The commander in chief of byteland wants to formulate a strategy for the army to safely move from the camping spot S to T. You have been assigned the task of finding the number of possible paths that a soldier could follow from camping spot S to T.
Input
The first line of input contains the number of test cases
D
. For each test case the first line contains C, B, S and T number of camping spots, number of one way bridges, camping spot close to byteland and camping spot close to bitland respectively. The next B lines contain description of bridges. Each bridge is described on a single line by two integers
X
and
Y
denoting the starting and ending point of a bridge.
Output
In each line print the number of possible paths
modulo
1000000007
Sample Input
2
4 4 1 4
1 2
1 3
2 4
3 4
5 5 1 5
1 2
2 3
2 4
3 5
4 5
Sample Output
2
2
Constraints
1 ≤ D ≤ 10
1 ≤ C ≤ 10000
1 ≤ B ≤ 10000
1 ≤ X, Y ≤ C
1 ≤ S, T ≤ C | 32,936 |
Morenas Candy Shop ( Easy ) (MORENA)
HARDER VERSION:
HILO
Brunette's is a big candy shop from Little Campina in Paraibas, Brazil. This company is known for making the best candies in the world. Matheus Pheverso is the president of this company and he has a sister called Morena who loves and helps him in running the company. She uses to go the supermarket every day and buy a lot of stuffs to make all the candies. But she's insane and likes to take an alternate path to go to the supermarket.
Given the streets heights, a path is alternate only if the differences between successive numbers strictly alternate between positive and negative.
Example:
- Street Heights: {1, 3, 4, 5, 2, 9, 8, 10}
- Alternate Paths: {1, 3, 2, 9, 8}, {1, 4, 2, 8}, {1, 5, 2, 9, 8}
Matheus Pheverso is a friendly brother and he would like to know the longest alternate path between the first supermarket and the last supermarket, this means that his sister always starts at the supermarket number 1, and always ends at the last supermarket.
Given the number of supermarkets, and their heights, your task is to print the longest alternate path between the first and the last city.
Input
There is a single positive integer N on the first line of input (1 ≤ N ≤ 10
6
) representing the number of supermarkets. In the second line there're N integers Ai representing the heights of each supermarket (-10
18
≤ Ai ≤ 10
18
).
Output
You have to print the longest alternate path between the first and the last supermarket. The supermarket number 1 is always the first, and the supermarket number N is always the last one.
Example
Input:
5
1 2 3 4 5
Output
2
Input:
8
1 4 2 10 1 9 7 8
Output
8 | 32,937 |
High and Low (HILO)
A student is always bored during his math classes. As the teacher won't let him sleep, he finds something else to do: try to find patterns in the numbers written on the board! Currently, he's spending his time trying to find Hi&Lo subsequences.
Intuitively, a Hi&Lo sequence is any sequence that has consecutive differences with opposite signs, that is, if the first number is greater than the second, then the second is smaller than the third, the third is greater than the fourth, and so on.
Formally, let x[1], x[2] ... x[n] be the numbers written on the board. A Hi&Lo subsequence of length k that only uses elements from A to B is a sequence of indices a
1
, a
2
... a
k
such that:
B ≤ a
k
> ... > a
2
> a
1
≤ A
x[a
i
]- x[a
i-1
] ≠ 0, for 1 < i ≤ k
( x[a
i
] - x[a
i-1
] )( x[a
i+1
] - x[a
i
] ) < 0, for 1 < i < k
Note that every sequence with only one element is a Hi&Lo sequence.
However, as the amount of numbers increases, finding a big subsequence is getting harder and harder, so he asked you to create a program to help him and quickly find the largest Hi&Lo subsequence in a given interval.
Input
The input contains several test cases. A test case begins with a line containing integers
N
(1 ≤ N ≤ 100000) and
M
(1 ≤ M ≤ 10000), separated by spaces. On the second line there are
N
positive integers, the initial state of the board.
M
lines follow, each with an instruction. Instructions can be of two kinds:
q A B: Print the length of the longest Hi&Lo subsequence only using elements in positions from A to B, inclusive. You may assume that 1 ≤ A ≤ B ≤ N.
m A B: Modify the Ath element of the sequence to the positive integer B. You may assume that 1 ≤ A ≤ N.
No number on the board will ever exceed 10
9
. There is a blank line after each test case. The last test case is followed by a line containing two zeros.
Output
For each instruction of type 1, print a line containing an integer, the answer to the query. After each test, print a blank line.
Example
Input:
5 7
1 2 3 4 5
q 2 4
m 3 1
q 2 4
m 3 2
q 2 4
m 4 2
q 2 4
0 0
Output:
2
3
2
1 | 32,938 |
Cloud Computing (CLOUDMG)
The concept of cloud computing has become fairly popular lately. One of the main kinds of cloud computing is known as IaaS (
Infrastructure as a Service
), in which servers can be rented and managed via the Internet.
Cloud, Inc. is an IaaS provider. The company is designing a new data center for its clients. Through some research, they found out that their clients, as a whole, need K servers, each of which needs to be able to withstand a certain level of demand. If we assume that the cost of a server always grows with the demand which that server can process, the best solution in terms of cost is to buy K servers explicitly designed to meet the exact requirements of the corresponding client.
However, having K different hardware configurations in the data center is extremely problematic for the system administrators. To simplify, they demand that no more than L distinct server types be bought. A server that meets a demand c also meets any demand smaller than c.
A possible solution is to buy only one server type that is able to meet the highest client demand, as it will also be able to meet all other demands. On the other hand, the cost of such a solution can be prohibitively high. Considering that you can buy up to L different kinds of servers, there's likely a better option. For instance, suppose that there are 3 clients, with demands 3, 7 and 16. Assume that the cost of a server meeting demands up to 3 is of R$ 1500 (1500 Brazilian reais), the cost of a server that meets demand 7 is R$ 5500 and the cost of a server that meets demand 16 is R$ 19200. If you want to buy at most 2 kinds of servers to satisfy all clients, you have four possibilities:
Buying three servers with capacity 16, at a total cost of R$ 57600;
Buying two servers with capacity 16 and one with capacity 7, at a total cost of R$ 43900;
Buying two servers with capacity 16 and one with capacity 3, at a total cost of R$ 39900;
Buying one server with capacity 16 and two servers with capacity 7, at a total cost of R$ 30200.
Among these options, the one with the least total cost is the last one.
You will receive a list of K requested demands and the price of a server type that meets the corresponding demand. Determine the lowest total cost to buy K servers in a way such that all requested demands are met and at most L different types of servers are bought.
Notes
Each server is used by one and only one client. A server with capacity 4 may
not
be used by two clients with demand 2 each.
Let D
i
and D
j
be two demands, and P
i
, P
j
prices associated to the servers that meet those demands. If D
i
< D
j
, then P
i
≤ P
j
.
Input
There are several test cases.
Each test case begins with a line containing integers K and L, respectively the number of servers to be bought and the maximum allowed number of distinct server types (1 ≤ L ≤ K ≤ 2000). K lines follow, each of which containing two integers D and P, respectively the demand of a client and the smallest price of a server which meets that demand (1 ≤ D ≤ 2000, 1 ≤ P ≤ 100000). If the same value of D is present on more than one line, then both lines will have the same value for P.
The input ends when K = L = 0, and this case should not be processed.
Output
For each test case, print a line with an integer T, which is the lowest total cost obtainable.
Example
Input:
10 3
1 1
2 4
3 5
4 7
5 8
6 12
7 13
8 18
9 19
10 21
0 0
Output:
129
The best option to buy servers of 3 kinds that meet the required demands is to buy:
3 servers of capacity 10, which account for client demands 10, 9 and 8;
2 servers of capacity 7, which account for client demands 7 and 6;
5 servers of capacity 5, which account for all other demands.
Total cost is 3*21 + 2*13 + 5*8 = 129. | 32,939 |
Multinomial numbers (HS12MULT)
You may perhaps know how to find the last nonzero digit of n factorial. This time your task is harder, find the last nonzero decimal digit of the multinomial coefficient:
(a
1
+a
2
+ … +a
n
)!/(a
1
!*a
2
!* … *a
n
!) . Note that this is an extension of the classical problem, since factorials (and binomial numbers) are also multinomial numbers!
Input
An integer
T
, denoting the number of testcases (
T
≤10000). In each line you are given one positive integer ( n≤20 ), followed by n integers: a
1
,a
2
,…,a
n
, where 0 ≤ a
i
≤ 1000000000. There are 4 input sets for 10 points.
Output
Output
T
lines, the case number followed by the last nonzero decimal digit. See the sample output for the correct format!
Example
Input:
7
1 0
2 11 9
4 5 7 2 9
3 1000 3000 2000
3 100000000 200000000 300000000
2 4 9
8 1 1 4 7 4 8 9 2
Output:
Case 1: 1
Case 2: 6
Case 3: 8
Case 4: 6
Case 5: 2
Case 6: 5
Case 7: 4
Warning: A naive algorithm will probably solve only the first two input sets. | 32,940 |
Classification from Erdős and Selfridge (HS12PRIM)
Erdős Pál and John Selfridge classified prime numbers in this way: for a prime
p
, if the largest prime factor of
p - 1
is
2
or
3
, then
p
is in class one. Otherwise,
p
is in class
c + 1
where
c
is the largest of the classes of the prime factors of
p - 1
. We put
p = 2
in class one. For example,
p = 89
is in class three, because
p - 1 = 2
3
× 11
and here
2
is in class one, but
11
is in class two (because
11 - 1 = 2 × 5
and here
2
and
5
are in class one). Your task is to count the number of primes in each class up to class thirteen for a given (closed) interval.
Input
The first line contains the number of test cases
T
, where
T ≤ 1000
. Each of the following
T
lines contains two integers
a, b
where
0 ≤ a ≤ b ≤ 50000000
. There are 4 input sets.
Output
Output the case number, followed by the distribution of the primes in each class up to class
13
in the (closed) interval
[a, b]
. See the sample input/output for the correct format!
Example
Input:
3
2 100
23 23
0 50000000
Output:
Case 1:
There are 10 primes in class 1.
There are 9 primes in class 2.
There are 5 primes in class 3.
There are 1 primes in class 4.
There are 0 primes in class 5.
There are 0 primes in class 6.
There are 0 primes in class 7.
There are 0 primes in class 8.
There are 0 primes in class 9.
There are 0 primes in class 10.
There are 0 primes in class 11.
There are 0 primes in class 12.
There are 0 primes in class 13.
Case 2:
There are 0 primes in class 1.
There are 0 primes in class 2.
There are 1 primes in class 3.
There are 0 primes in class 4.
There are 0 primes in class 5.
There are 0 primes in class 6.
There are 0 primes in class 7.
There are 0 primes in class 8.
There are 0 primes in class 9.
There are 0 primes in class 10.
There are 0 primes in class 11.
There are 0 primes in class 12.
There are 0 primes in class 13.
Case 3:
There are 54 primes in class 1.
There are 14196 primes in class 2.
There are 364182 primes in class 3.
There are 1029984 primes in class 4.
There are 939493 primes in class 5.
There are 458831 primes in class 6.
There are 150902 primes in class 7.
There are 34878 primes in class 8.
There are 7085 primes in class 9.
There are 1310 primes in class 10.
There are 203 primes in class 11.
There are 15 primes in class 12.
There are 1 primes in class 13.
Warning: A naive algorithm will probably solve only the first input set. | 32,941 |
Natalia Spins The Roulette (ROULETTD)
A La Vega Roulette is like a normal Roulette. It is a circular shape with numbers written down on the edge so that they fill up the whole circumference line. It differs from the well-known Roulette in two aspects. First, all numbers have the same color. Second, there is a marker right at the top of the center of the Roulette.
Natalia and Luis are bored and decided to play "Battle of the Spins" with a La Vega Roulette. On her first turn, a player rotates the La Vega Roulette such that the first number is below the marker. Then, she spins the Roulette and writes down the number that landed on the marker. She also records the position of the Roulette. In subsequent turns, the player must first rotate the Roulette back to the position where it ended in her previous turn, spin, sum the new marked number to her current sum and record again the position.
After both players take a turn then a decision must be made to whether continue playing or announce verdict. Let's say the sum of Player 1 and Player 2 are S1 and S2, respectively. If S1 - S2 > K, Player 1 wins and the game is over. If S2 - S1 > K, then Player 2 wins. However, if S1 - S2 = 0, the game is a draw and ends immediately. If none of the previous conditions apply, the game continues.
You are given the amount of numbers by which the La Vega Roulette spun after each player's turn. Please output the result of the battle.
Input
The first input line contains two space-separated integers N (2 ≤ N ≤ 10
3
), the size of the list of numbers along the La Vega Roulette's circumference and K (100 ≤ K ≤10
5
), the threshold. Then there's a second line with N space-separated 32-bit integers. Each of these integers represent the i
th
number written down on the circumference. Then there are many lines. Each of these lines contain two space-separated integers Spin1 and Spin2 (1 ≤ Spin1, Spin2 ≤ 10
5
). Each represent the amount of numbers by which the La Vega Roulette rotated in Player 1's and Player 2's turns, respectively. It is guaranteed that there are sufficient lines to reach a verdict.
Output
Please output the answer to this problem. If Player 1 wins, write "P1". If Player 2 wins, write "P2". If there's a draw, write "BAD LUCK".
Example
Input:
6 120
6 5 1 80 10 50
3 2
2 5
Output:
P1
Note:
In this test case, both players start at the first position. After the first round, Player 1 writes down 80 and Player 2 writes down 1. Because S1 - S2 and S2 - S1 are not zero and neither greater than K = 120, the game takes another round.
After the second round, Player 1 writes down 50 and Player 2 writes down 5. Now S1 = 80 + 50 = 130 and S2 = 1 + 5 = 6. Because S1 - S2 = 124 > 120, Player 1 wins and the game is over. | 32,942 |
Natalia Has Another Problem (NATALIAS)
Natalia has another problem she needs your help with. Do you still have some energies left?
A
Logical String
is a string that represents a valid boolean expression. It is composed of operators AND, OR and NOT and truth values operands. The boolean expressions are recursive in the sense that operators can have other operators as operands. For example, the following is a list of valid
Logical Strings
:
T
T
F
F
AND(T, T)
OR(T, F)
NOT(T)
AND(OR(T, F), AND(F, F))
AND(AND(AND(OR(T, F), F), F), T)
AND ( AND ( OR ( T,F),OR(F,F)),T)
Please note that there can be several spaces in between objects. However, no space will be in between letters of the names. Therefore, "AND(T,T)" is a valid
Logical String
but "A N D(T,T)" is not.
Given a
Logical String
, please evaluate it and output its truth value.
Input
The first line contains T (1 ≤ T ≤ 100), the number of test cases. Then there are T lines. Each line contains a string s
0
s
1
s
2
... s
n-1
(1 ≤ N ≤ 100). It is guaranteed that the i
th
Logical String
is valid.
Output
For each
Logical String
given, output its truth value. If it is true, output T, otherwise output F.
Example
Input:
7
T
F
AND(T, T)
OR(T, F)
NOT(T)
AND(OR(T, F), AND(F, F))
AND(AND(AND(OR(T, F), F), F), T)
Output:
T
F
T
T
F
F
F | 32,943 |
Natalia Plays a Game (NATALIAG)
When Natalia is not having fun studying Computing Science in Santiago de los Caballeros, she opens up her bag and pulls out an iPad she won at a Programming Olympiad to play a classical maze game.
The maze is a rectangular figure of M rows and N columns. Open areas are represented by a 'O' while closed areas are represented by a '*'. An area is just a 1x1 block inside the maze. There's an entrance area marked by a '$' and a destination area marked by a '#'. Please note that both the entrance and destination are also open areas.
Once Natalia is located inside an open area, she can decide to move to either cardinal direction (north, south, east or west). In other words, if Natalia is located at (x,y), she can move to either (x + 1, y), (x - 1, y), (x, y + 1) or (x, y - 1). Of course, she can't move inside a closed area.
Given a rectangular maze as described above, output the minimum number of steps necessary to reach the final position from the starting area, if it is possible. If not, output '-1'.
Input
The input contains many lines. The first line contains an integer T (1 ≤ T ≤ 100), the number of test cases. For each test case there's a first line that contains two space separated integers M and N (1 ≤ M ≤ 100), (2 ≤ N ≤ 100), the dimensions of the maze. The line is followed by M lines. Each of these lines contain a string of N characters. The position at index j of the ith string represents the marker of the i,j area. It can be either an open marker ('O'), a closed marker ('*'), the unique entrance marker ('$') or the unique destination marker ('#').
Output
For each test case output the minimum number of steps necessary to reach the final position from the entrance position. If it is impossible to reach the final position, output -1.
Example
Input:
2
3 3
$OO
***
OO#
3 3
$*#
O*O
OOO
Output:
-1
6 | 32,944 |
Spiderman vs Sandman (SPIDY)
There is a faceoff between Spiderman and Sandman.
There are two glass buildings each of height H. Each building has H equal sized windows on the outside covering entire space from bottom to top. Some windows are open and Spiderman cannot land on these window.
In one step, Spiderman can:
Rise up to just above window of the same building he is on.
Slide down to just below window of the same building he is on.
Use his web to jump to Kth window above from current height on the other building.
Sandman on the other rises steadily a rate of 1 per step.
For the purpose of this problem, assume Spiderman and Sandman take turns i.e. Spiderman takes one step, then Sandman takes one step.
Your goal is to assist Spiderman to always remain above or at same height as Sandman at the end of Sandman's turn. Spiderman gets the first turn and both start at height 0 (i.e. Sandman is on the ground and Spiderman is on the window of lowermost floor of left building. It is guaranteed that window of lowermost floor of left building is not open.
Note: If Spiderman gets to area with height ≥ H assume he has got out.
You are Spiderman's best friend, your duty is to guide Spiderman to escape from Sandman if possible in shortest number of steps to get out.
Input
First line contains integer T.
T test cases follow. Each test case contains 3 lines.
First line of input contains two space separated integers H and K
Next two lines contain description of two buildings.
2nd line represents the left building - a string of length H. The i
th
character represents the state of window between (i-1) and i heights: character '-' represents closed window (safe to land on), character 'X' represents open window.
Similarly 3rd line represents the right building.
Output
For every test case output single integer x where x is the number of steps taken to get out of building. Output "NO" if Spiderman cannot escape the area and has to fight in the enclosure.
Constraints
1 ≤ T ≤ 10
1 ≤ H, K ≤ 10
5
Example
Input:
2
7 3
---X--X
-X--XX-
6 2
--X-X-
X--XX-
Output:
4
NO
Explanation
In first case Spiderman jumps to right building, goes one height down, jumps to left building and jumps to right building (he got to the top).
In second case, no matter how he moves, Spiderman cannot escape above the buildings. | 32,945 |
Buzz Trouble (BUZZOFF)
Commander Nebula decided to take interns into Star Command to join the Little Green Men (LGMs). And the job of physical training of these LGMs went to Buzz Lightyear. Assume N interns are taken, each with a distinct LGM ID.
Being busy with XR, Buzz sent Mira Nova to select a few of the interns and line them in the training center. XR noticed that he neither told Mira how many LGMs to select, nor in which order to arrange them; so Mira can select any number M of students (1<=M<=N) and line them up randomly (Assume that if Mira is to select M LGMs, then she selects the M smallest LGM IDs, eg, if N=5 and IDs be 12, 3, 4, 11, 2 and she decided to select 3 LGMs, then she picks up 3, 4 and 2).
XR wonders, how many different arrangements might Buzz find on arriving in the training centre for which no LGM is more than unit distance away from its correct position, and Buzz has to do less work in ordering them correctly (in increasing order of LGM ID).
As result might be large, output result modulo 10^9+7 (1000000007)
Input
first line contains T, number of test cases
Next T lines contain single number N, indicating number of LGM interns.
Output
T lines, each with the answer for corresponding case.
Constraints
1<=T<=10^4
1<=N<=10^18
Example
Input:
5
1
2
5
8
10
Output:
1
3
19
87
231
Explanation
for N=1, only case is to pick the only LGM.
for N=2, and LGM IDs are say 1 and 2, then Buzz might find [1], [1, 2], or [2, 1] Therefore 3. | 32,946 |
Mad Hulk (MADHULK)
Evil Doctor D has captured Hulk and put him into an underground tunnel system. The tunnel system is closed but sadly Hulk is not aware of this fact.
Tunnel structure is of the form of an asterisk. There are many tunnels coming out of single center point. Hulk is left unconscious at the outer end of tunnel. Once Hulk gets up he just wants to get out of this underground system. Since its completely dark down there, Hulk adopts the following strategy : He runs to get to the center and once he gets there he randomly enters another tunnel other than the one he came from. He will run to outer end of this tunnel, come back to center and again choose a random tunnel other than presently exited one (may as well be the first chosen one).
Note: The starting point of Hulk is at the end of the tunnel whose length is mentioned first in the array
You have to find out the the expected length of Hulk's path in which he would have visited the ends of all tunnels at least once.
Input
First line contains integer n giving number of test cases.
n test cases follow.
For each test case contains k followed k space separated integers representing the lengths of the k tunnels.
Output
One line per test case containing one number E which is the expected length of Hulk's path.
Constraints
2 ≤ k ≤ 50
Each integer a[i] : 1 ≤ a[i] ≤ 10
5
Example
Input:
2
2 40 40
3 50 50 50
Output:
80.0
300.0
In test case 1 there are two tunnels of length 40 each meeting at the center. Hulk runs from end of first to center. He will take the second on to reach the end of second. Hence 40 + 40 = 80.
In test case 2 there are three tunnels of length 50 each meeting at the center. Hulk would run from end of 0th tunnel to center (Total: 50). Run to end of one of the other two tunnels and back to center (Total: 50 + 50 × 2). Now to cover last tunnel remaining, he either choose the third tunnel immediately with probability 1/2 or chooses the first, goes to end, comes back to center and chooses third with probability 1/2 × 1/2 and so on. Total expected path length = 150 + 50 × 1/2 + 150 × 1/2 × 1/2 + 250 × (1/2)
3
... = 300.0 | 32,947 |
Devlali Numbers (HARSHAD)
Devlali numbers were an important coinage by Indian recreational mathematician D. R. Kaprekar.
For any positive integer n, define d(n) as the sum of n and the digits of n. Eg, d(199) = 199 + 1 + 9 + 9 = 218.
For a positive number m, if there exists no positive number r such that d(r) = m, then m is a Devlali number. First few Devlali numbers are 1, 3, 5, 7, ... so on.
A prime number falling in this family is called a Devlali Prime. First few Devlali Primes are 3, 5, 7, ... so on.
Input
First line contains integer Q.
Next Q lines contain two integers A and B.
Output
Print Q lines, each listing number of Devlali Primes in range [A, B] (both inclusive.)
Limits
1 ≤ Q ≤ 100000
0 ≤ A ≤ B ≤ 1000000
Example
Input
3
1 3
0 10
5 8
Output
1
3
2 | 32,948 |
Mirror Strings !!! (MSUBSTR)
As we all know Utkarsh is very good at solving number based problems, this time Arpit thinks smartly and gives Utkarsh to solve a problem on Strings. Arpit gives Utkarsh a string and challenges him to find the length of largest substring that have its mirror string same as its original one and number of such substrings. Now Utkarsh is busy at preparing Avishkar papers so he asks you to help him in doing this task.
E.g. for mirror string: Consider string "lalit" then its mirror string will be "tilal".
Input
There are t numbers of test cases (t <= 200) followed t lines where each line contains a character string of lower case characters (a-z) of length l (1 <= l <= 3000).
Output
There will be two integers per line separated by space indicating the length of largest substring which have its mirror string same and number of such substrings.
Example
Input:
3
lalit
abedcdetr
abcde
Output:
3 1
5 1
1 5 | 32,949 |
The Trip (OPCTRIP)
Akshat aka Singham, watches a lot of TV Series. Today he finished Castle, he is bored now and is planning for a trip with friends. He has N friends. As you all know Singham is very cautious and wants to save every penny he can. He has identified few regions that they will visit. He will start from MNNIT and visit all the regions one by one in buses.
Assume that all regions are connect by a single road running through these regions. Each region has a temperature ti units, if a bus is travelling through ith region and has k people in it then the temperature of the bus ti+k units.
If the temperature of the bus exceeds Ti units, then each of the member on the bus ask for refreshment in the form of ice -cream, drinks due to uncomfortable conditions. As the cost of products varies from region to region, the refreshment cost on average per member on bus in region i is Rs. xi.
As Akshat wants to save money, he thinks of adding/removing buses in the beginning of the trip and between regions (they need at least one bus to pass any region). Assume that buses have infinite capacity and friends can be randomly distributed on buses. Each of the bus in region i cost Rs. Ci.
You have to help Akshat find the minimum cost needed to organize the trip.
Input
First Line contains one integer tc, representing the number of test cases, then tc test cases follow.
Each test cases starts with two integer on first line n and m (1 <= n <= 10^5; 1 <= m <= 10^6) -- the number of regions in the trip and number of friends.
Next n lines contains four integers: the ith line contains ti (temperature of region), Ti (maximum tolerable temperature), xi (Average refreshment cost), Ci (cost per bus).(1 <= ti, Ti, xi, Ci <= 10^6).
Output
Print one integer, minimum cost needed to organize to trip. (Warning: Output may not be in the range of integer)
Example
Input:
2
2 10
30 35 1 100
20 35 10 10
3 100
10 30 1000 1
5 10 1000 3
10 40 1000 100000
Output:
120
200065 | 32,950 |
Smallest Inverse Euler Totient Function (INVPHI)
This task is the inverse of
ETF
problem, given an integer
n
find smallest integer
i
such that φ(
i
)=
n
, where φ denotes
Euler's totient function
.
Input
The first line is an integer
T
(1 ≤
T
≤ 100,000), denoting the number of test cases. Then, T test cases follow.
For each test case, there is an integer
n
(1 ≤
n
≤ 100,000,000) written in one line. (one integer per line)
Output
For each test case, output Smallest Inverse Euler's Totient Function of
n
. if
n
doesn't have inverse, output -1.
Example
Input:
5
10
20
30
40
50
Output:
11
25
31
41
-1
Time Limit ≈ 3*(My Program Top Speed)
See also:
Another problem added by Tjandra Satria Gunawan | 32,951 |
Smallest Inverse Sum of Divisors (INVDIV)
First, we define σ(
i
) = Sum of all positive divisors of
i
.
For example: all positive divisors of 60 = {1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60}
So σ(60) = 1 + 2 + 3 + 4 + 5 + 6 + 10 + 12 + 15 + 20 + 30 + 60 = 168
Now for the task: given an integer
n
find smallest integer
i
such that σ(
i
) =
n
.
Input
The first line is an integer
T
(1 ≤
T
≤ 100,000), denoting the number of test cases. Then, T test cases follow.
For each test case, there is an integer
n
(1 ≤
n
≤ 100,000,000) written in one line. (One integer per line.)
Output
For each test case, output the smallest inverse sum of divisors of
n
. if
n
doesn't have inverse, output -1.
Example
Input:
5
1
16
40
60
168
Output:
1
-1
27
24
60
Time Limit ≈ 2.5*(My Program Top Speed)
See also:
Another problem added by Tjandra Satria Gunawan | 32,952 |
My Reaction when there is no internet connection (NITT1)
There is college whose name will not be disclosed. To raise the level the college management installed wifi connections. There was poor hostel where there was a poor floor. The floor had n rooms. Three routers were setup just for that floor to increase the signal strength. Still there they weren't able to operate the internet. Also no router can hold more than the current connections from that wing. They finally found that if three adjacent room connects to a same router then there won't be an internet connection established. You know which room is connected to which router. Since they are very lazy (as it is the typical character of their college) they want to swap the router connection between certain room so that the number of unswapped rooms are maximum and also no three continuous rooms are connected to the same wifi router.
Input
First line T denoting the number of cases (T ≤ 40)
For each line a string x is given which determines which denotes which room is connected to which router (size of x ≤ 50)
Output
Output the maximum unswapped rooms which follows the above mentioned condition or output -1 if it is not possible to make a valid arrangement
Example
Input:
2
111222333
11111111322
Output:
6
7 | 32,953 |
hai jolly jolly jolly (NITT2)
Alp and Gaut are like always opposite to each other. Once Alp told that he can identify a number which is divisible by 252 (He knows because that is his girlfriends birthday - 25/2). Now to come up against Alp, Gaut said he can identify whether the number is divisible by 525 (poor Gaut don't have a girlfriend though). The truth is they don't know to do it for big numbers. So you are here to help them with a method. Given a number you have to tell whether the number is divisible by 252 and 525.
Input
Number of testcases in first line, T (T ≤ 100).
Each line contains one number N, whose divisibility is to be tested (1 ≤ N ≤ 10
50000
).
Output
Each line containing two Yes/No. one for 252 and one for 525.
Example
Input:
4
252
525
16884
21347
Output:
Yes No
No Yes
Yes No
No No | 32,954 |
NSquare Sum ( Easy ) (NSQUARE)
Given two integers N (N <= 10
18
) and a prime number P (1 < P < 10
18
), find the lowest number x such that there are not N integers greater or equal to 0 whose sum of squares is equal to x.
N = 2, P = 2
x = 3 mod 2 = 1
0 = 0
2
+ 0
2
1 = 1
2
+ 0
2
2 = 1
2
+ 1
2
4 = 2
2
+ 0
2
Input
The two integers N (1 <= N <= 10
18
) and a prime number P (1 < P < 10
18
). You have to print the answer modulo P.
Output
You have to print an integer x mod P (-1 < x < 10
18
+ 1) that satisfies the problem. If there's no number x, print "Impossible".
Example
Input:
1 3
Output:
2
Input:
13 7
Output:
Impossible | 32,955 |
NSquare Sum ( Medium ) (NSQUARE2)
Given Q pairs of integers Ni, Ai (1 <= Ai, Q <= 10
5
, 4 <= N <= 100), find Ni numbers whose square sums is equal to Ai. If there're more than one solution, print the one lexicographically smallest. If there's no solution, print "Impossible".
Q = 1
Ni = 4
A1 = 16
{ 4
2
+ 0
2
+ 0
2
+ 0
2
= 16}
Input
There's an integer Q (1 <= Q <= 10
5
) in the first line; it stands for the number of queries. The next Q lines describe each query with two integers Ni, Ai (1 <= Ai <= 10
5
, 4 <= Ni <= 100). Ni is the number of integers that you need to find whose sum of squares is equal to Ai.
Output
You have to print Q lines, each one with Ni numbers such that the sum of squares is equal to Ai. If there's no solution, you've to print "Impossible".
Example
Input:
1
4 16
Output:
0 0 0 4
Input:
1
4 15
Output:
1 1 2 3 | 32,956 |
Minimum Knight moves !!! (NAKANJ)
Anjali and Nakul are good friends. They both had a quarrel recently while playing chess. Nakul wants to know the minimum number of moves a knight takes to reach from one square to another square of a chess board (8 × 8). Nakul is brilliant and he had already written a program to solve the problem. Nakul wants to know whether Anjali can do it. Anjali is very weak in programming. Help her to solve the problem.
A knight can move in the shape of an "L" in a chessboard - two squares either forward, backward, left, or right and then one square to its left or right. A knight move is valid if it moves as mentioned above and it is within the boundary of the chessboard (8 × 8).
Input
There are T test cases in total. The next T lines contain two strings (start and destination) separated by a space.
The strings start and destination will only contain two characters - First character is an alphabet between 'a' and 'h' (inclusive), Second character is a digit between '1' and '8' (inclusive) - (Quotes just for clarity).
To know the knight moves more clearly refer to the above figure.
Output
Print the minimum number of moves a knight takes to reach from start to destination in a separate line.
Constraints
1 <= T <= 4096
Example
Input:
3
a1 h8
a1 c2
h8 c3
Output:
6
1
4 | 32,957 |
Tiles (NITT4)
Given a N × M floor with few blocks already filled, check if it is possible to fill the remaining space with only 2 × 1 blocks, if it is not possible, print the minimum number of 1 × 1 blocks required to fill the floor completely.
Input
First line contains N (number of rows), M (number of columns), B (number of already blocked cells), followed by B lines each containing 2 integers x, y coordinates of the blocked cell
1 ≤ N ≤ 100, 1 ≤ M ≤ 100, 0 ≤ B ≤ N × M
Output
If it is possible to fill the floor with only 2 × 1 tiles, print Yes, else print No and the minimum number of 1 × 1 tiles required.
Example
Input:
1 1 0
Output:
No 1
Input:
2 2 0
Output:
Yes
Input:
2 2 2
0 1
1 0
Output:
No 2 | 32,958 |
Dating Rishi (NITT8)
Dating Rishi
It's Monday and
Rishi
Dude is planning to select a girl to date for this week. So all N girls are standing in a line from 1 to N so that Rishi will select one of them. The girls are standing in a straight line but randomly. They know they cannot predict what Rishi The Great likes, He may like
hot, smart, tall, short, witty, white, black
or anything. But wait, Rishi, the Coolest Dude plans to date two girls this week !!!
How lucky they are ????
. But he wants to select two girls whose friendship quotient is maximum so that they wont fight too much over Rishi during the date. He is shy too !. Friendship quotient is defined as the product of absolute difference between the position of the two girls and the minimum height of the two girls.
Can you help Rishi to find the maximum friendship quotient ?
Input Specification
The first line of input file contains T which denotes number of test cases.
2×T lines follows.
First line of each test case contains an integer N.
Second line of each test case contains N space separated integers denoting the height of each girl.
Output Specification
The output must contain T lines each line corresponding to a test case.
Constraints
T ≤ 20
N ≤ 100000
Height[i] ≤ 10
9
Example
Input:
2
4
3 2 1 3
5
4 2 3 1 4
Output:
9
16 | 32,959 |
HNumbers (HNUMBERS)
Note: Some tricky test cases were added on Feb. 26th, 2013 and time limit has been changed. All the solutions have been rejudged and some "Accepted" ones got Wrong Answer / Time Limit Exceeded. However, this problem can still be solved by a simple and beautiful solution :)
Ualter is a smart guy, and he loves mathematics and everything related to numbers. Recently his friend Matheus Pheverso showed him a group of H-numbers. Also, his friend told him that, in the Ancient Greek, there H-numbers would be used to create music. This group of numbers can be described in this way:
For each integer N, a positive integer A is H-number with N only if: LCM(N, A) = N * A
LCM is the Lowest Common Multiple between two numbers.
Example 1: N = 20, H-numbers = {1, 3, 7, 9, 11, 13, 17, 19}
Example 2: N = 10, H-numbers = {1, 3, 7, 9}
Ualter loves classical music mainly Pachelbel's compositions. In order to achieve his old dream, he's willing to make a version of Canon in D using only H-numbers to create notes.
To solve that problem, he needs, for each number N, the number of H-numbers of N that are between 1 and M, inclusive.
Task
You're given an integer Q - the number of queries. Each query consists of two integer N and M. Your task is to find the number of H-numbers of N between 1 and M.
Input
In the first line there's an integer Q (1 <= Q <= 10^5) representing the number of queries. In the next Q lines there are two numbers N, M (1 <= N, M <= 10^5, M < N).
Output
You have to print for each query an integer xi representing the number of H-numbers of N less or equal to M.
Sample
Input:
3
20 15
7 3
10 8
Output:
6
3
3 | 32,960 |
Subset and upset (HARD) (SUBSHARD)
The whole world is crazy about subset sum. We define subset sum as sum of all subparts. A subpart is a number which is obtained by erasing certain digits and arranging the remaining numbers in the same order. You have to calculate the subset sum of the given number. Since the number can be very large return the subset sum modulo
m
.
For example if the number is 1357, then the various subparts are 1, 3, 5, 7, 13, 15, 17, 35, 37, 57, 137, 135, 157, 357, 1357.
Input
First line contains
T
(1
≤
T
≤ 50) denoting the number of test cases.
Next T lines containing two numbers
n
(0 <
n
< 10
1000
) and
m
(1 <
m
< 10
9
).
Output
Print the subset sum modulo
m
.
Example
Input:
6
111 9
111 200
456 9
456 1000
1357 1000
1357 5000
Output:
3
147
6
618
333
2333
Time Limit ≈ 2*(My Python 3 Program Top Speed)
See also:
Another problem added by Tjandra Satria Gunawan | 32,961 |
Red And Green (RANDG)
You have several squares arranged in a single row. Each square is currently painted red or green. You can choose any of the squares and paint it over with either color. The goal is that, after painting, every red square is further to the left than any of the green squares. We want you to do it repainting the minimum possible number of squares.
Squares are numbered from left to right. You will be given the initial arrangement as a String, such that character i is 'R' if square i is red or 'G' if square i is green. Print the minimum number of repaints needed to achieve the goal.
Input
There will be several test cases. Each test case will contain a string of not more than 50 characters on a separate line. Input is terminated by EOF.
Output
For each test case, print the output on a separate line.
Constraints
Input will contain between 1 and 50 characters, inclusive.
Each character of input will be either 'R' or 'G'.
Sample
Input
RGRGR
RRRGGGGG
GGGGRRR
RGRGRGRGRGRGRGRGR
Output
2
0
3
8
Solution & Dataset: Bidhan Roy | 32,962 |
Awari 2 (TAP2012A)
Awari is a one-player game from the Antilles, which is played with boxes and stones instead of cards. A particular variant of Awari is played with
N
boxes numbered from
1
to
N
, each containing at the beginning of the game zero or more stones. The rules of this game are very simple, because there is only one type of valid move, consisting of choosing a box numbered
i
containing exactly
i
stones, and then taking those stones from the box in order to use them to add a single stone to every box numbered
1
through
i-1
; the remaining stone is then kept by the player. These moves are applied in succession as long as there exists a box
i
containing exactly
i
stones. When this is no longer true, the game ends. The player wins if at this stage every box is empty, and looses otherwise.
In the following figure, on the left hand side there is a possible initial state of a game with
N = 5
boxes (the circles) containing
P
1
= 0
,
P
2
= 1
,
P
3
= 3
,
P
4
= 0
and
P
5
= 2
stones (the black dots). If box number
3
, containing
P
3
= 3
stones, was chosen to make the next move, then the resulting configuration would be the one shown on the right hand side of the figure. Additionally, the player would now have one stone in his power.
Given the initial state of the boxes, you should determine if it is possible to win the game, that is, if there is a sequence of valid moves after which all the boxes are left empty.
Input
Each test case is described using two lines. The first line contains an integer
N
, indicating the number of boxes (
1 ≤ N
≤ 500
). The second line contains
N
integer numbers
P
i
, representing the number of stones in the boxes at the beginning of the game, from box
1
to box
N
in that order (
0
≤
P_i
≤
500
for
i = 1, ..., N
). In every test case there is at least one non-empty box, that is there exists
i
from
1
to
N
such that
P
i
≠ 0
. The end of the input is signalled by a line containing the number
-1
.
Output
For each test case, you should print a single line containing a single character. This character should be the uppercase letter
'S'
if it is possible to win the game; otherwise, it should be the uppercase letter
'N'
.
Awari is played with N boxes numbered from 1 to N, each
containing at the beginning of the game zero or more stones.
The rules of this game are very simple, because there is only
one type of valid move, consisting of choosing a box numbered i
containing exactly i stones, and then taking those stones from
the box in order to use them to add a single stone to every box
numbered 1 through i-1; the remaining stone is then kept by the
player. These moves are applied in succession as long as there
exists a box i containing exactly i stones. When this is no
longer true, the game ends. The player wins if at this stage
every box is empty, and looses otherwise.
In the following figure, on the left hand side there is a
possible initial state of a game with N = 5 boxes (the circles)
containing P_1 = 0, P_2 = 1, P_3 = 3, P4 = 0 and P_5 = 2 stones
(the black dots). If box number 3, containing P_3 = 3 stones,
was chosen to make the next move, then the resulting
configuration would be the one shown on the right hand side of
the figure. Additionally, the player would now have one stone
in his power.
[IMAGE GOES HERE]
Given the initial state of the boxes, you should determine if
it is possible to win the game, that is, if there is a sequence
of valid moves after which all the boxes are left empty.
Example
Input:
5
0 1 3 0 2
4
1 1 3 0
3
1 2 3
-1
Output:
N
S
N | 32,963 |
Ball of Reconciliation (TAP2012B)
Every year the kingdoms of Cubiconia, Quadradonia and Nlogonia organize a ball to commemorate the end of the war that ravaged the region for many years. A certain number of noblemen of each kingdom is invited to participate in this event, and it is expected that every pair of guests coming from different kingdoms will dance together exactly once. That is, each of the guests from Cubiconia shall dance once with every guest from Quadradonia and Nlogonia; in turn, each of the guests from Quadradonia shall also dance once with every guest from Nlogonia. However, guests coming from the same kingdom are not allowed to dance with one another.
To help organize the ball, the total number of dances that will take place is determined beforehand, so that care must be taken when choosing the number of noblemen that shall be invited from each kingdom. For example, if it is decided that the ball must have
N = 20
dances, one possibility is to invite
6
noblemen from Cubiconia,
2
from Quadradonia and
1
from Nlogonia, which can be represented by the expression
(6, 2, 1)
. This is a valid option because the total number of dances would then be
6*2 + 6*1 + 2*1 = 20
.
Traditions whose origins nobody can now remember indicate that the number of invited noblemen from Cubiconia must be greater or equal to the number of those coming from Quadradonia, and at the same time the number of invited noblemen from Quadradonia must be greater or equal to those coming from Nlogonia. Thus, for
N = 20
dances there are exactly
5
possible ways to choose the number of guests from each kingdom, namely
(5, 4, 0)
,
(4, 2, 2)
,
(10, 2, 0)
and
(20, 1, 0)
as well as the aforementioned
(6, 2, 1)
.
With so many restrictions, the organizing committee has problems finding the ideal way to choose the number of guests from each kingdom. Your task is to help this committee by counting the different ways in which the number of guests can be chosen for a ball with
N
dances. Two of these ways are considered different if they differ in the number of invited noblemen from at least on of the three kingdoms.
Input
Each test case is described using a single line, containing an integer
N
representing the total number of dances that the ball must have (
1 ≤ N ≤ 10
4
). The end of the input is signalled by a line containing the number
-1
.
Output
For each test case, print a single line containing the number of different ways in which the number of guests from each kingdom can be chosen in order to have a ball where there are exactly
N
dances, with all the restrictions mentioned in the problem statement.
Example
Input:
20
1
9747
-1
Output:
5
1
57 | 32,964 |
Cantor (TAP2012C)
The mathematician Georg Cantor was a lover of both sets and infinity, but he didn't get along too well with his colleagues. One morning he woke up with the idea of defining a set so strange that, when made public, would make the rest of the mathematicians lose their sleep for several days. And he was successful.
The set he defined is called the Cantor set, and it is formed by all the real numbers in the interval
[0, 1]
whose decimal expression in base
3
uses exclusively the digits
0
and
2
. This set has amazing properties, which we will not mention here so that you can sleep tonight. Moreover, and luckily for everyone involved, in this problem we will not be working with the Cantor set, but with a generalization of this set to the integer numbers.
We will say that an integer number is of Cantor type, or a
cantiger
for short, if its expression in a given base
B
uses solely the digits in a given set
C
contained in
{0, 1, ... B-1}
. Thus, the fact that a given number is a cantiger depends on how we choose
B
and
C
.
Your task is to count cantiger numbers, in order to prevent the mathematicians of the entire world from loosing their sleep. More precisely, given two integers
D
and
H
, along with
B
and
C
, you have to count the number of cantigers with respect to
B
and
C
from
D
to
H
inclusive.
Input
Each test case is described using a single line. This line contains three integers,
D
,
H
and
B
, and a string
L
. The values of
D
and
H
indicate the endpoints of the closed interval
[D, H]
we are interested in (
1 ≤ D
≤
H
≤
10
16
). The value of
B
is the base mentioned in the problem statement (
2
≤
B
≤
10
). The string
L = L
0
L
1
... L
B-1
has exactly
B
characters, and describes the set
C
also mentioned in the problem statement. The character
L
i
is the uppercase letter '
S
' if
i
is in
C
, and the uppercase letter '
N
' otherwise (
i = 0, 1, ... B-1
). The set
C
is non-empty, so that there is at least one '
S
' character in
L
. The end of the input is signalled by a line containing three times the number
-1
and a single '
*
' character.
Output
For each test case, you should print a single line containing an integer number, representing the number of cantigers (with respect to
B
and
C
) that are greater or equal to
D
and lower or equal to
H
.
Example
Input:
1 10 3 SNS
99 999 5 NSSNS
1110 1111 10 NSNNNNNNNN
1 10000000000000000 10 NNNNNSNNNN
1 10000000000000000 7 SSSSSSS
-1 -1 -1 *
Output:
3
144
1
16
10000000000000000 | 32,965 |
Designing T-Shirts (TAP2012D)
Argentina's rugby is currently in one of its best moments of all time. Recently the under-18 and under-21 national teams qualified for their corresponding world cups, so the coaches of both teams have asked the Incredible Commission for the Production of Clothing (ICPC) to provide the t-shirts for these events. Each team is formed by
N
players, but because the two world cups do not take place simultaneously it was agreed that the ICPC would provide only
N
t-shirts, to be used by both teams.
For this reason, the t-shirts must be a valid set of clothing for both teams. The rules of the rugby world cups state that each player must go in the field with a t-shirt imprinted with a unique number, along with a prefix of the player's surname, not necessarily unique. This includes boundary cases such as a t-shirt with no surname prefix (that is, a prefix of length
0
) and a t-shirt with a complete surname.
The experts of ICPC immediately realized that they could simply provide
N
t-shirts with only numbers and no surnames on them, and each of them would be a valid t-shirt to be used by any player of any of the two teams. However, the coaches would rather have the t-shirts with the longest possible prefixes, of course without violating world cup rules, because this way it's easier for them to identify the players while the matches are taking place.
Your task is to help the ICPC finding the maximum number of letters that can be imprinted on a set of
N
t-shirts, so that this set is a valid clothing set for both teams. For example, if we have
N = 3
players, the under-18 team is composed of "
PEREZ
", "
GONZALEZ
" and "
LOPEZ
", whereas the under-21 team is composed of "
GARCIA
", "
PERALTA
" and "
RODRIGUEZ
", the optimal choice consists in having one t-shirt with the
1
-letter prefix "
G
" (to be used by "
GONZALEZ
" and "
GARCIA
"), another one with the
3
-letter prefix "
PER
" (to be used by "
PEREZ
" and "
PERALTA
"), and the third t-shirt with a
0
-letter prefix (to be used by "
LOPEZ
" and "
RODRIGUEZ
"). This way, the answer in this case would be
1 + 3 + 0 = 4
.
Input
Each test case is described using three lines. The first line contains a single integer number
N
, indicating the number of players in each of the two teams (
1 ≤ N ≤ 10
4
). The second line contains the surnames of the
N
players in the under-18 team, whereas the third line contains the surnames of the
N
players in the under-21 team. Each surname is a non-empty string of at most
100
uppercase letters. In each test case the total number of characters in the
2N
surnames is at most
10
5
, and two or more players of the same or different teams may have the same surname.
The end of the input is indicated by a line containing the number
-1
.
Output
For each test case, you should print a single line containing an integer number, representing the maximum number of letters that can be imprinted on a set of
N
valid t-shirts to be used by both teams as explained in the problem statement.
Example
Input:
3
PEREZ GONZALEZ LOPEZ
GARCIA PERALTA RODRIGUEZ
2
RODRIGO GONZALEZ
GONZALO RODRIGUEZ
3
LOPEZ PEREZ LOPEZ
PEREZ LOPEZ LOPEZ
1
GIMENEZ
JIMENEZ
6
HEIDEGGER GAUSS GROTHENDIECK ERDOS CHURCH TURING
HEISENBERG GALOIS EULER ALLEN GODEL CHURCHILL
-1
Output:
4
12
15
0
13 | 32,966 |
Emma s Domino (TAP2012E)
The
domino effect
is a phenomenon that occurs when in a line of domino pieces, each standing on its smallest face, the first piece from one of the line's ends falls in the direction of the next piece. In turn, this second piece falls over the third one in the line, and so on until the other end of the line is reached, at which point every piece has fallen. Note that in order to produce this effect, the distance between consecutive pieces in the line must be lower or equal to their height.
Emma has very recently found out about the domino effect, and she was immediately amazed by it. She spent all morning forming a line with the
N
domino pieces that her brother Ezequiel gave her, but just before she was going to make the first piece fall, her grandma came to her home and took her to play in the park. Ezequiel knows Emma has not taken into account the distance between consecutive pieces when she formed her domino line, and doesn't want to see her frustrated if all the pieces do not fall after she pushes the first one. Thus, Ezequiel wants to move some pieces from inside the line so that the distance between consecutive pieces is always lower or equal to their height
H
. Because he doesn't want Emma to find out that he has moved some of the pieces, he will leave the first and last pieces where they are, and he would also like to move as few pieces as possible from inside the line. What is the minimum number of pieces he must move?
Input
Each test case is described using two lines. The first line contains two integer numbers
N
and
H
, indicating respectively the number of pieces in the line (
3 ≤ N
≤
1000
) and their height (
1
≤
H
≤
50
). The second line contains
N-1
integers
D
i
, representing the distances between pairs of consecutive domino pieces, in the order given by the line (
1
≤
D
i
≤
100
for
i = 1, 2 ... N-1
). The end of the input is signalled by a line containing two times the number
-1
.
Output
For each test case, you should print a line containing a single integer number, representing the minimum number of pieces that must be moved in order to have the distance between consecutive pieces always lower or equal to
H
. Note that the first and last pieces cannot be moved, and that the relative order between the the pieces cannot be changed. If it is impossible to achieve the desired result, print the number
-1
.
Example
Input:
8 3
2 4 4 1 4 3 2
10 2
1 2 2 2 2 2 2 2 3
5 2
2 2 2 2
5 3
1 6 2 4
-1 -1
Output:
3
8
0
-1 | 32,967 |
Fixture (TAP2012F)
The International Committee for Professional Chess (ICPC) organizes a Tournament for Advanced Players (TAP) with a very strange methodology. As expected, in each game exactly two players face each other, but in this case only one game takes place at a time, because there is only one chess board available. After receiving the inscriptions for the competitors and assigning them a number, the organization decides arbitrarily what matches are going to take place, and in which order. Each competitor can face any other competitor any number of times, and it is even possible that some competitors never play against others. Once built the general fixture of all the matches to be played, the organization hands each competitor a non-empty list of their rivals, in chronological order (that is, the order in which the matches will take place).
Florencia signed up in first place, so that she was assigned the number
1
. After chatting a bit with the other competitors, she realized that she had lost her list of rivals. Because she does not want to bother the TAP's organizers, she has asked all the other competitors for a copy of their own lists of rivals, hoping that with this information she would be able to reconstruct her lost list. Florencia is not sure if there exists a unique general fixture that is compatible with all the copied lists that she was given by the other competitors. However, she knows that the list that she was given by TAP's organizers is in fact unique. Your task is to help her reconstruct this list.
Input
Each test case is described using two lines. The first line contains a single integer number
N
, representing the number of competitors (
2
≤
N ≤ 9
). Each competitor is identified by a different integer from
1
to
N
, and competitor number
1
is always Florencia. The second line contains
N-1
non-empty strings
L
i
of at most
100
characters each (for
i = 2, 3, ..., N
). The string
L
i
is composed solely of digits between
1
and
N
, excluding digit
i
, and represents the list of rivals of competitor number
i
in chronological order. Note that competitor number
1
appears at least once in one of the given lists. In each test case, there exists a unique list of rivals for competitor number
1
that is compatible with the other lists of rivals. The end of the input is signalled by a line containing the number
-1
.
Output
For each test case, you should print a single line containing a string, representing the unique list of rivals of competitor number
1
(Florencia) that is compatible with the lists of rivals of the other competitors. The rivals indicated in this list must appear in chronological order.
Example
Input:
4
314 142 321
9
31 412 513 614 715 816 917 18
4
11111111111111111111111111111 4 3
-1
Output:
324
98765432
22222222222222222222222222222 | 32,968 |
Generating Alien DNA (TAP2012G)
GigaFarma is one of the largest pharmaceutical companies in the world, and it is currently conducting experiments using alien DNA. Its goal is to produce a chain of alien DNA that will report the maximum possible benefit when commercialized.
A chain of
alien
DNA can be understood as a non-empty sequence of genes connected by links, and in turn each
gene
is a non-empty sequence of bases. Because not every possible sequence of bases corresponds to a valid gene, GigaFarma has created a catalogue of genes that appear in alien DNA, which are the only ones considered valid sequences of bases. Each of these genes has a
value
according to its functionality, and a given chain of alien DNA has a
market value
that is the sum of the values of the genes that compose it.
We will represent the different
bases
with lowercase letters,
'a'
-
'z'
, and
links
using a hyphen
'-'
. In the following example we can see on the left a possible list of genes and their corresponding values; on the right there are some chains of alien DNA that can be formed with these genes, along with their corresponding market values.
GigaFarma can only produce very specific DNA chains, which we call
producible
. These chains are a non-empty sequence of DNA portions that the company can synthesize, joined without any additional links between them. Each
portion
is a sequence of bases and links containing at least one link, but without any consecutive, initial or final links. Each portion has a given
cost
, determined by the difficulty associated to its production, so each producible chain of DNA has a
production cost
that is the sum of the costs of each of the portions that form it. In the following example, we can see on the left a list of DNA portions and their costs; on the right we have some producible chains of DNA that can be formed with these portions, along with their associated production cost.
Note that there might be multiple ways of forming the same producible chain using different portions. This is the case of
"como-como-les"
in the example, which can be obtained using portions
"como-co"
and
"mo-les"
with a production cost of
7
, or just using
"como-como-les"
with a production cost of
12
. Of course, when there is more than one way to synthesize a given producible chain of DNA, GigaFarma will always do so using the cheapest possible process.
Clearly, the set of alien DNA chains is infinite, just like the set of producible DNA chains. However, GigaFarma is not directly interested in any of these sets, but in their intersection. If we check the previous examples, we can see that
"como-les"
is a valid alien DNA chain, but is not producible;
"mo-les"
is producible, but is not an alien DNA chain; and
"como-como-les"
is both. For each alien and producible DNA chain, the company can commercialize this chain to get a
net benefit
that equals the market value of this chain minus its production cost. Of course, if this net benefit is not positive, the corresponding chain will never be produced.
Because there is so much genetic material all over the place, GigaFarma would pay anything in order to know what is the maximum net benefit it can obtain for some producible and alien DNA chain.
Input
Each test case is described using several lines. The first line contains two integer numbers
G
and
P
, representing the number of genes in the catalogue and the number of portions GigaFarma can produce (
1 ≤ G, P ≤ 100
).
Each of the following
G
lines describes a different gene using a string
S
and an integer
V
. The string
S
has between
1
and
10
characters, and is formed solely by lowercase letters representing the bases that form this gene; the integer
V
represents the value of this gene (
1 ≤ V ≤ 1000
).
Each of the following
P
lines describe a different DNA portion, using a string
T
and an integer
C
. The string
T
has between
1
and
30
characters, and is composed of lowercase letters and hyphens only, respectively representing the bases and links in this portion.
T
contains at least one link, but will never have initial, final or consecutive links. The integer
C
represents the production cost for the corresponding portion (
1 ≤ C ≤ 1000
).
Note that in every test case, all of the genes are different from one another, and all of the portions are also different from one another. The end of the input is signalled by a line containing two times the number
-1
.
Output
For each test case, you should print a single line containing an integer number, representing the maximum net benefit that GigaFarma can obtain from a producible and alien DNA chain. If no net benefit is positive, you should print the value 0. If the net benefit can be arbitrarily large, you should print an asteris
'*'
.
Example
Input:
4 6
hola 5
como 5
les 3
va 2
como-co 3
mo-co 8
mo-les 4
como-como-les 12
ta-no-sirven 100
hasta-es 200
2 3
xyz 1000
zyxxyz 1000
xyz-zyx 1
zyx-xyz 1
xyz-xyz-zyx-xyz 1
2 1
abc 1
abcabc 1000
abc-abc 999
1 1
ser 10
no-ser 5
-1 -1
Output:
6
0
*
0 | 32,969 |
High Mountains (TAP2012H)
To go on holidays, Horacio and Hernan have sacrificed their participation in an important programming contest. While you are in this contest, they are close to the Andes driving along
Highway 40
, in Argentina, enjoying a pleasant view of the mountains in the horizon. Right now the sky over the highway is a clear, uniform blue, while the visible part of the mountains is a profile presenting rich and attractive textures. This worries Horacio and Hernan, because they fear that the pictures they are taking will be very expensive to print correctly. For this reason, in the next stop they will take out their laptops and write a program to estimate the area of the mountain profile that has to be printed in each picture. Can you finish this program before them?
Horacio and Hernan will be modeling the mountain profile in the following way. Each mountain is represented by an isosceles triangle whose base rests on the
X
axis of the
XY
plane. Two equal-length sides connect the endpoints of the base to the opposite vertex of the triangle, which is the tip of the corresponding mountain. To describe the position and shape of the triangle, we use the coordinates along the
X
axis of the base's endpoints, along with the height of the mountain.
The figure below is the model of a mountain profile formed by
4
mountains that are overlapping with one another. The area of the mountain profile that you have to calculate is marked with stripes. The lowest mountain of the figure is described by the values
I = 4
(the left endpoint of the mountain base),
D = 5
(the right endpoint of the mountain base) and
H = 1
(the height of the mountain).
In this problem, you are given the representation of the mountain profile, and you have to find the area of the union of all the corresponding triangles, in such a way that the overlapping parts are counted only once.
Input
Each test case is described using several lines. The first line contains a single integer number
N
, indicating the number of mountains (
1 ≤ N ≤ 1000
). Each of the
N
following lines describes a mountain using three integer numbers
I
,
D
and
H
, representing respectively the
X
coordinate of the left endpoint of the base, the same for the right endpoint of the base, and the height of the mountain (
1 ≤ I, D, H ≤ 10
5
with
I < D
). In each test case there are no two mountains that are exactly the same (that is, with equal values for the three parameters
I
,
D
and
H
). The end of the input is signalled by a line containing the number
-1
.
Output
For each test case, you should print a single line containing a rational number, representing the area of the corresponding mountain profile. Round the result to the closest rational with two decimal digits. In case of ties, round up. Note that you should always use exactly two digits after the decimal dot, even if this means ending with a zero.
Example
Input:
4
4 5 1
2 4 2
3 5 3
3 7 2
1
1 2 1
2
10 20 20
20 40 10
2
15 25 20
20 40 10
7
99998 99999 25000
99998 100000 50000
99996 100000 100000
1 3 100000
2 5 100000
1 5 60000
1 99999 100000
5
2 3 10
4 5 6
6 8 11
12 14 3
1 13 2
-1
Output:
6.90
0.50
200.00
190.00
5000331093.88
28.91 | 32,970 |
Johnny plays with connect 4 (LCPC12B)
"Connect Four is a two-player game in which the players first choose a color and then take turns dropping colored discs from the top into a seven-column, six-row grid. The pieces fall straight down, occupying the next available space within the column. The objective of the game is to connect four of one's own discs of the same color next to each other vertically, horizontally, or diagonally before his opponent." – Wikipedia.
Johnny plays with the connect-four board, Johnny has N discs and each disc has a number on it. Johnny drops these discs in the board columns. as Johnny was nervous he closed the top of the board and rotated it with different angles, when he rotate the board 90 degree, all pieces slide over their rows till they hit the board boundary or touch another piece. You will be given the board configuration and those rotation angles. And you should write a program that calculates the new discs’ positions.
Input Format
Input will start with
T
number of test cases. Followed by
T
test cases each test case starts with board dimensions
R
and
C
where
R
(1 <
R
< 100) is number of rows and
C
(1 <
C
< 100) is number of columns, and number of discs
N
(0 ≤
N
≤
R
×
C
). Then
N
lines follow, each contains two integers:
P
specifying the column number (0 ≤
P
<
C
) and
Q
specifying the disc number (0 ≤
Q
≤ 9). Then you will be given number of rotations
L
followed by
L
positive integers representing the rotation angles, all angles will be anti-clockwise in the main directions (90, 180, and 270) only.
Output Format
For each test case, output the result using the following format:
k
(the test case number starting at 1) followed by a period (on a line by itself), then the final configuration of the board. Each row on a line by itself, and each cell is either a "." (without quotes) if the cell is an empty or a number representing a piece.
Sample
Input
4
2 3
2
0 5
2 9
0
2 3
2
0 5
2 9
1 90
2 3
2
0 5
2 9
1 180
2 3
2
0 5
2 9
2 90 90
Output
1.
...
5.9
2.
..
.9
.5
3.
...
9.5
4.
...
.95 | 32,971 |
Johnny Listens to Music (LCPC12C)
Johnny loves to listen to music so much. Each day he decides to add, delete or listen to a music track on his laptop by doing one of the following operations:
Download a new track.
Delete the last downloaded track that is not deleted already.
Listen to the shortest track that is already on his laptop.
Each test case Johnny starts with an empty collection of tracks, at day Johnny decides which action to be taken depending on the value of
R[i]
% 3. if
R[i]
% 3 = 0 he listens to the shortest track on his laptop, if
R[i]
% 3 = 1 he deletes the last downloaded track that is not deleted already, if
R[i]
%3 = 2 he downloads a new track whose length is
R[i]
minutes. Your task is to compute the total number of minutes Johnny spends listening to music.
To keep the input small, it will be codified in the following way. You will be given an array
h
. Use the following pseudo-code on
h
to generate an array
R
.
input array:
h
output array:
R
(of size
n
)
j
:= 0
m
:= size of
h
for
i
:= 0 to
n
-1
R[i]
:=
h[j]
s
:= (
j
+1)%
m
h[j]
:= ( (
h[j]
^
h[s]
) + 13 ) % 835454957
j
:=
s
This code, along with the constraints, ensures that the length of each track is between 0 and 835454956, inclusive. In the above code, % is the modulus operator and ^ is the bitwise XOR binary operator. If x and y are integers, (x ^ y) represents the bitwise XOR operation on them in C/C++ and Java.
Input
Input will start with
T
number of test cases. Each test case will consist of 2 lines the first line starts with 0 <
n
<= 10,000,000 (size of array
R
), 0 <
m
<= 50 (size of array
h
). The second line will contain
M
numbers 0 <=
h[i]
<= 835454956 which are the elements of array
h
.
Output
For each test case, output the result using the following format:
k. S
Where
k
is the test case number (starting at 1), a single period, a single space, and
S
is the total time in minutes spent by Johnny listening to music.
Sample
Input
2
6 6
8 5 2 4 8 9
10 4
9 4 3 10
Output
1. 5
2. 52 | 32,972 |
Johnny Hates Climbing (LCPC12D)
Johnny has a map of the gang block which shows the heights of all buildings within the block. The plan is that a helicopter will drop Johnny on the roof of one of the buildings on the boundaries of the block during night. Then Johnny will get to the boss's building by moving to adjacent buildings, vertically or horizontally. Going up severely affects Johnny’s heart, so he can only go to a building which has the same or smaller height as the current building.
Given the gang building block map which shows the heights of all buildings in the block along with the boss building, write a program to help Johnny determine the safest path from any building on the boundary of the block to reach the boss’s building without going up. A path safety is measured by the maximum jump value between any two buildings along the path, where the jump value is the difference between the heights of the two buildings (the building he jumps from and the building he jumps to). The safest path is the path with minimum safety value.
Input
The first line of input contains an integer
T
, the number of test cases.
T
test cases follow, the first line of each test case contains two integers (1 ≤
R
,
C
≤ 10) the height and the width of the building block. The second line contains two integers (1 ≤
B
R
≤
R
), and (1 ≤
B
C
≤
C
), the coordinates of the boss’s building on the map.
R
lines follows; each line consists of
C
space separated integers representing the heights of all buildings. A height
H
of a building satisfies (1 ≤
H
≤ 1000).
Output
For each test case, output the result using the following format:
k
.
S
Where
k
is the test case number (starting at 1), a single period (.), a single space, and
S
(the safety value of the safest path) or "
IMPOSSIBLE
" (quotes for clarity) if there is no path to the boss's building.
Sample
Input
2
3 3
2 2
1 7 3
2 6 3
3 5 4
2 2
2 1
2 7
2 6
Output
1. 1
2. 0 | 32,973 |
Johnnys Empire (LCPC12E)
Description
Hundreds of years ago Johnny's father had a great kingdom. Before his death he divided his kingdom between his sons (Johnny and Johnny's brother). Johnny's brother took part of the kingdom with a circular shape with radius
R
. Jonny took part of kingdom of squared shape with side length
L
. As Johnny was jealous from his brother after his father's death, he decided to extend his kingdom to be a circle such that the corners of the square lies exactly on the border of the circle. A problem might occur that Johnny could steal some land from his brother, and that could wage a huge war between the two brothers. So Johnny decided to convince his brother to build a wall separating between the two kingdoms. The wall should be connecting the two intersection points between the two circles. You are to estimate the length of this wall.
Input Format
The first line of input contains an integer
T
, the number of test cases.
T
test cases follow, the first line of each test case contains 6 floating point numbers; 2 numbers denoting the center of Johnny's brother kingdom, another 2 for the center of Johnny's kingdom,
R
the radius of Johnny's brother kingdom
A
, and
L
the side length of the square of Johnny's kingdom. It’s guaranteed that both kingdoms don’t share any lands originally. Also after kingdom
B
is extended, it’s guaranteed that the intersection area will not cover Johnny's brother kingdom completely. The absolute value for all decimal numbers will be less than 10
9
.
Output Format
There should be
T
lines, containing the following format.
k. S
Where
k
is the test case number (starting at 1), a single period, a single space and
S
represent a decimal number with exactly 3 digits after the decimal point representing the wall length. If there’s no possibility of war, print “
No problem
”.
Sample Input
Sample Output
3
0.0 0.0 10.0 0 3 3
0.0 0.0 4.121 0 3 3
-1 3 1 -1 2 7.071
1. No problem
2. 2.971
3. 3.994 | 32,974 |
Johnny The Gambler (LCPC12F)
Johnny is a gambling addict. He entered a casino and started playing a game with the dealer. The game is as follows: the dealer deals a sequence of
N
cards, each card containing a number
C[i]
and asks Johnny how many pairs (
j, k
) such that
j
<
k
and
C[j]
+
C[k]
=
X
. If Johnny answers correctly he wins, otherwise the dealer wins.
Input
The first line of input contains an integer
T
, the number of test cases.
T
test cases follow, Each test case start with the value of 0 ≤
X
≤ 2*10
3
followed by the number of cards 0 <
N
≤ 10
5
followed by
N
numbers representing the numbers on the cards 0 ≤
C[i]
≤ 10
3
.
Output
There should be
T
lines, containing the following format.
k. S
Where
k
is the test case number (starting at 1), a single period, a single space and
S
representing the number of valid pairs (
j
,
k
) as described above.
Sample
Input
1
10 3 1 5 9
Output
1. 1 | 32,975 |
Johnny Studies Genetics (LCPC12G)
Description
While Johnny was studying a biology course he found a chapter about genetics and he started reading about it. Genetics is the study of genes, and studies what genes are and how they work. Genes are how living organisms inherit features from their ancestors; for example, children usually look like their parents because they have inherited their parents' genes. Genetics tries to identify which features are inherited, and explain how these features are passed from generation to generation. Genes are made from a long molecule called DNA, which is copied and inherited across generations. DNA is made of simple units that line up in a particular order within this large molecule. The order of these units carries genetic information, similar to how the order of letters on a page carries information. A chromosome is an organized structure of DNA. It is a single piece of coiled DNA containing many genes, regulatory elements and other nucleotide sequences. Chromosomes also contain DNA-bound proteins, which serve to package the DNA and control its functions.
Johnny decided to run an experiment to simulate the behavior of inheritance of a chromosome
C
that can be modeled as an array of integers each element
C[i]
of the array represents a gene of that chromosome. The value of each gene will be between 0 and 1,000,000,006. Since Johnny does not like programming he requested your help to run a simulation for a very large number of generations to check the values of the chromosome after
G
generations. On each generation
T
the value of each gene is the summation of some genes from the generation
T
-1 mod 1,000,000,007. For example if the chromosome of length 3, has values of genes 4, 7, and 12 initially and the 1
st
gene in new generation calculated as sum of 1
st
gene and 2
nd
gene in previous generation and 2
nd
gene in new generation calculated as sum of 2
nd
gene and 3
rd
gene in previous generation and 3
rd
gene in new generation calculated as sum of 3
rd
gene and 1
st
gene in previous generation. So after 1
st
generation chromosome will be 11, 19, and 16 and after 2
nd
generation chromosome will be 30, 35, and 27 and so on till generation
G
.
Input Format
Input will start with
T
number of test cases. The first line of each test case will contain two integers
G, N
where 0 <=
G
< 10
18
representing number of generations and 1 <=
N
<= 100 representing length of the chromosome. Followed by a line containing
N
integers
n[i]
separated by space where 0 <=
i
< N and 0 <=
n[i]
< 1,000,000,007 representing the value of each gene in the given chromosome. Followed by
N
lines, each line
i
start with integer
M[i]
representing the number of genes from the previous generation that is going to be added together to get the value of the new gene
i
at the new generation, followed by
M[i]
numbers
x[j]
where 0 <=
j
<
M[i]
and 0 <=
x[j]
<
N
representing the indices of genes to be added. The value of the gene at the new generation is
Output Format
For each test case, output the result using the following format:
k
.
n[0] n[1] …. n[N-1]
Where
k
is the test case number (starting at 1), a single period, a single space, and
n[i]
is the value of
i
th
gene after
G
generations.
Sample Input
Sample
Input
1
2 3
4 7 12
2 0 1
2 1 2
2 2 0
Output
1. 30 35 27 | 32,976 |
Johnny at school (LCPC12H)
After Johnny spent a long day in school, he decided to play a spot game with his friends. A Spot game is played as follows, there are
N
spots on a horizontal line one after another, each spot
i
has a radius
R[i]
. The player may start at any spot, but is only allowed to move from one spot to another if it occurs after it in the line and its radius is greater than the previous one. When he plays a move on a spot
i
he earns
P[i]
points. The player wins when he goes through the maximum number of spots if there are multiple ways, He must earn the maximum sum of points, if there are still multiple ways he must select the one that is lexicographically maximal (Let A=(a1,...,aN) and B=(b1,...,bN) be two different but equally large solution, with a1 >= a2 >= ... >= aN and b1 >= b2 >= ... >= bN. Let x be the smallest index such that ax != bx. If ax > bx, we say that the set A is lexicographically larger than the set B). As Johnny is a smart boy he wants to play optimally, so he asked you to show him which spots to move in order to win the game, Can you help him?
Input Format
Input will start with
T
number of test cases. Each test case starts with
N
where 1 <=
N
<= 1500 represent number of spots. Then follow
N
lines each contains two integers
R[i]
and
P[i]
where 1 <=
R[i]
<= 300 is the radius of
i
-th spot and 1 <=
P[i]
<= 2,000,000 is the points earned when you move on
i
-th spot.
Output Format
For each test case, output the result using the following format:
K
(start with 1) followed by a period, and a single space, then print the indices (1-based) of the spots that Johnny visits separated by a single space. If there are more than one subsequence of spots that makes Johnny wins then print the lexicographically largest.
Sample
Input
2
6
1 3
2 3
6 3
4 20
3 15
9 10
6
1 3
1 3
6 3
4 20
3 15
9 10
Output
1. 1 2 4 6
2. 2 4 6 | 32,977 |
Toward Infinity (PONY6)
Story:
Twilight Sparkle was working on some formulas when she came across a strange pattern.
When she added 1/2 + 1/4 + 1/8 + ..., she saw that it kept getting closer and closer to 1.
She was able to figure out that problem and a few more, but there are others that are too difficult. She needs your help.
Problem Statement
Given k and r, integers, find
Sum from n = 1 to infinity of n^k / r^n.
Also you must output the exact value, as a fraction in lowest terms.
Input
You will be given a number T on the first line. The following T lines will be of the form
S k r
where S is a String label with no spaces, and both k and r are as described above.
Output
Your output will contain T lines of the form
S N / D
where S is the label you were given in the input, N is the numerator of the answer, and D is the denominator. D may be 1.
To be more precise, if the fraction is negative, then output the negative sign next to N.
Example
Input:
6
Case1: 0 2
Case2: 0 3
Case3: 0 -3
Label: 2 9
Otherlabel: 12 16
Biggest: 50 -555
Output:
Case1: 1 / 1
Case2: 1 / 2
Case3: -1 / 4
Label: 45 / 256
Otherlabel: 268201436794928 / 320361328125
Biggest: -71542844799237379223056641850683038399677651990786654293842285446351016224553939010
882650681431892067495137019178862799169155069446928707568453465 /
7086055907083154841158073677533359179964732523333455695465110902606507148230087594593
20274728690683789654784801111318621847552
Note: The output for each case should all be on one line. It is split in the final case here for readability.
Bounds
T <= 10000
0 <= k <= 50
1 < |r| <= 1000
The timelimit per case is ~x5 my Java solution. | 32,978 |
Chocolate Distribution (KSELECT)
It is little John's birthday, and he has just received n boxes of chocolates as presents from his friends and family (1 < n ≤ 50). Now his mother knows that if she allows him to keep all the chocolates for himself, then he will definitely eat them all and end up with a stomach ache. So she instructs John to give one box each to each of the students in his class (excluding himself).
Now John's class has k students, excluding himself, (1 ≤ k < 50) and the ith box of chocolates contains exactly a[i] chocolates inside (1 ≤ a[i] ≤ 1000). So John obviously wants to select the k boxes such that the sum of the chocolates in the remaining (n-k) boxes is maximized, so he has more chocolates for himself.
This would be an easy task, except that John is very superstitious and wants to select these boxes in a very specific manner. He considers the number 4 and all its multiples to be extremely unlucky, and at no stage does he want the number of chocolates that he has to be a multiple of 4. Luckily, the sum of all the chocolates in all the n boxes is not a multiple of 4, and he wants to keep things that way. So, while distributing the boxes, he will only consider handing out a box, if the sum of the remaining chocolates that he has is not a multiple of 4.
John is confused as to how he should do this, so please help him out. Your task is to help John select k boxes from the n boxes
one at a time
, such that at no stage is the number of remaining chocolates a multiple of 4, and such that the final number of chocolates remaining with John is maximized (and also not a multiple of 4).
NOTE
:
At every step
, the sum of the chocolates in the remaining boxes must not be a multiple of 4. That is, after handing out the ith box, (1 ≤ i ≤ k), the sum of the chocolates in the remaining (n-i) boxes should not be a multiple of 4.
Input
In the first line we have a single integer T - the number of test cases (T ≤ 55). Then T test cases follow.
Each test case contains 2 lines. The first line contains 2 space separated numbers - n, the number of boxes (1 < n ≤ 50), and k, the number of students in John's class, excluding himself (1 ≤ k < 50)
The second line contains n space separated numbers, such that the ith number (a[i]) denotes the number of chocolates in the ith box (1 ≤ a[i] ≤ 1000).
Output
For each test case, on a single line, print the maximum possible chocolates that John can end up with after a valid distribution sequence. Print -1 if no such distribution exists.
Example
Input:
2
6 3
1 1 1 1 1 1
8 6
1 6 1 10 1 2 7 11
Output:
-1
21
Explanation
For the first case, the initial total number of chocolates is 6. After giving away any one of the boxes, the sum of chocolates remaining with John becomes 5. At this point, it becomes impossible to select any of the remaining boxes without making the sum with John a multiple of 4.
For the second test case, the maximum chocolates that can remain with John after a valid distribution sequence is 21. | 32,979 |
The One-Dimensional Pool Table (THEPOOL)
A set of N billiard balls are set on a one-dimensional table. The table is 10
5
meters long, with two pockets at either side. Each ball has zero width and there is no friction so it is moving with a fixed velocity of either left or right and bounces back in a
perfect elastic collision
from other balls it encounter on its way (or drop into one of the pockets). Your job is to keep track of the balls' movements.
Input
The first number, N, is the number of balls (≤ 10
5
).
This is followed by N pairs of numbers: the distance in meters from the left end of the table and the velocity (positive speed meaning it moves towards right).
The next line tells you which ball you have to track (1 ≤ tracked ball ≤ N).
The last line tells you the time T at which you have to locate the tracked ball.
Note: Each number is on a separate line.
Output
You have to output the position (from the left end) of the tracked ball after time T.
Example 1
Input:
1
50
1
1
6
Output:
56
Example 2
Input:
2
95
-1
10
1
1
60
Output:
35
Explanation for Example 2
2 is the number of balls.
One ball is placed at 95 from the left end. It's velocity is -1 (i.e. 1 m/s towards left).
Another ball is at distance 10. Velocity is 1 (i.e. towards right).
The first ball from left end is to be tracked. (i.e. ball at distance 10 from left end).
You need to find the new position of the tracked ball at time t=60s. | 32,980 |
BHAAD MEI JAAO (JUNL)
You are on vacation on a drunken island, but you couldn't resist the temptation of solving a good old problem. It all started when a group of kids played a game they call "The Falling Coconuts". In this game, a number of coconuts fall to the ground, one by one, on a single axis, at the locations given in drops. If a coconut X lands on the ground, it remains where it is. If it lands on top of another coconut Y, one of the following things happens:
If coconut Y is surrounded on both sides by coconuts (denoted by 'O'), coconut X remains where it is.
X
OYO
If there is no coconut directly to the right of coconut Y, coconut X slides down to the position directly to the right of coconut Y.
X
OY -> OYX
X
Y -> YX
If there is a coconut directly to the right of coconut Y, but no coconut directly to the left of coconut Y, coconut X slides down to the position directly to the left of coconut Y.
X
YO -> XYO
Each time coconut X slides down to a different position, it will continue to slide (following the behavior outlined above) until it's in a place where it will not slide any further.
The task is to display the final coconut configuration.
Input
First line is t = number of test cases.
Each test case consists of 2 lines, first line conataining the number of coconuts and second line contains n integers denoting the position of each coconut on the x-axis.
Output
As described in the problem statement.
Example
Input:
2
8
8 9 10 11 12 8 12 10
10
6 8 10 7 9 8 8 8 8 8
Output:
---O---
OOOOOOO
--O---
-OOO--
OOOOOO
Explanation of test case 1:
The configuration after each fallen coconut is given below:
X -> OX -> OOX -> 000X -> 0000X -> X00000 -> 000000X -> 0000000
In this diagram, 'X' denotes the last fallen coconut. | 32,981 |
How Many Games? (GAMES)
A player has played unknown number of games. We know the average score of the player (sum of scores in all the games / number of games). Find the minimum number of games the player should have played to achieve that average.
The player can score any non-negative integer score in a game.
Input
The first line consists of an integer t, the number of test cases. Each test case consists of a single
rational number
which represents the average score of the player.
Output
For each test case, find the minimum number of matches the player should have played to achieve that average.
Constraints
1 ≤ t ≤ 1000
1 ≤ average ≤ 1000000 (maximum 4 digits after the decimal place)
Example
Input:
3
5
5.5
30.25
Output:
1
2
4 | 32,982 |
Boggle Scoring (BOGGLE)
In Boggle, you win points for words you find on the board which no other player finds. If another player finds the same word as you, neither player gets points for that word.
For words of 4 or fewer letters, 1 point is awarded. 5-letter words are worth 2 points, 6-letter words are worth 3 points, 7-letter words are worth 5 points, and words longer than 7 letters are worth 11 points.
Given the set of words that some boggle players found, determine the score of the winner.
Input
The first line is the number of players (at most 100).
Each subsequent line is the space-separated list of no more than than 50 words each no more than 50 characters (ASCII 33-126) that player found.
Output
The score of the winning player.
Sample
Input
2
one two three
two three four
Output
1
Input
3
good dual strange stranger would
dual would duality dregs gnaw
dual gnaw draw would student
Output
17
Input
2
grid grades dread bread thread threads
grid grids grade brood broods thread threads
Output
9 | 32,983 |
DIE HARD (DIEHARD)
Problem Statement:
The game is simple. You initially have ‘H’ amount of health and ‘A’ amount of armor. At any instant you can live in any of the three places - fire, water and air. After every unit time, you have to change your place of living. For example if you are currently living at fire, you can either step into water or air.
If you step into air, your health increases by 3 and your armor increases by 2
If you step into water, your health decreases by 5 and your armor decreases by 10
If you step into fire, your health decreases by 20 and your armor increases by 5
If your health or armor becomes <=0, you will die instantly
Find the maximum time you can survive.
Input:
The first line consists of an integer t, the number of test cases. For each test case there will be two positive integers representing the initial health H and initial armor A.
Output:
For each test case find the maximum time you can survive.
Note:
You can choose any of the 3 places during your first move.
Input Constraints:
1 <= t <= 10
1 <= H, A <= 1000
Example:
Sample Input:
3
2 10
4 4
20 8
Sample Output:
1
1
5 | 32,984 |
MAXIMUM WOOD CUTTER (MAXWOODS)
The image explains it all. You initially step at 0,0 facing right. At each step you can move according to the conditions specified in the image. You cannot step into the blocked boxes (in blue). Find the maximum number of trees you can cut.
Input:
The first line consists of an integer t, the number of test cases. For each test case the first line consists of two integers m and n, the number of rows and columns. Then follows the description of the matrix M.
M[i][j] = ’T’ if the region has a tree.
M[i][j] = ’#’ if the region is blocked.
M[i][j] = ’0’ (zero) otherwise.
Output:
For each test case find the maximum trees that you can cut.
Constraints
1 ≤ t ≤ 10
1 ≤ m, n ≤ 200
Example
Input:
4
5 5
0TTTT
T#T#0
#TT#T
T00T0
T0#T0
1 1
T
3 3
T#T
TTT
T#T
1 1
#
Output:
8
1
3
0
Solution for test case #1: | 32,985 |
Another Traffic Problem (CDC12_A)
One day in a faraway city, Ronny, a famous scientist, was stuck in traffic once again. This thing happens everyday when he tries to get back home from work. But this time it was different, Ronny was working in a project that includes these situations about traffic and stuff. So in the middle of this dense traffic, Ronny started to think about a very interesting problem that includes traffic and how the cities are connected, including their avenues and intersections. The problem goes like this: There are at most N cities, connected by at most M roads. These roads are in one direction, so if you can go from city A to city B, then you can’t go from city B to city A. Following this scheme, every road will lead always forward from Ronny’s work to Ronny’s house.
In a city i there are at most Ai avenues and at most Ii intersections, these ones are not in a singular direction. If an avenue Z let you go from the intersection X to intersection Y, then the same avenue Z will let you go from Y to X. Due the horrible traffic that hits the cities everyday and the smoke derived from it, the authorities of each one of them will close a bunch of roads, allowing only one way from intersection 1 to intersection Ii. This only way will be the way with the maximum capacity, i.e., there exist no other way with a higher capacity than this. Obviously, the capacity of this way is determined by the street with the minimum capacity.
Due to the horrible traffic that hit the cities everyday, the authorities of each city close some avenues to avoid the city to overheat with the cars’ smoke. Of course, they will keep open those avenues that leads from the beginning to the end of the city, i.e., from intersection 1 to intersection Ii. Beside that, the authorities will close exactly those avenues that are strictly not necessarily to maximize the amount of vehicles that can transit in the city at a time. Fortunately, Ronny knows every little detail about the problem, even data! But not the answers. He will give you all the data of the problem, i.e., the number of cities, how are they connected, and the structure of each city, their avenues and how they connect their intersections. You may know that every road that goes from city A to city B, connects the last intersection of city A to the first intersection of city B.
Ronny need your help to figure out what's the maximum amount of vehicles that can go from Ronny’s work to Ronny’s house at a time.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
Every test case will have a line with 2 integers, N and M. Then N descriptions will follow, with a string Name (That represents the name of the city, this one will contain only lower case letters) and 2 integers Ii and Ai. Then Ai lines with 3 integers, X, Y and Cap; this mean that there is an avenue between the intersections X and Y with a capacity of Cap vehicles.
After all N descriptions, M lines will follow, with 2 strings, S and D, and one integer C. This indicates that exists a road that goes from city S to city D with capacity of C vehicles at a time. You should know that Ronny’s house and Ronny’s work are valid cities, but they’re not included on the N cities that were mentioned before. These ”special” cities are going to be called "ronnys_house" and "ronnys_work". It is sure that it will exist at least one way to get from Ronny’s work to Ronny’s house.
Output
For each input case you must print "Scenario #i: " where i is the number of the test case that you are evaluating (Starting by 1). Then you have to print a single integer that maximum amount of vehicles that can transit from Ronny’s house to Ronny’s work.
Sample
Input
2
2 4
caracas 4 4
1 2 2
1 3 2
2 3 2
2 4 1
valencia 4 5
1 2 2
1 3 3
1 4 5
2 4 1
3 4 1
ronnys_work caracas 4
ronnys_work valencia 5
caracas ronnys_house 2
valencia ronnys_house 3
4 7
caracas 4 4
1 2 2
1 3 2
2 3 2
2 4 1
valencia 4 4
1 2 2
1 3 3
1 4 5
3 4 1
maracay 3 2
1 2 2
2 3 2
maracaibo 5 6
1 3 5
1 4 2
2 3 4
2 4 4
2 5 3
4 5 4
ronnys_work caracas 4
ronnys_work maracaibo 5
ronnys_work maracay 3
caracas valencia 2
maracay valencia 3
valencia ronnys_house 4
maracaibo ronnys_house 3
Output
Scenario #1: 4
Scenario #2: 6
Constraints
1 ≤ T ≤ 10
1 ≤ N ≤ 100
1 ≤ Ii ≤ 30
1 ≤ |S|, |D|, |Name| ≤ 20
1 ≤ X, Y ≤ Ii
1 ≤ C, Cap ≤ 10,000 | 32,986 |
Basic Routines (CDC12_B)
Ronny is arriving from the work and the terrible traffic he was on. He leaves the car keys and decides to go and lay down to think about the activities he must do. He soon realizes that some activities require more energy than others. Ronny has N activities planned, and each activity has a name and a value associated, which is the amount of energy Ronny will spend by doing this activity. In addition, Ronny recovers energy each time he finishes an activity. He recovers number of energy points equal to number activities he has completed. For example, if he has 80 points of energy and doing an activity X costs Y energy, then he will have 80−Y+1 energy points. If he then performs another activity with costing Z energy, he will have (80−Y +1)−Z+2 energy points. Ronny’s energy must never be lower than 0 points.
He realized that he may not be able to complete all the activities. You are required to write a program to help him choose an subset of activities that can be finished with the given amount energy. See output description for more details.
Input
The first line contains an integer T , number of test cases. Then, descriptions of T test cases. Each test case will begin with two integers N and E, denoting respectively the number of activities that Ronny has planned and Ronny’s initial energy. N lines will follow, each with a string A and an integer V , denoting the name of the activity and the value associated with it.
The data must be read from standard input.
Output
For each input case you must print two lines line. First must start with string "Scenario #i:", where i is the test case number (starting by 1). Next a space and the maximum number of activities Ronny can do. Second line must contain a list of activities sorted by name (order of execution may be different). There must be an space after each name.
If there are many possible solutions, output the subset that requires the least amount of energy. If there is still a tie, output the lexicographical smaller sequence of names.
The output must be written to standard output.
Input
Output
2
5 80
CleanClothes 45
MakeFood 40
Shower 10
EatFood 20
WatchTv 5
4 80
Gaming 20
TVShow 30
ScoreSomeCoke 20
DrinkCoke 10
Scenario #1: 4
EatFood MakeFood Shower WatchTv
Scenario #2: 4
DrinkCoke Gaming ScoreSomeCoke TVShow
Constraints
T ≤ 100
1 ≤ N ≤ 100,000
1 ≤ E ≤ 1,000,000
1 ≤ |A| ≤ 100
1 ≤ V ≤ 100
First case analysis:
Ronny can choose activities {1, 3, 4, 5} or {2, 3, 4, 5}. Doing the second set of activities costs him less energy, so that's the final answer.
News: Inserted all test cases from the original contest. Statement updated. | 32,987 |
Collision Issue (CDC12_C)
When Ronny finished his routines, received a call from the Center of Extraordinary Investigations Defining Excluded Creatures (or CEIDEC by its acronym).
CEIDEC found a planet going through the orbit of the Earth at a great velocity, the planet was named Rainbowland by its fancy colors. We don’t know if this planet contains living creatures, what CEIDEC knows is that the collision is almost imminent. However, that’s why the CEIDEC calls you: to create a program that, given three points in the space and assuming that the space only has two dimensions, compute if the three given points makes a perfect triangle, an isosceles triangle or an scalene triangle.
In addition, CEIDEC would like to know the angle formed by these three points. Computing this would make the calculations for collision easier to perform. Obviously, CEIDEC will give you a useful formula to discover the angle ? on the triangle knowing the length of sides A, B and C. You must manipulate the following formula in order to get the angle formed by these three points:
sqrt( (A
2
) + (B
2
) - [ {8 * A
3
* B
3
}^(1/3) * sin
3
(ø) * cot
3
(ø) * sec
2
(ø) ] ) = c
That formula will find the angle between the vertex a and b. You must find if a triangle is equilateral, isosceles or scalene and, in addition, you must find the name of the interior angular triangle, knowing that.
The sum of all interior angles must be equal to 180°
A triangle will be equiangular if all the angles are the same.
A triangle will be right triangle if one and only one angle is equal to 90°
A triangle will be obtuse if one angle is greater than 90°
A triangle will be acute if all the angles are less than 90°
Two floating points numbers will be considered equal if their absolute difference is lower than 10
-2
when rounded, for instance 3.14159265 is rounded to 3.14.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
Each case will contain 3 lines, each of these three lines will contain two numbers, denoting the coordinates (x, y) of every vertex in the triangle. The input must be read from standard input.
Output
For each input case you must print the string "Scenario #i:" where i is the test case you are analyzing (starting at 1) followed by the name by side of the triangle and (only for large cases) the name by interior angle of the triangle separated by a single space. The output must be written to standard output.
Sample
Input
4
0 0
0 3
3 0
0 0
0 4
3.464 2
1 1
5 5
4 0
1252 1322
1904 1950
1700 1700
Output
Scenario #1: Isosceles Right Triangle
Scenario #2: Equilateral Equiangular
Scenario #3: Scalene Acute
Scenario #4: Scalene Obtuse
Constraints
1 ≤ T ≤ 100
-1,000,000 ≤ X ≤ 1,000,000
-1,000,000 ≤ Y ≤ 1,000,000 | 32,988 |
Drastic Race (CDC12_D)
Rainbowland and planet Earth made a giant and a fancy collision! Now Ronny ran out of the CEIDEC worried and running to search his family, however, when he was running to his car, a
Rainbowlandian explode the car, teddy bears flew out of it and Ronny was the first to discover officially that we’re not alone on this universe.
Angry about his car explosion, Ronny shouted to the Rainbowlandian all sort of swearings, then, in the blink of an eye, several Rainbowlandians appeared with some strange vehicles describing circles around Ronny and challenging him to do a race to some point of the empty highway. What the Rainbowlandians don’t know is that Ronny got some special compound that gives him super reflexes and he can, with that, overtake the Rainbowlandians by increasing his speed to the limit. However, this compound is very limited so Ronny must to use it wisely. He wants to reach his destination as soon as possible and faster than any other Rainbowlandian chasing him, otherwise, the Rainbowlandian will blow him up as they did with the car.
Can you help him to determine whether he can win the race?
You should take the following aspects into account:
Ronny can use the compound if and only if he is able to.
Ronny can restore the compound if and only if he stays still without moving.
Ronny can only win if his time is less than the fastest Rainbowland, so, in case of tie, Ronny lose.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
Each case will have 6 integers P, M, V, S, K, D, which denote, respectively, the time that will take to the fastest Rainbowlandian to get to the finish line, the meters up to the finish line, the normal velocity of Ronny, the boost that Ronny acquires when using the compound, the time that he can use the ability and the amount of compound he restores by second. (Have in account that he will not restore the compound more than what is given at the beginning.)
Output
For each case you must print the string "Scenario #i: " where i is the test case you’re analyzing (starting at 1) followed by the string "Ronny wins in time R" if and only if Ronny is able to win the race, R is the units of time that Ronny takes to win the race, otherwise print "Ronny will be annihilated". (Quotes for clarity.)
Sample
Input
2
10 500 40 40 5 1
7 1000 40 40 5 1
Output
Scenario #1: Ronny wins in time 8
Scenario #2: Ronny will be annihilated
Constraints
1 ≤ T ≤ 20
1 ≤ P ≤ 10,000
1 ≤ M ≤ 10,000
1 ≤ V ≤ M
1 ≤ S ≤ M
1 ≤ K ≤ 100
1 ≤ D ≤ K | 32,989 |
External Falling Objects (CDC12_E)
After Ronny finished the race challenge, he decided to go home. When he arrives, he notice
that his family is not there, instead, there is a note that says: ”We are at the basement”.
Ronny read this and decided to go to the basement. This one is located at some point of the
backyard, but due to the collision and fusion of the planets, there are objects of the external
planet falling from the sky, therefore, streets and gardens are full of these objects.
These objects have different sizes and shapes, but always with the colors of the rainbow. Beside
this, Ronny’s family will close the basement door after K minutes, to avoid a possible invasion
of the new life forms that are arriving to the Earth. Ronny need to get to the basement before
these K minutes. You must know that every object has a number, this number represents the
time that Ronny will take to avoid it. Ronny can move to any of the adjacent position but
never diagonal. Every step that Ronny make will take 1 second.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
For each test case, there will be a line with 3 integers, H, W and K. H and W are the dimensions of the garden, and K is the time in seconds that Ronny’s family will wait until they lock the door. Then H lines will follow, with W characters each; you may know that:
The character ’.’ denotes a free space on the garden.
One digit character denotes an object. An object with the number X on it represents that Ronny will take X seconds to avoid it.
The character ’R’ indicates the initial position of Ronny in the garden.
The character ’D’ indicates the door of the basement where is located Ronny’s family.
Output
For each input case you must print a line with "Scenario #i: " where i is the number of the test case that you are evaluating (starting at 1), followed by the minimum time that Ronny will take to reach his family. If it’s impossible to Ronny to reach his family in less than K units of time, then you should print "Ronny will be destroyed". (Quotes for clarity)
Sample
Input:
2
2 2 2
R9
1D
3 3 10
R..
42.
D1.
Output:
Scenario #1: Ronny will be destroyed
Scenario #2: 6
Constraints
1 ≤ T ≤ 100
1 ≤ H ≤ 1,000
1 ≤ W ≤ 1,000
1 ≤ K ≤ 8,000,000 | 32,990 |
Forbidden Machine (CDC12_F)
Finally Ronny could make it to the safe place, he left his family there and decided to go to this new planet and talk to their King. Ronny know that he can’t do this by himself, so he called every army of the Earth to have a backup in case that things turn out bad.
They made it to the new planet, and realize that it was like only rainbows and teddy bears, and just at the entrance there was a sign that said: ”Welcome to Rainbowland”. Ronny and his army went through this planet directly to their castle. At the entrance, a guard wearing a hat colored with rainbow colors, stopped Ronny. He said that Ronny could pass if and only if he could solve a puzzle: The Forbidden Machine Puzzle.
This puzzle consists on a machine that takes strings, and then says if the strings are correct. A string is considered correct if it follows the rules of the machine. This rules consists on a sequence of state transitions. Each transition tells the machine that if it was in a state X, it can go to a state Y with a character Z on the string. The machine starts reading from the first position of the string, and each transition move the string one position to the left, so the next position to read it’s the second one. It is important to add that the machine always start on an initial state and a string follows the rules of the machine if and only if this can made it to a final state of the machine, and the string has been read completely. Ronny has a hard time understanding this machine, so he would like you to simulate it, in order to have the correct answer for the guard.
Please note that a single state-character combination can lead to several different states.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
Each test case will contain a line with 4 integers, N, M, F and Q. N is the number of states of the machine, M is the number of transitions, F is the number of final states of the machine, and Q it’s the initial state. Then F lines will follow with a single integer E on it, representing that the state E it’s a final state. Then M lines will follow, with 2 integers I and J and a character C; this represents that there exists a transition that goes from state I to state J reading the character C. Then will be a line with an integer S, that indicate the number of strings to process, and S lines will follow, each one with a string A that has to be evaluated by Ronny.
Output
For each input case you must "Scenario #i:" where i is the number of the test case that you are evaluating (Starting by 1). Then S lines, with the string and the answer of the machine for that string, if the string is correct, you should output "Accepted", and if it’s not, you should output "Rejected" (Quotes for clarity).
Sample
Input
2
4 8 1 0
0
0 1 a
1 0 a
1 2 b
2 1 b
0 3 b
3 0 b
3 2 a
2 3 a
3
ababbaa
abababab
aaaabbbb
6 8 2 0
2
5
0 0 a
0 1 a
1 1 b
1 2 c
1 3 c
3 4 d
4 4 d
4 5 d
5
aaabcccc
aabbbbcdc
abbcdddcc
acdddddd
abc
Output
Scenario #1:
ababbaa Rejected
abababab Accepted
aaaabbbb Accepted
Scenario #2:
aaabcccc Rejected
aabbbbcdc Rejected
abbcdddcc Rejected
acdddddd Accepted
abc Accepted
Constraints
1 ≤ T ≤ 100
1 ≤ N ≤ 100
1 ≤ F, Q, I, J, E ≤ N
1 ≤ S ≤ 100
1 ≤ |A| ≤ 1000 | 32,991 |
Glory War (CDC12_G)
Ronny is hiding on the building where he left his family after failing the guard test (the guard
told him not to cheat and got angry after your help). The Rainbowlandians are brutally attacking
the citizens of planet Earth, there are corpses everywhere and desperate people running
on the street. Ronny must protect his family and that’s why he has decided to take down all
the Rainbowlandians inside the building as soon as possible.
Ronny know very little about the Rainbowlandians, but he knows that he must be silent when
he takes down one of then, hence, he hides his noisy gun in his pocket, impeding him to attack
them from the distance. In order to take down the Rainbowlandians, a knife or a good flying
kick will do the job. Ronny must step on the same space a Rainbowlandian is to take him
down. The building is full of rubble and some paths will lead to a trap. Fortunately, Ronnie
can throw a rope and go up or down through floors while he is walking the building. Obviously,
he cannot throw the rope if this will lead him to a rubble-full step.
Given the dimensions of the building, its width, height and depth and the marked targets,
you’re to make a program to help Ronny take down the Rainbowlandians in the minimum
steps possible so he can do the minimum noise possible.
Please note that:
Ronny starts at the north west corner of the first floor of the building (1,1,1)
Ronny can only move to these possible directions: east, west, north, south, in addition, he can go while moving up or down.
Ronny cannot leave the building at any moment and there’s no basement in the building neither, so he can’t be lower than height 1.
Input
The first line contains an integer T, which specifies the number of test cases. Then, will follow the descriptions of T test cases.
Each test case will start with two integers N and H, where N denotes the width and depth of each floor and H denotes the number of floors. Then, there will be H N×N matrices, each one describing one floor. The floor description is composed of the following characters:
The character ’#’ denotes a rubble space.
The character ’.’ denotes a free space.
The character ’*’ denotes a Rainbowlandian.
Output
For each input case you must print the string "Scenario #i: " where i is the test case you’re evaluating (starting at 1), followed by the minimum steps that Ronny have to make to take down all the enemies inside the building. If this is impossible, print -1.
Sample
Input
3
2 1
..
.*
3 2
.#.
.##
##.
#.#
###
.#*
4 3
....
.##.
####
****
####
####
....
#.##
####
*..*
*..*
####
Output
Scenario #1: 2
Scenario #2: -1
Scenario #3: 13
Constraints
1 ≤ T ≤ 30
1 ≤ N ≤ 20
1 ≤ H ≤ 20
1 ≤ Targets ≤ 10 | 32,992 |
Halt The War (CDC12_H)
The war was terrible, thousands of humans and rainbow people lying down on the streets.
Ronny didn’t know what to do, so he decided to go and search for the Rainbowland Castle
and talk to the King. The rainbowlandians stared at Ronny with caution, waiting him to do
something bad just to get him and rainbow-kill him. Finally, Ronny made it to the King’s room
and talked to him about stopping this horrible war. The King accepted Ronny’s proposal, but
only with one condition, Ronny needed to prove once again what human beings were capable
of. The King said that if Ronny answered the Q queries that he had for him about an order
line of rainbow people numbered from 1 to N , he and his nation would go away. These rainbow
people had a letter with a number on it (Initially this number it’s 0).
There are two types of queries, modification queries and answer queries. The modification
queries consists on, given an interval from A to B inclusive ([A,B]), Ronny needed to update
those rainbow people’s letter, adding one to the number on it; so, by instance, if the interval is
[1,2], then Ronny needed to add one to the first and second rainbowlandian on the line. The
answer queries consists on, given an interval from A to B inclusive, Ronny should say the sum
of every rainbow people’s letter.
If Ronny can do this, the humans are saved! So he need your help, because he is not really that
good in maths and fast sums.
Input
The first line contains an integer T, which specifies the number of test cases. Then will follow
the descriptions of T test cases.
For each test case you will get an integer N and an integer Q, that represents the number of
rainbowlandian in the line and the number of queries the King asks for. Then, Q lines will
follow, each containing a string and 2 integers, the type of query, that can be "modification"
or "answer" (Quotes for clarity), the first and the last rainbowlandian that Ronny must have<
in mind in order to answer the query.
Output
For each input case you must print the string "Scenario #i:" where i is the number of the
test case (Starting by 1), followed by Q lines with the answer of each query. If the query was
a modification query, then you should output "OK" (Quotes for clarity), otherwise, output the
sum of the number from A to B inclusive.
Sample
Input:
2
4 4
answer 1 4
modification 1 2
modification 2 3
answer 2 2
8 6
modification 2 4
modification 4 8
modification 4 5
answer 8 8
modification 5 7
answer 4 8
Output:
Scenario #1:
0
OK
OK
2
Scenario #2:
OK
OK
OK
1
OK
11
Constraints
1 ≤ T ≤ 100
1 ≤ N ≤ 100,000
1 ≤ Q ≤ 100,000 | 32,993 |
Search Insert Delete (SID)
You are given a bunch of data (all are positive 32 bit numbers) to operate on. The only operations on the data are search, insert, and delete. When storing the data you have to remember its rank, that is the original position when the data is being inserted. All successful operations must return the ranks of the data. Failed operations should return NONE as the answer.
Your objective is to execute all of the operations as fast as possible.
Input
The first line of input is N and M, separated by a space, N is the number of initial data. (0 <= N < 1000000) and M is the number of operations against the data. (0 <= M < 1000000).
The second line contains N data, separated by blanks. All data are positive 32 bits numbers
The next M lines contains operations against the data. Each line contains a symbol and a number, separated by a space.
There are 3 symbols (
S
,
I
,
D
), each representing search, insert, and delete operation.
'S number' tries to find the number in the stored data, and outputs its first rank in the stored data (as originally inserted), or NONE if no such number exists.
'I number' inserts the number into the stored data, and outputs its rank in the stored data. (Data can be duplicated).
'D number' deletes the least ranked number found in the stored data, and outputs its rank, or NONE if no such number originally exists.
Output
There is an output for each executed operation. See the above input description about each operation for the detail of the output.
Example
Input:
10 6
20 12 10 28 20 50 49 8 51 1
S 20
I 3
S 11
D 20
I 2
S 20
Output:
1
11
NONE
1
12
5 | 32,994 |
Blade Master (BMASTER)
Loda and Maelk are legendary ChefCraft players. They have played so many games that this number doesn't fit in a standard 32-bit integer type. Today Loda and Maelk are going to sort the things out and find out who is the greatest ChefCraft player ever. So the great fight is coming. There are a lot of different heroes you may choose to play ChefCraft. Obviously every hero has his pros and cons. Loda perfectly plays Blade Master. His main skill is to make mirror images of himself to spoof the enemy.
As every other popular game ChefCraft is played on a rectangular grid which consists of
N
rows and
M
columns. Rows of the grid are numbered by integers from
1
to
N
. So the upper row of the grid has number
1
and the lower row has number
N
. The same holds for columns. They are numbered by integers from
1
to
M
such that the most left column has number
1
while the most right column has number
M
.
At the beginning of the game the only Blade Master's image stands on some starting cell
(Sx, Sy)
where
1 ≤ Sx ≤ N
and
1 ≤ Sy ≤ M
. Then Loda makes
T
moves. Maelk knows how the distribution of images on the grid changes after each Loda's move. This happens according to the following rules.
1.
If there is an image standing on the cell
(i, j)
then the new images appear by the next rules:
Let
F(i, j)
be the total number of images in the "cross" of the cell
(i, j)
. The "cross" of the cell
(i, j)
is union of all cells in the
i
-th row of the grid and in the
j
-th column of the grid. So
N + M − 1
cells belongs to the "cross".
Let
X = F(i, j) mod 6
, that is
X
is the remainder of the division of
F(i, j)
by
6
.
For every possible value of
X
we have following values:
D1
,
D2
,
P1
and
P2
.
D1
and
D2
may be equal to one of the
4
values
['U', 'R', 'D', 'L']
and mean some two directions. Here
'U'
means
up
,
'R'
means
right
,
'D'
means
down
and
'L'
means
left
.
P1
and
P2
are integer numbers.
New mirror images will appear at every cell in the direction
D1
with the period
P1
starting from cell
(i, j)
and in the direction
D2
with the period
P2
also starting from the cell
(i, j)
. Of course, no images will appear out of the grid. For example, if
D1 = 'U'
and
P1 = 2
then images appear at the cells
(i − 2, j), (i − 4, j), (i − 6, j)
, and so on.
Loda always use the same values for
D1
and
D2
. Namely,
D1 = 'U', D2 = 'D'
for
X = 0,
D1 = 'L', D2 = 'R'
for
X = 1,
D1 = 'U', D2 = 'R'
for
X = 2,
D1 = 'R', D2 = 'D'
for
X = 3,
D1 = 'D', D2 = 'L'
for
X = 4,
D1 = 'L', D2 = 'U'
for
X = 5.
But values
P1
and
P2
may vary for different games. But once chosen they will be the same for all moves.
2.
Appearing of new mirror images happens immediately.
3.
Whenever there is more than one image at the cell they start one on one fights. In each fight two images participate and both die. So if the number of images in the cell was even than all images will disappear in the end, otherwise exactly one image will remain at this cell.
Now Maelk wants to choose his hero in order to win the fight. The most important thing he needs to know for this is how the number of images changes during Loda's moves. So he asks you for help. Denote by
C(t)
the number of images on the grid after the
t
-th Loda's move for
t
from
1
to
T
. For convenience we denote
C(0) = 1
with meaning that
0
-th move is the putting of the only Blade Master's image at the starting cell. Maelk wants you to calculate the sum
C(0) + C(1) + ... + C(T)
. Since Maelk doesn't know what to expect from Loda he would like to know the answer for several values of
T
. As you remember the total number of games played by Maelk and Loda at ChefCraft doesn't fit in a standard 32-bit integer type. Of course, the same can hold for the number of moves in their final fight. Since Maelk plays ChefCraft the whole life he is not strong in math and can't calculate such large sums. So let's help him to win the final fight and become the only ChefCraft master ever.
Input
The first line of the input contains three space separated integers
N
,
M
and
Q
. Here
N
and
M
are sizes of the grid described above and
Q
is the number of Maelk's queries. The second line contains two space separated integers
Sx
and
Sy
, row index and column index of the starting position of the first image. Each of the following six lines contains two space separated integers, the values
P1
and
P2
for the corresponding
X
, that is,
i
-th line among these six lines contains values
P1
and
P2
for
X = i − 1
. Each of the following
Q
lines contains a single integer
T
, the number of Loda's moves for the corresponding Maelk's query.
Output
For every Maelk's query output on a separate line the numbers of images Maelk will see during Loda's move.
Constrains
N
and
M
are positive
N
•
M
≤
34
1
≤
Sx
≤
N
1
≤
Sy
≤
M
1
≤
P1
,
P2
≤
max{N, M}
1
≤
Q
≤
100
1
≤
T
≤
10
16
Example
Input:
3 3 3
1 1
1 1
1 1
1 1
1 1
1 1
1 1
1
2
3
Output:
4
12
17
Explanation
The initial grid looks as follows:
100
000
000
Here '1' represents a cell with an image and '0' represents a free cell.
After the first move grid is
111
000
000
After the second move grid is
101
111
111
Finally, after the third move we have
011
101
010
So after the first move Maelk will see
3
images, after the second move –
8
images and after the third move –
5
images. Hence the answers for
T = 1, 2, 3
are
1 + 3 = 4
,
1 + 3 + 8 = 12
and
1 + 3 + 8 + 5 = 17
respectively. | 32,995 |
Different Vectors (DIFFV)
You are given set of
N
vectors, each vector consists of
K
integers. Vector ex equals ey
iff
there exists function bijection
f
and integer
r
, such that ex[i] = f( ey[(i+r)%K] ), for each i in range [0, K> Eg. (1, 2, 2, 3) == (22, 3, 4, 22), with r=2 and f(22)=2, f(3)=3 and f(4)=1. But (22,3,22,4) is not equal to (1, 2, 2, 3).
How many different vectors are there in set of N given vectors?
Constraints:
n <= 10000
k <= 100
vector values are from range [0, 10^9]
Input
First number contains T (T <= 10), number of test cases. Each test cases consists of following. First line consists of N and K. N lines follows, the i-th containing K integers describing i-th vector.
Output
Output one number, number of different vectors.
Input:
2
3 4
22 3 4 22
1 2 2 3
22 3 22 4
5 5
3 3 3 0 3
8 4 4 4 0
1 1 1 1 1
1 1 8 6 1
1 3 3 3 5
Output:
2
3 | 32,996 |
Path of the righteous man (RIOI_2_3)
You are given N×N matrix A filled with integers, which represents map of country "What" ("What" ain't no country I ever heard of). Our hero is called Brett. Brett has many enemies, namely Jules and Vincent (Jules doesn't like him because he said "what" too many times), but his biggest enemy is Marcellus Wallace, because Brett treated him like a male dog treats female dog. And Marcellus most certainly does not look like a female dog.
But Brett cannot sit at home all day enjoying his Big Kahuna burgers, he has to go from cell (sx, sy) to cell (ex, ey).
From cell (x, y) Brett can go to (x+1, y), (x, y+1), (x-1, y), (x, y-1).
If A[x][y] = S, we say that this cell is property of mafia boss S. When Brett visits cell (x, y), and has not yet apologised to boss A[x][y], then he apologises, after that he can visit any cell controlled by A[x][y] without apologising. Brett does not like to apologise (because there is always chance to hear Ezekiel 25:17), so he asks you to find him path which minimises number of times he has to apologise.
Constraints
N ≤ 50
0 ≤ A[i][j] < 10
Input
First line contains number t donating number of testcases. First line of each testcase consists of number N. N lines follows containing N numbers donating matrix A. After that two lines follow, containing sx, sy and ex, ey.
Output
For each test output number minimal number of times Brett has to apologise.
Example
Input:
3
5
0 1 0 2 3
0 2 0 3 1
0 5 0 0 0
0 5 7 8 0
0 0 0 0 0
0 0
0 4
5
0 1 0 2 3
0 2 0 3 1
0 5 0 0 0
0 5 7 8 0
0 0 0 0 0
0 0
0 2
5
0 1 0 8 3
0 2 0 3 1
0 5 0 0 0
0 5 7 8 9
0 0 0 0 0
0 0
0 3
Output:
3
1
2
Explanation
For the second test case, Brett can reach cell (0, 2) following path on which each cell is controlled by boss 0.
NOTE: If you wish to understand references in problem statement, watch the movie Pulp Fiction, or this clip
www.youtube.com/watch?v=aBs3Mu-qous | 32,997 |
Finding Fishes (FISHES)
Marlin engaged Dory, last April and they decided to marry in next November. Unfortunately, Dory is not like normal girls who their dowry is money, rings or furniture! She has many pictures of fishes and she wants a program that draws boxes around the fishes in the images. Time is passing and Marlin’s program just process the image and output some data that could be used to find the correct locations of these boxes. Please help him to save his marriage dream.
Marlin outputs for every image:
2 integers H and K.
A 2D matrix M of integer values from 1 to K.
T integer vectors V
i
, each of length K. Each vector is coupled with an integer value X
i
.
A Score Evaluator function is used to calculate the score of any box in the image, such that the higher box score, the more confidence in the box to tightly contain a fish. Hence, Marlin targets the box with the highest score that contains a fish.
Given 4 corners of box B, the function works as following:
Construct vector V that has the frequencies of the values in M corresponding to B.
Calculate the score as: Score = H + $\sum_{1}^{T}[X_i * (V.V_i)]$, where (a.b) means the dot product.
Input
The first line of input contains an integer S that represents the number of test cases, then S test cases follow. Each test case start with a line of 5 numbers R C H K T, where R and C are number of rows and columns for the matrix. K, T and H are as described in the problem. R lines follow each with C numbers corresponding to the matrix. Then T lines for the vectors follow each line starts with X of that vector, then K numbers of the vector.
1 ≤ R, C, H ≤ 100, 1 ≤ K ≤ 500, 0 ≤ T ≤ 500, 0 ≤ G ≤ 100 and -5 ≤ X ≤ 5. G is the range of values for vectors V
i
.
Output
For each test case, output on a single line “Case #K:” where K is the number of the test case, followed by a single integer which is the score of the box with highest to have a fish.
Example
Input:
1
3 4 7 3 2
1 1 2 2
1 2 2 3
2 3 1 3
-3 1 1 2
4 7 2 10
Output:
Case #1:
234
Explanation
Let's evaluate the first 2×2 box which is:
1 1
1 2
1 occurred 3 times, 2 occurred 1 time and 3 occurred 0 times. Then the frequencies vector is [3 1 0] and its function evaluation is:
7 + (- 3 * ([3 1 0]. [1 1 2]) + 4 * ([3 1 0].[7 2 10]) ) = 7 + (-12 + 92) = 87 | 32,998 |
Co-Prime (LCPC11B)
Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.
Input
The first line on input contains T (0 < T ≤ 100) the number of test cases, each of the next T lines contains three integers A, B, N where (1 ≤ A ≤ B ≤ 10
15
) and (1 ≤ N ≤ 10
9
).
Output
For each test case, print the number of integers between A and B inclusive which are relatively prime to N. Follow the output format below.
Sample
Input:
2
1 10 2
3 15 5
Output:
Case #1: 5
Case #2: 10
In the first test case, the five integers in range [1, 10] which are relatively prime to 2 are {1, 3, 5, 7, 9}. | 32,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.