task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Catch Sheep (XYYHHTT) XiYangYang is a kind of lovely and rare sheep. They live in a peaceful land which can be described as a tree with N cities (nodes). Now you have K robots. They will start at a same point and travel each edge at least once so that all XiYangYang will be caught. All your robots can stop at any city in the land. Because of expensive oil, you want minimize the total distance that your robots walk. Input First line : N K (N ≤ 15000, K ≤ 30) Next N-1 lines: a b c (city a and city b are connected with a road whose length is c (1 ≤ a, b ≤ N, 0 ≤ c ≤ 100) Output N lines: The total distance that your robots walk if they all start at city i. Example Input: 5 3 1 2 7 2 3 5 3 4 14 3 5 8 Output: 42 39 34 42 42 Hint: my solution can get AC in 0.75~1 second.
32,000
Tree game (CT23E) Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree. Input The first input line contains integer number n (1 ≤ n ≤ 700) — number of vertices in the tree. The following n - 1 lines contain the description of the edges. Each line contains the pair of vertices' indexes, joined by an edge, a i , b i (1 ≤ a i , b i ≤ n ). It's guaranteed that the graph described in the input is a tree. Output Output the only number — the maximum product of sizes of the connected components, that Bob can get after deleting some of the tree's edges. Example Input: 8 1 2 1 3 2 4 2 5 3 6 3 7 6 8 Output: 18
32,001
PIN (CTOI10D2) Martin has just been hired as a computer administrator in a big company. The company did not change its authorization system since 1980s. Every person has a four-digit personal identification number (PIN). Nobody uses usernames or passwords, you can login just by typing your PIN. As the company grew, they added the possibility to use letters as well, but the length of the PIN remained the same. Martin is not happy with the situation. Suppose there are people whose PINs differ only at a single place, for example 61ab and 62ab . If the first person accidentally presses 2 instead of 1, the system would still let him in. Martin would like to make the statistics about the PINs currently in use, in particular, compute the number of pairs of PINs that differ at 1, 2, 3 or 4 positions. He hopes that these numbers will be alarming enough to convince his boss to invest in a better system. Task specification Given the list of PINs and an integer D , find the number of pairs of PINs that differ at exactly D positions. Input The first line of the input contains two space-separated positive integers N and D , where N is the number of PINs and D is the chosen number of differences. Each of the following N lines contains a single PIN. Constraints You may assume that in all test cases 2 ≤ N ≤ 50000 and 1 ≤ D ≤ 4. Each PIN is of length 4 and each character is either a digit or a lowercase letter between ' a ' and ' z ', inclusive. You may assume that all PINs in the input are different. In test cases worth 15 points, N ≤ 2000. In test cases worth 60 points, D ≤ 2. Out of those, in test cases worth 30 points, D = 1. In test cases worth 75 points, every PIN will only consist of digits or lowercase letters between ' a ' and ' f ', inclusive. Thus it can be viewed as a hexadecimal number. Output Output a single line with a single number: the number of pairs of PINs that differ at exactly D positions. Examples Input: 4 1 0000 a010 0202 a0e2 Output: 0 For these PINs each pair of PINs differs at more than one position. Input: 4 2 0000 a010 0202 a0e2 Output: 3 There are three pairs that differ at exactly 2 positions: (0000, a010), (0000, 0202), and (a010, a0e2).
32,002
A HUGE TOWER (CTOI10D3) The ancient Babylonians decided to build a huge tower. The tower consists of N cubic building blocks that are stacked one onto another. The Babylonians gathered many building blocks of various sizes from all over the country. From their last unsuccessful attempt they have learned that if they put a large block directly onto a much smaller block, the tower will fall. Task specification Each two building blocks are different, even if they have the same size. For each building block you are given its side length. You are also given an integer D with the following meaning: you are not allowed to put block A directly onto block B if the side length of A is strictly larger than D plus the side length of B. Compute the number of different ways in which it is possible to build the tower using all the building blocks. Since this number can be very large, output the result modulo 10 9 + 9. Input specification The first line of the input contains two positive integers N and D : the number of building blocks and the tolerance respectively. The second line contains N space-separated integers; each represents the size of one building block. Constraints All numbers in the input files are positive integers not exceeding 10 9 . N is always at least 2. In test cases worth 70 points N will be at most 70. Out of those, in test cases worth 45 points, N will be at most 20. Out of those, in test cases worth 10 points, N will be at most 10. For some of the test cases the total number of valid towers will not exceed 1,000,000. These test cases are worth 30 points in total. For the last six test cases (worth 30 points) the value of N is larger than 70. No upper bound on N is given for these test cases. Output specification Output a single line containing a single integer: the number of towers that can be built, modulo 1,000,000,009. Examples input: 4 1 1 2 3 100 output: 4 We can arrange the first three blocks in any order, except for 2, 1, 3 or 1, 3, 2. The last block has to be at the bottom. input: 6 9 10 20 20 10 10 20 output: 36 We are not allowed to put a cube of size 20 onto a cube of size 10. There are six ways to order the cubes of size 10, and six ways to order the cubes of size 20.
32,003
MP3 Player (CTOI10D1) Georg's new MP3 player has many interesting features, one of them being the key lock. All the keys are locked after more than T seconds of inactivity. After the key lock is engaged, no key performs its original function, but if any key is pressed, the key lock is disengaged. For example, assume that T = 5 and the player is currently locked. Georg presses the key A , waits for 3 seconds, presses the key B , waits for 5 seconds, presses C , waits for 6 seconds, and presses D . In this case only the keys B and C perform their regular functions. Note that the keys became locked between C and D was pressed. Sound level of the MP3 player is controlled by the + and - keys, increasing and decreasing volume by 1 unit respectively. The sound level is an integer between 0 and V m a x . Pressing the + key at volume V m a x or pressing the - key at volume 0 leaves the volume unchanged. Task specification Georg does not know the value of T . He wanted to find it by an experiment. Starting with a locked keyboard, he pressed a sequence of N + and - keys. At the end of the experiment Georg read the final volume from the player's display. Unfortunately, he forgot to note the volume before his first keypress. For the purpose of this task, the unknown initial volume will be denoted V 1 and the known final volume will be denoted V 2 . You are given the value V 2 and a list of keystrokes in the order in which Georg made them. For each key, you are given the type of the key ( + or - ) and the number of seconds from the beginning of the experiment to the moment when the key was pressed. The task is to find the largest possible integer value of T which is consistent with the outcome of the experiment. Input The first line of the input contains three space-separated integers N , V m a x and V 2 (0 ≤ V 2 ≤ V max ). Each of the next N lines contains a description of one key in the sequence: a character + or - , a space and an integer C i (0 ≤ C i ≤ 2 x 10 9 ), the number of seconds from the beginning of the experiment. You may assume that the keypresses are in sorted order and that all times are distinct (i.e., C i < C i + 1 for all 1 ≤ i < N). Output If T can be arbitrarily large, output a single line containing the word " infinity " (quotes for clarity). Otherwise, output a single line containing two integers T and V 1 separated by a single space. The values must be such that carrying out the experiment with locking time T starting at volume V 1 gives the final volume V 2 . If there are multiple possible answers, output the one with the largest T ; if there are still multiple possible answers, output the one with the largest V 1 . (Note that at least one solution always exists: for T = 0 none of the keys performs its action, so it suffices to take V 1 = V 2 .) Constraints You may assume that 2 ≤ N ≤ 100000 and 2 ≤ V max ≤ 5000. In test cases worth 40 points N ≤ 4000. In test cases worth 70 points N x V max ≤ 400000. Examples Input: 6 4 3 - 0 + 8 + 9 + 13 - 19 - 24 Output: 5 4 For T = 5 the keys perform the following actions: unlock, unlock, + , + , unlock, - . For any V 1 ∈; {2, 3, 4} we would get V 2 = 3. Note that the output contains the largest possible V 1 . For T ≥ 6 the last two keystrokes will both be active, hence it will be impossible to have V 2 = 3. Input: 3 10 10 + 1 + 2 + 47 Output: infinity If V 1 = 10 then for any T we'll have V 2 = 10.
32,004
IOI2009 Mecho (CTOI09_1) Mecho the bear has found a little treasure - the bees' secret honeypot, which is full of honey! He was happily eating his newfound treasure until suddenly one bee saw him and sounded the bee alarm. He knows that at this very moment hordes of bees will emerge from their hives and start spreading around trying to catch him. He knows he has to leave the honeypot and go home quickly, but the honey is so sweet that Mecho doesn't want to leave too soon. Help Mecho determine the latest possible moment when he can leave. Mecho's forest is represented by a square grid of N by N unit cells, whose sides are parallel to the north-south and east-west directions. Each cell is occupied by a tree, by a patch of grass, by a hive or by Mecho's home. Two cells are considered adjacent if one of them is immediately to the north, south, east or west of the other (but not on a diagonal). Mecho is a clumsy bear, so every time he makes a step, it has to be to an adjacent cell. Mecho can only walk on grass and cannot go through trees or hives, and he can make at most S steps per minute. At the moment when the bee alarm is sounded, Mecho is in the grassy cell containing the honeypot, and the bees are in every cell containing a hive (there may be more than one hive in the forest). During each minute from this time onwards, the following events happen in the following order: If Mecho is still eating honey, he decides whether to keep eating or to leave. If he continues eating, he does not move for the whole minute. Otherwise, he leaves immediately and takes up to S steps through the forest as described above. Mecho cannot take any of the honey with him, so once he has moved he cannot eat honey again. After Mecho is done eating or moving for the whole minute, the bees spread one unit further across the grid, moving only into the grassy cells. Specifically, the swarm of bees spreads into every grassy cell that is adjacent to any cell already containing bees. Furthermore, once a cell contains bees it will always contain bees (that is, the swarm does not move, but it grows). In other words, the bees spread as follows: When the bee alarm is sounded, the bees only occupy the cells where the hives are located. At the end of the first minute, they occupy all grassy cells adjacent to hives (and still the hives themselves). At the end of the second minute, they additionally occupy all grassy cells adjacent to grassy cells adjacent to hives, and so on. Given enough time, the bees will end up simultaneously occupying all grassy cells in the forest that are within their reach. Neither Mecho nor the bees can go outside the forest. Also, note that according to the rules above, Mecho will always eat honey for an integer number of minutes. The bees catch Mecho if at any point in time Mecho finds himself in a cell occupied by bees. Task Write a program that, given a map of the forest, determines the largest number of minutes that Mecho can continue eating honey at his initial location, while still being able to get to his home before any of the bees catch him. Constraints 1 ≤ N ≤ 800 - the size (side length) of the map. 1 ≤ S ≤ 1,000 - the maximum number of steps Mecho can take in each minute. Input The input contains several test cases. The fist line contains the number of test cases T . Each test case has the form as following: The first line contains the integers N and S , separated by a space. The next N lines represent the map of the forest. Each of these lines contains N characters with each character representing one unit cell of the grid. The possible characters and their associated meanings are as follows: T denotes a tree, G denotes a grassy cell, M denotes the initial location of Mecho and the honeypot, which is also a grassy cell, D denotes the location of Mecho's home, which Mecho can enter, but the bees cannot. H denotes the location of a hive. Note: It is guaranteed that the map will contain exactly one letter M , exactly one letter D and at least one letter H . It is also guaranteed that there is a sequence of adjacent letters G that connects Mecho to his home, as well as a sequence of adjacent letters G that connects at least one hive to the honeypot (i.e., to Mecho's initial location). These sequences might be as short as length zero, in case Mecho's home or a hive is adjacent to Mecho's initial location. Also, note that the bees cannot pass through or fly over Mecho's home. To them, it is just like a tree. Output For each test case, your program must write to standard output a single line containing a single integer: the maximum possible number of minutes that Mecho can continue eating honey at his initial location, while still being able to get home safely. If Mecho cannot possibly reach his home before the bees catch him, the number your program writes to standard output must be -1 instead. Example For the input data: 1 7 3 TTTTTTT TGGGGGT TGGGGGT MGGGGGD TGGGGGT TGGGGGT THHHHHT the correct result is: 1 Explanation of the example: After eating honey for one minute, Mecho can take the shortest path directly to the right and he will be home in another two minutes, safe from the bees. For the input data: 1 7 3 TTTTTTT TGGGGGT TGGGGGT MGGGGGD TGGGGGT TGGGGGT TGHHGGT the correct result is: 2 Explanation of the example: After eating honey for two minutes, Mecho can take steps →↑→ during the third minute, then steps →→→ during the fourth minute and steps ↓→ during the fifth minute.
32,005
Partial Palindrome (PARTPAL) Fernando is president of country named Palindromia. Every two years there are elections in Palindromia, but not normal elections. Elections in Palindromia are preformed in next steps: Candidate which at the moment isn't president gives to the current president one string O , which consist only of upper-case letters of English alphabet and character '?', string U , which consist only of upper-case letters of English alphabet, and integer K . Current president has one day to compute all longest palindromes in the first string by the following rules: Every '?' in O is substituted with one letter from U , i -th '?' in O with i -th letter in U . Every time he search for palindromes, he may substitute some '?' with any letter, at most K -times. If he finds palindrome, he goes to step 1. If he doesn't succeed, the candidate becomes the new president. If there are more candidates, go to step one. Fernando wants to stay president for at least two more years, so he asks you to write program which solves his problem. Input First line of input will contain string O (1 <= length of O <= 5 * 10^5), string which Fernando must compute to stay president. O will consist only of upper-case letters of English alphabet and character '?'. You may assume there is at least one '?' in O . Second line will contain string U , string with leads for '?'s. i -th letter in U correspond to i -th '?' in O . U will consist only of upper-case letters of English alphabet. Third line will contain integer K (0 <= K <= 300), number of replacements. It is guaranteed that there will be not more than 300 '?'s. Output In first line of output print integer S , length of the longest palindrome that Fernando could find. In Second and next lines print string P i and integer L i , longest palindrome and position where it starts. Each P i must contain only upper-case letters of English alphabet. Notes: you must print all longest palindromes, in alphabetically increasing order if two or more palindromes starts at the same position, print only one of them Example Input: UDOVICAB??IVODUANAVOL?MILOVANA CCA 1 Output: 15 ANAVOLIMILOVANA 16 UDOVICABACIVODU 1 Note that both palindromes have 1 letter which Fernando has changed. Input: ABCDE??ABCDE?? ABCD 1 Output: 5 CBABC 6 Input: ABCDE??ABCDEFG FG 0 Output: 1 A 1 A 8 B 2 B 9 C 10 C 3 D 4 D 11 E 5 E 12 F 13 F 6 G 7 G 14
32,006
Odd Independent Sets (INDEPCNT) Given integer N (1 ≤ N ≤ 60), output the number of Rooted Unlabeled Trees which have an odd number of independent sets. Rooted Unlabeled Tree : An Unlabeled Tree with a specified vertex as root and order amongst children does not matter. That is, two trees are considered equal if they are the same after some re-ordering of their non-root vertices. A rigorous definition is "two Rooted Unlabeled Trees T1 and T2 are equal if and only if there is a bijection f between T1 and T2 such that if root1 and root2 are the roots of T1 and T2 respectively, f(root1)=root2 and edge (u, v) is in T1 if and only if edge (f(u), f(v)) exists in T2" Independent Set : A set of vertices (possibly empty) is called an Independent Set if no two vertices of the set have an edge between them. Input First line contains T, the number of test cases. Next T lines contain one number each, N. Output Output T lines, one per test case. Each line should contain the number of rooted unlabeled trees which have an odd number of independent sets. Output the answer modulo 1000000007. That is, if the actual answer is A, output A % 1000000007. (This is just to keep computations within 64 bit integers.) Example Input: 6 1 2 3 4 5 40 Output: 0 1 2 2 5 632355321
32,007
Check 1324 (PERMPATT) Given a permutation P[1...n] of {1,2,...n}, you should output if the permutation contains a pattern of the form 1324. That is, do there exist indices  1 <= i1 < i2 < i3 < i4 <= n such that  P[i1] < P[i3] < P[i2] < P[i4]. For example, P = 6 8 5 4 9 3 7 2 1 10 contains one: the indices 1, 2, 7, 10 correspond to the sequence  6 8 7 10 which is a 1324 pattern. Input First line contains T, the number of test cases Each of the next T lines contains n (1 <= n <= 100000), followed by n  integers, representing a permutation of [1,2,..,n]. SUM( n * log 2 (n)) over all test cases <= 10 8 . Do not assume anything else about the number of test cases or their distribution. Output Output T lines, one per test case: "yes"(without quotes) if the permutation contains a 1324 pattern or "no" (without quotes) otherwise. Warning: Huge I/O Example Input: 2 10 6 8 5 4 9 3 7 2 1 10 10 5 3 4 7 9 10 8 6 2 1 Output: yes no
32,008
The Least Number (RNDORDER) You are given n symbols a 1 , a 2 ... a n . You are told that there is a total ordering of the symbols. That is, there is a permutation [P1, P2 ... Pn] of [1, 2 ... n] such that a P1 < a P2 < ... < a Pn . You are trying to figure out the order by doing comparisons. The process you follow for determining the order is as follows: Compare [a 1 , a 2 ] Compare [a 2 , a 3 ], [a 1 , a 3 ] Compare [a 3 , a 4 ], [a 2 , a 4 ], [a 1 , a 4 ] ... ... Compare [a n-1 , a n ], [a n-2 , a n ] ... [a 1 , a n ] Note that you compare in the order specified. That is you compare [a 2 , a 3 ], then and only then do you compare [a 1 , a 3 ]. Definition of Compare[a i , a j ] (i < j) If Compare [a i , a j ] = 1, it means a i > a j . If Compare[a i , a j ] = -1, it means a i < a j . Compare is consistent. Suppose, that you queried [a 2 , a 6 ] and it was already established [a 2 < a 6 ] (because for example a 2 < a 5 and a 5 < a 6 - since both of these comparisons happen earlier), then [a 2 , a 6 ] returns -1. If no relationship is known between a i and a j , Compare[a i , a j ] = 1 with probability 1/2 and -1 with probability 1/2. Your task is to output the probability that a 1 is the smallest element of the final ordering so obtained. Input First line contains T, the number of test cases. Each of the next T lines contains one number each, n (1 ≤ n ≤ 1000). Output Output T lines in total, one per test case: Probability that a 1 is indeed the smallest element at the end of the comparisons. Your output will be judged correct if it differs by no more than 10 -9 to the reference answer. Example Input: 3 1 2 3 Output: 1 0.500 0.3750000 Explanation n = 1 is trivial. For n = 2, only comparison is [a 1 , a 2 ]. a1 is lower with probability 1/2. For n = 3, a1 is not the least element if either (a 1 > a 2 ) or (a 1 < a 2 and a 3 < a 2 and a 3 < a 1 ). So, probability that a 1 is not the least element = 1/2 + 1/8 = 5/8. Probability that a 1 is the least = 3/8 = 0.375.
32,009
Rearranging Digits (ARRANGE2) Given A and B, how many numbers between A and B (with no leading 0's) rearrange their digits when multiplied by 2? Input The first line contains the number of test cases T. T lines follow, each containing two integers A and B. Output Output T lines, one for each test case containing the desired answer for the corresponding test case. Sample Input: 2 1 100 499875921 499875921 Output: 0 1 Constraints 1 <= T <= 10000 1 <= A <= B <= 10000000000 (10^10)
32,010
Summing Slopes (SUMSLOPE) A digit in a number N is a minima if it is lesser than both the digits adjacent to it. Similarly, a digit is a maxima if it is greater than both the digits adjacent to it. The slope of N is the number of digits in N (leaving out the first and the last digit) which are either a minima or a maxima. Given A and B, count the sum of the slopes of all numbers between A and B. Input The first line contains the number of test cases T. Each of the next T lines contains two integers A and B. Output Output T lines one for each test case, containing the required sum for the corresponding test case. Sample Input 3 101 101 1 100 100 150 Output 1 0 19 Constraints 1 <= T <= 50000 1 <= A <= B <= 1000000000000000 (10^15)
32,011
Beer Machines (STJEPAN) Little Stjepan lives in a village which can be represented as X-axis. In village there are N beer machines, machine i has x coordinate P i and needs T i seconds to produce 1 liter of beer. This year M tourists (one by one because there is only one guide, Stjepan) will visit his village, tourist i will arrive at point A i , want to drink L i liters of beer but will have energy to walk at most D i seconds (that is D i units of length), he will walk to beer machine Stjepan suggests him and as soon as machine produces L i liters of beer tourist will be able to enjoy it. As Stjepan wants all tourists to come next year too he will choose machine for each tourist so that tourist can get a beer as soon as possible. Help Stjepan to do that and write program which will output minimal sum of passed times from arrival of tourist to getting a beer. If a tourist can't get a beer then his time is 0. Note that tourists are independent and machines can be used multiple times. Input On first line of standard input you are given two integers (2 ≤ N ≤ 250 000, 1 ≤ M ≤ 500 000), number of beer machines and number of tourists. Next 5 lines contain 4 integers (X 0 , A, B, C) each and they describe arrays P, T, A, L and D, respectively. With these four numbers i-th element of array is defined as X i = 1 + ((X i-1 *A + B) mod C), where indices are 1-based and X 0 is given in input. 1 ≤ X 0 , A, B, C ≤ 10 9 . Note:  Author's solution doesn't depend on properties of pseudo-random generator. Output Output total time from task statement. Answer will fit in 64-bit signed integer. Example Input: 3 4 1 4 3 6 2 4 4 10 3 8 1 10 3 1 8 7 1 3 2 6 Output: 53 Explanation Machines (P, T) : (2, 3), (6, 7), (4, 3) Tourists (A, L, D) : (6, 5, 6), (10, 7, 3), (2, 2, 6), (8, 4, 3) Tourist #1 → Machine #3 → 17 time units. Tourist #2 → No beer :( → 0 time units. Tourist #3 → Machine #1 → 6 time units. Tourist #4 → Machine #2 → 30 time units.
32,012
Avoiding SOS Grids (AVOIDSOS) You are given a grid having N rows and M columns. Some squares are contain letters 'S' or 'O', whereas the other squares are unfilled. A filled grid is called "Avoiding SOS" if there is no occurrence of the string "SOS" in the grid either vertically or horizontally. In how many ways can the grid be completed by filling the unfilled squares with either 'S' or 'O' such that the resultant grid is "Avoiding SOS"? Input The first line contains T the number of test cases. T test cases follow. The first line for each test case contains N and M, the number of rows and columns in the grid respectively. N lines follow, each containing M characters. The jth character in the ith line is a '.' if the corresponding square in the grid is unfilled, otherwise it contains either the letter 'S' or the letter 'O'. A blank line separates two test cases. Output Output T lines, one for each test case, containing the desired answer for the corresponding test case. Output each result modulo 1000000007. Example Input: 5 2 3 ... ... 1 4 .... 3 3 .O. S.S .O. 1 3 SOS 1 3 SOO Output 49 12 9 0 1 Constraints 1 ≤ T ≤ 100 1 ≤ N, M ≤ 8
32,013
Visible Lattice Points (VLATTICE) Consider a N * N * N lattice. One corner is at (0, 0, 0) and the opposite one is at (N, N, N). How many lattice points are visible from corner at (0, 0, 0)? A point X is visible from point Y iff no other lattice point lies on the segment joining X and Y. Input The first line contains the number of test cases T. The next T lines contain an integer N. Output Output T lines, one corresponding to each test case. Sample Input: 3 1 2 5 Sample Output: 7 19 175 Constraints T <= 50 1 <= N <= 1000000
32,014
Buildings (BUILDING) A certain city has M buildings, all having a width of 1. The ith building has height h i units. The outline of the city can be seen by everyone passing along, and you wish to place an advertisement in front. You want the advertisement to be totally contained within the boundary defined by the outline of the city. The advertisement should be rectangular in shape, and its base should be at ground level. Also, it should have an integral height and its vertical edges should coincide with the vertical edges of the buildings. Now you wonder, for each building x, how many ways are there to place an advertisement such that it hides (fully or partially) building x? Input The first line contains an integer M, the number of buildings. The second line contains M space separated integers, the heights of the buildings. Output Output M integers. The ith integer is the number of possible advertisements which cover the ith building partially or fully. Example Input: 4 2 1 4 4 Output: 5 6 12 10 Constraints 1 ≤ M ≤ 100000 1 ≤ h i ≤ 10000
32,015
Police Business (ACAB) Cops are one of the most fascinating types of people. In the movies they are usually shown as fat and lazy, but they are so much more! Our today's specimen, officer Acab is, for example, very much into philosophy. All the criminals are afraid of Acab so when he appears in a city no criminals can come there. He's often engaged in car chases, so he usually asks himself the following questions: If I know a criminal has to travel from city a to city b, how many cities are there (other than a and b) such that there are no other cops there, and if I come to that city the criminal won't be able to accomplish his trip? If I sort those cities by distance from a, which one will be the k-th in the sorted list? How many roads are there such that there are no other cops on them, and if I'm present on that road the criminal won't be able to travel from a to b? Which is the k-th such road if I sort the available roads by their distance from a? Given a list of bidirectional roads that connect the cities write a program that will answer Acab's questions. In the beginning we know that there are no other cops in any of the cities. There will be one or more paths between each pair of cities. Sometimes Acab's cop-friends contact him to tell him they have entered a city or road. There is never more than one cop present in a city or on a road. Thus, when a road or city is reported for the second time, we assume the cop has left there. This only means that after each even report of the same city or a road there are no cops there, and for odd reports there is a cop there. Note: we define the distance of a road from a city as the minimum of the distances of its endpoints from that city. Even though Acab is a good cop, he doesn't have any special powers such as multilocation, so he can only be present in one city at a time. If you, for some reason, find two cities or roads equidistant from the city a, output the one with the smaller index. Also, the other cops aren't as good as Acab, so they only block Acab from visiting a city, and not the criminals. Input The first line of input contains two integers N and M (1 ≤ N ≤ M ≤ 100000). The next M lines contain a pair of integers a and b (1 ≤ a, b ≤ N). All the cities are numbered from 1 to N. The next line contains a single integer Q (1 ≤ Q ≤ 200000). The next Q lines contain queries. There are six possible types of queries:     1 n   -  a cop has contacted Acab to let him know he's in city n     2 e   -  a cop has contacted Acab to let him know he's on the road e     3 a b  -  tell Acab how many cities he can block the criminal with     4 a b  -  tell Acab how many roads he can block the criminal with     5 a b k  -  tell Acab which is the k-th city he can block the criminal with     6 a b k  -  tell Acab which is the k-th road he can block the criminal with Output For each query of type 3, 4, 5 or 6 output a single line containing the answer. If for a query of type 5 or 6 k is greater than the actual number of possible cities, output -1. Also, in queries 2 and 6 the number of the road is assumed to be its index from the input. Example Input: 9 10 1 2 1 3 2 4 2 5 4 5 4 6 3 7 3 8 7 8 8 9 10 3 6 9 4 6 9 5 6 9 2 6 6 9 2 1 2 5 6 9 2 2 1 6 6 9 2 1 2 5 6 9 2 Output: 5 4 2 1 1 2 2 Explanation: In the first query, there are 5 blockable cities: 4, 2, 1, 3, 8. In the second query there are 4 blockable roads: 6, 1, 2, 10. In the third query the second city is 2 (4, 2, 1, 3, 8). In the fourth query the second road is 1 (6, 1, 2, 10). In the fifth query we've been reported there's a cop in city 2. In the sixth query the second blockable city is 1 (city 2 already contains a cop). In the seventh query we've been reported there's a cop on road 1. In the eighth query the second blockable road is 2 (road 1 already contains a cop). In the ninth query we've been reported the cop from city 2 has left. In the tenth query the second city is 2 again.
32,016
Party (CFPARTY) n  people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly  2, 3, ...,  n  - 1  friends among those who stayed by the moment of their leaving, did the same. What is the maximum amount of people that could stay at the party in the end? Input The first input line contains one number  t  — amount of tests ( 1 ≤  t  ≤ 10 5 ). Each of the following  t  lines contains one integer number  n  ( 1 ≤  n  ≤ 10 5 ). Output For each test output in a separate line one number — the maximum amount of people that could stay in the end. Example Input: 1 3 Output: 1
32,017
Zig-Zag rabbit (ZIGZAG) A N×N matrix is filled with numbers 1 to N 2 , diagonally in a zig-zag fashion. The table below shows numbers in the matrix for N = 6. 1 2 6 7 15 16 3 5 8 14 17 26 4 9 13 18 25 27 10 12 19 24 28 33 11 20 23 29 32 34 21 22 30 31 35 36 There is a rabbit in the cell containing number 1. A rabbit can jump to a neighboring cell (up, down, left or right) if that cell exists. Given K valid rabbit jumps, write a program that will calculate the sum of numbers of all cells that rabbit visited (add the number to the sum each time rabbit visits the same cell).  Input The first line contains two integers N and K (1 ≤ N ≤ 100 000, 1 ≤ K ≤ 300 000), the size of the matrix and the number of rabbit jumps. The second line contains a sequence of K characters 'U', 'D', 'L' and 'R', describing the direction of each jump. The sequence of jumps will not leave the matrix at any moment. Output Output one integer, the sum of numbers on visited cells. Note: This number doesn't always fit in 32-bit integer type. Example Input: 6 8 DDRRUULL Output: 47 Input: 3 8 DDRRUULL Output: 41 Input: 6 10 RRRRRDDDDD Output: 203 Clarification for the first sample: The rabbit visits cells 1, 3, 4, 9, 13, 8, 6, 2 and 1. Clarification for the second sample: The rabbit visits cells 1, 3, 4, 8, 9, 7, 6, 2 and 1. Clarification for the third sample: The rabbit visits cells 1, 2, 6, 7, 15, 16, 26, 27, 33, 34 and 36.
32,018
Cow Patterns (CPATTERN) A particular subgroup of K (1 ≤ K ≤ 25,000) of Farmer John's cows likes to make trouble. When placed in a line, these troublemakers stand together in a particular order. In order to locate these troublemakers, FJ has lined up his N (1 ≤ N ≤ 100,000) cows. The cows will file past FJ into the barn, staying in order. FJ needs your help to locate suspicious blocks of K cows within this line that might potentially be the troublemaking cows.  FJ distinguishes his cows by the number of spots 1..S on each cow's coat (1 ≤ S ≤ 25). While not a perfect method, it serves his purposes. FJ does not remember the exact number of spots on each cow in the subgroup of troublemakers. He can, however, remember which cows in the group have the same number of spots, and which of any pair of cows has more spots (if the spot counts differ). He describes such a pattern with a sequence of K ranks in the range 1..S. For example, consider this sequence:  1 4 4 3 2 1 In this example, FJ is seeking a consecutive sequence of 6 cows from among his N cows in a line. Cows #1 and #6 in this sequence have the same number of spots (although this number is not necessarily 1) and they have the smallest number of spots of cows #1..#6 (since they are labeled as '1'). Cow #5 has the second-smallest number of spots, different from all the other cows #1..#6. Cows #2 and #3 have the same number of spots, and this number is the largest of all cows #1..#6.  If the true count of spots for some sequence of cows is:  5 6 2 10 10 7 3 2 9 then only the subsequence 2 10 10 7 3 2 matches FJ's pattern above.  Please help FJ locate all the length-K subsequences in his line of cows that match his specified pattern. Input Line 1: Three space-separated integers: N, K, and S  Lines 2..N+1: Line i+1 describes the number of spots on cow i.  Lines N+2..N+K+1: Line i+N+1 describes pattern-rank slot i. Output Line 1: The number of indices, B, at which the pattern matches. Lines 2..B+1: An index (in the range 1..N) of the starting location where the pattern matches. Example Input: 9 6 10 5 6 2 10 10 7 3 2 9 1 4 4 3 2 1 Output: 1 3
32,019
Cookies (KOLACI) Darko and Marko are twins and they love to eat cookies. Their grandma Mara loves to bake cookies, but she doesn't like the fact that Darko and Marko eat them too fast. To teach her grandsons to eat slower, Mara turned it into a game. Mara will bake N cookies and assign them with integers 1 to N. Then she will arrange them in a circle such that each cookie i is between to cookie i−1 and i+1 except for cookies 1 and N that are neighbors. Mara knows a recipe for 26 different types of cookies. We will denote a cookie type with lower case English letters 'a' to 'z'. Darko and Marko will each get one cookie every 5 minutes. Mara will say one integer out loud. Darko and Marko will search for a cookie with this number, but will eat two neighboring cookies. This procedure is repeated until one or two cookies are left on the table. Then the game ends and Mara eats the remaining cookies. The game can be represented with a sequence of (N−1) div 2 integers that Mara said out loud. For example, the illustrations above can be represented with a sequence (4, 8, 6). Two games are considered different if their respective sequences are different. After a few games Mara noticed that Marko and Darko often fight during the game. In fact, they fight every time when the two neighboring cookies are of different types because they can't decide which one will get which cookie. Mara decided to count the number of ways to play a game in a way to avoid such situations. Given a cookie type for each of N cookies, write a program that will calculate the number of ways to play a game such that Darko and Marko will not fight. This number can get very large, so output the remainder of division by 10007 instead. Input The first line contains one integer N (3 ≤ N ≤ 75), the number of cookies. The second line contains a sequence of N lower case English letters, types of cookies in order they are arranged in a circle. Output Output a single integer, the total number of ways to play a game that will prevent Darko and Marko from fighting modulo 10007. Example Input: 8 cibaboca Output: 4 Input: 5 aabab Output: 5 Input: 11 fffffffffff Output: 388 Clarification for the first example: This sample corresponds to illustration above. Four valid sequences are (4, 8, 2), (4, 8, 6), (8, 4, 2) and (8, 4, 6). Clarification for the second example: Five valid sequences are (3, 1), (5, 2), (4, 4), (4, 1) and (4, 2). Clarification for the third example: All cookies share the same type, so Darko and Marko can't get into fight no matter what. In each step Mara can say any integer remaining on the table, so the total number of games is equal to 11⋅9⋅7⋅5⋅3 = 10395. 388 is the remainder of division by 10007.
32,020
Roads in Berland (CT25C) There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. Input The first line contains integer n ( 2 ≤ n ≤ 300 ) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of distances. j -th integer in the i -th row — d i , j , the distance between cities i and j . It is guaranteed that d i , i = 0, d i , j = d j , i , and a given matrix is a matrix of distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k ( 1 ≤ k ≤ 300 ) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers a i , b i , c i ( 1 ≤ a i , b i ≤ n , a i ≠ b i , 1 ≤ c i ≤ 1000 ) — a i and b i — pair of cities, which the road connects, c i — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. Output Output k lines, each line contains one integers q i ( 1 ≤ i ≤ k ). q i should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i . Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. Example Input: 3 0 4 5 4 0 9 5 9 0 2 2 3 8 1 2 1 Output: 17 12
32,021
Crashing Robots (CROBOTS) In a modernized warehouse, robots are used to fetch the goods. Careful planning is needed to ensure that the robots reach their destinations without crashing into each other. Of course, all warehouses are rectangular, and all robots occupy a circular floor space with a diameter of 1 meter. Assume there are N robots, numbered from 1 through N. You will get to know the position and orientation of each robot, and all the instructions, which are carefully (and mindlessly) followed by the robots. Instructions are processed in the order they come. No two robots move simultaneously; a robot always completes its move before the next one starts moving. A robot crashes with a wall if it attempts to move outside the area of the warehouse, and two robots crash with each other if they ever try to occupy the same spot. Input The first line of input is K, the number of test cases. Each test case starts with one line consisting of two integers, 1 ≤ A, B ≤ 100, giving the size of the warehouse in meters. A is the length in the EW-direction, and B in the NS-direction. The second line contains two integers, 1 ≤ N, M ≤ 100, denoting the numbers of robots and instructions respectively. Then follow N lines with two integers, 1 ≤ Xi ≤ A, 1 ≤ Yi ≤ B and one letter (N, S, E or W), giving the starting position and direction of each robot, in order from 1 through N. No two robots start at the same position. Finally there are M lines, giving the instructions in sequential order. An instruction has the following format: <robot #> <action> <repeat> Where <action> is one of: L: turn left 90 degrees, R: turn right 90 degrees, or F: move forward one meter, and 1 ≤ <repeat> ≤ 100 is the number of times the robot should perform this single move. Output Output one line for each test case: Robot i crashes into the wall, if robot i crashes into a wall. (A robot crashes into a wall if Xi = 0, Xi = A + 1, Yi = 0 or Yi = B + 1.) Robot i crashes into robot j, if robots i and j crash, and i is the moving robot. OK, if no crashing occurs. Only the first crash is to be reported. Example Input: 4 5 4 2 2 1 1 E 5 4 W 1 F 7 2 F 7 5 4 2 4 1 1 E 5 4 W 1 F 3 2 F 1 1 L 1 1 F 3 5 4 2 2 1 1 E 5 4 W 1 L 96 1 F 2 5 4 2 3 1 1 E 5 4 W 1 F 4 1 L 1 1 F 20 Output: Robot 1 crashes into the wall Robot 1 crashes into robot 2 OK Robot 1 crashes into robot 2
32,022
The Embarrassed Cryptographer (CRYPTON) The young and very promising cryptographer Odd Even has implemented the security module of a large system with thousands of users, which is now in use in his company. The cryptographic keys are created from the product of two primes, and are believed to be secure because there is no known method for factoring such a product effectively. What Odd Even did not think of, was that both factors in a key should be large, not just their product. It is now possible that some of the users of the system have weak keys. In a desperate attempt not to be fired, Odd Even secretly goes through all the users keys, to check if they are strong enough. He uses his very poweful Atari, and is especially careful when checking his boss’ key. Input The input consists of no more than 20 test cases. Each test case is a line with the integers 4 ≤ K ≤ 10 100 and 2 ≤ L ≤ 10 6 . K is the key itself, a product of two primes. L is the wanted minimum size of the factors in the key. The input set is terminated by a case where K = 0 and L = 0. Output For each number K, if one of its factors are strictly less than the required L, your program should output “BAD p”, where p is the smallest factor in K. Otherwise, it should output “GOOD”. Cases should be separated by a line-break. Example Input: 143 10 143 20 667 20 667 30 2573 30 2573 40 0 0 Output: GOOD BAD 11 GOOD BAD 23 GOOD BAD 31
32,023
Necklace Decomposition (NECKDEC) The set of cyclic rotations of a string are the strings obtained by embedding the string clockwise on a ring, with the first character following on the last, starting at any character position and moving clockwise on the ring until the character preceeding the starting character is reached. A string is a necklace if it is the lexicographically smallest among all its cyclic rotations. For instance, for the string 01011 the cyclic rotations are (10110,01101,11010,10101,01011), and furthermore 01011 is the smallest string and hence, a necklace. Any string S can be written in a unique way as a concatenation S = T1 T2 ... Tk of necklaces Ti such that Ti+1 < Ti for all i = 1...k − 1, and Ti Ti+1 is not a necklace for any i = 1...k − 1. This representation is called the necklace decomposition of the string S, and your task is to find it. The relation < on two strings is the lexicographical order and has the usual interpretation: A < B if A is a proper prefix of B or if A is equal to B in the first j − 1 positions but smaller in the jth position for some j. For instance, 001 < 0010 and 1101011 < 1101100. Input On the first line of the input is a single positive integer n, telling the number of test scenarios to follow. Each scenario consists of one line containing a non-empty string of zeros and ones of length at most 100. Output For each scenario, output one line containing the necklace decomposition of the string. The necklaces should be written as ’(’ necklace ’)’. Example Input: 5 0 0101 0001 0010 11101111011 Output: (0) (0101) (0001) (001)(0) (111)(01111)(011)
32,024
Advanced Edit Distance (ADVEDIST) The edit distance of two strings S and T is the minimum number of edit operations that need to be done to transform S into T . The valid edit operations are: Insert a single character at any position. Modify an existing character. Remove an existing character. For example, the edit distance of “pantera” and “aorta” is 5, because the following chain of edits is valid (and there is no shorter chain): “pantera” → “antera” → “aotera” → “aoera” → “aora” → “aorta”. We define the advanced edit distance in a similar way, but adding the swap of two adjacent characters as an extra valid operation. With this setting, the advanced edit distance of “pantera” and “aorta” is 4: “pantera” → “antera” → “antra” → “aotra” → “aorta”. You need to write a program that calculates the advanced edit distance of two given words. Input The input contains several test cases. Each test case is described in a single line that contains two non-empty words, each of them of at most 1000 lowercase letters, separated by a single space. The last line of the input contains two asterisks separated by a single space and should not be processed as a test case. Output For each test case output a single line with an integer representing the advanced edit distance of the two input words. Example Input: pantera aorta zero zero * * Output: 4 0
32,025
Back To The Polygon (BACKTPOL) A simple polygon is a polygon that does not overlap with itself. A diagonal of a simple polygon is a segment within the polygon that connects two non-consecutive vertices. A triangulation of a simple polygon of N edges is the drawing of exactly N − 3 diagonals that do not touch each other anywhere, with the possible exception of their endpoints. A triangulation divides the polygon in exactly N − 2 triangles that do not overlap and only touch each other along their edges. In this problem, you are given the triangulation of a simple polygon, which means, the set of triangles in which a polygon was divided. From them, you need to reconstruct the original polygon. Input The input contains several test cases, each one described in several lines. The first line of each test case contains an integer N (3 ≤ N ≤ 500), the number of edges of the original polygon. Each of the next N − 2 lines describes one triangle in the triangulation of the polygon. Each triangle is given by six integers X1, Y1, X2, Y2, X3 and Y3 separated by single spaces, where Xi and Yi are the coordinates in the XY plane of the i-th vertex of the triangle (−1000 ≤ Xi, Yi ≤ 1000). The triangles and their vertices are not given in any specific order. The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output a single line with 2N integers separated by single spaces. These integers must represent the coordinates in the XY plane of the vertices of the original polygon, in clockwise order. To make the output unique, the first vertex to be listed is the one with the smallest X coordinate, and if there are many of those, the one with the smallest Y coordinate among them. Example Input: 5 0 0 10 9 10 0 10 9 0 9 0 0 10 9 0 9 5 13 3 0 1 1 1 1 0 10 -1 -2 2 -2 2 -1 -1 -2 0 -1 -2 3 -2 3 2 3 1 2 0 -1 2 1 1 2 -1 -2 2 -1 0 -1 2 1 0 -1 2 0 2 3 2 2 1 2 0 -1 -2 3 1 2 -1 Output: 0 0 0 9 5 13 10 9 10 0 0 1 1 1 1 0 -2 3 2 3 2 2 1 2 2 1 2 0 0 -1 2 -1 2 -2 -1 -2
32,026
Charly And Nito (CANDN) Charly and Nito are friends and they like to be together at a nice bar in Palermo Hollywood. About at 3 a.m. they start to feel sleepy and want to go home. They want to get home quickly so each of them uses a path that minimizes the distance to his home. However, Charly and Nito also like to walk together while they talk about the “good old times”, so they want to walk together as much as possible. Charly and Nito live in a city that can be modelled as a set of streets and junctions. Each street connects a pair of distinct junctions and can be walked in both directions. No two streets connect the same pair of junctions. Charly and Nito do not live together, and they do not live at the bar. There is at least one path from the bar to Charly’s home; the same occurs with Nito’s home. Given information about the streets and junctions in the city, the locations of the bar, Charly’s home and Nito’s home, you must tell Charly and Nito the maximum distance that they can walk together without forcing them to walk more than the minimum distance from the bar to their respective homes. Charly and Nito also want to know how much each of them will walk alone. Input The input contains several test cases, each one described in several lines. The first line of each test case contains five integers J, B, C, N and S separated by single spaces. The value J is the number of junctions in the city (3 ≤ J ≤ 5000); each junction is identified by an integer number between 1 and J. The values B, C and N are the identifiers of the junctions where the bar, Charly’s home and Nito’s home are located, respectively (1 ≤ B, C, N ≤ J); these three junction identifiers are different. The value S is the number of streets in the city (2 ≤ S ≤ 150000). Each of the next S lines contains the description of a street. Each street is described using three integers E1, E2 and L separated by single spaces, where E1 and E2 identify two distinct junctions that are endpoints of the street (1 ≤ E1, E2 ≤ J), and L is the length of the street (1 ≤ L ≤ 10 4 ). You may assume that each street has a different pair of endpoints, and that there exist paths from junction B to junctions C and N. The last line of the input contains the number −1 five times separated by single spaces and should not be processed as a test case. Output For each test case output a single line with three integers T, C and N separated by single spaces, where T is the maximum distance that Charly and Nito can walk together, C is the distance that Charly walks alone, and N is the distance that Nito walks alone. Example Input: 5 3 2 1 6 3 4 10 4 5 10 5 1 3 5 2 4 1 3 23 2 3 24 8 1 7 8 8 1 2 1 2 4 1 2 3 1 4 5 1 3 5 1 5 6 1 6 8 1 6 7 1 -1 -1 -1 -1 -1 Output: 20 4 3 4 1 1
32,027
Doing The Word Wrap (DTWW) You are developing a visual component for a web browser. The component is known as textarea, and its main functionality is to show a given text using one or more lines. Every textarea has a linewidth W , which is the number of characters that can fit in a single line. The text that needs to be shown is a sequence of words. The textarea must display the text using lines of W characters, without breaking any word, and placing a single space between each pair of consecutive words that are in the same line. Any number of trailing spaces may be left at the end of each line. So the behavior of the textarea is quite simple: it keeps adding words to a line until the next word does not fit; each time this occurs, a new line is started. With the permanent growing in the amount of information that web pages must show, you have to make a smart textarea that uses as little space as possible, even when dealing with very long texts. Given a text to show and a number of lines L, you must set the linewidth W to the minimum possible value such that the text is shown using at most L lines. Input The input contains several test cases, each one described in exactly two lines. The first line of each test case contains two integers L and N separated by a single space, where L is the maximum number of lines the textarea can have (1 ≤ L ≤ 10 8 ), and N is the number of words the text to show is made of (1 ≤ N ≤ 10 5 ). The second line contains the text to show, formed by N non-empty words of at most 25 lowercase letters each, separated by an arbitrary number of spaces. The last line of the input contains the number −1 twice separated by a single space and should not be processed as a test case. Output For each test case output a single line with an integer W representing the minimum linewidth such that the textarea has at most L lines. Example Input: 1 2 hello word 2 2 racing club -1 -1 Output: 10 6
32,028
Edit Distance (EDDIST) The edit distance of two strings S and T is the minimum number of edit operations that need to be done to transform S into T. The valid edit operations are: Insert a single character at any position. Modify an existing character. Remove an existing character. For example, the edit distance of “pantera” and “aorta” is 5, because the following chain of edits is valid (and there is no shorter chain): “pantera” → “antera” → “aotera” → “aoera” → “aora” → “aorta”. In this problem, given a value K and a word S, we need to construct a word T such that the edit distance of S and T is at most K. There are of course several possibilities for that, so we will ask that you choose the word T that comes first alphabetically. A word always comes alphabetically after any proper prefix. Among two words that are not prefixes of each other, the one that comes first alphabetically is the one that has, in the first position at which they differ from left to right, a letter closest to the beginning of the alphabet. Notice that the empty word (that has zero characters) is a valid word and is alphabetically before any other word. Input The input contains several test cases. Each test case is described in a single line that contains an integer K (0 ≤ K ≤ 1000) and a non-empty word S of at most 1200 lowercase letters, separated by a single space. The last line of the input contains the number −1 and an asterisk separated by a single space and should not be processed as a test case. Output For each test case output a single line with a word T of lowercase letters such that the edit distance of S and T is at most K. If there are several words in that situation, output the one that comes first alphabetically. Example Input: 4 abcadef 1000 zero 0 zero -1 * Output: aaaaaadef zero
32,029
Feanor The Elf (FTHEELF) Feanor is an elf, and of course, he really likes arrows and bows. Surprisingly enough, Feanor has a laptop, but he knows nothing about programming, so he requires your help. Feanor lives in a tower of height H, and he loves throwing arrows from the top of it. He had a good amount of intensive training and he knows that he always throws his arrows with the same initial speed V. He wants you to make a program that given H and V returns the maximum distance that a Feanor’s arrow can reach when it hits the ground, measured from the base of the tower. With this information, he will be able to place a nice circular fence to prevent disoriented little elves from being killed. Newtonian laws apply in Feanor’s world and the gravity has the same strength as in ours. These laws can be summarized as follows: The position of Feanor is assumed to be a point. The same occurs with the position of his arrow at each moment in time. The initial speed V of the arrow can be expressed as Vx 2 + Vy 2 = V 2 , where Vx and Vy are the horizontal and vertical components of V , respectively. Speed Vx is always non- negative, while speed Vy is positive if the arrow is thrown up, and negative if the arrow is thrown down. The initial position of the arrow is the position of Feanor. The horizontal position of the arrow (relative to Feanor’s position) at time t is x(t) = Vx * t. The vertical position of the arrow (relative to Feanor’s position) at time t is y(t) = Vy * t − gt 2 / 2, where g = 9.8 m/s 2 . Input The input contains several test cases. Each test case is described in a single line that contains two integers V and H separated by a single space. The value V is the initial speed of Feanor’s arrow measured in m/s (0 ≤ V ≤ 1000), while the value H is the tower’s height in meters (0 ≤ H ≤ 1000). The last line of the input contains the number −1 twice separated by a single space and should not be processed as a test case. Output For each test case output a single line with the radius of Feanor’s fence in meters, rounded up to 6 decimal digits (he wants to be sure that he doesn’t kill those cute little elves). Example Input: 1 0 10 0 100 0 1000 0 -1 -1 Output: 0.102041 10.204082 1020.408163 102040.816327
32,030
G Key (GK) Leandro and Fede are traveling by train and to spend some time they decided to start playing the guitar. They want to play together some songs, but Fede’s memory is not working well because he caught a little cold. To work it out, Leandro wants to show to Fede some music scores of several punk rock songs. A punk rock song is a sequence of notes, and there are twelve possible notes, divided in two groups. The first group has seven natural notes called A, B, C, D, E, F and G, while the second group has five alterations called A#, C#, D#, F# and G#. The way to draw a music score is as follows: you start with an empty one, and then you draw note by note from left to right in the same order they appear in the song. In the following picture you can see an empty music score with two lines. The symbol at the beginning of each line is called G key. Each line is divided in four groups, each group having room for four notes. In this figure, the song “E, F, F#, G, G#, A, A#, B, C, C#, D, D#” is depicted. Can you help Leandro writing a program for drawing punk rock songs given the sequence of notes? Input The input contains several test cases. Each test case is described in a single line that contains the number of notes N (1 ≤ N ≤ 100), followed by the sequence of N notes. Each note is one of A, A#, B, C, C#, D, D#, E, F, F#, G and G#. Values in each line are separated by single spaces. The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output the music score of the input song and print a blank line after each test case (even after the last one). You have to follow the sample input and output for drawing the music scores. Every score line has the same background formed by the characters “|” (pipe) and “-” (hyphen). They differ in the borders (first and last borders are doubled), and of course in the notes they have inside. Each eighth note is drawn consecutively as in the sample, and the different heights are those shown. Alterations are preceded by a character “#” (sharp sign). There must be no trailing spaces at the end of printed lines, neither empty score lines (without notes inside). Example Input: 36 E F F# G G# A A# B C C# D D# E F F# G G# A A# B C C# D D# E F F# G G# A A# B C C# D D# -1 Output: ||                        |                        |                        |                        | ||------------------------|------------------------|--------------|\----|\--|------------------------| ||                        |                        |  |\    |\    |     |   |                        | ||------------------------|--------------------|\--|--|-----|----x|---#x|---|------------------------| ||                        |        |\    |\    |   | x|   #x|               |                        | ||--------------------|\--|--|\----|-----|----x|---|------------------------|--------------------|\--| ||        |\    |\    |   |  |    x|   #x|         |                        |        |\    |\    |   | ||--|\----|-----|----x|---|#x|---------------------|------------------------|--|\----|-----|----x|---| ||  |    x|   #x|         |                        |                        |  |    x|   #x|         | ||-x|---------------------|------------------------|------------------------|-x|---------------------| ||                        |                        |                        |                        |  |                        |                        |                        |                        |  |------------------------|--------------|\----|\--|------------------------|------------------------|  |                        |  |\    |\    |     |   |                        |                        |  |--------------------|\--|--|-----|----x|---#x|---|------------------------|--------------------|\--|  |        |\    |\    |   | x|   #x|               |                        |        |\    |\    |   |  |--|\----|-----|----x|---|------------------------|--------------------|\--|--|\----|-----|----x|---|  |  |    x|   #x|         |                        |        |\    |\    |   |  |    x|   #x|         |  |#x|---------------------|------------------------|--|\----|-----|----x|---|#x|---------------------|  |                        |                        |  |    x|   #x|         |                        |  |------------------------|------------------------|-x|---------------------|------------------------|  |                        |                        |                        |                        |  |                        |                        |                        |                        ||  |--------------|\----|\--|------------------------|------------------------|------------------------||  |  |\    |\    |     |   |                        |                        |                        ||  |--|-----|----x|---#x|---|------------------------|------------------------|------------------------||  | x|   #x|               |                        |                        |                        ||  |------------------------|------------------------|------------------------|------------------------||  |                        |                        |                        |                        ||  |------------------------|------------------------|------------------------|------------------------||  |                        |                        |                        |                        ||  |------------------------|------------------------|------------------------|------------------------||  |                        |                        |                        |                        ||
32,031
Heptadecimal Numbers (HEPNUM) The Factory of Computer Enhaced Numbers (FCEN) has asked its Development Comitee (DC) to come up with a way to handle numbers written in base 17 As everybody knows, base 17 is very important for many scientific applications, as well as for engineering and other practical uses. Numbers in base 17 can be tough, but are kind and soft if treated appropiately. Numbers in base 17 are written by using a set of 17 characters: digits 0 to 9 with their usual values, and uppercase letters A to G that have values from 10 to 16, respectively. Base 17, probably because its basement on a prime number, does not require numbers to start with a non-zero digit, so each number has many representations. For instance, the decimal number 117 can be written as 6F, but also as 06F or even 00000006F. Because of this leading-zeroes thing, heptadecimal numbers are hard to compare. As a member of the FCEN-DC, you were asked to write a program that helps in this difficult and challenging task. Input The input contains several test cases. Each test case is described in a single line that contains two non-empty strings of at most 10 5 heptadecimal digits, separated by a single space. The last line of the input contains two asterisks separated by a single space and should not be processed as a test case. Output For each test case output a single line with the sign “ < ” if the first heptadecimal number is smaller than the second one, the sign “ > ” if the first heptadecimal number is greater than the second one, or the sign “ = ” if both heptadecimal numbers are equal. Example Input: 006F B3B 0000 0 * * Output: < =
32,032
Indicator of progression (INDIPROG) When dealing with a long task, computers often provide a progress indicator to help users estimate how much longer they will have to wait. This is especially useful when copying a large number of data files from one drive to another. In the Institute of Computer Power Control (ICPC) are very concerned about their brand new file copier, which they think will change forever the way people copy files. While this is a great accomplishment for the engineers in ICPC, the lack of a progress indicator is threatening the future of the project and the well being of most computer users around the world! The Supremum Principal Director Manager of ICPC has called you personally to ensure you are up for the task. The interface provided by the developing team of the file copier only gives two integers M and N. M is the number of files that have already been copied, and N is the total number of files to be copied. Using this information, you must write a module that displays the progress indicator. The indicator must be drawn as a string of exactly 20 characters. The first K of them must be asterisks (“*”) and the rest must be hyphens (“-”). The number K must be chosen in such a way that K/20 correctly approximates M/N ; this means that the distance between the two mentioned fractions is minimum. If there is more than one possible value for K, the greatest one must be chosen. Also, for more precision, a number P without leading zeroes and followed by a percentage sign (“%”) must be written on top of the described indicator. Since the goal is to represent the finished percentage, the number P must be such that P/100 correctly approximates M/N, with the same policy as before. The finished percentage must be centered on top of the display. This means that if possible, the same number of display characters (“*” or “-”) must be seen to the left and to the right of the percentage; if this is not possible, exactly one extra character must be seen to the left. Input The input contains several test cases. Each test case is described in a single line that contains two integers M and N as explained above (0 ≤ M ≤ N ≤ 10 9 and N ≠ 0). These values are separated by a single space. The last line of the input contains the number −1 twice separated by a single space and should not be processed as a test case. Output For each test case output a single line with exactly 20 characters representing the mentioned display. Example Input: 2 5 2 6 0 10 -1 -1 Output: ********-40%-------- *******--33%-------- ---------0%---------
32,033
Headshot (HEADSHOT) You have a revolver gun with a cylinder that has n chambers. Chambers are located in a circle on a cylinder. Each chamber can be empty or can contain a round. One chamber is aligned with the gun's barrel. When trigger of the gun is pulled, the gun's cylinder rotates, aligning the next chamber with the barrel, hammer strikes the round, making a shot by firing a bullet through the barrel. If the chamber is empty when the hammer strikes it, then there is no shot but just a "click". You have found a use for this gun. You are playing Russian Roulette with your friend. Your friend loads rounds into some chambers, randomly rotates the cylinder, aligning a random chamber with a gun's barrel, puts the gun to his head and pulls the trigger. You hear "click" and nothing else - the chamber was empty and the gun did not shoot. Now it is your turn to put the gun to your head and pull the trigger. You have a choice. You can either pull the trigger right away or you can randomly rotate the gun's cylinder and then pull the trigger. What should you choose to maximize the chances of your survival? Input The input first line contains a single line with a string of n digits " 0 " and " 1 " (2 ≤ n ≤ 100). This line of digits represents the pattern of rounds that were loaded into the gun's chambers. " 0 " represent an empty chamber, " 1 " represent a loaded one. In this representation, when cylinder rotates before a shot, the next chamber to the right gets aligned with the barrel for a shot. Since the chambers are actually located on a circle, the first chamber in this string follows the last one. There is at least one "0" in this string. Output Write to the output single one of the following words (without quotes): " SHOOT " - if pulling the trigger right away makes you less likely to be actually shot in the head with the bullet (more likely that the chamber will be empty). " ROTATE " - if randomly rotating the cylinder before pulling the trigger makes you less likely to be actually shot in the head with the bullet (more likely that the chamber will be empty). " EQUAL " - if both of the above choices are equal in terms of probability of being shot. Example Input: 0011 Output: EQUAL Input: 0111 Output: ROTATE Input: 000111 Output: SHOOT
32,034
Garden 2005 (IOIGARD) Byteman owns the most beautiful garden in Bytetown. He planted n roses in his garden. Summer has come and the flowers have grown big and beautiful. Byteman has realized that he is not able to take care of all the roses on his own. He has decided to employ two gardeners to help him. He wants to select two rectangular areas, so that each of the gardeners will take care of the roses inside one area. The areas should be disjoint and each should contain exactly k roses. Byteman wants to make a fence surrounding the rectangular areas, but he is short of money, so he wants to use as little fence as possible. Your task is to help Byteman select the two rectangular areas. The garden forms a rectangle l meters long and w meters wide. It is divided into l · w squares of size 1 meter × 1 meter each. We fix a coordinate system with axes parallel to the sides of the garden. All squares have integer coordinates (x, y) satisfying 1 ≤ x ≤ l, 1 ≤ y ≤ w. Each square may contain any number of roses. The rectangular areas, which must be selected, should have their sides parallel to the sides of the garden and the squares in their corners should have integer coordinates. For 1 ≤ l1 ≤ l2 ≤ l and 1 ≤ w1 ≤ w2 ≤ w, a rectangular area with corners (l1, w1), (l1, w2), (l2, w1) and (l2, w2): contains all the squares with coordinates (x, y) satisfying l1 ≤ x ≤ l2 and w1 ≤ y ≤ w2, and has perimeter 2 · (l2 − l1 + 1) + 2 · (w2 − w1 + 1). The two rectangular areas must be disjoint, that is they cannot contain a common square. Even if they have a common side, or part of it, they must be surrounded by separate fences. Write a program, that: reads from the standard input the dimensions of the garden, the number of roses in the garden, the  number of roses that should be in each of the rectangular areas, and the positions of the roses. finds the corners of two such rectangular areas with minimum sum of perimeters that satisfy the given conditions. writes to the standard output the minimum sum of perimeters of two non-overlapping rectangular areas,  each containing exactly the given number of roses (or a single word NO, if no such pair of areas exists). Input The first line of standard input contains two integers: l and w (1 ≤ l, w ≤ 250) separated by a single space — the length and the width of the garden. The second line contains two integers: n and k (2 ≤ n ≤ 5000, 1 ≤ k ≤ n/2) separated by a single space — the number of roses in the garden and the number of roses that should be in each of the rectangular areas. The following n lines contain the coordinates of the roses, one rose per line. The (i+2)-nd line contains two integers li, wi (1 ≤ li ≤ l, 1 ≤ wi ≤ w) separated by a single space — the coordinates of the square containing the i-th rose. Two or more roses can occur in the same square. Output The standard output should contain only one line with exactly one integer—the minimum sum of perimeters of two non-overlapping rectangular areas, each containing exactly k roses, or a single word NO, if no such pair of areas exists. Example Input: 6 5 7 3 3 4 3 3 6 1 1 1 5 5 5 5 3 1 Output: 22
32,035
Palindrome 2000 (IOIPALIN) A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome. As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome. Input The first line contains one integer: the length of the input string N, 3 ≤ N ≤ 5000. The second line contains one string with length N. The string is formed from uppercase letters from ‘A’ to ‘Z’, lowercase letters from ‘a’ to ‘z’ and digits from ‘0’ to ‘9’. Uppercase and lowercase letters are to be considered distinct. Output The first line contains one integer, which is the desired minimal number. Example Input: 5 Ab3bd Output: 2
32,036
Boundary 2003 (IOIBOUND) Farmer Don watches the fence that surrounds his N meter by N meter square, flat field (2 ≤ N ≤ 500,000). One fence corner is at the origin (0, 0) and the opposite corner is at (N,N); the sides of Farmer Don's fence are parallel to the X and Y axes. Fence posts appear at all four corners and also at every meter along each side of the fence, for a total of 4×N fence posts. The fence posts are vertical and are considered to have no radius. Farmer Don wants to determine how many of his fence posts he can watch when he stands at a given location within his fence. Farmer Don’s field contains R (1 ≤ R ≤ 30,000) huge rocks that obscure his view of some fence posts, as he is not tall enough to look over any of these rocks. The base of each rock is a convex polygon with nonzero area whose vertices are at integer coordinates. The rocks stand completely vertical. Rocks do not overlap, do not touch other rocks, and do not touch Farmer Don or the fence. Farmer Don does not touch the fence, does not stand within a rock, and does not stand on a rock. Given the size of Farmer Don's fence, the locations and shapes of the rocks within it, and the location where Farmer Don stands, compute the number of fence posts that Farmer Don can see. If a vertex of a rock lines up perfectly with a fence post from Farmer Don's location, he is not able to see that fence post. Input The first line of input contains two space-separated integers: N and R. The next line of input contains two space-separated integers that specify the X and Y coordinates of Farmer Don's location inside the fence. The rest of the input file describes the R rocks: Rock i’s description starts with a line containing a single integer pi (3 ≤ pi ≤ 20), the number of vertices in the rock's base. Each of the next pi lines contains a space-separated pair of integers that are the X and Y coordinates of a vertex. The vertices of a rock’s base are distinct and given in counterclockwise order. Output The output file should contain a single line with a single integer, the number of fence posts visible to Farmer Don. Example Input: 100 1 60 50 5 70 40 75 40 80 40 80 50 70 60 Output: 319
32,037
Test (CF25E) Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s 1 , the second enters an infinite loop if the input data contains the substring s 2 , and the third requires too much memory if the input data contains the substring s 3 . Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions? Input There are several test cases. For each test case there are exactly 3 lines. The i -th line contains string s i . All the strings are non-empty, consists of lowercase Latin letters, the length of each string doesn't exceed 10 5 . Output For each test case output one number — what is minimal length of the string, containing s 1 , s 2 and s 3 as substrings. Example Input : ab bc cd abacaba abaaba x Output: 4 11
32,038
Termites strike back (TERMITES) Princess Bala and Z founded a new colony where ants are free to express their own beliefs. The new colony, however, now faces a serious threat to its survival. Acid-shooting termites have become stronger and are willing to attack the nest. Z needs to develop a defence strategy for the colony. Queen Ant, Princess Bala's mother, tells him that at least twelve ants are needed to successfully kill a single termite. Unfortunately, the number of soldiers has had a significant decrease since the new freedom ideals were spread out. Thus, he decides that no more ants than needed will participate in the battle. In order to create a safety perimeter, soldiers need to be set in concentric rings around the colony's nest. The number of warriors of the innermost ring must be a multiple of four. Besides, to coordinate the defence each ring must have exactly 8 ants more than the ring it surrounds. Taking into account these constraints, the number of rings must be as large as possible. Z's friend, Weaver, has been sent to the enemy's territory to spy them and gather vital information about their plans. Being successful, he will inform Z the exact number of warriors they are going to send. Given this information Ant Z needs all the help you can provide him to determine the best deployment for his troops. Input The input consists of several test cases, each one in a single line. Each test case consists of the number of termites n (1 <= n < 2 32 ) willing to attack the nest. The input terminates when n = 0. Output For each test case, indicate the number of soldiers needed on the outmost defence ring. Example Input: 1 2 33 0 Output: 12 16 76
32,039
Pizza (EGYPIZZA) Abotrika is having a party because his team won the African cup so he is inviting his friends to eat some pizza. Unfortunately, his friends can't eat an entire pizza but all of them know exactly how much pizza they can eat and insist on getting the exact amount of pizza but Abotrika eats one complete pizza and all of them wants his amount of pizza in one slice. Their requests break down to three different pizza slices-either one quarter or a half or three quarters of pizza. Write a program that will help Abotrika to find out what is the minimal number of pizzas he has to order so that everyone gets exact amount of pizza they want. Input First line contains an integer N , 0 ≤ N ≤ 10 000, the number of friends. In each of next N lines there is amount of pizza that each of Abotrika's friends wants to eat, that is the fraction 1/4, 1/2 or 3/4. Output In the first and only line you should write the minimal number of pizzas Abotrika has to order don't forget to order one complete pizza for Abotrika. Example 1 Input: 3 1/2 3/4 3/4 Output: 4 Example 2 Input: 5 1/2 3/4 1/2 1/4 1/4 Output: 4
32,040
Axis of Symmetry (AXIS) Given a point p and a line L on the plane, the reflection of p against L is a point q such that the segment pq is perpendicular to L and its middle point is on L. If p is on L, then p = q. Given a set of points on the plane, an axis of symmetry is a line on the plane such that the reflection of any point of the set against that line gives a point of the set. In this problem you are given a set of points on the plane, and you must decide whether there exists at least one axis of symmetry or not. Input The input contains several test cases, each one described in several lines. The first line of each test case contains an integer N indicating the number of points in the set (3 ≤ N ≤ 1000). Each of the next N lines describes a different point of the set using two integers X and Y separated by a single space (−2000 ≤ X, Y ≤ 2000); these numbers represent the coordinates of the point in the XY plane. You may assume that no two points of each test case have the same location. The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output a single line with an uppercase “Y” if there exists at least one axis of symmetry for the provided set of points, or an uppercase “N” otherwise. Example Input: 4 -10 0 10 0 10 10 10 -10 4 -10 0 10 1 10 10 10 -10 6 -1000 30 -100 20 -10 10 1000 30 100 20 10 10 -1 Output: Y N Y
32,041
Bye Bye Cakes (BYECAKES) John is moving to a different city and he wants to use all his perishable food before doing it, to avoid wasting. Luckily all he has now is eggs, flour, sugar and milk, so he is going to make his famous cakes and give them to his friends as a goodbye gift. John only knows how to make an entire cake and not half a cake, a third of a cake, or any other portion. So, he will buy whatever is needed of each ingredient so that he can make an integer number of cakes and have nothing left. Of course, he wants to spend as little money as possible. You must help John to decide how much he should buy of each ingredient. Input The input contains several test cases. Each test case is described in a single line that contains eight integers E, F, S, M, E', F', S' and M' separated by single spaces. Values E and E' are numbers of eggs, F and F' are grams of flour, S and S' are grams of sugar, and M and M' are centiliters of milk. For each ingredient, X is the amount John has (0 ≤ X ≤ 1000), while X' is the amount needed to make a single cake (1 ≤ X ≤ 1000). The last line of the input contains the number −1 eight times separated by single spaces and should not be processed as a test case. Output For each test case output a single line with four non-negative integers separated by single spaces, representing the amount of each ingredient John needs to buy, in the same order and units as the input. Example Input: 2 3 4 5 1 1 1 1 3 6 9 0 1 2 3 4 -1 -1 -1 -1 -1 -1 -1 -1 Output: 3 2 1 0 0 0 0 12
32,042
Counting Pascal (COUNTPAS) Pascal’s triangle is a common figure in combinatorics. It is a triangle formed by rows of integers. The top row contains a single 1. Each new row has one element more than the previous one and is formed as follows: the leftmost and rightmost values are 1, while each of the other values is the sum of the two values above it. Here we depict the first 7 rows of the triangle. 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 Pascal’s triangle is infinite, of course, and contains the value 1 an unbounded number of times. However, any other value appears a finite number of times in the triangle. In this problem you are given an integer K ≥ 2. Your task is to calculate the number of values in the triangle that are different from 1 and less than or equal to K. Input The input contains several test cases. Each test case is described in a single line that contains an integer K (2 ≤ K ≤ 10 9 ). The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output a single line with an integer indicating the number of values in Pascal’s triangle that are different from 1 and less than or equal to K. Example Input: 2 6 -1 Output: 1 10
32,043
Dinosaur Menace (DINOSM) After a failed but interesting DNA project, a lot of dinosaurs spread over the lab devouring most of the staff. Jeff, a scientist that worked in the project, managed to survive by hiding in the southwest corner of the lab. Now that all dinosaurs are asleep, he is going to try to leave. The exit of the lab is located at the northeast corner. Jeff knows that if any of the dinosaurs wakes up, he does not stand a chance, so he needs to minimize the likelihood of that happening. For that, he wants to follow a path that maximizes the minimum distance from him to a dinosaur along the path. The length of the path is of no interest to Jeff. For this problem we consider that Jeff and the dinosaurs are points on the plane, and that Jeff’s path is a continuous curve connecting the southwest and northeast corners of the lab. As we mentioned, Jeff wants to maximize the minimum distance between this curve and the position of any dinosaur. Input The input contains several test cases, each one described in several lines. The first line of each test case contains three integers N, W, and H separated by single spaces. The value N is the number of dinosaurs in the lab (1 ≤ N ≤ 300). The values W (width) and H (height) are the size of the lab on the x and y coordinates, respectively (2 ≤ W, H ≤ 10 6 ). This means that the starting position of Jeff is at (0, 0), while the exit of the lab is located at (W, H). Each of the next N lines contains two integers X and Y separated by a single space, representing the coordinates of a different dinosaur (1 ≤ X ≤ W − 1 and 1 ≤ Y ≤ H − 1). Note that no dinosaur is located on the border of the lab. You may assume that no two dinosaurs have the same location. The last line of the input contains the number −1 three times separated by single spaces and should not be processed as a test case. Output For each test case output a single line with the maximum possible distance to the closest dinosaur. Write the result rounded to the closest number with exactly three decimal places, using the highest in case of ties, as usual. Example Input: 1 2 2 1 1 3 5 4 1 3 4 1 1 2 2 5 4 1 3 4 1 -1 -1 -1 Output: 1.000 1.581 1.803
32,044
Escape from Jail (ESJAIL) Harry is currently a prisoner of the International Common Prison for Criminals (ICPC), the most secure prison in the world. It was designed by and old gamer and as such, the prison is not necessarily closed, but only an incredibly logical and fast mind can get out. The prison is made of N chambers connected by M corridors. Each corridor connects exactly two chambers and can be traversed in any direction. Each chamber is either empty, contains a single unbreakable door, or contains a single key. No chamber contains both a door and a key. There are K doors and K keys in the whole prison. Each key opens a different door, and each door is opened by a different key. If a chamber contains a door, the corresponding key is needed to enter the chamber, regardless of which corridor was used to reach it. Harry found the complete map of the prison, including the location of each door and each key, and wants to know how to get out that hell hole. According to the map, Harry is now in chamber number 1, and the exit is in chamber N . Given the information on the map, let Harry know if it is possible to escape or if he is doomed forever. Input The input contains several test cases, each one described in several lines. The first line of each test case contains three integers N , K, and M separated by single spaces. The value N is the number of chambers in the prison (4 ≤ N ≤ 10 5 ); each chamber is identified by an integer number between 1 and N . The value K is the number of doors and keys (1 ≤ K ≤ N/2), while M is the number of corridors (1 ≤ M ≤ 10 5 ). Each of the next K lines describes a door and its corresponding key using two integers A and B separated by a single space, with the following meaning: chamber A contains the key that opens the door in chamber B (2 ≤ A, B ≤ N − 1). The last M lines of the test case describe the corridors. Each of these lines contains two integers C and D separated by a single space, indicating that there is a corridor connecting chambers C and D (1 ≤ C < D ≤ N ). You may assume that no two corridors connect the same pair of chambers. The last line of the input contains the number −1 three times separated by single spaces and should not be processed as a test case. Output For each test case output a single line with an uppercase “Y” if it is possible for Harry to escape from the prison, or an uppercase “N” otherwise. Example Input: 4 1 4 2 3 3 4 2 3 1 3 2 4 6 2 5 5 4 3 2 2 6 2 5 1 4 1 5 3 4 4 1 1 3 2 2 3 -1 -1 -1 Output: N Y N
32,045
Falta Envido (FALTAENV) Envido is an important part of the typical Argentinian game Truco. It is even more important when Falta Envido is called, because in this case the winner of the Envido wins the entire game. In this problem you are asked to calculate the envido advantage of a cheater. Truco is played with a limited deck of spanish cards. This deck contains four suits: espada, basto, copa and oro. There are 10 cards of each suit: 1, 2, 3, 4, 5, 6, 7, 10, 11 and 12. Cards 10, 11 and 12 have an envido value of 0, while the envido value for any of the other cards is simply its number. Each player holds three cards. The winner of an Envido is the player with the higher envido score. When calculating his envido score each player can either: select a single card and have as envido score the envido value of the card; or select two cards of the same suit and have as envido score 20 plus the sum of the envido value of each selected card. Players always select the card or cards that yield the highest envido score. For instance, a player having a 10 and a 2 of the same suit, together with a 5 of a different suit, would inform an envido score of 22 because 20 + 0 + 2 = 22. A cheater playing Truco thinks that he can change one of his three cards without anybody else in the table noticing. If he changes more than one card, he surely will be discovered, so he does not do that. Since even changing one card is risky, he only does it when the envido score of the resulting hand is much higher than the one of his original hand. Given the cards the cheater has in hand, you must calculate the maximum increase he can get in the envido score by exchanging one of his cards with a card from the deck. Notice that the resulting hand must be formed by two of his original cards and one new card selected from the deck, and that he cannot have two equal cards (same number and suit). Input The input contains several test cases. Each test case is described in a single line that contains six values N1, S1, N2, S2, N3, and S3 separated by single spaces. Each pair (Ni , Si) describes a card in the hand of the cheater (1 ≤ i ≤ 3), where Ni is the number of the card (1, 2, 3, 4, 5, 6, 7, 10, 11 or 12), and Si is its suit (espada, basto, copa or oro). You may assume that the three cards are different. The last line of the input contains three times the number −1 and an asterisk, with the six values separated by single spaces, and should not be processed as a test case. Output For each test case output a single line with an integer representing the maximum increase in the envido score that can be obtained by replacing exactly one card of the input hand. Example Input: 12 espada 10 basto 11 basto 7 espada 1 oro 2 oro 7 espada 1 oro 6 espada -1 * -1 * -1 * Output: 7 10 0
32,046
Guess the Number (GUESSTHE) You are playing the funny game “Guess the number” with a friend. In this game, one of the players choose a positive integer and the other has to guess it by using the clues that are revealed. The i-th clue is either “Y” or “N” indicating whether the hidden number is a multiple of i or not, respectively. For instance, if the clues so far are “YYNYY” it means that the number is a multiple of 1, 2, 4 and 5, but it is not a multiple of 3. Given the clues of the game so far, you have to guess the minimum possible number according to them, or call your friend a cheater if there is no number such that the clues were correctly given. Input The input contains several test cases. Each test case is described in a single line that contains a non-empty string of at most 20 characters. The string is formed entirely of uppercase letters “ Y ” and “ N ”, and represents the clues given so far, in order from left to right. The last line of the input contains a single asterisk and should not be processed as a test case. Output For each test case output a single line with the minimum positive integer that satisfies all the clues, or −1 if there is no such a number. Example Input: YYNYY YYYNNN * Output: 20 -1
32,047
Hexagonal Board (HEXBOARD) Square boards (as the chessboard) are really common among games and luckily, they are easy to draw with the help of a ruler. However, there exist other games that require hexagonal boards, that are much harder to draw by hand. The Institute for Client Permanent Comfort (ICPC) of a famous board game factory has decided to provide their customers with an automated program to build hexagonal boards for several games. The size of an hexagonal board is determined by a single integer N that indicates how many cells there are in each of the 6 sides of the board. For example, a board of size N = 2 should look as follows when drawn by the program. _ _/ \_ / \_/ \ \_/ \_/ / \_/ \ \_/ \_/ \_/ Your task is to help ICPC in making the program. Input The input contains several test cases. Each test case is described in a single line that contains an integer N representing the size of the board (1 ≤ N ≤ 20). The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output the hexagonal board of the required size, and a line with exactly three asterisks. You have to follow the sample input and output, as well as the example given above. Use only regular spaces, underscores (“_”), slashes (“/”) and backslashes (“\”). There must be no trailing spaces at the end of printed lines, neither empty lines. Example Input: 1 3 -1 Output: _ / \ \_/ *** _ _/ \_ _/ \_/ \_ / \_/ \_/ \ \_/ \_/ \_/ / \_/ \_/ \ \_/ \_/ \_/ / \_/ \_/ \ \_/ \_/ \_/ \_/ \_/ \_/ ***
32,048
Integral Maximization (INTEGMAX) A set of points on the XY plane, all of them with different x coordinate, defines a polygonal line in the following way: sort the points in increasing order of their x coordinates, and connect each point with its neighbors. The integral of such polygonal line is the area contained below the line and above the x axis, between the first and last values of x. For instance, the set of points {(5, 1), (3, 2), (6, 2), (2, 1)} defines the polygonal line shown in the figure; the integral of the polygonal line is the shaded area, with a value of 6. Given a set of N different values for x, and a set of N values for y, we want to pair them to form N points on the plane such that the integral of the polygonal line defined by the points is as large as possible. Input The input contains several test cases, each one described in exactly three lines. The first line of each test case contains an integer N indicating the number of points in the set (2 ≤ N ≤ 10 4 ). The second line contains N different integers Xi separated by single spaces (1 ≤ Xi ≤ 10 4 for 1 ≤ i ≤ N ); these integers represent the values of x and are given in increasing order (Xi < Xi+1 for 1 ≤ i ≤ N − 1). The third line contains N integers Yi separated by single spaces (1 ≤ Yi ≤ 10 4 for 1 ≤ i ≤ N ); these integers represent the values of y and are not given in any particular order. The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output a single line with the maximum integral of a polygonal line formed by pairing the input values, using exactly one decimal digit. Notice that one decimal digit is always enough to represent the exact value of the integral of a polygonal line defined by points with integer coordinates. Example Input: 2 1 2 1 2 4 2 3 5 6 1 2 1 2 -1 Output: 1.5 7.0
32,049
The Pharaoh Curse (CURSE) Most of the contestants managed to arrive at the Benelux Algorithm Programming Contest on time. All except those unfortunate souls who chose to use a cheap car navigation system. A couple of wrong turns led them completely off course, and now they have ended up all over the world. Consider the case of contestant J.-P. B. (who has asked to remain anonymous). After driving for countless hours he found himself beneath three miles of water in the middle of the Atlantic Ocean. He was so focused on his navigation system that he failed to look outside until he noticed that the air was getting very moist. Fortunately for this contestant there was a spare submarine under his seat, which allowed him to escape this perilous situation. Tragic as this story seems, it is not even the worst. Another contestant, whom we will simply call S, wisely decided to travel by train. Sadly, she still listened to the advice of her evil car navigation system, and this morning she took a southbound train instead of heading north. After some more bad directions she found herself locked inside a labyrinth, in the pyramid of the Egyptian pharaoh Sok-O-Ban. As any experienced adventurer knows, these ancient tombs are often riddled with traps and other mechanisms. Sok-O-Ban's final resting place was no exception. During his lifetime this pharaoh was known for his sadistic behavior, and he liked to give impossible challenges to random strangers. It is therefore no coincidence that the cavern where contestant S ended up was completely closed off, surrounded by solid rock on every side. After looking around, our protagonist S managed to draw a map of the tomb. Fortunately she found no skeletons, mummies or spiked death traps. She did discover some buttons embedded in the floor tiles. If she could press them all at the same time, then the hidden exit would open. But as soon as she would release one of the buttons, the door would close again. Besides the buttons, the walls and a few dusty floor tiles, there were also two sarcophagi filled with rocks. To accommodate the small stature of the ancient Egyptians, the sarcophagi were cubes with sides measuring 1 meter, the same size as the floor tiles. It seemed that these sarcophagi were the key to escaping: by pushing them onto the buttons the exit could be kept open. Only one small problem remained: the sarcophagi were far too heavy to move by hand and too large to climb over. Fortunately for S, the pharaoh did not anticipate the portable sarcophagus transporter she had conveniently stashed in her backpack. Attaching this reusable system to her arms allowed her to effortlessly push a sarcophagus exactly one meter straight ahead. This corresponds nicely to the 1 meter steps S used when marking out the grid in her map. Input On the first line of the input is a positive integer, the number of test cases. Then for each test case: A line containing two positive integers h, w ≤ 50, the height and width of the maze. h lines of w characters each, the map of the cavern our protagonist made, in which: '#' is a wall or otherwise impassible space. '.' is an empty space, of which there are at most 100. 'S' is our protagonist. 'X' is one of the heavy sarcophagi. There are at most two of these. 'B' is a button. 'E' is the exit. There is exactly one exit, on the edge of the map. The edge of the map contains only walls and the exit. Output For each test case: One line containing the minimum number of steps it will take S to escape the tomb, or the text "impossible" if she cannot escape. Example Input: 3 7 8 ######## #..S...# #.####.# #.#.XB.# #.####.# #......E ######## 7 8 ######## #..S...# #.####.# #.#.BX.# #.####.# #......E ######## 4 8 ##E##### #...#### #SX.XBB# ######## Output: impossible 10 19
32,050
Strange Calendar (CAL) In a galaxy, far far away, there was a planet, Gringo quite similar to our own. Maybe it is because the planet has a similar "Sun" and "Moon". In Gringo, people use a calendar which is identical to ours. It is said this calendar was made by one of many kings in Gringo's history thousands of years ago. In the legend, it says the king liked programming very much, and at one night he solved a very difficult problem. He was so happy that he wanted to make a new calendar to congratulate. Hence in his calendar, this very midnight with full moon is first second. In this calendar, names of periods of time are same to ours, like days, months, years, minutes and seconds. In Gringo planet, the planet will reach same position on its revolution around the "Sun" every T1 seconds, the time between two neighbor full moons is T2 seconds and the time between two neighbor midnights is T3 seconds. It's very clear that a year is T1 seconds and a day is T3 seconds. And luckily, T1 is divisible by T3. So a leap year is unnecessary. But T2 may be not divisible by T3, which is very troublesome. But our king was very clever, he made following rules. A new day comes when a midnight come. A new year comes when the planet reaches the same position with the "first midnight" on its revolution around the "Sun". Of course it will be a midnight and a new day will come, too. When a new day comes, if the "Moon" will be full in this day, a new month will come, too. When a new year comes, a new month will come, too. The "Moon" may not be full. So the month was called "0th month" of a year, until a new full moon come. Due to these complex rules, it is very difficult to calculate how many days in a month. Now many people in Gringo are turning to you for help. Input There are multiple test cases. The first line of input contains an integer T (T <= 20), indicating the number of test cases. Then T test cases follow. There is a blank line between different test cases. The first line of each test case contains 3 integers T1, T2 and T3 (1 <= T3 <= 10000, 5 <= T1 / T3 <= 1000, T1 is divisible by T3, T3 < T2 < T1). The next line contains an integer Q (1 <= Q <= 100). Then Q lines follow, each line contains two integer Yi and Mi, means the Mi th month in Yi th year, (1 <= Yi <= 5000, 0 <= Mi <= 5000). Output For each query, output how many days in that month. If there is no such month, output 0. Sample Input: 1 3650 295 10 4 1 1 1 2 2 0 2 13 Output: 29 30 18 0
32,051
Black or White (BORW) “ It’s Black, It’s White, It’s Tough For You To Get By ” Michael Jackson (1958-2009) You have a sequence of integers. You can paint each of the integers black or white, or leave it unpainted. The black integers must appear in ascending order and the white integers must appear in descending order. The ascending/descending order must be strict, that is, two integers painted with the same color cannot be equal. Paint the sequence so as to minimize the number of unpainted integers. Input The input contains several test cases, each one described in exactly two lines. The first line contains an integer N indicating the number of elements in the sequence (1 ≤ N ≤ 200). The second line contains N integers Xi separated by single spaces, representing the sequence to paint (1 ≤ Xi ≤ 10 6 for 1 ≤ i ≤ N ). The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output a single line with an integer representing the minimum number of unpainted elements of the sequence, when the sequence is painted optimally following the rules described above. Example Input: 8 1 4 2 3 3 2 4 1 12 7 8 1 2 4 6 3 5 2 1 8 7 -1 Output: 0 2
32,052
Closest Triplet (CLOSEST) Closest pair is an old problem that asks to find, given a set of N points in the plane, the pair that minimizes the distance between them. This problem can easily be solved using roughly N 2 operations by testing all possible pairs of points and keeping at each step the optimal pair. With a more clever approach, the problem has been solved using ∼ N log N operations. Closest triplet is an analogous problem which also takes a set of N points as input, and asks for the triplet (group of three points) that minimizes the sum of the three distances between each pair of them. In this case there is also a trivial solution that tests all possible triplets using roughly N 3 operations. However, since you are a clever programmer, we are confident that you are able to find a better algorithm. Input The input contains several test cases, each one described in several lines. The first line contains an integer N indicating the number of points in the set (3 ≤ N ≤ 3000). Each of the next N lines describes a different point of the set using two integers X and Y separated by a single space (1 ≤ X, Y ≤ 10 6 ); these values represent the coordinates of the point in the XY plane. You may assume that within each test case no two points have the same location. The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output a single line with a real number representing the sum of the distances between each pair of points of any closest triplet of the set of points. Round the result to the closest rational number with three decimal places. In case of ties, round up. Always use exactly three digits after the decimal point, even if it means finishing with a zero. Example Input: 4 1 1 4 1 1 5 1000 1000 9 100000 200000 200000 200000 150000 286603 60000 140000 240000 140000 150000 340000 1 340000 300000 340000 150000 87087 -1 Output: 12.000 300000.796
32,053
Draw Mountains (DRAWM) You are a member of a team that is working in a new wonderful graphics program. Your task is to write a module for drawing skylines of mountains. However, for now the program is in beta version, so each skyline is discretized. This means that your module receives as input a sequence of integers representing heights. Each pair of consecutive heights in the sequence may differ by at most 1 and produces a column of output, each column containing a single character. The particular character to write and its position in the column depend on the pair of heights. When both heights are equal an underscore (“ ”) must be printed. If the heigths within the pair increase or decrease, you must write a slash (“/”) or a backslash (“\”), respectively. The position of the character in the column is such that the skyline visually respect the given heights. For instance, the sequence of heights (1, 2, 3, 2, 3, 3, 2, 1, 0) must produce the skyline shown in the following figure. _ /\/ \ / \ \ Notice that when the sequence of heights has C + 1 elements, the corresponding skyline has only C columns. Given a sequence of heights, you must draw the skyline according to the rules given above. See the examples for further clarification. Input The input contains several test cases, each one described in exactly two lines. The first line contains an integer C indicating the number of columns of the skyline (1 ≤ C ≤ 70). The second line contains C + 1 integers Hi separated by single spaces representing the sequence of heights (0 ≤ Hi ≤ 30 for 1 ≤ i ≤ C + 1). You may assume that there exist an height Hi = 0, and that the difference between succesive heights is at most 1 (i.e. |Hi − Hi+1 | ≤ 1 for 1 ≤ i ≤ C). The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output the correponding skyline, followed by a line with exactly three asterisks (“***”). While writting the skyline, use only regular spaces, newlines, and the three characters mentioned in the statement. Ths skyline must be left aligned and it must contain exactly C columns. There must be no trailing spaces at the end of printed lines, neither empty lines. Example Input: 8 1 2 3 2 3 3 2 1 0 3 1 0 0 1 -1 Output: _ /\/ \ / \ \ *** \_/ ***
32,054
Elastic Bands (ELASTIC) The Institute of Circles with Perimetral Connections (ICPC) has recently discovered that several machines that were working in their diverse productive areas were totally obsolete. Of course, all machines in the Institute contain several circles. The Supreme Chief Director Manager President of the ICPC asked their Computer Aided Problem Solving department to help in overcoming this situation. They have signalled you as the maximum responsible, so you better get to work. Many machines in the Institute have mechanical parts in the shape of a circle that need to be rotated clockwise in order for the machine to work. Currently, each circular part is connected to a different electrical engine that does the job. You noted, however, that when many circles are coplanar, you can connect them with elastic bands and they will rotate all together with the energy of one engine. This marvellous idea lead you to a new problem. What’s the optimal way to connect all the circles? In general, there are many ways to place elastic bands and make all the circles be connected. Since some of the rotating power of the system is lost in the tension of the elastic bands, you want to minimize the total length of elastic bands used. Formally, the length of the elastic band that connects two circles is the perimeter of the smallest convex area that contains both circles. The total length is the sum of the lengths of all used elastic bands. Two circles can be connected with an elastic band even if the band touches or goes through any number of other circles or elastic bands. Input The input contains several test cases, each one described in several lines. The first line contains an integer N indicating the number of circles to connect (2 ≤ N ≤ 3000). Each of the next N lines describes a different circle using three integers X, Y and R separated by single spaces (1 ≤ X, Y, R ≤ 10 6 ). The values X and Y represent the coordinates of the centre of the circle in the XY plane, while the value R indicates its radius. You may assume that within each test case no two circles overlap or touch each other. The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output a single line containing a real number representing the minimum total length of elastic band needed to connect all the circles. Round the result to the closest rational number with three decimal places. In case of ties, round up. Always use exactly three digits after the decimal point, even if it means finishing with a zero. Example Input: 3 2 2 2 1 6 1 6 1 1 2 1 1 1 1 4 1 -1 Output: 35.829 12.283
32,055
Find String Roots (FINDSR) In mathematics, the N-th root of a number M, is a number K such that K N = M , i.e. KKK ... K = M where K is multiplied N times. We can translate this into strings. In string notation, the juxtaposition is concatenation instead of multiplication. So, the N-th root of a string S is another string T such that T N = S, where T N = TTT ... T is the string T concatenated N times. For instance, if S = “abcabcabcabc”, for N = 2 the string T = “abcabc” is the N-th root of S, while for N = 4 its N-th root is T = “abc”. Note that for N = 1 any string S is the N-th root of S itself. Given a string S you have to find the maximum N such that the N-th root of S exists. In the above example the answer would be 4, because there is no N-th root of S = “abcabcabcabc” for N > 4. Input The input contains several test cases, each one described in a single line. The line contains a non-empty string S of at most 10 5 characters, entirely formed of digits and lowercase letters. The last line of the input contains a single asterisk (“*”) and should not be processed as a test case. Output For each test case output a single line with the greatest integer N such that there exists a string T that concatenated N times is equal to S. Example Input: abcabcabcabc abcdefgh012 aaaaaaaaaa * Output: 4 1 10
32,056
The Clocks (CLOCKS) |-------| |-------| |-------| | | | | | | | |---O | |---O | | O | | | | | | | |-------| |-------| |-------| A B C |-------| |-------| |-------| | | | | | | | O | | O | | O | | | | | | | | | | |-------| |-------| |-------| D E F |-------| |-------| |-------| | | | | | | | O | | O---| | O | | | | | | | | | |-------| |-------| |-------| (Figure 1) G H I There are nine clocks in a 3*3 array (figure 1). The goal is to return all the dials to 12 o'clock with as few moves as possible. There are nine different allowed ways to turn the dials on the clocks. Each such way is called a move. Select for each move a number 1 to 9. That number will turn the dials 90' (degrees) clockwise on those clocks which are affected according to figure 2 below. Move Affected clocks 1 ABDE 2 ABC 3 BCEF 4 ADG 5 BDEFH 6 CFI 7 DEGH 8 GHI 9 EFHI (Figure 2) Input Read nine numbers from standard input. These numbers give the start positions of the dials. Each number represents a time according to following table: 0 = 12 o'clock 1 = 3 o'clock 2 = 6 o'clock 3 = 9 o'clock Output Write to the standard output the shortest sequence of moves (numbers), which returns all the dials to 12 o'clock. In case there are many solutions, write the solution which is the least in lexicographic order. Example Input: 3 3 0 2 2 2 2 1 2 Output: 4 5 8 9 Although not the solution, a longer sequence of valid moves is illustrated below: 3 3 0 3 0 0 3 0 0 0 0 0 0 0 0 2 2 2 5-> 3 3 3 8-> 3 3 3 4 -> 0 3 3 9-> 0 0 0 2 1 2 2 2 2 3 3 3 0 3 3 0 0 0
32,057
Training for final (TRIKA) Abotrika is a famous player who plays in a good team. His team is going to play the final match next week and he have to train hard because all his fans are expecting that Abotrika will score more than one goal, so his team-mates suggested helping him in training given that Abotrika will play alone against all his friends in the training. Input Given two integers N,M (length and width of the training court) 2 <= N, M <= 20 and X,Y the starting point of Abotrika on the court where X is number of row and Y is number of column 1 <= X <= N, 1 <= Y <= M then P[i][j], where P is the power of each of his friends 0 < P[i][j] <100, and P[X][Y] is the power of Abotrika. Output The output must be one line either " N " or " Y " then the maximum power "Abotrika can get when he pass from his friends to reach the (the goal who is at the cell P[N][M] in the court ). NOTE : Abotrika's power decreases by the power of his team-mate whom Aboutrika succeeded to get through on his way to score a goal. " Y " means that he had scored a goal with power at least 0 and " N " if he couldn't reach the goal with zero power at least. Also, Abotrika can only move in two directions -- right and down -- to reach the goal. Example Input: 4 4 1 1 100 55 10 2 20 10 90 1 60 20 22 4 1 30 70 5 Output: Y 23 Explanation : The maximum power Abotrika can get after reaching goal : 100 - (55+10+2+1+4+5) = 23 Input: 2 2 1 1 1 55 20 10 Output: N Explanation : The maximum power Abotrika can get after reaching goal : 1 - (20+10) = -29 so it will be N.
32,058
Garbage Collection (GARBAGE) A big office uses a cleaning robot to empty the trash can in every cubicle. The surface of each cubicle is a square and the office floor plan is organized as a rectangular matrix of R rows of C cubicles each. The cleaning process begins by the robot entering the floor by a door that accesses the topmost leftmost cubicle, and finishes with the robot exiting using the same door. Both entering and leaving take 26 seconds each. When the cleaning robot is in a cubicle it can empty the trash can using 13 seconds. The robot can also move to a cubicle that shares a side with its current location, using 38 seconds. The robot needs to enter in each cubicle at least once to empty its trash can. The total time the robot takes for the entire process depends on the actual tour through the different cubicles. Among all possible tours, we are interested in those of minimum time. Given the description of the office, you must indicate the minimum time required for the entire cleaning process (including entering, leaving, emptying the trash can in every cubicle, and moving around). Notice that it is possible that an optimal tour passes through a cubicle several times, but the robot has to take the time to empty the trash can only once. Input The input contains several test cases, each one described in a single line. The line contains two integers R and C separated by a single space, representing the number of rows and cubicles per row, respectively (1 ≤ R, C ≤ 100). The last line of the input contains the number −1 twice separated by a single space and should not be processed as a test case. Output For each test case output a single line with an integer representing the minimum number of seconds that the robot needs to complete the cleaning process. Example Input: 4 2 3 3 -1 -1 Output: 460 549
32,059
Homework (HOMEW) When trying to clean your old room, you find out your old notes from high school. Reading the homeworks you were given then, you start thinking how much easier they would have been today. However, there is a particular one that still seems to maintain its difficulty. When the solution to a problem involved solving the square root of an integer, to keep a fancy and clean expression, you were asked to express it as the integer part and the root part. This means that if you had as solution N you were asked to express it as √N = A √B with the part A being as high as possible. For instance, 180 can be expressed as 1 √180, 2 √45, 3 √20 or 6 √5. Of course, the last expression is the correct one. Now that you are grown up, you decide to write a program to perform this task for you. Input The input contains several test cases, each one described in a single line. The line contains an integer N (1 ≤ N ≤ 10 18 ). The last line of the input contains a single −1 and should not be processed as a test case. Output For each test case output a single line with two integers A and B separated by a single space such that √N = A √B and A is maximum. Example Input: 180 17 1000000000000000000 -1 Output: 6 5 1 17 1000000000 1
32,060
Inversion Sort (INVESORT) You have just bought an old fashioned jukebox that can hold 10 music albums. Albums are maintained as a sequence, each album represented by a unique lowercase letter between “a” and “j”, inclusive. The jukebox allows you to select a subsequence of contiguous albums and a mechanical arm inverts that part of the sequence. For instance, if the current sequence is “abcdefghij” and you select the subsequence “bcd”, the result of the inversion would be “adcbefghij”. Soon you notice that it is possible to get the albums into any desired order using simply inversions. However, you are interested in doing so with the minimum number of operations. Given the current order and a desired order of the 10 music albums, find the minimum number of inversion operations needed to obtain the desired order. Input The input contains several test cases, each one described in a single line. The line contains two strings C and D separated by a single space, representing the current and desired orders of the music albums, respectively. Each of the strings has exactly 10 characters and contains the characters of “abcdefghij” in some order. The last line of the input contains two asterisks (“*”) separated by a single space and should not be processed as a test case. Output For each test case output a single line with an integer representing the minimum number of inversions needed to transform the current order given by C, into the desired order given by D. Example Input: abcdefghij adcbefghij abcdefghij abcdefghij bcdaefghji beagfcdhji * * Output: 1 0 2
32,061
Cells (IPCELLS) Tim loves spreadsheets. Everything he does on a computer, he does in a spreadsheet. Track his expenses? Create a spreadsheet! Decide which car to buy? Create a spreadsheet to compare them! Make an inventory of his games? Create a spreadsheet! Decide which girl he loves most? … Unfortunately his spreadsheet software just crashed and he needs some of the data right now and does not have the time to install a competing office suit. Given the formulas used in the cells of a spreadsheet, calculate the values of all the cells. Input The first line of the input file contains an integer T specifying the number of test cases. Each test case is preceded by a blank line. Each test case starts a single number N giving the number of expression. Each of the following N lines contains a single cell formula of the form “ CELL = EXPRESSION ”, where CELL is the name of the cell and EXPRESSION is a mathematical expression consisting of cell names and the operators +, -, * and /. A cell name is a non-empty sequence of letters followed by a positive integer. Each test case is correct: there are no cycles, and all cells referenced in expressions have definitions. Evaluating expressions When evaluating an expression, usual priorities apply: first we evaluate all * and / (left to right), and only then all + and - (again, left to right). You may assume that the expressions are such that when evaluating the expression in correct order, the result and also all intermediate values will fit into 32-bit signed integer variables. The operator / represents integer division which is always rounded down . The dividend will always be non-negative and the divisor will always be positive. Output For each test case output the calculated values of cells, one per line, in the form “ CELL = VALUE ”. The rows in the output should be ordered alphabetically. (To compare two rows, take a look at the first character where they differ. The one with a smaller ASCII value goes first.) Optionally, output a blank line between test cases. Example Input: 2 3 A47 = 5 + ZZ22 ZZ22 = 3 A9 = 13 + A47 * ZZ22 2 A1 = 4 / 7 + 4 / 7 B2 = 3 * 3 / 7 Output: A47 = 8 A9 = 37 ZZ22 = 3 A1 = 0 B2 = 1
32,062
Playground (PLYGRND) George has K ≤ 20 steel wires shaped in the form of half-circles, with radii a 1 , a 2 ... a K . They can be soldered (connected) at the ends, in any angle. Is it possible for George to make a closed shape out of these wires? He does not have to use all the wires. The wires can be combined at any angle, but may not intersect. Beware of floating point errors. Input Each data set consists of a number 0 < K ≤ 20 on a line by itself, followed by a line of K space-separated numbers a i . Each number is in the range 0 < a i < 10 7 , and has at most 3 digits after the decimal point.  The input will be terminated by a zero on a line by itself. Output For each test case, there should be one word on a line by itself; “YES” if it is possible to make a simple connected figure out of the given arcs, and “NO” if it isn’t. Example Input: 1 4.000 2 1.000 1.000 3 1.455 2.958 4.424 7 1.230 2.577 3.411 2.968 5.301 4.398 6.777 0 Output: NO YES NO YES
32,063
Chess part1 (ROOKS) Two rooks are to be placed on a chess like N×N game board. Each square contains a single non negative integer. The rooks must be placed on different squares. We say that some squares on the board are attacked if that square in the same row or same column with the rook but squares containing rooks are not attacked. We want to place our rooks so that the total sum of the numbers of all attacked squares is as large as possible. write a program that will find this maximum sum. Input The first line on input will contain N, 2 <= N <= 300. Each of the following N lines has N integers. Each number will be greater than or equal to zero and less than 1000, these are the numbers on the board. Output The only line should contain a single integer – the maximum sum from the task description. Example Input: 3 0 1 4 3 0 2 1 4 1 Output: 15
32,064
Perfume (PERFUME) One of the largest perfume shops is making perfumes by mixing fragrant essential oils with other compounds. The shop representative told you that what really matters in the mixture is the percentages of two main components (call them A and B), all other stuff is complementary. For example their first sold perfume had 10% of component A and 35% of component B, while the most successful one had 16% of A and 20% of B. Sometimes the store needs to create a new mixture with specific percentages of A and B and they wonder if this can be achieved by mixing some of the mixtures they already have and this is where they need your help. For example a new mixture which has 12% of A and 30% of B can be created by mixing the two mixtures above in the ratio 2:1, while it is impossible to create a mixture which has 13% of A and 22% of B using the same two mixtures. One of the largest perfume shops is making perfumes by mixing fragrant essential oils with other compounds. The shop representative told you that what really matters in the mixture is the percentages of two main components (call them A and B), all other stuff is complementary. For example their first sold perfume had 10% of component A and 35% of component B, while the most successful one had 16% of A and 20% of B. Sometimes the store needs to create a new mixture with specific percentages of A and B and they wonder if this can be achieved by mixing some of the mixtures they already have and this is where they need your help. For example a new mixture which has 12% of A and 30% of B can be created by mixing the two mixtures above in the ratio 2:1, while it is impossible to create a mixture which has 13% of A and 22% of B using the same two mixtures. Input The first line contains T <= 100, the number of test cases. The first line of each test case contains an integer (1 <= N <= 200), the number of mixtures the shop already has. The next N lines each contain two floating point numbers (0 <= A, B <= 100, A+B <= 100) representing the percentages of components A and B in each mixture. The next line contains an integer (1 <= Q <= 5151) the number of mixtures to verify. The next Q lines each contain two floating point numbers (0 <= A, B <= 100, A+B <= 100) representing the percentages of components A and B in each new mixture. Test cases are separated by one or more empty lines. Output For each mixture query print "Yes" if the new mixture can be created from the already existent ones or "No" otherwise. Print a blank line between test cases. Example Input: 2 2 10.0000 35.0000 16.0000 20.0000 2 12.0000 30.0000 13.0000 22.0000 3 10 35 16 20 7 15 1 13 22 Output: Yes No Yes
32,065
Blocks for kids (PBOARD) Wango is a brilliant maths teacher. He has two sons Kango and Dango. They are born two years apart on the same day! Kango is 9 and Dango is 7. Their birthdays are approaching again. Wango has to buy them a gift each. After long thought, this time Wango wanted to give each of his sons a piece of the Pango board and thus introduce them to higher mathematics. A size n (n >= 0) Pango board is a 2 by n rectangle of unit squares. A pango board has to be tiled with Pango pieces. Any tiling with the Pango pieces is acceptable. A size 0 Pango board exists and is unique and serves as an example of the empty set. Four types of Pango pieces are available. 1      2     3      4 ==    ==   ==    == XX    X    X      X XX    XX  X Picture of the four kinds of pieces When Wango presents a board to Kango or Dango, he has to tile the board completely with these pieces (unlimited number of pieces of each type are available) and then give them out. Note that pieces cannot be rotated for tiling. To cut costs (recession mind you), Wango decides to buy a single board of size N, then choose a k (0 <= k <= N), and give a size k board to Kango and a size (N-k) board to Dango, (tiled of course). Help him find the number of ways he can give the presents. Two ways are distinct if and only if either Dango gets a different board or Kango gets a different board. Two Pango boards are considered the same if and only if they have the same tiling (same set of tiles at the same places) from left to right (rotation of board is not allowed in comparing). Input The input consists of a sequence of cases, one per line. Each case consists of one integer N (0 <= N <= 1000,000,000) representing the size of the board which Wango is going to buy. The input will end with a line containing -1. This case should not be processed. There will be a maximum of 10000 test cases. Output One line per case, outputting the number of ways Wango can distribute the presents to his sons modulo 10,007. Example Input: 0 1 2 -1 Output: 1 4 16 Explanation Number of different 0-sized Pango boards = 1 Number of different 1-sized Pango boards = 2 Number of different 2-sized Pango boards = 6 For N = 0, he has to give 0-sized boards to both his sons. He can do this in 1*1 = 1 way For N = 1, he has to give 0-sized board to one of his sons, and 1-sized board to the other, for a total of 2*1 + 1*2 = 4 ways For N = 2, he can give the presents in 6*1 + 2*2 + 1*6 = 16 ways.
32,066
Lexicographical Substring Search (SUBLEX) Little Daniel loves to play with strings! He always finds different ways to have fun with strings! Knowing that, his friend Kinan decided to test his skills so he gave him a string S and asked him Q questions of the form: If all distinct substrings of string S were sorted lexicographically, which one will be the K-th smallest? After knowing the huge number of questions Kinan will ask, Daniel figured out that he can't do this alone. Daniel, of course, knows your exceptional programming skills, so he asked you to write him a program which given S will answer Kinan's questions. Example: S = "aaa" (without quotes) substrings of S are "a", "a", "a", "aa", "aa", "aaa". The sorted list of distinct substrings will be: "a", "aa", "aaa". Input In the first line there is Kinan's string S (with length no more than 90000 characters). It contains only small letters of English alphabet. The second line contains a single integer Q ( Q ≤ 500), the number of questions Daniel will be asked. In the next Q lines a single integer K is given (0 < K < 2 31 ). Output Output consists of Q lines, the i-th contains a string which is the answer to the i-th asked question. Example Input: aaa 2 2 3 Output: aa aaa Edited: Some input file contains garbage at the end. Do not process them.
32,067
Light Switching (LITE) Farmer John tries to keep the cows sharp by letting them play with intellectual toys. One of the larger toys is the lights in the barn.  Each of the N (2 ≤ N ≤ 100,000) cow stalls conveniently numbered 1..N has a colorful light above it. At the beginning of the evening, all the lights are off. The cows control the lights with a set of N pushbutton switches that toggle the lights; pushing switch i changes the state of light i from off to on or from on to off. The cows read and execute a list of M (1 ≤ M ≤ 100,000) operations expressed as one of two integers (0 ≤ operation ≤ 1). The first kind of operation (denoted by a 0 command) includes two subsequent integers S i and E i (1 ≤ S i ≤ E i ≤ N) that indicate a starting switch and ending switch. They execute the operation by pushing each pushbutton from S i through E i inclusive exactly once. The second kind of operation (denoted by a 1 command) asks the cows to count how many lights are on in the range given by two integers S i and E i (1 ≤ S i ≤ E i ≤ N) which specify the inclusive range in which the cows should count the number of lights that are on. Help FJ ensure the cows are getting the correct answer by processing the list and producing the proper counts. Input Line 1: Two space-separated integers: N and M Lines 2 to M+1: Each line represents an operation with three space-separated integers: operation, S i , and E i Output Lines 1: number of queries: For each output query, print the count as an integer by itself on a single line. Example Input: 4 5 0 1 2 0 2 4 1 2 3 0 2 4 1 1 4 Output: 1 2
32,068
Number Game (NUMGAME) Arya and Bran are playing a game. Initially, two positive integers A and B are written on a blackboard. The players take turns, starting with Arya. On his or her turn, a player can replace A with A - k * B for any positive integer k , or replace B with B - k * A for any positive integer k . The first person to make one of the numbers drop to zero or below loses. For example, if the numbers are initially (12, 51), the game might progress as follows: Arya replaces 51 with 51 - 3*12 = 15, leaving (12, 15) on the blackboard. Bran replaces 15 with 15 - 1*12 = 3, leaving (12, 3) on the blackboard. Arya replaces 12 with 12 - 3*3 = 3, leaving (3, 3) on the blackboard. Bran replaces one 3 with 3 - 1*3 = 0, and loses. We will say ( A , B ) is a winning position if Arya can always win a game that starts with ( A , B ) on the blackboard, no matter what Bran does. Given four integers A 1 , A 2 , B 1 , B 2 , count how many winning positions ( A , B ) there are with A 1 ≤ A ≤ A 2 and B 1 ≤ B ≤ B 2 . Input The first line of the input gives the number of test cases, T . T test cases follow, one per line. Each line contains the four integers A 1 , A 2 , B 1 , B 2 , separated by spaces. 1 ≤ T ≤ 250. 1 ≤ A 1 ≤ A 2 ≤ 1,000,000. 1 ≤ B 1 ≤ B 2 ≤ 1,000,000. A 2 - A 1 ≤ 999,999. B 2 - B 1 ≤ 999,999. Output For each test case, output one line containing "Case #x: y", where x is the case number (starting from 1), and y is the number of winning positions ( A , B ) with A 1 ≤ A ≤ A 2 and B 1 ≤ B ≤ B 2 . Example Input: 3 5 5 8 8 11 11 2 2 1 6 1 6 Output: Case #1: 0 Case #2: 1 Case #3: 20
32,069
Digital LED Number (DIGNUM) Given a digital LED pattern of a number. You have to find the number and print it. All inputs will be valid as shown. Input Input consists of LED patterns. Each pattern is given in set of fixed number of lines. You have to read input till EOF. Output Print the number corresponding to each pattern. Example Input: _ _  _  _  _ _  _| _| _|| ||_||_ |_  _||_ |_|  | _| _     _    _   ||_ |_||_  || |   ||_|  ||_| ||_| _  _  _  _    _   ||_||_||_  ||_|   |  | | _| ||_| Output: 232095 164610 799518
32,070
Collect Diamonds (COLDIAM) Misty has won a contest in a jewellery store and now she is allowed to collect diamonds as prize. But the store manager doesn't wan't to be so generous. He has spread several diamonds on the floor and now he asks Misty to encircle them using her gold chain. After that she can exhange her chain with all the diamonds that are encircled. Misty can manage to get the gold chain of any length from her friends. But she has to minimise the length and also want to collect all the diamonds on the floor. Diamonds lying on the chain are also considered to be inside. Help her to find the minimum length of the gold chain required. Input First line of input consist of a single positive integer n <= 1000 i.e number of diamonds. Next n lines consist of two integers x,y that denotes position ( coordinates ) of diamonds on the floor.  0 =< x,y <= 1000 Output Minimum length of gold chain required so that misty can collect all the diamonds. Answer should be rounded to two places after decimal. Example Input: 4 1 0 0 1 1 1 0 0 Output: 4.44
32,071
Trees Again (CNTTREE) Given a tree, you need to count how many subtrees with diameter ≤ K exist. Input The first line contains the number of test cases T. T test cases follow. For each test case, the first line contains N and K. The following N - 1 lines contain two integers ai and bi, indicating an edge between nodes ai and bi in the tree. There is a blank line after each test case. Output Output T lines, one corresponding to each test case, containing the required answer. Example Input: 2 3 1 0 1 1 2 6 3 0 1 1 2 2 3 2 4 3 5 Output: 5 23 Constraints 1 ≤ T ≤ 100 2 ≤ N ≤ 60 0 ≤ ai, bi < N 1 ≤ K ≤ N - 1
32,072
Placing Coins on a Grid (GRIDCOIN) In how many ways can R coins be placed on an N × M grid such that each row and each column have at least 1 coin? Input The first line contains the number of test cases T. T lines follow containing 3 integers: N, M and R. (1 ≤ T ≤ 100. 1 ≤ N, M ≤ 200. 1 ≤ R ≤ N × M) Output Output T lines, one for each test case, containing the output for the corresponding test case. Output all values modulo 1000000007. Example Input: 3 1 1 1 2 1 1 2 3 3 Output: 1 0 6
32,073
Multiples of 3 (MULTQ3) There are N numbers a[0], a[1] ... a[N - 1]. Initially all are 0. You have to perform two types of operations : Increase the numbers between indices A and B (inclusive) by 1. This is represented by the command "0 A B" Answer how many numbers between indices A and B (inclusive) are divisible by 3. This is represented by the command "1 A B". Input The first line contains two integers, N and Q. Each of the next Q lines are either of the form "0 A B" or "1 A B" as mentioned above. Output Output 1 line for each of the queries of the form "1 A B" containing the required answer for the corresponding query. Sample Input: 4 7 1 0 3 0 1 2 0 1 3 1 0 0 0 0 3 1 3 3 1 0 3 Output: 4 1 0 2 Constraints 1 ≤ N ≤ 100000 1 ≤ Q ≤ 100000 0 ≤ A ≤ B ≤ N - 1
32,074
Lucky Controller (LCKYCONT) Egor works as a controller in the bus. Each day he is given a pack of tickets which he then sells. Recently he has become interested about how many tickets in the pack are lucky. He thinks that the more tickets are lucky the luckier day he will have. Now he wants to find out how lucky for him will the next day be. The numbers of all tickets consist of n digits. The ticket is considered to be lucky if the sum of the first n/2 digits equals to the sum of the last n/2 digits. Egor knows that the numbers in the pack that he will be given can start with equal probability from any number in the interval from a to b inclusive. The pack holds k tickets. The numbers in the tickets are consecutive. Help Egor find out the expected amount of lucky tickets in the pack. Input The first line of the input file contain number n - the amount of tests. The next n lines consist of three integers a, b and k (0 ≤ a ≤ b < 10 12 , 1 <= k ≤ 100000). Integers a, b and b+k consist of the same amount of digits which is equal to the amount of digits in the number of each ticket. They may start with zeroes. The number of digits in a and b is always even. Output Output the expected quantity of lucky tickets in the pack in the form of irreducible fraction. In case the result is an integer, no slash should appear in the output. Example Input: 3 0123 4567 150 10 10 20 4000 4999 11 Output: 6519/635 2 103/125
32,075
Prime Pattern (CHEFJUN) There is a very large field, colored white and divided into squares. There is a coordinate system attached to the field: y-axis goes from south to north and x-axis goes from west to east. Sides of the squares are parallel to the axes. There is a robot in the (0, 0) square. Robot starts to move in spiral as depicted. First it moves one step east and one step north. Then two steps west and two steps south. Then three steps east and three steps north, four steps west and four steps south and so on. It moves to a new square with each step. As it moves it counts squares it passes and, if the number of the square is the prime number, then the robot fills this square with black color. The (0, 0) square has the number 0. Given the coordinates of a square you are to calculate the distance from this square to the nearest to it black square. For two squares with coordinates (x1, y1) and (x2, y2) the distance between those squares is |x1-x2|+|y1-y2|.   Input Input file consists of a set of tests. The first line of the file is number T – the number of tests (T <= 500). Following T lines contains two integers each separated with a space: x and y – the coordinates of the square (-2000001 < x < 2000001, -2000001 < y < 2000001). Output For each coordinate pair in the input file you are to output the distance between this square and the nearest to it black square. Example Input: 8 0 0 1 0 1 1 0 1 3 3 -3 -3 -1 2 0 -3 Output: 1 1 0 0 1 1 2 2
32,076
Happy Days (CHEFJUL) Johnny has a pool in his garden. There are several islands in the pool. Some islands are connected by bridges. Any bridge can be removed. Every day Johnny removes some bridges so that there is only one way from any island to any other. In the evening he returns removed bridges to their places. Also he has some favorite bridges which he never removes. Johnny will be happy if he is able to make a configuration of bridges on the given day which he has never made before. You have to count the amount of days he will be happy. Of course, if the favorite bridges themselves don't satisfy the happiness condition Johnny will not be happy for even single day. Input The first line of input file contains number t the number of test cases. Then the description of each test case follows. The first line of each test case contains number n the number of islands. Islands are numbered with integers from 1 to n. Then n lines follow each containing n characters defining the connectivity matrix of those islands. Character in column x of line y will be 1 if the islands with numbers x and y are connected and 0 otherwise. The next line is number p the number of favorite bridges. The next p lines contain the pairs of islands that are connected by favorite bridges. Constraints 1 ≤ t ≤ 5 2 ≤ n ≤ 30 1 ≤ p ≤ min(6, n-1) Output For each test case print the number of days Johnny will be happy in this situation. Example Input: 1 4 0111 1011 1101 1110 2 1 2 3 4 Output: 4
32,077
Shuffle Music (SHUFFLEN) My office is quite far from my home. Every day, I go there by bus. That takes a lot of time. More over, due to traffic jams, the time to reach my office is not fixed. To make the best use of this time, I carry my music player all the time. My music player has a ‘shuffle’ mode. In that mode, the music player selects a track randomly that has not been played in that session ( before the next Shuffle ), and starts playing. It will continue doing so, until, I have stopped playing, or it has played all tracks in that session. For the purpose of this problem, you can assume that all tracks are of equal duration. To select randomly, the player keeps list of the tracks already played. That is, if I listen to one track now, from next shuffle session, that track will be marked as played. In addition, after stopping play, when it shuffles once more, to select a random track, the player always use such strategy that, selecting an old track ( already listened in any previous shuffle session ) is twice more probable than a new track ( not listened in any previous shuffle session ). I go to my office in the morning and return home at night. Performing 2 shuffles a day, one in the morning, one at night . It takes at least p minutes and at most q minutes to reach my office. The time required will always be an integer. You can assume that all travel times are equiprobable (that is, if p = 2 and q = 4, and if P(t) is the probability to reach office in t minutes, then P(2) = P(3) = P(4)). If all tracks are of 1 minute, how many days on average are required to listen to all the songs? Input First line of input contains an integer T (≤ 10053) , the number of test cases. Each test case contains 5 integers, N (1 ≤ N ≤ 75) , p1, q1, p2, q2 (0 ≤ p1, q1, p2, q2 ≤ 30, p1 ≤ q1, p2 ≤ q2) , where N is the number of songs, p1, q1 are the minimum and maximum number of songs listened during day, and p2, q2 are the minimum and maximum number of songs during night. Output For each test case, output the test case, followed by the expected number of days required to listen all songs. If it’s not possible to listen to all songs, output “IMPOSSIBLE”. The Judge used is "Ignore FP rounding up to 10^-6". Example Input: 11 1 0 1 0 1 20 0 26 1 3 10 11 21 0 0 64 0 0 1 23 48 0 0 0 0 42 18 29 6 13 29 19 25 0 0 32 0 0 8 27 75 0 1 0 1 75 0 1 0 0 75 0 0 0 1 Output: Case 1: 1.3333333 Case 2: 3.1143655 Case 3: 1.0000000 Case 4: 39.6303478 Case 5: IMPOSSIBLE Case 6: 7.1950023 Case 7: 4.7682679 Case 8: 8.1514607 Case 9: 660.4533446 Case 10: 1320.4066892 Case 11: 1320.4066892 Hint Calculate P[n][rest][q][next]. It is in this session, we have not heard the song in each n songs played, with "rest" number of songs never heard, with q minutes played so far, the probability of "next" song been played for the first time. Dp by this O (N ^ 2q ^ 2). Sum over [0, q] to get P[n][rest][qsum][next], so we can use subtraction to get interval sums. Now let 0 be day, 1 be night, then we compute dp[0][rest], dp[1][rest], the expected number of days it takes to finish all the songs if only considering day or night. dp[0][rest] is [0, rest) of dp [1][rest] and P[n][rest][qsum][next]. Using O (rest) can be calculated as as X = dp[0][rest], Y = dp[1][rest], then {X = a Y + c, Y = b X + d}. Solving this, and done. In the base case with rest = 1, use infinite geometric series to compute overall O (TN ^ 2 + N ^ 2q ^ 2).
32,078
Spheres (KULE) English version Wersja polska John has a certain number of spheres. Almost all of them have identical weight apart from one. There are a lot of them and John cannot say which one differs from the other ones by himself. You can help him to determine which sphere it is by using the pair of scales. Input/Output In the first line of the input there is one integer n [3 <= n <= 100 000] that stands for the number of spheres which John has. The spheres are numbered from 1 to n . You can give John two types of orders (just print them to standard output): WEIGHT m a 1 a 2 ... a m b 1 b 2 ... b m Weighting spheres. All numbers should be separated with a space and they stand for: m - number of spheres that should be put on one of the scales (there should be the same amount of spheres on both of the scales), a 1 a 2 ... a m - identifiers of spheres that you want John to put on the left scale and b 1 b 2 ... b m - identifiers of spheres that you want John to put on the right scale. After conducting the weighting John will tell you about the outcome (which you will be able to read from the standard input). Possible answers are LEFT - spheres on the left scale are heavier, RIGHT - spheres on the right answer are heavier, EQUAL - spheres on both scales have equal weight. After conducting the weighting John is ready right away to execute the next order. However, you should remember that if the weighting's number is too high John can become quite bored... ANSWER k Answering. This order is to give information that k is the identifier of the searched sphere; however if the sphere we are looking for is lighter than the other ones you should precede that with a '-' sign. John no longer needs you after that command (your program should end). Example John: 3 You: WEIGHT 1 1 2 John: LEFT You: WEIGHT 1 1 3 John: EQUAL You: ANSWER -2 Remark: Program should clear the output buffer after printing each line. It can be done using fflush(stdout) command or you can set the proper type of buffering at the beginning of the execution - setlinebuf(stdout).
32,079
Mastermind (MSTRMND) English version Wersja polska Task ( the rules of the game ) requires to guess the code which consists of four elements. Each element of the code can have one of six different values. The same values can appear multiple times. The code should be guessed in a maximum amount of ten tries. After guessing the code (or after using up the limit of ten tries) your program should end. Input/output During each try you give your suggestion of a correct code – you output four numbers from a range of one to six on the standard output. In the response you get a hint about which elements were typed correctly and which were not – you read four numbers and each of them can have one of those values: 1 (the number is correct), 0 (element is not in the right place) or -1 (the element is incorrect). Example You: 1 1 1 2 Judge: 1 1 -1 1 You: 3 4 5 6 Judge: -1 -1 -1 0 You: 1 1 6 2 Judge: 1 1 1 1 Remark: Program should clear the output buffer after printing each line. It can be done using fflush(stdout) command or you can set the proper type of buffering at the beginning of the execution - setlinebuf(stdout).
32,080
Shuffling (SHUFFLE1) A casino owns an expensive card shuffling machine which may shuffle up to 520 cards at a time (there are 52 cards in each deck). For convenience, we will simply label the cards 1, 2, 3 ... N where N is the total number of cards, and copies of the same card (e.g. Ace of Spades) from different decks are considered different. Unfortunately, the card shuffling machine is defective, and it always shuffles the cards the same way. The company that produces these machines is out of business because of the economic downturn. There is no one who can fix the machine, and a new machine is too expensive. Being a brilliant employee of the casino, you realized that all is not lost. You can shuffle the cards differently simply by using the machine zero or more times. For example, suppose that the machine shuffles the cards 1, 2, 3, 4 into the order 2, 3, 4, 1. If you put the cards into the machine, take the shuffled cards out and insert them into the machine again (without changing the order), you will get the order 3, 4, 1, 2. That way, it is possible to shuffle the cards in many different ways even though it may take longer. But this is not a significant issue since decks do not have to be reshuffled often, and used decks can be shuffled while other decks are being used to avoid any waiting time. Unfortunately, not all shufflings can be produced in this way in general, and you wish to know if this procedure "stack the decks" in a favorable way for the casino or the player. As a first step, you wish to know which shufflings are possible to produce, and how many times you need to use the machine on the deck in order to produce the shuffling. Input The input for each case consists of three lines. The first line consists of a single integer N indicating the number of cards to shuffle. The number of cards is a positive integer up to 520. The second line consists of the integers 1, 2 ... N listed in some order and separated by a space. The list gives the order of the shuffling performed by the machine when the input cards are ordered 1, 2 ... N. The third line is in the same format as the second line, and gives the shuffling we wish to obtain. The end of input is indicated by a line in which N = 0. Output For each case, print the smallest number of times (zero or more) you need to pass the deck through the machine to produce the desired shuffling. If it is not possible, print -1. The output for each case should be in a single line. You may assume that the answer will always fit in a 32-bit signed integer. Example Input: 4 2 3 4 1 3 4 1 2 4 2 3 4 1 1 3 2 4 10 2 1 3 5 6 7 8 9 10 4 1 2 3 9 10 4 5 6 7 8 0 Output: 2 -1 12
32,081
Iterated Bitcount Function (ITERBIT) Let f(x) be the number of 1's in the binary representation of x. We can define f^k(x) as f(x) for k = 1, and f^(k-1)(f(x)) for k > 1. Let f^*(x) be the smallest k >= 1 such that f^k(x) = 1. Given N and K, how many numbers x between 1 and N inclusive have f^*(x) = K? Input The first line contains the number of test cases T. Each of the next T lines contains two space separated numbers N and K. Output: Output one line corresponding to each test case, containing the answer for the corresponding test case. Output all answers modulo 1000000007. Sample Input: 6 1 1 2 1 3 1 3 2 13 3 20 2 Output: 1 2 2 1 3 10 Constraints 1 <= T <= 1000 1 <= N <= 10^500 1 <= K <= 10
32,082
Tree Sum (TREESUM) Let Lx denote the level of a node x in a rooted tree. Lx is 1 if x is the root, otherwise Lx = 1 + Ly, where y is the parent of x in the rooted tree. You need to calculate the sum Lx ^ K for all nodes x in the tree. Input The first line contains the number of test cases T. T test cases follow. The first line of each test case contains N and K, where N is the number of nodes in the tree. The following N - 1 lines contain two integers ai and bi, indicating an edge between nodes ai and bi in the tree. There is a blank line after each test case. Output Output N lines for each test case. The i-th line should contain the required sum if the tree is rooted at node i. Output all values modulo 1000000007. Output a blank line after each test case. Example Sample Input: 2 3 2 0 1 1 2 3 3 0 1 0 2 Sample Output: 14 9 14 17 36 36 Constraints 1 ≤ T ≤ 10 1 ≤ N ≤ 20000 1 ≤ K ≤ 20 0 ≤ ai, bi < N
32,083
Manhattan Companies (MCOMP) Everyone knows what Manhattan streets look like. For simplicity, we'll say there are two types of streets: horizontal and vertical (when seen on a map). For two junctions A and B, with coordinates (ax, ay), (bx, by) respectively, we define distance (A, B) = |ax - bx| + |ay - by|. A company in Manhattan has the following problem: we have to link N junctions by couriers in such a way that each pair of junctions can communicate through the couriers. We must use the minimal possible number of couriers to do so. Also, of all the possible solutions with the minimal number of couriers, we'll take the one that minimizes the maximum distance of assigned junction pairs over all the couriers. Input The first line of input contains a single integer: N (2 ≤ N ≤ 10 5 ). The next N lines each contains two integers: x i and y i (0 ≤ x i , y i ≤ 10 5 ). Output The first and only line of output should contain the minimal maximum distance over all the couriers defined above. Example Input: 3 0 0 0 2 2 0 Output: 2 Explanation: couriers go between junction pairs (1, 2) and (1, 3). Maximum distance is 2.
32,084
Factorial challenge (FUNFACT) Ling: Stir, let's go out and play our favorite game. Stir: I am already having fun with my first factorial program. Ling: Than I will give you a challenge on factorials. If you fail in it, you will have to come. Stir: ok... Ling gives Stir a number x and the challenge is to find the largest value of n such that n! is not greater than the largest value that can be formed by x digits. Stir is stuck with the problem and needs your help. Now, it's your turn to make sure that Stir can continue having fun with factorials. Input The first line of the input contains a number t (about 10 5 ), the number of the test cases. The next t lines contain a number x (1 ≤ x ≤ 10 9 ). Output Output a total of t lines with each line containing the value n corresponding to the input case. Example Input: 2 1 7 Output: 3 10
32,085
Activities (ACTIV) Ana likes many activities. She likes acrobatics, alchemy, archery, art, Arabic dances, and many more. She joined a club that offers several classes. Each class has a time interval in every week. Ana wants to sign up for many classes, but since they overlap in time, she looks for a subset of non-overlapping classes to attend. A subset is non-overlapping if it does not contain two classes that overlap in time. If a class starts at the time another class ends, this is not considered overlapping. Ana decided to list all the non-overlapping non-empty subsets of classes. Then she will choose the subset she likes best. In order to predict the amount of paper needed to write the list, she wants you to calculate how many of these subsets there are. Input Each test case is described using several lines. The first line contains an integer N indicating the number of classes the club offers (1 ≤ N ≤ 10 5 ). Each of the next N lines describes a class using two integers S and E that represent the starting and ending times of the class, respectively (1 ≤ S < E ≤ 10 9 ). The end of input is indicated with a line containing a single −1. Output For each test case, output a single line with a single integer representing the number of non-overlapping non-empty subsets of classes. To make your life easier, output only the last 8 digits of the result. If the result has less than 8 digits, write it with leading zeros to complete 8 digits. Example Input: 5 1 3 3 5 5 7 2 4 4 6 3 500000000 1000000000 1 500000000 1 500000000 1 999999999 1000000000 -1 Output: 00000012 00000005 00000001
32,086
Airplane Parking (PKA) During this economic crisis time, Jack has started an incredible new business related to air travel, a parking-lot for airplane. He bought a very large land to park airplanes. However the land is very narrow, so that the only way airplanes can go in or go out of the parking lot must be in the Last-In First-Out fashion (see picture below). He only has spaces in the parking lot so he cannot take some airplane at the end out so that other airplanes can move. Because of the limitation of the parking lot, it is not possible to accommodate all requests for parking. Each request consists of the planned arrival time and planned departure time, which are the times the airplane arrives at the parking lot. An example below shows a request table for 4 planes. Airplane Arrival Departure 1 1 10 2 2 5 3 3 7 4 6 9 In this case, it is possible to accommodate airplane 1, 2, and 4. But it is not possible to accommodate both airplanes 2 and 3. It is possible that different planes plan to arrive or depart the parking lot at the same time. Jack has the best crews working with him, so that they will manage to arrange the plane to the parking lot in the best way that if it is possible to park and take out the planes they will be able to do it. Consider another example. Airplane Arrival Departure 5 10 12 6 10 15 7 13 17 Although airplane 5 and 6 arrive at the same time, Jack's crews know that airplane 5 will have to be out before airplane 6, so when both airplanes arrive they put airplane 6 in first, following by airplane 5. Given a list of parking requests, you want to find the maximum number of airplanes that can be parked in this parking lot, provided that they can only depart in the Last-In First-Out fashion. Input The first line contains an integer T, the number of test cases (1 < T < 5). Each test case is in the following format. The first line starts with an integer N (1 < N < 300) denoting the number of airplanes. The next N lines describe the request table. Each line 1 + i, for 1 < i < N, contains two integer Si and Ti, (0 < Si < Ti < 1,000,000,000) which are the planned arrival time and planned departing time for airplane i. Output For each test case, you program must output a single line consisting of one integer, the maximum number of airplanes that can be parked in Jack's parking lot. Example Input: 2 4 1 10 2 5 3 7 6 9 3 10 12 10 15 13 17 Output: 3 2
32,087
Rating Hazard (PKD) A very important aspect of web portals is customer reviews. The customers can rate any product in the web portal. Generally, a customer can rate a product from one star to five star. Based on the rating of all the customers the average customer rating for a product is shown. Look at the figure on the left to get a clear idea. For example if three customers rate a product as 3 star, 4 star and 4 star respectively then the average rating will be (3+4+4)/3 = 3.67 (Rounded to two digits after the decimal point). In the figure on the left 847 customers have rated a product and 597, 189, 26, 11 and 24 customers have rated the product as 5 star, 4 star, 3 star, 2 star and 1 star respectively. So the average rating is: (Rounded to eight digits after the decimal point). Most web portals display the total number of people who have rated the product (As more people rates the product the more reliable the rating is) but do not display the numeric value of the average rating. In the web portal of warzone (A renowned web portal) the total number of customers that have rated a product (In the figure above the total 847 customers have rated the product) and the average rating is stored in two different tables. The average rating is stored, rounded to n (0 < n < 9) digits after the decimal point so its value is not always the exact average value. Unfortunately, the table that stored the total number of people that rated different products somehow got corrupted. All information available in the database now is the average rating (rounded to at most eight digits after the decimal point). They do not want to lose the huge number of customer ratings they have received throughout 10-15 years but also they cannot cheat with their customers by guessing the number of raters or voters. So from the average rating they want to determine the minimum possible number of people that rated that product. You have to help them find it out by writing a program. Input The input file can contain up to 2000 lines of inputs. Each line contains a non-negative floating- point number v (1 ≤ v ≤ 5). This number will have minimum one digit and maximum eight digits after the decimal point. If this number has n digits after the decimal point then you have to assume that the value of the average is given rounded to n digits after the decimal point. Input is terminated by a line containing a negative number. Output For each line of input produce one line of output. This line contains the serial of output followed by an integer T which denotes the minimum number of voter that is required for this average rating. Example Input: 1.15 4.56316411 4.56316 3.67 3.66 -1.00 Output:   Case 1: 13 Case 2: 847 Case 3: 190 Case 4: 3 Case 5: 29
32,088
Repair Depots (PC8H) RoboCorp Oregon has already deployed several of its PoliceBots throughout the state, and suddenly they have remembered the importance of being able to repair these bots when they break. They are willing to build only a limited number of repair depots in the state, and they want to locate these depots so that each PoliceBot's city is within a given distance of some depot. You are given the locations of where the n (1 ≤ n ≤ 16) PoliceBots have been deployed, and the maximum number (1 ≤ c ≤ n) of repair depots that RoboCorp is willing to construct. Your job is to locate these repair depots to minimize the distance any bot has to be transported for repair, and return what that maximum distance is. You can assume that any bot can be repaired at any depot. Input The first line contains the integer t (1 ≤ t ≤ 350), the number of cases. Each case starts with a line containing n and c. Following this line is one line per deployed bot; that line contains two floating point values, separated by a single space, giving the Cartesian coordinates of the bot. Each such value will be between 0.0 and 10.0, inclusive (NOTE: the Sample Input shows integer values for brevity). Output You are to print for each input set the minimum value that can be obtained, such that each PoliceBot is within that distance of some depot. You should print your result with at least one digit before and exactly six digits after the decimal point; your value should be within 5e-7 of the true result. To make round-off error less of a concern, the true result will never have a 4 or a 5 as the seventh digit after the decimal point. Example Input: 2 9 3 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 4 2 0 0 1 1 2 4 3 9 Output:   1.000000 2.236068
32,089
Messy Administration (MESS) For the fall semester 2010, EPFL proudly welcomed 2300 new students to the campus. Handling their registrations to the different sections and levels requires an administrative masterstroke. Nowadays this process is highly automated and worked impeccably up to this year... The software that handles the registrations wasn’t lead out for such a huge number of new students and the secretaries were close to a heart attack when they received the registration printouts. Instead of receiving one sheet per class (defined by the orientation of studies and the level, e.g. Architecture, Bachelor 1) containing the list of all the students registered to that class, the printouts contained sentences in 5 different formats: ! STUDENT_ID1 studies SECTION ! STUDENT_ID1 enters semester SEMESTER ! STUDENT_ID1 and STUDENT_ID2 chose the same studies ! STUDENT_ID1 and STUDENT_ID2 are in same semester ! STUDENT_ID1 and STUDENT_ID2 are in same class STUDENT_ID1 and STUDENT_ID2 are the 6-digit sciper numbers, SEMESTER is an integer number in the range from 1 to 10 and SECTION is a one-worded string. The secretaries were very puzzled and couldn’t figure out how to recreate the expected lists from these printouts. But luckily they remembered PolyProg. The desperate secretaries provide you with the printouts and you are to answer their impatient questions to your best. ? What does STUDENT_ID1 study ? Which semester will STUDENT_ID1 enter ? Are STUDENT_ID1 and STUDENT_ID2 classmates Two students are considered to be classmates if and only if they study the same subject and enter the same semester. Answering to your best means that your answer must be as complete as possible, you must never give an erroneous answer, but you can just admit that the input was insufficient to answer a question at the point in time it was asked. Your answers shall respect the following priority: Question Answer ? What does STUDENT_ID1 study STUDENT_ID1 studies SECTION Sorry, I have no clue yet ? Which semester will STUDENT_ID1 enter STUDENT_ID1 enters semester SEMESTER Sorry, I have no clue yet ? Are STUDENT_ID1 and STUDENT_ID2 classmates Yes, STUDENT_ID1 and STUDENT_ID2 are classmates No, this is not possible Possible, given that STUDENT_ID1 and STUDENT_ID2 study the same subject Possible, given that STUDENT_ID1 and STUDENT_ID2 are in the same semester Sorry, I have no clue yet Input The input consists of a single test-case with no more than 1’000 printout sentences and no more than 500 questions. They may be mixed and you are to go through them in sequential order, which means that in order to answer a question, you must not rely on any information further down the list. You may safely assume that the sentences are not contradictory! Input terminates on a line containing the single word END. Output Output your answers, one per line and terminate with a newline. Be aware of typos :) Sample Input: ! 166554 and 175129 chose the same studies ! 175129 and 170113 are in same semester ! 166554 studies electronics ! 169983 and 170113 chose the same studies ? Are 170113 and 169983 classmates ! 169983 enters semester 9 ! 175129 and 169983 are in same semester ? Which semester will 170113 enter ? Are 169983 and 170113 classmates ? Which semester will 166554 enter ? What does 175129 study ! 169983 studies communicationsystems ? Are 166554 and 169983 classmate END Output: Possible, given that 170113 and 169983 study the same subject 170113 enters semester 9 Yes, 169983 and 170113 are classmates Sorry, I have no clue yet 175129 studies electronics No, this is not possible
32,090
Just on Time (ONTIME) Last week’s campaign on healthy and environmentally friendly mobility was a big success. Hundreds of commuters to the EPFL campus traded their car for a ride by bus or metro and gave a very positive feedback. They merely complained about earlier wake-up times necessary to reach the campus on time. This is where you enter the story. Try to improve the mood of the people by indicating them the latest time they can leave their house such that they can reach the campus no later than 8h15. Any means are ok to maximize their sleeping time, and all would accept to change bus or metro lines several times during their journey if this helps your planning. The public transport network is made up of S (0 <= S <= 100) stations (numbered from 1 to S ) and counts C (0 <= C <= 1,000) unidirectional connections that link two stations in regular time intervals, starting from a certain time in the morning and up to 8h15. Note that for any two stations, there might exist several direct shuttle services with different starting time and frequency. You are to answer some students’ request on the latest possible time they can leave from home in order not to be late. Input The input consists of several test-cases separated by an empty line. Each test-case starts with the number of stations S , the number of connections C and the number of requests R on a line. Then come C lines, each describing one shuttle service in the format ‘from’ ‘to’ ‘firstRide’ ‘travelTime’ ‘frequency’ (in minutes). The next R lines each hold two integers, the first being the closest station to the student’s home (come what may, but so early no student would like to walk more than necessary) and the second the time (in minutes) it takes the student to reach that station. The campus is located at station S . Input terminates on a test-case with S = C = R = 0 , which must not be evaluated. Output Answer the requests in the same order as they appear in the input. For each request, print a line in the form “Leave no later than ‘time’”, where ‘time’ is in the format hh:mm . Add an empty line after each test-case. If there is no way the students can make it on time, output “Doomed to be late”. You can safely assume that the commuters are so experienced in hopping on and off busses that they can change busses in no time at all. Sample Input: 3 2 2 1 3 07:10 50 15 2 3 08:20 5 5 1 3 2 0 3 4 3 2 3 05:30 6 5 1 3 06:11 5 15 1 2 07:01 2 5 3 2 08:00 1 8 1 2 2 1 3 10 0 0 0 Output: Leave no later than 07:22 Doomed to be late Leave no later than 07:59 Leave no later than 08:04 Leave no later than 08:05
32,091
Delicious Pancakes (PANCAKES) Just as promised, PolyProg will invite you to a bounteous pancake buffet right after this contest. Can you already feel the seductive odours dazing your senses? Well, before your mouth starts watering, you should solve this last problem. As you might know, the basic ingredients to pancakes are flour, milk and eggs. These may be completed by a passel of additional toppings such as sugar, jam, berries, cheese, ham, mushrooms etc. As the chef of the evening was yet uncertain about the recipe he’d whip up tonight, he asked his assistant simply to buy random quantities of each ingredient. With these quantities he could make N1 pancakes according to recipe 1, N2 if he decides to follow recipe 2, N3 for recipe 3 and so on and so forth. As the end of the competition is close, the chef will not have enough time to combine several recipes: All pancakes tonight will be of the same taste (too bad :( ). The repertoire of recipes is huge, and as we imagine you to have a ravenous appetite, you are to select the recipe that yields the largest number of pancakes. Input The input consists of several test-cases separated by an empty line. The first line of each test-case holds the number of ingredients N (1 ≤ N ≤ 50) the assistant bought followed by the number of recipes R (1 ≤ R ≤ 100) in the chef’s repertoire. Each of the next lines contains exactly N non-negative integers (no larger than 10 6 ) informing about the ingredients. The first of these lines lists the quantities the assistant bought of each ingredient. The remaining R lines list the quantities (in the same order as the previous line) necessary to make ten pancakes according to the recipe r i (from 1 to R ). The input ends on a test-case having both N and R zero, which must not be processed. Output Your program should produce one line per test-case containing the recipe that yields the largest number of pancakes followed by the number of entire pancakes that can be made then. If there is a tie, prefer the recipe that appears first in the input. SAMPLE INPUT 3 2 20 20 20 5 10 1 2 1 3   6 3 100 60 130 80 100 90 10 5 10 5 10 5 1 2 1 2 20 7 0 0 0 10 30 1   0 0 SAMPLE OUTPUT 2 66 1 100
32,092
Beehive Numbers (BEENUMS) A beehive is an enclosed structure in which some honey bee species live and raise their young. In this problem we consider a two-dimensional sketch of the beehives. Each beehive is composed of a certain number of cells, where each cell is a regular hexagon. Each cell may have some neighbors, which are other cells that share a side with that cell. A cell with exactly 6 neighbors is an internal cell, while a cell with fewer neighbors is an external one. Notice that an external cell can always be changed to internal by adding some neighbor cells. We are interested in a particular class of beehives. This class of valid beehives is defined recursively as follows: a) a single cell is a valid beehive; and b) given a valid beehive B, if we add the minimum number of cells such that each external cell of B becomes an internal cell, the result is a valid beehive. The number of cells in a valid beehive is called a beehive number. Given an integer N, you must decide whether it is a beehive number. Input Each test case is described using a single line. The line contains an integer N (1 ≤ N ≤ 10 9 ). The end of input is indicated with a line containing a single −1. Output For each test case, output a single line containing an uppercase “Y” if N is a beehive number, or an uppercase “N” otherwise. Example Input: 43 1 7 19 15 -1 Output: N Y Y Y N
32,093
Camelot (CAMELOT) Camelot is a solitaire game that is played with a deck of French cards. The deck contains 52 cards, each of them having a suit and a face value. There are 4 possible suits and 13 possible face values. Since for this solitaire suits are not important, we consider that the deck contains 4 repetitions of each possible face value. Face values are A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q and K. The solitaire starts with the full deck placed, face down, on the table. There is also a board containing 16 empty slots arranged in a 4 by 4 grid. The game repeatedly alternates two phases: a dealing phase and a removal phase. The first phase is a dealing phase. During this phase cards are dealt from the deck one at a time. Each card is placed, face up, in an empty slot. However, certain cards can only be placed in specific slots: Jacks (face value J) can only occupy the middle two slots of first and last columns. Queens (face value Q) can only occupy the middle two slots of first and last rows. Finally, Kings (face value K) can only occupy the corner slots. Cards having other face values can be placed in any empty slot. The game is lost whenever a card is dealt from the deck for which no valid empty slot exists. Each time the last empty slot has just been occupied, or when the deck is empty, a removal phase starts. During a removal phase, it is possible to remove from the board any card or pair of cards that add up to 10. For this purpose, Aces (face value A) are considered as having value 1, while Jacks, Queens and Kings cannot be removed. For instance, it is possible to remove a 10 on its own, a pair formed by a 3 and a 7, a pair formed by an Ace and a 9, etcetera. Cards removed from the board are not used anymore during the game. The removal phase ends when no card can be removed from the board, or when the player decides not to continue removing cards. Notice that it is not mandatory to remove from the board every card that can be removed. However, since the player cannot decide the moment in which a new removal phase will begin, leaving removable cards on the board must be done carefully. Besides, note that if during a removal phase no card is removed, then the game is lost. When the removal phase ends, a new dealing phase starts, unless the deck is empty, in which case the game is over. The game is won if the deck is empty and only Jacks, Queens and Kings are left on the board. Camelot is really nice to play, but is frustrating to discover at the end of a game that it was impossible to win because of the initial arrangement of the deck. Even if the initial deck allows the player to win, he may fail to do so because of bad decisions or bad luck when placing or removing cards. Your job in this problem is to find out whether it is at least possible to win the game, given the order in which the cards will be dealt from the deck. Input Each test case is described using a single line. The line contains a single string of exactly 52 characters representing the initial arrangement of the deck. The first card dealt from the deck is given by the first character of the string, and so on. Each card is represented by its face value, with the exception of cards with face value 10 that are represented by the digit “0”. You may assume that the string corresponds to a valid initial arrangement of the deck, i.e., it contains exactly 4 repetitions of each possible face value. The end of input is indicated with a line containing a single asterisk (“*”). Output For each test case, output a single line containing an uppercase “Y” if it is possible to win the game with the given initial arrangement of the deck, or an uppercase “N” otherwise. Example Input: AAAA222233334444555566667777888899990000JJJJQQQQKKKK JJJJQQQQKKKKA9A9A9A928282828373737374646464655550000 JJJJQQQQKKKKA9A9A9A928282828333377774646464655550000 28333377774646464655550000JJJJQQQQKKKKA9A9A9A9282828 * Output: N Y N Y
32,094
Drawing Quadrilaterals (DRAWQUAD) A quadrilateral consists of 4 points A, B, C and D in the plane, together with the segments AB, BC, CD and DA. Points are called vertices, while segments are called sides. The quadrilateral is simple if opposite sides (i.e. sides that do not share a vertex) do not intersect. Notice that it is possible to have a simple quadrilateral that looks like a triangle, with exactly 3 collinear vertices. Demetrio has just drawn N points on the wall of his room. He planned to draw a simple quadrilateral having 4 of these points as vertices, and then paint it with blue ink. Demetrio is going to buy the ink right now, but he has not chosen the 4 points yet. Can you tell him the maximum area a simple quadrilateral drawn on his wall can have? In this way Demetrio will be sure he will not run out of blue ink before the work is done. Input Each test case is described using several lines. The first line contains an integer N indicating the number of points drawn on the wall (4 ≤ N ≤ 1000). Each of the next N lines describes a different point of the set using two integers X and Y (−10 7 ≤ X, Y ≤ 10 7 ); these values represent the coordinates of the point in the XY plane. You may assume that within each test case no two points have the same location, neither are all collinear. The end of input is indicated with a line containing a single −1. Output For each test case, output a single line with a single decimal number representing the maximum area of a simple quadrilateral having as vertices 4 different points of the input set. Round the result to the closest rational number with one decimal place. In case of ties, round up. Always use exactly one digit after the decimal point, even if it means finishing with a zero. Example Input: 6 -100 0 100 0 -100 50 0 55 0 -65 1 1 4 -1 0 10000 0 0 0 0 1 -1 Output: 12000.0 5000.5
32,095
Escape from Jail Again (ESCJAILA) A new International Common Prison for Criminals (ICPC) was built, and your old friend Harry was moved there as a prisoner. As before, the new ICPC is one of the most secure prisons in the world. It was designed by and old gamer and as such, the prison is not necessarily closed, but only an incredibly logical and fast mind can get out. The new ICPC can be represented as a grid of square cells. Each cell is empty, or it contains a wall, a door, an opening button or a closing button. Harry was accommodated in an empty cell, and all doors were closed. Nevertheless, Harry told you that he will try to escape. Each time Harry is in a cell, he can move in a single step to an adjacent cell (i.e., a cell that shares a side with his current location). Each time Harry steps on a cell that contains an opening button, all doors open, while each time he steps on a cell that contains a closing button, all doors close. Harry can walk around as he wants within the prison, although he cannot move to a cell that contains a wall, neither to a cell that contains a door if the doors are closed. To escape from the prison, Harry needs to step outside, which means placing himself in one of the cells on the sides and then taking one extra step out in the direction opposite to the prison. You obtained a map of the prison, and Harry deserves your advise. Tell him the minimum number of steps he needs to escape, or warn him that there is no way to get out. Input Each test case is described using several lines. The first line contains two integers N and M indicating respectively the number of rows and columns of the grid that represents the prison (1 ≤ N, M ≤ 100). Line i of the next N lines describes row i of the grid using a string of exactly M characters, where character j represents cell j of that row. This string only contains the following characters with the indicated meanings: “H” is the empty cell where Harry is at the beginning; “.” is an empty cell where Harry is not at the beginning; “W” is a wall; “D” is a door; “O” is an opening button; and “C” is closing button. You may assume that within each test case there is exactly one character “H”. The end of input is indicated with a line containing the number −1 twice. Output For each test case, output a single line with a single integer representing the minimum number of steps Harry needs to escape the prison, or the number −1 if it is impossible for him to do so. Example Input: 5 8 WWWWWWW. WHDC...D W.WW.WCW W.OW..OW .WWWWWWW 3 3 ODO DHD ODO 3 7 WWWWWWW DH..OCD WWWWWWW 4 1 W H O W 1 13 HOW.DO.COW.DO -1 -1 Output: 21 -1 8 1 1
32,096
File Recover Testing (FILRTEST) In a recent programming contest appeared a problem named “File Recover”. In that problem, repeated strings of a given text were to be counted. You are preparing test cases for that problem, and in order to test for border cases you want to generate a text with many repetitions of a particular string. Of course, test cases cannot be arbitrarily long, so you decided to choose a length and a string, and then fit in a text of that length as many repetitions as possible of the string. For instance, if the length is 14 and the string is “abcab”, you may generate the text “abcabcabcabcab” whose length is 14 and where the string “abcab” appears 4 times (starting at positions 1, 4, 7 and 10). You would like to know how good your idea is before implementing. Given a length and a string, you must determine the maximum number of times the characters of the string can appear consecutively in a text of that length. Input Each test case is described using a single line. The line contains an integer K (1 ≤ K ≤ 10 9 ) and a non-empty string S of at most 10 6 lowercase letters. The end of input is indicated with a line containing the number −1 and an asterisk (“*”). Output For each test case, output a single line with a single integer representing the maximum number of times the characters of S can appear consecutively in a text of length K. Example Input: 14 abcab 1000 abcde 1000000000 z 1 zzzzz -1 * Output: 4 200 1000000000 0
32,097
Girls and Boys (GIRLSNBS) There are G girl students and B boy students in a class that is about to graduate. You need to arrange them in a single row for the graduation. To give a better impression of diversity, you want to avoid having too many girls or too many boys seating consecutively. You decided to arrange the students in order to minimize the gender regularity. The gender regularity of an arrangement is the maximum number of students of the same gender (all girls or all boys) that appear consecutively. Given G and B, calculate the minimum gender regularity among all possible arrangements. Input Each test case is described using a single line. The line contains two integers G and B representing the number of girls and boys in the class, respectively (0 ≤ G, B ≤ 1000). The end of input is indicated with a line containing the number −1 twice. Output For each test case, output a single line with a single integer representing the minimum gender regularity that an arrangement of G girls and B boys can have. Example Input: 10 10 5 1 0 1000 -1 -1 Output: 1 3 1000
32,098
Hackers (HACKERS) The network of your office is composed of several computers and bidirectional links. Each link connects a given pair of computers and has an access value. Each user in the network has an access privilege, and is able to use any link with access value not exceeding his access privilege. Everything was fine until you notice that a bunch of hackers are accessing the network. You know that if there is a link between computers A and B, with access value V, and a hacker with access privilege of at least V controls A, then he can control B. Hackers wish to control the most important computers by exploiting problems in the network. They are trying to increase their access privileges in order to use the links, and your task is to measure how safe the network is. Given the description of the network, the computer each hacker currently controls and the target computer each hacker wishes to control, you need to calculate the minimum access privilege each hacker needs to get in order to control his target computer. Hackers act independently, neither they collaborate nor interfere with each other. This means that each hacker may control each computer and use each link independently of what the other hackers do. Input Each test case is described using several lines. The first line contains three integers C, L and H, indicating the number of computers, links and hackers in the network, respectively (2 ≤ C ≤ 3000, 1 ≤ L, H ≤ 10 5 ). Each computer is identified by an integer number between 1 and C. Each of the next L lines describes a different bidirectional link using three integers A, B and V; the numbers A and B identify two distinct computers that are the endpoints of the link (1 ≤ A < B ≤ C); the number V is the access value of the link, that is, any hacker must have an access privilege of at least V to use the link (1 ≤ V ≤ 10 9 ). Each of the last H lines describes a different hacker using two distinct integers S and T that identify the computer that the hacker currently controls and the computer that the hacker wishes to control, respectively (1 ≤ S, T ≤ C). You may assume that within each test case no two links connect the same pair of computers, and that for any pair of computers there is at least one sequence of links that allow to reach one computer starting from the other. The end of input is indicated with a line containing the number −1 three times. Output For each test case, output a single line with H integers representing the minimum access privilege each hacker needs to achieve his goal. The result for each hacker must appear in the same order that the hackers are described in the input. Example Input: 5 6 4 1 2 4 1 3 5 2 4 3 2 5 1 3 4 2 4 5 2 3 2 2 4 1 5 3 1 2 1 1 1 2 1 2 1 2 1 3 1 2 1000000000 2 1 2 1 1 2 -1 -1 -1 Output: 2 2 4 4 1 1000000000 1000000000 1000000000
32,099