task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Getting There Fast (GETFAST) Gabriela drives a school bus. Being one of the few women who have that job, she is always mocked by the male drivers. To improve her status, she decided that besides driving responsibly she is going to drive more efficiently. Her idea is to finish her route spending as little time as possible, without violating any traffic rule. The bus Gabriela drives has a very modern driving system that allows her to adjust the acceleration to any real number instantly. Hence, the acceleration is constant by intervals, jumping to another acceleration whenever Gabriela decides so. If v is the bus' speed at a given instant of time, and a its acceleration that remains constant over a period of time t , then the speed at the end of that period will be v + at . Moreover, the bus will move a distance of at 2 /2 + vt during that period of time. The traffic rules prevent vehicles from using an acceleration greater than A , or a deceleration less than D , i.e. the acceleration a at any time must satisfy - D <= a <= A . Moreover, there are check points along the route of the bus where the speed must lie within a certain given interval. Gabriela knows in advance the location of the check points, the total length of the route, and the constants A and D . At the beginning of the route the speed and acceleration of the bus are both 0. There are no additional restrictions regarding the speed or the acceleration the bus must have at the end of the route (in particular, it is not necessary to stop in the end). Your job is to use this data to determine the minimum time that Gabriela needs in order to finish the route without violating the rules. Input The input contains several test cases. Each test case is described using several lines. The first line of each test case contains four integers N , L , A and D . N represents the total number of check points that are present in Gabriela's route (1 <= N <= 10 5 ). L indicates the length of the route in meters (2 <= L <= 10 7 ). A and D represent, respectively, the maximum allowed acceleration and deceleration for the bus (1 <= A , D <= 100). Each of the following N lines describe a different check point using three integers X , V and W that represent, respectively, the distance between the check point and the starting point of the route (1 <= X <= L -1), the minimum speed, and the maximum speed allowed for the bus at the time it passes by that check point (1 <= V , W <= 100). Assume that in each test case the check points are given in ascending order of distance from the start point of the route, and no two check points are at the same distance from the start point. In this problem, the length is expressed in m (meters), the speed in m/s, and the acceleration in m/s 2 . The end of the input is indicated by a line containing the number -1 four times, and should not be processed as a test case. Output For each test case, output a single line containing a rational that represents the minimum time (in seconds) needed for Gabriela to finish her route without violating any traffic rule, or an asterisk if it is impossible to do that. Round the answer to the nearest rational with two decimal digits. In case of a tie, round up. Print exactly two digits after the decimal point, even if that means ending the number with 0's. Example Input: 1 40 10 1 20 21 21 1 40 10 5 20 20 20 1 20 10 50 10 14 15 5 1000 2 5 400 30 80 600 35 50 700 10 30 900 30 40 950 10 30 -1 -1 -1 -1 Output: * 2.83 2.00 35.96
32,500
He is Lazy (HEISLAZY) As we all know, Humberto is really lazy. He is so lazy that he sticks his nose out of the window so that the wind will blow it for him. Obviously, he hasn't worked at all in his whole life. However, he got lucky and won a lot of money in the lottery. With some of that money he bought an empty field, and made build several houses inside of it, where he moved with his family and friends. Thus, Humberto can go in a straight line from any point in his field to any other, without having to make detours because of urban design (for the sake of simplicity, we consider the objects in Humberto's field as dots, so they don't interfere in Humberto's way). Sadly, that was not enough for Humberto, so in order to walk even less he decided to have installed some catapults in strategic points of his field. Each catapult can send him from the point where it is installed, to any point at a certain fixed distance (that depends on the range of the catapult). But, in spite of simplifying his life, the catapults made the task of choosing a way in the field a real headache, because Humberto wants to walk as less as possible. As tired as he is of all his problems, he decided to use the rest of his money to hire you to tell him the minimum distance he has to walk to move from a given point in the field to another. Input The input contains several test cases. Each test case is described in several lines. The first line contains five integers N , P_X , P_Y , L_X and L_Y . N represents the number of catapults in the field (1 <= N <= 100). The pair ( P_X , P_Y ) indicates the coordinates in the XY plane ot the starting point for Humberto, while the pair ( L_X , L_Y ) indicates analogously the destination point (1 <= P_X , P_Y , L_X , L_Y <= 10 9 ). Each of the next N lines describes a different catapult, using three integers C_X , C_Y and F , that indicate the point ( C_X , C_Y ) where the catapult of strength F is installed. This means that Humberto may move, without walking, from the point ( C_X , C_Y ) to any point in the plane that is at a distance of exactly F from ( C_X , C_Y ). Assume that in each test case all the points given in the plane are different. The end of the input is indicated by a single line containing the number -1 five times, and it should not be processed as a test case. Output F or each test case, output a single line containing a rational number that represents the minimum distance Humberto has to walk in order to get from the starting point to the destination point, using some or none of the catapults. Round the answer to the nearest rational with two decimal digits. In case of a tie, round up. Print exactly two digits after the decimal point, even if that means ending the number with 0's. Example Input: 1 10 10 20 10 11 10 9 1 20 10 10 10 11 10 9 2 1 1 12 1 3 1 6 8 1 5 1 12 12 1 1 6 6 9 5 10 10 1 1 3 3 7 8 3 7 8 8 7 3 8 7 5 5 5 -1 -1 -1 -1 -1 Output: 1.00 10.00 4.00 10.41 5.11
32,501
Imperialism (IMPER) The ambition of conquest and expansion is a very well known disease in planet Earth... and also in the entire universe. In planet “Imperius” several fortresses have been built one at a time and each one of them but the first was connected at the moment of its construction to a previously built fortress by a direct path, for commercial purposes. Imperius was becoming one of the most peaceful and prosperous planet in the universe, until they built no more fortresses. At that moment, N different empires emerged (numbered from 1 to N ), each one of them dominating a different fortress. And the thirst of conquest took Imperius. Thus, every year, exactly one of the living empires conquers every neighbor empire, and dominates every fortress belonging to them. Two empires are considered neighbors if there exist two fortresses joined by a path, each one dominated by one different empire of these two. Eventually a single empire will dominate every fortress. Your task is to find the minimum number of years such that this can happen. As an example, on the left side of the figure below a possible scenario in which six fortresses are initially dominated by six different empires is shown. Each fortress is tagged with the identification number of the empire dominating it. If empire 2 conquered every neighbor on the first year, the the situation would be as in the central figure. Finally, if empire 5 conquered his neighbor empires, it would end up dominating every fortress, as seen on the right side of the figure.                     Input The input contains several test cases. Each test case is described in two lines. The first line contains an integer N (2 <= N <= 10 4 ) representing the number of fortresses in planet Imperius. The next line contains N -1 integers P_i indicating that the fortress i +1 was connected to fortress P_i (1 <= P_i <= i for 1 <= i <= N -1). 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 years such that a single empire may dominate every fortress. Example Input: 6 1 2 2 4 5 7 1 1 3 3 4 4 6 1 2 2 2 2 -1 Output: 2 2 1
32,502
Joy of CompuTenis (JOCTENIS) The Modern Club Association organizes every year a tournament of CompuTenis, which is a sport specially adapted to a public without any mensurable physical qualities. The rules of CompuTenis are very complex (suffices to say that they involve coding with your elbow glued to your ear), but fortunately it is not necessary to know them in detail to solve this problem. You just need to know that in a CompuTenis match two players oppose each other, and the match is won by the player that first wins S sets; in turn, each set is composed of several games, and to win a set a player must win at least J games, with a difference of at least D more games won than the opponent. The tournament has K rounds, and there are N = 2 K players in it, who all participate in the first round. In each round each of the remaining participating players is paired with another participating player, in order to play a single match. The winning player of each of these matches advances to the next round, whereas the losing player is automatically disqualified from the tournament. The winner of the only match of round K is thus the winner of the tournament. It is desirable to make the tournament as long as possible, considering that the matches are broadcast on television and the Association is paid for every minute on air. Given any pair of different players, the Association knows the probability for one of them to win a game against the other. You are a member of the organizing committee, and your task is to prepare the fixture for the matches of each round in order to maximize the expected number of games played in the tournament. Doing this involves deciding which pairs of players will play a match in the first round, and then for each of the following rounds deciding which pair of matches from the previous round will provide the winning players for each match in that round. Note that this can only depend on the identification of the matches in the previous round. The following figure shows a possible fixture for K = 3 rounds and N = 2 3 = 8 players. For the moment, the Association only wants to estimate their earnings, so it is sufficient to tell them the maximum expected number of games that can be played in the tournament. Input The input contains several test cases. Each test case is described using several lines. The first line contains four integer numbers, K , S , J and D . The value K denotes the number of rounds in the tournament (1 <= K <= 3). The value S denotes the number of sets that a player must win to win a match (1 <= S <= 10). The value J denotes the minimum number of games that a player must win in order to win a set, whereas D indicates that a player should win D more games than its opponent for him to win the set (1 <= D <= J <= 100). The players are identified by different integer numbers from 1 to N = 2 K . Each of the following N lines contains N values. In the i -th line, the j -th value is an integer number P_ij such that p_ij = P_ij /100 is the probability that player number i wins a game against player number j (0 <= P_ij <= 100 for 1 <= i , j <= N ). You may assume that P_ii = 0 (no player opposes himself) and that P_ij + P_ji = 100 for i and j different. The end of the input is denoted by a line containing four times the number -1. Output For each test case, you should print a line containing a rational number representing the maximum expected number of games that the given tournament can have. The result should be rounded to the nearest rational number with 2 decimal digits. In case of ties, round up. Note that you should always print 2 digits after the dot, even if this means ending with a zero. Example Input: 1 1 2 2 0 50 50 0 3 3 6 2 0 88 2 76 71 24 50 4 12 0 54 37 84 95 88 98 98 46 0 66 36 13 33 33 24 63 34 0 29 21 96 63 29 16 64 71 0 0 47 13 76 5 87 79 100 0 56 89 50 12 67 4 53 44 0 23 96 2 67 37 87 11 77 0 -1 -1 -1 -1 Output: 4.00 224.08
32,503
Mega Inversions (TRIPINV) The n^2 upper bound for any sorting algorithm is easy to obtain: just take two elements that are misplaced with respect to each other and swap them. Conrad conceived an algorithm that proceeds by taking not two, but three misplaced elements. That is, take three elements ai > aj > ak with i < j < k and place them in order ak; aj; ai. Now if for the original algorithm the steps are bounded by the maximum number of inversions n(n-1)/2, Conrad is at his wits' end as to the upper bound for such triples in a given sequence. He asks you to write a program that counts the number of such triples. Input The first line of the input is the length of the sequence, 1 <= n <= 10^5. The next line contains the integer sequence a1, a2 ... an. You can assume that all ai belongs [1; n]. Output Output the number of inverted triples. Example Input: 4 3 3 2 1 Output: 2
32,504
Robots on a grid (ROBOTGRI) You have recently made a grid traversing robot that can find its way from the top left corner of a grid to the bottom right corner. However, you had forgotten all your AI programming skills, so you only programmed your robot to go rightwards and downwards (that's after all where the goal is). You have placed your robot on a grid with some obstacles, and you sit and observe. However, after a while you get tired of observing it getting stuck, and ask yourself "How many paths are there from the start position to the goal position?", and "If there are none, could the robot have made it to the goal if it could walk upwards and leftwards?" So you decide to write a program that, given a grid of size n x n with some obstacles marked on it where the robot cannot walk, counts the different ways the robot could go from the top left corner s to the bottom right t, and if none, tests if it were possible if it could walk up and left as well. However, your program does not handle very large numbers, so the answer should be given modulo 2 31 - 1. Input On the first line is one integer, 1 < n ≤ 1000. Then follows n lines, each with n characters, where each character is one of '.' and '#', where '.' is to be interpreted as a walkable tile and '#' as a non-walkable tile. There will never be a wall at s, and there will never be a wall at t. Output Output one line with the number of different paths starting in s and ending in t (modulo 2 31 - 1) or THE GAME IS A LIE if you cannot go from s to t going only rightwards and downwards but you can if you are allowed to go left and up as well, or INCONCEIVABLE if there simply is no path from s to t. Example Input: ..... #..#. #..#. ...#. ..... Output: 6
32,505
Elevator Trouble (ELEVTRBL) You are on your way to your first job interview as a program tester, and you are already late. The interview is in a skyscraper and you are currently in floor s , where you see an elevator. Upon entering the elevator, you learn that it has only two buttons, marked "UP u " and "DOWN d ". You conclude that the UP-button takes the elevator u floors up (if there aren't enough floors, pressing the UP-button does nothing, or at least so you assume), whereas the DOWN-button takes you d stories down (or none if there aren't enough). Knowing that the interview is at floor g , and that there are only f floors in the building, you quickly decide to write a program that gives you the amount of button pushes you need to perform. If you simply cannot reach the correct floor, your program halts with the message " use the stairs ". Given input f , s , g , u and d (floors, start, goal, up, down), find the shortest sequence of button presses you must press in order to get from s to g , given a building of floors, or output " use the stairs " if you cannot get from s to g by the given elevator. Input The input will consist of one line, namely f s g u d , where 1 <= s, g <= f <= 1000000 and 0 <= u, d <= 1000000. The floors are one-indexed, i.e. if there are 10 stories, s and g be in [1; 10]. Output You must reply with the minimum numbers of pushes you must make in order to get from s to g, or output " use the stairs " if it is impossible given the conguration of the elevator. Example Input: 10 1 10 2 1 Output: 6 Input: 100 2 1 1 0 Output: use the stairs
32,506
Zombie’s Treasure Chest (ZTC) Some brave warriors come to a lost village. They are very lucky and find a lot of treasures and a big treasure chest, but with angry zombies. The warriors are so brave that they decide to defeat the zombies and then bring all the treasures back. A brutal long-drawn-out battle lasts from morning to night and the warriors find the zombies are undead and invincible. Of course, the treasures should not be left here. Unfortunately, the warriors cannot carry all the treasures by the treasure chest due to the limitation of the capacity of the chest. Indeed, there are only two types of treasures: emerald and sapphire. All of the emeralds are equal in size and value, and with infinite quantities. So are sapphires. Being the priest of the warriors with the magic artifact: computer, and given the size of the chest, the value and size of each types of gem, you should compute the maximum value of treasures our warriors could bring back. Input There are multiple test cases. The number of test cases T (T <= 200) is given in the first line of the input file. For each test case, there is only one line containing five integers N, S1, V1, S2, V2.It means the size of the treasure chest is N and the size and value of an emerald is S1 and V1, size and value of a sapphire is S2, V2. All integers are positive and fit in 32-bit signed integers. Output For each test case, output a single line containing the case number and the maximum total value of all items that the warriors can carry with the chest. Example Input: 2 100 1 1 2 2 100 34 34 5 3 Output: Case #1: 100 Case #2: 86 This problem is first solved by team Windrunner (Tsinghua University) at 32 minutes after the onsite contest starts. (They have 1 wrong try before they get Accepted.)
32,507
Yummy Triangular Pizza (YUMMY) Pizzahat has released a new pizza with triangular shaped pieces. This pizza is composed of some equal-sized equilateral triangle. Moreover, all the triangles are connected. Also, if two triangles are directly connected, they must share a common edge. How many different shapes of this kind of N-pieces pizza are there? Two patterns are considered as same if they can completely overlap after rotation and shifting (note that flipping is not included). Input There are multiple test cases. The first line of input contains a single integer denoting the number of test cases. For each test case, there is only one line with only one integer N denoting the number of pieces that can be used. (1 <= N <= 16) Output For each test case, output a single integer denoting the number of possible different shapes of the pizza. Example Input: 3 2 4 10 Output: Case #1: 1 Case #2: 4 Case #3: 866 This problem is first (and only) solved by team Cabbage (Zhongnan University) at 225 minutes after the onsite contest starts. (They have 1 wrong try before they get Accepted.)
32,508
Xavier is Learning to Count (XC) Xavier, a 9-year-old student, loves playing many kinds of puzzles. One of his favourites is the following: Xerier, his classmate, has made many cards. She writes down a single positive number on each of them. No numbers written on different cards are the same. After that she writes down an equation, whose right side is a single positive number chosen by her, and the left side is the sum of p integers: Then she asks Xavier put p cards on the corresponding X i 's position to make this equation correct, with an additional condition that X i should be ordered from smaller to bigger , i.e. Every time Xavier immediately comes up with many solutions. Now he wants to know how many solutions in total are there for any n given by Xerier. Input There are multiple test cases. The number of them is given in the beginning of the input. Then a series of input block comes one by one. For each test case: The first line contains two space-separated integers m and p (1<=p<=5). The second line contains m distinct positive integers - the numbers written on each of the cards. None of these integers exceeds 13000. There are about 120 test cases in total, but 90% of them are relatively small. More precisely, all numbers are less than or equal to 100 in 90% of the test cases. Output For each test case: For each positive integer, output the number of ways in a single line. To keep the output finite, only numbers with positive ways should be outputted. Output a blank line after each test case. See sample for more format details. Example Input: 3 3 3 1 2 3 5 4 1 3 5 6 7 10 3 1 2 3 4 5 6 7 8 9 10 Output: Case #1: 6: 1 Case #2: 15: 1 16: 1 17: 1 19: 1 21: 1 Case #3: 6: 1 7: 1 8: 2 9: 3 10: 4 11: 5 12: 7 13: 8 14: 9 15: 10 16: 10 17: 10 18: 10 19: 9 20: 8 21: 7 22: 5 23: 4 24: 3 25: 2 26: 1 27: 1 This problem has 82 submissions during the onsite contest, but none of them gets Accepted.
32,509
Very Boring Homework (VBWORK) Prof. Z thinks his homework is very hard for most of his students to solve (do you remember the task "Boring Homework"?) To his surprise, many students hand in correct solutions. He thinks the reason is actually the small size of the data set he used to test students' programs rather than the low difficulty of the homework task. He decides to give his students the same homework again, but with enormous test cases. Of course, his students think his homework becomes even more boring this time. They need your help again. For the ones who don't know what homework Prof. Z. had given to his students last time:   You're asked to draw a graph of a binary search tree (BST).   A binary search tree, which may sometimes also be called ordered or sorted binary tree, is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. --from Wikipedia   Given a list of integer keys that should be inserted into the BST one by one orderly, we can form a unique BST. Moreover, Prof. Z wants the students to draw the graph of this BST. The rules to draw a graph of a BST are listed below: The graph of a 1-node BST is a single 'o' (15th small Latin letter). If a BST has a non-empty subtree, draw a single '|' just above the subtree's root, and a single '+' just above the previous drawn '|'. Finally, in the row of '+', use the least number (including 0) of '-'s to connect '+' (corresponding to the left or right subtree) and 'o' (denoting the parent node of the subtrees). The left subtree (if exists) must be drawn on the left side of its parent. Similarly, the right subtree (if exists) must be drawn on the right side of its parent. The column of the BST's root must not contain any characters belonging to left or right subtree. For each node of the BST, the graph of its left subtree and the graph of its right subtree do not share common columns in the picture of the whole tree. After the whole BST has been drawn, we number the rows from top to bottom, counting from 1, and so do the columns from left to right, counting from 1. Due to the large scale of the tree, the graph will become so large that it is impossible for Prof. Z to check every detail of the graph this time. So you are only asked to hand in m fragments of that graph to Prof. Z instead of the whole one. Input The first line contains T, the number of test cases. T test cases follow. For each test case: The first line contains a positive integer N (N <= 100000). The second line contains N distinct integers, each of which can be represented by a 32-bit signed integer. These numbers should be inserted into an empty BST one by one in the given order. The third line contains an integer M (M <= 5). M lines follow, each contains four integers, which are the row and column number of the top left corner, and the number of rows R i and columns C i of the required graph fragment, respectively. All the input integers will be positive and fit into a 32-bit signed integer, except R i and C i , which will be less than or equal to 200 and greater than 0 . Output For each test case: Output the case number counting from 1 in the first line. Then M blocks follow, each contains R i (or less, see next) lines. Each line should contain exactly C i characters. Use space (ASCII 32) to fill in the blank. But if a line contains only whitespaces, this line should not be outputted. Output a blank line after each graph fragment. Be careful with space characters in your output, any extra whitespace will cause Wrong Answer. Example Input: 3 3 3 1 2 2 1 1 5 3 1 2 5 2 6 4 5 6 1 3 2 1 1 1 8 10 10 2 6 7 4 5 3 1 9 10 8 2 1 1 5 5 3 6 5 5 Output: Case #1: +-o | o+ | o -o + | o Case #2: +--o+ | | o-+ o+ | | +o o | o Case #3: +o--- | o +- | +o+ o+ | o-+ | +o+ This problem is first solved by team Seraphim (Shanghai Jiao Tong University) at 234 minutes after the onsite contest starts.
32,510
Universal Question Answering System (UQAS) Every student needs help from getting new knowledge by asking questions. Surveys are suggesting that some similar questions are repeated frequently. So it will be nice to develop an automatic question-answering system to answer these questions. Your algorithm should not have any prior knowledge, but it must be able to read sentences and remember the mentioned facts. Whenever the question is asked about such a fact, the system has to answer it properly. Input The input consists of many dialogues. There is a single positive integer T on the first line of input, which denotes the number of following dialogues. (T <= 500, but note that 95% of them are relatively small.) Each dialogue includes one or more lines. Each line contains one sentence: either a statement or a question. Statements end with a dot character (.) while questions end with a question mark (?). There is one extra line after each dialogue. That line ends with an exclamation mark (!). The definitions of the statements and questions will be discussed later. Sentences can contain words, spaces and punctuation characters. All words contain only Latin letters and are case-sensitive. Unlike the normal English writing rules, the first letter of a sentence should keep lowercase unless the first word itself should begin with a capital letter. There are no extra spaces between words. No word will have more than 10 characters. There will be at most 1000 lines per dialogue. Statements Each statement has one of the following forms: noun_phrase are noun_phrase. noun_phrase can verb_phrase. everything which can verb_phrase can verb_phrase. everything which can verb_phrase are noun_phrase. noun_phrase and verb_phrase are both single word. The meanings of the four forms are: A are B: If X is A, then X is B. A can B: If X is A, then X has the ability to B. everything which can A can B: If X has the ability to A, X has the ability to B. everything which can A are B: If X has the ability to A, X is B. Questions Each question has one of the following forms: are noun_phrase noun_phrase? can noun_phrase verb_phrase? can everything which can verb_phrase verb_phrase? are everything which can verb_phrase noun_phrase? They are the question forms of the statements. In each test case, the number of different noun phrases will not exceed 100; the number of different verb phrases will not exceed 100. Output For each test case, output two lines. The first line describes the test case number counting from 1, while the second line contains the same number of characters as the number of questions in this test case. Each character is either Y (denoting you can get that fact logically) or M (otherwise), without quotes. See the example. Example Input: 1 flies can fly. flies are insects. everything which can fly are animals. are everything which can fly insects? are flies animals? can flies eat? everything which can fly can eat. can flies eat? Bye! Output: Case #1: MYMY This problem is first solved by team Seraphim (Shanghai Jiao Tong University) at 66 minutes after the onsite contest starts.
32,511
Triangles and Quadrangle (TQ) Little Yuan is two years old and she is learning about some triangles and quadrangles. She is such a smart girl that she soon realizes two triangles can form a quadrangle without overlapping each other . She picks up a lot of triangles and uses them to form some quadrangles. Unfortunately, she is not good at this kind of jigsaw game and makes some mistakes. As her brother, you are curious about whether she has made a mistake when forming two triangles into a quadrangle. You are thinking about to write a program to determine it. Notice that the quadrangle in this problem is defined as a simple polygon with four vertexes. And you may also assume that all triangles and quadrangle have positive area. Note that two graphs are considered as the same if and only if they can overlap completely by shifting, rotation and flipping . Input There are multiple test cases. The first line of input contains a single integer T denoting the number of test cases. (T < 1000) For each test case, there are 10 lines in total.The first 3*2 lines describe the two triangles. Each line with two numbers denotes the coordinates of a point.The next 4 lines describe the quadrangle in clockwise order or counter-clockwise order. All coordinates are integers and less than 15000 in absolute value. Output For each test case, output Yes if the given triangles can form the given quadrangle without overlapping, No otherwise. See the example for more output format details. Example Input: 2 0 0 0 1 1 0 0 0 0 1 1 0 -1 0 0 0 1 0 0 1 0 0 -1 1 1 0 0 0 0 1 1 0 -1 0 0 0 1 0 0 1 Output: Case #1: Yes Case #2: No This problem is first solved by team FreeJourney (Wuhan University) at 83 minutes after the onsite contest starts. The test set of this problem is not the same as that of the onsite contest.
32,512
Share the Cakes (CAKE4) Lunar Rose is a pure and kind girl who was born in a serene town on, with surprising coincidence, the Mid-autumn Festival that year. Therefore, on each of her birthday, she enjoys two cakes: for the birthday, and for the festival. This year, Lunar would like to share the cakes with Jaddy, her boyfriend, on the nice day, isn't it so romantic? What is the tragedy, Jaddy screwed up, again: When Lunar placed two cakes on the table, she wanted Jaddy to cut the cakes for her so that they can both have half of the moon cake and so do the birthday cake. But Jaddy, as a lazy and impetuous guy, he just used a knife to cut them together easily, hence although the two cakes had been cut into two pieces each, they were not really uniform. What was worth? Lunar is a pretty perfectionist and suddenly quite angry with Jaddy due to his arbitrariness. Finally, Lunar chose to leave him. Stupid Jaddy! Jaddy became extremely regretful and distressing. Lunar, a softhearted girl, does not have the heart to make him so painful so that she'd like to give Jaddy a chance to do it again. However, she set a strict limit for this task: Jaddy can only use one cut to separate the two cakes into equivalent halves. Evil Ms. Rose! Both two cakes are convex polygons ; the table and knife are both big enough and long enough thus can be considered as infinite planar and line. This way, tell Jaddy a strategy, which means a line, satisfying Lunar's condition to cut cakes so that he can get her back. Input The first line of the input data is a positive integer T (T <= 100) indicating the number of test cases. Then T cases follow. Each test case contains description of two cakes (polygons): each polygon begins with an integer n which denotes the number of vertices, and then n pairs of integers (x, y) follows describing the coordinates of vertices in clockwise or counterclockwise order. You may assume that each polygon has no more than 20 vertices and all the coordinates are in range of [-1000, 1000]. Besides, no point is in the two polygons (including their boudary) simultaneously . Output For each test case, output two real numbers k and b, leading by the case number, which means that Jaddy should cut the cakes along the line y=k*x+b . It is guaranteed that both k and b among the answers are in range of [-10000, 10000]. See sample output for further details. We accept answers within 10 -4 relative or absolute error. Example Input: 2 3 0 0 1 1 0 2 3 2 1 3 0 3 2 4 0 0 1 0 1 1 0 1 4 2 2 3 2 3 3 2 3 Output: Case #1: 0 1 Case #2: 1 0 This problem is first (and only) solved by team Y.E.S (Tsinghua University) at 201 minutes after the onsite contest starts. (They have 1 wrong try before they get Accepted.)
32,513
Revenge of Fibonacci (REVFIB) The well-known Fibonacci sequence is defined as following: Here we regard n as the index of the Fibonacci number F(n). This sequence has been studied since the publication of Fibonacci's book Liber Abaci . So far, many properties of this sequence have been introduced. You had been interested in this sequence, while after reading lots of papers about it. You think there's no need to research in it anymore because of the lack of its unrevealed properties. Yesterday, you decided to study some other sequences like Lucas sequence instead. Fibonacci came into your dream last night. "Stupid human beings. Lots of important properties of Fibonacci sequence have not been studied by anyone, for example, from the Fibonacci number 347746739…" You woke up and couldn't remember the whole number except the first few digits Fibonacci told you. You decided to write a program to find this number out in order to continue your research on Fibonacci sequence. Input There are multiple test cases. The first line of input contains a single integer T denoting the number of test cases (T ≤ 50000). For each test case, there is a single line containing one non-empty string made up of at most 40 digits. And there won't be any unnecessary leading zeroes. Output For each test case, output the smallest index of the smallest Fibonacci number whose decimal notation begins with the given digits. If no Fibonacci number with index smaller than 100000 satisfy that condition, output -1 instead – you think what Fibonacci wants to told you beyonds your ability. Example Input: 15 1 12 123 1234 12345 9 98 987 9876 98765 89 32 51075176167176176176 347746739 5610 Output: Case #1: 0 Case #2: 25 Case #3: 226 Case #4: 1628 Case #5: 49516 Case #6: 15 Case #7: 15 Case #8: 15 Case #9: 43764 Case #10: 49750 Case #11: 10 Case #12: 51 Case #13: -1 Case #14: 1233 Case #15: 22374 This problem is first solved by team Y.E.S (Tsinghua University) at 77 minutes after the onsite contest starts. (They have 2 wrong tries before they get Accepted.)
32,514
Quelling Blade (QB) Mr. Sheep lost himself in a computer game. In this game, he plays the part of a super hero and fight with the evil. The equipment is very important in this game and Mr. Sheep thinks the Quelling Blade is the most powerful weapon. In this game, each type of weapon costs hero some money, and brings the hero benefits. If the hero buys two weapons (no matter they have the same type or not), the benefit values are accumulated. That is to say, if the hero buys two weapons with benefit 3 and 5, the hero will get total benefit value 8=3+5. There are some requirements for each weapon. If the hero wants to buy a certain weapon, he may need some other weapons first. For example, if hero wants to buy a Divine Rapier , he needs a Demon Edge and a Scared Relic . Of course, if he wants to buy the second Devine Rapier , he must buy another Demon Edge and another Scared Relic first. Notice that the existing weapon will not disappear after the trade. Note that a weapon may need multiple weapons with same type. And you may assume that a type of weapon is required by at most one other type of weapon. The hero is busy with combat and has no time to earn money. Fortunately, the game will give the hero 1 coin per second. So if the hero wants to buy a Quelling Blade , the minimum total time for him to achieve his goal can be easily calculated. Mr. Sheep is a perfectionist. He not only wants to get the Quelling Blade as soon as possible, but also wants to optimize every second during the game. He defines the utility of the game as the sum of the benefit value of the hero in each second. He calculates the utility from the start of the game until the second he gets Quelling Blade , exclusively. You may refer to the samples for further clarification. In the other words, you should define a way of process to buy the weapons for the hero, which minimize the total time to get Quelling Blade and optimize the utility of the game. Input There are hundreds of test cases, the number of test case are in the first line of the input. Notice that most of the test cases are relatively small. For each test case, the first line contains a single integer N denoting the number of different types of weapons. (1 ≤ N ≤ 1000) The next lines are describing the weapons. For each weapon, the first line contains two integers B and C, denoting the benefit value and the cost of this kind of weapon. (1 ≤ B, C ≤ 2 31 -1) Then a single integer P in the next line describes the number of requirements of this weapon. Next P lines, each line contains two integers I and A, means that this weapon needs A weapons of index I. The indexes of weapons are start from 1 to N. The Quelling Blade is the first type of weapon. You may assume that the total numbers of weapons which are needed by the Quelling Blade is less than 1000000. Also notice that Quelling Blade can be brought in a finite game time and a type of weapon can be required by at most one other type of weapon. Output For each test case, output a single integer denoting the optimal utility. You may assume that the answer fits into 64-bit signed integer. Example Input: 2 3 1 1 1 2 2 2 1 1 3 1 1 1 0 3 1 1 1 2 2 1 1 1 3 1 2 1 0 Output: Case #1: 14 Case #2: 17 This problem has no submissions during the onsite contest.
32,515
2s Complement (CODESPTA) One of the basics of Computer Science is knowing how numbers are represented in 2's complement. Imagine that you write down all numbers between A and B in 2's complement representation using 32 bits. How many 1's will you write down in all? 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 corresponding to each test case. Constraints: -2 31 <= A <= B <= 2 31 - 1 Sample Input: 3 -2 0 -3 4 -1 4 Output: 63 99 37 Explanation For the first case, -2 contains 31 1's followed by a 0 whereas -1 contains 32 1's. Thus the total is 63. For the second case, the answer is 31 + 31 + 32 + 0 + 1 + 1 + 2 + 1 = 99
32,516
Insertion Sort (CODESPTB) Insertion Sort is a classical sorting technique. One variant of insertion sort works as follows when sorting an array a[1..N] in non-descending order: for i <- 2 to N     j <- i     while j > 1 and a[j] < a[j - 1]        swap a[j] and a[j - 1]        j <- j - 1 The pseudocode is simple to follow. In the ith step, element a[i] is inserted in the sorted sequence a[1..i - 1]. This is done by moving a[i] backward by swapping it with the previous element until it ends up in it's right position. As you probably already know, the algorithm can be really slow. To study this more, you want to find out the number of times the swap operation is performed when sorting an array. Input The first line contains the number of test cases T. T test cases follow. The first line for each case contains N, the number of elements to be sorted. The next line contains N integers a[1], a[2] ... a[N]. Output Output T lines, containing the required answer for each test case. Constraints 1 ≤ T ≤ 5 1 ≤ N ≤ 100000 1 ≤ a[i] ≤ 1000000 Example Sample Input: 2 5 1 1 1 2 2 5 2 1 3 1 2 Sample Output: 0 4
32,517
Card Shuffling (CODESPTC) Here is an algorithm for shuffling N cards: The cards are divided into K equal piles, where K is a factor of N. The bottom N / K cards belong to pile 1 in the same order (so the bottom card of the initial pile is the bottom card of pile 1). The next N / K cards from the bottom belong to pile 2, and so on. Now the top card of the shuffled pile is the top card of pile 1. The next card is the top card of pile 2 .. the K-th card of the shuffled pile is the top card of pile K. Then (K + 1)-th card is the card which is now at the top of pile 1, the (K + 2)-nd is the card which is now at the top of pile 2 and so on. For example, if N = 6 and K = 3, the order of a deck of cards "ABCDEF" (top to bottom) when shuffled once would change to "ECAFDB". Given N and K, what is the least number of shuffles needed after which the pile is restored to its original order? Input The first line contains the number of test cases T. The next T lines contain two integers each N and K. Output Output T lines, one for each test case containing the minimum number of shuffles needed. If the deck never comes back to its original order, output -1. Constraints T ≤ 10000 2 ≤ K ≤ N ≤ 10 9 K will be a factor of N. Example Sample Input: 3 6 3 4 2 5 5 Sample Output: 6 4 2
32,518
Queens on a Board (CODESPTD) You have an N × M chessboard on which some squares are blocked out. In how many ways can you place one or more queens on the board such that no two queens attack each other? Two queens attack each other if one can reach the other by moving horizontally, vertically or diagonally without passing over any blocked square. At most one queen can be placed on a square. A queen cannot be placed on a blocked square. Input The first line contains the number of test cases T. T test cases follow. Each test case contains integers N and M on the first line. The following N lines contain M characters each representing the board. A '#' represents a blocked square and a '.' represents an unblocked square. Output Output T lines containing the required answer for each test case. As the answers can be really large, output them modulo 1000000007. Constraints 1 ≤ T ≤ 100 1 ≤ N ≤ 50 1 ≤ M ≤ 5 Exaample Input: 4 3 3 ... ... ... 3 3 .#. .#. ... 2 4 .#.. .... 1 1 # Output: 17 18 14 0
32,519
Hacking the random number generator (HACKRNDM) You recently wrote a random number generator code for a web application and now you notice that some cracker has cracked it. It now gives numbers at a difference of some given value k more predominantly. You being a hacker decide to write a code that will take in n numbers as input and a value k and find the total number of pairs of numbers whose absolute difference is equal to k, in order to assist you in your random number generator testing. NOTE: All values fit in the range of a signed integer, n, k>=1 Input 1st line contains n & k. 2nd line contains n numbers of the set. All the n numbers are assured to be distinct. ( Edited: n <= 10^5) Output One integer saying the no of pairs of numbers that have a diff k. Example Input: 5 2 1 5 3 4 2 Output: 3
32,520
Bytelandian Tours (CODESPTE) The country of Byteland contains of N cities and N - 1 bidirectional roads between them such that there a path between any two cities. The cities are numbered 0 ... N - 1. The people were very unhappy about the time it took to commute, especially salesmen who had to go about every city selling goods. So it was decided that new roads would be built. A new road was built between every two cities which could be reached from each other by travelling on exactly two old roads. Now a salesman situated in city 0, just like any other typical salesman, has to visit all cities exactly once and return back to city 0 in the end. In how many ways can he do this? Input The first line contains the number of test cases T. T test cases follow. The first line contains N, the number of cities in Byteland. The following N - 1 lines contain the description of the roads. The ith line contains two integers a i and b i , meaning that there was originally a road connecting cities with numbers a i and b i . Output Output T lines, one corresponding to each test case containing the required answer for that test case. Since the answers can be huge, output them modulo 1000000007. Constraints 1 ≤ T ≤ 20 1 ≤ N ≤ 10000 0 ≤ a i , b i < N Sample Input: 2 3 0 1 1 2 5 0 1 1 2 2 3 2 4 Output: 2 4 Explanation For the first case, a new road was build between cities 0 and 2. Now, the salesman has two tour possibilities: 0-1-2-0 or 0-2-1-0.
32,521
Palindromes (CODESPTF) Given a string, you keep swapping any two characters in the string randomly until the string becomes a palindrome. What is the expected number of swaps you will make? Input The first line contains the number of test cases T. Each of the next T lines contains a string each. Output Output T lines containing the answer for the corresponding test case. Print the answer rounded to exactly 4 decimal places. Constraints: T ≤ 10000 The length of the string will be at most 8 characters. The string will consist of only lower-case letters 'a'-'z'. There will always be at least one palindrome which can be formed with the letters of the given string. Sample Input: 4 b bb abb cbaabbb Output: 0.0000 0.0000 3.0000 59.3380 Explanation For the first two cases, the string is already a palindrome so no swaps are needed. For the third case, there are 3 possible swaps. The string will become "bab","bba" or remain "abb" with 1/3rd probability each. It's easy to see that the expected number of swaps needed is 3.0000 For the last case, the answer is 59.337962..., which should be printed as 59.3380
32,522
Cliques (CODESPTG) A clique in a graph is set of nodes such that there is an edge between any two distinct nodes in the set. It is well known that finding the largest clique in a graph is a computationally tough problem and no polynomial time algorithm is known for it. However, you wonder what is is the mininum size of the largest clique in any graph with N nodes and M edges. Of course, the graph should have at most one edge between any two nodes and no edges connecting a node to itself. Input The first line contains T the number of test cases. Each of the next T lines contain 2 integers N and M. Output Output T lines, one for each test case, containing the desired answer for the corresponding test case. Example Input: 3 3 2 4 6 5 7 Output: 2 4 3 Constraints 1 ≤ T ≤ 100000 2 ≤ N ≤ 10000 1 ≤ M ≤ N*(N-1)/2 Explanation For the second test case, the only valid graph having 4 nodes and 6 edges is one where each pair of nodes is connected. So the size of the largest clique cannot be smaller than 4. For the third test case, it is easy to verify that any graph with 5 nodes and 7 edges will surely have a clique of size 3 or more.
32,523
Polygon Diagonals (CODESPTH) Consider a regular polygon with N vertices labelled 1..N. In how many ways can you draw K diagonals such that no two diagonals intersect at a point strictly inside the polygon? A diagonal is a line segment joining two non adjacent vertices of the polygon. Input The first line contains the number of test cases T. Each of the next T lines contain two integers N and K. Output Output T lines, one corresponding to each test case. Since the answer can be really huge, output it modulo 1000003. Constraints 1 ≤ T ≤ 10000 4 ≤ N ≤ 10 9 1 ≤ K ≤ N Example Input: 3 4 1 5 2 5 3 Output: 2 5 0 Explanation For the first case, there are clearly 2 ways to draw 1 diagonal - 1 to 3, or 2 to 4. (Assuming the vertices are labelled 1..N in cyclic order). For the third case, at most 2 non-intersecting diagonals can be drawn in a 5-gon, and so the answer is 0.
32,524
Repairing Roads (CODESPTI) The country of Byteland contains of N cities and N - 1 bidirectional roads between them such that there a path between any two cities. The roads in Byteland were built long ago and now they are in need of repair. You have been hired to repair all the roads. You intend to do this by dispatching robots on some of the roads. Each robot will repair the road he is currently on and then move to one of the adjacent unrepaired roads. After repairing that, he will move to another adjacent unrepaired road, repair that and so on. Two roads are adjacent if they have the same city at one of their endpoints. For the process to be efficient, no two robots will can ever repair the same road, and no road can be visited twice. What is the least number of robots needed to accomplish the task? Input The first line contains the number of test cases T. T test cases follow. The first line contains N, the number of cities in Byteland. The cities are numbered 0..N - 1. The following N - 1 lines contain the description of the roads. The ith line contains two integers a i and b i , meaning that there is a road connecting cities with numbers a i and b i . Output Output T lines, one corresponding to each test case containing the required answer for that test case. Constraints 1 ≤ T ≤ 20 1 ≤ N ≤ 10000 0 ≤ a i , b i < N Example Input: 3 4 0 1 0 2 0 3 6 0 1 1 2 2 3 2 4 4 5 7 0 1 1 2 2 3 2 4 4 5 3 6 Output: 1 1 2 Explanation For the first case, one robot is enough to repair all roads: (0, 1) → (0, 2) → (0, 3) For the second case, one robot is again enough: (0, 1) → (1, 2) → (2, 3) → (2, 4) → (4, 5) For the third case, there is no way to repair all the roads with one robot and at least two are needed.
32,525
Tuple Division (TUPLEDIV) You are given N tuples with M dimensions. You need to choose some tuples and divide them into M groups. Each tuple can be used for only once and the size of the i th group is C i . We define the score of the i th group is the sum of value in the i th dimension of the tuples in the i th group. Your target is to firstly maximize the score of 1 st group, then maximize the score 2 nd group and so on.  Input The first line of the input contains an integer T (T ≤ 50), indicating the number of cases. Each case begins with two integer N (1 ≤ N ≤ 10000) and M (1 ≤ M ≤ 10), the number of tuples and the number of groups. Then there is one line contain M integers. The i th integer C i (C i ≥ 0, sigma C i ≤ N) represents the size of the i th group. Then N lines with M integers follow. Each of them describes a tuple. The j th integer on the i th line T ij (0 ≤ T ij ≤ 10000) denotes the value of the j th dimension of the i th tuple. Output For each test case, print one line with M score of some optimal division. Example Input: 2 4 2 2 1 3 2 2 1 2 2 1 1 4 3 1 1 2 8 7 1 8 7 2 8 7 4 8 2 3 Output: 5 2 8 7 7 Hint In case 2, we can divide the group like: Group 1: (8, 7, 2)  score = 8 Group 2: (8, 7, 1)  score = 7 Group 3: (8, 7, 4), (8, 2, 3) score = 4 + 3 = 7
32,526
Grey Area (SCPC11A) Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram generator. A histogram is a visual display of frequencies of value occurrences as bars. In this example, values in the interval 0–9 occur five times, those in the interval 10–19 occur three times, and 20–29 and 30–39 once each. Dr. Grey’s histogram generator is a simple tool. First, the height of the histogram is fixed, that is, the height of the highest bar is always the same and those of the others are automatically adjusted proportionately. Second, the widths of bars are also fixed. It can only produce a histogram of uniform intervals, that is, each interval of a histogram should have the same width (10 in the above example). Finally, the bar for each interval is painted in a grey color, where the colors of the leftmost and the rightmost intervals are black and white, respectively, and the darkness of bars monotonically decreases at the same rate from left to right. For instance, in Figure 1, the darkness levels of the four bars are 1, 2/3, 1/3, and 0, respectively. In this problem, you are requested to estimate ink consumption when printing a histogram on paper. The amount of ink necessary to draw a bar is proportional to both its area and darkness. Input The input consists of multiple datasets, each of which contains integers and specifies a value table and intervals for the histogram generator, in the following format: n w v1 v2 ... vn n is the total number of value occurrences for the histogram, and each of the n lines following the first line contains a single value. Note that the same value may possibly occur multiple times. w is the interval width. A value v is in the first (i.e. leftmost) interval if 0 ≤ v You may assume the following: 1 ≤ n ≤ 100 10 ≤ w ≤ 50 0 ≤ vi ≤ 100 for 1 ≤ i ≤ n You can also assume that the maximum value is no less than w. This means that the histogram has more than one interval. The end of the input is indicated by a line containing two zeros. Output For each dataset, output a line containing the amount of ink consumed in printing the histogram. One unit of ink is necessary to paint one highest bar black. Assume that 0.01 units of ink per histogram is consumed for various purposes except for painting bars such as drawing lines and characters (see Figure 1). For instance, the amount of ink consumed in printing the histogram in Figure 1 is: Each output value should be a 6 decimal fraction. Example Input: 3 50 100 0 100 3 50 100 100 50 10 10 1 2 3 4 5 16 17 18 29 30 0 0 Output: 0.510000 0.260000 1.476667
32,527
Alaska (SCPC11B) The Alaska Highway runs 1422 miles from Dawson Creek, British Columbia to Delta Junction, Alaska.  Brenda would like to be the first person to drive her new electric car the length of the highway. Her car can travel up to 200 miles once charged at a special charging station. There is a charging station in Dawson Creek, where she begins her journey, and also several charging stations along the way. Can Brenda drive her car from Dawson City to Delta Junction and back? Input The input contains several scenario. Each scenario begins with a line containing n, a positive number indicating the number of charging stations. n lines follow, each giving the location of a filling station on the highway, including the one in Dawson City. The location is an integer between 0 and 1422, inclusive, indicating the distance in miles from Dawson Creek. No two filling stations are at the same location. A line containing 0 follows the last scenario. Output For each scenario, output a line containing POSSIBLE if Brenda can make the trip. Otherwise, output a line containing the word IMPOSSIBLE . Example Input: 2 0 900 8 1400 1200 1000 800 600 400 200 0 0 Output: IMPOSSIBLE POSSIBLE
32,528
GO (SCPC11F) In the game of Go, two players alternate placing black and white stones on lattice points of an n × n grid, each attempting to surround as much territory (i.e., regions of unfilled lattice points) as possible. At the end of the game, the score for each player is the total area of the territory surrounded by his or her stones. Given the locations of black and white stones on a Go board at the end of a match, your task is to compute the score of each player in order to determine the winner. Formally, two grid lattice points with coordinates (r, c) and (r', c') are adjacent if |r − r'| + |c − c'| = 1. A connected region of unfilled lattice points belongs to one player’s territory if all adjacent filled lattice points contain stones belonging to that player (see Figure 1). Finally, a player’s score consists of the number of unfilled lattice points in his or her territory. Note that the scoring of Go boards described here does not correspond exactly to the real game of Go: we make the simplifying assumptions that all “disputes” have been settled so that any territories surrounded by stones of both colors are considered neutral, and that all groups on the board are considered “alive.” Figure 1: Diagram of a 9 × 9 Go board. Unfilled lattice points belonging to black’s territory are marked with B, and unfilled lattice points belonging to white’s territory are marked with W. Neutral unfilled lattice points are unmarked. In the game above, white wins by 21 − 3 = 18. Input The input test file will contain multiple cases, each consisting of three lines. Each test case begins with a line containing three integers, n (where 1 ≤ n ≤ 19), b, and w (where b ≥ 0,w ≥ 0 and 1 ≤ b + w ≤ n2). Here, n denotes the size of the board, b is the number of black pieces placed, and w is the number of white pieces placed. The second line of each test case contains b pairs of integers r1 c1 ... rb cb (where 1 ≤ ri , ci ≤ n) indicating the positions of the b black stones. The third line of each test case contains w pairs of integers r'1 c'1 ... r'w c'w (where 1 ≤ r'i , c'i ≤ n) indicating the positions of the w white stones. No two stones will be located at the same lattice point. Input is terminated by a single line containing only the number 0; do not process this line. Output For each test case, print either “White wins by ”, “Black wins by ”, or “Draw”. Example Input: 1 1 0 1 1 2 0 1 1 1 5 12 4 1 1 1 2 1 3 2 1 2 3 3 1 3 3 4 1 4 3 5 1 5 2 5 3 1 4 2 4 3 4 3 5 0 Output: Draw White wins by 3 Black wins by 1
32,529
Indomie (SCPC11G) During recession, Amjad needs to queue for SembakoPlus. Sembako, as we all know, stands for “Sembilan Bahan Pokok” which consists of 9 kinds of item: Rice, Sugar, Cooking-oil, Meat, Egg, Milk, Corn, Kerosene and Iodized Salt. SembakoPlus consists of Sembako and one more item: Indomie! Amjad’s favorite of all time!! (therefore, no wonder why he could stand for this long queue). Each person in the queue is allowed to pick only one item. No need to ask, Amjad wants only Indomie. Unfortunately, they are running out of SembakoPlus stock and currently there are three kinds of item left: Rice, Sugar and Indomie. As he could see from afar, he is quite sure that Rice and Sugar will be enough for everybody. Given the number of remaining Indomie and the number of people queuing in front of Amjad, your task is to count the probability that he will get his Indomie. Amjad can’t do programming right now as he is very nervous so he can’t think logically. He needs your help! Input There will be multiple test cases for this problem. Each test case contains two integers N (1 ≤ N ≤ 50) and S (0 ≤ S ≤ 50), where N is the number of people queuing in front of Amjad and S is the remaining number of Indomie. Output For each case, print in a single line the probability in percentage that he will get his Indomie with 5 digits precision (he’s being paranoid) Example Input: 2 1 3 2 4 0 4 1 10 10 14 9 30 14 Output: 50.00000 76.92308 0.00000 33.33333 99.99831 98.65515 95.16071 Explanation for 1st sample test case: There are two peoples queuing in front of Amjad, so those two peoples could pick of the following combination {1st people, 2nd people}: 1. Rice, Rice 2. Rice, Sugar 3. Rice, Indomie 4. Sugar, Rice 5. Sugar, Sugar 6. Sugar, Indomie 7. Indomie, Rice 8. Indomie, Sugar Since there is only one Indomie left, there are only 4 out of 8 combinations that ensure Amjad to get his Indomie (1, 2, 4 and 5), hence the probability is 4/8 = 50%.
32,530
Dolls (SCPC11H) Do you remember the box of Matryoshka dolls last week? Adam just got another box of dolls from Matryona. This time, the dolls have different shapes and sizes: some are skinny, some are fat, and some look as though they were attened. Specifically, doll i can be represented by three numbers wi, li, and hi, denoting its width, length, and height. Doll i can fit inside another doll j if and only if wi < wj , li < lj , and hi < hj . That is, the dolls cannot be rotated when fitting one inside another. Of course, each doll may contain at most one doll right inside it. Your goal is to fit dolls inside each other so that you minimize the number of outermost dolls. Input The input consists of multiple test cases. Each test case begins with a line with a single integer N, 1 ≤ N ≤ 500, denoting the number of Matryoshka dolls. Then follow N lines, each with three space-separated integers wi, li, and hi (1 ≤ wi; li; hi ≤ 10,000) denoting the size of the ith doll. Input is followed by a single line with N = 0, which should not be processed. Output For each test case, print out a single line with an integer denoting the minimum number of outermost dolls that can be obtained by optimally nesting the given dolls. Example Input: 3 5 4 8 27 10 10 100 32 523 3 1 2 1 2 1 1 1 1 2 4 1 1 1 2 3 2 3 2 2 4 4 4 0 Output: 1 3 2
32,531
Friends of Friends (FACEFRND) Bob uses a social networking site almost all the time. He was wondering what are Friends of Friends in that social networking site? If “X” is his friend, and “Y” is X’s friend but “Y” is not his friend, then “Y” is called his friend of friend. You have to find how many friends of friends Bob has. (Each user in that social networking site has a unique 4-digit ID number) Input First line contains a integer “N” (1 ≤ N ≤ 100) the number of friends in Bob's Profile. Then follow N lines. First Integer in each line is the ID number of Bob's friend, then an integer “M” (1 ≤ M ≤ 100) is the number of people in his friend list. Then follow M integers in that line, denoting the ID number of friends in his friend list (excluding Bob).  Output Output a single integer denoting Bob's number of friends of friends. Example Input: 3 2334 5 1256 4323 7687 3244 5678 1256 2 2334 7687 4323 5 2334 5678 6547 9766 9543 Output: 6
32,532
Be Awesome As Barney Stinson (BEHAPPY) Barney Stinson ;) is way too flirty. He has many girlfriends and he wants to keep all of them happy. He has M girlfriends. He bought N gifts for them. Now he knows that some girlfriends need more gifts and some need less. So he decided that he will give at least Ai gifts and at most Bi gifts to his i th girlfriend. He has to give away all the N gifts. Tell us in how many different ways he can do this. Input For each test case, first line contains two integers M and N, then follows M lines each having two integers Ai and Bi (1 ≤ i ≤ M). Input ends with M and N both equal to 0 and that case should not be processed. Output: For each test case, output the number of different ways in which he can distribute those gifts in a single line. Constraints 1 ≤ M ≤ 20, 1 ≤ N ≤ 100, 0 ≤ Ai, Bi ≤100 Example Input: 3 5 0 1 1 3 1 4 0 0 Output: 6 Explanation He can distribute 5 gifts in his 3 girlfriends in 6 different ways as follows (0 1 4), (0 2 3), (0 3 2), (1 1 3), (1 2 2), (1 3 1).
32,533
Shortcut (WPC4C) Into the new level, a witch provides an option to Mario, so that he can avoid the intense battle ahead in this level. He needs to perform a task on a sheet of paper provided by the witch. He needs to cut a rectangular area out of them so that the ratio of height to width (i.e. the height/width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2 x for some integer x). If those rules don't indicate the size of the cut area clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, he must choose the answer with the maximal height. Input The first line contains number of test cases T (T ≤ 50). The next lines contain a pair of integers x and y (1 ≤ x , y ≤ 10 9 ) which are the height and width of the sheet. Output T lines of two integers which are the height and width of the cut area. Example Input: 2 2 1 2 2 Output: 1 1 2 2
32,534
Through the troops (WPC4F) Having crossed the first hurdle, Mario encounters a long and narrow alleyway, with turtles. Mario can cross it by jumping from one turtle to another. Whenever Mario makes his jump on any given turtle, he can leave it in any of the three possible states, as per his choice. These states are: Active (A) Dormant (D) Bruised (B) There are n turtles in the street, indexed 0..(n-1). Each jump costs some amount of energy, which depends on the index of turtle as well as the state it is left in. However, Mario has to take care that no neighboring turtles are left in the same state, or otherwise they all will reunite and cause a fatal attack on Mario, as he is about to leave the alley. The neighbors of turtle i are turtles i-1 and i+1. ( Edited: If n ≥ 3,) The first and last turtles are not neighbors. You need to find out the minimum amount of energy required to cross the alley. Input first line contains no. of test cases T (T ≤ 5) T input sets are given in the following manner: the first line contains n, number of turtles (n ≤ 20) the next n lines have space separated 3 numbers (a1, a2, a3), the values of energy needed for ith turtle to change into states A D B (0 ≤ ai ≤ 1000) similarly, the inputs are given for other cases Output T lines, the minimal energy needed for each set of input Example Input: 2 3 0 1 2 1 4 8 9 2 5 4 10 10 10 2 4 9 12 7 10 6 6 6 Output: 4 25
32,535
Matrix inverse (MIFF) Let p a prime number. A set F p ={0, 1 ... p-1} equipped with the mod p addition and multiplication is a finite field. In this problem you have to compute the multiplicative inverse of some F p valued (quadratic) matrices. The input consists of blocks. The structure of a block is: n p A 1, 1 ... A 1, n ... A n, 1 ... A n, n where p is a prime number, 1 ij are in F p . The last block followed by 0 0.   The output for each block is either the multiplicative inverse of a given matrix if it exists or the word "singular" Example Input: 4 2 1 1 1 1 1 1 0 1 0 0 0 1 0 1 0 1 3 7 3 5 0 0 5 1 6 6 6 2 2 1 1 1 0 3 5 4 0 0 2 4 1 0 2 3 3 7 0 1 4 6 1 2 2 1 1 0 0 Output: 0 1 0 1 0 0 1 1 1 1 0 0 0 0 1 0 6 3 3 5 1 1 3 3 2 0 1 1 1 singular singular
32,536
Yet Another Fancy Game (GAME3) Two girls - Ivica and Marica - play an interesting game. First, they randomly choose a natural number N. They also define M = 1. Ivica plays first, then Marica, then Ivica, then Marica and so on. In each move, a girl has to increase M by 1 or multiply M by 2 (that is, M = M+1 or M = 2×M). The resulting number must not be greater than N . The loser of the game is the girl who gets M = N. The other girl is, of course, the winner. Write a program to determine the winner, assuming that both girls play optimally. Input In the first line there is an integer T (1 ≤ T ≤ 5), the number of games. T lines follow. In i th line there is an integer N (2 ≤ N ≤ 10 15) , a chosen number for i th  game. Output For each of the T games print the name of the winner. Example Input: 4 2 3 4 5 Output: Marica Ivica Marica Marica
32,537
The Glazier (GLASS) Jozo the glazier has made N square pieces of glass. The dimensions (sides) of these squares are equal to 1, 2, 3, ..., N - therefore, the areas of these squares equal to 1 2 , 2 2 , 3 2 , ..., N 2 . Four customers have arrived. Each of them buys exactly 3 pieces of of glass (Jozo will therefore sell exactly 12 pieces of glass). Each customer has stated that the sum of the dimensions  of the squares he gets must be equal to N (for example he could get the pieces with dimensions 1, 2 and N-3). Furthermore, since all customers pay the same price, Jozo wants to be fair and ensure that the sum of areas of the 3 squares must be equal for each customer (but this sum is not defined in advance). Help Jozo to choose which pieces to sell. Input A natural number N (12 ≤ N ≤ 1500). Output Print -1 if there is no solution. Otherwise, print four lines: in each of these four lines there must be three numbers from the set {1, 2, ..., N} and their sum must be equal to N. Also, the sum of squares of these three numbers must be constant for each row. All 12 numbers must be distinct. Example Input: 84 Output: 17 33 34 18 29 37 19 27 38 22 23 39
32,538
Eight Directions Crossword (EIGHT) What is an Eight Directions Crossword? It's a filled crossword in which all the words are hidden in eight directions (up, down, left and right and also up-left, down-right etc.) You have to find these hidden words in each crossword. Ðuro has made an N × N eight-directions-crossword. His crossword is a bit strange: you are given only one word and you have to find it in a crossword. To make things more difficult, you can skip some letters in the crossword while looking for the given word. More precisely, the given word is the subsequence of not necessarily consecutive letters in a row, column or a diagonal of the crossword in one of the eight directions. Now you discover that, under these conditions, you can read the given word in the crossword in multiple ways. How many? Input In the first line of the input there is an integer N (2 = N = 1000), the crossword dimension, followed by space and the given word you are to find. This word has 2-10 letters. N lines follow, representing the crossword. All letters in the crossword and in the given word are small letters of the English alphabet. Output Print the required number of ways. (This number will fit into int64 in Pascal or long long in C/C++.) Example input 2 aa aa aa   output 12 input 3 aa aaa aaa aaa   output 56 input 8 silba siolobba oooaoooo oooboooo aooooooo oboloooo oolooooo oooioooo ooossooo   output 4
32,539
Štef and Barica (WALK1) Štef lives in a house located in (0, 0). His girlfriend Barica lives in a house located in (X, Y). Štef likes walking, so he decided to walk for exactly N hours (starting from his house) and finish his route at Barica's house. Each hour, Štef moves from his current position to one of the four adjacent positions (north, south, east or west). Help Štef and calculate how many possible routes there are. (If there aren't any, print 0.) Input In the first line there is an integer N (1 ≤ N ≤ 10 6 ). In the second line there are integers X, Y separated by a space (-N ≤ X, Y ≤ N). Output Calculate the number of possible Štef's routes from (0, 0) to (X, Y) that last for exactly N hours. Print the result modulo 500 000 003. Example Input: 3 2 1 Output: 3 Input: 2 0 0 Output: 4
32,540
The Glazier 2 (GLASS2) Jozo the glazier has once again made N square pieces of glass. The dimensions (sides) of these squares are equal to 1, 2, 3, ... N - therefore, the areas of these squares equal to 1 2 , 2 2 , 3 2 , ... N 2 . Four customers have arrived once again. This time Jozo will sell all N squares of glass. Again, each of the customers must get the same total area of glass (which equals the total area of all N squares divided by four). Help Jozo and divide his N pieces of glass among the four customers. Assume that the solution (not necessarily unique) exists in all of the test data. Input An integer N (10 ≤ N ≤ 60). Output In the first line, print four numbers: the number of pieces of glass assigned to the first, to the second, to the third and to the fourth customer (respectively). In i th of the next four lines, print the dimensions of the squares of glass assigned to the i th customer. (Each square must be assigned to exactly one customer.) Example Input: 15 Output: 4 4 4 3 3 6 11 12 4 5 10 13 1 7 8 14 2 9 15
32,541
Hotels Along the Croatian Coast (HOTELS) There are N hotels along the beautiful Adriatic coast. Each hotel has its value in Euros. Sroljo has won M Euros on the lottery. Now he wants to buy a sequence of consecutive hotels, such that the sum of the values of these consecutive hotels is as great as possible - but not greater than M. You are to calculate this greatest possible total value. Input In the first line of the input there are integers N and M (1 ≤ N ≤ 300 000, 1 ≤ M < 2 31 ). In the next line there are N natural numbers less than 10 6 , representing the hotel values in the order they lie along the coast. Output Print the required number (it will be greater than 0 in all of the test data). Example input 5 12 2 1 3 4 5 output 12 input 4 9 7 3 5 6 output 8
32,542
Help the Airline Company (REMOVE) In a far away country there are N cities, and every two of them are connected by a two-way direct airplane line. Gripped by the crisis, the airline company has decided to remove as many lines as possible. The lines will be eliminated one by one. This elimination must not significantly affect the city connections, so when removing a line, it must belong to a cycle of length four. In other words, if the cities A, B, C, D are such that currently there are lines AB, BC, CD and DA, then we can remove any of these lines. It is possible to prove that there must remain at least N lines at the end of the elimination process (i.e., that we are unable to remove more lines under the described conditions). You are not required to prove it, but to write a program that helps the airline company to remove a line by line until there are exactly N left. Input 4 ≤ N ≤ 2000. Output Print one line of data for each airplane line you are removing. In each of these lines, print the numbers A, B, C, D which represent the cities forming a cycle. These numbers indicate that you are removing the line AB. Example Input: 4 Output: 2 3 1 4 3 4 2 1 Input: 5 Output: 3 4 5 2 2 3 1 5 3 5 2 1 2 4 1 5 4 5 2 1
32,543
Binomial coefficients (NWERC11A) Gunnar is quite an old and forgetful researcher. Right now he is writing a paper on security in social networks and it actually involves some combinatorics. He wrote a program for calculating binomial coefficients to help him check some of his calculations. A binomial coefficient is a number where n and k are non-negative integers. Gunnar used his program to calculate and got a number m as a result. Unfortunately, since he is forgetful, he forgot the numbers n and k he used as input. These two numbers were a result of a long calculation and they are written on one of many papers lying on his desk. Instead of trying to search for the papers, he tried to reconstruct the numbers n,k from the output he got. Can you help him and find all possible candidates? Input On the first line a positive integer: the number of test cases, at most 100. After that per test case: one line with an integer m (2 ≤ m ≤ 10 15 ): the output of Gunnar’s program. Output Per test case: one line with an integer: the number of ways of expressing m as a binomial coefficient. one line with all pairs ( n, k ) that satisfy = m . Order them in increasing order of n and, in case of a tie, order them in increasing order of k . Format them as in the sample output. Sample Input: 2 2 15 Output: 1 (2,1) 4 (6,2) (6,4) (15,1) (15,14)
32,544
Bird tree (NWERC11B) Bird tree The Bird tree 1 is an infinite binary tree, whose first 5 levels look as follows: It can be defined as follows: This is a co-recursive definition in which both occurrences of bird refer to the full (infinite) tree. The expression bird + 1 means that 1 is added to every fraction in the tree, and 1 ∕bird means that every fraction in the tree is inverted (so a ∕ b becomes b ∕ a ). Surprisingly, the tree contains every positive rational number exactly once, so every reduced fraction is at a unique place in the tree. Hence, we can also describe a rational number by giving directions ( L for left subtree, R for right subtree) in the Bird tree. For example, 2 ∕ 5 is represented by LRR . Given a reduced fraction, return a string consisting of L ’s and R ’s: the directions to locate this fraction from the top of the tree.   Input On the first line a positive integer: the number of test cases, at most 100. After that per test case: one line with two integers a and b (1 ≤ a,b ≤ 10 9 ), separated by a ’/’ . These represent the numerator and denominator of a reduced fraction. The integers a and b are not both equal to 1, and they satisfy gcd( a,b ) = 1. For every test case the length of the string with directions will be at most 10   000.   Output Per test case: one line with the string representation of the location of this fraction in the Bird tree.   Sample in- and output Input Output 3 1/2 2/5 7/3 L LRR RLLR 1 Hinze, R. (2009). The Bird tree. J. Funct. Program., 19:491–508.
32,545
Movie collection (NWERC11C) Movie collection Mr. K. I. has a very big movie collection. He has organized his collection in a big stack. Whenever he wants to watch one of the movies, he locates the movie in this stack and removes it carefully, ensuring that the stack doesn’t fall over. After he finishes watching the movie, he places it at the top of the stack. Since the stack of movies is so big, he needs to keep track of the position of each movie. It is sufficient to know for each movie how many movies are placed above it, since, with this information, its position in the stack can be calculated. Each movie is identified by a number printed on the movie box. Your task is to implement a program which will keep track of the position of each movie. In particular, each time Mr. K. I. removes a movie box from the stack, your program should print the number of movies that were placed above it before it was removed.   Input On the first line a positive integer: the number of test cases, at most 100. After that per test case: one line with two integers m and r (1 ≤ m,r ≤ 100  000): the number of movies in the stack and the number of locate requests. one line with r integers a 1 , … ,a r (1 ≤ a i ≤ m ) representing the identification numbers of movies that Mr. K. I. wants to watch. For simplicity, assume that the initial stack contains the movies with identification numbers 1 , 2 , … ,m in increasing order, where the movie box with label 1 is the top-most box.   Output Per test case: one line with r integers, where the i -th integer gives the number of movie boxes above the box with label a i , immediately before this box is removed from the stack. Note that after each locate request a i , the movie box with label a i is placed at the top of the stack.   Sample in- and output Input Output 2 3 3 3 1 1 5 3 4 4 5 2 1 0 3 0 4
32,546
Piece it together (NWERC11D) Tom has developed a special kind of puzzle: it involves a whole bunch of identical puzzle pieces. The pieces have the shape of three adjoint squares in an L-shape. The corner square is black, the two adjacent squares are white. Figure 1: A puzzle piece The puzzler is given a pattern of black and white squares in a rectangular grid. The challenge is to create that pattern using these pieces. The pieces can be rotated, but must not overlap. Tom has already designed a few nice patterns, but he needs to find out if they can be constructed with the pieces at all. Rather than trying to test this for each pattern by hand, he wants to write a computer program to determine this for him. Can you help him? Input On the first line a positive integer: the number of test cases, at most 100. After that per test case: One line with two integers n and m (1 = n,m = 500): the height and width of the grid containing the pattern, respectively. n lines, each containing m characters, denoting the grid. Each character is ‘ B ’, ‘ W ’, or ‘ . ’, indicating a black, white or empty square respectively. The grid contains at least one black or white square. Output Per test case: one line with either “ YES ” or “ NO ”, indicating whether or not it is possible to construct the pattern with the puzzle pieces. You may assume that there is an infinite supply of pieces. Sample Input: 2 3 4 BWW. WWBW ..WB 3 3 W.. BW. WBW Output: YES NO
32,547
Please, go first (NWERC11E) Please, go first You are currently on a skiing trip with a group of friends. In general, it is going well: you enjoy the skiing during the day and, of course, the après-skiing during the night. However, there is one nuisance: the skiing lift. As always, it is too small, and can only serve one person every 5 seconds. To make matters worse, you and your friends generally don’t arrive simultaneously at the lift, which means that you spend time waiting at the bottom of the mountain for the lift and at the top again for your friends. The waiting at the top is especially inefficient. In fact, you realize that if your friends haven’t arrived yet, you might as well let other people pass you in the queue. For you, it makes no difference, since otherwise you’d be waiting at the top. On the other hand, your actions might save them time if their friends have already arrived and are currently waiting for them at the top. You are wondering how much time would be saved if everybody adopts this nice attitude. You have carefully observed the queue for a while and noticed which persons form groups of friends. Suppose someone lets another pass if doing this doesn’t change his own total waiting time, but saves time for the other person. Do this over and over again until it can’t be done anymore. How much time will this save, in total? Input On the first line a positive integer: the number of test cases, at most 100. After that per test case: one line with an integer n (1 ≤ n ≤ 25000): the number of people in the line for the lift. one line with n alphanumeric characters (uppercase and lowercase letters and numbers): the queue. The first person in this line corresponds to the person at the head of the queue. Equal characters correspond to persons from the same group of friends. Output Per test case: one line with an integer: the time saved, in seconds. Sample Input 2 6 AABABB 10 Ab9AAb2bC2 Output 15 45
32,548
Pool construction (NWERC11F) You are working for the International Company for Pool Construction, a construction company which specializes in building swimming pools. A new client wants to build several new pool areas. A pool area is a rectangular grid of w × h square patches, consisting of zero or more (possibly disconnected) pools. A pool consists of one or multiple connected hole patches, which will later be filled with water. In the beginning, you start with a piece of land where each patch is either a hole in the ground ('.') or flat grass ('#'). In order to transform this land into a pool area, you must adhere to the following: You can leave a patch as it is. This costs nothing. If the patch is grass in the beginning, you can dig a hole there. This costs d EUR. If the patch is a hole in the beginning, you can fill the hole and put grass on top. This costs f EUR. You must place special boundary elements along each edge running between a final grass patch and a final hole patch, to ensure that water does not leak from the pool. This costs b EUR per boundary element. The outermost rows and columns of the pool area must always be grass. You are given the task of calculating the cost of the cheapest possible pool area given the layout of the existing piece of land. Input On the first line a positive integer: the number of test cases, at most 100. After that per test case: one line with two integers w and h (2 ≤ w, h ≤ 50): the width and height of the building site. one line with three integers d , f and b (1 ≤ d, f, b ≤ 10 000): the costs for digging a new hole, filling an existing hole, and building a boundary element between a pool and grass patch. h lines of w characters each, denoting the layout of the original building site. Output Per test case: one line with an integer: the cost of building the cheapest possible pool area from the original piece of land. Example Input: 3 3 3 5 5 1 #.# #.# ### 5 4 1 8 1 #..## ##.## #.#.# ##### 2 2 27 11 11 #. .# Output: 9 27 22
32,549
Smoking gun (NWERC11G) Andy: ”Billy the Kid fired first!” Larry: ”No, I’m sure I heard the first shot coming from John!” The arguments went back and forth during the trial after the big shoot-down, somewhere in the old wild west. Miraculously, everybody had survived (although there were serious injuries), but nobody could agree about the exact sequence of shots that had been fired. It was known that everybody had fired at most one shot, but everything had happened very fast. Determining the precise order of the shots was important for assigning guilt and penalties. But then the sheriff, Willy the Wise, interrupted: ”Look, I’ve got a satellite image from the time of the shooting, showing exactly where everybody was located. As it turns out, Larry was located much closer to John than to Billy the Kid, while Andy was located just slightly closer to John than to Billy the Kid. Thus, because sound travels with a finite speed of 340 meters per second, Larry may have heard John’s shot first, even if Billy the Kid fired first. But, although Andy was closer to John than to Billy the Kid, he heard Billy the Kid’s shot first – so we know for a fact that Billy the Kid was the one who fired first! Your task is to write a program to deduce the exact sequence of shots fired in situations like the above. Input On the first line a positive integer: the number of test cases, at most 100. After that per test case: one line with two integers n (2 ≤ n ≤ 100) and m (1 ≤ m ≤ 1000): the number of people involved and the number of observations. n lines with a string S , consisting of up to 20 lower and upper case letters, and two integers x and y (0 ≤ x, y ≤ 1 000 000): the unique identifier for a person and his/her position in Cartesian coordinates, in metres from the origin. m lines of the form “ S1 heard S2 firing before S3 ”, where S1 , S2 and S3 are identifiers among the people involved, and S2 ≠ S3 . If a person was never mentioned as S2 or S3 , then it can be assumed that this person never fired, and only acted as a witness. No two persons are located in the same position. The test cases are constructed so that an error of less than 10 -7 in one distance calculation will not affect the output. Output Per test case: one line with the ordering of the shooters that is compatible with all of the observations, formatted as the identifiers separated by single spaces. If multiple distinct orderings are possible, output “ UNKNOWN ” instead. If no ordering is compatible with the observations, output “ IMPOSSIBLE ” instead. Sample Input: 3 4 2 BillyTheKid 0 0 Andy 10 0 John 19 0 Larry 20 0 Andy heard BillyTheKid firing before John Larry heard John firing before BillyTheKid 2 2 Andy 0 0 Beate 0 1 Andy heard Beate firing before Andy Beate heard Andy firing before Beate 3 1 Andy 0 0 Beate 0 1 Charles 1 3 Beate heard Andy firing before Charles Output: BillyTheKid John IMPOSSIBLE UNKNOWN
32,550
Tichu (NWERC11H) Tichu Tichu is a card game played by four players. The players sit around a square table, and each player forms a team with the person sitting opposite him or her. The game is played with a standard deck of cards and four additional special cards. The basic rule of the game is as follows: the player who won the last trick can start a new trick with any legal combination of cards. Then, in turn, each next player can either pass or play the same combination of cards, but with a higher value. This continues until everyone passes, and at that point the player who played the last combination wins the trick and can start a new trick. The main goal is to get rid of all of your cards as soon as possible. These basic rules make it a good tactic to combine the cards in such a way that they can be played in as few combinations as possible. For simplicity we consider here a slightly modified version of the game. We ignore the special cards, so that leaves a standard deck of 52 cards, ranging over the values 2 to Ace and over the suits hearts , diamonds , clubs , and spades . The suits are indicated by the lowercase letters h , d , c , and s , while the values are indicated in increasing order by 2 – 9 , T , J , Q , K , A . The following list is a complete set of legal combinations: 1 any single card; a pair of cards of the same value; three cards of the same value; four cards of the same value; a full house, that is, three cards of the same value and two cards of another, same value, for example 444KK ; a straight of length at least five, that is, at least five cards of consecutive increasing values, for example 89TJQK . In this problem, your task is to determine the minimum number of combinations that your hand of 13 cards can be partitioned into.   Input On the first line a positive integer: the number of test cases, at most 100. After that per test case: one line that describes your hand of 13 cards. A card is described by two characters: the value followed by the suit. All cards in your hand are different.   Output Per test case: one line containing an integer n : the minimum number of combinations that your hand can be partitioned into. n lines that describe a minimal set of combinations of cards from your hand. Each line should contain the cards in one legal combination, in the same format as in the input. All cards from your hand must occur exactly once in one of the combinations. No specific ordering of the combinations or the cards within a combination is required.   Sample in- and output Input Output 2 2h 3c 4d 5d 6s Th Qc Qs Ad Tc Ts 9c 9d 2h 3h 4h 5h 6d 7s 8h 8d 8c 8s 9c Td Js 4 2h 3c 4d 5d 6s Th Ts Tc Qc Qs 9d 9c Ad 2 2h 3h 4h 5h 6d 7s 8d 9c Td Js 8h 8s 8c 1 Those who know the game of Tichu might have noticed that we removed consecutive pairs of cards as a valid combination.
32,551
Tracking RFIDs (NWERC11I) Tracking RFIDs Jeroen operates a warehouse storage facility for the North Western Electrical Resource Company (NWERC). When a customer places an order with NWERC, this order is conveyed to the warehouse. Jeroen’s task is to then find the products ordered, pack them into a box, and ship them to the customer. NWERC has an unusual warehouse policy: the products are not arranged in any particular order, and are strewn all over the place. However, it is possible for Jeroen to do his job because each product is tracked using RFID technology 1 . Specifically, each product is assigned a wireless RFID chip as soon as it enters the warehouse, and sensors located on the warehouse ceiling are used to automatically track the products. By default, each sensor has a range of r units – that is, it can read any RFID chip that is located at most r units from it in a straight line. However, if the line segment between a sensor and a product intersects with or touches x walls, the range of the sensor is reduced by x units in that direction. Furthermore, the sensors may fail to read an RFID chip due to interference from other sensors, so the distance between any pair of sensors in the warehouse is guaranteed to be at least r units. You may further assume that no sensor or product is placed on a wall. Jeroen now wants to determine, for each product, which sensors can read its RFID chip. Can you help him?   Figure 1: Illustration of sensors, walls and products as in the Sample Input.   Input On the first line one positive integer: the number of test cases, at most 100. After that per test case: one line with four integers s (1 ≤ s ≤ 250  000), r (1 ≤ r ≤ 25), w (0 ≤ w ≤ 10) and p (1 ≤ p ≤ 10  000) where s represents the number of sensors, r the range of each sensor, w the number of walls and p the number of products. s lines containing two integers x i and y i (-10  000 ≤ x i ,y i ≤ 10  000). Each such line represents a sensor at location ( x i , y i ). The distance between any pair of sensors is guaranteed to be at least r units. w lines containing four integers bx i , by i , ex i and ey i (-10  000 ≤ bx i ,by i ,ex i ,ey i ≤ 10  000). Each such line represents a wall, which should be considered as straight line segment from ( bx i , by i ) to ( ex i , ey i ). The length of this line segment will be positive. p lines, each containing two integers px i and py i (-10  000 ≤ px i ,py i ≤ 10  000). Each such line represents a product at location ( px i , py i ).   Output Per test case: p lines, each representing a product in the order they appear in the input. Each line should contain an integer t , the number of sensors that can track the product; this integer should then be followed by a list of t ordered pairs representing the corresponding sensor locations. If there are multiple sensors, they should be sorted in increasing order by x -coordinate. If multiple sensors have the same x -coordinate, they should be sorted in increasing order by y -coordinate.   Sample in- and output Input Output 1 4 3 4 7 0 0 -1 3 2 3 11 5 -4 -1 5 -1 3 5 6 1 11 4 11 3 12 5 12 8 1 1 0 -2 4 4 11 2 13 5 13 7 14 5 3 (-1,3) (0,0) (2,3) 1 (0,0) 0 0 1 (11,5) 0 0 1 Objects, that have a radio-frequency identification (RFID) tag attached, can be tracked using radio waves.
32,552
Train delays (NWERC11J) Train delays Last year, some of the judges tried to travel to NWERC’10 by train. This turned into a big disaster: on the way there, a fire in a control room caused huge delays, while on the return trip, trains in Bremen were delayed due to a terrorist threat in Hamburg. Of course, these huge delays caused other delays in the train schedule, so the big question was which trains to take: would it be better to take this slow regional train now, or wait for that intercity train, which has a big chance of being delayed? This year, the judges have planned ahead and carefully analyzed the train schedule. They even kept track of how often trains were delayed and by how much. Now that they have all this information, they want to travel as quickly possible, minimizing the expected duration of the journey. Can you help them? For each train connection, the judges know exactly what its scheduled departure time and duration are, as well as the probability that its arrival at the destination will be delayed. You may assume that the probabilities of delays are independent and that the judges can adapt their itinerary as they go, depending on any delays which they might already have incurred. Trains always depart on time, but may arrive late and the judges do not know whether a train’s arrival will be delayed until they have boarded it. It takes judges no time to switch trains, so they can take a connecting train that departs at the same time as they arrive at a place. The judges can choose the time of their initial departure as they wish and they want to minimize the expected duration 1 of their total trip.   Input On the first line a positive integer: the number of test cases, at most 100. After that per test case: one line with the judges’ place of origin and destination, these are different. one line with an integer n (1 ≤ n ≤ 1  000): the number of train connections. n lines, each describing a train connection: the origin and destination of this connection, these are different. an integer m (0 ≤ m ≤ 59), the departure time in minutes after each full hour. an integer t (1 ≤ t ≤ 300), the standard journey time (assuming no delays). an integer p (0 ≤ p ≤ 100), the probability of delays as a percentage. an integer d (1 ≤ d ≤ 120), the maximum delay in minutes. All place names are given as strings of upper and lower case alphabetical characters, of length at most 20. If a train is delayed, then the length of the delay will be a whole number of minutes, and will be uniformly distributed in the range [1 ,d ].   Output Per test case: one line with a floating point number: the minimum expected duration of the total trip in minutes. This number should be accurate up to 10 -6 relative or absolute precision. Output IMPOSSIBLE instead if the destination is not reachable.   Sample in- and output Input Output 3 Hamburg Bremen 3 Hamburg Bremen 15 68 10 5 Hamburg Bremen 46 55 50 60 Bremen Frankfurt 14 226 10 120 Amsterdam Rotterdam 1 Amsterdam Utrecht 10 22 5 10 BremenVegesack Utrecht 9 BremenVegesack BremenHbf 15 10 0 1 BremenVegesack BremenHbf 45 10 0 1 BremenVegesack Leer 23 140 10 15 BremenHbf Osnabruck 44 51 60 70 Osnabruck Amersfoort 55 147 38 40 Amersfoort Utrecht 24 15 30 15 Amersfoort Utrecht 54 15 10 35 Leer Groningen 45 140 5 10 Groningen Amersfoort 46 96 10 20 68.3 IMPOSSIBLE 305.0532857 Note in the first example that it is better to take the slower train from Hamburg to Bremen, since the fast train would give an expected travel time of 70 . 25 minutes. 1 Given a travel plan of which trains to take (depending on previous connections and delays), the expected trip duration E is defined to be the sum of the trip duration T i for each itinerary i possibly taken multiplied by the chance p i of that itinerary occurring: E = ∑ i p i  T i .
32,553
Help Dr Whooves (PONY1) On the continent of Equestria, Dr. Whooves used to have it all. He owned a very successful transportation business which was connected to all the villages and towns of Equestria. However, when Discord took over Equestria, a lot of the ponies got confused. Even now, some of his workers are working at the wrong routes, and Dr. Whooves is pretty sure that his business is now fragmented, and that he isn't connected to all the villages of Equestria anymore. Twilight Sparkle and her friends are here to help. Dr. Whooves knows that there is some minimum number of routes he'll need to add to make sure his business is reconnected. He asked Twilight Sparkle and her friends to find out how many different ways he can choose to add this minimum number of routes so that his business is connected to all the cities of Equestria. There might be a lot of ways, so the ponies have agreed upon giving the answer modulo 999,999,937. Input First is an integer T, the number of test cases, followed by T sets of data for each test case. Each test case is in the following format: It indicates that there are C cities, numbered 1 through C, and R routes, on a single line. After that follow R lines, each containing two city numbers Ai and Bi, indicating a bidirectional route between cities Ai and Bi. Test cases are not separated by blank lines, and the input ends with the last line of the final test case. Constraints: 1 ≤ C ≤ 1000000, 0 ≤ R < min{C, 100000} Output T lines, each containing the number of different ways Dr. Whooves can choose to add the minimum number of routes required to reconnect his business, modulo 999999937. Example Input: 4 4 0 3 1 1 2 5 4 1 2 2 3 3 4 2 5 7 6 2 3 3 4 2 4 5 6 6 7 7 5 Output: 16 2 1 63
32,554
ABC Path (ABCPATH) You will be given a 2-dimensional grid of letters. Find the length of the longest path of consecutive letters, starting at 'A'. Paths can step from one letter in the grid to any adjacent letter (horizontally, vertically, or diagonally). For example, in the following grid, there are several paths from 'A' to 'D', but none from 'A' to 'E': One such path is: Input Each test case will start with a line contains two integers H, W the height and width of the grid respectively 1 <= H, W <= 50. Then H lines follow each of W uppercase letters only. Input terminates with H = 0 and W = 0. Output For each test case print “Case C: X” without quotes where C is the case number starting with 1 and X is the solution. Example Sample Input: 4 3 ABE CFG BDH ABC 0 0 Sample Output: Case 1: 4
32,555
Alice and Bob (ALICE) Alice and Bob are very smart guys and they like to play all kinds of games in their spare time. The most amazing thing is that they always find the best strategy, and that's why they feel bored again and again. They just invented a new game, as they usually did. The rule of the new game is quite simple. At the beginning of the game, they write down N random positive integers, then they take turns (Alice first) to either: Decrease a number by one. Erase any two numbers and write down their sum. Whenever a number is decreased to 0, it will be erased automatically. The game ends when all numbers are finally erased, and the one who cannot play in his (her) turn loses the game. Here's the problem: Who will win the game if both use the best strategy? Find it out quickly, before they get bored of the game again! Input The first line contains an integer T (1 ≤ T ≤ 4000), indicating the number of test cases. Each test case contains several lines. The first line contains an integer N (1 ≤ N ≤ 50). The next line contains N positive integers A 1 ... A N (1 ≤ A i ≤ 1000), represents the numbers they write down at the beginning of the game. Output For each test case in the input, print one line: "Case #X: Y" , where X is the test case number (starting with 1) and Y is either "Alice" or "Bob" . Example Input: 3 3 1 1 2 2 3 4 3 2 3 5 Output: Case #1: Alice Case #2: Bob Case #3: Bob
32,556
Break the Chocolate (BC) Benjamin is going to host a party for his big promotion coming up. Every party needs candies, chocolates and beer, and of course Benjamin has prepared some of those. But as everyone likes to party, many more people showed up than he expected. The good news is that candies are enough. And for the beer, he only needs to buy some extra cups. The only problem is the chocolate. As Benjamin is only a 'small court officer' with poor salary even after his promotion, he can not afford to buy extra chocolate. So he decides to break the chocolate cubes into smaller pieces so that everyone can have some. He have two methods to break the chocolate. He can pick one piece of chocolate and break it into two pieces with bare hand, or put some pieces of chocolate together on the table and cut them with a knife at one time. You can assume that the knife is long enough to cut as many pieces of chocolate as he want. The party is coming really soon and breaking the chocolate is not an easy job. He wants to know what is the minimum number of steps to break the chocolate into unit-size pieces (cubes of size 1×1×1). He is not sure whether he can find a knife or not, so he wants to know the answer for both situations. Input The first line contains an integer T (1 ≤ T ≤ 10000), indicating the number of test cases. Each test case contains one line with three integers N , M , K (1 ≤ N , M , K ≤ 2000), meaning the chocolate is a cube of size N × M × K . Output For each test case in the input, print one line: "Case #X: A B" , where X is the test case number (starting with 1) , A and B are the minimum numbers of steps to break the chocolate into N × M × K unit-size pieces with bare hands and knife respectively. Example Input: 2 1 1 3 2 2 2 Output: Case #1: 2 2 Case #2: 7 3
32,557
Construct the Great Wall (CGW) A defensive wall is a fortification used to protect a city or settlement from potential aggressors. From ancient to modern times, they were used to enclose settlements. Generally, these are referred to as city walls or town walls. Even though, our ancestors decided to build a Great Wall to protect the northern borders of the Chinese Empire against invasion by various nomadic groups. The map is given as an rectangle area of size N × M . Each grid is an empty area, a city or an enemy. The Great Wall is a simple polygon build alone the edge of the grids, enclosing all the cities and keeping all the enemies out. The Great Wall is not easy to build, so we should make the Great Wall as short as possible. Now it is your job to calculate the length of the shortest Great Wall so that it can protect all the cities from the enemies. Input The first line contains an integer T (1 ≤ T ≤ 50), indicating the number of test cases. Each test case contains several lines. The first line contains two integer H , W (1 ≤ H , W ≤ 8), indicating the number of rows and columns of the map. The following H lines contains W chars, indicating the map. 'o' represents a city, '.' represents a empty area and 'x' represents an enemy. You can assume that there will be at least one city on the map. Output For each test case in the input, print one line: "Case #X: Y" , where X is the test case number (starting with 1) and Y is the length of the shortest Great Wall (-1 if impossible). Example Input: 3 3 3 .o. .x. o.o 4 4 .... .ox. .xo. .... 5 5 .ooo. .x... ..xoo x.xoo .ox.x Output: Case #1: 14 Case #2: -1 Case #3: 28 Hint A simple polygon is a closed polygonal chain of line segments in the plane which do not have points in common other than the common vertices of pairs of consecutive segments. The solution for the first test case in sample is shown in Figure 1. There is no solution for the second test case because no matter how you build the Great Wall, it will always intersects with itself (Figure 2).
32,558
Disney Fastpass (DISNEY) Disney's FastPass is a virtual queuing system created by the Walt Disney Company. First introduced in 1999 (thugh the idea of a ride reservation system was first introduced in world fairs), FastPass allows guests to avoid long lines at the attractions on which the system is installed, freeing them to enjoy other attractions during their wait. The service is available at no additional charge to all park guests. --- Wikipedia Disneyland is a large theme park with plenties of entertainment facilities, also with a large number of tourists. Normally, you need to wait for a long time before getting the chance to enjoy any of the attractions. The FastPass is a system allowing you to pick up FastPass-tickets in some specific position, and use them at the corresponding facility to avoid long lines. With the help of the FastPass System, one can arrange his/her trip more efficiently. You are given the map of the whole park, and there are some attractions that you are interested in. How to visit all the interested attractions within the shortest time? Input The first line contains an integer T (1 ≤ T ≤ 25), indicating the number of test cases. Each test case contains several lines. The first line contains three integers N , M , K (1 ≤ N ≤ 50, 0 ≤ M ≤ N ( N -1)/2, 0 ≤ K ≤ 8), indicating the number of locations(starting with 1, and 1 is the only gate of the park where the trip must be started and ended), the number of roads and the number of interested attractions. The following M lines each contains three integers A , B , D (1 ≤ A , B ≤ N , 0 ≤ D ≤ 10 4 ) which means it takes D minutes to travel between location A and location B . The following K lines each contains several integers P i , T i , FT i , N i , F i ,1 , F i ,2 ... F i , N i -1 , F i , N i , (1 ≤ P i , N i , F i , j ≤ N , 0 ≤ FT i ≤ T i ≤ 10 4 ), which means the i-th interested attraction is placed at location P i and there are N i locations F i ,1 , F i ,2 ... F i , N i where you can get the FastPass for the i -th attraction. If you come to the i -th attraction with its FastPass, you need to wait for only FT i minutes, otherwise you need to wait for T i minutes. You can assume that all the locations are connected and there is at most one road between any two locations. Note that there might be several attractions at one location. Output For each test case in the input, print one line: "Case #X: Y" , where X is the test case number (starting with 1) and Y is the minimum time of the trip. Example Input: 2 4 5 2 1 2 8 2 3 4 3 4 19 4 1 6 2 4 7 2 25 18 1 3 4 12 6 1 3 4 6 2 1 2 5 1 4 4 3 1 1 3 2 1 3 4 1 2 4 10 2 8 3 1 4 4 8 3 1 2 Output: Case #1: 53 Case #2: 14
32,559
Eliminate the Conflict (EC) Conflicts are everywhere in the world, from the young to the elderly, from families to countries. Conflicts cause quarrels, fights or even wars. How wonderful the world will be if all conflicts can be eliminated. Edward contributes his lifetime to invent a 'Conflict Resolution Terminal' and he has finally succeeded. This magic item has the ability to eliminate all the conflicts. It works like this: If any two people have conflict, they should simply put their hands into the 'Conflict Resolution Terminal' (which is simply a plastic tube). Then they play 'Rock, Paper and Scissors' in it. After they have decided what they will play, the tube should be opened and no one will have the chance to change. Finally, the winner have the right to rule and the loser should obey it. Conflict Eliminated! But the game is not that fair, because people may be following some patterns when they play, and if the pattern is founded by others, the others will win definitely. Alice and Bob always have conflicts with each other so they use the 'Conflict Resolution Terminal' a lot. Sadly for Bob, Alice found his pattern and can predict how Bob plays precisely. She is very kind that doesn't want to take advantage of that. So she tells Bob about it and they come up with a new way of eliminate the conflict: They will play the 'Rock, Paper and Scissors' for N round. Bob will set up some restricts on Alice. But the restrict can only be in the form of you must play the same (or different) on the i -th and j -th rounds . If Alice loses in any round or break any of the rules she loses, otherwise she wins. Will Alice have a chance to win? Input The first line contains an integer T (1 ≤ T ≤ 50), indicating the number of test cases. Each test case contains several lines. The first line contains two integers N , M (1 ≤ N ≤ 10000, 1 ≤ M ≤ 10000), representing how many round they will play and how many restricts are there for Alice. The next line contains N integers B 1 , B 2 , ..., B N , where B i represents what item Bob will play in the i -th round. 1 represents Rock, 2 represents Paper, 3 represents Scissors. The following M lines each contains three integers A , B , K (1 ≤ A , B ≤ N , K =0 or 1) represent a restrict for Alice. If K equals 0, Alice must play the same on A -th and B -th round. If K equals 1, she must play different items on A -th and B -th round. Output For each test case in the input, print one line: "Case #X: Y" , where X is the test case number (starting with 1) and Y is "yes" or "no" represents whether Alice has a chance to win. Example Input: 2 3 3 1 1 1 1 2 1 1 3 1 2 3 1 5 5 1 2 3 2 1 1 2 1 1 3 1 1 4 1 1 5 1 2 3 0 Output: Case #1: no Case #2: yes
32,560
Fruit Ninja (FNINJA) Fruit Ninja is a juicy action game enjoyed by millions of players around the world, with squishy, splat and satisfying fruit carnage! Become the ultimate bringer of sweet, tasty destruction with every slash. --- Wikipedia It is a very popular game on cell phones where people can enjoy cutting the fruit by touching the screen. The screen is rectangular, and all the fruit can be considered as circles, with coordinate of the center, and radius. Note that the fruit may overlap with each other. In this problem, a touch is a straight line cutting through the whole screen, scoring all the fruits it cuts or touches. Now Fred is playing the Fruit Ninja, and seems absorbed in the game. He's desperate to create a new record, so he asks you for help. Now you are given a screen shot of the game, help him find the highest score he can get in a single touch. Input The first line contains an integer T (1 ≤ T ≤ 50), indicating the number of test cases. Each test case contains several lines. The first line contains an integer N (1 ≤ N ≤ 1000), indicating the number of fruit. The following N lines each contains three integers X i , Y i , R i (-1000 ≤ X , Y ≤ 1000, 1 ≤ R i ≤ 1000), representing a fruit on the screen, where ( X , Y ) is the coordinate of the center of the fruit, and R i is the radius. You can assume the screen is infinite. Output For each test case in the input, print one line: "Case #X: Y" , where X is the test case number (starting with 1) and Y is maximum number of fruit that you can cut in a single touch. It is guaranteed that the answer will remain the same even if you expand the radius of all the fruit slightly by 10 -5 . Example Input: 2 4 -2 5 1 5 5 1 -3 2 1 0 1 1 4 -4 5 1 3 2 1 -5 3 1 4 -3 1 Output: Case #1: 3 Case #2: 2
32,561
GRE Words (GRE) Recently George is preparing for the Graduate Record Examinations (GRE for short). Obviously the most important thing is reciting the words. Now George is working on a word list containing N words. He has so poor a memory that it is too hard for him to remember all of the words on the list. But he does find a way to help him to remember. He finds that if a sequence of words has a property that for all pairs of neighboring words, the previous one is a substring of the next one, then the sequence of words is easy to remember. So he decides to eliminate some words from the word list first to make the list easier for him. Meantime, he doesn't want to miss the important words. He gives each word an importance, which is represented by an integer ranging from -1000 to 1000, then he wants to know which words to eliminate to maximize the sum of the importance of remaining words. Negative importance just means that George thought it useless and is a waste of time to recite the word. Note that although he can eliminate any number of words from the word list, he can never change the order between words. In another word, the order of words appeared on the word list is consistent with the order in the input. In addition, a word may have different meanings, so it can appear on the list more than once, and it may have different importance in each occurrence. Input The first line contains an integer T (1 ≤ T ≤ 50), indicating the number of test cases. Each test case contains several lines. The first line contains an integer N (1 ≤ N ≤ 2×10 4 ), indicating the number of words. Then N lines follows, each contains a string S i and an integer W i , representing the word and its importance. S i contains only lowercase letters. You can assume that the total length of all words will not exceeded 3×10 5 . Output For each test case in the input, print one line: "Case #X: Y" , where X is the test case number (starting with 1) and Y is the largest importance of the remaining sequence of words. Example Input: 1 5 a 1 ab 2 abb 3 baba 5 abbab 8 Output: Case #1: 14 There was a serious and subtle problem regarding the test cases. It has been fixed and all submissions were rejudged now.
32,562
Holiday Accommodation (HOLI) Nowadays, people have many ways to save money on accommodation when they are on vacation. One of these ways is exchanging houses with other people. Here is a group of N people who want to travel around the world. They live in different cities, so they can travel to some other people's city and use someone's house temporary. Now they want to make a plan that choose a destination for each person. There are two rules should be satisfied: All the people should go to one of the other people's city. Two of them never go to the same city, because they are not willing to share a house. They want to maximize the sum of all people's travel distance. The travel distance of a person is the distance between the city he lives in and the city he travels to. These N cities have N -1 highways connecting them. The travelers always choose the shortest path when traveling. Given the highways' information, it is your job to find the best plan, that maximum the total travel distance of all people. Input The first line of input contains one integer T (1 ≤ T ≤ 10), indicating the number of test cases. Each test case contains several lines. The first line contains an integer N (2 ≤ N ≤ 10 5 ), representing the number of cities. Then the following N -1 lines each contains three integers X , Y , Z (1 ≤ X , Y ≤ N , 1 ≤ Z ≤ 10 6 ), means that there is a highway between city X and city Y , and length of that highway. You can assume all the cities are connected and the highways are bi-directional. Output For each test case in the input, print one line: "Case #X: Y" , where X is the test case number (starting with 1) and Y represents the largest total travel distance of all people. Example Input: 2 4 1 2 3 2 3 2 4 3 2 6 1 2 3 2 3 4 2 4 1 4 5 8 5 6 5 Output: Case #1: 18 Case #2: 62
32,563
Isabella Message (ISAB) Isabella and Steve are very good friends, and they often write letters to each other. They exchange funny experiences, talk about people around, share their feelings and write about almost everything through the letters. When the letters are delivered, they are quite afraid that some other people (maybe their parents) would peek. So they encrypted the letter, and only they know how to decrypt it. This guarantees their privacy. The encrypted message is an N × N matrix, and each grid contains a character. Steve uses a special mask to work as a key. The mask is N × N (where N is an even number) matrix with ( N × N )/4 holes of size 1 × 1 on it. The decrypt process consist of the following steps: Put the mask on the encrypted message matrix. Write down the characters you can see through the holes, from top to down, then from left to right. Rotate the mask by 90 degrees clockwise. Go to step 2, unless you have wrote down all the N × N characters in the message matrix. Erase all the redundant white spaces in the message. For example, you got a message shown in figure 1, and you have a mask looks like figure 2. The decryption process is shown in figure 3, and finally you may get a message "good morning" . You can assume that the mask is always carefully chosen that each character in the encrypted message will appear exactly once during decryption. However, in the first step of decryption, there are several ways to put the mask on the message matrix, because the mask can be rotated (but not flipped). So you may get different results such as "od morning go" (as showed in figure 4), and you may also get other messages like "orning good m" , "ng good morni" . Steve didn't know which direction of the mask should be chosen at the beginning, but after he tried all possibilities, he found that the message "good morning" is the only one he wanted because he couldn't recognize some words in the other messages. So he will always consider the message he can understand the correct one. Whether he can understand a message depends whether he knows all the words in the message. If there are more than one ways to decrypt the message into an understandable one, he will choose the lexicographically smallest one. The way to compare two messages is to compare the words of two messages one by one, and the first pair of different words in the two messages will determine the lexicographic order of them. Isabella sends letters to Steve almost every day. As decrypting Isabella's message takes a lot of time, and Steve can wait no longer to know the content of the message, he asked you for help. Now you are given the message he received, the mask, and the list of words he already knew, can you write a program to help him decrypt it? Input The first line contains an integer T (1 ≤ T ≤ 100), indicating the number of test cases. Each test case contains several lines. The first line contains an even integer N (2 ≤ N ≤ 50), indicating the size of the matrix. The following N lines each contains exactly N characters, representing the message matrix. The message only contains lowercase letters and periods ( '.' ), where periods represent the white spaces. You can assume the matrix contains at least one letter. The following N lines each contains N characters, representing the mask matrix. The asterisk ( '*' ) represents a hole, and period ( '.' ) otherwise. The next line contains an integer M (1 ≤ M ≤ 100), the number of words he knew. Then the following M lines each contains a string represents a word. The words only contain lowercase letters, and its length will not exceed 20. Output For each test case in the input, print one line: "Case #X: Y" , where X is the test case number (starting with 1) and Y is Isabella's message. If Steve cannot understand the message, just print the Y as "FAIL TO DECRYPT" . Example Input: 3 4 o.do .ng. grmn o.i. .*.. *.*. .... *... 2 good morning 4 ..lf eoyv oeou vrer ..*. .*.. .... *.*. 5 i you the love forever 4 .sle s.c. e.fs ..uu *... .*.. ...* ..*. 1 successful Output: Case #1: good morning Case #2: love you forever Case #3: FAIL TO DECRYPT
32,564
Ji-Tu Problem (JITU) There are some chickens and rabbits in the cage. They have fifteen heads and forty feet in all. How many chickens and rabbits are there respectively? It is a classical math problem which can date back to the Northern and Southern Dynasties (420-589). Here is an interesting algorithm to solve the problem: Assume that the chickens and rabbits are well trained. You whistle, and all of them lift a leg, then there are 40-15=25 feet on the floor. You whistle again, and there are 25-15=10 legs remain standing. After two whistles, all the chickens sit on the floor, and all the rabbits stand on two legs. So there are 10/2=5 rabbits and 15-5=10 chickens. John has a farm with lots of animals in it. He is now facing the similar problem. There are exactly N kinds of animals and he wants to know their quantities. He only knows that different kinds of animals have different number of legs (at least one), but he has no idea how many legs they each have. He trains the animals and tries to figure it out using the algorithm stated above. First he makes all the animals stand up with all their legs and counts their legs. Then, for each time he whistles, all the animals lift one leg(if it has at least one leg standing on the ground), and then he counts the feet again. After K times, he thinks that it is enough to determine the quantity of each kind of animal, but does it really work? So, it is your job to help him to solve the problem. Input The first line contains an integer T (1 ≤ T ≤ 100), indicating the number of test cases. Each test case contains two lines. The first line contains two integers N (1 ≤ N ≤ 1000) and K (1 ≤ K ≤ 1000), representing the number of different kinds of animals and the time he whistles. The second line contains K +1 integers A 0 , A 1 ... A K (0 ≤ A i ≤ 10 4 ) where A i represents the number of legs after his i -th whistle. Output For each test case in the input, print several lines. The first line contains "Case #X:" , where X is the test case number (starting with 1). The next line contains "No Solution" , "Unique Solution" or "Multiple Solutions" according to the result. If the result is uniquely determined, you should print N extra lines each contains two integer L i , N i , where L i represents how many legs does the i -th kind of animal have and N i represents the number of i -th kind of animal. The animals should be sorted by the number of their legs in ascending order. Example Input: 3 2 3 14 9 6 3 2 2 8 5 3 3 2 20 13 8 Output: Case #1: Unique Solution 1 2 4 3 Case #2: No Solution Case #3: Multiple Solutions
32,565
Will it ever stop (WILLITST) When Bob was in library in University of Warsaw he saw on one of facades caption :"Will it ever stop?" and below some mysterious code: while n > 1 if n mod 2 = 0 then n:=n/2 else n:=3*n+3 Help him finding it out ! Input In first line one number n<=10^14. Output Print "TAK" if program will stop, otherwise print "NIE" Example Input: 4 Output: TAK
32,566
IQ Team (IQTEAM) In Byteland we can study only math and IT. In the university there are n math students and m IT students. Rector Byteasar knows IQ of every student. He wants to make the best team, which would solve the hardest human being problems. So he decided to pick team with the highest summary IQ. Of course it's not everything. He wants to make team in which each student knows another students from team. Every student from IT know other student from IT and same with math students. Help him finding team with the largest summary IQ and in which every student from team knows another students from team. Input In first line n, m, k (0 < n ≤ 400, 0 < m ≤ 400, 0 ≤ k ≤ n × m) which means number of math students, number of IT students, number of friendships between IT and math student. In next k lines pairs 0 < ai ≤ n, 0 < bi ≤ m, which means ai student from math knows bi student from IT. In next line n numbers, IQ of i-th math student. In next line m numbers, IQ of i-th IT student. Output Output in one line : number of team's summary IQ. Example Input: 3 2 3 1 1 2 1 2 2 1 3 1 1 2 Output: 6
32,567
111…1 Squared (GUANGGUN) We call an integer Sticks if its decimal representation contains only digit 1. Let S( n ) be the sticks with n digits, find the sum of digits of S(n) 2 For example, S(9) 2 =12345678987654321, its sum of digits is 81. Input Each line contains an integer represents n (1 ≤ n ≤ 10 18 ). Input is terminated by EOF, and contains at most 100 lines. Output For each n , print an integer represents the answer. Example Input: 9 10 Output: 81 82
32,568
Fibonacci vs Polynomial (PIBO) Define a sequence Pib (n) as following Pib (0) = 1 Pib (1) = 1 otherwise, Pib (n) = Pib (n-1) + Pib (n-2) + P (n) Here P is a polynomial. Given n and P , find Pib (n) modulo 1,111,111,111. Input First line of input contains two integer n and d (0 ≤ n ≤ 10 9 , 0 ≤ d ≤ 100), d is the degree of polynomial. The second line contains d +1 integers c 0 , c 1 … c d , represent the coefficient of the polynomial (Thus P (x) can be written as Σ c i x i ). 0 ≤ c i ≤ 100 and c d ≠ 0 unless d = 0. Output A single integer represents the answer. Example Input: 10 0 0 Output: 89 Input: 10 0 1 Output: 177 Input: 100 1 1 1 Output: 343742333
32,569
Playing with Words (PWORDS) Amr M. believes in conspiracies. He is very suspicious about everything, and he is always trying to uncover the truth to everyone (or so he thinks). Lately he became very suspicious of TV ads, especially the ones that are made of 2 words: ad1 and ad2, and thinks they carry hidden messages. After contacting his top secret resources, he found out the process that the evil people use to hide the message. The original message is always two strings: orig1 and orig2. The transformation happened as follows: The letters from orig1 are shuffled. The letters from orig2 are shuffled. One letter from either orig1 or orig2 is replaced with its next or previous letter in the alphabet. This produces ad1 and ad2 from orig1 and orig2 respectively. For example for orig1 = "bcd", orig2 = "wcy" we may have ad1 = "dcb", ad2 = "cxy" (shuffled to cwy and 'w' replaced with 'x'.) After more research, Amr also found out the distance X, which is equal to distance(orig1, ad1) + distance (orig2, ad2). The distance between 2 strings is the sum of absolute difference between the letters at same positions (e.g. difference("ab", "cd") = abs('a'-'c') + abs('b'-'d') = 4) But the number of possible original messages appears to be very high, so Amr hired you to count them. Given string ad1 and ad2, and X = distance(orig1, ad1) + distance (orig2, ad2), return the number of possible strings orig1 and orig2. Input The first line of input contains an integer T that represents the number of test cases, then follow T lines each line is in format ad1 ad2 X, space separated where ad1, ad2 are composed from English lowercase letters. 1 ≤ length (ad1), length(ad2) ≤ 10, 'b' ≤ ad1[i], ad2[i] ≤ 'y' and 0 ≤ X ≤ 100000 Output For each test case, output a single line of output in the form “Case K: cnt” where K is the number of the test case and cnt is the number of possible strings orig1 and orig2. Example Input: 2 c n 1 kbenh kbenh 5 Output: Case 1: 4 Case 2: 16
32,570
Magic Crystals and Laser Beams (MCLB) John and Ged are playing a game with magic crystals and a laser beams. The game starts by arranging a 64 magic crystal in a single row and both John and Ged stand on the right of this row and start shooting them with laser beams. The magic crystals come in different colors each of which has a different behavior.  The red crystal absorbs the laser beam while the blue crystal allows the laser beam to move through it passing to the following crystal. In both cases, the crystals flip its color: red crystal flips to blue crystal while blue crystal flips to red crystal. The behavior of crystals with other colors is not always defined so they will not be part of the game. The game ends when all the magic crystals are all red. After a long time of playing with the magic crystals, John was wondering, given start state of crystals order, after how many laser beams they can reach a given target order before reaching the end of the game. Kindly help them J, and if the target state can’t be reached, tell them. Input Specification: A row of crystals is represented by a string, and the row's right is the last character in the given string. The first line of input contains an integer T that represents the number of test cases, then follow 2T lines such that each case will consist of 2 lines each of them contain a string of exactly 64 character either R (for Red) or B (for Blue) . The first line is the starting state of the game and the second line is the state that John wonders if they can reach. Output Specification: For each test case, output a single line of output in the form “Case K: state” where K is the number of the test case and state is either “The goal state could be reached after X laser beams.” Or “The goal state will never be reached!” where X is the number of laser beams needed before reaching the goal state. Sample input: 3 BBRRBRBRBRBBRBBBRBBRBRBBBRBBBRBRRRBBRBRBBRBRBRBRBBRBRBRBRRBBBBBR BBRRBRBRBRBBRBBBRBBRBRBBBRBBBRBRRRBBRBRBBRBRBRBRBBRBRBRBRBRRRRRR BBRRBRBRBRBBRBBBRBBRBRBBBRBBBRBRRRBBRBRBBRBRBRBRBBRBRBRBRRBBBBBR RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR BBRRBRBRBRBBRBBBRBBRBRBBBRBBBRBRRRBBRBRBBRBRBRBRBBRBRBRBRRBBBBBR Sample Output: Case 1: The goal state could be reached after 2 laser beams. Case 2: The goal state will never be reached! Case 3: The goal state will never be reached!
32,571
Road Network (RDNWK) In a country of N cities, the government would like to develop a new system that can answer drivers’ queries to find the shortest path between 2 cities in the country road network. However, some cities are more exciting than others, and drivers would prefer driving through them. Last month, a voting for the most exciting cities in the country was conducted, and a ranking of the P most exciting cities has been made. The government decided to utilize this ranking so that drivers can find the shortest path between 2 cities that only goes through the first K cities of the ranking as intermediate cites on the road. Hence, the query is defined as: the source city, the destination city, and K for the first K cities from the ranking. (Note that some cities may not be exciting at all, and so they will not be included in the ranking, i.e. P ≤ N) Given undirected graph representing the country cities, and ranked list of exciting cities, you are to answer Q quires, each one asking for the shortest path between 2 cities utilizing only the first K cities from the ranked list. For example, given the graph in the sample (4 cities and ranked list [2 1]) 1 - Query (k = 0, Src = 3, dest = 4): means no cities to use as intermediate, hence only direct path allowed 3-4 with cost 10 . 2 - Query (k = 1, Src = 3, dest = 4): means we can use first city on list (2), hence we can choose between paths (3-4, 3-2-4) path 3-2-4 with cost 8 is best. 3 - Query (k = 2, Src = 3, dest = 4): means we can use first 2 cities on list (1, 2), hence we can choose between paths (3-4, 3-2-4, 3-2-1-4) path 3-2-1-4 with cost 6 is best. Input The first line of input contains an integer T that represents the number of test cases, then follow T test cases, each in following format: Line 1 - N (1 ≤ N ≤ 150), the number of cities of the country. N-1 lines follow, where ith line represents ith-city connection costs, C i,j is the cost of edge (i, j), if there is no edge between i, j then C i, j = -1 else 1 ≤ C i,j ≤ 10000.             C 1,2     C 1,3     ... C 1,N             C 2,3     C 2,4     ... C 2,N             ...             C N-1,N Line N+1 - P (0 ≤ P ≤ N), represents the size of ranked list. Line N+2 - P space-separated list of distinct cities ids (1 ≤ city id ≤ N) Line N+3 - Q (1 ≤ Q ≤ 6000), represents the number of queries. Q lines follow             K source destination ... Note that: 0 ≤ K ≤ P, 1 ≤ source, destination ≤ N. Output For each test case, output a single line of output in the form " Case K: A 1 A 2 ... A q " where K is the number of the test case and [A 1 A 2 ... A q ] are the answers for the Q queries. Each answer is the shortest path cost between the 2 given cities using the first only K cities of given list as intermediate cities. In case there is no path between 2 cities, the answer is -1. Example Input: 1 4 2 -1 3 1 7 10 2 2 1 3 0 3 4 1 3 4 2 3 4 Output: Case 1: 10 8 6
32,572
The Egyptian Parliament (EGYPAR) This year, Egypt has been going through an extremely challenging stage. The parliamentary elections are about to take place according to a newly introduced election laws. The seats of the parliament are going to be divided in a party-list proportional representation. This type of elections allows voters to vote for a party (not for individual candidates). Each party wins a number of seats which depends on the number of votes they received. You are the president of the ACM party in your electoral district (Association of Corrupt Murderers) and you want your party to win as much seats as possible in the coming elections. You know exactly how many people will vote for every party (including yours), thanks to your amazing prediction abilities. There are two proposed voting systems (explained later) and it is not yet decided which of them is going to be used. You can use your connections trying to influence the decision of which voting system is put to use. Assuming your prediction is completely correct, the problem is to find the voting system that will let your party win more seats. Voting System 1: D'Hondt method This system is used in many countries, including Turkey, Japan and Spain. Let's say there are P parties and S seats. This method creates a grid of numbers, with P rows and S columns, where the entry in the i-th row and j-th column is the number of votes won by the i-th party divided by the number j. The first seat is given to the party that has the entry with the highest value. The second seat is given to the party that has the entry with the second highest value, and so on. If two or more entries have the same value, then the seat is given to the party that occurs first in the input file (for the simplicity of this problem).   For example : if 5 seats are to be allocated, divide each party's total votes by 1, then by 2, 3, 4 and 5. An example is given in the table below. The 5 highest five entries are highlighted in bold, ranging from 70.0 down to 30.0. The tie between party B and party D is resolved by giving the seat to B as it occurs first in the input. For each cell in bold, the corresponding party gets a seat. Party Number of received votes (V) V/1 V/2 V/3 V/4 V/5 Seats won A 70 70 35 23.3 17.5 14 2 B 60 60 30 20 15 12 2 C 50 50 25 16.7 12.5 10 1 D 30 30 15 10 7.5 6 0   Voting System 2: Sainte-Laguë method This system is used in fewer countries, including Norway, Sweden and Germany. This method favors smaller parties more than D'Hondt method. After the votes to each party has been counted, the parliament seats are given in an iterative way, one by one to the party that has the highest quotient. The quotient of a party is calculated by this formula: quot = V / (2s+1) Where: V: is the total number of votes that party received, and s: is the number of seats that party has been allocated so far, initially 0 for all parties.   For simplicity, if two or more parties are tied because they have the same quotients, the party that occurs first in the input file is given the  next seat allocated. The quotients are recalculated after each seat has been given and this process is repeated until all seats have been allocated. Example: using the same example from before, in the table below: Party Number of received votes (V) quot in round 1 quot in round 2 quot in round 3 quot in round 4 quot in round 5 Seats won A 70 70 23.3 23.3 23.3 23.3 2 B 60 60 60 20 20 20 1 C 50 50 50 50 16.7 16.7 1 D 30 30 30 30 30 10 1 The cells in bold represent the highest quotient for this seat and their party wins a seat correspondingly. Input Specification: First line of the input will contain T, the number of test cases. T test cases follow. The first line of each test case contains two integers N and S, separated by a single space. N is the number of parties and S is the number of seats to be allocated, 2  ≤ N, S ≤ 10,000. Each of the next N lines contains the name of the party P[i], a unique string of at most 20 lowercase and upper case English letters, followed by a single space, then an integer V[i], the exact number of predicted votes to be earned by this party. 0  ≤ V[i] ≤ 10^9 (1,000,000,000). The number of earned votes may be delimited by comas (e.g. could be 127 or 12,7). “ACM” will exist as a party name exactly once in every input case. Output Specification: For each test case, output a single line of output in the form “Case K: Method” where K is the number of the test case and Method is “S”, “D”, or “No difference”. Method = “D” if D'Hondt method wins the ACM party more seats. Method = “S” if Sainte-Laguë method wins the ACM party more seats. If both methods result in the same seat count for your party, then method = “No difference”. Sample input: 1 6 10 Yellow 47000 White 16000 Red 15900 ACM 12000 Blue 6000 Pink 3100 Sample Output: Case 1: No difference
32,573
Adventurous Chess Masters (ACHESS) The world of the Adventurous Chess Masters is quite different than our world, instead of having streets and buildings everything is composed of a big chess board and chess pieces. A square of a chess board is said to be covered if at least one chess piece is placed on it. The mysteries of the world can be revealed by covering special magical squares over the chess board, and you can't wait to discover them. In every turn you can update the board by moving one of the pieces on the board according to the following rules: The king moves only one square in any direction. The queen moves any number of squares in any direction along a row, column, or diagonal. The rook moves any number of squares along rows or columns (forward, backward, left or right). The bishop moves any number of squares diagonally. The knight moves to a square in an "L"-shape (two spaces forward, backward, left, or right and one space perpendicular to it). The pawn can only move one space forward or backward (unlike a chess game). Note that, unlike normal chess, more than one piece can occupy the same square and pieces can move through occupied squares. To reveal the secrets of the world you have to make the maximum number of magical squares covered, in the minimum number of turns. Input The first line of input contains an integer T that represents the number of test cases, then follow T test cases. The first line of each test case contains P and L, the number of chess pieces on the board and the number of magical squares in order.  Following the first line P lines each contains two integers x and y coordinates of the location of the piece where (1 ≤ x, y ≤ 8) and the type of the chess pieces (king, queen, rook, bishop, knight, or pawn - all in lowercase letters) and the last L lines of the test case each contains a unique pair of integers x and y as the coordinates of the magical squares where (1 ≤ x, y ≤ 8). Note that: (0 ≤ P ≤ 64), and these P pieces won't be in any of the L given locations. Output For each test case, print on one line " Case K: Secret reveals after moving H pieces with minimum number of moves M. " Where K is test case number, H is the number of pieces to be moved and M is the total number of moves used. Check example below to see the format. Example Input: 2 1 1 1 1 pawn 8 1 3 5 2 8 king 2 8 queen 7 5 bishop 1 1 2 2 3 6 6 3 4 4 Output: Case 1: Secret reveals after moving 1 pieces with minimum number of moves 7. Case 2: Secret reveals after moving 3 pieces with minimum number of moves 5.
32,574
The SKey (SKEY) It is the 10-th ACM Egyptian National Programming Contest and Mostafa S., the chief judge, started to prepare for the problem set. In previous years, a chief judge used to ask problems’ setters to use his public key to encrypt the data so that they keep everything related to the problems secured. Unfortunately, the RSA algorithm was broken 2 weeks ago and Mostafa decided to invent a temporary algorithm till someone finds a new robust approach for encrypting/decrypting  plaintext. After finding the algorithm, Mostafa met the judges and described the new encryption algorithm for them and gave them an equation to generate a key which the algorithm depends on. The key is generated through the following equation: SKEY = (M * SUM [1 / A^K (from k = 0 to k = N)] ) % P A, N and P are integers and P is a prime number that is co-prime with A (e.g. gcd(A, P) = 1). Furthermore M is a very large number (millions of digits) generated to be divisible by . For example given: A = 3, N = 2, P =  7  and M = 18, then the skey value is:  (18 * (1/1 + 1/3 + 1/9)  ) % 7 = 26 % 7 = 5.   Unfortunately, sending extremely large numbers for M in the emails between judges is impractical. Luckily, a property of the modulus operator is: (A*B)%X = (A%X * B%X) %X. Hence, we still can find our way to evaluate the skey by replacing M with M%P.   Given A, N, P, M%P, kindly help the chief judge with writing a code to compute the SKey. Input Specification: The first line of input contains an integer T that represents the number of test cases, then follow T lines each contains only four integer numbers A, N, P where 1 ≤ A ≤ 2147483647, 0 ≤ N ≤ 2147483647, 2 ≤ P ≤ 2147483647 and 0 ≤ M%P < P. Output Specification: For each test case, output a single line of output in the form “Case K: SKey” where K is the number of the test case and Skey is as defined in the problem statement. Check sample below for the format. Sample input: 1 3 2 7 4 Sample Output: Case 1: 5
32,575
Problem Set Score (PROSCORE) Fegla, one of the ACM ICPC coaches, is very happy as one of his teams won the ACPC regional contest, and now he is preparing his team for the ACM ICPC World Final. He decided to establish a training camp for his team in the north coast, practicing on subset of problem sets from previous World Final contests to sharpen the team skills, but he needs to choose this subset wisely as World Final is soon. After a long discussion with his team, they agreed on a certain criteria to choose the problem sets that will help in the training. Considering a problem set with N teams and P problems, a good problem set must satisfy the following conditions to be chosen: Any problem is solved by at least one team. Minimum number of solved problems per team is one. Maximum number of solved problems per team is less than p. Although they are all programmers, these lazy guys would to ask for your help in writing a program to calculate that for them. We really doubt that they will do something in the World Finals with such behavior,  so kindly help them, even if you are not from their school to state these 3 conditions for a given problem set. But, push them for some work, represent the true condition as 1 and the false condition as 0, and then convert the result to a decimal number to be the problem set score. Let the first condition to be the most left bit, the third condition to be the right most bit and the second condition to be middle bit. E.g. if a problem set matched only the first condition, it's represented as "100" and converted to 4. Input Specification: First line contains an integer T that represents the number of test cases, then follow T test cases, each in the following format: Line 1 contains two integers N and P, space separated, where 0 < N, P ≤  10. Then N lines each contains P integers are followed, where i-th line and j-th column represent (team=i, problem=j) state: 1 if problem is solved and 0 otherwise. Output Specification: For each test case, print on one line, “Case K: score” where K is the Test Case number and score is the problem set score. Sample input: 1 2 3 1 1 1 0 0 0 Sample Output: Case 1: 4
32,576
Men From Mars (MENMARS) Beings (men) living on Mars discovered that there are beautiful beings (women) living on Venus.  Men decided to change their life and want to travel using their spaceships to Venus to start a new life style. Unfortunately, women love connections and relationships and they won’t let a group of spaceships pass to their planet unless the number of spaceships in one of the “fully coupled” subgroups exceeds a certain minimum threshold. A fully coupled/connected group of spaceships is a group with each pair of spaceships can communicate together. The spaceships and their airport on mars are very complicated. First, a spaceship communicates with another spaceship only if a command from the airport headquarter is issued. Second, the airport is a small one that can launch at a time a group of maximum K spaceships, connected in a random way. There are 2 types of commands that can be issued from headquarter to manage the spaceships connections: 1) Flip command for a group that establishes a new communication between every pair of disconnected spaceships and disconnect every previously connected pair of spaceships in the group, 2) Merge command for some of the groups to let them be one group , but no communications/connections modifications happen. Unfortunately, under these constraints we can’t launch all spaceships in a fully coupled state that satisfies women. So, the Men developed an automatic software that will issue commands to launch the spaceships in groups, then will issue commands (Flip, Merge) in a way that hopefully produces at least one of the fully connected subgroups with maximum number of spaceships that satisfies women so that they pass to Venus. Given the groups of spaceships and the issued commands for them, you have to calculate the maximum number of spaceships that are fully coupled in the final group . Input Specification: The first line of input contains an integer T that represents the number of test cases, then follow T test cases. Each test case start with a line with N (the number of spaceships - 1 ≤ N ≤ 1000), M (the number of launch groups - 1 ≤ M ≤ 1000). Then M lines follow, one for each group: starting with K (number of spaceships in the group 1 ≤ K ≤ 10), E (number of connections in the group), and then E pair of numbers representing bidirectional connection between 2 spaceships: space_ship_id1, space_ship_id2 where 0 ≤ space_ship_id1, space_ship_id2 < K. The m-th group has id (m-1). Then Set of commands are given, each one on a line. Flip command on format “ F group_id” to flip the group with given group id. Merge Command on format “ M T group_id_1, group_id_2… group_id_T” that merges T groups and let their new id to be the maximum id of the merged groups.   Output Specification: For each test case, output a single line of output in the form “Case K: T” where K is the number of the test case and T is the maximum number of spaceships that are fully coupled in the final group. Check sample below for the format. Sample input: 1 7 4 3 3 0 1 0 2 1 2 2 1 0 1 1 0 1 0 F 1 M 2 1 2 F 0 M 2 0 2 F 2 M 2 3 2 * Sample Output: Case 1: 6 Sample Explanation In this example we have 7 spaceships in 4 groups. First group (id = 0) is forming a triangle shape, second is segment shape, third is isolated spaceship and forth (id = 3) is also isolated. The first command flips the second group to 2 isolated spaceships. The second command merge 2 groups, id =2 to have 3 isolated spaceships with new. The third command flips first group to 3 isolated spaceships. The fourth one merges them under one group of 6 isolated group with id = 2. The fifth command flips this group to a fully coupled group of 6 spaceships. Finally a merge for that group with the fourth group and we have a new group with id = 3 of 6 spaceships fully connected and 1 isolated node.
32,577
No Stories Any More! (FSEQ) Have you ever wished to be given a direct problem statement in the contest? Do you hate the boring stories that problem setters write...starting from “john was going on a trip”…passing with “blablabla”…and ending with “kindly help John J”. We all know that there is no John so why wasting contestants time. As we were contestants and know that feeling very well, we decided to break that boring way and save your time… Given the following sequence details:  F(0) = 0, F(1) = 1       and              SUM F(i) [i from 0 to n] = F(n+2) - 1 For a given integer M, we will generate another infinite sequence defined as:  T(i) = F(i) % M . We noticed that this is a repeating sequence: it repeats itself after some C iterations, where C is the cycle length for sequence T. Let’s define H(j), as the finite, most left , strictly increasing sub -sequence starting at position j in the sequence T, preserving the elements order of T. In other words: 1)      H(0), the first element in H, is T(j) 2)      H(1)   = T(k1), where T(k1) is the first element > T(j) where j < k1 3)      H(2)   = T(k2), where T(k2) is the first element > T(k1) where k1 < k2, and so on For example, if M = 4, then T = [ 0 1 1 2 3 1    0 1 1 2 3 1   0 1 1 2 …]. Furthermore: H(0) = [0 1 2 3], H(3) = [2 3], and H(5) = [1 2 3]. Length(  H(j) ) is the number of elements in that sequence, e.g. Length(H(5)) = 3. The Cycle length(C) for sequence T is 6.   For a given M, you will calculate its C, and evaluate the following summation :                                           SUM Length( H(k) ) [k = 0 to C-1] Input Specification: The first line of input contains an integer T that represents the number of test cases, then follow T lines each contains an integer 1 ≤ M ≤ 10 5 . NOTE: for any given test case, sequence T repeats after maximum C iterations where C ≤ 10 5 . Output Specification: For each test case, output a single line of output in the form “Case K: summation” where K is the number of the test case and summation is as defined in the problem statement.   Sample input: 1 4 Sample Output: Case 1: 16
32,578
Distance (DISTX) In this task let's consider distance between two positive integers defined as below. Single operation is: multiplying some number by prime number or dividing some number by prime number (we can divide only when remainder is equal to 0.) Distance d between two numbers a, b is minimum number operations to convert one number to another. For example d(69, 42) = 3. This distance is very similar to well-known term "distance" in real human life: d(a, a) = 0, distance number to itself is 0. d(a, b) = d(b, a) distance from a→b is equal to b→a. d(a, b) + d(b, c) ≥ d(a, c) triangle equation is true too. With given n number you have to determine for each i-th of those numbers closest number a j from set that i ≠ j and if there is many numbers with equal, smallest distance, you have to pick number with smallest index Input In first line - number n ≤ 10 5 . In next n lines - i-th number. Every number is not greater than 10 6 . Output You have to output n lines. I-th line should contain index of closest number (if there are many answers, please output smallest index.) Example Input: 6 1 2 3 4 5 6 Output: 2 1 1 2 1 2
32,579
Power Tower City (POWTOW) You are living in a city build entirely of power towers such as 3^3^3 and 10^10^10^10. To enter a building you must type the last 9 digits of the number represented by the tower, written in decimal form, on a keypad next to the main entrance. You are not sharp enough at mental maths, but you can write a handy program to bring along in your pocket. A power tower is defined as repeated exponentiation. We write this using Knuth's up-arrow notation as: e↑↑a = e^e^...^e (a terms). Remember that ^ (exponentiation) is right associative. For example: 2↑↑4 = 2^2^2^2 = 2^(2^(2^2)) = 2^2^4 = 2^16 = 65536, and 3↑↑1 = 3. The value of a tower of height 0 is 1. Input The first line contains integer C in [0..1000], the number of test cases. Then follows C lines, each with integers e,a in [0..2147483647]. (non-negative 32-bit integers). Output For each testcase output e↑↑a, or if the output has more than 9 digits, output "..." and then the last 9 digits. Example Input: 3 0 0 2 5 993306745 75707320 Output: 1 ...719156736 ...884765625
32,580
Kompići (KOMPICI) After successfully solving his math homework from the previous task, Mirko has become bored, so he has made a list of N large integers. On the list there are some pairs of numbers that he likes, and some pairs he doesn’t like. Mirko has named the pairs that he likes pals. Two numbers are pals if they have at least one digit in common (not necessarily in the same position).  Help Mirko count how many pairs of numbers in his list are pals Input The first line of input contains the positive integer N (1 ≤ N ≤ 500 000). Each of the next N lines contains a positive integer from the range [1, 10 18 ], a number from Mirko’s list. No two numbers in the list will be equal. Output The first and only line of output must contain the number of pairs that are pals. Example Input: 3 4 20 44 Output: 1
32,581
Trick or Treat (TRICKTRT) Johnny and his friends have decided to spend Halloween night doing the usual candy collection from the households of their village. As the village is too big for a single group to collect the candy from all houses sequentially, Johnny and his friends have decided to split up so that each of them goes to a different house, collects the candy (or wreaks havoc if the residents don’t give out candy), and returns to a meeting point arranged in advance. There are n houses in the village, the positions of which can be identified with their Cartesian coordinates on the Euclidean plane. Johnny’s gang is also made up of n people (including Johnny himself). They have decided to distribute the candy after everybody comes back with their booty. The houses might be far away, but Johnny’s interest is in eating the candy as soon as possible. Keeping in mind that, because of their response to the hospitality of some villagers, some children might be wanted by the local authorities, they have agreed to fix the meeting point by the river running through the village, which is the line y = 0. Note that there may be houses on both sides of the river, and some of the houses may be houseboats ( y = 0). The walking speed of every child is 1 meter per second, and they can move along any direction on the plane. At exactly midnight, each child will knock on the door of the house he has chosen, collect the candy instantaneously, and walk back along the shortest route to the meeting point. Tell Johnny at what time he will be able to start eating the candy. Input Each test case starts with a line indicating the number n of houses (1 ≤ n ≤ 50 000). The next n lines describe the positions of the houses; each of these lines contains two floating point numbers x and y (−200 000 ≤ x , y ≤ 200 000), the coordinates of a house in meters. All houses are at different positions. A blank line follows each case. A line with n = 0 indicates the end of the input; do not write any output for this case. Output For each test case, print two numbers in a line separated by a space: the coordinate x of the meeting point on the line y = 0 that minimizes the time the last child arrives, and this time itself (measured in seconds after midnight). Your answer should be accurate to within an absolute or relative error of 10 −5 . Example Input: 2 1.5 1.5 3 0 1 0 0 4 1 4 4 4 -3 3 2 4 5 4 7 -4 0 7 -6 -2 4 8 -5 0 Output: 1.500000000 1.500000000 0.000000000 0.000000000 1.000000000 5.000000000 3.136363636 7.136363636 Problem setter: Javier Gómez Serrano
32,582
Working at the Restaurant (RESTAURN) Last night, Tom went on a date with a really nice girl. However, he forgot to take his credit card with him and he had no cash in his wallet, so he ended up working at the restaurant to pay for the bill. His task is to take plates from the waiter when he comes from the tables, and pass them along when the dishwasher requests them. It is very important for the plates to be washed in the same order as they are brought from the tables, as otherwise it could take too long before a plate is washed, and leftover food might get stuck. Trying to hold all the plates in his hands is probably not a great idea, so Tom puts them on a table as soon as the waiter hands them over to him, and picks them up from the table again when the time comes to pass them along to the dishwasher. There is space for only two piles of plates on the table, which will be referred to as pile 1 and pile 2. There is only one table Tom can use. Tom won last year’s SWERC, so he is certainly capable of optimizing for efficiency. You have to output a transcript of one possible way in which Tom might decide to organize the plates on the table during the process, given the sequence of plates and requests he receives. Input The input has several test cases. Each case begins with a line containing a number N (1 ≤ N ≤ 1 000), followed by N lines, which contain either DROP m or TAKE m , where m > 0 is the number of plates to take or drop. DROP m represents that the next event is the waiter bringing m plates to Tom, one by one, so he has to drop them on the table; TAKE m represents that the next event is Tom taking m plates from the table, one by one, and passing them along in the right order. You can assume that he never receives a TAKE m instruction when there are fewer than m plates on the table, and that the sum M of all values of m corresponding to DROP operations does not exceed 100 000. Note that there might be plates left on Tom’s table when the last request is issued, as Tom might be relieved of his duty to stay until the restaurant closes. The input ends with a line with N = 0, which must not be processed. Output For every test case, the output will be a series of lines describing the operations to be performed with the plates. The content of each line will be one of the following: DROP 1 m ( DROP 2 m ), m > 0, if Tom needs to take a plate from the waiter, drop it on top of pile 1 (pile 2), and repeat this operation m times in total. TAKE 1 m ( TAKE 2 m ), m > 0, if Tom needs to take a plate from the top of pile 1 (pile 2), pass it along to the dishwasher, and repeat m times in total. MOVE 1->2 m ( MOVE 2->1 m ), m > 0, if Tom needs to take a plate from the top of pile 1 (pile 2), drop it on top of pile 2 (pile 1), and repeat m times in total. You must output at most 6 N lines, and the total number of movements of plates in your transcript (that is, the sum of the m ’s printed in your output, for all three kinds of operations), must be at most 6 M , as otherwise Tom won’t be able to cope with all the work. Note that Tom must obey the commands in the same order as they are issued. This means that, if he receives a TAKE m command, he must perform a certain number of MOVE and TAKE operations such that the sum of the numbers of plates taken adds up exactly to m before performing the operations corresponding to the next command; and if he receives a DROP m command, he must perform a number of DROP or MOVE operations for which the sum of the numbers of plates dropped adds up exactly to m before performing the operations corresponding to the next command. Of course, it is also forbidden to take plates from the waiter or pass them along to the dishwasher in the absence of the corresponding order. There must be an empty line between the outputs of different cases. Any solution satisfying these conditions will be accepted. Sample Input: 3 DROP 100 TAKE 50 TAKE 20 3 DROP 3 DROP 5 TAKE 8 0 Output: DROP 2 100 MOVE 2->1 100 TAKE 1 50 TAKE 1 20 DROP 2 3 DROP 2 5 MOVE 2->1 8 TAKE 1 8 Problemsetter: Abel Molina Prieto
32,583
Lights (LIGHTS2) John has n light bulbs and a switchboard with n switches; each bulb can be either on or off, and pressing the i −th switch changes the state of bulb i from on to off, and viceversa. He is using them to play a game he has made up. In each move, John selects a (possibly empty) set of switches and presses them, thus inverting the states of the corresponding bulbs. Initially all lights are off, and after exactly m moves John would like to have the first v bulbs on and the rest off; otherwise he loses the game. There is only one restriction: he is not allowed to press the same set of switches in two different moves. This is quite an easy game, as there are lots of ways of winning. This has encouraged him to keep playing different winning games, and now he is intent on trying them all. Help him count how many ways of winning there are. Two games are considered the same if, after a reordering of the moves in one of them, at every step the same set of switches is pressed in both of them. For example, if n = 4, m = 3, and v = 2, one possible winning game is obtained by pressing switches 1, 2 and 4 in the first move, 1 and 3 in the second one, and 1, 3 and 4 in the last one. This is considered equivalent to, say, first pressing 1 and 3; then 1, 2, 4; and then 1, 3, 4. Input The input has at most 500 lines, one for each test case. Each line contains three integers n (1 ≤ n ≤ 1 000), m (1 ≤ m ≤ 1 000), and v (0 ≤ v ≤ n ). The last line of input will hold the values 0 0 0 and must not be processed. Output Print one line for each test case containing the number of ways John can play the game, modulo the prime 10 567 201. Example Input: 3 3 1 6 4 0 6 4 3 0 0 0 Output: 7 10416 9920 Problem setter: David García Soriano
32,584
Darts (DARTS) After a long week of work at the ICPC Headquarters, Bill and his friends usually go to a small pub on Friday evenings to have a couple of beers and play darts. All of them are well aware of the fact that their ability at darts decreases at the same rate as the amount of beer left in their mugs. They always play 501, one of the easiest games. Players start with a score of N points (typically, N =501, hence the name) and take turns throwing darts. The score of each player decreases by the value of the section hit by the dart, unless the score becomes negative, in which case it remains unchanged. The first player to reach a score of 0 wins. The figure below shows the dartboard with which the game is played. Dartboard As the clock ticks closer to midnight and they start running out of beer, everyone wonders the same: is it worth trying to aim the dart at a specific section? Or is it better just to throw the dart at a random section on the dartboard? You are asked to deal with the question by finding out what would happen if two players (A and B) applying these two different strategies were to play against each other: Player A throws the darts at random, and consequently they land with equal probability in each of the sections of the dartboard. If Player B aims at a certain section, the dart has the same probability of landing in the correct one as in each of the two adjacent ones (the neighbouring regions to the left and right). Moreover, he is completely aware of his ability and sober enough to aim at the section that maximizes his probability of winning. Given the initial score of both players, can you determine the probability that the first player wins? Of course, being the first to throw a dart might be advantageous, so the answer depends on who plays first. Input The input consists of a series of lines, each containing an integer N (1 ≤ N ≤ 501), the initial score of both players. A case with N = 0 marks the end of the input and must not be processed. Output For each number in the input, your program should output a line containing two real numbers: the probability that A wins if A throws the first dart, and the probability that B wins if B throws the first dart. Your answers should be accurate to within an absolute or relative error of 10 −8 . Sample Input 5 100 0 Sample Output 0.136363636364 0.909090909091 0.072504908290 0.950215081962 Problemsetter: Luis Hernández Corbato
32,585
Genetics (GENETIC2) A colony of alien bacteria has recently been discovered close to a crater in New Mexico. Dr. Poucher is in charge of the scientific team at the ICPC BioLab committed to the study of the alien DNA structure. We briefly sketch their discoveries here. Alien DNA molecules have the structure of a circular sequence. Each sequence is composed of nucleotides. There are 26 different types of nucleotides, and each of them can occur in two faces. It is very important to remark that in any given alien DNA molecule, every nucleotide either does not appear at all or appears exactly twice (hence, the length of a DNA molecule is an even integer between 2 and 52). In case a nucleotide occurs twice, each occurrence can be of either type independently. Alien bacteria have two types of extremities, which in the technical biological jargon are referred to as arms and legs. A major discovery of Dr. Poucher’s team is a method to determine the exact number of arms and legs of a bacterium by examining its DNA structure. Here we represent each nucleotide as a letter of the alphabet. We refer to the different nucleotides as a , A , … z , Z , where the lowercase and uppercase forms of a letter represent the two possible faces a nucleotide may appear with; we shall also use a / A , b / B , … z / Z to refer to a nucleotide in either face. To determine the number of extremities, Dr. Poucher starts by initializing two counters of arms and legs to zero, and then proceeds to perform a number of surgeries, transforming a DNA sequence into another one. After each transformation, you may need to increase some of the counters, depending on the type of surgery applied. When the empty sequence of nucleotides (which will be denoted by ∅) has been reached, the number of extremities of the original molecule has been found. The possible surgeries are: Eliminate consecutive instances of a given nucleotide appearing with opposite faces. The number of arms and legs is preserved. For example: aBbCaC → aCaC by eliminating Bb . Another example: DeHhEd → eHhE by eliminating dD . Remember that DNA structure is circular, so in our representation as a string the last and first letters are connected. Eliminate consecutive nucleotides appearing with the same face. Add one to the number of arms. For example: BBcgCg → cgCg by eliminating BB . Another example: xabyyaBX → xabaBX by eliminating yy . Eliminate a sequence of four nucleotides formed by two different nucleotides that appear alternately where different occurrences of the same nucleotide have opposite faces. Add one to the number of legs. For example: dcDCefFe → efFe , by eliminating dcDC . Another example: cmNMnC → cC by eliminating mNMn . Cut and paste, the most sophisticated procedure. First, a nucleotide is selected, for instance a / A , and the DNA sequence is chopped into two linear chains such that the nucleotide appears once in each of them. Second, if both occurrences of a / A are of the same face, one of the chains is “inverted” by reversing the sequence and changing the face of every nucleotide in the chain. Given a chain S , S denotes its “inverted” chain. Then, the chains are combined by concatenating the subsequence occurring before a with the subsequence occurring after A , and the subsequence occurring after a with the sub-sequence occurring before  A . Finally, two new a / A nucleotides are added to close the chain into a circular shape. The face of the new nucleotides are the same if the original pair of nucleotides selected had the same face, and is different otherwise. Formally, suppose you select the nucleotide a / A , and further assume for the moment that it appears both times with the face a ( A ). The cut and paste surgery turns sequences of the form S 1 a S 2 S 3 a S 4 (respectively S 1 A S 2 S 3 A S 4 ) into S 2 a S 1 S_3 a S_4 (respectively S 2 A S 1 S_3 A S_4 ). On the other hand, if nucleotide a / A appears with its two different faces, the surgery turns sequences of the form S 1 a S 2 S 3 A S 4 into S 2 a S 1 S 4 A S 3 . S 1 , S 2 , S 3 and S 4 are arbitrary sub-chains (possibly empty). In both cases the original circular chain was chopped into S 1 ( a / A ) S 2 and S 3 ( a / A ) S 4 . For example (see the figure below): starting with the sequence BacDcAbD , we can get chains BacDc and AbD . Then, merging at nucleotide a / A we get the sequence cDca’BbDA’ where a’ and A’ represent the new a / A nucleotides. Here, S 1 = B , S 2 = cDc , S 3 = ∅ and S 4 = bD . Another example: take the same DNA sequence BacDcAbD , and cut to get the chains DBac and DcAb ; paste nucleotide c / C (in this case you need to reverse one chain, for example BaCd ) to get the sequence cDBadcBa . Here, S 1 = DBa , S 2 = ∅, S 3 = D and S 4 = Ab . Figure 1: First example of use of cut&paste This surgery does not modify the number of arms or legs, but can be used cleverly in combination with the previous surgeries to reduce the size of the DNA molecule and finish the calculation. However, alien bacteria do not present both arms and legs at the same time. This is due to the fact that, in their early development, a leg, in the presence of one or more arms, becomes two arms. Because of the above, the end result is either a number of arms or a number of legs, but not both at the same time. In order to avoid expensive surgical procedures, Dr. Poucher has hired you to write a program that computes the number of arms and legs a bacterium will develop, given its DNA sequence. It is guaranteed that the result is determined uniquely by the original string, regardless of the particular sequence of surgeries applied. Input Each test case consists of a string of even length between 2 and 52, inclusive, representing the DNA structure of an alien bacterium. All characters are letters. There will be one case per line in the input. The last line contains the word “END” and must not be processed. Output The output for each test case should have exactly one line, containing the number of arms or legs the bacterium will have, followed by the word “arms” or “legs” respectively (if the number is 1, the words should be in singular). In case there will be neither arms nor legs, the program should print the word “none”. Sample Input rkrk abcdeABCDE shcoOCfFHS END Sample Output 1 arm 2 legs none Problemsetter: Luis Hernández Corbato
32,586
Haunted Graveyard (GRAVEYRD) Tonight is Halloween and Scared John and his friends have decided to do something fun to celebrate the occasion: crossing the graveyard. Although Scared John does not find this fun at all, he finally agreed to join them in their adventure. Once at the entrance, the friends have begun to cross the graveyard one by one, and now it is the time for Scared John. He still remembers the tales his grandmother told him when he was a child. She told him that, on Halloween night, “haunted holes” appear in the graveyard. These are not usual holes, but they transport people who fall inside to some point in the graveyard, possibly far away. But the scariest feature of these holes is that they allow one to travel in time as well as in space; i.e., if you fall inside a “haunted hole”, you appear somewhere in the graveyard a certain time before (or after) you entered the hole, in a parallel universe otherwise identical to ours. The graveyard is organized as a grid of W × H cells, with the entrance in the cell at position (0,0) and the exit at ( W −1, H −1). Despite the darkness, Scared John can always recognize the exit, and he will leave the moment he reaches it, determined never to set foot anywhere in the graveyard again. On his way to the exit, he can walk from one cell to an adjacent one, and he can only head to the North, East, South or West. In each cell there can be either one gravestone, one “haunted hole”, or grass: If the cell contains a gravestone, you cannot walk over it, because gravestones are too high to climb. If the cell contains a “haunted hole” and you reach it, you will appear somewhere in the graveyard at a possibly different moment in time. The time difference depends on the particular “haunted hole” you fell into, and can be positive, negative or zero. Otherwise, the cell has only grass, and you can walk freely over it. He is terrified, so he wants to cross the graveyard as quickly as possible. And that is the reason why he has phoned you, a renowned programmer. He wants you to write a program that, given the description of the graveyard, computes the minimum time needed to go from the entrance to the exit. Scared John accepts using “haunted holes” if they permit him to cross the graveyard quicker, but he is frightened to death of the possibility of getting lost and being able to travel back in time indefinitely using the holes, so your program must report these situations. Sample graveyard The figure illustrates a possible graveyard (the second test case from the sample input). In this case there are two gravestones in cells (2,1) and (3,1), and a “haunted hole” from cell (3,0) to cell (2,2) with a difference in time of 0 seconds. The minimum time to cross the graveyard is 4 seconds, corresponding to the path: (0,0) → 1  sec East (1,0) → 1  sec East  (2,0) → 1  sec East  (3,0) → 0  sec hole (2,2) → 1  sec East  (3,2) If you do not use the “haunted hole”, you need at least 5 seconds. Input The input consists of several test cases. Each test case begins with a line containing two integers W and H (1 ≤ W , H ≤ 30). These integers represent the width W and height H of the graveyard. The next line contains an integer G ( G ≥ 0), the number of gravestones in the graveyard, and is followed by G lines containing the positions of the gravestones. Each position is given by two integers X and Y (0 ≤ X < W and 0 ≤ Y < H ). The next line contains an integer E ( E ≥ 0), the number of “haunted holes”, and is followed by E lines. Each of these contains five integers X 1, Y 1, X 2, Y 2, T . ( X 1, Y 1) is the position of the “haunted hole” (0 ≤ X 1 < W and 0 ≤ Y 1 < H ). ( X 2, Y 2) is the destination of the “haunted hole” (0 ≤ X 2 < W and 0 ≤ Y 2 < H ). Note that the origin and the destination of a “haunted hole” can be identical. T (−10 000 ≤ T ≤ 10 000) is the difference in seconds between the moment somebody enters the “haunted hole” and the moment he appears in the destination position; a positive number indicates that he reaches the destination after entering the hole. You can safely assume that there are no two “haunted holes” with the same origin, and the destination cell of a “haunted hole” does not contain a gravestone. Furthermore, there are neither gravestones nor “haunted holes” at positions (0,0) and (W-1,H-1). The input will finish with a line containing 0 0 , which should not be processed. Output For each test case, if it is possible for Scared John to travel back in time indefinitely, output Never . Otherwise, print the minimum time in seconds that it takes him to cross the graveyard from the entrance to the exit if it is reachable, and Impossible if not. Sample Input 3 3 2 2 1 1 2 0 4 3 2 2 1 3 1 1 3 0 2 2 0 4 2 0 1 2 0 1 0 -3 0 0 Sample Output Impossible 4 Never Problemsetter: Enrique Martín Martín
32,587
Slalom (SLALOM2) In spite of the scarcity of snowfall in Madrid, interest in winter sports is growing in the city, especially with regard to skiing. Many people spend several weekends or even full weeks improving their skills in the mountains. In this problem we deal with only one of the multiple alpine skiing disciplines: slalom. A course is constructed by laying out a series of gates, which are formed by two poles. The skier must pass between the two poles forming each gate. The winner is the skier who takes the least time to complete the course while not missing any of the gates. You have recently started to learn to ski, but you have already set yourself the goal of taking part in the Winter Olympic Games of 2018, for which Madrid will presumably present a candidature. As part of the theoretical training, you need to write a program that calculates, given a starting point and a series of gates, the minimum-length path starting from the point given and passing through each gate until you reach the last one, which is the finish line. You may assume that the gates are horizontal and are ordered from highest to lowest, so that you need to pass through them in order. You consider yourself an accomplished skier, so you can make any series of turns, no matter how difficult, and your only concern is minimizing the total length of the path. Input The first line of each case gives the number of gates n (1 ≤ n ≤ 1 000). The next line contains two floating point numbers, the Cartesian coordinates x and y of the starting position, in that order. Next come n lines with three floating point numbers each, y   x 1   x 2 , meaning that the next gate is a horizontal line from ( x 1 , y ) to ( x 2 , y ). You can safely assume that x 1 < x 2 . The values of y are strictly decreasing and are always smaller than that of the starting position. The last gate represents the finish line. All coordinates are between −500 000 and 500 000, inclusive. A value of 0 for n means the end of the input. A blank line follows each case. Output For each test case, output a line with the minimum distance needed to reach the finish line. Your answer should be accurate to within an absolute or relative error of 10 −7 . Example Input: 2 0 2 1 1 2 0 0.5 3 3 0 4 3 1 2 2 -1 0 1 1 2 0 Output: 2.41421356237 4.24264068712 Problem setter: Manuel Abellanas
32,588
Routing (ROUTING) You work as an engineer for the Inane Collaboration for Performance Computing , where you are in charge of designing an intercommunication network for their computers. The network is arranged as a rectangular array of 2 n −1 rows, each having 2 n − 1 switches. A switch is a device with two input wires, X and Y , and two output wires, X ′ and Y ′. If the switch is off, data from input X will be relayed to output X ′, and data from Y to Y ′. If it is on, X will be connected to Y ′ and Y to X ′. Additionally, there are 2 n computers in the topmost and bottommost rows, and messages need to be sent between pairs of them. Notice that data from two different sources cannot share a wire but, of course, both pieces of data can be routed through the same switch on different inputs. You have come to the conclusion that the network that best suits your purposes has the Beneš topology. A 1-Beneš network is just a switch. For n > 1, a n -Beneš network can be constructed recursively as follows: In the first (top) row there are 2 n − 1 switches such that switch j (0 ≤ j < 2 n −1 ) has data inputs from computers 2 j and 2 j + 1 (we label the computers in the topmost and bottommost rows with integers between 0 and 2 n − 1, inclusive, from left to right). Then a perfect shuffle permutation is applied to the output wires between the first and the second rows of switches, meaning that output number j in a row is connected to input number j ′ in the next row, where j ′ is obtained by rotating the n-bit pattern representing j in binary one bit to the right (again, inputs and outputs are numbered from left to right). If n > 2, the next rows of switches, up to (and including) the last-but-one, form two ( n −1)-Beneš subnetworks, one on the left side and the other on the right side. Finally, the inverse shuffle permutation is applied to the outputs and a last row of switches is added.     3-Benes network For example, the figure on the left shows the Beneš network for n =3 ( squares represent switches; computers in the top and bottom rows are not drawn, but assigned with integers from 0 to 7). The figure on the right shows a possible state of the switches; squares where two of the lines cross are switches that have been turned on. You may verify that this state allows us to simultaneously establish communication paths from computers 0, 1, 2, 3, 4, 5, 6, 7 at the bottom to 3, 7, 4, 0, 2, 6, 1, 5 at the top, respectively. You are given a set of pairs ( a , b ) of computers to connect simultaneously (where a is a computer in the bottom row and b a computer in the top row) by means of wire-disjoint paths, and you are to find how to select the state of all switches so that this can be accomplished. Input The first line of each test case is an integer n (1 ≤ n ≤ 13), meaning that you have 2 n pairs of computers to connect, as described above. A line with n = 0 marks the end of the input and should not be processed. Each line with n > 0 will be followed by another line containing 2 n integers. The i -th integer (0 ≤ i < 2 n ) will be the computer in the topmost row that the i -th computer in the bottommost row needs to communicate with. Output The output for each case should have 2 n −1 lines, each containing a binary string of length 2 n −1 indicating, for each switch, whether it must be turned on (1) or off (0). The input given will always have at least one solution. In case of several solutions, return the lexicographically smallest one. That is, the string in the top row must be lexicographically smallest; in case of a tie, the string in the second row must be lexicographically smallest, and so on. Outputs for different test cases should be separated by a blank line. Sample Input 2 3 2 1 0 3 3 7 4 0 2 6 1 5 0 Sample Output 00 11 11 0011 0000 0110 1111 1101 Problemsetter: David García Soriano
32,589
Happy Telephones (HAPPYTL) In the land of Eden, all phone conversations are happy ones. People complaining on the phone are immediately put in jail. To enforce this law, the police taps all phone conversations. The police wants to hire the appropriate number of operators to listen to all conversations in a given period of time. Unfortunately, each of their operators can listen to one conversation only before needing a really long break to rest from the effort. As a contractor of the police department, you have been asked to provide a program capable of determining the required number of operators. If the program does not work correctly, you will be put in jail as well, along with all the unhappy complainers. Do you really want to end up there? Input Each test case starts with two integers denoting the number of phone calls N (1 ≤ N < 10 000) and the number of intervals M (1 ≤ M < 100). This is followed by N lines describing the telephone calls, each one consisting of four integers Source , Destination , Start and Duration . Source and Destination identify the pair of telephone numbers establishing the connection (0 ≤ Source , Destination ≤ 10 000 000). Start and Duration are the start time and duration of the call in seconds (1 ≤ Duration ≤ 10 000 and Start ≥ 0). You can safely assume that the sum of Start and Duration fits into a 32-bit signed integer. Afterwards follow M lines containing the time intervals the police are interested in, each described by two integers Start and Duration , in the same format and with the same meaning and constraints as those in the telephone calls. The last test case is represented by N = M = 0 and must not be processed. Output For each of the M intervals of each test case, print the number of calls that are active during at least one second of the interval. Sample Input 3 2 3 4 2 5 1 2 0 10 6 5 5 8 0 6 8 2 1 2 8 9 0 10 9 1 10 1 0 0 Sample Output 3 2 1 0 Problem setter: Manuel Freire
32,590
Stammering Aliens (STAMMER) Dr. Ellie Arroway has established contact with an extraterrestrial civilization. However, all efforts to decode their messages have failed so far because, as luck would have it, they have stumbled upon a race of stuttering aliens! Her team has found out that, in every long enough message, the most important words appear repeated a certain number of times as a sequence of consecutive characters, even in the middle of other words. Furthermore, sometimes they use contractions in an obscure manner. For example, if they need to say bab twice, they might just send the message babab , which has been abbreviated because the second b of the first word can be reused as the first b of the second one. Thus, the message contains possibly overlapping repetitions of the same words over and over again. As a result, Ellie turns to you, S.R. Hadden, for help in identifying the gist of the message. Given an integer m , and a string s , representing the message, your task is to find the longest substring of s that appears at least m times. For example, in the message baaaababababbababbab , the length-5 word babab is contained 3 times, namely at positions 5, 7 and 12 (where indices start at zero). No substring appearing 3 or more times is longer (see the first example from the sample input). On the other hand, no substring appears 11 times or more (see example 2). In case there are several solutions, the substring with the rightmost occurrence is preferred (see example 3). Input The input contains several test cases. Each test case consists of a line with an integer m ( m ≥ 1), the minimum number of repetitions, followed by a line containing a string s of length between m and 40 000, inclusive. All characters in s are lowercase characters from “a” to “z”. The last test case is denoted by m = 0 and must not be processed. Output Print one line of output for each test case. If there is no solution, output none ; otherwise, print two integers in a line, separated by a space. The first integer denotes the maximum length of a substring appearing at least m times; the second integer gives the rightmost possible starting position of such a substring. Sample Input 3 baaaababababbababbab 11 baaaababababbababbab 3 cccccc 0 Sample Output 5 12 none 4 2 Problemsetter: David García Soriano
32,591
Lawn Mower (LAWNMWR) The International Collegiate Soccer Competition (ICSC) is famous for its well-kept rectangular stadiums. The grass playing fields in ICSC stadiums are always 100 meters long, and 75 meters wide. The grass is mowed every week with special lawn mowers, always using the same strategy: first, they make a series of passes along the length of the field, and then they do the same along the width of the field. All passes are straight lines, parallel to the sides of the field. The ICSC has hired a new lawn-mower, Guido. Guido is very chaotic, and instead of covering the field incrementally, he likes to choose random starting positions for each of his passes. But he is afraid of not doing a good job and being fired by the ICSC, so he has asked you to help him. Write a program to make sure that the grass in the field is perfectly cut: all parts of the field have to be mowed at least once when the mower goes from end to end, and again when the mower goes from side to side. Input Each test case contains 3 lines. The first line contains two integers, n x (0 < n x < 1 000) and n y (0 < n x < 1 000), and a real number w (0 < w ≤ 50), which represents the width of the cut of that particular lawn mower. The next line describes the end-to-end passes (along the length of the field), and contains n x real numbers x i (0 ≤ x i ≤ 75) describing the starting positions of the mower’s center in Guido’s end-to-end passes. The last line describes the side-to-side passes, with n y real numbers y i (0 ≤ y i ≤ 100). The end of the test cases is signalled with a line that contains the numbers 0 0 0.0 . You should generate no output for this line, as it is not a test case. Real numbers for w , x i and y i can have up to 7 digits after the decimal point, and any cut will also include its boundaries. For example, if a 2.0-meter wide cut is performed along the 10.0-meter mark, then a strip of grass from 9.0 to 11.0 (including both) will be considered “cut”. Output Print YES if Guido has done a good job, or NO if some part of the field has not been mowed at least once when the mower was travelling along the length of the field, and again when it was travelling along the width. Example Input: 8 11 10.0 0.0 10.0 20.0 30.0 40.0 50.0 60.0 70.0 0.0 10.0 20.0 30.0 40.0 50.0 60.0 70.0 80.0 90.0 100.0 8 10 10.0 0.0 10.0 20.0 30.0 40.0 50.0 60.0 70.0 0.0 10.0 30.0 40.0 50.0 60.0 70.0 80.0 90.0 100.0 4 5 20.0 70.0 10.0 30.0 50.0 30.0 10.0 90.0 50.0 70.0 4 5 20.0 60.0 10.0 30.0 50.0 30.0 10.0 90.0 50.0 70.0 0 0 0.0 Output: YES NO YES NO The ICSC is sponsored by the Association for Sports Machinery (ASM), which started out in the US, so they prefer to use the term ‘soccer’ instead of ‘football’. Problem setter: Manuel Freire
32,592
Periodic Points (PERIODIC) Computing the number of fixed points and, more generally, the number of periodic orbits within a dynamical system is a question attracting interest from different fields of research. However, dynamics may turn out to be very complicated to describe, even in seemingly simple models. In this task you will be asked to compute the number of periodic points of period n of a piecewise linear map f mapping the real interval [0, m ] into itself. That is to say, given a map f : [0, m ] → [0, m ] you have to calculate the number of solutions to the equation f n ( x ) = x for x ∈ [0, m ], where f n is the result of iterating function f a total of n times, i.e. f n  =  n   f ′ s ◢  ◣ f  ∘ .. ∘  f  ∘  f     , where ∘ stands for the composition of maps, ( g ∘ h ) ( x ) = g ( h ( x )). Fortunately, the maps you will have to work with satisfy some particular properties: m will be a positive integer and the image of every integer in [0, m ] under f is again an integer in [0, m ], that is, for every k ∈ {0, 1, … , m } we have that f ( k ) ∈ {0, 1, … , m }. For every k ∈ {0, 1, …, m − 1}, the map f is linear in the interval [ k , k + 1]. This means that for every x ∈ [ k , k + 1], its image satisfies f ( x ) = ( k + 1 − x ) f ( k ) + ( x − k ) f ( k + 1), which is equivalent to its graph on [ k , k + 1] being a straight line segment.      Figure 1: Graphs of the third map in the sample input, f 3 (left), and of its square, f 3 2 (right). Since there might be many periodic points you will have to output the result modulo an integer. Input The input consists of several test cases, separated by single blank lines. Each test case begins with a line containing the integer m (1 ≤ m ≤ 80). The following line describes the map f ; it contains the m + 1 integers f (0), f (1), …, f ( m ), each of them between 0 and m inclusive. The test case ends with a line containing two integers separated by a blank space, n (1 ≤ n ≤ 5 000) and the modulus used to compute the result, mod (2 ≤ mod ≤ 10 000). The input will finish with a line containing 0 . Output For each case, your program should output the number of solutions to the equation f n ( x ) = x in the interval [0, m ] modulo mod . If there are infinitely many solutions, print Infinity instead. Sample Input 2 2 0 2 2 10 3 0 1 3 2 1 137 3 2 3 0 3 20 10000 0 Sample Output 4 Infinity 9074 Problemsetter: Luis Hernández Corbato
32,593
Comparing Answers (CMPANS) In a place in Southwestern Europe, the name of which I do not wish to recall, not long ago there were n cities connected by unidirectional roads, with possibly more than one road connecting a city to another one, or even to itself. As a homework assignment for your geography class, you need to calculate the number of paths of length exactly two that were between each pair of cities. However, you’ve been too busy celebrating the Spanish victory in the World Cup, so now you are copying the answers from your friend. You would like to make sure his answers are correct before handing in your homework. Input The input consists of several test cases, separated by single blank lines. Each test case begins with a line containing the integer n (1 ≤ n ≤ 700). The following n lines contain n elements each, with element j of line i being the number of roads from city i to city j (a number between 0 and 10, inclusive). After that, there will be n lines. Each will contain n elements, with element j of line i being the answer from your friend for the number of length-2 paths from city i to city j ; it will be an integer between 0 and 100 000 inclusive. The test cases will finish with a line containing only the number zero (also preceded by a blank line). Note: Large input file; use fast I/O routines (e.g. scanf in C++ or BufferedReader in Java). Output For each case, your program should output a line. The content of this line should be YES if your classmate’s solution to the assignment is right, and NO otherwise. Example Input: 3 2 0 1 1 0 3 1 1 0 5 1 2 5 3 1 3 0 4 3 2 0 1 1 0 3 1 1 0 5 1 2 5 3 2 3 0 4 0 Output: YES NO Problem setter: Abel Molina Prieto
32,594
Fake Scoreboard (FAKESCOR) As you know, after the award ceremony of SWERC it is customary to publish a complete scoreboard with detailed information on the submissions and verdicts received. However, due to the buggy contest management system, most of the relevant data are not being recorded today. Clearly such state of affairs fails to meet the high standards we are committed to, so the judges have resolved to make up the rest of the data based on whatever shred of information left, and hope contestants are unable to tell the difference. To make our lives even simpler, we kindly ask you to provide a solution for us, or else today’s scoreboard will remain forever veiled in mystery (even the fake one). What we will know by the end of the contest is the number T of teams, the number P of problems, and the number of accepted submissions by each team. From the number and colour of balloons floating around on the premises we will also be able to infer how many teams solved each of the problems. Your task is to figure out which teams solved which problems. Our counting skills are not up to par, so your program should be able to detect when the data we collected must be wrong (see sample input 1). Otherwise you should output a possible solution, represented as a sequence of T strings of P characters each, in the following way. Both problems and teams are assigned with distinct integers, from 1 to P and 1 to T , respectively. For team number i (1 ≤ i ≤ T ), write the string on alphabet N, Y such that its j -th (1 ≤ j ≤ P ) character is Y if the team managed to get problem j accepted, and N otherwise. For example, the following three strings form a solution to the second sample case, where the score of each of three teams is 2, 1, 2, and the count of accepted submissions for each of three problems is 1, 2, 2: NYY NNY YYN There is at least one other solution, namely: NYY NYN YNY When several solutions are possible we ask you to supply the one giving rise to the lexicographically smallest string, when each of the T rows are concatenated in order. In the example above we prefer the first solution, since NYYNNYYYN comes before NYYNYNYNY in lexicographical order. (String S comes before S ′ in lexicographical order if the first different character between the two is N in S but Y in S '). Input Each input case is described by three lines: The first contains two space-separated integers T (the number of teams) and P (the number of problems), with 1 ≤ T , P ≤ 80. The second contains T space-separated integers between 0 and 90 (inclusive), the i -th of which indicates the number of problems solved by team i . The third (and last) line has P integers between 0 and 90, the j -th of which describes the number of teams successfully solving problem j . Different input cases are separated by a blank line. The last line of the input file will be 0 0 . Output If the input data has a solution, print T lines of P characters each, depicting the lexicographically smallest solution as explained above. Otherwise output a single line with the word Impossible . In any case a blank line should separate outputs for different test cases. Example Input: 2 2 1 2 1 1 3 3 2 1 2 1 2 2 3 5 3 3 1 3 1 1 0 2 0 0 Output: Impossible NYY NNY YYN YNYNY YYNNY YNNNN Problem setter: David García Soriano
32,595
Palindromic DNA (PALINDNA) A DNA sequence is composed of a series of four possible nucleobases, namely Adenine, Guanine, Thymine and Cytosine; we will refer to each of these bases by their initial. For our purposes, nucleobases have an associated cyclic “order”: A is followed by G , which in turn is followed by T , which is followed by C , which is followed by A again. State-of-the-art research in genomics has revealed the startling fact that many diseases are caused by certain subsequences of bases not forming a palindromic sequence! Your mission as a leading researcher at ICPC laboratories is to take a DNA string S and a series of subsets P 1 , …, P t of indices to characters (nucleobases) in S , and transform S so that each of the restrictions of the resulting string to P 1 , …, P t are palindromic. (The restriction of S to a subset P ={ i 1 , i 2 , …, i k } of indices, where 0 ≤ i 1 < i 2 < … < i k < | S |, is the string S i 1 S i 2 … S i k ). It is possible to inspect any base of S at will, but only three transformations can be applied to a base: Leave it unaltered. Increase it by 1 in the cyclic order of nucleobases (e.g. turn C into A ). Decrease it by 1 (e.g. turn T into G ). Moreover, owing to limitations of current technology, it is impossible to modify two bases in consecutive positions of the sequence. Is our goal achievable? By way of example, consider DNA sequence AGTAT . Number positions starting from 0, and suppose we have the three subsets P 1 = {1, 4}, P 2 = {0, 1} and P 3 = {0, 2, 4}. One solution is to increase the first character and decrease the last, yielding S ′ = GGTAG . The restrictions of S ′ to P 1 , P 2 and P 3 are GG , GG and GTG , respectively; all of them are palindromic. One case where no solution is possible is when the string is CATGC , and we require the subsequences determined by positions {0,3} and {3,4} be palindromic. Here, characters 3, 0 and 4 would all need to become a T . But this entails modifying consecutive characters 3 and 4, which is not allowed. Input The first line of each test case has two integers N and T (1 ≤ N ≤ 10 000, 1 ≤ T ≤ 6 000), the sequence length and number of subsets to consider. The next line contains the DNA sequence of length N , all of whose characters are in ACGT . The subsets are described by the following T lines. Each line starts by “ L :”, where L (0 ≤ L ≤ N ) is the number of positions in the subset, and is followed by T distinct integers between 0 and N − 1 in increasing order. Subsets may overlap partially or totally. A blank line separates different test cases. The input file is terminated by a line containing 0 0 . Output In a single line per test case, print YES if the task is solvable and NO otherwise. Sample Input 5 3 AGTAT 2: 1 4 2: 0 1 3: 0 2 4 5 3 CATGC 0: 2: 0 3 2: 3 4 0 0 Sample Output YES NO Problemsetter: David García Soriano
32,596
Jumping Monkey (JMPMNKEY) You are a hunter chasing a monkey in the forest, trying to shoot it down with your all-powerful automatic machine gun. The monkey is hiding somewhere behind the branches of one of the trees, out of your sight. You can aim at one of the trees and shoot; your bullets are capable of going through the branches and killing the monkey instantly if it happens to be in that tree. If it isn’t, the monkey takes advantage of the time it takes you to reload and takes a leap into a neighbouring tree without you noticing. It never stays in the same place after a shot. You would like to find out whether there is an strategy that allows you to capture the monkey for sure, irrespective of its initial location and subsequent jumps. If so, you need to determine the shortest sequence of shots guaranteeing this. As an example, consider the situation in which there are only two neighboring trees in the forest (left hand side of the figure). It is then possible to make sure you capture the monkey by shooting twice at the same tree. Your first shot succeeds if the monkey happened to be there in the first place. Otherwise, the monkey was behind the other tree and it will necessarily have moved when you shoot for the second time. However, depending on the shape of the forest it may not be possible for you to ensure victory. One example of this is if there are three trees, all connected to one another (right hand side of the figure). No matter where you aim at, there are always two possible locations for the monkey at any given moment. (Note that here we are concerned with the worst-case scenario where the monkey may consistently guess your next target tree). Input The input consists of several test cases, separated by single blank lines. Each test case begins with a line containing two integers n and m (1 ≤ n ≤ 21); n is the number of trees in the forest, and m is the number of adjacency relations between trees. Each of the following m lines contains two distinct integers between 0 and n −1 (inclusive), the identifiers of the trees in an adjacent pair. The order of both trees within a pair carries no meaning, and no pair appears more than once. You may further assume that no tree is adjacent to itself, and there is always a path between any two trees in the forest. The test cases will finish with a line containing only two zeros (also preceded with a blank line). Output Print a line for each test case. The line should contain the single word Impossible if the task is impossible. Otherwise, it must contain the shortest sequence of shots with the required property, in the format L : V 1 V 2 ... V L , where L is the length of the sequence, and V 1 , V 2 ... V L are space-separated integers containing the identifiers of the trees to shoot at in the right order. If several shortest sequences exist, print the lexicographically smallest one. (A sequence is smaller than another in lexicographic order if the first element on which they differ is smaller in the first one). Example Input: 2 1 0 1 3 3 0 1 1 2 2 0 4 3 0 1 2 3 1 3 0 0 Output: 2: 0 0 Impossible 4: 1 3 3 1 Problemsetter: Marçal Garolera Huguet
32,597
Sensor Network (SENSORNT) In response to a request by the SWERC 2010 problem-setting team, a sensor network has just been installed in the headquarters. The organizing committee has put in the problem-setters the disproportionate fear of suffering a leak of classified information about the problems. Nevertheless, in the rush they forgot to think about the electricity network needed to make the sensors work. Because of this, the security system is currently not working, but we need to justify the great amount of resources invested in it, so the installation must be ready before the end of the contest. Hence you are now asked to elaborate a program which will help the electrician in his duty. Since the organizing committee spared no expense, they ordered the sensors from a prestigious company. Every sensor is handcrafted and a number is written on each of them, whose meaning is the recommended voltage that should be applied to it for correct operation. They can be used under higher voltages, with an increasing risk of failure, but never with a voltage below the recommended one. The electrician gazed open-mouthed at the sensors when they were given to him: nearly all of them had different recommended voltages! The sensors were installed in the building in such a way that each of them controls exactly two doors and every door is controlled by at least one sensor. Now is the time for the electrician to supply power to the sensors. He faces the following constraints: Fortunately, there is no need to activate all sensors. However, we will require that the subset of sensors chosen to be on satisfy that every door is controlled by, at least, one sensor in the subset. Electricity is to be supplied to one of the active sensors, and then distributed to the others with wires. In order not to waste wires, they can only be installed by connecting a pair of neighboring active sensors (by “neighbouring” we mean that some door is controlled by both of them). Since we must supply energy to every active sensor, not every subset of sensors is suitable as the chosen subset of working sensors. Because of the above, all of the sensors will be supplied the same voltage, which cannot be below the corresponding recommended voltages. For simplicity, we will refer to a subset of sensors satisfying the first two constraints above as an admissible subset. The network is designed so that the set of all sensors is always admissible, but we would like to take a possibly smaller subset so as to minimize the margin , defined as the maximum of the differences, in absolute value, between the numbers written on each pair of sensors in the subset. (This is to keep the chances of failure to a minimum). The electrician could not solve the task of finding the admissible subset of the set of sensors for which the margin is minimum. Therefore, the electrical installation is still missing. Today, we ask you to write a program to find out the answer, given a sensor network and the recommended voltage for each of the sensors. Input The input consists of several test cases, separated by single blank lines. Each test case begins with a line containing the integer n (2 ≤ n ≤ 350), the number of doors in the building. The following line contains another integer, m ( n − 1 ≤ m ≤ n ( n − 1) / 2), the number of sensors in the network. The test case finishes with m lines containing a description of each of the m sensors. The i -th of those lines contains three integers, a (0 ≤ a ≤ n − 1), b (0 ≤ b ≤ n − 1) and w (1 ≤ w ≤ 2 15 ), in that order. Integers a and b represent the pair of doors controlled by the i -th sensor, and w its recommended voltage. You can safely assume that there are no two sensors controlling the same two doors. The input will finish with a line containing 0 . Output For each case, your program should output a line containing the minimum margin of an admissible subset of the sensors. Sample Input 3 3 0 1 220 1 2 120 2 0 160 4 5 2 3 80 1 3 80 0 1 180 2 1 200 3 0 140 0 Sample Output 40 60 Problemsetter: Luis Hernández Corbato
32,598
Assembly Line (ASSEMBLY) The last worker in a production line at the factory of Automated Composed Machinery is worried. She knows that her job hangs in the balance unless her productivity increases. Her work consists of assembling a set of pieces in a given sequence, but the time spent on assembling pieces a and b and then c may not the same as that on assembling pieces b and c , and then assembling a with the resulting component. Only two consecutive pieces may be assembled at a time, and once they are assembled they behave as another piece in terms of the time needed for further assembly. In order to aid her, you need to find the optimal way to assemble all components. The input to your program will be a set of symbols representing (types of) pieces, and a so-called assembly table representing the time it takes to assemble them, as well as the type of the resulting component. For instance, we may have two symbols { a , b }, and the following table: a b a 3 - b 5 - b b 6 - a 2 - b This means, for example, that two pieces of type a and a may be assembled in 3 minutes, and the result is a component of type b , in that the time required to assemble it again with another piece of, say, type a is 6 minutes, and so on. Note that the table is not symmetric, i.e. assembling b and a may be more time-consuming than a and b . For a sequence of components labelled aba , the two possible solutions are: ( ab ) a → ba → a with time time ( ab ) + time ( ba ) = 5 + 6 = 11. a ( ba ) → aa → b with time time ( ba ) + time ( aa ) = 6 + 3 = 9. So the result for this case would be a piece of type b in 9 minutes (denoted 9 - b ). Input The input consists of several test cases. Each test case begins with a line containing a natural number k (1 ≤ k ≤ 26), followed by a line with k symbols (characters in [a-z]) separated by spaces. The following k lines contain the assembly table: the i -th line has k pairs of the form time - result , where time is an integer between 0 and 1 000 000 inclusive, and result a symbol belonging to the preceding set. The j -th pair in the i -th line represents the time to compose pieces of types represented by the i -th and j -th symbols, along with the type of the resulting piece. After the table, a line with an integer n indicates the number of lines that follow, each line being a string of at most 200 symbols. Each of these lines is a sequence of components that need to be assembled together in the right order. The input will finish with a line containing 0 , which should not be processed. Output For each test case, print n lines, each with an integer time and a symbol result in the format time - result . Each line represents the minimum time and the type of the resulting piece for the corresponding case in the input. In case of a tie among several possible results with the same minimum time, choose from among those the piece whose type letter appears first in the line that contained the k symbols at the beginning of the test case. (For example, if that line was a c b and both c and b can be obtained with minimum cost 5, print 5 - c ). There must be an empty line between the output of different test cases. Example Input: 2 a b 3-b 5-b 6-a 2-b 2 aba bba 2 m e 5-e 4-m 3-e 4-m 1 eme 0 Output: 9-b 8-a 7-m Problem setter: Enrique Martín Martín
32,599