第二阶段 中级:第 3 周-第 4 周(共 85 题) 项目 时间 搜 记忆化搜索 必做题目 poj3373 索 较为复杂的动态规划 第4周 动 poj3280,poj2029,poj2948, poj1925,poj3034 态 记录状态的动态规划 poj3254,poj2411,poj1185 树型动态规划 poj2057,poj1947,poj2486, 规 划 poj3140 第4周 组合数学 poj1286,poj2409,poj3270, poj1026 poj2947,poj1487, 高斯消元法 poj2065,poj1222 数 概率问题 poj3071,poj3440 GCD、扩展的欧几里德 poj3101 计算方法 poj2976,poj3150,poj3422, 学 poj3070, poj3301 随机化算法 poj3318,poj2454 杂题 poj1870,poj3296,poj3286, poj1095 计 扫描线算法 poj1765,poj1177,poj1151, 算 poj3277,poj2280,poj3004 几 边形的内核 poj3130,poj3335 何 几何工具的综合应用 poj1819,poj1066,poj2043, 学 poj3227,poj2165,poj3429 第三阶段 高级:第 5 周-第 6 周(共 59 题) 项目 基 代码快速写成 时间 必做题目 第5周 poj2525,poj1684,poj1421, 本 poj1048,poj2050,poj3306 算 保证正确性和高效性 poj3434 法 度限制最小生成树和第 K 第5周 poj1639 最短路 poj3155,poj2112,poj1966, 最短路,最小生成树,二分 图 图,最大流问题的相关理论 poj3281,poj1087,poj2289, 算 poj3216,poj2446 法 最优比率生成树 poj2728 最小树形图 poj3164 次小生成树 无向图、有向图的最小环 trie 图的建立和应用 数 第5周 poj2778 LCA 和 RMQ 问题 poj1330 双端队列和它的应用 poj2823 据 结 构 左偏树 poj3415,poj3294 后缀树 较麻烦的搜索题目训练 第5周 poj1069,poj3322,poj1475, poj1924,poj2049,poj3426 搜 poj1768,poj1184,poj1872, 广搜的状态优化 索 poj1324,poj2046,poj1482 poj3131,poj2870,poj2286 深搜的优化 动 需要用数据结构优化的动 第6周 poj2754,poj3378,poj3017 态 态规划 规 四边形不等式理论 划 较难的状态 DP 数 组合数学 学 博奕论 poj3133 第6周 poj2888,poj2154 poj3317,poj1085 第6周 计 半平面求交 算 可视图的建立 poj3384,poj2540 poj2966 几 点集最小圆覆盖 何 对踵点 poj2079 学 第6周 综 poj3109,poj1478,poj1462, 合 poj2729,poj2048,poj3336, 题 poj3315,poj2148,poj1263 华南理工大学 ACM 集训队 Changing Digits Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 1794 Accepted: 520 Description Given two positive integers n and k, you are asked to generate a new integer, say m, by changing some (maybe none) digits of n, such that the following properties holds: 1. m contains no leading zeros and has the same length as n (We consider zero itself a one-digit integer without leading zeros.) 2. m is divisible by k 3. among all numbers satisfying properties 1 and 2, m would be the one with least number of digits different from n 4. among all numbers satisfying properties 1, 2 and 3, m would be the smallest one Input There are multiple test cases for the input. Each test case consists of two lines, which contains n(1≤n≤10100) and k(1≤k≤104, k≤n) for each line. Both n and k will not contain leading zeros. Output Output one line for each test case containing the desired number m. Sample Input 2 2 619103 3219 Sample Output 2 119103 Cheapest Palindrome Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 2938 Accepted: 1437 Description Keeping track of all the cows can be a tricky task so Farmer John has installed a system to automate it. He has installed on each cow an electronic ID tag that the system will read as the cows pass by a scanner. Each ID tag's contents are currently a single string with length M (1 ≤ M ≤ 2,000) characters drawn from an alphabet of N (1 ≤ N ≤ 26) different symbols (namely, the lower-case roman alphabet). Cows, being the mischievous creatures they are, sometimes try to spoof the system by walking backwards. While a cow whose ID is "abcba" would read the same no matter which direction the she walks, a cow with the ID "abcb" can potentially register as two different IDs ("abcb" and "bcba"). FJ would like to change the cows's ID tags so they read the same no matter which direction the cow walks by. For example, "abcb" can be changed by adding "a" at the end to form "abcba" so that the ID is palindromic (reads the same forwards and backwards). Some other ways to change the ID to be palindromic are include adding the three letters "bcb" to the begining to yield the ID "bcbabcb" or removing the letter "a" to yield the ID "bcb". One can add or remove characters at any location in the string yielding a string longer or shorter than the original string. Unfortunately as the ID tags are electronic, each character insertion or deletion has a cost (0 ≤ cost ≤ 10,000) which varies depending on exactly which character value to be added or deleted. Given the content of a cow's ID tag and the cost of inserting or deleting each of the alphabet's characters, find the minimum cost to change the ID tag so it satisfies FJ's requirements. An empty ID tag is considered to satisfy the requirements of reading the same forward and backward. Only letters with associated costs can be added to a string. Input Line 1: Two space-separated integers: N and M Line 2: This line contains exactly M characters which constitute the initial ID string Lines 3..N+2: Each line contains three space-separated entities: a character of the input alphabet and two integers which are respectively the cost of adding and deleting that character. Output Line 1: A single line with a single integer that is the minimum cost to change the given name tag. Sample Input 3 4 abcb a 1000 1100 b 350 700 c 200 800 Sample Output 900 Hint If we insert an "a" on the end to get "abcba", the cost would be 1000. If we delete the "a" on the beginning to get "bcb", the cost would be 1100. If we insert "bcb" at the begining of the string, the cost would be 350 + 200 + 350 = 900, which is the minimum. Get Many Persimmon Trees Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 1930 Accepted: 1228 Description Seiji Hayashi had been a professor of the Nisshinkan Samurai School in the domain of Aizu for a long time in the 18th century. In order to reward him for his meritorious career in education, Katanobu Matsudaira, the lord of the domain of Aizu, had decided to grant him a rectangular estate within a large field in the Aizu Basin. Although the size (width and height) of the estate was strictly specified by the lord, he was allowed to choose any location for the estate in the field. Inside the field which had also a rectangular shape, many Japanese persimmon trees, whose fruit was one of the famous products of the Aizu region known as 'Mishirazu Persimmon', were planted. Since persimmon was Hayashi's favorite fruit, he wanted to have as many persimmon trees as possible in the estate given by the lord. For example, in Figure 1, the entire field is a rectangular grid whose width and height are 10 and 8 respectively. Each asterisk (*) represents a place of a persimmon tree. If the specified width and height of the estate are 4 and 3 respectively, the area surrounded by the solid line contains the most persimmon trees. Similarly, if the estate's width is 6 and its height is 4, the area surrounded by the dashed line has the most, and if the estate's width and height are 3 and 4 respectively, the area surrounded by the dotted line contains the most persimmon trees. Note that the width and height cannot be swapped; the sizes 4 by 3 and 3 by 4 are different, as shown in Figure 1. Figure 1: Examples of Rectangular Estates Your task is to find the estate of a given size (width and height) that contains the largest number of persimmon trees. Input The input consists of multiple data sets. Each data set is given in the following format. N WH x1 y1 x2 y2 ... xN yN ST N is the number of persimmon trees, which is a positive integer less than 500. W and H are the width and the height of the entire field respectively. You can assume that both W and H are positive integers whose values are less than 100. For each i (1 <= i <= N), xi and yi are coordinates of the i-th persimmon tree in the grid. Note that the origin of each coordinate is 1. You can assume that 1 <= xi <= W and 1 <= yi <= H, and no two trees have the same positions. But you should not assume that the persimmon trees are sorted in some order according to their positions. Lastly, S and T are positive integers of the width and height respectively of the estate given by the lord. You can also assume that 1 <= S <= W and 1 <= T <= H. The end of the input is indicated by a line that solely contains a zero. Output For each data set, you are requested to print one line containing the maximum possible number of persimmon trees that can be included in an estate of the given size. Sample Input 16 10 8 2 2 2 5 2 7 3 3 3 8 4 2 4 5 4 8 6 4 6 7 7 5 7 8 8 1 8 4 9 6 10 3 4 3 8 6 4 1 2 2 1 2 4 3 4 4 2 5 3 6 1 6 2 3 2 0 Sample Output 4 3 Martian Mining Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 1506 Accepted: 909 Description The NASA Space Center, Houston, is less than 200 miles from San Antonio, Texas (the site of the ACM Finals this year). This is the place where the astronauts are trained for Mission Seven Dwarfs, the next giant leap in space exploration. The Mars Odyssey program revealed that the surface of Mars is very rich in yeyenum and bloggium. These minerals are important ingredients for certain revolutionary new medicines, but they are extremely rare on Earth. The aim of Mission Seven Dwarfs is to mine these minerals on Mars and bring them back to Earth. The Mars Odyssey orbiter identified a rectangular area on the surface of Mars that is rich in minerals. The area is divided into cells that form a matrix of n rows and m columns, where the rows go from east to west and the columns go from north to south. The orbiter determined the amount of yeyenum and bloggium in each cell. The astronauts will build a yeyenum refinement factory west of the rectangular area and a bloggium factory to the north. Your task is to design the conveyor belt system that will allow them to mine the largest amount of minerals. There are two types of conveyor belts: the first moves minerals from east to west, the second moves minerals from south to north. In each cell you can build either type of conveyor belt, but you cannot build both of them in the same cell. If two conveyor belts of the same type are next to each other, then they can be connected. For example, the bloggium mined at a cell can be transported to the bloggium refinement factory via a series of south-north conveyor belts. The minerals are very unstable, thus they have to be brought to the factories on a straight path without any turns. This means that if there is a south-north conveyor belt in a cell, but the cell north of it contains an east-west conveyor belt, then any mineral transported on the south-north conveyor beltwill be lost. The minerals mined in a particular cell have to be put on a conveyor belt immediately, in the same cell (thus they cannot start the transportation in an adjacent cell). Furthermore, any bloggium transported to the yeyenum refinement factory will be lost, and vice versa. Your program has to design a conveyor belt system that maximizes the total amount of minerals mined,i.e., the sum of the amount of yeyenum transported to the yeyenum refinery and the amount of bloggium transported to the bloggium refinery. Input The input contains several blocks of test cases. Each case begins with a line containing two integers: the number 1 ≤ n ≤ 500 of rows, and the number 1 ≤ m ≤ 500 of columns. The next n lines describe the amount of yeyenum that can be found in the cells. Each of these n lines contains m integers. The first line corresponds to the northernmost row; the first integer of each line corresponds to the westernmost cell of the row. The integers are between 0 and 1000. The next n lines describe in a similar fashion theamount of bloggium found in the cells. The input is terminated by a block with n = m = 0. Output For each test case, you have to output a single integer on a separate line: the maximum amount of mineralsthat can be mined. Sample Input 4 4 0 0 10 9 1 3 10 0 4 2 1 3 1 1 20 0 10 0 0 0 1 1 1 30 0 0 5 5 5 10 10 10 0 0 Sample Output 98 Hint Huge input file, 'scanf' recommended to avoid TLE. Spiderman Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 4272 Accepted: 744 Description Dr. Octopus kidnapped Spiderman's girlfriend M.J. and kept her in the West Tower. Now the hero, Spiderman, has to reach the tower as soon as he can to rescue her, using his own weapon, the web. From Spiderman's apartment, where he starts, to the tower there is a straight road. Alongside of the road stand many tall buildings, which are definitely taller or equal to his apartment. Spiderman can shoot his web to the top of any building between the tower and himself (including the tower), and then swing to the other side of the building. At the moment he finishes the swing, he can shoot his web to another building and make another swing until he gets to the west tower. Figure-1 shows how Spiderman gets to the tower from the top of his apartment – he swings from A to B, from B to C, and from C to the tower. All the buildings (including the tower) are treated as straight lines, and during his swings he can't hit the ground, which means the length of the web is shorter or equal to the height of the building. Notice that during Spiderman's swings, he can never go backwards. You may assume that each swing takes a unit of time. As in Figure-1, Spiderman used 3 swings to reach the tower, and you can easily find out that there is no better way. Input The first line of the input contains the number of test cases K (1 <= K <= 20). Each case starts with a line containing a single integer N (2 <= N <= 5000), the number of buildings (including the apartment and the tower). N lines follow and each line contains two integers Xi, Yi, (0 <= Xi, Yi <= 1000000) the position and height of the building. The first building is always the apartment and the last one is always the tower. The input is sorted by Xi value in ascending order and no two buildings have the same X value. Output For each test case, output one line containing the minimum number of swings (if it's possible to reach the tower) or -1 if Spiderman can't reach the tower. Sample Input 2 6 0 3 3 5 4 3 5 5 7 4 10 4 3 0 3 3 4 10 4 Sample Output 3 -1 Whac-a-Mole Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 2090 Accepted: 624 Description While visiting a traveling fun fair you suddenly have an urge to break the high score in the Whac-a-Mole game. The goal of the Whac-a-Mole game is to… well… whack moles. With a hammer. To make the job easier you have first consulted the fortune teller and now you know the exact appearance patterns of the moles. The moles appear out of holes occupying the n2 integer points (x, y) satisfying 0 ≤ x, y < n in a two-dimensional coordinate system. At each time step, some moles will appear and then disappear again before the next time step. After the moles appear but before they disappear, you are able to move your hammer in a straight line to any position (x2, y2) that is at distance at most d from your current position (x1, y1). For simplicity, we assume that you can only move your hammer to a point having integer coordinates. A mole is whacked if the center of the hole it appears out of is located on the line between (x1, y1) and (x2, y2) (including the two endpoints). Every mole whacked earns you a point. When the game starts, before the first time step, you are able to place your hammer anywhere you see fit. Input The input consists of several test cases. Each test case starts with a line containing three integers n, d and m, where n and d are as described above, and m is the total number of moles that will appear (1 ≤ n ≤ 20, 1 ≤ d ≤ 5, and 1 ≤ m ≤ 1000). Then follow m lines, each containing three integers x, y and t giving the position and time of the appearance of a mole (0 ≤ x, y < n and 1 ≤ t ≤ 10). No two moles will appear at the same place at the same time. The input is ended with a test case where n = d = m = 0. This case should not be processed. Output For each test case output a single line containing a single integer, the maximum possible score achievable. Sample Input 4 0 3 0 0 1 2 5 0 1 2 0 2 0 1 1 2 0 0 4 0 2 4 0 6 1 3 2 2 2 2 3 1 1 1 0 Sample Output 4 2 Corn Fields Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 2506 Accepted: 1273 Description Farmer John has purchased a lush new rectangular pasture composed of M by N (1 ≤ M ≤ 12; 1 ≤ N ≤ 12) square parcels. He wants to grow some yummy corn for the cows on a number of squares. Regrettably, some of the squares are infertile and can't be planted. Canny FJ knows that the cows dislike eating close to each other, so when choosing which squares to plant, he avoids choosing squares that are adjacent; no two chosen squares share an edge. He has not yet made the final choice as to which squares to plant. Being a very open-minded man, Farmer John wants to consider all possible options for how to choose the squares for planting. He is so open-minded that he considers choosing no squares as a valid option! Please help Farmer John determine the number of ways he can choose the squares to plant. Input Line 1: Two space-separated integers: M and N Lines 2..M+1: Line i+1 describes row i of the pasture with N space-separated integers indicating whether a square is fertile (1 for fertile, 0 for infertile) Output Line 1: One integer: the number of ways that FJ can choose the squares modulo 100,000,000. Sample Input 2 3 1 1 1 0 1 0 Sample Output 9 Hint Number the squares as follows: 1 2 3 4 There are four ways to plant only on one squares (1, 2, 3, or 4), three ways to plant on two squares (13, 14, or 34), 1 way to plant on three squares (134), and one way to plant on no squares. 4+3+1+1=9. Source USACO 2006 November Gold Mondriaan's Dream Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 5358 Accepted: 3063 Description Squares and rectangles fascinated the famous Dutch painter Piet Mondriaan. One night, after producing the drawings in his 'toilet series' (where he had to use his toilet paper to draw on, for all of his paper was filled with squares and rectangles), he dreamt of filling a large rectangle with small rectangles of width 2 and height 1 in varying ways. Expert as he was in this material, he saw at a glance that he'll need a computer to calculate the number of ways to fill the large rectangle whose dimensions were integer values, as well. Help him, so that his dream won't turn into a nightmare! Input The input contains several test cases. Each test case is made up of two integer numbers: the height h and the width w of the large rectangle. Input is terminated by h=w=0. Otherwise, 1<=h,w<=11. Output For each test case, output the number of different ways the given rectangle can be filled with small rectangles of size 2 times 1. Assume the given large rectangle is oriented, i.e. count symmetrical tilings multiple times. Sample Input 1 1 1 2 2 2 2 4 0 2 3 4 2 3 4 11 11 0 Sample Output 1 0 1 2 3 5 144 51205 炮兵阵地 Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 8378 Accepted: 2936 Description 司令部的将军们打算在 N*M 的网格地图上部署他们的炮兵部队。一个 N*M 的地图由 N 行 M 列组成,地 图的每一格可能是山地(用"H" 表示),也可能是平原(用"P"表示),如下图。在每一格平原地形上最 多可以布置一支炮兵部队(山地上不能够部署炮兵部队);一支炮兵部队在地图上的攻击范围如图中黑色 区域所示: 如果在地图中的灰色所标识的平原上部署一支炮兵部队,则图中的黑色的网格表示它能够攻击到的区域: 沿横向左右各两格,沿纵向上下各两格。图上其它白色网格均攻击不到。从图上可见炮兵的攻击范围不受 地形的影响。 现在,将军们规划如何部署炮兵部队,在防止误伤的前提下(保证任何两支炮兵部队之间不能互相攻击, 即任何一支炮兵部队都不在其他支炮兵部队的攻击范围内),在整个地图区域内最多能够摆放多少我军的 炮兵部队。 Input 第一行包含两个由空格分割开的正整数,分别表示 N 和 M; 接下来的 N 行,每一行含有连续的 M 个字符('P'或者'H'),中间没有空格。按顺序表示地图中每一行的数据。 N <= 100;M <= 10。 Output 仅一行,包含一个整数 K,表示最多能摆放的炮兵部队的数量。 Sample Input 5 4 PHPP PPHH PPPP PHPP PHHP Sample Output 6 The Lost House Description Time Limit: 3000MS Memory Limit: 30000K Total Submissions: 1294 Accepted: 525 One day a snail climbed up to a big tree and finally came to the end of a branch. What a different feeling to look down from such a high place he had never been to before! However, he was very tired due to the long time of climbing, and fell asleep. An unbelievable thing happened when he woke up ---- he found himself lying in a meadow and his house originally on his back disappeared! Immediately he realized that he fell off the branch when he was sleeping! He was sure that his house must still be on the branch he had been sleeping on. The snail began to climb the tree again, since he could not live without his house. When reaching the first fork of the tree, he sadly found that he could not remember the route that he climbed before. In order to find his lovely house, the snail decided to go to the end of every branch. It was dangerous to walk without the protection of the house, so he wished to search the tree in the best way. Fortunately, there lived many warm-hearted worms in the tree that could accurately tell the snail whether he had ever passed their places or not before he fell off. Now our job is to help the snail. We pay most of our attention to two parts of the tree ---- the forks of the branches and the ends of the branches, which we call them key points because key events always happen there, such as choosing a path, getting the help from a worm and arriving at the house he is searching for. Assume all worms live at key points, and all the branches between two neighboring key points have the same distance of 1. The snail is now at the first fork of the tree. Our purpose is to find a proper route along which he can find his house as soon as possible, through the analysis of the structure of the tree and the locations of the worms. The only restriction on the route is that he must not go down from a fork until he has reached all the ends grown from this fork. The house may be left at the end of any branches in an equal probability. We focus on the mathematical expectation of the distance the snail has to cover before arriving his house. We wish the value to be as small as possible. As illustrated in Figure-1, the snail is at the key point 1 and his house is at a certain point among 2, 4 and 5. A worm lives at point 3, who can tell the snail whether his house is at one of point 4 and 5 or not. Therefore, the snail can choose two strategies. He can go to point 2 first. If he cannot find the house there, he should go back to point 1, and then reaches point 4 (or 5) by point 3. If still not, he has to return point 3, then go to point 5 (or 4), where he will undoubtedly find his house. In this choice, the snail covers distances of 1, 4, 6 corresponding to the circumstances under which the house is located at point 2, 4 (or 5), 5 (or 4) respectively. So the expectation value is (1 + 4 + 6) / 3 = 11 / 3. Obviously, this strategy does not make full use of the information from the worm. If the snail goes to point 3 and gets useful information from the worm first, and then chooses to go back to point 1 then towards point 2, or go to point 4 or 5 to take his chance, the distances he covers will be 2, 3, 4 corresponding to the different locations of the house. In such a strategy, the mathematical expectation will be (2 + 3 + 4) / 3 = 3, and it is the very route along which the snail should search the tree. Input The input contains several sets of test data. Each set begins with a line containing one integer N, no more than 1000, which indicates the number of key points in the tree. Then follow N lines describing the N key points. For convenience, we number all the key points from 1 to N. The key point numbered with 1 is always the first fork of the tree. Other numbers may be any key points in the tree except the first fork. The i-th line in these N lines describes the key point with number i. Each line consists of one integer and one uppercase character 'Y' or 'N' separated by a single space, which represents the number of the previous key point and whether there lives a worm ('Y' means lives and 'N' means not). The previous key point means the neighboring key point in the shortest path between this key point and the key point numbered 1. In the above illustration, the previous key point of point 2 or 3 is point 1, while the previous key point of point 4 or 5 is point 3. This integer is -1 for the key point 1, means it has no previous key point. You can assume a fork has at most eight branches. The first set in the sample input describes the above illustration. A test case of N = 0 indicates the end of input, and should not be processed. Output Output one line for each set of input data. The line contains one float number with exactly four digits after the decimal point, which is the mathematical expectation value. Sample Input 5 -1 N 1 N 1 Y 3 N 3 N 10 -1 N 1 Y 1 N 2 N 2 N 2 N 3 N 3 Y 8 N 8 N 6 -1 N 1 N 1 Y 1 N 3 N 3 N 0 Sample Output 3.0000 5.0000 3.5000 Source Beijing 2004 Rebuilding Roads Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 4825 Accepted: 2017 Description The cows have reconstructed Farmer John's farm, with its N barns (1 <= N <= 150, number 1..N) after the terrible earthquake last May. The cows didn't have time to rebuild any extra roads, so now there is exactly one way to get from any given barn to any other barn. Thus, the farm transportation system can be represented as a tree. Farmer John wants to know how much damage another earthquake could do. He wants to know the minimum number of roads whose destruction would isolate a subtree of exactly P (1 <= P <= N) barns from the rest of the barns. Input * Line 1: Two integers, N and P * Lines 2..N: N-1 lines, each with two integers I and J. Node I is node J's parent in the tree of roads. Output A single line containing the integer that is the minimum number of roads that need to be destroyed for a subtree of P nodes to be isolated. Sample Input 11 6 1 2 1 3 1 4 1 5 2 6 2 7 2 8 4 9 4 10 4 11 Sample Output 2 Hint [A subtree with nodes (1, 2, 3, 6, 7, 8) will become isolated if roads 1-4 and 1-5 are destroyed.] Source USACO 2002 February Apple Tree Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 3520 Accepted: 1059 Description Wshxzt is a lovely girl. She likes apple very much. One day HX takes her to an apple tree. There are N nodes in the tree. Each node has an amount of apples. Wshxzt starts her happy trip at one node. She can eat up all the apples in the nodes she reaches. HX is a kind guy. He knows that eating too many can make the lovely girl become fat. So he doesn’t allow Wshxzt to go more than K steps in the tree. It costs one step when she goes from one node to another adjacent node. Wshxzt likes apple very much. So she wants to eat as many as she can. Can you tell how many apples she can eat in at most K steps. Input There are several test cases in the input Each test case contains three parts. The first part is two numbers N K, whose meanings we have talked about just now. We denote the nodes by 1 2 ... N. Since it is a tree, each node can reach any other in only one route. (1<=N<=100, 0<=K<=200) The second part contains N integers (All integers are nonnegative and not bigger than 1000). The ith number is the amount of apples in Node i. The third part contains N-1 line. There are two numbers A,B in each line, meaning that Node A and Node B are adjacent. Input will be ended by the end of file. Note: Wshxzt starts at Node 1. Output For each test case, output the maximal numbers of apples Wshxzt can eat at a line. Sample Input 2 0 1 3 0 1 1 1 11 2 2 1 2 2 3 Sample Output 11 2 Contestants Division Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 4944 Accepted: 1339 Description In the new ACM-ICPC Regional Contest, a special monitoring and submitting system will be set up, and students will be able to compete at their own universities. However there’s one problem. Due to the high cost of the new judging system, the organizing committee can only afford to set the system up such that there will be only one way to transfer information from one university to another without passing the same university twice. The contestants will be divided into two connected regions, and the difference between the total numbers of students from two regions should be minimized. Can you help the juries to find the minimum difference? Input There are multiple test cases in the input file. Each test case starts with two integers N and M, (1 ≤ N ≤ 100000, 1 ≤ M ≤ 1000000), the number of universities and the number of direct communication line set up by the committee, respectively. Universities are numbered from 1 to N. The next line has N integers, the Kth integer is equal to the number of students in university numbered K. The number of students in any university does not exceed 100000000. Each of the following M lines has two integers s, t, and describes a communication line connecting university s and university t. All communication lines of this new system are bidirectional. N = 0, M = 0 indicates the end of input and should not be processed by your program. Output For every test case, output one integer, the minimum absolute difference of students between two regions in the format as indicated in the sample output. Sample Input 7 1 1 2 3 4 6 5 0 6 1 1 1 1 1 1 2 7 7 6 2 7 0 Sample Output Case 1: 1 Source Shanghai 2006 Necklace of Beads Description Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 3321 Accepted: 1391 Beads of red, blue or green colors are connected together into a circular necklace of n beads ( n < 24 ). If the repetitions that are produced by rotation around the center of the circular necklace or reflection to the axis of symmetry are all neglected, how many different forms of the necklace are there? Input The input has several lines, and each line contains the input data n. -1 denotes the end of the input file. Output The output should contain the output data: Number of different forms, in each line correspondent to the input data. Sample Input 4 5 -1 Sample Output 21 39 Let it Bead Description Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 2164 Accepted: 1332 "Let it Bead" company is located upstairs at 700 Cannery Row in Monterey, CA. As you can deduce from the company name, their business is beads. Their PR department found out that customers are interested in buying colored bracelets. However, over 90 percent of the target audience insists that the bracelets be unique. (Just imagine what happened if two women showed up at the same party wearing identical bracelets!) It's a good thing that bracelets can have different lengths and need not be made of beads of one color. Help the boss estimating maximum profit by calculating how many different bracelets can be produced. A bracelet is a ring-like sequence of s beads each of which can have one of c distinct colors. The ring is closed, i.e. has no beginning or end, and has no direction. Assume an unlimited supply of beads of each color. For different values of s and c, calculate the number of different bracelets that can be made. Input Every line of the input file defines a test case and contains two integers: the number of available colors c followed by the length of the bracelets s. Input is terminated by c=s=0. Otherwise, both are positive, and, due to technical difficulties in the bracelet-fabrication-machine, cs<=32, i.e. their product does not exceed 32. Output For each test case output on a single line the number of unique bracelets. The figure below shows the 8 different bracelets that can be made with 2 colors and 5 beads. Sample Input 1 2 2 5 2 2 6 0 1 1 2 1 5 6 2 0 Sample Output 1 2 3 5 8 13 21 Cow Sorting Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 3568 Accepted: 1170 Description Farmer John's N (1 ≤ N ≤ 10,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage FJ's milking equipment, FJ would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (not necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes FJ a total of X+Y units of time to exchange two cows whose grumpiness levels are X and Y. Please help FJ calculate the minimal time required to reorder the cows. Input Line 1: A single integer: N. Lines 2..N+1: Each line contains a single integer: line i+1 describes the grumpiness of cow i. Output Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness. Sample Input 3 2 3 1 Sample Output 7 Hint 2 3 1 : Initial order. 2 1 3 : After interchanging cows with grumpiness 3 and 1 (time=1+3=4). 1 2 3 : After interchanging cows with grumpiness 1 and 2 (time=2+1=3). Source USACO 2007 February Gold Cipher Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 13573 Accepted: 3416 Description Bob and Alice started to use a brand-new encoding scheme. Surprisingly it is not a Public Key Cryptosystem, but their encoding and decoding is based on secret keys. They chose the secret key at their last meeting in Philadelphia on February 16th, 1996. They chose as a secret key a sequence of n distinct integers, a1 ; . . .; an, greater than zero and less or equal to n. The encoding is based on the following principle. The message is written down below the key, so that characters in the message and numbers in the key are correspondingly aligned. Character in the message at the position i is written in the encoded message at the position ai, where ai is the corresponding number in the key. And then the encoded message is encoded in the same way. This process is repeated k times. After kth encoding they exchange their message. The length of the message is always less or equal than n. If the message is shorter than n, then spaces are added to the end of the message to get the message with the length n. Help Alice and Bob and write program which reads the key and then a sequence of pairs consisting of k and message to be encoded k times and produces a list of encoded messages. Input The input file consists of several blocks. Each block has a number 0 < n <= 200 in the first line. The next line contains a sequence of n numbers pairwise distinct and each greater than zero and less or equal than n. Next lines contain integer number k and one message of ascii characters separated by one space. The lines are ended with eol, this eol does not belong to the message. The block ends with the separate line with the number 0. After the last block there is in separate line the number 0. Output Output is divided into blocks corresponding to the input blocks. Each block contains the encoded input messages in the same order as in input file. Each encoded message in the output file has the lenght n. After each block there is one empty line. Sample Input 10 4 5 3 7 2 8 1 6 10 9 1 Hello Bob 1995 CERC 0 0 Sample Output BolHeol C RCE b Source Central Europe 1995 Widget Factory Time Limit: 7000MS Memory Limit: 65536K Total Submissions: 2146 Accepted: 717 Description The widget factory produces several different kinds of widgets. Each widget is carefully built by a skilled widgeteer. The time required to build a widget depends on its type: the simple widgets need only 3 days, but the most complex ones may need as many as 9 days. The factory is currently in a state of complete chaos: recently, the factory has been bought by a new owner, and the new director has fired almost everyone. The new staff know almost nothing about building widgets, and it seems that no one remembers how many days are required to build each diofferent type of widget. This is very embarrassing when a client orders widgets and the factory cannot tell the client how many days are needed to produce the required goods. Fortunately, there are records that say for each widgeteer the date when he started working at the factory, the date when he was fired and what types of widgets he built. The problem is that the record does not say the exact date of starting and leaving the job, only the day of the week. Nevertheless, even this information might be helpful in certain cases: for example, if a widgeteer started working on a Tuesday, built a Type 41 widget, and was fired on a Friday,then we know that it takes 4 days to build a Type 41 widget. Your task is to figure out from these records (if possible) the number of days that are required to build the different types of widgets. Input The input contains several blocks of test cases. Each case begins with a line containing two integers: the number 1 ≤ n ≤ 300 of the different types, and the number 1 ≤ m ≤ 300 of the records. This line is followed by a description of the m records. Each record is described by two lines. The first line contains the total number 1 ≤ k ≤ 10000 of widgets built by this widgeteer, followed by the day of week when he/she started working and the day of the week he/she was fired. The days of the week are given bythe strings `MON', `TUE', `WED', `THU', `FRI', `SAT' and `SUN'. The second line contains k integers separated by spaces. These numbers are between 1 and n , and they describe the diofferent types of widgets that the widgeteer built. For example, the following two lines mean that the widgeteer started working on a Wednesday, built a Type 13 widget, a Type 18 widget, a Type 1 widget, again a Type 13 widget,and was fired on a Sunday. 4 WED SUN 13 18 1 13 Note that the widgeteers work 7 days a week, and they were working on every day between their first and last day at the factory (if you like weekends and holidays, then do not become a widgeteer!). The input is terminated by a test case with n = m = 0 . Output For each test case, you have to output a single line containing n integers separated by spaces: the number of days required to build the different types of widgets. There should be no space before the first number or after the last number, and there should be exactly one space between two numbers. If there is more than one possible solution for the problem, then write `Multiple solutions.' (without the quotes). If you are sure that there is no solution consistent with the input, then write `Inconsistent data.'(without the quotes). Sample Input 2 3 2 MON 1 2 3 MON 1 1 2 3 MON 1 2 2 10 2 1 MON 3 1 MON 3 0 0 THU FRI SUN TUE WED Sample Output 8 3 Inconsistent data. Hint Huge input file, 'scanf' recommended to avoid TLE. Source Central Europe 2005 Single-Player Games Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 492 Accepted: 156 Description Playing games is the most fun if other people take part. But other players are not always available if you need them, which led to the invention of single-player games. One of the most well-known examples is the infamous ``Solitaire'' packaged with Windows, probably responsible for more wasted hours in offices around the world than any other game. The goal of a single-player game is usually to make ``moves'' until one reaches a final state of the game, which results in a win or loss, or a score assigned to that final state. Most players try to optimize the result of the game by employing good strategies. In this problem we are interested in what happens if one plays randomly. After all, these games are mostly used to waste time, and playing randomly achieves this goal as well as any other strategy. Games can very compactly represented as (possibly infinite) trees. Every node of the tree repre- sents a possible game state. The root of the tree corresponds to the starting position of the game. For an inner node, its children are the game states to which one can move in a single move. The leaf nodes are the final states, and every one of them is assigned a number, which is the score one receives when ending up at that leaf. Trees are defined using the following grammar. Definition ::= Identifier "=" RealTree RealTree ::= "("Tree+")" Tree ::= Identifier | Integer | "("Tree+")" Identifier ::= a|b|...|z Integer ∈ {...,-3,-2,-1,0,1,2,3,...,} By using a Definition, the RealTree on the right-hand side of the equation is assigned to the Identifier on the left. A RealTree consists of a root node and one or more children, given as a sequence enclosed in brackets. And a Tree is either . the tree represented by a given Identifier, or . a leaf node, represented by a single Integer, or . an inner node, represented by a sequence of one or more Trees (its children), enclosed in brackets. Your goal is to compute the expected score, if one plays randomly, i.e. at each inner node selects one of the children uniformly at random. This expected score is well-defined even for the infinite trees definable in our framework as long as the probability that the game ends (playing randomly) is 1. Input The input file contains several gametree descriptions. Each description starts with a line containing the number n of identifiers used in the description. The identifiers used will be the first n lowercase letters of the alphabet. The following n lines contain the definitions of these identifiers (in the order a, b, ...). Each definition may contain arbitrary whitespace (but of course there will be no spaces within a single integer). The right hand side of a definition will contain only identifiers from the first n lowercase letters. The inputs ends with a test case starting with n = 0. This test case should not be processed. Output For each gametree description in the input, first output the number of the game. Then, for all n identifiers in the order a, b, ..., output the following. If an identifier represents a gametree for which the probability of finishing the game is 1, print the expected score (when playing randomly). This value should be exact to three digits to the right of the decimal point. If the game described by the variable does not end with probability 1, print ``Expected score of id undefined'' instead. Output a blank line after each test case. Sample Input 1 a 2 a b 1 a 0 = ((1 7) 6 ((8 3) 4)) = (1 b) = (4 a) = (a a a) Sample Output Game 1 Expected score for a = 4.917 Game 2 Expected score for a = 2.000 Expected score for b = 3.000 Game 3 Expected score for a undefined Source Southwestern European Regional Contest 1998 SETI Description Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 673 Accepted: 387 For some years, quite a lot of work has been put into listening to electromagnetic radio signals received from space, in order to understand what civilizations in distant galaxies might be trying to tell us. One signal source that has been of particular interest to the scientists at Universit´e de Technologie Spatiale is the Nebula Stupidicus. Recently, it was discovered that if each message is assumed to be transmitted as a sequence of integers a0, a1, ...an-1 the function f (k) = ∑0<=i<=n-1aiki (mod p) always evaluates to values 0 <= f (k) <= 26 for 1 <= k <= n, provided that the correct value of p is used. n is of course the length of the transmitted message, and the ai denote integers such that 0 <= ai < p. p is a prime number that is guaranteed to be larger than n as well as larger than 26. It is, however, known to never exceed 30 000. These relationships altogether have been considered too peculiar for being pure coincidences, which calls for further investigation. The linguists at the faculty of Langues et Cultures Extraterrestres transcribe these messages to strings in the English alphabet to make the messages easier to handle while trying to interpret their meanings. The transcription procedure simply assigns the letters a..z to the values 1..26 that f (k) might evaluate to, such that 1 = a, 2 = b etc. The value 0 is transcribed to '*' (an asterisk). While transcribing messages, the linguists simply loop from k = 1 to n, and append the character corresponding to the value of f (k) at the end of the string. The backward transcription procedure, has however, turned out to be too complex for the linguists to handle by themselves. You are therefore assigned the task of writing a program that converts a set of strings to their corresponding Extra Terrestial number sequences. Input On the first line of the input there is a single positive integer N, telling the number of test cases to follow. Each case consists of one line containing the value of p to use during the transcription of the string, followed by the actual string to be transcribed. The only allowed characters in the string are the lower case letters 'a'..'z' and '*' (asterisk). No string will be longer than 70 characters. Output For each transcribed string, output a line with the corresponding list of integers, separated by space, with each integer given in the order of ascending values of i. Sample Input 3 31 aaa 37 abc 29 hello*earth Sample Output 1 0 0 0 1 0 8 13 9 13 4 27 18 10 12 24 15 EXTENDED LIGHTS OUT Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 2896 Accepted: 1933 Description In an extended version of the game Lights Out, is a puzzle with 5 rows of 6 buttons each (the actual puzzle has 5 rows of 5 buttons each). Each button has a light. When a button is pressed, that button and each of its (up to four) neighbors above, below, right and left, has the state of its light reversed. (If on, the light is turned off; if off, the light is turned on.) Buttons in the corners change the state of 3 buttons; buttons on an edge change the state of 4 buttons and other buttons change the state of 5. For example, if the buttons marked X on the left below were to be pressed,the display would change to the image on the right. The aim of the game is, starting from any initial set of lights on in the display, to press buttons to get the display to a state where all lights are off. When adjacent buttons are pressed, the action of one button can undo the effect of another. For instance, in the display below, pressing buttons marked X in the left display results in the right display.Note that the buttons in row 2 column 3 and row 2 column 5 both change the state of the button in row 2 column 4,so that, in the end, its state is unchanged. Note: 1. It does not matter what order the buttons are pressed. 2. If a button is pressed a second time, it exactly cancels the effect of the first press, so no button ever need be pressed more than once. 3. As illustrated in the second diagram, all the lights in the first row may be turned off, by pressing the corresponding buttons in the second row. By repeating this process in each row, all the lights in the first four rows may be turned out. Similarly, by pressing buttons in columns 2, 3 ?, all lights in the first 5 columns may be turned off. Write a program to solve the puzzle. Input The first line of the input is a positive integer n which is the number of puzzles that follow. Each puzzle will be five lines, each of which has six 0 抯 or 1 抯 separated by one or more spaces. A 0 indicates that the light is off, while a 1 indicates that the light is on initially. Output For each puzzle, the output consists of a line with the string: "PUZZLE #m", where m is the index of the puzzle in the input file. Following that line, is a puzzle-like display (in the same format as the input) . In this case, 1's indicate buttons that must be pressed to solve the puzzle, while 0 抯 indicate buttons, which are not pressed. There should be exactly one space between each 0 or 1 in the output puzzle-like display. Sample Input 2 0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 0 0 0 0 1 1 0 1 0 1 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 0 0 Sample Output PUZZLE #1 1 0 1 0 0 1 1 0 1 0 0 0 1 0 1 1 0 0 1 0 0 1 0 0 0 PUZZLE #2 1 0 0 1 1 1 1 0 0 0 0 0 0 1 0 1 1 0 1 0 1 0 1 1 0 1 1 1 0 0 1 0 0 1 1 Football Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1403 Accepted: 686 Description Consider a single-elimination football tournament involving 2n teams, denoted 1, 2, …, 2n. In each round of the tournament, all teams still in the tournament are placed in a list in order of increasing index. Then, the first team in the list plays the second team, the third team plays the fourth team, etc. The winners of these matches advance to the next round, and the losers are eliminated. After n rounds, only one team remains undefeated; this team is declared the winner. Given a matrix P = [pij] such that pij is the probability that team i will beat team j in a match determine which team is most likely to win the tournament. Input The input test file will contain multiple test cases. Each test case will begin with a single line containing n (1 ≤ n ≤ 7). The next 2n lines each contain 2n values; here, the jth value on the ith line represents pij. The matrix P will satisfy the constraints that pij = 1.0 − pji for all i ≠ j, and pii = 0.0 for all i. The end-of-file is denoted by a single line containing the number −1. Note that each of the matrix entries in this problem is given as a floating-point value. To avoid precision problems, make sure that you use either the double data type instead of float. Output The output file should contain a single line for each test case indicating the number of the team most likely to win. To prevent floating-point precision issues, it is guaranteed that the difference in win probability for the top two teams will be at least 0.01. Sample Input 2 0.0 0.9 0.8 0.7 -1 0.1 0.0 0.6 0.5 0.2 0.4 0.0 0.4 0.3 0.5 0.6 0.0 Sample Output 2 Hint In the test case above, teams 1 and 2 and teams 3 and 4 play against each other in the first round; the winners of each match then play to determine the winner of the tournament. The probability that team 2 wins the tournament in this case is: P(2 wins) = P(2 beats 1)P(3 beats 4)P(2 beats 3) + P(2 beats 1)P(4 beats 3)P(2 beats 4) = p21p34p23 + p21p43p24 = 0.9 · 0.6 · 0.4 + 0.9 · 0.4 · 0.5 = 0.396. The next most likely team to win is team 3, with a 0.372 probability of winning the tournament. Source Stanford Local 2006 Coin Toss Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 2030 Accepted: 558 Description In a popular carnival game, a coin is tossed onto a table with an area that is covered with square tiles in a grid. The prizes are determined by the number of tiles covered by the coin when it comes to rest: the more tiles it covers, the better the prize. In the following diagram, the results from five coin tosses are shown: In this example: coin 1 covers 1 tile coin 2 covers 2 tiles coin 3 covers 3 tiles coin 4 covers 4 tiles coin 5 covers 2 tiles Notice that it is acceptable for a coin to land on the boundary of the playing area (coin 5). In order for a coin to cover a tile, the coin must cover up a positive area of the tile. In other words, it is not enough to simply touch the boundary of the tile. The center of the coin may be at any point of the playing area with uniform probability. You may assume that (1) the coin always comes to a rest lying flat, and (2) the player is good enough to guarantee that the center of the coin will always come to rest on the playing area (or the boundary). The probability of a coin covering a certain number of tiles depends on the tile and coin sizes, as well as the number of rows and columns of tiles in the playing area. In this problem, you will be required to write a program which computes the probabilities of a coin covering a certain number of tiles. Input The first line of input is an integer specifying the number of cases to follow. For each case, you will be given 4 integers m, n, t, and c on a single line, separated by spaces. The playing area consists of m rows and n columns of tiles, each having side length t. The diameter of the coin used is c. You may assume that 1 <= m, n <= 5000, and 1 <= c < t <= 1000. Output For each case, print the case number on its own line. This is followed by the probability of a coin covering 1 tile, 2 tiles, 3 tiles, and 4 tiles each on its own line. The probability should be expressed as a percentage rounded to 4 decimal places. Use the format as specified in the sample output. You should use double-precision floating-point numbers to perform the calculations. "Negative zeros" should be printed without the negative sign. Separate the output of consecutive cases by a blank line. Sample Input 3 5 5 10 3 7 4 25 20 10 10 10 4 Sample Output Case 1: Probability Probability Probability Probability of of of of covering covering covering covering 1 2 3 4 tile tiles tiles tiles = = = = 57.7600% 36.4800% 1.2361% 4.5239% Case 2: Probability Probability Probability Probability of of of of covering covering covering covering 1 2 3 4 tile tiles tiles tiles = = = = 12.5714% 46.2857% 8.8293% 32.3135% Case 3: Probability Probability Probability Probability of of of of covering covering covering covering 1 2 3 4 tile tiles tiles tiles = = = = 40.9600% 46.0800% 2.7812% 10.1788% Source Rocky Mountain 2007 Astronomy Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 2941 Accepted: 610 Description There are n planets in the planetary system of star X. They orbit star X in circular orbits located in the same plane. Their tangent velocities are constant. Directions of orbiting of all planets are the same. Sometimes the event happens in this planetary system which is called planet parade. It is the moment when all planets and star X are located on the same straight line. Your task is to find the length of the time interval between two consecutive planet parades. Input The first line of the input file contains n — the number of planets (2 ≤ n ≤ 1 000). Second line contains n integer numbers ti — the orbiting periods of planets (1 ≤ ti ≤ 10 000). Not all of ti are the same. Output Output the answer as a common irreducible fraction, separate numerator and denominator by a space. Sample Input 3 6 2 3 Sample Output 3 1 Hint Source Northeastern Europe 2005, Northern Subregion Dropping tests Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 2950 Accepted: 942 Description In a certain course, you take n tests. If you get ai out of bi questions correct on test i, your cumulative average is defined to be . Given your test scores and a positive integer k, determine how high you can make your cumulative average if you are allowed to drop any k of your test scores. Suppose you take 3 tests with scores of 5/5, 0/1, and 2/6. Without dropping any tests, your cumulative average is . However, if you drop the third test, your cumulative average becomes . Input The input test file will contain multiple test cases, each containing exactly three lines. The first line contains two integers, 1 ≤ n ≤ 1000 and 0 ≤ k < n. The second line contains n integers indicating ai for all i. The third line contains n positive integers indicating bi for all i. It is guaranteed that 0 ≤ ai ≤ bi ≤ 1, 000, 000, 000. The end-of-file is marked by a test case with n = k = 0 and should not be processed. Output For each test case, write a single line with the highest cumulative average possible after dropping k of the given test scores. The average should be rounded to the nearest integer. Sample Input 3 5 5 4 1 5 1 0 1 2 2 6 2 6 7 9 7 9 0 0 Sample Output 83 100 Hint To avoid ambiguities due to rounding errors, the judge tests have been constructed so that all answers are at least 0.001 away from a decision boundary (i.e., you can assume that the average is never 83.4997). Source Stanford Local 2005 Cellular Automaton Time Limit: 12000MS Memory Limit: 65536K Total Submissions: 1783 Accepted: 702 Case Time Limit: 2000MS Description A cellular automaton is a collection of cells on a grid of specified shape that evolves through a number of discrete time steps according to a set of rules that describe the new state of a cell based on the states of neighboring cells. The order of the cellular automaton is the number of cells it contains. Cells of the automaton of order n are numbered from 1 to n. The order of the cell is the number of different values it may contain. Usually, values of a cell of order m are considered to be integer numbers from 0 to m − 1. One of the most fundamental properties of a cellular automaton is the type of grid on which it is computed. In this problem we examine the special kind of cellular automaton — circular cellular automaton of order n with cells of order m. We will denote such kind of cellular automaton as n,m-automaton. A distance between cells i and j in n,m-automaton is defined as min(|i − j|, n − |i − j|). A d-environment of a cell is the set of cells at a distance not greater than d. On each d-step values of all cells are simultaneously replaced by new values. The new value of cell i after d-step is computed as a sum of values of cells belonging to the d-enviroment of the cell i modulo m. The following picture shows 1-step of the 5,3-automaton. The problem is to calculate the state of the n,m-automaton after k d-steps. Input The first line of the input file contains four integer numbers n, m, d, and k (1 ≤ n ≤ 500, 1 ≤ m ≤ 1 000 000, 0 ≤ d < n ⁄2 , 1 ≤ k ≤ 10 000 000). The second line contains n integer numbers from 0 to m − 1 — initial values of the automaton’s cells. Output Output the values of the n,m-automaton’s cells after k d-steps. Sample Input sample input #1 5 3 1 1 1 2 2 1 2 sample input #2 5 3 1 10 1 2 2 1 2 Sample Output sample output #1 2 2 2 2 1 sample output #2 2 0 0 2 2 Source Northeastern Europe 2006 Kaka's Matrix Travels Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 3828 Accepted: 1491 Description On an N × N chessboard with a non-negative number in each grid, Kaka starts his matrix travels with SUM = 0. For each travel, Kaka moves one rook from the left-upper grid to the right-bottom one, taking care that the rook moves only to the right or down. Kaka adds the number to SUM in each grid the rook visited, and replaces it with zero. It is not difficult to know the maximum SUM Kaka can obtain for his first travel. Now Kaka is wondering what is the maximum SUM he can obtain after his Kth travel. Note the SUM is accumulative during the K travels. Input The first line contains two integers N and K (1 ≤ N ≤ 50, 0 ≤ K ≤ 10) described above. The following N lines represents the matrix. You can assume the numbers in the matrix are no more than 1000. Output The maximum SUM Kaka can obtain after his Kth travel. Sample Input 3 1 0 1 2 2 3 2 1 4 2 Sample Output 15 Source POJ Monthly--2007.10.06, Huang, Jinsong Fibonacci Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 4267 Accepted: 2965 Description In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … An alternative formula for the Fibonacci sequence is . Given an integer n, your goal is to compute the last 4 digits of Fn. Input The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1. Output For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000). Sample Input 0 9 999999999 1000000000 -1 Sample Output 0 34 626 6875 Hint As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by . Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix: . Source Stanford Local 2006 Texas Trip Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 2542 Accepted: 673 Description After a day trip with his friend Dick, Harry noticed a strange pattern of tiny holes in the door of his SUV. The local American Tire store sells fiberglass patching material only in square sheets. What is the smallest patch that Harry needs to fix his door? Assume that the holes are points on the integer lattice in the plane. Your job is to find the area of the smallest square that will cover all the holes. Input The first line of input contains a single integer T expressed in decimal with no leading zeroes, denoting the number of test cases to follow. The subsequent lines of input describe the test cases. Each test case begins with a single line, containing a single integer n expressed in decimal with no leading zeroes, the number of points to follow; each of the following n lines contains two integers x and y, both expressed in decimal with no leading zeroes, giving the coordinates of one of your points. You are guaranteed that T ≤ 30 and that no data set contains more than 30 points. All points in each data set will be no more than 500 units away from (0,0). Output Print, on a single line with two decimal places of precision, the area of the smallest square containing all of your points. Sample Input 2 4 -1 -1 1 -1 1 1 -1 1 4 10 1 10 -1 -10 1 -10 -1 Sample Output 4.00 242.00 Source Waterloo Local Contest, 2007.7.14 Matrix Multiplication Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 12437 Accepted: 2554 Description You are given three n × n matrices A, B and C. Does the equation A × B = C hold true? Input The first line of input contains a positive integer n (n ≤ 500) followed by the the three matrices A, B and C respectively. Each matrix's description is a block of n × n integers. It guarantees that the elements of A and B are less than 100 in absolute value and elements of C are less than 10,000,000 in absolute value. Output Output "YES" if the equation holds true, otherwise "NO". Sample Input 2 1 0 2 3 5 1 0 8 5 1 10 26 Sample Output YES Hint Multiple inputs will be tested. So O(n3) algorithm will get TLE. Source POJ Monthly--2007.08.05, qzc Jersey Politics Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 3348 Accepted: 789 Special Judge Description In the newest census of Jersey Cows and Holstein Cows, Wisconsin cows have earned three stalls in the Barn of Representatives. The Jersey Cows currently control the state's redistricting committee. They want to partition the state into three equally sized voting districts such that the Jersey Cows are guaranteed to win elections in at least two of the districts. Wisconsin has 3*K (1 <= K <= 60) cities of 1,000 cows, numbered 1..3*K, each with a known number (range: 0..1,000) of Jersey Cows. Find a way to partition the state into three districts, each with K cities, such that the Jersey Cows have the majority percentage in at least two of districts. All supplied input datasets are solvable. Input * Line 1: A single integer, K * Lines 2..3*K+1: One integer per line, the number of cows in each city that are Jersey Cows. Line i+1 contains city i's cow census. Output * Lines 1..K: K lines that are the city numbers in district one, one per line * Lines K+1..2K: K lines that are the city numbers in district two, one per line * Lines 2K+1..3K: K lines that are the city numbers in district three, one per line Sample Input 2 510 500 500 670 400 310 Sample Output 1 2 3 6 5 4 Hint Other solutions might be possible. Note that "2 3" would NOT be a district won by the Jerseys, as they would be exactly half of the cows. Source USACO 2005 February Gold Bee Breeding Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 1321 Accepted: 545 Description Professor B. Heif is conducting experiments with a species of South American bees that he found during an expedition to the Brazilian rain forest. The honey produced by these bees is of superior quality compared to the honey from European and North American honey bees. Unfortunately, the bees do not breed well in captivity. Professor Heif thinks the reason is that the placement of the different maggots (for workers, queens, etc.) within the honeycomb depends on environmental conditions, which are different in his laboratory and the rain forest. As a first step to validate his theory, Professor Heif wants to quantify the difference in maggot placement. For this he measures the distance between the cells of the comb into which the maggots are placed. To this end, the professor has labeled the cells by marking an arbitrary cell as number 1, and then labeling the remaining cells in a clockwise fashion, as shown in the following figure. __ __/ __/ / __ \__/ \__/ \__/ __ \__/ __ \__/ \__/53\__/ \__ \__/ \__/52\__/54\__/ \__ \__/ \ \__/ / \__/51\__/31\__/55\__/ \__/ \__/50\__/30\__/32\__/56\__/ \ \__/49\__/29\__/15\__/33\__/57\__/ / \__/28\__/14\__/16\__/34\__/ \ \__/48\__/13\__/ 5\__/17\__/58\__/ /..\__/27\__/ 4\__/ 6\__/35\__/ \ \__/47\__/12\__/ 1\__/18\__/59\__/ /..\__/26\__/ 3\__/ 7\__/36\__/ \ \__/46\__/11\__/ 2\__/19\__/60\__/ /..\__/25\__/10\__/ 8\__/37\__/ \ \__/45\__/24\__/ 9\__/20\__/61\__/ /..\__/44\__/23\__/21\__/38\__/ \ \__/70\__/43\__/22\__/39\__/62\__/ / \__/69\__/42\__/40\__/63\__/ \__/ / \__/68\__/41\__/64\__/ \__/ \__/ \__/67\__/65\__/ \__/ \__/ \__/66\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \ \ \__/ \__/ \__/ For example, two maggots in cells 19 and 30 are 5 cells apart. One of the shortest paths connecting the two cells is via the cells 19 - 7 - 6 - 5 - 15 - 30, so you must move five times to adjacent cells to get from 19 to 30. Professor Heif needs your help to write a program that computes the distance, defined as the number of cells in a shortest path, between any pair of cells. Input The input consists of several lines, each containing two integers a and b (a,b <= 10000), denoting numbers of cells. The integers are always positive, except in the last line where a=b=0 holds. This last line terminates the input and should not be processed. Output For each pair of numbers (a,b) in the input file, output the distance between the cells labeled a and b. The distance is the minimum number of moves to get from a to b. Sample Input 19 30 0 0 Sample Output The distance between cells 19 and 30 is 5. Source World Finals 1999 Rinse Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 395 Accepted: 128 Description Granny's reunion was a smashing success. Next she is expecting a visit from Eliot Ness and in anticipation of his visit would like to remove as much whiskey from the cream can as possible prior to his visit. Granny can upend the cream can, thus pouring its contents on the ground. But due to surface tension and the shape of the can a small amount of the content remains, even after the can is upended. Granny has a barrel full of rain water that she can use to rinse the can several times. Each rinse involves pouring some amount of water (perhaps none) into the cream can, mixing it thoroughly with the existing contents, and pouring it out. After each rinse an amount of liquid remains, some fraction of which is whiskey and the rest water. Mr. Ness' visit is imminent, affording Granny the time to do at most k rinses. You are to determine a rinsing strategy that Granny should employ to minimize the amount of residual whiskey in the cream can after the last rinse. Input Standard input consists of several test cases. Each test case is represented by a line with five numbers: 0 < k ≤ 100 -- an integer denoting the maximum number of rinses Vb > 0 -- a real number denoting the volume of available rain water in the barrel Vw > 0 -- a real number denoting the volume of whiskey in the cream can Vr > 0 -- a real number denoting the volume of liquid that cannot be poured out by upending the can (further liquid might be eliminated by evaporation, but there is insufficient time before Ness' visit for any evaporation to take place) Vc > Vw , Vr -- a real number denoting the maximum capacity of the cream can. A line containing 0 follows the last case. Output For each test case, output r, the number of rinses that Granny should perform. On the same line, output r real numbers, rounded to two decimal places, giving the amount of rain water to be used for each rinse, in order. Note that the total amount of water used in all rinses must not exceed Vb. The total amount of liquid in the cream can cannot exceed Vc at any time. Assume that whiskey and water mix perfectly and that their volumes are additive; that is, x units of whiskey and y units of water combine to form x+y units of liquid. Sample Input 2 15.0 25.0 1.0 50.0 0 Sample Output 2 0.00 15.00 Source Waterloo Local Contest, 2006.9.30 How many 0's? Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1780 Accepted: 846 Description A Benedict monk No.16 writes down the decimal representations of all natural numbers between and including m and n, m ≤ n. How many 0's will he write down? Input Input consists of a sequence of lines. Each line contains two unsigned 32-bit integers m and n, m ≤ n. The last line of input has the value of m negative and this line should not be processed. Output For each line of input print one line of output with one integer number giving the number of 0's written down by the monk. Sample Input 10 11 100 200 0 500 1234567890 2345678901 0 4294967295 -1 -1 Sample Output 1 22 92 987654304 3825876150 Source Waterloo Local Contest, 2006.5.27 Trees Made to Order Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 4977 Accepted: 2839 Description We can number binary trees using the following scheme: The empty tree is numbered 0. The single-node tree is numbered 1. All binary trees having m nodes have numbers less than all those having m+1 nodes. Any binary tree having m nodes with left and right subtrees L and R is numbered n such that all trees having m nodes numbered > n have either Left subtrees numbered higher than L, or A left subtree = L and a right subtree numbered higher than R. The first 10 binary trees and tree number 20 in this sequence are shown below: Your job for this problem is to output a binary tree when given its order number. Input Input consists of multiple problem instances. Each instance consists of a single integer n, where 1 <= n <= 500,000,000. A value of n = 0 terminates input. (Note that this means you will never have to output the empty tree.) Output For each problem instance, you should output one line containing the tree corresponding to the order number for that instance. To print out the tree, use the following scheme: A tree with no children should be output as X. A tree with left and right subtrees L and R should be output as (L')X(R'), where L' and R' are the representations of L and R. If L is empty, just output X(R'). If R is empty, just output (L')X. Sample Input 1 20 31117532 0 Sample Output X ((X)X(X))X (X(X(((X(X))X(X))X(X))))X(((X((X)X((X)X)))X)X) Source East Central North America 2001 November Rain Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 1616 Accepted: 351 Case Time Limit: 2000MS Description Contemporary buildings can have very complicated roofs. If we take a vertical section of such a roof it results in a number of sloping segments. When it is raining the drops are falling down on the roof straight from the sky above. Some segments are completely exposed to the rain but there may be some segments partially or even completely shielded by other segments. All the water falling onto a segment as a stream straight down from the lower end of the segment on the ground or possibly onto some other segment. In particular, if a stream of water is falling on an end of a segment then we consider it to be collected by this segment. For the purpose of designing a piping system it is desired to compute how much water is down from each segment of the roof. To be prepared for a heavy November rain you should count one liter of rain water falling on a meter of the horizontal plane during one second. Task Write a program that: reads the description of a roof, computes the amount of water down in one second from each segment of the roof, writes the results. Input The first line of the input contains one integer n (1 <= n < = 40000) being the number of segments of the roof. Each of the next n lines describes one segment of the roof and contains four integers x1, y1, x2, y2 (0 <= x1, y1, x2, y2 < = 1000000, x1 < x2, y1<>y2) separated by single spaces. Integers x1, y1 are respectively the horizontal position and the height of the left end of the segment. Integers x2, y2 are respectively the horizontal position and the height of the right end of the segment. The segments don't have common points and there are no horizontal segments. You can also assume that there are at most 25 segments placed above any point on the ground level. Output The output consists of n lines. The i-th line should contain the amount of water (in liters) down from the i-th segment of the roof in one second. Sample Input 6 13 7 15 6 3 8 7 7 1 7 5 6 5 5 9 3 6 3 8 2 9 6 12 8 Sample Output 2 4 2 11 0 3 Source Central Europe 2003 Picture Time Limit: 2000MS Memory Limit: 10000K Total Submissions: 6277 Accepted: 3248 Description A number of rectangular posters, photographs and other pictures of the same shape are pasted on a wall. Their sides are all vertical or horizontal. Each rectangle can be partially or totally covered by the others. The length of the boundary of the union of all rectangles is called the perimeter. Write a program to calculate the perimeter. An example with 7 rectangles is shown in Figure 1. The corresponding boundary is the whole set of line segments drawn in Figure 2. The vertices of all rectangles have integer coordinates. Input Your program is to read from standard input. The first line contains the number of rectangles pasted on the wall. In each of the subsequent lines, one can find the integer coordinates of the lower left vertex and the upper right vertex of each rectangle. The values of those coordinates are given as ordered pairs consisting of an x-coordinate followed by a y-coordinate. 0 <= number of rectangles < 5000 All coordinates are in the range [-10000,10000] and any existing rectangle has a positive area. Output Your program is to write to standard output. The output must contain a single line with a non-negative integer which corresponds to the perimeter for the input rectangles. Sample Input 7 -15 0 5 10 -5 8 20 25 15 -4 24 14 0 -6 16 4 2 15 10 22 30 10 36 20 34 0 40 16 Sample Output 228 Source IOI 1998 Atlantis Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 8312 Accepted: 3277 Description There are several ancient Greek texts that contain descriptions of the fabled island Atlantis. Some of these texts even include maps of parts of the island. But unfortunately, these maps describe different regions of Atlantis. Your friend Bill has to know the total area for which maps exist. You (unwisely) volunteered to write a program that calculates this quantity. Input The input consists of several test cases. Each test case starts with a line containing a single integer n (1 <= n <= 100) of available maps. The n following lines describe one map each. Each of these lines contains four numbers x1;y1;x2;y2 (0 <= x1 < x2 <= 100000;0 <= y1 < y2 <= 100000), not necessarily integers. The values (x1; y1) and (x2;y2) are the coordinates of the top-left resp. bottom-right corner of the mapped area. The input file is terminated by a line containing a single 0. Don't process it. Output For each test case, your program should output one section. The first line of each section must be "Test case #k", where k is the number of the test case (starting with 1). The second one must be "Total explored area: a", where a is the total explored area (i.e. the area of the union of all rectangles in this test case), printed exact to two digits to the right of the decimal point. Output a blank line after each test case. Sample Input 2 10 10 20 20 15 15 25 25.5 0 Sample Output Test case #1 Total explored area: 180.00 Source Mid-Central European Regional Contest 2000 City Horizon Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 10810 Accepted: 2862 Description Farmer John has taken his cows on a trip to the city! As the sun sets, the cows gaze at the city horizon and observe the beautiful silhouettes formed by the rectangular buildings. The entire horizon is represented by a number line with N (1 ≤ N ≤ 40,000) buildings. Building i's silhouette has a base that spans locations Ai through Bi along the horizon (1 ≤ Ai < Bi ≤ 1,000,000,000) and has height Hi (1 ≤ Hi ≤ 1,000,000,000). Determine the area, in square units, of the aggregate silhouette formed by all N buildings. Input Line 1: A single integer: N Lines 2..N+1: Input line i+1 describes building i with three space-separated integers: Ai, Bi, and Hi Output Line 1: The total area, in square units, of the silhouettes formed by all N buildings Sample Input 4 2 9 6 4 5 1 10 4 8 2 6 3 Sample Output 16 Hint The first building overlaps with the fourth building for an area of 1 square unit, so the total area is just 3*1 + 1*4 + 2*2 + 2*3 - 1 = 16. Source USACO 2007 Open Silver Amphiphilic Carbon Molecules Time Limit: 20000MS Memory Limit: 65536K Total Submissions: 926 Accepted: 293 Description Shanghai Hypercomputers, the world's largest computer chip manufacturer, has invented a new class of nanoparticles called Amphiphilic Carbon Molecules (ACMs). ACMs are semiconductors. It means that they can be either conductors or insulators of electrons, and thus possess a property that is very important for the computer chip industry. They are also amphiphilic molecules, which means parts of them are hydrophilic while other parts of them are hydrophobic. Hydrophilic ACMs are soluble in polar solvents (for example, water) but are insoluble in nonpolar solvents (for example, acetone). Hydrophobic ACMs, on the contrary, are soluble in acetone but insoluble in water. Semiconductor ACMs dissolved in either water or acetone can be used in the computer chip manufacturing process. As a materials engineer at Shanghai Hypercomputers, your job is to prepare ACM solutions from ACM particles. You go to your factory everyday at 8 am and find a batch of ACM particles on your workbench. You prepare the ACM solutions by dripping some water, as well as some acetone, into those particles and watch the ACMs dissolve in the solvents. You always want to prepare unmixed solutions, so you first separate the ACM particles by placing an Insulating Carbon Partition Card (ICPC) perpendicular to your workbench. The ICPC is long enough to completely separate the particles. You then drip water on one side of the ICPC and acetone on the other side. The ICPC helps you obtain hydrophilic ACMs dissolved in water on one side and hydrophobic ACMs dissolved in acetone on the other side. If you happen to put the ICPC on top of some ACM particles, those ACMs will be right at the border between the water solution and the acetone solution, and they will be dissolved. Fig.1 shows your working situation. Fig. 1 Your daily job is very easy and boring, so your supervisor makes it a little bit more challenging by asking you to dissolve as much ACMs into solution as possible. You know you have to be very careful about where to put the ICPC since hydrophilic ACMs on the acetone side, or hydrophobic ACMs on the water side, will not dissolve. As an experienced engineer, you also know that sometimes it can be very difficult to find the best position for the ICPC, so you decide to write a program to help you. You have asked your supervisor to buy a special digital camera and have it installed above your workbench, so that your program can obtain the exact positions and species (hydrophilic or hydrophobic) of each ACM particle in a 2D pictures taken by the camera. The ICPC you put on your workbench will appear as a line in the 2D pictures. Fig. 2 Input There will be no more than 10 test cases. Each case starts with a line containing an integer N, which is the number of ACM particles in the test case. N lines then follow. Each line contains three integers x, y, r, where (x, y) is the position of the ACM particle in the 2D picture and r can be 0 or 1, standing for the hydrophilic or hydrophobic type ACM respectively. The absolute value of x, y will be no larger than 10000. You may assume that N is no more than 1000. N = 0 signifies the end of the input and need not be processed. Fig.2 shows the positions of ACM particles and the best ICPC position for the last test case in the sample input. Output For each test case, output a line containing a single integer, which is the maximum number of dissolved ACM particles. Sample Input 3 0 0 0 0 1 0 2 2 1 4 0 0 0 0 4 0 4 0 0 1 2 1 7 -1 0 0 1 2 1 2 3 0 2 1 1 0 3 1 1 4 0 -1 2 0 0 Sample Output 3 3 6 Source Shanghai 2004 Subway planning Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 799 Accepted: 204 Description The government in a foreign country is looking into the possibility of establishing a subway system in its capital. Because of practical reasons, they would like each subway line to start at the central station and then go in a straight line in some angle as far as necessary. You have been hired to investigate whether such an approach is feasible. Given the coordinates of important places in the city as well as the maximum distance these places can be from a subway station (possibly the central station, which is already built), your job is to calculate the minimum number of subway lines needed. You may assume that any number of subway stations can be built along a subway line. Figure 1: The figure above corresponds to the first data set in the example input. Input The first line in the input file contains an integer N, the number of data sets to follow. Each set starts with two integers, n and d (1 ≤ n ≤ 500, 0 ≤ d < 150). n is the number of important places in the city that must have a subway station nearby, and d is the maximum distance allowed between an important place and a subway station. Then comes n lines, each line containing two integers x and y (-100 ≤ x, y ≤ 100), the coordinates of an important place in the capital. The central station will always have coordinates 0, 0. All pairs of coordinates within a data set will be distinct (and none will be 0, 0). Output For each data set, output a single integer on a line by itself: the minimum number of subway lines needed to make sure all important places in the city is at a distance of at most d from a subway station. Sample Input 2 7 1 -1 -4 -3 1 -3 -1 2 3 2 4 2 -2 6 -2 4 0 0 4 -12 18 0 27 -34 51 Sample Output 4 2 Source Svenskt Mästerskap i Programmering/Norgesmesterskapet 2003 How I Mathematician Wonder What You Are! Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 1543 Accepted: 834 Description After counting so many stars in the sky in his childhood, Isaac, now an astronomer and a mathematician uses a big astronomical telescope and lets his image processing program count stars. The hardest part of the program is to judge if shining object in the sky is really a star. As a mathematician, the only way he knows is to apply a mathematical definition of stars. The mathematical definition of a star shape is as follows: A planar shape F is star-shaped if and only if there is a point C ∈ F such that, for any point P ∈ F, the line segment CP is contained in F. Such a point C is called a center of F. To get accustomed to the definition let’s see some examples below. The first two are what you would normally call stars. According to the above definition, however, all shapes in the first row are star-shaped. The two in the second row are not. For each star shape, a center is indicated with a dot. Note that a star shape in general has infinitely many centers. Fore Example, for the third quadrangular shape, all points in it are centers. Your job is to write a program that tells whether a given polygonal shape is star-shaped or not. Input The input is a sequence of datasets followed by a line containing a single zero. Each dataset specifies a polygon, and is formatted as follows. n x1 x2 y1 y2 … xn yn The first line is the number of vertices, n, which satisfies 4 ≤ n ≤ 50. Subsequent n lines are the x- and y-coordinates of the n vertices. They are integers and satisfy 0 ≤ xi ≤ 10000 and 0 ≤ yi ≤ 10000 (i = 1, …, n). Line segments (xi, yi)–(xi + 1, yi + 1) (i = 1, …, n − 1) and the line segment (xn, yn)–(x1, y1) form the border of the polygon in the counterclockwise order. That is, these line segments see the inside of the polygon in the left of their directions. You may assume that the polygon is simple, that is, its border never crosses or touches itself. You may assume assume that no three edges of the polygon meet at a single point even when they are infinitely extended. Output For each dataset, output “1” if the polygon is star-shaped and “0” otherwise. Each number must be in a separate line and the line should not contain any other characters. Sample Input 6 66 13 96 61 76 98 13 94 4 0 45 68 8 27 21 55 14 93 12 56 95 15 48 38 46 51 65 64 31 0 Sample Output 1 0 Source Japan 2006 Rotating Scoreboard Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 2136 Accepted: 789 Description This year, ACM/ICPC World finals will be held in a hall in form of a simple polygon. The coaches and spectators are seated along the edges of the polygon. We want to place a rotating scoreboard somewhere in the hall such that a spectator sitting anywhere on the boundary of the hall can view the scoreboard (i.e., his line of sight is not blocked by a wall). Note that if the line of sight of a spectator is tangent to the polygon boundary (either in a vertex or in an edge), he can still view the scoreboard. You may view spectator's seats as points along the boundary of the simple polygon, and consider the scoreboard as a point as well. Your program is given the corners of the hall (the vertices of the polygon), and must check if there is a location for the scoreboard (a point inside the polygon) such that the scoreboard can be viewed from any point on the edges of the polygon. Input The first number in the input line, T is the number of test cases. Each test case is specified on a single line of input in the form n x1 y1 x2 y2 ... xn yn where n (3 ≤ n ≤ 100) is the number of vertices in the polygon, and the pair of integers xi yi sequence specify the vertices of the polygon sorted in order. Output The output contains T lines, each corresponding to an input test case in that order. The output line contains either YES or NO depending on whether the scoreboard can be placed inside the hall conforming to the problem conditions. Sample Input 2 4 0 0 0 1 1 1 1 0 8 0 0 0 2 1 2 1 1 2 1 2 2 3 2 3 0 Sample Output YES NO Disks Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 1004 Accepted: 210 Description Consider N floating point numbers N representing the radii of N disks. We fix a disk in the xOy system, if we position it at a positive coordinate x (big enough), tangential to the 0x axis and above it and after that we push it to 0y until it becomes tangent to 0y or to the first disk that it meets on the way. In the configuration that results by fixing in order all the given disks, some of them can be considered as being dispensible, because, if we eliminate them, the total width of the configuration is the same, which means that there is no disk that can be moved to the left. Identify all the indispensible disks for a given configuration (in the configuration from above; the gray disks are dispensible). Input The input has the following structure: the first line contains N ( N <= 1000), the number of disks; the next N lines contain N real numbers representing the radii of the disks, in the order they are fixed in the configuration. Output The output will have the following structure: the first line will contain an integer K, representing the number of dispensable disks; each of the next K lines will contain the order number of the dispensable disks. Sample Input 7 4 0.1 0.5 3 0.5 4 1 Sample Output 3 2 3 5 Source Romania OI 2002 Treasure Hunt Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 2706 Accepted: 1092 Description Archeologists from the Antiquities and Curios Museum (ACM) have flown to Egypt to examine the great pyramid of Key-Ops. Using state-of-the-art technology they are able to determine that the lower floor of the pyramid is constructed from a series of straightline walls, which intersect to form numerous enclosed chambers. Currently, no doors exist to allow access to any chamber. This state-of-the-art technology has also pinpointed the location of the treasure room. What these dedicated (and greedy) archeologists want to do is blast doors through the walls to get to the treasure room. However, to minimize the damage to the artwork in the intervening chambers (and stay under their government grant for dynamite) they want to blast through the minimum number of doors. For structural integrity purposes, doors should only be blasted at the midpoint of the wall of the room being entered. You are to write a program which determines this minimum number of doors. An example is shown below: Input The input will consist of one case. The first line will be an integer n (0 <= n <= 30) specifying number of interior walls, followed by n lines containing integer endpoints of each wall x1 y1 x2 y2 . The 4 enclosing walls of the pyramid have fixed endpoints at (0,0); (0,100); (100,100) and (100,0) and are not included in the list of walls. The interior walls always span from one exterior wall to another exterior wall and are arranged such that no more than two walls intersect at any point. You may assume that no two given walls coincide. After the listing of the interior walls there will be one final line containing the floating point coordinates of the treasure in the treasure room (guaranteed not to lie on a wall). Output Print a single line listing the minimum number of doors which need to be created, in the format shown below. Sample Input 7 20 0 37 100 40 0 76 100 85 0 0 75 100 90 0 90 0 71 100 61 0 14 100 38 100 47 47 100 54.5 55.4 Sample Output Number of doors = 2 Source East Central North America 1999 Area of Polygons Time Limit: 3000MS Memory Limit: 30000K Total Submissions: 781 Accepted: 303 Description Yoko's math homework today was to calculate areas of polygons in the xy-plane. Vertices are all aligned to grid points (i.e. they have integer coordinates). Your job is to help Yoko, not good either at math or at computer programming, get her homework done. A polygon is given by listing the coordinates of its vertices. Your program should approximate its area by counting the number of unit squares (whose vertices are also grid points) intersecting the polygon. Precisely, a unit square "intersects the polygon" if and only if the intersection of the two has non-zero area. In the figure below, dashed horizontal and vertical lines are grid lines, and solid lines are edges of the polygon. Shaded unit squares are considered intersecting the polygon. Your program should output 55 for this polygon (as you see, the number of shaded unit squares is 55). Input The input file describes polygons one after another, followed by a terminating line that only contains a single zero. A description of a polygon begins with a line containing a single integer, m (>= 3), that gives the number of its vertices. It is followed by m lines, each containing two integers x and y, the coordinates of a vertex. The x and y are separated by a single space. The i-th of these m lines gives the coordinates of the i-th vertex (i = 1,...,m). For each i = 1,...,m-1, the i-th vertex and the (i+1)-th vertex are connected by an edge. The m-th vertex and the first vertex are also connected by an edge (i.e., the curve is closed). Edges intersect only at vertices. No three edges share a single vertex (i.e., the curve is simple). The number of polygons is no more than 100. For each polygon, the number of vertices (m) is no more than 100. All coordinates x and y satisfy -2000 <= x <= 2000 and -2000 <= y <= 2000. Output The output should consist of as many lines as the number of polygons. The k-th output line should print an integer which is the area of the k-th polygon, approximated in the way described above. No other characters, including whitespaces, should be printed. Sample Input 4 5 -3 1 0 1 7 -7 -1 3 5 5 18 5 5 10 3 -5 -5 -5 -10 -18 -10 5 0 0 20 2 11 1 21 2 2 0 0 Sample Output 55 41 41 23 Source Japan 2003,Aizu Mountains Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1280 Accepted: 314 Description Octopus and Penguin love sports, especially the climb. They step on the most top building of Changsha to view the Yuelu Mountain in weekend and are attracted by the imposing landscape. However, they can't see the whole mountain because the building is not high enough. Please help them to calculate the total length of surface for mountain they can see. Suppose Octopus and Penguin's coordinate is (0,h) and the mountain is composed by n points which satisfy: 1.All points' coordinates are equal to or larger than zero. 2. The first point is 0, it's coordinate is (w0, 0)(w0 >= 0). 3. n points are listing in ascending sort by x-axis. 4. Odd points' y-axis is larger than the former one. 5. Even points' y-axis (except for 0 point) is small than the former one. Condition 3,4 and 5 is means for three nearby points (w2k, h2k), (w2k+1, h2k+1) and (w2k+2, h2k+2)(k ∈N*,2k+2<n), satisfied w2k < w2k+1 < w2k+2, h2k+1 > h2k and h2k+2 < h2k+1. 6. The last point is (wn-1, 0). The figure below corresponding sample input one: Input There are several test cases. For each case, the first line is two integers n (0<n<=1000) and h. Then n lines follow and each line is two integers x and y(0<=x,y<=1000) describe the coordinates of mountains. n=h=0 means end of the input. Output For each case, output the surface length of mountain they can see. Sample Input 3 0 1 2 5 0 2 3 5 8 5 0 2 3 5 8 0 5 0 1 0 5 0 2 1 3 0 4 0 2 1 3 0 0 Sample Output 2.83 7.07 5.66 Source South Central China 2007 hosted by NUDT Gunman Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1046 Accepted: 400 Special Judge Description Consider a 3D scene with OXYZ coordinate system. Axis OX points to the right, axis OY points up, and axis OZ points away from you. There is a number of rectangular windows on the scene. The plane of each window is parallel to OXY , its sides are parallel to OX and OY . All windows are situated at different depths on the scene (different coordinates z > 0). A gunman with a rifle moves along OX axis (y = 0 and z = 0). He can shoot a bullet in a straight line. His goal is to shoot a single bullet through all the windows. Just touching a window edge is enough. Your task is to determine how to make such shot. Input The first line of the input file contains a single integer number n (2 <= n <= 100) — the number of windows on the scene. The following n lines describe the windows. Each line contains five integer numbers x1i, y1i, x2i, y2i, zi (0 < x1i, y1i, x2i, y2i, zi < 1000). Here (x1i, y1i, zi) are coordinates of the bottom left corner of the window, and (x2i, y2i, zi) are coordinates of the top right corner of the window (x1i < x2i, y1i < y2i). Windows are ordered by z coordinate (zi > zi-1 for 2 <= i <= n). Output Output a single word "UNSOLVABLE" if the gunman cannot reach the goal of shooting a bullet through all the windows. Otherwise, on the first line output a word "SOLUTION". On the next line output x coordinate of the point from which the gunman must fire a bullet. On the following n lines output x, y, z coordinates of the points where the bullet goes through the consecutive windows. All coordinates in the output file must be printed with six digits after decimal point. Sample Input 3 1 3 5 5 3 1 2 5 7 5 5 2 7 6 6 Sample Output SOLUTION -1.000000 2.000000 3.000000 3.000000 4.000000 5.000000 5.000000 5.000000 6.000000 6.000000 Source Northeastern Europe 2004 Geometry with a ruler Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 1366 Accepted: 283 Description Classic geometric construction is based on two instruments: ruler and compass. However, some constructions are possible using only the ruler. Specifically, let us define that if we have a set of N points, we can select two pairs of them, draw a line through each pair, and construct a new point as an intersection of these two lines. New point can then be added to the set as (N + 1)-th point, and the process repeated. Such geometric constructions are abstract notions, and attempt to verify them with physical pencil and ruler can lead to errors caused by imprecision of these instruments. So you are tasked to write a program that does exact verification. Your program must read a set of points and a sequence of constructing operations and find out whether the point with coordinates (0, 0) is one of the constructed points. Note that, similar to physical instruments, floating point calculations performed by computers are also imprecise. This should not, of course, alter verification results. Input Input file contains number of points N followed by their integer coordinates x1 y1 x2 y2 ... xN yN. Next comes number of construction operations M followed by M quads of integers ai bi ci di, where k-th quad means that a new point is constructed as an intersection of lines containing pairs of points ai, bi and ci, di. Such a point is guaranteed to exist. Constructed point is assigned a number N + k and can be used in following operations. Constraints 4 ≤ N ≤ 100, 1 ≤ M ≤ 10, −106 ≤ xi, yi ≤ 106 Output Output file must contain a single integer — number of the first operation which constructs a point (0, 0), or 0 (zero), if there is no such operation. Sample Input Sample Input 4 -1 -1 -2 2 1 1 3 2 4 Sample Input 4 -1000 -1000 1 1 3 2 4 1 2 2 1 -1 2 -2000 2000 2001 2000 1000 -1000 Sample Output Sample Output 1 1 Sample Output 2 0 Hint Bold texts appearing in the sample sections are informative and do not form part of the actual data. Source Northeastern Europe 2006, Far-Eastern Subregion Text Formalization Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 656 Accepted: 111 Description One duty Jimmy has at the ACM is to formalize the language and grammar used in texts. Part of this job is expanding contractions and certain acronyms. A contraction in English is a word or phrase formed by omitting or combining some of the sounds of a longer phrase. For example, "don't" is a contraction for "do not" and "o'clock" comes from "of the clock." An acronym is a series of letters (or word) formed from the initial letters of a name or from combining parts of a series of words. For example, "ACM" for "Association for Computing Machinery" or "radar" for "radio detecting and ranging." Your job is to take a list of contractions and acronyms, and expand all contractions and some acronyms in a text. Input Input begins with two numbers, C < 50 and A < 50, indicating respectively the number of contractions and acronyms Jimmy must expand. The next C lines list a contraction and its formal expansion. Following will be a list of A acronyms and their expansions, each on individual lines. Both contractions and acronyms will be presented in the following format: "contraction or acronym" -> "expansion" Since contractions, acronyms and expansions may contain spaces, each will be enclosed in quotation marks and be no more than 80 characters in length. Following the lists of contractions and acronyms will be a series of texts to expand. Each text will consist of lines no longer than 80 characters. No contraction or acronym will be split over multiple lines. A text will be terminated with a line consisting only of the character '#'. Output Output each text exactly as input, except for necessary expansions. All contractions must be fully expanded. Each contraction may appear as listed, entirely uppercase, or capitalized (first letter uppercase, remaining letters as listed). The expansion should follow the same rule; if a contraction is uppercased, the expansion should be uppercased as well. If more than one case applies, choose the earliest matching case in the list: "as listed," "uppercased," and "capitalized." Since acronyms are useful for understanding and identifying names, only modify the first instance of an acronym in each text. An instance of an acronym must match the case exactly ("acm" is not an instance of "ACM"). The modification consists of replacing the acronym with the expansion, followed by a space, followed by the acronym in brackets. This allows the reader to connect the acronym with the fully expanded term. The terminating line of '#' should be printed after each text. If more than one expansion or acronym match can be valid, use the one which starts earlier in the text. If several begin at the same letter, use the one appearing earliest in the input lists. Use the sample below to illustrate the process. Sample Input 3 2 "doesn't" -> "does not" "isn't" -> "is not" "can't" -> "cannot" "ACM" -> "Association for Computing Machinery" "CS" -> "Computing Science" The ACM can't solve all the problems in CS. Though large and having many resources at its disposal, the ACM doesn't use magic. Magic isn't part of science, and hence not part of CS. Thank you for your suggestions. Signed, ACM # The ACM doesn't like magic. It's not that the ACM won't use it, it's just that the ACM doesn't understand magic. # Sample Output The Association for Computing Machinery (ACM) cannot solve all the problems in Computing Science (CS). Though large and having many resources at its disposal, the ACM does not use magic. Magic is not part of science, and hence not part of CS. Thank you for your suggestions. Signed, ACM # The Association for Computing Machinery (ACM) does not like magic. It's not that the ACM won't use it, it's just that the ACM does not understand magic. # Hint Clarifications Problem D: Text Formalization No left hand side in the rules for contractions and acronyms is a prefix of any other left hand side in the rules. The rules are not applied recursively, i.e. the result of a substitution is not a subject to further processing. Source Alberta Collegiate Programming Contest 2003.10.18 Dynamic Declaration Language (DDL) Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 679 Accepted: 196 Description DDL is a very simple programming language in which variables are dynamically declared at run time. All variables in DDL are of the signed integer type within the range -9999...9999. There are up to five types of statements in a DDL program (each statement is in a separate program line, and the first statement is in line 1): 1. Dcl < id > Dcl is a keyword specifying a declaration statement. id is a single (case-sensitive) letter designating a DDL variable. For example Dcl x when executed correctly, allocates memory for variable x, and sets its value to zero. 2. < id > = < ic > This is an assignment statement, where id is a DDL variable, and ic is a literal integer constant in the range (0...9999). For example x = 2000 when executed correctly, changes value of x to 2000. Note that there may be one or more number of blank characters around =, but there is no tab characters. 3. Goto < label >, or Goto < id > < label > Goto is a keyword specifying an unconditional or conditional goto statement. label is a program line's number. For example Goto 5 transfers the program execution flow to line 5 of the program, and Goto x 5 when executed correctly, trasfers the flow to line 5 iff x>0, and to the next line otherwise. The label is guaranteed to be in the range of program line numbers. 4.Inc < id >, or Dec < id > Inc and Dec are keywords specifying increment and decrement statements respectively. For example Inc x (Dec y) when executed correctly adds (substracts) 1 to (from) the value of x (y). 5. End End is a keyword specifying the end statement, whose execution stops the program. Not that the keywords of the DDL language are case-insensitive. Error conditions: When one of the following erroneous statements encounters during the program execution, an error message appears in a separate line of the output. Each error message is of the form < label > < space > < error code >. label is the line number for the erroneous statement, space is one blank character, and error code is a positive integer specified below. 1. Dcl x is erroneous if x has not been referenced (used in assignment, goto, increment or decrement) since the last time a Dcl x (declaring the same variable) statement has been executed, unless this is the first Dcl x statement being executed. In this erroneous condition, an error message indicating a repeated declaration is generated as < label > 1, where label is the program line number for the erroneous statement. Then the program flow transfers to the statement in the next program line, and any prior correctly executed declaration for x is valid. 2.Any other statement where a variable such as x is referenced (used in assignment, goto, increment or decrement) is erroneous if no Dcl x has been previously correctly executed. In this case, an error message indicating an undeclared reference is generated as < label > 2 and the program execution continues from the next line. Input First line of the input file contains a single integer N indicating the number of DDL programs to follow (1 <= N <= 20). The first line of each test case contains a single integer indicating number of statements in that program which is in the range (1...100). There are no blank lines between test cases. Statements of each DDL program come one after the other in separate lines without any blank lines in between. Statements are not explicitly labeled, but they are implicitly labeled by the number of their line beginning from 1 for the first statement in each program. There is no syntax error in programs and they are guaranteed to terminate, and no overflow or underflow errors will occur during execution. In each line of the program, tokens (e.g. GOTO, =, etc.) are separated by at least one blank character. Also there may be some blank characters in the beginning or at the end of each line. Output For each input DDL program, your output should start with the program number in the first line, followed by the error messages generated by the program in the order they are generated, each error message in one line. There should be no blank lines between error messages. Sample Input 2 4 DCL X INC X DCL X END 9 DCL X INC X GOTO X 5 DCL Y Y = 100 DCL X DCL X Y = 50 END Sample Output 1 2 5 2 7 1 8 2 Source Tehran 2000 Peter's Calculator Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 192 Accepted: 51 Description Unfortunately, Peter's Calculator broke down last week. Now Peter is left with his computer, which has no calculator application, and paper and pencil, which is too tiresome for an engineer. As one of Peter's friends, you are asked to write him a calculator application. After talking to him, you figure out the following: Peter does only integer arithmetic. The operations he needs are addition, subtraction and multiplication. He would like to use an arbitrary number of variables whose names are not longer than 50 characters. His main way of doing calculations are to type in a few formulas and to assign them to variables. Some formulas are complicated expressions, which can refer to yet undefined variables, while other formulas consist of a single number. Then Peter asks for the value of some variables, i.e. he evaluates the formulas. Peters wants to redefine some variables and then to reevaluate formulas that depend on these variables. The input strictly adheres to the following syntax (given in EBNF): file = line { line } . line = [ assignment | print | reset ] . assignment = var ":=" expression. print = "PRINT" var. reset = "RESET". expression = term { addop term }. term = factor { mulop factor }. factor = "(" expression ")" | var | number. addop = "+" | "-". mulop = "*". In the Extended Backus-Naur Formalism (EBNF), A = B C declares that the grammatical construct A consists of a B followed by a C. A = B | C means that A consists of a B or, alternatively, of a C. A = [ B ] defines construct A to be either a B or nothing and A = { B } tells you that A consists of the concatenation of any number of Bs (including none). The production var stands for the name of a variable, which starts with a letter followed by up to 49 letters or digits. Letters may be uppercase or lowercase. The production number stands for a integer number. The precise syntax for these productions are given below. The case of letters is important for both variables and statements. var = letter { letter | digit }. number = [ "-" ] digit { digit }. letter = "A" | "B" | ... | "Z" | "a" | "b" | ... | "z". digit = "0" | "1" | ... | "8" | "9". Between the parts of a grammatical construct but not within the names of variables or integer numbers, any number of spaces may appear. stands for the end of the input file and stands for the new-line character. All lines in the input file are shorter than 200 characters. The value of a variable is said to be undefined: if it has not yet been defined or it refers to a variable, which has not yet been defined; if the definition of the variable contains a cycle. Your are to write a program that implements Peter's calculator. It should store all variable definitions and for each "PRINT" statement evaluate the specified variable based on the latest variable definitions. If your program encounters a "RESET" statement, it should delete all stored variables so that all variables become undefined. Input The input contains calculations adhering to the syntax given above. Each line contains either an assignment to a variable, a "PRINT" statement, a "RESET" statement or nothing. Output For each "PRINT" statement found in the input, your program should output a line containing the numerical value of the specified variable or the word "UNDEF" if the variable is undefined. Sample Input a := b + c b := 3 c := 5 PRINT d PRINT a b := 8 PRINT a RESET PRINT a Sample Output UNDEF 8 13 UNDEF Source Southwestern European Regional Contest 1995 Follow My Logic Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 1447 Accepted: 424 Description For this problem you will determine the output of a logic circuit composed of one or more inputs, zero or more dual-input AND/OR gates, and one output. The input circuits are drawn with standard ASCII characters. Circuit paths are represented using horizontal and vertical lines, and junctions. Horizontal lines are represented with dash characters (ASCII code 45 decimal), vertical lines with vertical bar characters (ASCII code 124 decimal), and junctions with plus characters (ASCII code 43 decimal). Inputs are represented using the capital letters A through Z, and the output is represented by a question mark. AND and OR gates are represented as shown in the leftmost entries in the figure below, and their orientation will always be exactly as shown. The location of the gate inputs and output is shown by the middle figure below. Finally, gate inputs or its output can be inverted, represented by a lowercase "oh"character (ASCII code 111 decimal) at the input or output location. The figure on the right below shows a simple but complete logic circuit. :\ :\ -:\ -o:\ A-o:\ : ) : )o-? :/ : > : )- :/ -:/ OR gate Gate with inputs : )o- --:/ B--:/ AND gate logic inputs An inverted top input Two and an inverted output and the output Input Circuits in the input will obey the following guidelines: 1. The maximum size of the circuit picture is 100 by 100 characters. 2. A path always travels in a straight line unless altered by a junction. At a junction, the path can and will make a ninety degree turn. Two junctions will not be horizontally or vertically adjacent. 3. No paths will be "broken" That is, every path character is guaranteed to be adjacent on both sides to either another path character of the same type, a junction, a gate input, a gate output, a logic input, or the logic output. 4. Circuit paths do not cross or intersect other paths. 5. Gate inputs always approach horizontally from the left as shown above. Gate outputs always leave horizontally to the right as shown above. 6. Inversions may only appear immediately adjacent to a gate input or output, and will always be preceded (in the case of an input) or followed (in the case of an output) by at least one dash as shown above. The end of a logic diagram in the input is indicated by line containing only a single asterisk in the first column. Following this are several lines which indicate the state of the inputs in the logic diagram. Each of these lines is a string of twenty-six "0"(zero) or "1"characters, with the first position representing the state of input A, the second position representing the state of input B, etc. Note that input values which are not actually used in the circuit may simply be ignored. The list of input states is terminated by a line containing only a single asterisk character in the first column. Following the asterisk which terminates the list of input states is another circuit diagram followed by a list of input states, which is then followed by another circuit diagram and list of input states, and so on until the end of the file. The file will always contain at least one circuit and one set of inputs for that circuit. Output The program is to report the value of the output (0 or 1) of each logic circuit, one value per line, for each set of input values in the list which follows the circuit. The list of outputs for each circuit should be separated by a single blank line. Sample Input A---:\ : )---? B---:/ * 00000000000000000000000000 10000000000000000000000000 01000000000000000000000000 11000000000000000000000000 * A---+ | +---:\ : >o---:\ +---:/ : )---? | C--o:/ B---+ * 00000000000000000000000000 11100000000000000000000000 * Sample Output 0 0 0 1 1 0 Source Greater New York 2001 Searching the Web Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 1668 Accepted: 366 Description The word "search engine" may not be strange to you. Generally speaking, a search engine searches the web pages available in the Internet, extracts and organizes the information and responds to users' queries with the most relevant pages. World famous search engines, like GOOGLE, have become very important tools for us to use when we visit the web. Such conversations are now common in our daily life: "What does the word like ****** mean?" "Um... I am not sure, just google it." In this problem, you are required to construct a small search engine. Sounds impossible, does it? Don't worry, here is a tutorial teaching you how to organize large collection of texts efficiently and respond to queries quickly step by step. You don't need to worry about the fetching process of web pages, all the web pages are provided to you in text format as the input data. Besides, a lot of queries are also provided to validate your system. Modern search engines use a technique called inversion for dealing with very large sets of documents. The method relies on the construction of a data structure, called an inverted index,which associates terms (words) to their occurrences in the collection of documents. The set of terms of interest is called the vocabulary, denoted as V. In its simplest form, an inverted index is a dictionary where each search key is a term ω∈V. The associated value b(ω) is a pointer to an additional intermediate data structure, called a bucket. The bucket associated with a certain term ω is essentially a list of pointers marking all the occurrences of ω in the text collection. Each entry in each bucket simply consists of the document identifier (DID), the ordinal number of the document within the collection and the ordinal line number of the term's occurrence within the document. Let's take Figure-1 for an example, which describes the general structure. Assuming that we only have three documents to handle, shown at the right part in Figure-1; first we need to tokenize the text for words (blank, punctuations and other non-alphabetic characters are used to separate words) and construct our vocabulary from terms occurring in the documents. For simplicity, we don't need to consider any phrases, only a single word as a term. Furthermore, the terms are case-insensitive (e.g. we consider "book" and "Book" to be the same term) and we don't consider any morphological variants (e.g. we consider "books" and "book", "protected" and "protect" to be different terms) and hyphenated words (e.g. "middle-class" is not a single term, but separated into 2 terms "middle" and "class" by the hyphen). The vocabulary is shown at the left part in Figure-1.Each term of the vocabulary has a pointer to its bucket. The collection of the buckets is shown at the middle part in Figure-1. Each item in a bucket records the DID of the term's occurrence. After constructing the whole inverted index structure, we may apply it to the queries. The query is in any of the following formats: term term AND term term OR term NOT term A single term can be combined by Boolean operators: AND, OR and NOT ("term1 AND term2" means to query the documents including term1 and term2; "term1 OR term2" means to query the documents including term1 or term2; "NOT term1" means to query the documents not including term1). Terms are single words as defined above. You are guaranteed that no non-alphabetic characters appear in a term, and all the terms are in lowercase. Furthermore, some meaningless stop words (common words such as articles, prepositions, and adverbs, specified to be "the, a, to, and, or, not" in our problem) will not appear in the query, either. For each query, the engine based on the constructed inverted index searches the term in the vocabulary, compares the terms' bucket information, and then gives the result to user. Now can you construct the engine? Input The input starts with integer N (0 < N < 100) representing N documents provided. Then the next N sections are N documents. Each section contains the document content and ends with a single line of ten asterisks. ********** You may assume that each line contains no more than 80 characters and the total number of lines in the N documents will not exceed 1500. Next, integer M (0 < M <= 50000) is given representing the number of queries, followed by M lines, each query in one line. All the queries correspond to the format described above. Output For each query, you need to find the document satisfying the query, and output just the lines within the documents that include the search term (For a NOT query, you need to output the whole document). You should print the lines in the same order as they appear in the input. Separate different documents with a single line of 10 dashes. ---------If no documents matching the query are found, just output a single line: "Sorry, I found nothing." The output of each query ends with a single line of 10 equal signs. ========== Sample Input 4 A manufacturer, importer, or seller of digital media devices may not (1) sell, or offer for sale, in interstate commerce, or (2) cause to be transported in, or in a manner affecting, interstate commerce, a digital media device unless the device includes and utilizes standard security technologies that adhere to the security system standards. ********** Of course, Lisa did not necessarily intend to read his books. She might want the computer only to write her midterm. But Dan knew she came from a middle-class family and could hardly afford the tuition, let alone her reading fees. Books might be the only way she could graduate ********** Research in analysis (i.e., the evaluation of the strengths and weaknesses of computer system) is essential to the development of effective security, both for works protected by copyright law and for information in general. Such research can progress only through the open publication and exchange of complete scientific results ********** I am very very very happy! What about you? ********** 6 computer books AND computer books OR protected NOT security very slick Sample Output want the computer only to write her ---------computer system) is essential to the ========== intend to read his books. She might want the computer only to write her fees. Books might be the only way she ========== intend to read his books. She might fees. Books might be the only way she ---------for works protected by copyright law ========== Of course, Lisa did not necessarily intend to read his books. She might want the computer only to write her midterm. But Dan knew she came from a middle-class family and could hardly afford the tuition, let alone her reading fees. Books might be the only way she could graduate ---------I am very very very happy! What about you? ========== I am very very very happy! ========== Sorry, I found nothing. ========== Source Beijing 2004 Busy Airport Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 448 Accepted: 123 Description Today is a busy day of Mehrabad Airport. There are a lot of aircrafts requesting to land but unfortunately, the number of available bands for landing is a few. As a result, a policy has been set to manage the landing aircrafts: Landing requests are processed in the order they are received. While processing a landing request, if there is a free band, the band is allocated and the landing process starts immediately. For each aircraft, the duration it takes, from the time its landing request is accepted to the time its landing is finished and the band is de-allocated, has been computed beforehand and is available now. Note that, if an aircraft starts landing at time 00:00:00.000 and it takes 10 minutes for it to land, then the band which was used for its landing is de-allocated at 00:10:00.000 and can be used by another aircraft at that time. In the case there is no free band while processing a request, the request is temporarily rejected and the requesting aircraft is asked to request for landing again after 10 minutes. In the case two aircrafts request to land at the same time, the request of the one with the smaller ID is processed first. You are asked to write a program that, given the initial request time and the duration of landing for each aircraft, simulates the above process and generates a detailed report of in which order and at what times these aircrafts will land. Input The first line of input consists of a single integer T, the number of test-cases. Each test-case starts with a line containing two integers, , 1 ≤ R ≤ 100 , the number of aircrafts requesting to land and 1 ≤ B ≤ 10, the number of available bands for landing. Each of the next R lines contains the description of the landing aircraft consisting of the aircraft ID (less than 10000000), the date of arrival (due to Persian Calendar ) in the format 'dd/mm/yyyy' where 1178 ≤ yyyy < 1634 , the time of initial request for landing in the format 'hh:mm:ss.uuu' in 24 hour format, and the time-span 'hh:mm:ss.uuu', guaranteed to be at most 2 hours, which is the amount of time needed for that aircraft to land. Output For each test case, your program should first output a line containing the phrase 'Report for Test-Case #k:', where k is the index of the test-case, followed by the report associated with it. Each line of the report contains an entry which can be: An accepted request: In this case, the entry contains the aircraft ID together with the date and time of the request followed by the word ACCEPTED. A rejected request: In this case, the entry contains the aircraft ID together with the date and time of the request followed by the word POSTPONED. A finished landing: is generated when an accepted aircraft is finished landing. It contains the aircraft ID together with the date and time of the request followed by the word LANDED. The entries must be sorted in increasing order, according to the following conditions: An entry with an earlier date should precede the other requests. In the case of two entries with equal dates, the one with earlier time should precede the other In the case some entries have equal dates and times, the finished landing entries should precede the others. In the case none of the above rules are applicable between a pair of entries, the one with the lower ID precedes the other. There should be an empty line after each test-case. Sample Input 1 3 1 377 11/01/1385 10:45:54.000 00:04:00.000 367 11/01/1385 10:45:54.000 00:03:00.000 357 11/01/1385 10:48:54.000 00:04:00.000 Sample Output Report for Test-Case #1: 367 377 367 357 357 377 377 11/01/1385 11/01/1385 11/01/1385 11/01/1385 11/01/1385 11/01/1385 11/01/1385 10:45:54.000 10:45:54.000 10:48:54.000 10:48:54.000 10:52:54.000 10:55:54.000 10:59:54.000 ACCEPTED POSTPONED LANDED ACCEPTED LANDED ACCEPTED LANDED Hint There may be situations in which handling of leap years is required. According to the Persian (Jalali) Calendar, leap year is a year which has 366 days instead of 365, and this extra day is added to the end of Esfand. You may assume that a given year is leap year if the remainder of it divided by 33 is either 1, 5, 9, 13, 17, 22, or 30. Actually, this formula is only correct if the given year is in the range [1178, 1634) but regardless of the given year in the input, use it for detection of leap years. NOTE:It seems that there are 12 months in a Persian (Jalali) year. The first 6 month have 31 days. The following 5 months have 30 day. The last year has 29 or 30 days according whether or not it is leap year. Source Amirkabir University of Technology Local Contest 2006 Terrarium Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 759 Accepted: 206 Description A zoology research lab has a terrarium with rare species of snakes. Terrarium is a flat box filled with soil, and has a glass top allowing to watch the snakes. There are trenches in the soil, and snakes constantly move along the trenches. All snakes have diameter of 1 cm and integer length of no less than 2 cm. While watching the snakes, the zoologists discovered a pattern in their movement: each snake moves at a speed of 1 cm per second forward, until it encounters either a wall or another snake. Faced an obstacle, snake first tries to turn right, if there is also obstacle on the right, then it tries to turn left. If there is obstacle on the left also, the snake waits for a second before trying to move again. In order to validate the discovery, it was decided to write a program that simulates snakes' behaviour. This task was assigned to you. The terrarium is represented by an array of N × N characters. Each character is one of: '.' (ASCII 46) — trench '#' (ASCII 35) — wall 'A' to 'Z' — snake's head 'a' to 'z' — snake's body or tip of the tail Snakes are represented by Latin letters, so there are no more than 26 snakes in terrarium. Snakes try to move in alphabetical order every second. Your program must output the state of the terrarium after T seconds. Input First line of input file contains integers N T. Following N lines contain N characters each — the initial state of the terrarium. The input file guarantees unambiguous recognition of snakes — all snakes are continuous, every character of snake's body has exactly two neighbour characters belonging to the same snake, while head and tip of the tail have exactly one. Constraints 2 ≤ N ≤ 1000, 1 ≤ T ≤ 106. Output Output file must contain N lines of N characters — the state of the terrarium after T seconds. Sample Input Sample input 1 4 8 .bB. .... a.#. aaA. Sample input 2 7 100000 aA..... a#####D aa....d ......d ......d ......d ....... Sample Output Sample output 1 .baa .BAa ..#. .... Sample output 2 aaaaADd .#####d ......d ......d ....... ....... ....... Hint Bold texts appearing in the sample sections are informative and do not form part of the actual data. Source Northeastern Europe 2005, Far-Eastern Subregion Picnic Planning Time Limit: 5000MS Memory Limit: 10000K Total Submissions: 5592 Accepted: 1831 Description The Contortion Brothers are a famous set of circus clowns, known worldwide for their incredible ability to cram an unlimited number of themselves into even the smallest vehicle. During the off-season, the brothers like to get together for an Annual Contortionists Meeting at a local park. However, the brothers are not only tight with regard to cramped quarters, but with money as well, so they try to find the way to get everyone to the party which minimizes the number of miles put on everyone's cars (thus saving gas, wear and tear, etc.). To this end they are willing to cram themselves into as few cars as necessary to minimize the total number of miles put on all their cars together. This often results in many brothers driving to one brother's house, leaving all but one car there and piling into the remaining one. There is a constraint at the park, however: the parking lot at the picnic site can only hold a limited number of cars, so that must be factored into the overall miserly calculation. Also, due to an entrance fee to the park, once any brother's car arrives at the park it is there to stay; he will not drop off his passengers and then leave to pick up other brothers. Now for your average circus clan, solving this problem is a challenge, so it is left to you to write a program to solve their milage minimization problem. Input Input will consist of one problem instance. The first line will contain a single integer n indicating the number of highway connections between brothers or between brothers and the park. The next n lines will contain one connection per line, of the form name1 name2 dist, where name1 and name2 are either the names of two brothers or the word Park and a brother's name (in either order), and dist is the integer distance between them. These roads will all be 2-way roads, and dist will always be positive.The maximum number of brothers will be 20 and the maximumlength of any name will be 10 characters.Following these n lines will be one final line containing an integer s which specifies the number of cars which can fit in the parking lot of the picnic site. You may assume that there is a path from every brother's house to the park and that a solution exists for each problem instance. Output Output should consist of one line of the form Total miles driven: xxx where xxx is the total number of miles driven by all the brothers' cars. Sample Input 10 Alphonzo Bernardo 32 Alphonzo Park 57 Alphonzo Eduardo 43 Bernardo Park 19 Bernardo Clemenzi 82 Clemenzi Park 65 Clemenzi Herb 90 Clemenzi Eduardo 109 Park Herb 24 Herb Eduardo 79 3 Sample Output Total miles driven: 183 Source East Central North America 2000 Hard Life Time Limit: 8000MS Memory Limit: 65536K Total Submissions: 3440 Accepted: 937 Case Time Limit: 2000MS Special Judge Description John is a Chief Executive Officer at a privately owned medium size company. The owner of the company has decided to make his son Scott a manager in the company. John fears that the owner will ultimately give CEO position to Scott if he does well on his new manager position, so he decided to make Scott’s life as hard as possible by carefully selecting the team he is going to manage in the company. John knows which pairs of his people work poorly in the same team. John introduced a hardness factor of a team — it is a number of pairs of people from this team who work poorly in the same team divided by the total number of people in the team. The larger is the hardness factor, the harder is this team to manage. John wants to find a group of people in the company that are hardest to manage and make it Scott’s team. Please, help him. In the example on the picture the hardest team consists of people 1, 2, 4, and 5. Among 4 of them 5 pairs work poorly in the same team, thus hardness factor is equal to 5⁄4. If we add person number 3 to the team then hardness factor decreases to 6⁄5. Input The first line of the input file contains two integer numbers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 1000). Here n is a total number of people in the company (people are numbered from 1 to n), and m is the number of pairs of people who work poorly in the same team. Next m lines describe those pairs with two integer numbers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) on a line. The order of people in a pair is arbitrary and no pair is listed twice. Output Write to the output file an integer number k (1 ≤ k ≤ n) — the number of people in the hardest team, followed by k lines listing people from this team in ascending order. If there are multiple teams with the same hardness factor then write any one. Sample Input sample input #1 5 6 1 5 5 4 4 2 2 5 1 2 3 1 sample input #2 4 0 Sample Output sample output #1 4 1 2 4 5 sample output #2 1 1 Hint Note, that in the last example any team has hardness factor of zero, and any non-empty list of people is a valid answer. Source Northeastern Europe 2006 Optimal Milking Time Limit: 2000MS Memory Limit: 30000K Total Submissions: 4605 Accepted: 1783 Case Time Limit: 1000MS Description FJ has moved his K (1 <= K <= 30) milking machines out into the cow pastures among the C (1 <= C <= 200) cows. A set of paths of various lengths runs among the cows and the milking machines. The milking machine locations are named by ID numbers 1..K; the cow locations are named by ID numbers K+1..K+C. Each milking point can "process" at most M (1 <= M <= 15) cows each day. Write a program to find an assignment for each cow to some milking machine so that the distance the furthest-walking cow travels is minimized (and, of course, the milking machines are not overutilized). At least one legal assignment is possible for all input data sets. Cows can traverse several paths on the way to their milking machine. Input * Line 1: A single line with three space-separated integers: K, C, and M. * Lines 2.. ...: Each of these K+C lines of K+C space-separated integers describes the distances between pairs of various entities. The input forms a symmetric matrix. Line 2 tells the distances from milking machine 1 to each of the other entities; line 3 tells the distances from machine 2 to each of the other entities, and so on. Distances of entities directly connected by a path are positive integers no larger than 200. Entities not directly connected by a path have a distance of 0. The distance from an entity to itself (i.e., all numbers on the diagonal) is also given as 0. To keep the input lines of reasonable length, when K+C > 15, a row is broken into successive lines of 15 numbers and a potentially shorter line to finish up a row. Each new row begins on its own line. Output A single line with a single integer that is the minimum possible total distance for the furthest walking cow. Sample Input 2 0 3 2 1 1 3 3 0 3 2 0 2 2 3 0 1 0 1 2 1 0 2 1 0 0 2 0 Sample Output 2 Source USACO 2003 U S Open Cable TV Network Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 1837 Accepted: 808 Description The interconnection of the relays in a cable TV network is bi-directional. The network is connected if there is at least one interconnection path between each pair of relays present in the network. Otherwise the network is disconnected. An empty network or a network with a single relay is considered connected. The safety factor f of a network with n relays is: 1. n, if the net remains connected regardless the number of relays removed from the net. 2. The minimal number of relays that disconnect the network when removed. For example, consider the nets from figure 1, where the circles mark the relays and the solid lines correspond to interconnection cables. The network (a) is connected regardless the number of relays that are removed and, according to rule (1), f=n=3. The network (b) is disconnected when 0 relays are removed, hence f=0 by rule (2). The network (c) is disconnected when the relays 1 and 2 or 1 and 3 are removed. The safety factor is 2. Input Write a program that reads several data sets from the standard input and computes the safety factor for the cable networks encoded by the data sets. Each data set starts with two integers: 0<=n<=50,the number of relays in the net, and m, the number of cables in the net. Follow m data pairs (u,v), u < v, where u and v are relay identifiers (integers in the range 0..n-1). The pair (u,v) designates the cable that interconnects the relays u and v. The pairs may occur in any order.Except the (u,v) pairs, which do not contain white spaces, white spaces can occur freely in input. Input data terminate with an end of file and are correct. Output For each data set, the program prints on the standard output, from the beginning of a line, the safety factor of the encoded net. Sample Input 0 1 3 2 5 0 0 3 (0,1) (0,2) (1,2) 0 7 (0,1) (0,2) (1,3) (1,2) (1,4) (2,3) (3,4) Sample Output 0 1 3 0 2 Hint The first data set encodes an empty network, the second data set corresponds to a network with a single relay, and the following three data sets encode the nets shown in figure 1. Dining Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 4154 Accepted: 1889 Description Cows are such finicky eaters. Each cow has a preference for certain foods and drinks, and she will consume no others. Farmer John has cooked fabulous meals for his cows, but he forgot to check his menu against their preferences. Although he might not be able to stuff everybody, he wants to give a complete meal of both food and drink to as many cows as possible. Farmer John has cooked F (1 ≤ F ≤ 100) types of foods and prepared D (1 ≤ D ≤ 100) types of drinks. Each of his N (1 ≤ N ≤ 100) cows has decided whether she is willing to eat a particular food or drink a particular drink. Farmer John must assign a food type and a drink type to each cow to maximize the number of cows who get both. Each dish or drink can only be consumed by one cow (i.e., once food type 2 is assigned to a cow, no other cow can be assigned food type 2). Input Line 1: Three space-separated integers: N, F, and D Lines 2..N+1: Each line i starts with a two integers Fi and Di, the number of dishes that cow i likes and the number of drinks that cow i likes. The next Fi integers denote the dishes that cow i will eat, and the Di integers following that denote the drinks that cow i will drink. Output Line 1: A single integer that is the maximum number of cows that can be fed both food and drink that conform to their wishes Sample Input 4 2 2 2 2 3 2 2 2 1 3 1 2 1 1 2 3 3 3 3 1 1 2 1 2 3 Sample Output 3 Hint One way to satisfy three cows is: Cow 1: no meal Cow 2: Food #2, Drink #2 Cow 3: Food #1, Drink #1 Cow 4: Food #3, Drink #3 The pigeon-hole principle tells us we can do no better since there are only three kinds of food or drink. Other test data sets are more challenging, of course. Source USACO 2007 Open Gold A Plug for UNIX Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 8992 Accepted: 2848 Description You are in charge of setting up the press room for the inaugural meeting of the United Nations Internet eXecutive (UNIX), which has an international mandate to make the free flow of information and ideas on the Internet as cumbersome and bureaucratic as possible. Since the room was designed to accommodate reporters and journalists from around the world, it is equipped with electrical receptacles to suit the different shapes of plugs and voltages used by appliances in all of the countries that existed when the room was built. Unfortunately, the room was built many years ago when reporters used very few electric and electronic devices and is equipped with only one receptacle of each type. These days, like everyone else, reporters require many such devices to do their jobs: laptops, cell phones, tape recorders, pagers, coffee pots, microwave ovens, blow dryers, curling irons, tooth brushes, etc. Naturally, many of these devices can operate on batteries, but since the meeting is likely to be long and tedious, you want to be able to plug in as many as you can. Before the meeting begins, you gather up all the devices that the reporters would like to use, and attempt to set them up. You notice that some of the devices use plugs for which there is no receptacle. You wonder if these devices are from countries that didn't exist when the room was built. For some receptacles, there are several devices that use the corresponding plug. For other receptacles, there are no devices that use the corresponding plug. In order to try to solve the problem you visit a nearby parts supply store. The store sells adapters that allow one type of plug to be used in a different type of outlet. Moreover, adapters are allowed to be plugged into other adapters. The store does not have adapters for all possible combinations of plugs and receptacles, but there is essentially an unlimited supply of the ones they do have. Input The input will consist of one case. The first line contains a single positive integer n (1 <= n <= 100) indicating the number of receptacles in the room. The next n lines list the receptacle types found in the room. Each receptacle type consists of a string of at most 24 alphanumeric characters. The next line contains a single positive integer m (1 <= m <= 100) indicating the number of devices you would like to plug in. Each of the next m lines lists the name of a device followed by the type of plug it uses (which is identical to the type of receptacle it requires). A device name is a string of at most 24 alphanumeric characters. No two devices will have exactly the same name. The plug type is separated from the device name by a space. The next line contains a single positive integer k (1 <= k <= 100) indicating the number of different varieties of adapters that are available. Each of the next k lines describes a variety of adapter, giving the type of receptacle provided by the adapter, followed by a space, followed by the type of plug. Output A line containing a single non-negative integer indicating the smallest number of devices that cannot be plugged in. Sample Input 4 A B C D 5 laptop B phone C pager B clock B comb X 3 B X X A X D Sample Output 1 Source East Central North America 1999 Jamie's Contact Groups Time Limit: 7000MS Memory Limit: 65536K Total Submissions: 3338 Accepted: 1051 Description Jamie is a very popular girl and has quite a lot of friends, so she always keeps a very long contact list in her cell phone. The contact list has become so long that it often takes a long time for her to browse through the whole list to find a friend's number. As Jamie's best friend and a programming genius, you suggest that she group the contact list and minimize the size of the largest group, so that it will be easier for her to search for a friend's number among the groups. Jamie takes your advice and gives you her entire contact list containing her friends' names, the number of groups she wishes to have and what groups every friend could belong to. Your task is to write a program that takes the list and organizes it into groups such that each friend appears in only one of those groups and the size of the largest group is minimized. Input There will be at most 20 test cases. Ease case starts with a line containing two integers N and M. where N is the length of the contact list and M is the number of groups. N lines then follow. Each line contains a friend's name and the groups the friend could belong to. You can assume N is no more than 1000 and M is no more than 500. The names will contain alphabet letters only and will be no longer than 15 characters. No two friends have the same name. The group label is an integer between 0 and M - 1. After the last test case, there is a single line `0 0' that terminates the input. Output For each test case, output a line containing a single integer, the size of the largest contact group. Sample Input 3 2 John 0 1 Rose 1 Mary 1 5 4 ACM 1 2 3 ICPC 0 1 Asian 0 2 3 Regional 1 2 ShangHai 0 2 0 0 Sample Output 2 2 Source Shanghai 2004 Repairing Company Time Limit: 1000MS Memory Limit: 131072K Total Submissions: 4256 Accepted: 1117 Description Lily runs a repairing company that services the Q blocks in the city. One day the company receives M repair tasks, the ith of which occurs in block pi, has a deadline ti on any repairman’s arrival, which is also its starting time, and takes a single repairman di time to finish. Repairmen work alone on all tasks and must finish one task before moving on to another. With a map of the city in hand, Lily want to know the minimum number of repairmen that have to be assign to this day’s tasks. Input The input contains multiple test cases. Each test case begins with a line containing Q and M (0 < Q ≤ 20, 0 < M ≤ 200). Then follow Q lines each with Q integers, which represent a Q × Q matrix Δ = {δij}, where δij means a bidirectional road connects the ith and the jth blocks and requires δij time to go from one end to another. If δij = −1, such a road does not exist. The matrix is symmetric and all its diagonal elements are zeroes. Right below the matrix are M lines describing the repairing tasks. The ith of these lines contains pi, ti and di. Two zeroes on a separate line come after the last test case. Output For each test case output one line containing the minimum number of repairmen that have to be assigned. Sample Input 1 0 1 1 0 2 1 10 5 10 0 Sample Output 2 Source POJ Monthly--2007.04.01, crazyb0y Chessboard Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 6719 Accepted: 2103 Description Alice and Bob often play games on chessboard. One day, Alice draws a board with size M * N. She wants Bob to use a lot of cards with size 1 * 2 to cover the board. However, she thinks it too easy to bob, so she makes some holes on the board (as shown in the figure below). We call a grid, which doesn’t contain a hole, a normal grid. Bob has to follow the rules below: 1. Any normal grid should be covered with exactly one card. 2. One card should cover exactly 2 normal adjacent grids. Some examples are given in the figures below: A VALID solution. An invalid solution, because the hole of red color is covered with a card. An invalid solution, because there exists a grid, which is not covered. Your task is to help Bob to decide whether or not the chessboard can be covered according to the rules above. Input There are 3 integers in the first line: m, n, k (0 < m, n <= 32, 0 <= K < m * n), the number of rows, column and holes. In the next k lines, there is a pair of integers (x, y) in each line, which represents a hole in the y-th row, the x-th column. Output If the board can be covered, output "YES". Otherwise, output "NO". Sample Input 4 3 2 2 1 3 3 Sample Output YES Hint A possible solution for the sample input. Source POJ Monthly,charlescpp Desert King Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 11731 Accepted: 3305 Description David the Great has just become the king of a desert country. To win the respect of his people, he decided to build channels all over his country to bring water to every village. Villages which are connected to his capital village will be watered. As the dominate ruler and the symbol of wisdom in the country, he needs to build the channels in a most elegant way. After days of study, he finally figured his plan out. He wanted the average cost of each mile of the channels to be minimized. In other words, the ratio of the overall cost of the channels to the total length must be minimized. He just needs to build the necessary channels to bring water to all the villages, which means there will be only one way to connect each village to the capital. His engineers surveyed the country and recorded the position and altitude of each village. All the channels must go straight between two villages and be built horizontally. Since every two villages are at different altitudes, they concluded that each channel between two villages needed a vertical water lifter, which can lift water up or let water flow down. The length of the channel is the horizontal distance between the two villages. The cost of the channel is the height of the lifter. You should notice that each village is at a different altitude, and different channels can't share a lifter. Channels can intersect safely and no three villages are on the same line. As King David's prime scientist and programmer, you are asked to find out the best solution to build the channels. Input There are several test cases. Each test case starts with a line containing a number N (2 <= N <= 1000), which is the number of villages. Each of the following N lines contains three integers, x, y and z (0 <= x, y < 10000, 0 <= z < 10000000). (x, y) is the position of the village and z is the altitude. The first village is the capital. A test case with N = 0 ends the input, and should not be processed. Output For each test case, output one line containing a decimal number, which is the minimum ratio of overall cost of the channels to the total length. This number should be rounded three digits after the decimal point. Sample Input 4 0 0 1 1 0 0 1 1 0 0 1 2 3 Sample Output 1.000 Source Beijing 2005 Command Network Time Limit: 1000MS Memory Limit: 131072K Total Submissions: 5313 Accepted: 1527 Description After a long lasting war on words, a war on arms finally breaks out between littleken’s and KnuthOcean’s kingdoms. A sudden and violent assault by KnuthOcean’s force has rendered a total failure of littleken’s command network. A provisional network must be built immediately. littleken orders snoopy to take charge of the project. With the situation studied to every detail, snoopy believes that the most urgent point is to enable littenken’s commands to reach every disconnected node in the destroyed network and decides on a plan to build a unidirectional communication network. The nodes are distributed on a plane. If littleken’s commands are to be able to be delivered directly from a node A to another node B, a wire will have to be built along the straight line segment connecting the two nodes. Since it’s in wartime, not between all pairs of nodes can wires be built. snoopy wants the plan to require the shortest total length of wires so that the construction can be done very soon. Input The input contains several test cases. Each test case starts with a line containing two integer N (N ≤ 100), the number of nodes in the destroyed network, and M (M ≤ 104), the number of pairs of nodes between which a wire can be built. The next N lines each contain an ordered pair xi and yi, giving the Cartesian coordinates of the nodes. Then follow M lines each containing two integers i and j between 1 and N (inclusive) meaning a wire can be built between node i and node j for unidirectional command delivery from the former to the latter. littleken’s headquarter is always located at node 1. Process to end of file. Output For each test case, output exactly one line containing the shortest total length of wires to two digits past the decimal point. In the cases that such a network does not exist, just output ‘poor snoopy’. Sample Input 4 0 4 0 7 1 1 2 3 3 3 4 0 1 0 1 1 4 2 6 6 6 0 20 2 3 3 4 1 2 3 0 0 1 2 3 1 3 Sample Output 31.19 poor snoopy Source POJ Monthly--2006.12.31, galaxy DNA Sequence Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 4476 Accepted: 1570 Description It's well known that DNA Sequence is a sequence only contains A, C, T and G, and it's very useful to analyze a segment of DNA Sequence,For example, if a animal's DNA sequence contains segment ATC then it may mean that the animal may have a genetic disease. Until now scientists have found several those segments, the problem is how many kinds of DNA sequences of a species don't contain those segments. Suppose that DNA sequences of a species is a sequence that consist of A, C, T and G,and the length of sequences is a given integer n. Input First line contains two integer m (0 <= m <= 10), n (1 <= n <=2000000000). Here, m is the number of genetic disease segment, and n is the length of sequences. Next m lines each line contain a DNA genetic disease segment, and length of these segments is not larger than 10. Output An integer, the number of DNA sequences, mod 100000. Sample Input 4 3 AT AC AG AA Sample Output 36 Source POJ Monthly--2006.03.26,dodo Nearest Common Ancestors Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 8157 Accepted: 4294 Description A rooted tree is a well-known data structure in computer science and engineering. An example is shown below: In the figure, each node is labeled with an integer from {1, 2,...,16}. Node 8 is the root of the tree. Node x is an ancestor of node y if node x is in the path between the root and node y. For example, node 4 is an ancestor of node 16. Node 10 is also an ancestor of node 16. As a matter of fact, nodes 8, 4, 10, and 16 are the ancestors of node 16. Remember that a node is an ancestor of itself. Nodes 8, 4, 6, and 7 are the ancestors of node 7. A node x is called a common ancestor of two different nodes y and z if node x is an ancestor of node y and an ancestor of node z. Thus, nodes 8 and 4 are the common ancestors of nodes 16 and 7. A node x is called the nearest common ancestor of nodes y and z if x is a common ancestor of y and z and nearest to y and z among their common ancestors. Hence, the nearest common ancestor of nodes 16 and 7 is node 4. Node 4 is nearer to nodes 16 and 7 than node 8 is. For other examples, the nearest common ancestor of nodes 2 and 3 is node 10, the nearest common ancestor of nodes 6 and 13 is node 8, and the nearest common ancestor of nodes 4 and 12 is node 4. In the last example, if y is an ancestor of z, then the nearest common ancestor of y and z is y. Write a program that finds the nearest common ancestor of two distinct nodes in a tree. Input The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case starts with a line containing an integer N , the number of nodes in a tree, 2<=N<=10,000. The nodes are labeled with integers 1, 2,..., N. Each of the next N -1 lines contains a pair of integers that represent an edge --the first integer is the parent node of the second integer. Note that a tree with N nodes has exactly N - 1 edges. The last line of each test case contains two distinct integers whose nearest common ancestor is to be computed. Output Print exactly one line for each test case. The line should contain the integer that is the nearest common ancestor. Sample Input 2 16 1 14 8 5 10 16 5 9 4 6 8 4 4 10 1 13 6 15 10 11 6 7 10 2 16 3 8 1 16 12 16 7 5 2 3 3 4 3 1 1 5 3 5 Sample Output 4 3 Source Taejon 2002 Sliding Window Time Limit: 12000MS Memory Limit: 65536K Total Submissions: 15692 Accepted: 4506 Case Time Limit: 5000MS Description An array of size n ≤ 106 is given to you. There is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves rightwards by one position. Following is an example: The array is [1 3 -1 -3 5 3 6 7], and k is 3. Window position Minimum value Maximum value [1 3 1 [3 -1] -3 -1 5 3 6 7 -1 3 -3] 5 3 6 7 -3 3 5] 3 6 7 -3 5 3] 6 7 -3 5 6] 7 3 6 6 3 7 1 3 [-1 -3 1 3 -1 [-3 1 3 -1 -3 [5 1 3 -1 -3 5 3 5 [3 7] Your task is to determine the maximum and minimum values in the sliding window at each position. Input The input consists of two lines. The first line contains two integers n and k which are the lengths of the array and the sliding window. There are n integers in the second line. Output There are two lines in the output. The first line gives the minimum values in the window at each position, from left to right, respectively. The second line gives the maximum values. Sample Input 8 3 1 3 -1 -3 5 3 6 7 Sample Output -1 -3 -3 -3 3 3 3 3 5 5 6 7 Source POJ Monthly--2006.04.28, Ikki Common Substrings Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 2962 Accepted: 943 Description A substring of a string T is defined as: T(i, k)=TiTi+1...Ti+k-1, 1≤i≤i+k-1≤|T|. Given two strings A, B and one integer K, we define S, a set of triples (i, j, k): S = {(i, j, k) | k≥K, A(i, k)=B(j, k)}. You are to give the value of |S| for specific A, B and K. Input The input file contains several blocks of data. For each block, the first line contains one integer K, followed by two lines containing strings A and B, respectively. The input file is ended by K=0. 1 ≤ |A|, |B| ≤ 105 1 ≤ K ≤ min{|A|, |B|} Characters of A and B are all Latin letters. Output For each case, output an integer |S|. Sample Input 2 aababaa abaabaa 1 xx xx 0 Sample Output 22 5 Source POJ Monthly--2007.10.06, wintokk Life Forms Description Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 4263 Accepted: 1096 You may have wondered why most extraterrestrial life forms resemble humans, differing by superficial traits such as height, colour, wrinkles, ears, eyebrows and the like. A few bear no human resemblance; these typically have geometric or amorphous shapes like cubes, oil slicks or clouds of dust. The answer is given in the 146th episode of Star Trek - The Next Generation, titled The Chase. It turns out that in the vast majority of the quadrant's life forms ended up with a large fragment of common DNA. Given the DNA sequences of several life forms represented as strings of letters, you are to find the longest substring that is shared by more than half of them. Input Standard input contains several test cases. Each test case begins with 1 ≤ n ≤ 100, the number of life forms. n lines follow; each contains a string of lower case letters representing the DNA sequence of a life form. Each DNA sequence contains at least one and not more than 1000 letters. A line containing 0 follows the last test case. Output For each test case, output the longest string or strings shared by more than half of the life forms. If there are many, output all of them in alphabetical order. If there is no solution with at least one letter, output "?". Leave an empty line between test cases. Sample Input 3 abcdefg bcdefgh cdefghi 3 xxx yyy zzz 0 Sample Output bcdefg cdefgh ? Source Waterloo Local Contest, 2006.9.30 The Bermuda Triangle Time Limit: 2000MS Memory Limit: 32768K Total Submissions: 755 Accepted: 326 Description People in the hidden region of the Bermuda Triangle make everything they need in triangular shapes. One day, someone decided to break the rule and bake a hexagonally shaped cake. But as usual, he has to serve the cake in triangular pieces. The pieces are equilateral triangles but in different sizes for different people. He can use as many triangles as needed to cut the cake into pieces, such that nothing remains from the cake. For example, the following figure shows one way that a hexagon with side 9 can be cut into triangles with side 2 and 3. (The cake is cut along the thick lines, thin lines are drawn to show the sizes). Input is a hexagon and triangle types (specified by the length of their sides) and the goal is to decide if the hexagon can be completely divided by the given triangle types. Input The first line of the input file contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. Each test case consists of a single line, containing s (1 <= s <= 25), the length of the hexagon's side, followed by n, the number of triangle types (1 <= n <= 10), followed by n integers representing the length of each triangle type's side (between 1 and 25, inclusive). Output There should be one output line per test case containing either YES or NO depending on whether the hexagon can be completely divided by the given triangle types. Sample Input 3 5 2 2 3 7 2 3 2 13 2 2 3 Sample Output NO NO YES Source Tehran 2001 Bloxorz I Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 3645 Accepted: 1218 Description Little Tom loves playing games. One day he downloads a little computer game called 'Bloxorz' which makes him excited. It's a game about rolling a box to a specific position on a special plane. Precisely, the plane, which is composed of several unit cells, is a rectangle shaped area. And the box, consisting of two perfectly aligned unit cube, may either lies down and occupies two neighbouring cells or stands up and occupies one single cell. One may move the box by picking one of the four edges of the box on the ground and rolling the box 90 degrees around that edge, which is counted as one move. There are three kinds of cells, rigid cells, easily broken cells and empty cells. A rigid cell can support full weight of the box, so it can be either one of the two cells that the box lies on or the cell that the box fully stands on. A easily broken cells can only support half the weight of the box, so it cannot be the only cell that the box stands on. An empty cell cannot support anything, so there cannot be any part of the box on that cell. The target of the game is to roll the box standing onto the only target cell on the plane with minimum moves. The box stands on a single cell The box lies on two neighbouring cells, horizontally The box lies on two neighbouring cells, vertically After Little Tom passes several stages of the game, he finds it much harder than he expected. So he turns to your help. Input Input contains multiple test cases. Each test case is one single stage of the game. It starts with two integers R and C(3 ≤ R, C ≤ 500) which stands for number of rows and columns of the plane. That follows the plane, which contains R lines and C characters for each line, with 'O' (Oh) for target cell, 'X' for initial position of the box, '.' for a rigid cell, '#' for a empty cell and 'E' for a easily broken cell. A test cases starts with two zeros ends the input. It guarantees that There's only one 'O' in a plane. There's either one 'X' or neighbouring two 'X's in a plane. The first(and last) row(and column) must be '#'(empty cell). Cells covered by 'O' and 'X' are all rigid cells. Output For each test cases output one line with the minimum number of moves or "Impossible" (without quote) when there's no way to achieve the target cell. Sample Input 7 7 ####### #..X### #..##O# #....E# #....E# #.....# ####### 0 0 Sample Output 10 Source POJ Monthly--2007.08.05, Rainer Pushing Boxes Time Limit: 2000MS Memory Limit: 131072K Total Submissions: 2916 Accepted: 1071 Special Judge Description Imagine you are standing inside a two-dimensional maze composed of square cells which may or may not be filled with rock. You can move north, south, east or west one cell at a step. These moves are called walks. One of the empty cells contains a box which can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. Such a move is called a push. The box cannot be moved in any other way than by pushing, which means that if you push it into a corner you can never get it out of the corner again. One of the empty cells is marked as the target cell. Your job is to bring the box to the target cell by a sequence of walks and pushes. As the box is very heavy, you would like to minimize the number of pushes. Can you write a program that will work out the best such sequence? Input The input contains the descriptions of several mazes. Each maze description starts with a line containing two integers r and c (both <= 20) representing the number of rows and columns of the maze. Following this are r lines each containing c characters. Each character describes one cell of the maze. A cell full of rock is indicated by a `#' and an empty cell is represented by a `.'. Your starting position is symbolized by `S', the starting position of the box by `B' and the target cell by `T'. Input is terminated by two zeroes for r and c. Output For each maze in the input, first print the number of the maze, as shown in the sample output. Then, if it is impossible to bring the box to the target cell, print ``Impossible.''. Otherwise, output a sequence that minimizes the number of pushes. If there is more than one such sequence, choose the one that minimizes the number of total moves (walks and pushes). If there is still more than one such sequence, any one is acceptable. Print the sequence as a string of the characters N, S, E, W, n, s, e and w where uppercase letters stand for pushes, lowercase letters stand for walks and the different letters stand for the directions north, south, east and west. Output a single blank line after each test case. Sample Input 1 7 SB....T 1 7 SB..#.T 7 11 ########### #T##......# #.#.#..#### #....B....# #.######..# #.....S...# ########### 8 4 .... .##. .#.. .#.. .#.B .##S .... ###T 0 0 Sample Output Maze #1 EEEEE Maze #2 Impossible. Maze #3 eennwwWWWWeeeeeesswwwwwwwnNN Maze #4 swwwnnnnnneeesssSSS Source Southwestern European Regional Contest 1997 The Treasure Time Limit: 5000MS Memory Limit: 30000K Total Submissions: 1729 Accepted: 330 Description We have arrived at the age of the Internet. Many software applications have transformed from stand-alone to online applications. Computer games are following this trend as well. Online games are becoming more and more popular, not only because they are more intelligent, but also because they can bring great profits. "The computer game industry is developing rapidly in China. Online game revenues amounted to 1.3 billion Yuan last year and are expected to reach 6.7 billion Yuan by 2007." reported by China Daily in 2004. However, good games originate from good programmers. We take for example that there is a RPG (Role Playing Game) and your boss asks you to implement some tasks. For simplicity’s sake, we assume there are two kinds of roles in this game: one is player and the other is monster. You should help the player to achieve the goal: reach the place where treasure is positioned as early as possible and get the treasure. The map of the game is a matrix of N * M identical cells. Some cells are passable blocks, and others are non-passable rocks. At any time, there is at most one role occupying a block. At the beginning, the time is set to 0, and the player is at a certain block. He then moves towards the treasure. At each turn, we have some rules: The player can stay in the same block during the next one-second time duration, or he can walk or run towards the east, south, west, north, northeast, northwest, southeast, and southwest. With walking, the player can arrive at the corresponding passable blocks around him (See Fig.1). Each move takes 1 second. With running, the player can arrive at the corresponding passable blocks 2 cells away from him (See Fig.2). Each run takes 1 second. As demonstrated in Fig.3, if a neighbor cell is not passable, the player cannot run in that direction. For example, if cell 2 is a rock, running from 1 to 3 is impossible. The monsters are classified into aggressive and non-aggressive. If a monster occupies a cell, the player cannot move into that cell or run through that cell. In addition, the player cannot move into the cells surrounding an aggressive monster, because it will attack the player near it. For example, in Fig.4, if there is an aggressive monster in 5, then the cell 1, 2, 3, 4, 6, 7, 8 and 9 are in its attacking region, so the player cannot stay in or pass through these cells. Monsters change their positions each turn. Each monster appears by its position sequence iteratively. That's to say, given the position sequence of monster i: (x1, y1), (x2, y2), ..., (xs, ys), its initial position is (x1, y1) at time 0, then it appears in (x2, y2) at time 1, and so on. When monster i arrives at (xs, ys) at time s-1, it will arrive in (x1, y1) at time s, and start to repeat. At the start of each turn, all the monsters change their positions first (the way of changing is given above). If a monster appears in the player's cell, or if an aggressive monster appears near the player to put him in its attacking region, the player will die, and the goal cannot be achieved. After all the monsters change their positions, the player makes a move or stays in the same cell. In his move, the moving path should not be occupied by any rocks or monsters or in the attacking region of any aggressive monsters. When counting the total time, we can neglect the time between monsters' position change and the player's move. Given the map of the game, the player's starting position, the treasure position and all the monsters' positions in every second, your task is to write a program to find the minimum time that the player gets the treasure. Input The input consists of several test cases. The first line of each case contains two integers N and M (1 <= N, M <= 100), where N is the height of the map and M is the width of the map. This is followed by N lines each containing M characters representing the map. A '#' represents a rock, a '.' is a free block, 'p' is the starting position of the player, 't' is the position of the treasure, 'n' is the initial position of a non-aggressive monster, and an 'a' stands for the initial position of an aggressive monster. The cell (i, j) is the j-th cell on the i-th row counting from left to right. The rows are counted from 1 to N starting from the first line of the matrix. We can number all the monsters as 1, 2, 3… according to their initial position, sorting first by row, then by column. The (n+2)-th line contains an integer p (0 <= p <= 100), which is the total number of monsters (i.e. the total number of 'n's and 'a's in the matrix). It is followed by p lines each specifying a monster's position sequence in the following format: the i-th (1 <= i <= p) line corresponds to monster i, which begins with an integer s (1 <= s <= 100), meaning the length of position sequence. Then s pairs of integers x1, y1, x2, y2, …, xs, ys are followed, separated by blanks. Each pair is a free block in the map, (i.e. a monster never goes to a rock cell). It is assured that none of the aggressive monsters' initial position is around the player. Two consecutive cases are separated by a blank line. The input is terminated by a line containing a pair of zeros. Output For each test case, output the minimum total time required for the player to get the treasure, in seconds. If it's not possible to get the treasure, or the minimum required time is greater than 100 seconds, please print a line just containing the string "impossible". Two consecutive cases should be separated by a blank line. Sample Input 7 8 #.#####. #.t#..p. #..#.... ..#a.#.# #...##.n .#...... ........ 2 2 4 4 5 4 3 5 8 6 8 5 7 3 3 p#. ##. t.. 0 2 2 #t p# 0 0 0 Sample Output 8 impossible 1 Hint In the first sample case, the player can follow (2,7), (4,7), stay in (4,7), (6,7), (7,6), (7,4), (5,2), (3,2) and (2,3) to get the treasure with the minimum time (8 seconds). Source Beijing 2004 Preliminary@POJ Finding Nemo Time Limit: 2000MS Memory Limit: 30000K Total Submissions: 5017 Accepted: 1074 Description Nemo is a naughty boy. One day he went into the deep sea all by himself. Unfortunately, he became lost and couldn't find his way home. Therefore, he sent a signal to his father, Marlin, to ask for help. After checking the map, Marlin found that the sea is like a labyrinth with walls and doors. All the walls are parallel to the X-axis or to the Y-axis. The thickness of the walls are assumed to be zero. All the doors are opened on the walls and have a length of 1. Marlin cannot go through a wall unless there is a door on the wall. Because going through a door is dangerous (there may be some virulent medusas near the doors), Marlin wants to go through as few doors as he could to find Nemo. Figure-1 shows an example of the labyrinth and the path Marlin went through to find Nemo. We assume Marlin's initial position is at (0, 0). Given the position of Nemo and the configuration of walls and doors, please write a program to calculate the minimum number of doors Marlin has to go through in order to reach Nemo. Input The input consists of several test cases. Each test case is started by two non-negative integers M and N. M represents the number of walls in the labyrinth and N represents the number of doors. Then follow M lines, each containing four integers that describe a wall in the following format: xydt (x, y) indicates the lower-left point of the wall, d is the direction of the wall -- 0 means it's parallel to the X-axis and 1 means that it's parallel to the Y-axis, and t gives the length of the wall. The coordinates of two ends of any wall will be in the range of [1,199]. Then there are N lines that give the description of the doors: xyd x, y, d have the same meaning as the walls. As the doors have fixed length of 1, t is omitted. The last line of each case contains two positive float numbers: f1 f2 (f1, f2) gives the position of Nemo. And it will not lie within any wall or door. A test case of M = -1 and N = -1 indicates the end of input, and should not be processed. Output For each test case, in a separate line, please output the minimum number of doors Marlin has to go through in order to rescue his son. If he can't reach Nemo, output -1. Sample Input 8 9 1 1 1 3 2 1 1 3 3 1 1 3 4 1 1 3 1 1 0 3 1 2 0 3 1 3 0 3 1 4 0 3 2 1 1 2 2 1 2 3 1 3 1 1 3 2 1 3 3 1 1 2 0 3 3 0 4 3 1 1.5 1.5 4 0 1 1 0 1 1 1 1 1 2 1 1 1 1 2 0 1 1.5 1.7 -1 -1 Sample Output 5 -1 Source Beijing 2004 Doors and... more doors Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 256 Accepted: 137 Special Judge Description When wondering through the labyrinth, the goal is usually to find some kind of door. Well, not this time. A labyrinth consists of N × N cells, each 1 × 1 meter in size. Cells are separated by doors. Each door opens in a specific direction (as shown on the picture): 1. left outwards; 2. left inwards; 3. right outwards; 4. right inwards. So a cell can be represented by two numbers describing doors on its eastern and southern sides according to the list above. The doors are just slightly less then 1 meter in width. The traveler in the labyrinth is also slightly less then 1 meter in diameter, so he has following limitations: * He can not pull doors, only push them. * After opening the door and entering the cell it leads to, he can not take a turn in the direction where the door opened, because the passage is blocked by the door. Doors have springs and close automatically when traveler leaves the cell. Your program must find the shortest path for the traveler from north-western cell (1, 1) to south-eastern cell (N, N). Input Input file contains labyrinth size N followed by 2 × N2 numbers describing doors for each cell row by row. As there are no doors leading outside of labyrinth, values for eastern doors in the last column and southern doors in the last row are zero. Constraints 1 ≤ N ≤ 1000 Output Output file must contain the shortest path as a list of cell coordinates (column number, then row number), including both (1, 1) and (N, N) cells. If there are several solutions with the same length, output any one of them. If it is impossible to get to a destination cell, output a singe zero. Sample Input Sample Input 1 2 2 3 0 4 1 0 0 0 Sample Input 2 3 4 3 1 4 0 1 3 3 2 3 0 4 2 0 1 0 0 0 Sample Output Sample Output 1 1 1 1 2 2 2 Sample Output 2 1 1 1 2 2 2 2 1 3 1 3 2 2 2 2 3 3 3 Hint Bold texts appearing in the sample sections are informative and do not form part of the actual data. Source Northeastern Europe 2006, Far-Eastern Subregion Hang or not to hang Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 390 Accepted: 119 Description Little Tom is learning how to program. He has just written some programs but is afraid to run them, because he does not know if they will ever stop. Please write a program to help him. This task is not as easy as it may seem, because Tom's programs are possibly not deterministic. Given a program written by Tom, your program should tell him whether his program can stop and if so, what is the shortest possible time before it stops. Tom's computer consists of 32 1-bit registers and the program consists of n instructions. The registers are numbered from 0 to 31 and the instructions are numbered from 0 to n-1. Below, MEM[a] stands for the contents of the a-th register, 0 <= a, b < 32, 0 <= x < n, 0 <= c <= 1. The instruction set is as follows: Instruction Semantics AND a b OR a b XOR a b NOT a MOV a b SET a c RANDOM a MEM[a] := MEM[a] and MEM[b] MEM[a] := MEM[a] or MEM[b] MEM[a] := MEM[a] xor MEM[b] MEM[a] := not MEM[a] MEM[a] := MEM[b] MEM[a] := c MEM[a] := random value (0 or 1) JMP x JZ x a STOP jump to the instruction with the number x jump to the instruction with the number x if MEM[a] = 0 stop the program The last instruction of a program is always STOP (although there can be more than one STOP instruction). Every program starts with the instruction number 0. Before the start, the contents of the registers can be arbitrary values. Each instruction (including STOP) takes 1 processor cycle to execute. Task Write a program that: reads the program, computes the shortest possible running time of the program, writes the result. Input The first line of the input contains an integer n (1 <= n <= 16) being the number of instructions of the program. Each of the next n lines contains one instruction of the program in the format given above. You may assume that the only white characters in the program are single spaces between successive tokens of each instruction. Output The first and only line of the output should contain the shortest possible running time of the program, measured in processor cycles. If the program cannot stop, output should contain the word HANGS. Sample Input 5 SET 0 1 JZ 4 0 RANDOM 0 JMP 1 STOP Sample Output 6 Source Central Europe 2003 聪明的打字员 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 3733 Accepted: 764 Description 阿兰是某机密部门的打字员,她现在接到一个任务:需要在一天之内输入几百个长度固定为 6 的密码。当然,她希望输 入的过程中敲击键盘的总次数越少越好。 不幸的是,出于保密的需要,该部门用于输入密码的键盘是特殊设计的,键盘上没有数字键,而只有以下六个键:Swap0, Swap1, Up, Down, Left, Right,为了说明这 6 个键的作用,我们先定义录入区的 6 个位置的编号,从左至右依次为 1,2, 3,4,5,6。下面列出每个键的作用: Swap0:按 Swap0,光标位置不变,将光标所在位置的数字与录入区的 1 号位置的数字(左起第一个数字)交换。如果光 标已经处在录入区的 1 号位置,则按 Swap0 键之后,录入区的数字不变; Swap1:按 Swap1,光标位置不变,将光标所在位置的数字与录入区的 6 号位置的数字(左起第六个数字)交换。如果光 标已经处在录入区的 6 号位置,则按 Swap1 键之后,录入区的数字不变; Up:按 Up,光标位置不变,将光标所在位置的数字加 1(除非该数字是 9) 。例如,如果光标所在位置的数字为 2,按 Up 之后,该处的数字变为 3;如果该处数字为 9,则按 Up 之后,数字不变,光标位置也不变; Down:按 Down,光标位置不变,将光标所在位置的数字减 1(除非该数字是 0),如果该处数字为 0,则按 Down 之后, 数字不变,光标位置也不变; Left:按 Left,光标左移一个位置,如果光标已经在录入区的 1 号位置(左起第一个位置)上,则光标不动; Right:按 Right,光标右移一个位置,如果光标已经在录入区的 6 号位置(左起第六个位置)上,则光标不动。 当然,为了使这样的键盘发挥作用,每次录入密码之前,录入区总会随机出现一个长度为 6 的初始密码,而且光标固定 出现在 1 号位置上。当巧妙地使用上述六个特殊键之后,可以得到目标密码,这时光标允许停在任何一个位置。 现在,阿兰需要你的帮助,编写一个程序,求出录入一个密码需要的最少的击键次数。 Input 仅一行,含有两个长度为 6 的数,前者为初始密码,后者为目标密码,两个密码之间用一个空格隔开。 Output 仅一行,含有一个正整数,为最少需要的击键次数。 Sample Input 123456 654321 Sample Output 11 Source Noi 01 A Dicey Problem Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 601 Accepted: 232 Description The three-by-three array in Figure 1 is a maze. A standard six-sided die is needed to traverse the maze (the layout of a standard six-sided die is shown in Figure 2). Each maze has an initial position and an initial die configuration. In Figure 1, the starting position is row 1, column 2-the "2" in the top row of the maze-and the initial die configuration has the "5" on top of the die and the "1" facing the player (assume the player is viewing the maze from the bottom edge of the figure). To move through the maze you must tip the die over on an edge to land on an adjacent square, effecting horizontal or vertical movement from one square to another. However, you can only move onto a square that contains the same number as the number displayed on the top of the die before the move, or onto a "wild" square which contains a star. Movement onto a wild square is always allowed regardless of the number currently displayed on the top of the die. The goal of the maze is to move the die off the starting square and to then find a way back to that same square. For example, at the beginning of the maze there are two possible moves. Since the 5 is on top of the die, it is possible to move down one square, and since the square to the left of the starting position is wild it is also possible to move left. If the first move chosen is to move down, this brings the 6 to the top of the die and moves are now possible both to the right and down. If the first move chosen is instead to the left, this brings the 3 to the top of the die and no further moves are possible. If we consider maze locations as ordered pairs of row and column numbers (row, column) with row indexes starting at 1 for the top row and increasing toward the bottom, and column indexes starting at 1 for the left column and increasing to the right, the solution to this simple example maze can be specified as: (1,2), (2,2), (2,3), (3,3), (3,2), (3,1), (2,1), (1,1), (1,2). A bit more challenging example maze is shown in Figure 3. The goal of this problem is to write a program to solve dice mazes. The input file will contain several mazes for which the program should search for solutions. Each maze will have either a unique solution or no solution at all. That is, each maze in the input may or may not have a solution, but those with a solution are guaranteed to have only one unique solution. For each input maze, either a solution or a message indicating no solution is possible will be sent to the output. Input The input file begins with a line containing a string of no more than 20 non-blank characters that names the first maze. The next line contains six integers delimited by single spaces. These integers are, in order, the number of rows in the maze (an integer from 1 to 10, call this value R), the number of columns in the maze (an integer from 1 to 10, call this value C), the starting row, the starting column, the number that should be on top of the die at the starting position, and finally the number that should be facing you on the die at the starting position. The next R lines contain C integers each, again delimited by single spaces. This R * C array of integers defines the maze. A value of zero indicates an empty location in the maze (such as the two empty squares in the center column of the maze in Figure 3), and a value of -1 indicates a wild square. This input sequence is repeated for each maze in the input. An input line containing only the word "END" (without the quotes) as the name of the maze marks the end of the input. Output The output should contain the name of each maze followed by its solution or the string "No Solution Possible" (without the quotes). All lines in the output file except for the maze names should be indented exactly two spaces. Maze names should start in the leftmost column. Solutions should be output as a comma-delimited sequence of the consecutive positions traversed in the solution, starting and ending with the same square (the starting square as specified in the input). Positions should be specified as ordered pairs enclosed in parentheses. The solution should list 9 positions per line (with the exception of the last line of the solution for which there may not be a full 9 positions to list), and no spaces should be present within or between positions. Sample Input DICEMAZE1 3 3 1 2 5 1 -1 2 4 5 5 6 6 -1 -1 DICEMAZE2 4 7 2 6 3 6 6 4 6 0 2 6 4 1 2 -1 5 3 6 1 5 3 4 5 6 4 2 4 1 2 0 3 -1 6 DICEMAZE3 3 3 1 1 2 4 2 2 3 4 5 6 -1 -1 -1 END Sample Output DICEMAZE1 (1,2),(2,2),(2,3),(3,3),(3,2),(3,1),(2,1),(1,1),(1,2) DICEMAZE2 (2,6),(2,5),(2,4),(2,3),(2,2),(3,2),(4,2),(4,1),(3,1), (2,1),(2,2),(2,3),(2,4),(2,5),(1,5),(1,6),(1,7),(2,7), (3,7),(4,7),(4,6),(3,6),(2,6) DICEMAZE3 No Solution Possible Source World Finals 1999 Holedox Moving Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 8351 Accepted: 1987 Description During winter, the most hungry and severe time, Holedox sleeps in its lair. When spring comes, Holedox wakes up, moves to the exit of its lair, comes out, and begins its new life. Holedox is a special snake, but its body is not very long. Its lair is like a maze and can be imagined as a rectangle with n*m squares. Each square is either a stone or a vacant place, and only vacant places allow Holedox to move in. Using ordered pair of row and column number of the lair, the square of exit located at (1,1). Holedox's body, whose length is L, can be represented block by block. And let B1(r1,c1) B2(r2,c2) .. BL(rL,cL) denote its L -1, and B1 is its head, BL is its tail. To move in the lair, Holedox chooses an adjacent vacant square of its head, which is neither a stone nor occupied by its body. Then it moves the head into the vacant square, and at the same time, each other block of its body is moved into the square occupied by the corresponding previous block. For example, in the Figure 2, at the beginning the body of Holedox can be represented as B1(4,1) B2(4,2) B3(3,2)B4(3,1). During the next step, observing that B1'(5,1) is the only square that the head can be moved into, Holedox moves its head into B1'(5,1), then moves B2 into B1, B3 into B2, and B4 into B3. Thus after one step, the body of Holedox locates in B1(5,1)B2(4,1)B3(4,2) B4(3,2) (see the Figure 3). Given the map of the lair and the original location of each block of Holedox's body, your task is to write a program to tell the minimal number of steps that Holedox has to take to move its head to reach the square of exit (1,1). Input The input consists of several test cases. The first line of each case contains three integers n, m (1<=n, m<=20) and L (2<=L<=8), representing the number of rows in the lair, the number of columns in the lair and the body length of Holedox, respectively. The next L lines contain a pair of row and column number each, indicating the original position of each block of Holedox's body, from B1(r1,c1) to BL(rL,cL) orderly, where 1<=ri<=n, and 1<=ci<=m,1<=i<=L. The next line contains an integer K, representing the number of squares of stones in the lair. The following K lines contain a pair of row and column number each, indicating the location of each square of stone. Then a blank line follows to separate the cases. The input is terminated by a line with three zeros. Note: Bi is always adjacent to Bi+1 (1<=i<=L-1) and exit square (1,1) will never be a stone. Output For each test case output one line containing the test case number followed by the minimal number of steps Holedox has to take. "-1" means no solution for that case. Sample Input 5 4 4 3 3 3 2 3 3 6 4 1 2 2 1 4 2 1 1 4 4 3 3 4 3 3 4 2 4 4 2 2 3 4 1 2 4 2 0 0 0 Sample Output Case 1: 9 Case 2: -1 Hint In the above sample case, the head of Holedox can follows (4,1)->(5,1)->(5,2)->(5,3)->(4,3)->(4,2)->(4,1)->(3,1)->(2,1)->(1,1) to reach the square of exit with minimal number of step, which is nine. Source Beijing 2002 Gap Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 1267 Accepted: 584 Description Let's play a card game called Gap. You have 28 cards labeled with two-digit numbers. The first digit (from 1 to 4) represents the suit of the card, and the second digit (from 1 to 7) represents the value of the card. First, you shu2e the cards and lay them face up on the table in four rows of seven cards, leaving a space of one card at the extreme left of each row. The following shows an example of initial layout. Next, you remove all cards of value 1, and put them in the open space at the left end of the rows: "11" to the top row, "21" to the next, and so on. Now you have 28 cards and four spaces, called gaps, in four rows and eight columns. You start moving cards from this layout. At each move, you choose one of the four gaps and fill it with the successor of the left neighbor of the gap. The successor of a card is the next card in the same suit, when it exists. For instance the successor of "42" is "43", and "27" has no successor. In the above layout, you can move "43" to the gap at the right of "42", or "36" to the gap at the right of "35". If you move "43", a new gap is generated to the right of "16". You cannot move any card to the right of a card of value 7, nor to the right of a gap. The goal of the game is, by choosing clever moves, to make four ascending sequences of the same suit, as follows. Your task is to find the minimum number of moves to reach the goal layout. Input The input starts with a line containing the number of initial layouts that follow. Each layout consists of five lines - a blank line and four lines which represent initial layouts of four rows. Each row has seven two-digit numbers which correspond to the cards. Output For each initial layout, produce a line with the minimum number of moves to reach the goal layout. Note that this number should not include the initial four moves of the cards of value 1. If there is no move sequence from the initial layout to the goal layout, produce "-1". Sample Input 4 12 22 32 42 13 23 33 43 14 24 34 44 15 25 35 45 16 26 36 46 17 27 37 47 21 31 41 11 26 17 46 16 31 45 34 43 13 23 14 27 44 25 12 35 21 41 37 22 24 36 32 33 42 11 47 15 17 27 37 47 12 22 32 42 16 26 36 46 13 23 33 43 15 25 35 45 14 24 34 44 11 21 31 41 27 13 43 25 14 17 16 37 22 36 45 41 35 24 47 34 32 44 23 42 46 21 11 12 33 15 26 31 Sample Output 0 33 60 -1 Source Japan 2003,Aizu It's not a Bug, It's a Feature! Time Limit: 5000MS Memory Limit: 30000K Total Submissions: 869 Accepted: 330 Description It is a curious fact that consumers buying a new software product generally do not expect the software to be bug-free. Can you imagine buying a car whose steering wheel only turns to the right? Or a CD-player that plays only CDs with country music on them? Probably not. But for software systems it seems to be acceptable if they do not perform as they should do. In fact, many software companies have adopted the habit of sending out patches to fix bugs every few weeks after a new product is released (and even charging money for the patches). Tinyware Inc. is one of those companies. After releasing a new word processing software this summer, they have been producing patches ever since. Only this weekend they have realized a big problem with the patches they released. While all patches fix some bugs, they often rely on other bugs to be present to be installed. This happens because to fix one bug, the patches exploit the special behavior of the program due to another bug. More formally, the situation looks like this. Tinyware has found a total of n bugs B = {b1, b2, ..., bn} in their software. And they have released m patches p1, p2, ..., pm. To apply patch pi to the software, the bugs Bi+ in B have to be present in the software, and the bugs Bi- in B must be absent (of course Bi+ ∩ Bi- = Φ). The patch then fixes the bugs Fi- in B (if they have been present) and introduces the new bugs Fi+ in B (where, again, Fi+ ∩ Fi- = Φ). Tinyware's problem is a simple one. Given the original version of their software, which contains all the bugs in B, it is possible to apply a sequence of patches to the software which results in a bug- free version of the software? And if so, assuming that every patch takes a certain time to apply, how long does the fastest sequence take? Input The input contains several product descriptions. Each description starts with a line containing two integers n and m, the number of bugs and patches, respectively. These values satisfy 1 <= n <= 20 and 1 <= m <= 100. This is followed by m lines describing the m patches in order. Each line contains an integer, the time in seconds it takes to apply the patch, and two strings of n characters each. The first of these strings describes the bugs that have to be present or absent before the patch can be applied. The i-th position of that string is a ``+'' if bug bi has to be present, a ``-'' if bug bi has to be absent, and a `` 0'' if it doesn't matter whether the bug is present or not. The second string describes which bugs are fixed and introduced by the patch. The i-th position of that string is a ``+'' if bug bi is introduced by the patch, a ``-'' if bug bi is removed by the patch (if it was present), and a ``0'' if bug bi is not affected by the patch (if it was present before, it still is, if it wasn't, is still isn't). The input is terminated by a description starting with n = m = 0. This test case should not be processed. Output For each product description first output the number of the product. Then output whether there is a sequence of patches that removes all bugs from a product that has all n bugs. Note that in such a sequence a patch may be used multiple times. If there is such a sequence, output the time taken by the fastest sequence in the format shown in the sample output. If there is no such sequence, output ``Bugs cannot be fixed.''. Print a blank line after each test case. Sample Input 3 1 1 2 4 7 0 3 000 0000- 0-+ 0-- -++ 1 0-0+ ---0 Sample Output Product 1 Fastest sequence takes 8 seconds. Product 2 Bugs cannot be fixed. Source Southwestern European Regional Contest 1998 Cubic Eight-Puzzle Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 1007 Accepted: 345 Description Let’s play a puzzle using eight cubes placed on a 3 × 3 board leaving one empty square. Faces of cubes are painted with three colors. As a puzzle step, you can roll one of the cubes to a adjacent empty square. Your goal is to make the specified color pattern visible from above by a number of such steps. The rules of this puzzle are as follows. 1. Coloring of Cubes: All the cubes area colored in the same way as shown in Figure 1. The opposite faces have the same color. Figure 1: Coloring of a cube 2. Initial Board State: Eight cubes are placed on the 3 × 3 board leaving one empty square. All the cubes have the same orientation as shown in Figure 2. As shown in the figure, squares on the board are given x and y coordinates, (1, 1), (1, 2), …, and (3, 3). The position of the initially empty square may vary. Figure 2: Initial board state 3. Rolling Cubes: At each step, we can choose one of the cubes adjacent to the empty square and roll it into the empty square, leaving the original position empty. Figure 3 shows an example. Figure 3: Rolling a cube 4. Goal: The goal of this puzzle is to arrange the cubes so that their top faces form the specified color pattern by a number of cube rolling steps described above. Your task is to write a program that finds the minimum number of steps required to make the specified color pattern from the given initial state. Input The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. The number of datasets is less than 16. Each dataset is formatted as follows. x y F11 F21 F31 F12 F22 F32 F13 F23 F33 The first line contains two integers x and y separated by a space, indicating the position (x, y) of the initially empty square. The values of x and y are 1, 2, or 3. The following three lines specify the color pattern to make. Each line contains three characters F1j, F2j, and F3j, separated by a space. Character Fij indicates the top color of the cube, if any, at the position (i, j) as follows: B: Blue, W: White, R: Red, E: the square is Empty. There is exactly one ‘E’ character in each dataset. Output For each dataset, output the minimum number of steps to achieve the goal, when the goal can be reached within 30 steps. Otherwise, output “-1” for the dataset. Sample Input 1 W E W 2 R R 2 W W W 1 B W W W W W W E 3 W B R 3 B B B 2 B B B 1 R W R 2 R B R 3 R W R 0 W 3 B R B 3 W W E 1 B R R 1 R W R 1 R W R 2 R E R 0 W W E R R R R B B E R W E R B E R W R Sample Output 0 3 13 23 29 30 -1 -1 Source Japan 2006 Light Up Description Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 454 Accepted: 180 Light Up is a puzzle set in a rectangular board divided in smaller squares. Some squares in the board are ``empty'' (white squares the figure below), some squares are ``barriers'' (dark squares in the figure below). A barrier square may have an integer number i associated to it (0 <= i <= 4). Figure 2: (a) Puzzle with 6 rows, 7 columns and 7 barriers; (b) a solution to the puzzle. In this puzzle the goal is to ``light up'' all the empty squares by placing lamps in some of them (lamps are depicted as circles in the figure). Each lamp illuminates the square it is on, plus all squares in line with it, horizontally or vertically, up to a barrier square or the board end. A winning configuration satisfies the following conditions: all empty squares must be lit; no lamp may be lit by another lamp; all numbered barrier squares must have exactly that number of lamps adjacent to them (in the four squares above, below, and to the side); non-numbered barrier squares may have any number of lamps adjacent to them. You must write a program to determine the smallest number of lamps that are needed to reach a winning configuration. Input The input contains several test cases. The first line of a test case contains two integers N, M indicating respectively the number of rows and the number of columns of the board (1 <= N <= 7, 1 <= M <= 7). The second line contains one integer B indicating the number of barrier squares (0 <= B <= N × M). Each of the next B lines describe a barrier, containing three integers R, C and K, representing respectively the row number (1 <= R <= N), the column number (1 <= C <= M) and the barrier number (-1 <= K <= 4); K = -1 means the barrier is unnumbered. The end of input is indicated by N = M = 0. Output For each test case in the input your program must produce one line of output, containing either an integer indicating the smallest number of lamps needed to reach a winning configuration, in case such a configuration exists, or the words `No solution'. Sample Input 2 2 0 2 1 2 6 7 2 3 4 5 5 1 6 0 2 2 1 7 3 3 2 4 6 7 5 0 -1 0 1 3 2 -1 -1 Sample Output 2 No solution 8 Source South America 2005 The Rotation Game Time Limit: 15000MS Memory Limit: 150000K Total Submissions: 3322 Accepted: 1098 Description The rotation game uses a # shaped board, which can hold 24 pieces of square blocks (see Fig.1). The blocks are marked with symbols 1, 2 and 3, with exactly 8 pieces of each kind. Initially, the blocks are placed on the board randomly. Your task is to move the blocks so that the eight blocks placed in the center square have the same symbol marked. There is only one type of valid move, which is to rotate one of the four lines, each consisting of seven blocks. That is, six blocks in the line are moved towards the head by one block and the head block is moved to the end of the line. The eight possible moves are marked with capital letters A to H. Figure 1 illustrates two consecutive moves, move A and move C from some initial configuration. Input The input consists of no more than 30 test cases. Each test case has only one line that contains 24 numbers, which are the symbols of the blocks in the initial configuration. The rows of blocks are listed from top to bottom. For each row the blocks are listed from left to right. The numbers are separated by spaces. For example, the first test case in the sample input corresponds to the initial configuration in Fig.1. There are no blank lines between cases. There is a line containing a single `0' after the last test case that ends the input. Output For each test case, you must output two lines. The first line contains all the moves needed to reach the final configuration. Each move is a letter, ranging from `A' to `H', and there should not be any spaces between the letters in the line. If no moves are needed, output `No moves needed' instead. In the second line, you must output the symbol of the blocks in the center square after these moves. If there are several possible solutions, you must output the one that uses the least number of moves. If there is still more than one possible solution, you must output the solution that is smallest in dictionary order for the letters of the moves. There is no need to output blank lines between cases. Sample Input 1 1 1 1 3 2 3 2 3 1 3 2 2 3 1 2 2 2 3 1 2 1 3 3 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 0 Sample Output AC 2 DDHH 2 Source Shanghai 2004 Similarity of necklaces 2 Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 369 Accepted: 90 Description The background knowledge of this problem comes from "Similarity of necklaces". Do not worry. I will bring you all the information you need. The little cat thinks about the problem he met again, and turns that problem into a fair new one, by putting N * (N + 1) / 2 elements into a linear list, with M = N * (N + 1) / 2 elements: (The above table denotes Table and Pairs in description of after converting) One more array named "Multi" appears here. Suppose Pairs and Multi are given, the little cat's purpose is to determine an array Table with M integers that obey: (this condition is similar with the condition that appears in the problem "Similarity of necklaces") and make as large as possible. What is more, we must have Low[i] <= Table[i] <= Up[i] for any 1 <= i <= M. Here Low and Up are two more arrays with M integers given to you. Input The input contains a number of test cases. Each of the following blocks denotes a single test case. A test case starts by an integer M (1 <= M <= 200) and M lines followed. The i-th line followed contains four integers: Pairs[i], Multi[i], Low[i], Up[i]. Restrictions: -25 <= Low[i] < Up[i] <= 25, 0 <= Pairs[i] <= 100000, 1 <= Multi[i] <= 20. From the input given, you may assume that there is always a solution. Output For each test case, output a single line with a single number, which is the largest Sample Input 10 7 1 1 10 0 2 -10 10 2 0 0 0 0 0 0 0 2 2 1 2 2 1 2 1 -10 10 -10 10 1 10 -10 10 -10 10 1 10 -10 10 1 10 10 0 1 2 2 2 2 2 2 0 1 2 2 2 2 0 1 2 2 0 1 1 10 -10 10 -10 10 -10 10 1 10 -10 10 -10 10 1 10 -10 10 1 10 Sample Output 90 -4 Source POJ Monthly--2006.01.22,Zeyuan Zhu Crazy Thairs Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 4723 Accepted: 1139 Description These days, Sempr is crazed on one problem named Crazy Thair. Given N (1 ≤ N ≤ 50000) numbers, which are no more than 109, Crazy Thair is a group of 5 numbers {i, j, k, l, m} satisfying: 1. 1 ≤ i < j < k < l < m ≤ N 2. Ai < Aj < Ak < Al < Am For example, in the sequence {2, 1, 3, 4, 5, 7, 6},there are four Crazy Thair groups: {1, 3, 4, 5, 6}, {2, 3, 4, 5, 6}, {1, 3, 4, 5, 7} and {2, 3, 4, 5, 7}. Could you help Sempr to count how many Crazy Thairs in the sequence? Input Input contains several test cases. Each test case begins with a line containing a number N, followed by a line containing N numbers. Output Output the amount of Crazy Thairs in each sequence. Sample Input 5 1 2 3 4 5 7 2 1 3 4 5 7 6 7 1 2 3 4 5 6 7 Sample Output 1 4 21 Source POJ Monthly--2007.09.09, tdzl2003 Cut the Sequence Time Limit: 2000MS Memory Limit: 131072K Total Submissions: 4057 Accepted: 1067 Description Given an integer sequence { an } of length N, you are to cut the sequence into several parts every one of which is a consecutive subsequence of the original sequence. Every part must satisfy that the sum of the integers in the part is not greater than a given integer M. You are to find a cutting that minimizes the sum of the maximum integer of each part. Input The first line of input contains two integer N (0 < N ≤ 100 000), M. The following line contains N integers describes the integer sequence. Every integer in the sequence is between 0 and 1 000 000 inclusively. Output Output one integer which is the minimum sum of the maximum integer of each part. If no such cuttings exist, output −1. Sample Input 8 17 2 2 2 8 1 8 2 1 Sample Output 12 Hint Use 64-bit integer type to hold M. Source POJ Monthly--2006.09.29, zhucheng Manhattan Wiring Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 729 Accepted: 397 Description There is a rectangular area containing n × m cells. Two cells are marked with “2”, and another two with “3”. Some cells are occupied by obstacles. You should connect the two “2”s and also the two “3”s with non-intersecting lines. Lines can run only vertically or horizontally connecting centers of cells without obstacles. Lines cannot run on a cell with an obstacle. Only one line can run on a cell at most once. Hence, a line cannot intersect with the other line, nor with itself. Under these constraints, the total length of the two lines should be minimized. The length of a line is defined as the number of cell borders it passes. In particular, a line connecting cells sharing their border has length 1. Fig. 1(a) shows an example setting. Fig. 1(b) shows two lines satisfying the constraints above with minimum total length 18. Figure 1: An example of setting and its solution Input The input consists of multiple datasets, each in the following format. n m row1 … rown n is the number of rows which satisfies 2 ≤ n ≤ 9. m is the number of columns which satisfies 2 ≤ m ≤ 9. Each rowi is a sequence of m digits separated by a space. The digits mean the following. 0: Empty 1: Occupied by an obstacle 2: Marked with “2” 3: Marked with “3” The end of the input is indicated with a line containing two zeros separated by a space. Output For each dataset, one line containing the minimum total length of the two lines should be output. If there is no pair of lines satisfying the requirement, answer “0” instead. No other characters should be contained in the output. Sample Input 5 0 0 2 1 5 0 0 0 0 0 0 2 1 0 3 0 1 0 0 0 1 0 2 2 0 6 2 0 0 1 0 0 5 0 0 0 0 0 9 3 0 0 0 0 0 0 0 2 9 0 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 0 0 0 0 3 2 3 5 0 3 0 1 0 0 9 0 0 2 0 0 9 0 0 0 0 0 0 0 0 0 9 0 2 0 0 0 0 0 0 0 9 0 3 0 0 0 0 0 0 0 0 0 0 3 0 3 0 0 0 1 0 2 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 2 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 2 Sample Output 18 2 17 12 0 52 43 Source Japan 2006 Magic Bracelet Time Limit: 2000MS Memory Limit: 131072K Total Submissions: 1877 Accepted: 597 Description Ginny’s birthday is coming soon. Harry Potter is preparing a birthday present for his new girlfriend. The present is a magic bracelet which consists of n magic beads. The are m kinds of different magic beads. Each kind of beads has its unique characteristic. Stringing many beads together a beautiful circular magic bracelet will be made. As Harry Potter’s friend Hermione has pointed out, beads of certain pairs of kinds will interact with each other and explode, Harry Potter must be very careful to make sure that beads of these pairs are not stringed next to each other. There infinite beads of each kind. How many different bracelets can Harry make if repetitions produced by rotation around the center of the bracelet are neglected? Find the answer taken modulo 9973. Input The first line of the input contains the number of test cases. Each test cases starts with a line containing three integers n (1 ≤ n ≤ 109, gcd(n, 9973) = 1), m (1 ≤ m ≤ 10), k (1 ≤ k ≤ m(m − 1) ⁄ 2). The next k lines each contain two integers a and b (1 ≤ a, b ≤ m), indicating beads of kind a cannot be stringed to beads of kind b. Output Output the answer of each test case on a separate line. Sample Input 4 3 2 0 3 2 1 1 2 3 1 1 3 1 1 2 2 2 1 2 2 3 1 2 2 Sample Output 4 2 1 0 Source POJ Monthly--2006.07.30, cuiaoxiang Color Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 2938 Accepted: 1008 Description Beads of N colors are connected together into a circular necklace of N beads (N<=1000000000). Your job is to calculate how many different kinds of the necklace can be produced. You should know that the necklace might not use up all the N colors, and the repetitions that are produced by rotation around the center of the circular necklace are all neglected. You only need to output the answer module a given number P. Input The first line of the input is an integer X (X <= 3500) representing the number of test cases. The following X lines each contains two numbers N and P (1 <= N <= 1000000000, 1 <= P <= 30000), representing a test case. Output For each test case, output one line containing the answer. Sample Input 5 1 30000 2 30000 3 30000 4 30000 5 30000 Sample Output 1 3 11 70 629 Source POJ Monthly,Lou Tiancheng Stake Your Claim Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 867 Accepted: 304 Description The designers at Gazillion Games Inc. have come up with a new, relatively simple game called "Stake Your Claim". Two players – 0 and 1 – initially select two values n and m and an n × n board is created with m 0's and m 1's randomly placed on the board. Starting with player 0, each player puts his/her number in one of the empty squares on the board. After the board is filled, each player's score is equal to the largest connected region on the board filled with that player's number (where a connected region is one where for any two squares in the region a path exists consisting of only N/S/E/W moves). The player with the highest score wins, and is awarded the difference between his/her score and the score of the other player. Two examples of finished games are shown below, with the largest connected regions for each player outlined. Note in the second example that the two sections with 2 0's each are not connected. In order to test how good this game is, the gang at Gazillion has hired you to write a program which can play the game. Specifically, given any starting configuration, they would like a program to determine the best move for the current player, i.e., the score which maximizes the points awarded to that player (or minimizes those awarded to the player's opponent). Input Input will consist of multiple test cases. Each test case will start with a line containing a positive integer n (≤ 8) indicating the size of the board. Next will come n lines describing the current board layout (row 0 first, followed by row 1, etc). Each of these lines will contain n characters taken from '0', '1' and '.', where '.' represents an empty square. The first character will be in column 0, the second in column 1, etc. The number of 0's on the board will either be equal to the number of 1's or one greater, and there will be between 1 and 10 (inclusive) empty squares. The last case is followed by a line containing 0 which indicates end-of-input and should not be processed. Output For each test case, output a single line containing two items: the coordinates of the best move for the player and the best point total achieved by that player. In case of ties, print the move which comes first lexicographically. Use the format shown in the sample output. Sample Input 4 01.1 00.. .01. ...1 4 0.01 0.01 1..0 .1.. 0 Sample Output (1,2) 2 (2,2) -1 Source East Central North America 2006 Triangle War Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1514 Accepted: 609 Description Triangle War is a two-player game played on the following triangular grid: Two players, A and B, take turns filling in any dotted line connecting two dots, with A starting first. Once a line is filled, it cannot be filled again. If the line filled by a player completes one or more triangles, she owns the completed triangles and she is awarded another turn (i.e. the opponent skips a turn). The game ends after all dotted lines are filled in, and the player with the most triangles wins the game. The difference in the number of triangles owned by the two players is not important. For example, if A fills in the line between 2 and 5 in the partial game on the left below: Then, she owns the triangle labelled A and takes another turn to fill in the line between 3 and 5. B can now own 3 triangles (if he wishes) by filling in the line between 2 and 3, then the one between 5 and 6, and finally the one between 6 and 9. B would then make one more move before it is A's turn again. In this problem, you are given a number of moves that have already been made. From the partial game, you should determine which player will win assuming that each player plays a perfect game from that point on. That is, assume that each player always chooses the play that leads to the best possible outcome for himself/herself. Input You will be given a number of games in the input. The first line of input is a positive integer indicating the number of games to follow. Each game starts with an integer 6 <= m <= 18 indicating the number of moves that have been made in the game. The next m lines indicate the moves made by the two players in order, each of the form i j (with i < j) indicating that the line between i and j is filled in that move. You may assume that all given moves are legal. Output For each game, print the game number and the result on one line as shown below. If A wins, print the sentence "A wins." If B wins, print "B wins." Sample Input 4 6 2 4 4 5 5 9 3 6 2 5 3 5 7 2 4 4 5 5 9 3 6 2 5 3 5 7 8 6 1 2 2 3 1 3 2 4 2 5 4 5 10 1 2 2 5 3 6 5 8 4 7 6 10 2 4 4 5 4 8 7 8 Sample Output Game Game Game Game 1: 2: 3: 4: B A A B wins. wins. wins. wins. Source East Central North America 1999 Feng Shui Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 1829 Accepted: 549 Special Judge Description Feng shui is the ancient Chinese practice of placement and arrangement of space to achieve harmony with the environment. George has recently got interested in it, and now wants to apply it to his home and bring harmony to it. There is a practice which says that bare floor is bad for living area since spiritual energy drains through it, so George purchased two similar round-shaped carpets (feng shui says that straight lines and sharp corners must be avoided). Unfortunately, he is unable to cover the floor entirely since the room has shape of a convex polygon. But he still wants to minimize the uncovered area by selecting the best placing for his carpets, and asks you to help. You need to place two carpets in the room so that the total area covered by both carpets is maximal possible. The carpets may overlap, but they may not be cut or folded (including cutting or folding along the floor border) — feng shui tells to avoid straight lines. Input The first line of the input file contains two integer numbers n and r — the number of corners in George’s room (3 ≤ n ≤ 100) and the radius of the carpets (1 ≤ r ≤ 1000, both carpets have the same radius). The following n lines contain two integers xi and yi each — coordinates of the i-th corner (−1000 ≤ xi, yi ≤ 1000). Coordinates of all corners are different, and adjacent walls of the room are not collinear. The corners are listed in clockwise order. Output Write four numbers x1, y1, x2, y2 to the output file, where (x1, y1) and (x2, y2) denote the spots where carpet centers should be placed. Coordinates must be precise up to 4 digits after the decimal point. If there are multiple optimal placements available, return any of them. The input data guarantees that at least one solution exists. Sample Input 52 -2 0 -5 3 #1 08 73 50 43 00 #2 0 8 10 8 10 0 Sample Output #1 -2 3 3 2.5 #2 3 5 7 3 Hint Source Northeastern Europe 2006, Northern Subregion Hotter Colder Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1234 Accepted: 487 Description The children's game Hotter Colder is played as follows. Player A leaves the room while player B hides an object somewhere in the room. Player A re-enters at position (0,0) and then visits various other positions about the room. When player A visits a new position, player B announces "Hotter" if this position is closer to the object than the previous position; player B announces "Colder" if it is farther and "Same" if it is the same distance. Input Input consists of up to 50 lines, each containing an x,y coordinate pair followed by "Hotter", "Colder", or "Same". Each pair represents a position within the room, which may be assumed to be a square with opposite corners at (0,0) and (10,10). Output For each line of input print a line giving the total area of the region in which the object may have been placed, to 2 decimal places. If there is no such region, output 0.00. Sample Input 10.0 10.0 Colder 10.0 0.0 Hotter 0.0 0.0 Colder 10.0 10.0 Hotter Sample Output 50.00 37.50 12.50 0.00 Source Waterloo local 2001.01.27 A safe way Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 1255 Accepted: 234 Special Judge Description There is a map of a minefield. The border of the minefield is a polygon which has not got self-intersections or self-contacts. There are two points A and B outside of this minefield or on its border. You need to find the minimum length way from A to B. Obviously the way can not cross the minefield. However, it may contact edges or vertices of the bounding polygon. Input The input consists of several lines. The first line contains four numbers XA, YA, XB and YB – the coordinates of two given points. The second line contains integer number N, 3 ≤ N ≤ 100 – the number of vertices of the bounding polygon. Finally, each of the next N lines contains a coordinates X and Y of one polygon vertex, in the counterclockwise order. All the coordinates are integer numbers between −100000 and 100000. The numbers are separated by one or more spaces. Output The output consists of one line containing the length of a shortest safe way, with the accuracy 0.0001. Sample Input 0 4 1 3 3 1 0 5 5 0 0 2 2 Sample Output 7.2361 Source Northeastern Europe 2004, Western Subregion Triangle Time Limit: 3000MS Memory Limit: 30000K Total Submissions: 4851 Accepted: 1344 Description Given n distinct points on a plane, your task is to find the triangle that have the maximum area, whose vertices are from the given points. Input The input consists of several test cases. The first line of each test case contains an integer n, indicating the number of points on the plane. Each of the following n lines contains two integer xi and yi, indicating the ith points. The last line of the input is an integer −1, indicating the end of input, which should not be processed. You may assume that 1 <= n <= 50000 and −10 4 <= xi, yi <= 104 for all i = 1 . . . n. Output For each test case, print a line containing the maximum area, which contains two digits after the decimal point. You may assume that there is always an answer which is greater than zero. Sample Input 3 3 4 2 6 2 7 5 2 6 3 9 2 0 8 0 6 5 -1 Sample Output 0.50 27.00 Source Shanghai 2004 Preliminary Inner Vertices Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 1200 Accepted: 306 Case Time Limit: 2000MS Description There is an infinite square grid. Some vertices of the grid are black and other vertices are white. A vertex V is called inner if it is both vertical-inner and horizontal-inner. A vertex V is called horizontal-inner if there are two such black vertices in the same row that V is located between them. A vertex V is called vertical-inner if there are two such black vertices in the same column that V is located between them. On each step all white inner vertices became black while the other vertices preserve their colors. The process stops when all the inner vertices are black. Write a program that calculates a number of black vertices after the process stops. Input The first line of the input file contains one integer number n (0 ≤ n ≤ 100 000) — number of black vertices at the beginning. The following n lines contain two integer numbers each — the coordinates of different black vertices. The coordinates do not exceed 109 by their absolute values. Output Output the number of black vertices when the process stops. If the process does not stop, output -1. Sample Input 4 0 2 2 0 -2 0 0 -2 Sample Output 5 Hint Source Northeastern Europe 2005, Northern Subregion Island of Logic Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 302 Accepted: 100 Description The Island of Logic has three kinds of inhabitants: divine beings that always tell the truth, evil beings that always lie, and human beings that are truthful during the day and lie at night. Every inhabitant recognizes the type of every other inhabitant. A social scientist wants to visit the island. Because he is not able to distinguish the three kinds of beings only from their looks, he asks you to provide a communication analyzer that deduces facts from conversations among inhabitants. The interesting facts are whether it is day or night and what kind of beings the speakers are. Input The input contains several descriptions of conversations. Each description starts with an integer n, the number of statements in the conversation. The following n lines each contain one statement by an inhabitant. Every statement line begins with the speaker's name, one of the capital letters A, B, C, D, E, followed by a colon `:'. Next is one of the following kinds of statements: I am [not] ( divine | human | evil | lying ). X is [not] ( divine | human | evil | lying ). It is ( day | night ). Square brackets [] mean that the word in the brackets may or may not appear, round brackets () mean that exactly one of the alternatives separated by | must appear. X stands for some name from A, B, C, D, E. There will be no two consecutive spaces in any statement line, and at most 50 statements in a conversation. The input is terminated by a test case starting with n = 0. Output For each conversation, first output the number of the conversation in the format shown in the sample output. Then print ``This is impossible.'', if the conversation cannot happen according to the rules or ``No facts are deducible.'', if no facts can be deduced. Otherwise print all the facts that can be deduced. Deduced facts should be printed using the following formats: X is ( divine | human | evil ). It is ( day | night ). X is to be replaced by a capital letter speaker name. Facts about inhabitants must be given first (in alphabetical order), then it may be stated whether it is day or night. The output for each conversation must be followed by a single blank line. Sample Input 1 A: 1 A: 1 A: 3 A: B: A: 0 I am divine. I am lying. I am evil. B is human. A is evil. B is evil. Sample Output Conversation #1 No facts are deducible. Conversation #2 This is impossible. Conversation #3 A is human. It is night. Conversation #4 A is evil. B is divine. Hint To make things clearer, we will show the reasoning behind the third input example, where A says ``I am evil.''. What can be deduced from this? Obviously A cannot be divine, since she would be lying, similarly A cannot be evil, since she would tell the truth. Therefore, A must be human, moreover, since she is lying, it must be night. So the correct output is as shown. In the fourth input example, it is obvious that A is lying since her two statements are contradictory. So, B can be neither human nor evil, and consequently must be divine. B always tells the truth, thus A must be evil. Voila! Source Southwestern European Regional Contest 1997 Random Walk Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 633 Accepted: 166 Description Random Algorithms are very popular now. For example, it's widely used in cryptography (primality test and etc.). Different from the normal definite algorithms, random algorithms may not have a definite running trace. Sometimes, it comes to some point, flips a coin, and decides where to go according to the result of the coin flipping. The following command may be such a point: x=random(1); // random(1) returns a random number from [0..1) uniformly IF x > 0.3 GOTO ... When the random program comes here, it generates a random number and assigns it to x, if x is greater than 0.3 it goes to somewhere; otherwise, it goes straight ahead. So, the program goes somewhat like a drunk man walking a long the street. You can't predict where the program should go beforehand. Your task in this problem is to create a simple Random Program Evaluator, which can calculate the expected running time of some random algorithms. A simple random program is described as follows: 1. There are several reserved words: "NOP", "IF", "GOTO", "END", "PROC", "PROG_START", and "PROG_END", case is sensitive. 2. A program starts with "PROG_START" and ends with "PROG_END". 3. A program may have one or more procedures. 4. Each procedure starts with "PROC [name]". [name] is the name of this procedure. It can be any string that only contains characters or numbers, except reserved words. 5. A procedure ends with "END;" 6. A procedure may have one or more commands ("END;" is not a command). It takes one time unit to execute one command. 7. A command is of one of the following formats: "NOP;" The program will go to execute the next line in the next time unit. "IF x>[threshold] GOTO [line number];" The program takes a value x from [0..1) randomly. If x is larger than the [threshold], the program will execute the [line number] in the next time unit, otherwise, the program execute the next line in the next time unit. "IF x<[threshold] GOTO [line number];" The program takes a value x from [0..1) randomly. If x is smaller than the [threshold], the program will execute the [line number] in the next time unit, otherwise, the program execute the next line in the next time unit. "IF x>[threshold] PROC [procedure name];" The program takes a value x from [0..1) randomly. If x is larger than the [threshold], the program will execute the procedure with [procedure name], then come back to the next line after the current command in this procedure. "IF x<[threshold] PROC [procedure name];" The program takes a value x from [0..1) randomly. If x is smaller than the [threshold], the program will execute the procedure with [procedure name], then come back to the next line after the current command in this procedure. 8. The program finishes one procedure whenever it sees the "END;". 9. In each procedure, the line number starts with 1. That is, the first command in a procedure is "line 1", the second is "line 2". "END;" is the last line in a procedure. The Evaluator takes one random program as input; return the expected runtime of some procedures upon requests, with an accuracy of 3 digits after the decimal point. To make your lives easier, we have the following simplification: 1. The condition of "IF" is always a comparison between a random variable and a constant threshold. 2. Random Variables in different "IF" clause are independent. Even there may be more than one "IF x>0.5" in one procedure, the "x"s in different commands are independent. 3. There is no loop-reference (including indirect loop reference) between different procedures. 4. For each command, the probability that the program starts from this command and ends at the end of the procedure is positive. That means, you can finally reach the end of a procedure from any command. 5. There are more than 1 and less than 100 procedures in a program 6. All the strings in this problem are within 100 characters. Input The input file contains one random program described as above with one or more random procedures, and one or more requests. The requests are following the program. Each request is a line with one string, which is the name of the requested procedure. The request list ends with a line containing "REQUEST_END" (there is no procedure with a name as "REQUEST_END") Output For each request, output a line with a number presents the expected running time of the requested procedure. The accuracy is up to 3 digits after decimal point. Sample Input PROG_START PROC A IF x>0.5 GOTO 3; NOP; END; PROC B IF x<0.5 PROC A; NOP; END; PROG_END B A REQUEST_END Sample Output 2.750 1.500 Source Beijing 2002 Robocode Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 622 Accepted: 113 Description Robocode is an educational game designed to help learn Java. The players write programs that control tanks fighting with each other on a battlefield. The idea of this game may seem simple, but it takes a lot of effort to write a winning tank's program. Today we are not going to write an intelligent tank, but to design a simplified robocode game engine. Assuming the whole battlefield is 120*120 (pixel). Each tank can ONLY move in vertical and horizontal direction on the fixed path (There are paths every 10 pixels in the battlefield in both vertical and horizontal direction. In all there are 13 vertical paths and 13 horizontal paths available for tanks, as shown in Figure 1). The shape and size of the tank are negligible and one tank has (x, y) (x, y ∈ [0, 120]) representing its coordinate position and α (α ∈ {0, 90, 180, 270}) representing its facing direction (α = 0, 90, 180 or 270 means facing right, up, left or down respectively). They have a constant speed of 10 pixels/second when they move and they can't move out of the boundary (they will stop moving, staying in the direction that they are currently facing, when touching any boundary of the battlefield). The tank can shoot in the direction it's facing whether it's moving or still. The shot moves at the constant speed 20 pixel/second and the size of the shot is also negligible. It will explode when it meets a tank on the path. It's possible for more than one shot to explode in the same place if they all reach a tank at the exact same time. The tank being hit by the explosion will be destroyed and will be removed from the battlefield at once. A shot exploding or flying out of the boundary will also be removed. Figure 1 When the game begins, all the tanks are stopped at different crosses of the vertical and horizontal paths. Given the initial information of all the tanks and several commands, your job is to find the winner -- the last living tank when all the commands are executed (or omitted) and no shot exists in the battlefield (meaning that no tank may die in the future). Input There are several test cases. The battlefield and paths are all the same for all test cases as shown in Figure 1. Each test case starts with integers N (1 <= N <= 10) and M (1 <= M <= 1000), separated by a blank. N represents the number of the tanks playing in the battlefield, and M represents the number of commands to control the tanks' moving. The following N lines give the initial information (at time 0) of each tank, in the format: Name x y α The Name of a tank is consisted of no more than 10 letters. x, y, α are integers and x, y ∈ {0, 10, 20, ..., 120}, α ∈ {0, 90, 180, 270}。Each field is separated by a blank. The following M lines give commands in such format: Time Name Content Each field is separated by a blank. All the commands are giving in the ascending order of Time (0 <= Time <= 30), which is a positive integer meaning the timestamp when the commands are sent. Name points out which tank will receive the command. The Content has different types as follows: MOVE When receiving the command, the tank starts to move in its facing direction. If the tank is already moving, the command takes no effect. STOP When receiving the command, the tank stops moving. If the tank is already stopped, the command takes no effect. When receiving the command, the tank changes the facing direction α to be ((α + angle + 360) mod 360), no matter TURN angle whether it is moving or not. You are guaranteed that ((α + angle + 360) mod 360) ∈ {0, 90, 180, 270}. TURN command doesn't affect the moving state of the tank. SHOOT When receiving the command, the tank will shoot one shot in the direction it's facing. Tanks take the corresponding action as soon as they receive the commands. E.g., if the tank at (0, 0), α = 90, receives the command MOVE at time 1, it will start to move at once and will reach (0, 1) at time 2. Notice that a tank could receive multiple commands in one second and take the action one by one. E.g., if the tank at (0, 0), α = 90, receives a command sequence of "TURN 90; SHOOT; TURN -90", it will turn to the direction α = 180, shoot a shot and then turn back. If the tank receives a command sequence of "MOVE; STOP", it will keep still in the original position. Some more notes you need to pay attention: If a tank is hit by an explosion, it will take no action to all the commands received at that moment. Of course, all the commands sent to the already destroyed tank should also be omitted. Although the commands are sent at discrete seconds, the movement and explosions of tanks and shots happen in the continuous time domain. No two tanks will meet on the path guaranteed by the input data, so you don't need to consider about that situation. All the input contents will be legal for you. A test case with N = M = 0 ends the input, and should not be processed. Output For each test case, output the winner's name in one line. The winner is defined as the last living tank. If there is no tank or more than one tank living at the end, output "NO WINNER!" in one line. Sample Input 2 A B 1 2 2 A B 1 2 2 2 0 0 A A 2 0 0 A B 6 0 90 120 180 MOVE SHOOT 0 90 120 270 SHOOT SHOOT A 0 0 90 B 0 120 0 1 A MOVE 2 A SHOOT 6 B MOVE 30 B STOP 30 B TURN 180 30 B SHOOT 0 0 Sample Output A NO WINNER! B Source Beijing 2005 Monster Trap Time Limit: 1000MS Memory Limit: 30000K Total Submissions: 656 Accepted: 169 Description Once upon a time when people still believed in magic, there was a great wizard Aranyaka Gondlir. After twenty years of hard training in a deep forest, he had finally mastered ultimate magic, and decided to leave the forest for his home. Arriving at his home village, Aranyaka was very surprised at the extraordinary desolation. A gloom had settled over the village. Even the whisper of the wind could scare villagers. It was a mere shadow of what it had been. What had happened? Soon he recognized a sure sign of an evil monster that is immortal. Even the great wizard could not kill it, and so he resolved to seal it with magic. Aranyaka could cast a spell to create a monster trap: once he had drawn a line on the ground with his magic rod, the line would function as a barrier wall that any monster could not get over. Since he could only draw straight lines, he had to draw several lines to complete a monster trap, i.e., magic barrier walls enclosing the monster. If there was a gap between barrier walls, the monster could easily run away through the gap. For instance, a complete monster trap without any gaps is built by the barrier walls in the left figure, where "M" indicates the position of the monster. In contrast, the barrier walls in the right figure have a loophole, even though it is almost complete. Your mission is to write a program to tell whether or not the wizard has successfully sealed the monster. Input The input consists of multiple data sets, each in the following format. n x1 y1 x01 y01 x2 y2 x02 y02 ... xn yn x0n y0n The first line of a data set contains a positive integer n, which is the number of the line segments drawn by the wizard. Each of the following n input lines contains four integers x, y, x0, and y0, which represent the x- and y-coordinates of two points (x, y) and (x0, y0) connected by a line segment. You may assume that all line segments have non-zero lengths. You may also assume that n is less than or equal to 100 and that all coordinates are between -50 and 50, inclusive. For your convenience, the coordinate system is arranged so that the monster is always on the origin (0, 0). The wizard never draws lines crossing (0, 0). You may assume that any two line segments have at most one intersection point and that no three line segments share the same intersection point. You may also assume that the distance between any two intersection points is greater than 10^-5. An input line containing a zero indicates the end of the input. Output For each data set, print "yes" or "no" in a line. If a monster trap is completed, print "yes". Otherwise, i.e., if there is a loophole, print "no". Sample Input 8 -7 9 6 9 -5 5 6 5 -10 -5 10 -5 -6 9 -9 -6 6 9 9 -6 -1 -2 -3 10 1 -2 3 10 -2 -3 2 -3 8 -7 9 5 7 -5 5 6 5 -10 -5 10 -5 -6 9 -9 -6 6 9 9 -6 -1 -2 -3 10 1 -2 3 10 -2 -3 2 -3 0 Sample Output yes no Source Japan 2003,Aizu ACM Underground Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 156 Accepted: 61 Description ACM is a town with a very special underground metro system which consists of a set of railway segments, each is called a line. There are trains in both directions of each line. Two lines may intersect which allows a passenger to switch from one train in the first line to another train in the second line on that intersection. The source and destination of your travel lie somewhere on the metro lines. You start using the metro line where the source is located on and may change your line only at the intersection points between two metro lines, and continue until your reach the destination. Your goal is to make your travel free of charge; i.e., without the need to buy any tickets. The problem is that there are a number of policemen who check your tickets. Obviously, you do not want to confront with any of these policemen during your travel. You may confront policemen in two situations: either on an intersection, but only when you are changing your line, or when you are traveling along a line in which a policeman indiscriminately asks for everyone's tickets that are inside that wagon, including you. You know the locations of all policemen in advance. Note that if a police is located on an intersection, he asks for your ticket only if you want to change your line on that intersection, and if a police is located on a line (but not on an intersection), he will ask for your ticket if you are passing that location. In your map, there are some policemen in other locations, not on any metro lines, which you must ignore. For example, in the following figure, there are five metro lines, with three policemen located at black circles. You may travel from s to d without meeting any police along the path l1 -- l4, but it is not possible to travel from s to d' without confronting any policemen. In this problem, you must write a program that reads the metro line specifications, the police locations, and your source and destination, and determine whether it is possible to travel from the given source to the given destination without meeting any policeman. Input The first number in the input line, T is the number of test cases. The first line of each test case contains two integers n and m (1 ≤ m ≤ 100, 1 ≤ n ≤ 3000) which are the number of lines and the number of policemen. The second line contains four integers xs ys xd yd which are the coordinates of the source and the destination points respectively. You may assume these two points lie on metro lines. Following the second line, there are n lines of the form x1 y1 x2 y2 describing the metro lines where (x1, y1) and (x2, y2) specify the endpoints of the metro line. After this, there are m lines each containing a pair of integers x y that specify the location of a policeman. All coordinates are arbitrary integer numbers. Output The output contains T lines, each corresponding to an input test case in that order. The output line contains a single word YES or NO depending on whether there is a safe way to travel from source to destination or not. Sample Input 2 4 3 3 8 7 9 3 6 3 2 2 2 2 1 7 2 4 6 2 3 5 3 5 2 1 8 6 8 2 6 6 3 1 3 1 3 4 3 7 3 2 3 6 5 7 2 4 3 Sample Output YES NO Source Tehran 2006 Preliminary Roofing It Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 313 Accepted: 104 Description Bill Eaves owns the Shingle Minded roofing company which is a sub-contracting firm specializing in putting roofs on buildings. Often, Bill will receive a design for a roof from some young hot-shot architect which, though it may have some aesthetic appeal, is totally impractical. In these cases, Bill will begin negotiations with the architect and the client to find a simpler design. Bill's only concern is that the roof be convex, to allow rain, snow and frisbees to roll off easily. The architect's main concern is that the maximum height between his original roof and the compromise roof be as small as possible. The client's main concern is to get out of this meeting as soon as possible and get back to watching TV. The architect's plans for the roof come in the form of a series of n points (xi, yi) specifying the outline of the roof as seen from the side of the house. The roofs are always symmetrical, so the architect only shows the front side of the roof (from its start at the front of the house to its peak). Once Bill gets these plans and a decision is made on how many sections the convex roof should have, he must decide how to place the sections so as to 1) make sure that all the original (xi, yi) points lie on or below the new roof, and 2) to minimize the maximum vertical distance between any of the original (xi, yi) points and the new roof. All sections must lie on at least two of the initial points specified by the architect. An example is shown below. On the left are the initial points from the architect. The next two pictures show an approximation of the roof using only two sections. While both of these are convex, the second of the two is the one which minimizes the maximum distance. Input Input will consist of multiple test cases. Each case will begin with two positive integers n and k (2 ≤ n ≤ 100, 1 ≤ k < n) indicating the number of points used in the original roof plan and the number of sections used in the compromise roof. These will be followed by n lines each containing two floating points numbers xi yi, specifying the n points in the roof plan. These values will be given in increasing order of x, and the last point will be guaranteed to have the highest y value of any of the points. All values will be between 0.0 and 10000.0. The last case is followed by a line containing 0 0 which indicates end-of-input and should not be processed. Output For each test case, output the maximum distance between the best compromise roof and the initial points, rounded to the nearest thousandth. Sample Input 6 2 0.0 0.0 1.0 3.0 3.0 6.0 6.0 9.0 8.0 10.0 17.0 12.0 0 0 Sample Output 1.500 Source East Central North America 2006 Color the Map Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 550 Accepted: 181 Description You were lucky enough to get a map just before entering the legendary magical mystery world. The map shows the whole area of your planned exploration, including several countries with complicated borders. The map is clearly drawn, but in sepia ink only; it is hard to recognize at a glance which region belongs to which country, and this might bring you into severe danger. You have decided to color the map before entering the area. "A good deal depends on preparation," you talked to yourself. Each country has one or more territories, each of which has a polygonal shape. Territories belonging to one country may or may not "touch" each other, i.e. there may be disconnected territories. All the territories belonging to the same country must be assigned the same color. You can assign the same color to more than one country, but, to avoid confusion, two countries "adjacent" to each other should be assigned different colors. Two countries are considered to be "adjacent" if any of their territories share a border of non-zero length. Write a program that finds the least number of colors required to color the map. Input The input consists of multiple map data. Each map data starts with a line containing the total number of territories n, followed by the data for those territories. n is a positive integer not more than 100. The data for a territory with m vertices has the following format: String x1 y1 x2 y2 ... xm ym -1 "String" (a sequence of alphanumerical characters) gives the name of the country it belongs to. A country name has at least one character and never has more than twenty. When a country has multiple territories, its name appears in each of them. Remaining lines represent the vertices of the territory. A vertex data line has a pair of nonnegative integers which represent the xand y-coordinates of a vertex. x- and y-coordinates are separated by a single space, and y-coordinate is immediately followed by a newline. Edges of the territory are obtained by connecting vertices given in two adjacent vertex data lines, and by connecting vertices given in the last and the first vertex data lines. None of x- and y-coordinates exceeds 1000. Finally, -1 in a line marks the end of vertex data lines. The number of vertices m does not exceed 100. You may assume that the contours of polygons are simple, i.e. they do not cross nor touch themselves. No two polygons share a region of non-zero area. The number of countries in a map does not exceed 10. The last map data is followed by a line containing only a zero, marking the end of the input data. Output For each map data, output one line containing the least possible number of colors required to color the map satisfying the specified conditions. Sample Input 6 Blizid 0 0 60 0 60 60 0 60 0 50 50 50 50 10 0 10 -1 Blizid 0 10 10 10 10 50 0 50 -1 Windom 10 10 50 10 40 20 20 20 20 40 10 50 -1 Accent 50 10 50 50 35 50 35 25 -1 Pilot 35 25 35 50 10 50 -1 Blizid 20 20 40 20 20 40 -1 4 A1234567890123456789 0 0 0 100 100 100 100 0 -1 B1234567890123456789 100 100 100 200 200 200 200 100 -1 C1234567890123456789 0 100 100 100 100 200 0 200 -1 D123456789012345678 100 0 100 100 200 100 200 0 -1 0 Sample Output 4 2 Source Japan 2004 Reflections Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 747 Accepted: 316 Description Rendering realistic images of imaginary environments or objects is an interesting topic in computer graphics. One of the most popular methods for this purpose is ray-tracing. To render images using ray-tracing, one computes (traces) the path that rays of light entering a scene will take. We ask you to write a program that computes such paths in a restricted environment. For simplicity, we will consider only two-dimensional scenes. All objects in the scene are totally reflective (mirror) spheres. When a ray of light hits such a sphere, it is reflected such that the angle of the incoming ray and the leaving ray against the tangent are the same: The following figure shows a typical path that a ray of light may take in such a scene: Your task is to write a program, that given a scene description and a ray entering the scene, determines which spheres are hit by the ray. Input The input consists of a series of scene descriptions. Each description starts with a line containing the number n (n <= 25) of spheres in the scene. The following n lines contain three integers xi, yi, ri each, where (xi, yi) is the center, and ri > 0 is the radius of the i-th sphere. Following this is a line containing four integers x, y, dx, dy, which describe the ray. The ray originates from the point (x,y) and initially points in the direction (dx, dy). At least one of dx and dy will be non-zero. The spheres will be disjoint and non-touching. The ray will not start within a sphere, and never touch a sphere tangentially. A test case starting with n = 0 terminates the input. This case should not be processed. Output For each scene first output the number of the scene. Then print the numbers of the spheres that the ray hits in its first ten deflections (the numbering of spheres is according to their order in the input). If the ray hits at most ten spheres (and then heads towards infinity), print inf after the last sphere it hits. If the ray hits more than 10 spheres, print three points (...) after the tenth sphere. Output a blank line after each test case. Sample Input 3 3 7 8 3 2 0 5 3 7 1 8 2 1 1 1 -4 0 1 0 2 2 0 1 0 0 Sample Output Scene 1 1 2 1 3 inf Scene 2 2 1 2 1 2 1 2 1 2 1 ... Source Southwestern European Regional Contest 1998