problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
βŒ€
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
C. Jeff and Bracketstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJeff loves regular bracket sequences.Today Jeff is going to take a piece of paper and write out the regular bracket sequence, consisting of nm brackets. Let's number all brackets of this sequence from 0 to nm - 1 from left to right. Jeff knows that he is going to spend ai mod n liters of ink on the i-th bracket of the sequence if he paints it opened and bi mod n liters if he paints it closed.You've got sequences a, b and numbers n, m. What minimum amount of ink will Jeff need to paint a regular bracket sequence of length nm?Operation x mod y means taking the remainder after dividing number x by number y.InputThe first line contains two integers n and m (1 ≀ n ≀ 20;Β 1 ≀ m ≀ 107; m is even). The next line contains n integers: a0, a1, ..., an - 1 (1 ≀ ai ≀ 10). The next line contains n integers: b0, b1, ..., bn - 1 (1 ≀ bi ≀ 10). The numbers are separated by spaces.OutputIn a single line print the answer to the problem β€” the minimum required amount of ink in liters.ExamplesInput2 61 22 1Output12Input1 1000000023Output25000000NoteIn the first test the optimal sequence is: ()()()()()(), the required number of ink liters is 12.
Input2 61 22 1
Output12
1 second
256 megabytes
['dp', 'matrices', '*2500']
B. Jeff and Furiktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJeff has become friends with Furik. Now these two are going to play one quite amusing game.At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes i and i + 1, for which an inequality pi > pi + 1 holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes i and i + 1, for which the inequality pi < pi + 1 holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.You can consider that the coin shows the heads (or tails) with the probability of 50 percent.InputThe first line contains integer n (1 ≀ n ≀ 3000). The next line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the permutation p. The numbers are separated by spaces.OutputIn a single line print a single real value β€” the answer to the problem. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.ExamplesInput21 2Output0.000000Input53 5 2 4 1Output13.000000NoteIn the first test the sequence is already sorted, so the answer is 0.
Input21 2
Output0.000000
1 second
256 megabytes
['combinatorics', 'dp', 'probabilities', '*1900']
A. Jeff and Roundingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows: choose indexes i and j (i ≠ j) that haven't been chosen yet; round element ai to the nearest integer that isn't more than ai (assign to ai: ⌊ aiΒ βŒ‹); round element aj to the nearest integer that isn't less than aj (assign to aj: ⌈ ajΒ βŒ‰). Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.InputThe first line contains integer n (1 ≀ n ≀ 2000). The next line contains 2n real numbers a1, a2, ..., a2n (0 ≀ ai ≀ 10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.OutputIn a single line print a single real number β€” the required difference with exactly three digits after the decimal point.ExamplesInput30.000 0.500 0.750 1.000 2.000 3.000Output0.250Input34469.000 6526.000 4864.000 9356.383 7490.000 995.896Output0.279NoteIn the first test case you need to perform the operations as follows: (i = 1, j = 4), (i = 2, j = 3), (i = 5, j = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25.
Input30.000 0.500 0.750 1.000 2.000 3.000
Output0.250
1 second
256 megabytes
['dp', 'greedy', 'implementation', 'math', '*1800']
E. Wrong Floydtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from n vertexes and m edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly k vertexes a1, a2, ..., ak.Valera's code is given below.ans[i][j] // the shortest distance for a pair of vertexes i, ja[i] // vertexes, marked by Valerafor(i = 1; i <= n; i++) { for(j = 1; j <= n; j++) { if (i == j) ans[i][j] = 0; else ans[i][j] = INF; //INF is a very large number }} for(i = 1; i <= m; i++) { read a pair of vertexes u, v that have a non-directed edge between them; ans[u][v] = 1; ans[v][u] = 1;}for (i = 1; i <= k; i++) { v = a[i]; for(j = 1; j <= n; j++) for(r = 1; r <= n; r++) ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);}Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes a1, a2, ..., ak, find such non-directed connected graph, consisting of n vertexes and m edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (i, j). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.InputThe first line of the input contains three integers n, m, k (3 ≀ n ≀ 300, 2 ≀ k ≀ n , ) β€” the number of vertexes, the number of edges and the number of marked vertexes. The second line of the input contains k space-separated integers a1, a2, ... ak (1 ≀ ai ≀ n) β€” the numbers of the marked vertexes. It is guaranteed that all numbers ai are distinct.OutputIf the graph doesn't exist, print -1 on a single line. Otherwise, print m lines, each containing two integers u, v β€” the description of the edges of the graph Valera's been looking for.ExamplesInput3 2 21 2Output1 32 3Input3 3 21 2Output-1
Input3 2 21 2
Output1 32 3
1 second
256 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'graphs', '*2200']
D. Looking for Owlstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEmperor Palpatine loves owls very much. The emperor has some blueprints with the new Death Star, the blueprints contain n distinct segments and m distinct circles. We will consider the segments indexed from 1 to n in some way and the circles β€” indexed from 1 to m in some way. Palpatine defines an owl as a set of a pair of distinct circles (i, j) (i < j) and one segment k, such that: circles i and j are symmetrical relatively to the straight line containing segment k; circles i and j don't have any common points; circles i and j have the same radius; segment k intersects the segment that connects the centers of circles i and j. Help Palpatine, count the number of distinct owls on the picture. InputThe first line contains two integers β€” n and m (1 ≀ n ≀ 3Β·105, 2 ≀ m ≀ 1500). The next n lines contain four integers each, x1, y1, x2, y2 β€” the coordinates of the two endpoints of the segment. It's guaranteed that each segment has positive length.The next m lines contain three integers each, xi, yi, ri β€” the coordinates of the center and the radius of the i-th circle. All coordinates are integers of at most 104 in their absolute value. The radius is a positive integer of at most 104.It is guaranteed that all segments and all circles are dictinct.OutputPrint a single number β€” the answer to the problem.Please, do not use the %lld specifier to output 64-bit integers is Π‘++. It is preferred to use the cout stream or the %I64d specifier.ExamplesInput1 23 2 3 -20 0 26 0 2Output1Input3 20 0 0 10 -1 0 10 -1 0 02 0 1-2 0 1Output3Input1 2-1 0 1 0-100 0 1100 0 1Output0NoteHere's an owl from the first sample. The owl is sitting and waiting for you to count it.
Input1 23 2 3 -20 0 26 0 2
Output1
2 seconds
256 megabytes
['binary search', 'data structures', 'geometry', 'hashing', 'sortings', '*2400']
C. Bombstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains n bombs, the i-th bomb is at point with coordinates (xi, yi). We know that no two bombs are at the same point and that no bomb is at point with coordinates (0, 0). Initially, the robot is at point with coordinates (0, 0). Also, let's mark the robot's current position as (x, y). In order to destroy all the bombs, the robot can perform three types of operations: Operation has format "1 k dir". To perform the operation robot have to move in direction dir k (k β‰₯ 1) times. There are only 4 directions the robot can move in: "R", "L", "U", "D". During one move the robot can move from the current point to one of following points: (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) (corresponding to directions). It is forbidden to move from point (x, y), if at least one point on the path (besides the destination point) contains a bomb. Operation has format "2". To perform the operation robot have to pick a bomb at point (x, y) and put it in a special container. Thus, the robot can carry the bomb from any point to any other point. The operation cannot be performed if point (x, y) has no bomb. It is forbidden to pick a bomb if the robot already has a bomb in its container. Operation has format "3". To perform the operation robot have to take a bomb out of the container and destroy it. You are allowed to perform this operation only if the robot is at point (0, 0). It is forbidden to perform the operation if the container has no bomb. Help the robot and find the shortest possible sequence of operations he can perform to destroy all bombs on the coordinate plane.InputThe first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of bombs on the coordinate plane. Next n lines contain two integers each. The i-th line contains numbers (xi, yi) ( - 109 ≀ xi, yi ≀ 109) β€” the coordinates of the i-th bomb. It is guaranteed that no two bombs are located at the same point and no bomb is at point (0, 0). OutputIn a single line print a single integer k β€” the minimum number of operations needed to destroy all bombs. On the next lines print the descriptions of these k operations. If there are multiple sequences, you can print any of them. It is guaranteed that there is the solution where k ≀ 106.ExamplesInput21 1-1 -1Output121 1 R1 1 U21 1 L1 1 D31 1 L1 1 D21 1 R1 1 U3Input35 00 51 0Output121 1 R21 1 L31 5 R21 5 L31 5 U21 5 D3
Input21 1-1 -1
Output121 1 R1 1 U21 1 L1 1 D31 1 L1 1 D21 1 R1 1 U3
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*1600']
B. Resorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera's finally decided to go on holiday! He packed up and headed for a ski resort.Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each object is either a hotel or a mountain.Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object v, the resort has at most one object u, such that there is a ski track built from object u to object v. We also know that no hotel has got a ski track leading from the hotel to some object.Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects v1, v2, ..., vk (k β‰₯ 1) and meet the following conditions: Objects with numbers v1, v2, ..., vk - 1 are mountains and the object with number vk is the hotel. For any integer i (1 ≀ i < k), there is exactly one ski track leading from object vi. This track goes to object vi + 1. The path contains as many objects as possible (k is maximal). Help Valera. Find such path that meets all the criteria of our hero!InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of objects.The second line contains n space-separated integers type1, type2, ..., typen β€” the types of the objects. If typei equals zero, then the i-th object is the mountain. If typei equals one, then the i-th object is the hotel. It is guaranteed that at least one object is a hotel.The third line of the input contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ n) β€” the description of the ski tracks. If number ai equals zero, then there is no such object v, that has a ski track built from v to i. If number ai doesn't equal zero, that means that there is a track built from object ai to object i.OutputIn the first line print k β€” the maximum possible path length for Valera. In the second line print k integers v1, v2, ..., vk β€” the path. If there are multiple solutions, you can print any of them.ExamplesInput50 0 0 0 10 1 2 3 4Output51 2 3 4 5Input50 0 1 0 10 1 2 2 4Output24 5Input41 0 0 02 3 4 2Output11
Input50 0 0 0 10 1 2 3 4
Output51 2 3 4 5
2 seconds
256 megabytes
['graphs', '*1500']
A. TLtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, a seconds, an inequality 2a ≀ v holds.As a result, Valera decided to set v seconds TL, that the following conditions are met: v is a positive integer; all correct solutions pass the system testing; at least one correct solution passes the system testing with some "extra" time; all wrong solutions do not pass the system testing; value v is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.InputThe first line contains two integers n, m (1 ≀ n, m ≀ 100). The second line contains n space-separated positive integers a1, a2, ..., an (1 ≀ ai ≀ 100) β€” the running time of each of the n correct solutions in seconds. The third line contains m space-separated positive integers b1, b2, ..., bm (1 ≀ bi ≀ 100) β€” the running time of each of m wrong solutions in seconds. OutputIf there is a valid TL value, print it. Otherwise, print -1.ExamplesInput3 64 5 28 9 6 10 7 11Output5Input3 13 4 56Output-1
Input3 64 5 28 9 6 10 7 11
Output5
2 seconds
256 megabytes
['brute force', 'greedy', 'implementation', '*1200']
B. Color the Fencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.Help Igor find the maximum number he can write on the fence.InputThe first line contains a positive integer v (0 ≀ v ≀ 106). The second line contains nine positive integers a1, a2, ..., a9 (1 ≀ ai ≀ 105).OutputPrint the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1.ExamplesInput55 4 3 2 1 2 3 4 5Output55555Input29 11 1 12 5 8 9 10 6Output33Input01 1 1 1 1 1 1 1 1Output-1
Input55 4 3 2 1 2 3 4 5
Output55555
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'implementation', '*1700']
A. Cinema Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 β€” the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.OutputPrint "YES" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print "NO".ExamplesInput425 25 50 50OutputYESInput225 100OutputNOInput450 50 25 25OutputNO
Input425 25 50 50
OutputYES
2 seconds
256 megabytes
['greedy', 'implementation', '*1100']
E. Pilgrimstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA long time ago there was a land called Dudeland. Dudeland consisted of n towns connected with n - 1 bidirectonal roads. The towns are indexed from 1 to n and one can reach any city from any other city if he moves along the roads of the country. There are m monasteries in Dudeland located in m different towns. In each monastery lives a pilgrim.At the beginning of the year, each pilgrim writes down which monastery is the farthest from the monastery he is living in. If there is more than one farthest monastery, he lists all of them. On the Big Lebowski day each pilgrim picks one town from his paper at random and starts walking to that town. Walter hates pilgrims and wants to make as many of them unhappy as possible by preventing them from finishing their journey. He plans to destroy exactly one town that does not contain a monastery. A pilgrim becomes unhappy if all monasteries in his list become unreachable from the monastery he is living in. You need to find the maximum number of pilgrims Walter can make unhappy. Also find the number of ways he can make this maximal number of pilgrims unhappy: the number of possible towns he can destroy.InputThe first line contains two integers n (3 ≀ n ≀ 105) and m (2 ≀ m < n). The next line contains m distinct integers representing indices of towns that contain monasteries.Next n - 1 lines contain three integers each, ai, bi, ci, indicating that there is an edge between towns ai and bi of length ci (1 ≀ ai, bi ≀ n, 1 ≀ ci ≀ 1000, ai ≠ bi).OutputOutput two integers: the maximum number of pilgrims Walter can make unhappy and the number of ways in which he can make his plan come true.ExamplesInput8 57 2 5 4 81 2 12 3 21 4 14 5 21 6 16 7 86 8 10Output5 1
Input8 57 2 5 4 81 2 12 3 21 4 14 5 21 6 16 7 86 8 10
Output5 1
2 seconds
256 megabytes
['dfs and similar', 'dp', 'trees', '*2800']
D. Turtlestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a table of size n × m. We'll consider the table rows numbered from top to bottom 1 through n, and the columns numbered from left to right 1 through m. Then we'll denote the cell in row x and column y as (x, y).Initially cell (1, 1) contains two similar turtles. Both turtles want to get to cell (n, m). Some cells of the table have obstacles but it is guaranteed that there aren't any obstacles in the upper left and lower right corner. A turtle (one or the other) can go from cell (x, y) to one of two cells (x + 1, y) and (x, y + 1), as long as the required cell doesn't contain an obstacle. The turtles have had an argument so they don't want to have any chance of meeting each other along the way. Help them find the number of ways in which they can go from cell (1, 1) to cell (n, m).More formally, find the number of pairs of non-intersecting ways from cell (1, 1) to cell (n, m) modulo 1000000007 (109 + 7). Two ways are called non-intersecting if they have exactly two common points β€” the starting point and the final point.InputThe first line contains two integers n, m (2 ≀ n, m ≀ 3000). Each of the following n lines contains m characters describing the table. The empty cells are marked by characters ".", the cells with obstacles are marked by "#".It is guaranteed that the upper left and the lower right cells are empty.OutputIn a single line print a single integer β€” the number of pairs of non-intersecting paths from cell (1, 1) to cell (n, m) modulo 1000000007 (109 + 7).ExamplesInput4 5......###..###......Output1Input2 3......Output1
Input4 5......###..###......
Output1
2 seconds
256 megabytes
['dp', 'matrices', '*2500']
C. Subset Sumstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1, a2, ..., an and m sets S1, S2, ..., Sm of indices of elements of this array. Let's denote Sk = {Sk, i}Β (1 ≀ i ≀ |Sk|). In other words, Sk, i is some element from set Sk.In this problem you have to answer q queries of the two types: Find the sum of elements with indices from set Sk: . The query format is "? k". Add number x to all elements at indices from set Sk: aSk, i is replaced by aSk, i + x for all i (1 ≀ i ≀ |Sk|). The query format is "+ k x". After each first type query print the required sum.InputThe first line contains integers n, m, q (1 ≀ n, m, q ≀ 105). The second line contains n integers a1, a2, ..., an (|ai| ≀ 108) β€” elements of array a. Each of the following m lines describes one set of indices. The k-th line first contains a positive integer, representing the number of elements in set (|Sk|), then follow |Sk| distinct integers Sk, 1, Sk, 2, ..., Sk, |Sk| (1 ≀ Sk, i ≀ n) β€” elements of set Sk.The next q lines contain queries. Each query looks like either "? k" or "+ k x" and sits on a single line. For all queries the following limits are held: 1 ≀ k ≀ m, |x| ≀ 108. The queries are given in order they need to be answered.It is guaranteed that the sum of sizes of all sets Sk doesn't exceed 105.OutputAfter each first type query print the required sum on a single line.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput5 3 55 -5 5 1 -42 1 24 2 1 4 52 2 5? 2+ 3 4? 1+ 2 1? 2Output-349
Input5 3 55 -5 5 1 -42 1 24 2 1 4 52 2 5? 2+ 3 4? 1+ 2 1? 2
Output-349
3 seconds
256 megabytes
['brute force', 'data structures', '*2500']
B. Apple Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree with n vertices. In each leaf vertex there's a single integer β€” the number of apples in this vertex. The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.A tree is balanced if for every vertex v of the tree all its subtrees, corresponding to the children of vertex v, are of equal weight. Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.InputThe first line contains integer n (2 ≀ n ≀ 105), showing the number of vertices in the tree. The next line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 108), ai is the number of apples in the vertex number i. The number of apples in non-leaf vertices is guaranteed to be zero. Then follow n - 1 lines, describing the tree edges. Each line contains a pair of integers xi, yi (1 ≀ xi, yi ≀ n, xi ≠ yi) β€” the vertices connected by an edge. The vertices are indexed from 1 to n. Vertex 1 is the root.OutputPrint a single integer β€” the minimum number of apples to remove in order to make the tree balanced.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the sin, cout streams cin, cout or the %I64d specifier.ExamplesInput60 0 12 13 5 61 21 31 42 52 6Output6
Input60 0 12 13 5 61 21 31 42 52 6
Output6
2 seconds
256 megabytes
['dfs and similar', 'number theory', 'trees', '*2100']
A. Mafiatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?InputThe first line contains integer n (3 ≀ n ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the i-th number in the list is the number of rounds the i-th person wants to play.OutputIn a single line print a single integer β€” the minimum number of game rounds the friends need to let the i-th person play at least ai rounds.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput33 2 2Output4Input42 2 2 2Output3NoteYou don't need to know the rules of "Mafia" to solve this problem. If you're curious, it's a game Russia got from the Soviet times: http://en.wikipedia.org/wiki/Mafia_(party_game).
Input33 2 2
Output4
2 seconds
256 megabytes
['binary search', 'math', 'sortings', '*1600']
B. Fixed Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.InputThe first line contains a single integer n (1 ≀ n ≀ 105). The second line contains n integers a0, a1, ..., an - 1 β€” the given permutation.OutputPrint a single integer β€” the maximum possible number of fixed points in the permutation after at most one swap operation.ExamplesInput50 1 3 4 2Output3
Input50 1 3 4 2
Output3
2 seconds
256 megabytes
['brute force', 'implementation', 'math', '*1100']
A. Difference Rowtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The value of such an arrangement is (x1 - x2) + (x2 - x3) + ... + (xn - 1 - xn).Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value.InputThe first line of the input contains integer n (2 ≀ n ≀ 100). The second line contains n space-separated integers a1, a2, ..., an (|ai| ≀ 1000).OutputPrint the required sequence x1, x2, ..., xn. Sequence x should be the lexicographically smallest permutation of a that corresponds to an arrangement of the largest possible value.ExamplesInput5100 -100 50 0 -50Output100 -50 0 50 -100 NoteIn the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one.Sequence x1, x2, ... , xp is lexicographically smaller than sequence y1, y2, ... , yp if there exists an integer r (0 ≀ r < p) such that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1.
Input5100 -100 50 0 -50
Output100 -50 0 50 -100
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'sortings', '*1300']
E. Doodle Jumptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output In Doodle Jump the aim is to guide a four-legged creature called "The Doodler" up a never-ending series of platforms without falling. β€” Wikipedia. It is a very popular game and xiaodao likes it very much. One day when playing the game she wondered whether there exists a platform that the doodler couldn't reach due to the limits of its jumping ability. Consider the following problem.There are n platforms. The height of the x-th (1 ≀ x ≀ n) platform is aΒ·x mod p, where a and p are positive co-prime integers. The maximum possible height of a Doodler's jump is h. That is, it can jump from height h1 to height h2 (h1 < h2) if h2 - h1 ≀ h. Initially, the Doodler is on the ground, the height of which is 0. The question is whether it can reach the highest platform or not.For example, when a = 7, n = 4, p = 12, h = 2, the heights of the platforms are 7, 2, 9, 4 as in the picture below. With the first jump the Doodler can jump to the platform at height 2, with the second one the Doodler can jump to the platform at height 4, but then it can't jump to any of the higher platforms. So, it can't reach the highest platform. User xiaodao thought about the problem for a long time but didn't solve it, so she asks you for help. Also, she has a lot of instances of the problem. Your task is solve all of these instances.InputThe first line contains an integer t (1 ≀ t ≀ 104) β€” the number of problem instances. Each of the next t lines contains four integers a, n, p and h (1 ≀ a ≀ 109, 1 ≀ n < p ≀ 109, 0 ≀ h ≀ 109). It's guaranteed that a and p are co-prime.OutputFor each problem instance, if the Doodler can reach the highest platform, output "YES", otherwise output "NO".ExamplesInput37 4 12 27 1 9 47 4 12 3OutputNONOYES
Input37 4 12 27 1 9 47 4 12 3
OutputNONOYES
2 seconds
256 megabytes
['math', 'number theory', '*3000']
D. Robot Controltime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe boss of the Company of Robot is a cruel man. His motto is "Move forward Or Die!". And that is exactly what his company's product do. Look at the behavior of the company's robot when it is walking in the directed graph. This behavior has been called "Three Laws of Robotics": Law 1. The Robot will destroy itself when it visits a vertex of the graph which it has already visited. Law 2. The Robot will destroy itself when it has no way to go (that is when it reaches a vertex whose out-degree is zero). Law 3. The Robot will move randomly when it has multiple ways to move (that is when it reach a vertex whose out-degree is more than one). Of course, the robot can move only along the directed edges of the graph. Can you imagine a robot behaving like that? That's why they are sold at a very low price, just for those who are short of money, including mzry1992, of course. mzry1992 has such a robot, and she wants to move it from vertex s to vertex t in a directed graph safely without self-destruction. Luckily, she can send her robot special orders at each vertex. A special order shows the robot which way to move, if it has multiple ways to move (to prevent random moving of the robot according to Law 3). When the robot reaches vertex t, mzry1992 takes it off the graph immediately. So you can see that, as long as there exists a path from s to t, she can always find a way to reach the goal (whatever the vertex t has the outdegree of zero or not). Sample 2 However, sending orders is expensive, so your task is to find the minimum number of orders mzry1992 needs to send in the worst case. Please note that mzry1992 can give orders to the robot while it is walking on the graph. Look at the first sample to clarify that part of the problem.InputThe first line contains two integers n (1 ≀ n ≀ 106) β€” the number of vertices of the graph, and m (1 ≀ m ≀ 106) β€” the number of edges. Then m lines follow, each with two integers ui and vi (1 ≀ ui, vi ≀ n; vi ≠ ui), these integers denote that there is a directed edge from vertex ui to vertex vi. The last line contains two integers s and t (1 ≀ s, t ≀ n).It is guaranteed that there are no multiple edges and self-loops.OutputIf there is a way to reach a goal, print the required minimum number of orders in the worst case. Otherwise, print -1.ExamplesInput4 61 22 11 33 12 43 41 4Output1Input4 51 22 11 32 43 41 4Output1NoteConsider the first test sample. Initially the robot is on vertex 1. So, on the first step the robot can go to vertex 2 or 3. No matter what vertex the robot chooses, mzry1992 must give an order to the robot. This order is to go to vertex 4. If mzry1992 doesn't give an order to the robot at vertex 2 or 3, the robot can choose the "bad" outgoing edge (return to vertex 1) according Law 3. So, the answer is one.
Input4 61 22 11 33 12 43 41 4
Output1
6 seconds
256 megabytes
['dp', 'graphs', 'shortest paths', '*2600']
C. Number Transformation IItime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of positive integers x1, x2, ..., xn and two non-negative integers a and b. Your task is to transform a into b. To do that, you can perform the following moves: subtract 1 from the current a; subtract a mod xi (1 ≀ i ≀ n) from the current a. Operation a mod xi means taking the remainder after division of number a by number xi.Now you want to know the minimum number of moves needed to transform a into b.InputThe first line contains a single integer n (1 ≀  n ≀ 105). The second line contains n space-separated integers x1, x2, ..., xn (2 ≀  xi ≀ 109). The third line contains two integers a and b (0  ≀ b ≀  a ≀ 109, a - b ≀ 106).OutputPrint a single integer β€” the required minimum number of moves needed to transform number a into number b.ExamplesInput33 4 530 17Output6Input35 6 71000 200Output206
Input33 4 530 17
Output6
1 second
256 megabytes
['greedy', 'math', '*2200']
B. Lucky Common Subsequencetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.InputThe input contains three strings in three separate lines: s1, s2 and virus (1 ≀ |s1|, |s2|, |virus| ≀ 100). Each string consists only of uppercase English letters.OutputOutput the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted. If there is no valid common subsequence, output 0.ExamplesInputAJKEQSLOBSROFGZOVGURWZLWVLUXTHOZOutputORZInputAAAAOutput0
InputAJKEQSLOBSROFGZOVGURWZLWVLUXTHOZ
OutputORZ
3 seconds
512 megabytes
['dp', 'strings', '*2000']
A. Alice and Bobtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers x and y from the set, such that the set doesn't contain their absolute difference |x - y|. Then this player adds integer |x - y| to the set (so, the size of the set increases by one).If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.InputThe first line contains an integer n (2 ≀ n ≀ 100) β€” the initial number of elements in the set. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the set.OutputPrint a single line with the winner's name. If Alice wins print "Alice", otherwise print "Bob" (without quotes).ExamplesInput22 3OutputAliceInput25 3OutputAliceInput35 6 7OutputBobNoteConsider the first test sample. Alice moves first, and the only move she can do is to choose 2 and 3, then to add 1 to the set. Next Bob moves, there is no valid move anymore, so the winner is Alice.
Input22 3
OutputAlice
2 seconds
256 megabytes
['games', 'math', 'number theory', '*1600']
G. Suffix Subgrouptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a group of n strings: s1, s2, ..., sn.You should find a subgroup si1, si2, ..., sik (1 ≀ i1 < i2 < ... < ik ≀ n) of the group. The following two conditions must hold: there exists a string t such, that each string from found subgroup is its suffix; the number of strings in the found subgroup is as large as possible. Your task is to print the number of strings in the found subgroup.InputThe first line contains an integer n (1 ≀ n ≀ 105) β€” the number of strings in the group. Each of the next n lines contains a string. The i-th line contains non-empty string si.Each string consists only from lowercase Latin letters. The sum of all strings si doesn't exceed 105.OutputOutput a single integer β€” the number of strings in the found subgroup.ExamplesInput6bbbbbaaaaazOutput3NoteLook at the test sample. The required subgroup is s1, s2, s3.
Input6bbbbbaaaaaz
Output3
2 seconds
256 megabytes
['*special problem', 'strings', '*2200']
F. Superstitions Inspectiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou read scientific research regarding popularity of most famous superstitions across various countries, and you want to analyze their data. More specifically, you want to know which superstitions are popular in most countries.The data is given as a single file in the following format: country name on a separate line, followed by a list of superstitions popular in it, one entry per line. Each entry of the list is formatted as an asterisk "*" followed by a single space and then by the superstition name. Entries are unique within each country. The first line of input will represent a country. The input will contain at least one superstition. Country name is a non-empty sequence of words, where each word consists of only English letters. The words of the name of some country will be separated in input with one or more spaces.Superstition name is a non-empty sequence of words, where each word consists of only English letters and digits. The words of the name of some superstition will be separated in input with one or more spaces.You can consider two names equal, if corresponding sequences of words are equal. You shouldn't consider the case of the letters when you compare the words.Output the list of superstitions which are observed in the greatest number of countries. It's guaranteed that all countries have distinct names.InputThe input contains between 2 and 50 lines. Every line of input will contain between 1 and 50 characters, inclusive.No line has leading or trailing spaces.OutputOutput the list of superstitions which are observed in the greatest number of countries in alphabetical order. Each superstition must be converted to lowercase (one superstition can be written with varying capitalization in different countries).The alphabetical order of superstitions means the lexicographical order of sequences of words (their names).ExamplesInputUkraine* Friday the 13th* black cat* knock the woodUSA* wishing well* friday the 13thHollandFrance* Wishing WellOutputfriday the 13th wishing well InputSpain* Tuesday the 13thItaly* Friday the 17thRussia* Friday the 13thEngland* rabbit footOutputfriday the 13th friday the 17th rabbit foot tuesday the 13th
InputUkraine* Friday the 13th* black cat* knock the woodUSA* wishing well* friday the 13thHollandFrance* Wishing Well
Outputfriday the 13th wishing well
2 seconds
256 megabytes
['*special problem', '*2700']
E. Black Cat Rushtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday you go out of your house and immediately notice that something is weird. Around your door there is a swarm of black cats β€” all tense paws and twitching tails. As you do your first step, they all dart off and start running towards you. It looks like they want to thwart you!You are moving in a straight line from point (0, 0) to point (a, 0) with velocity v. There are n black cats around you who want to cross your paths. A cat can move in any direction with velocity at most u. A cat assumes it has crossed your path if it managed to get to at least one point of your path earlier or at the same time as you got there.You are given four integers: a, v, u, n, as well as cats' coordinates (xi, yi). What is the greatest number of cats who manage to cross your path?InputThe first line contains four integers a, v, u, n (1 ≀ a ≀ 10000;Β 1 ≀ v, u ≀ 100;Β 1 ≀ n ≀ 1000). Each of the next n lines contains two integers xi, yi ( - 100 ≀ xi, yi ≀ 100) β€” location of the i-th cat.It's guaranteed that all cats are located in distinct points.OutputOutput a single integer β€” what is the greatest number of cats who manage to cross your path?ExamplesInput1 1 5 40 34 -47 0-2 -2Output3Input10 5 3 47 55 210 -715 0Output3
Input1 1 5 40 34 -47 0-2 -2
Output3
2 seconds
256 megabytes
['*special problem', '*2700']
D. Chain Lettertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA chain letter is a kind of a message which urges the recipient to forward it to as many contacts as possible, usually with some kind of mystic explanation. Of course, this is only a superstition, and you don't believe in it, but all your friends do. You know that today there will be one of these letters going around, and you want to know how many times you'll receive it β€” of course, not that you'll be sending it yourself!You are given an array of strings f with n elements which describes the contacts between you and n - 1 of your friends: j-th character of i-th string (f[i][j]) is "1" if people i and j will send messages to each other, and "0" otherwise. Person 1 starts sending the letter to all his contacts; every person who receives the letter for the first time sends it to all his contacts. You are person n, and you don't forward the letter when you receive it. Calculate the number of copies of this letter you'll receive.InputThe first line of the input contains an integer n (2 ≀ n ≀ 50) β€” the number of people involved. Next n following lines contain elements of f, strings of length n. Each character in f is either "0" or "1". It's guaranteed that two following equations hold: f[i][j] = f[j][i], f[i][i] = 0, for all i, j (1 ≀ i, j ≀ n).OutputOutput a single integer β€” the number of copies of the letter you will receive eventually.ExamplesInput40111101111011110Output3Input40110101011000000Output0Input40101100100011110Output2NoteIn the first case, everybody sends letters to everyone, so you get copies from all three of your friends.In the second case, you don't know any of these people, so they don't bother you with their superstitious stuff.In the third case, two of your friends send you copies of the letter but the third friend doesn't know them so he is unaffected.
Input40111101111011110
Output3
2 seconds
256 megabytes
['*special problem', 'dfs and similar', 'graphs', '*2200']
C. Counting Fridaystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJudging from the previous problem, Friday the 13th really doesn't treat you well, so you start thinking about how to minimize its impact on your life. You are a passionate participant of programming contests, so various competitions are an important part of your schedule. Naturally, you'd like as few of them to be spoiled as possible.A friendly admin leaked to you the list of dates on which the contests will be held for several years ahead. Check how many of them happen to take place on Friday the 13th of any month.InputThe first line of the input contains an integer n (1 ≀ n ≀ 10) β€” the number of the contests you have been told about. The following n lines contain dates of these contests, one per line, formatted as "YYYY-MM-DD" (1974  ≀  YYYY  ≀  2030; 01  ≀  MM  ≀  12; 01  ≀  DD  ≀  31). It's guarateed that all the given dates are correct. Two distinct contests may be at the same day.OutputOutput a single integer β€” the number of dates which happen to be Friday the 13th.ExamplesInput52012-01-132012-09-132012-11-202013-09-132013-09-20Output2
Input52012-01-132012-09-132012-11-202013-09-132013-09-20
Output2
2 seconds
256 megabytes
['*special problem', '*2000']
B. Triskaidekaphobiatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTriskaidekaphobia is a fear of number 13. Ordinary people who suffer from this phobia feel uncomfortable around numbers 13, 130, 513 etc, but you, being a programmer, take this fear one step further. For example, consider number 7. It's ok when written in decimal, but written in base 4 it becomes 13, the dreadful number!The more you think about it, the worse it looks. Number 100 has as many as 13 notations which contain 13! And there are numbers which have 13 in infinite number of their notations! Luckily, you can do any math in binary, which is completely safe from the nasty number. But still, you want to be able to estimate the level of nastiness of any number. Your task is: given an integer n, find the number of different integer bases b (b β‰₯ 2) for which n, written in base b, contains at least one 13. Assume that "digits" of the number in bases larger than 10 are written not as letters but as decimal numbers; thus, 30 in base 16 is not 1E but (1)(14) or simply 114. Please note, that 13 must be present as a substring of notation, not a subsequence (123 doesn't contain 13).InputThe only line of the input contains a single integer n (1 ≀ n ≀ 105).OutputOutput a single integer β€” the number of different integer bases b (b β‰₯ 2) for which n, written in base b, contains at least one 13. If there are infinitely many such bases, output -1.ExamplesInput7Output1Input100Output13Input13Output-1
Input7
Output1
2 seconds
256 megabytes
['*special problem', '*2100']
A. Expecting Troubletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Friday the 13th today, and even though you're a modern well-educated person, you can't help feeling a bit nervous about it. You decide to look for evidence against this superstition (or for it). As a first step, you recall all Fridays the 13th in your life and calculate how many of them were unusually bad β€” like that time when you decided to play a game on ZX Spectrum and ended up breaking your TV set. The problem is, you can't remember some Fridays, and you're not sure why β€” were they really that bad?You have assembled a sequence of your recollections. Character "0" stands for a normal day, "1" β€” for a nasty one, and "?" means you have no idea what kind of day that was. Being a programmer, you decide to approximate these unknown days with independent random variables, which take value 1 with probability p, and 0 with probability (1 - p).Given a string of your memories and the value of p, calculate out the expected value of average badness of your Fridays the 13th.InputThe first line of the input contains a string s which represents your Fridays; s will contain between 1 and 50 characters, inclusive. Each character of s will be "0", "1" or "?".The second line of the input contains a double p (0 ≀ p ≀ 1). Double p is given with at most 2 digits after the decimal point.OutputOutput the expected value of average badness of your Fridays with exactly 5 decimal places. Please, use standard mathematical rules when you are rounding an answer.ExamplesInput?111?1??11.0Output1.00000Input01?10??100000.5Output0.37500NoteIn the first case, you're doomed. DOOMED! Sorry, just had to say that.
Input?111?1??11.0
Output1.00000
2 seconds
256 megabytes
['*special problem', 'probabilities', '*1500']
B. Simple Moleculestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule.A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number β€” the number of bonds the atom must form with other atoms. An atom can form one or multiple bonds with any other atom, but it cannot form a bond with itself. The number of bonds of an atom in the molecule must be equal to its valence number. Mike knows valence numbers of the three atoms. Find a molecule that can be built from these atoms according to the stated rules, or determine that it is impossible.InputThe single line of the input contains three space-separated integers a, b and c (1 ≀ a, b, c ≀ 106) β€” the valence numbers of the given atoms.OutputIf such a molecule can be built, print three space-separated integers β€” the number of bonds between the 1-st and the 2-nd, the 2-nd and the 3-rd, the 3-rd and the 1-st atoms, correspondingly. If there are multiple solutions, output any of them. If there is no solution, print "Impossible" (without the quotes).ExamplesInput1 1 2Output0 1 1Input3 4 5Output1 3 2Input4 1 1OutputImpossibleNoteThe first sample corresponds to the first figure. There are no bonds between atoms 1 and 2 in this case.The second sample corresponds to the second figure. There is one or more bonds between each pair of atoms.The third sample corresponds to the third figure. There is no solution, because an atom cannot form bonds with itself.The configuration in the fourth figure is impossible as each atom must have at least one atomic bond.
Input1 1 2
Output0 1 1
1 second
256 megabytes
['brute force', 'graphs', 'math', '*1200']
A. Magnetstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own. Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.InputThe first line of the input contains an integer n (1 ≀ n ≀ 100000) β€” the number of magnets. Then n lines follow. The i-th line (1 ≀ i ≀ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.OutputOn the single line of the output print the number of groups of magnets.ExamplesInput6101010011010Output3Input401011010Output2NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.
Input6101010011010
Output3
1 second
256 megabytes
['implementation', '*800']
E. Pumping Stationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMad scientist Mike has applied for a job. His task is to manage a system of water pumping stations.The system consists of n pumping stations, which are numbered by integers from 1 to n. Some pairs of stations are connected by bidirectional pipes through which water can flow in either direction (but only in one at a time). For each pipe you know its bandwidth β€” the maximum number of liters of water that can flow through it in one hour. Each pumping station can pump incoming water from some stations to other stations through the pipes, provided that in one hour the total influx of water to the station is equal to the total outflux of water from the station.It is Mike's responsibility to pump water between stations. From station a to station b through the pipes (possibly through other stations) within one hour one can transmit a certain number of liters of water according to the rules described above. During this time, water from other stations can not flow into station a, and can not flow out of the station b. However, any amount of water can flow out of station a or in station b. If a total of x litres of water flows out of the station a in an hour, then Mike gets x bollars more to his salary.To get paid, Mike needs to work for n - 1 days, according to the contract. On the first day he selects two stations v1 and v2, and within one hour he pumps a certain amount of water from v1 to v2. Next, on the i-th day Mike chooses a station vi + 1 that has been never selected before, and pumps a certain amount of water out of the station vi to station vi + 1 for one hour. The quantity of water he pumps on the i-th day does not depend on the amount of water pumped on the (i - 1)-th day.Mike needs to earn as much bollars as he can for his projects. Help Mike find such a permutation of station numbers v1, v2, ..., vn so Mike will be able to earn the highest possible salary.InputThe first line of the input contains two space-separated integers n and m (2 ≀ n ≀ 200, 1 ≀ m ≀ 1000) β€” the number of stations and pipes in the system, accordingly. The i-th of the next m lines contains three space-separated integers ai, bi and ci (1 ≀ ai, bi ≀ n, ai ≠ bi, 1 ≀ ci ≀ 100) β€” the numbers of stations connected by the i-th pipe and the pipe's bandwidth, accordingly. It is guaranteed that any two stations are connected by at most one pipe and that there is a pipe path between any two stations.OutputOn the first line print a single integer β€” the maximum salary Mike can earn.On the second line print a space-separated permutation of n numbers from 1 to n β€” the numbers of stations in the sequence v1, v2, ..., vn. If there are multiple answers, print any of them.ExamplesInput6 111 2 101 6 82 3 42 5 22 6 33 4 53 5 43 6 24 5 74 6 25 6 3Output776 2 1 5 3 4
Input6 111 2 101 6 82 3 42 5 22 6 33 4 53 5 43 6 24 5 74 6 25 6 3
Output776 2 1 5 3 4
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'divide and conquer', 'flows', 'graphs', 'greedy', 'trees', '*2900']
D. Water Treetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMad scientist Mike has constructed a rooted tree, which consists of n vertices. Each vertex is a reservoir which can be either empty or filled with water.The vertices of the tree are numbered from 1 to n with the root at vertex 1. For each vertex, the reservoirs of its children are located below the reservoir of this vertex, and the vertex is connected with each of the children by a pipe through which water can flow downwards.Mike wants to do the following operations with the tree: Fill vertex v with water. Then v and all its children are filled with water. Empty vertex v. Then v and all its ancestors are emptied. Determine whether vertex v is filled with water at the moment. Initially all vertices of the tree are empty.Mike has already compiled a full list of operations that he wants to perform in order. Before experimenting with the tree Mike decided to run the list through a simulation. Help Mike determine what results will he get after performing all the operations.InputThe first line of the input contains an integer n (1 ≀ n ≀ 500000) β€” the number of vertices in the tree. Each of the following n - 1 lines contains two space-separated numbers ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi) β€” the edges of the tree.The next line contains a number q (1 ≀ q ≀ 500000) β€” the number of operations to perform. Each of the following q lines contains two space-separated numbers ci (1 ≀ ci ≀ 3), vi (1 ≀ vi ≀ n), where ci is the operation type (according to the numbering given in the statement), and vi is the vertex on which the operation is performed.It is guaranteed that the given graph is a tree.OutputFor each type 3 operation print 1 on a separate line if the vertex is full, and 0 if the vertex is empty. Print the answers to queries in the order in which the queries are given in the input.ExamplesInput51 25 12 34 2121 12 33 13 23 33 41 22 43 13 33 43 5Output00010101
Input51 25 12 34 2121 12 33 13 23 33 41 22 43 13 33 43 5
Output00010101
4 seconds
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'trees', '*2100']
C. Read Timetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel.When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the i-th reading head is above the track number hi. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered read if at least one head has visited this track. In particular, all of the tracks numbered h1, h2, ..., hn have been read at the beginning of the operation. Mike needs to read the data on m distinct tracks with numbers p1, p2, ..., pm. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.InputThe first line of the input contains two space-separated integers n, m (1 ≀ n, m ≀ 105) β€” the number of disk heads and the number of tracks to read, accordingly. The second line contains n distinct integers hi in ascending order (1 ≀ hi ≀ 1010, hi < hi + 1) β€” the initial positions of the heads. The third line contains m distinct integers pi in ascending order (1 ≀ pi ≀ 1010, pi < pi + 1) - the numbers of tracks to read.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.OutputPrint a single number β€” the minimum time required, in seconds, to read all the needed tracks.ExamplesInput3 42 5 61 3 6 8Output2Input3 31 2 31 2 3Output0Input1 2165142 200Output81NoteThe first test coincides with the figure. In this case the given tracks can be read in 2 seconds in the following way: during the first second move the 1-st head to the left and let it stay there; move the second head to the left twice; move the third head to the right twice (note that the 6-th track has already been read at the beginning). One cannot read the tracks in 1 second as the 3-rd head is at distance 2 from the 8-th track.
Input3 42 5 61 3 6 8
Output2
1 second
256 megabytes
['binary search', 'greedy', 'two pointers', '*1900']
B. Alternating Currenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view): Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.InputThe single line of the input contains a sequence of characters "+" and "-" of length n (1 ≀ n ≀ 100000). The i-th (1 ≀ i ≀ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.OutputPrint either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.ExamplesInput-++-OutputYesInput+-OutputNoInput++OutputYesInput-OutputNoNoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled: In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher: In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:
Input-++-
OutputYes
1 second
256 megabytes
['data structures', 'greedy', 'implementation', '*1600']
A. Rational Resistancetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements: one resistor; an element and one resistor plugged in sequence; an element and one resistor plugged in parallel. With the consecutive connection the resistance of the new element equals R = Re + R0. With the parallel connection the resistance of the new element equals . In this case Re equals the resistance of the element being connected.Mike needs to assemble an element with a resistance equal to the fraction . Determine the smallest possible number of resistors he needs to make such an element.InputThe single input line contains two space-separated integers a and b (1 ≀ a, b ≀ 1018). It is guaranteed that the fraction is irreducible. It is guaranteed that a solution always exists.OutputPrint a single number β€” the answer to the problem.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specifier.ExamplesInput1 1Output1Input3 2Output3Input199 200Output200NoteIn the first sample, one resistor is enough.In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance . We cannot make this element using two resistors.
Input1 1
Output1
1 second
256 megabytes
['math', 'number theory', '*1600']
E. Xenia and Treetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia the programmer has a tree consisting of n nodes. We will consider the tree nodes indexed from 1 to n. We will also consider the first node to be initially painted red, and the other nodes β€” to be painted blue.The distance between two tree nodes v and u is the number of edges in the shortest path between v and u.Xenia needs to learn how to quickly execute queries of two types: paint a specified blue node in red; calculate which red node is the closest to the given one and print the shortest distance to the closest red node. Your task is to write a program which will execute the described queries.InputThe first line contains two integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of nodes in the tree and the number of queries. Next n - 1 lines contain the tree edges, the i-th line contains a pair of integers ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi) β€” an edge of the tree.Next m lines contain queries. Each query is specified as a pair of integers ti, vi (1 ≀ ti ≀ 2, 1 ≀ vi ≀ n). If ti = 1, then as a reply to the query we need to paint a blue node vi in red. If ti = 2, then we should reply to the query by printing the shortest distance from some red node to node vi.It is guaranteed that the given graph is a tree and that all queries are correct.OutputFor each second type query print the reply in a single line.ExamplesInput5 41 22 32 44 52 12 51 22 5Output032
Input5 41 22 32 44 52 12 51 22 5
Output032
5 seconds
256 megabytes
['data structures', 'divide and conquer', 'trees', '*2400']
D. Xenia and Dominoestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia likes puzzles very much. She is especially fond of the puzzles that consist of domino pieces. Look at the picture that shows one of such puzzles. A puzzle is a 3 × n table with forbidden cells (black squares) containing dominoes (colored rectangles on the picture). A puzzle is called correct if it meets the following conditions: each domino occupies exactly two non-forbidden cells of the table; no two dominoes occupy the same table cell; exactly one non-forbidden cell of the table is unoccupied by any domino (it is marked by a circle in the picture). To solve the puzzle, you need multiple steps to transport an empty cell from the starting position to some specified position. A move is transporting a domino to the empty cell, provided that the puzzle stays correct. The horizontal dominoes can be moved only horizontally, and vertical dominoes can be moved only vertically. You can't rotate dominoes. The picture shows a probable move.Xenia has a 3 × n table with forbidden cells and a cell marked with a circle. Also, Xenia has very many identical dominoes. Now Xenia is wondering, how many distinct correct puzzles she can make if she puts dominoes on the existing table. Also, Xenia wants the circle-marked cell to be empty in the resulting puzzle. The puzzle must contain at least one move.Help Xenia, count the described number of puzzles. As the described number can be rather large, print the remainder after dividing it by 1000000007 (109 + 7).InputThe first line contains integer n (3 ≀ n ≀ 104) β€” the puzzle's size. Each of the following three lines contains n characters β€” the description of the table. The j-th character of the i-th line equals "X" if the corresponding cell is forbidden; it equals ".", if the corresponding cell is non-forbidden and "O", if the corresponding cell is marked with a circle.It is guaranteed that exactly one cell in the table is marked with a circle. It is guaranteed that all cells of a given table having at least one common point with the marked cell is non-forbidden.OutputPrint a single number β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput5....X.O......X.Output1Input5......O........Output2Input3........OOutput4NoteTwo puzzles are considered distinct if there is a pair of cells that contain one domino in one puzzle and do not contain it in the other one.
Input5....X.O......X.
Output1
2 seconds
256 megabytes
['bitmasks', 'dfs and similar', 'dp', '*2100']
C. Cupboard and Balloonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius r (the cupboard's top) and two walls of height h (the cupboard's sides). The cupboard's depth is r, that is, it looks like a rectangle with base r and height h + r from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right). Xenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius . Help Xenia calculate the maximum number of balloons she can put in her cupboard. You can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin.InputThe single line contains two integers r, h (1 ≀ r, h ≀ 107).OutputPrint a single integer β€” the maximum number of balloons Xenia can put in the cupboard.ExamplesInput1 1Output3Input1 2Output5Input2 1Output2
Input1 1
Output3
2 seconds
256 megabytes
['geometry', '*1900']
B. Xenia and Spiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia the vigorous detective faced n (n β‰₯ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step ti (steps are numbered from 1) Xenia watches spies numbers li, li + 1, li + 2, ..., ri (1 ≀ li ≀ ri ≀ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).InputThe first line contains four integers n, m, s and f (1 ≀ n, m ≀ 105;Β 1 ≀ s, f ≀ n;Β s ≠ f;Β n β‰₯ 2). Each of the following m lines contains three integers ti, li, ri (1 ≀ ti ≀ 109, 1 ≀ li ≀ ri ≀ n). It is guaranteed that t1 < t2 < t3 < ... < tm.OutputPrint k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal "L". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal "R". If the spy must keep the note at the i-th step, the i-th character must equal "X".As a result of applying the printed sequence of actions spy s must pass the note to spy f. The number of printed characters k must be as small as possible. Xenia must not catch the spies passing the note.If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists.ExamplesInput3 5 1 31 1 22 2 33 3 34 1 110 1 3OutputXXRR
Input3 5 1 31 1 22 2 33 3 34 1 110 1 3
OutputXXRR
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*1500']
A. Xenia and Divisorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held: a < b < c; a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has groups of three.Help Xenia, find the required partition or else say that it doesn't exist.InputThe first line contains integer n (3 ≀ n ≀ 99999) β€” the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7.It is guaranteed that n is divisible by 3.OutputIf the required partition exists, print groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them.If there is no solution, print -1.ExamplesInput61 1 1 2 2 2Output-1Input62 2 1 1 4 6Output1 2 41 2 6
Input61 1 1 2 2 2
Output-1
1 second
256 megabytes
['greedy', 'implementation', '*1200']
E. Candies Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIahub is playing an uncommon game. Initially, he has n boxes, numbered 1, 2, 3, ..., n. Each box has some number of candies in it, described by a sequence a1, a2, ..., an. The number ak represents the number of candies in box k. The goal of the game is to move all candies into exactly two boxes. The rest of n - 2 boxes must contain zero candies. Iahub is allowed to do several (possible zero) moves. At each move he chooses two different boxes i and j, such that ai ≀ aj. Then, Iahub moves from box j to box i exactly ai candies. Obviously, when two boxes have equal number of candies, box number j becomes empty.Your task is to give him a set of moves such as Iahub to archive the goal of the game. If Iahub can't win the game for the given configuration of boxes, output -1. Please note that in case there exist a solution, you don't need to print the solution using minimal number of moves.InputThe first line of the input contains integer n (3 ≀ n ≀ 1000). The next line contains n non-negative integers: a1, a2, ..., an β€” sequence elements. It is guaranteed that sum of all numbers in sequence a is up to 106. OutputIn case there exists no solution, output -1. Otherwise, in the first line output integer c (0 ≀ c ≀ 106), representing number of moves in your solution. Each of the next c lines should contain two integers i and j (1 ≀ i, j ≀ n, i ≠ j): integers i, j in the kth line mean that at the k-th move you will move candies from the j-th box to the i-th one.ExamplesInput33 6 9Output22 31 3Input30 1 0Output-1Input40 1 1 0Output0NoteFor the first sample, after the first move the boxes will contain 3, 12 and 3 candies. After the second move, the boxes will contain 6, 12 and 0 candies. Now all candies are in exactly 2 boxes.For the second sample, you can observe that the given configuration is not valid, as all candies are in a single box and they should be in two boxes. Also, any move won't change the configuration, so there exists no solution.For the third sample, all candies are already in 2 boxes. Hence, no move is needed.
Input33 6 9
Output22 31 3
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*3000']
D. Iahub and Xorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIahub does not like background stories, so he'll tell you exactly what this problem asks you for.You are given a matrix a with n rows and n columns. Initially, all values of the matrix are zeros. Both rows and columns are 1-based, that is rows are numbered 1, 2, ..., n and columns are numbered 1, 2, ..., n. Let's denote an element on the i-th row and j-th column as ai, j.We will call a submatrix (x0, y0, x1, y1) such elements ai, j for which two inequalities hold: x0 ≀ i ≀ x1, y0 ≀ j ≀ y1.Write a program to perform two following operations: Query(x0, y0, x1, y1): print the xor sum of the elements of the submatrix (x0, y0, x1, y1). Update(x0, y0, x1, y1, v): each element from submatrix (x0, y0, x1, y1) gets xor-ed by value v. InputThe first line contains two integers: n (1 ≀ n ≀ 1000) and m (1 ≀ m ≀ 105). The number m represents the number of operations you need to perform. Each of the next m lines contains five or six integers, depending on operation type. If the i-th operation from the input is a query, the first number from i-th line will be 1. It will be followed by four integers x0, y0, x1, y1. If the i-th operation is an update, the first number from the i-th line will be 2. It will be followed by five integers x0, y0, x1, y1, v. It is guaranteed that for each update operation, the following inequality holds: 0 ≀ v < 262. It is guaranteed that for each operation, the following inequalities hold: 1 ≀ x0 ≀ x1 ≀ n, 1 ≀ y0 ≀ y1 ≀ n.OutputFor each query operation, output on a new line the result.ExamplesInput3 52 1 1 2 2 12 1 3 2 3 22 3 1 3 3 31 2 2 3 31 2 2 3 2Output32NoteAfter the first 3 operations, the matrix will look like this: 1 1 21 1 23 3 3The fourth operation asks us to compute 1 xor 2 xor 3 xor 3 = 3.The fifth operation asks us to compute 1 xor 3 = 2.
Input3 52 1 1 2 2 12 1 3 2 3 22 3 1 3 3 31 2 2 3 31 2 2 3 2
Output32
1 second
256 megabytes
['data structures', '*2500']
E. Iahub and Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.The girl finds an important permutation for the research. The permutation contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ n). She replaces some of permutation elements with -1 value as a revenge. When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element ak which has value equal to k (ak = k). Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo 1000000007 (109 + 7).InputThe first line contains integer n (2 ≀ n ≀ 2000). On the second line, there are n integers, representing Iahub's important permutation after Iahubina replaces some values with -1. It's guaranteed that there are no fixed points in the given permutation. Also, the given sequence contains at least two numbers -1 and each positive number occurs in the sequence at most once. It's guaranteed that there is at least one suitable permutation.OutputOutput a single integer, the number of ways Iahub could recover his permutation, modulo 1000000007 (109 + 7).ExamplesInput5-1 -1 4 3 -1Output2NoteFor the first test example there are two permutations with no fixed points are [2, 5, 4, 3, 1] and [5, 1, 4, 3, 2]. Any other permutation would have at least one fixed point.
Input5-1 -1 4 3 -1
Output2
1 second
256 megabytes
['combinatorics', 'math', '*2000']
D. Bubble Sort Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode). procedure bubbleSortGraph() build a graph G with n vertices and 0 edges repeat swapped = false for i = 1 to n - 1 inclusive do: if a[i] > a[i + 1] then add an undirected edge in G between a[i] and a[i + 1] swap( a[i], a[i + 1] ) swapped = true end if end for until not swapped /* repeat the algorithm as long as swapped value is true. */ end procedureFor a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph G, if we use such permutation as the premutation a in procedure bubbleSortGraph.InputThe first line of the input contains an integer n (2 ≀ n ≀ 105). The next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ n).OutputOutput a single integer β€” the answer to the problem. ExamplesInput33 1 2Output2NoteConsider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
Input33 1 2
Output2
1 second
256 megabytes
['binary search', 'data structures', 'dp', '*1500']
C. Tourist Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.InputThe first line contains integer n (2 ≀ n ≀ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 107).OutputOutput two integers β€” the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.ExamplesInput32 3 5Output22 3NoteConsider 6 possible routes: [2, 3, 5]: total distance traveled: |2 – 0| + |3 – 2| + |5 – 3| = 5; [2, 5, 3]: |2 – 0| + |5 – 2| + |3 – 5| = 7; [3, 2, 5]: |3 – 0| + |2 – 3| + |5 – 2| = 7; [3, 5, 2]: |3 – 0| + |5 – 3| + |2 – 5| = 8; [5, 2, 3]: |5 – 0| + |2 – 5| + |3 – 2| = 9; [5, 3, 2]: |5 – 0| + |3 – 5| + |2 – 3| = 8. The average travel distance is = = .
Input32 3 5
Output22 3
1 second
256 megabytes
['combinatorics', 'implementation', 'math', '*1600']
B. Maximal Area Quadrilateraltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIahub has drawn a set of n points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral. InputThe first line contains integer n (4 ≀ n ≀ 300). Each of the next n lines contains two integers: xi, yi ( - 1000 ≀ xi, yi ≀ 1000) β€” the cartesian coordinates of ith special point. It is guaranteed that no three points are on the same line. It is guaranteed that no two points coincide. OutputOutput a single real number β€” the maximal area of a special quadrilateral. The answer will be considered correct if its absolute or relative error does't exceed 10 - 9.ExamplesInput50 00 44 04 42 3Output16.000000NoteIn the test example we can choose first 4 points to be the vertices of the quadrilateral. They form a square by side 4, so the area is 4Β·4 = 16.
Input50 00 44 04 42 3
Output16.000000
1 second
256 megabytes
['brute force', 'geometry', '*2100']
A. The Walltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered 1, 2, 3 and so on. Iahub has the following scheme of painting: he skips x - 1 consecutive bricks, then he paints the x-th one. That is, he'll paint bricks x, 2Β·x, 3Β·x and so on red. Similarly, Floyd skips y - 1 consecutive bricks, then he paints the y-th one. Hence he'll paint bricks y, 2Β·y, 3Β·y and so on pink.After painting the wall all day, the boys observed that some bricks are painted both red and pink. Iahub has a lucky number a and Floyd has a lucky number b. Boys wonder how many bricks numbered no less than a and no greater than b are painted both red and pink. This is exactly your task: compute and print the answer to the question. InputThe input will have a single line containing four integers in this order: x, y, a, b. (1 ≀ x, y ≀ 1000, 1 ≀ a, b ≀ 2Β·109, a ≀ b).OutputOutput a single integer β€” the number of bricks numbered no less than a and no greater than b that are painted both red and pink.ExamplesInput2 3 6 18Output3NoteLet's look at the bricks from a to b (a = 6, b = 18). The bricks colored in red are numbered 6, 8, 10, 12, 14, 16, 18. The bricks colored in pink are numbered 6, 9, 12, 15, 18. The bricks colored in both red and pink are numbered with 6, 12 and 18.
Input2 3 6 18
Output3
1 second
256 megabytes
['math', '*1200']
E. Three Swapstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia the horse breeder has n (n > 1) horses that stand in a row. Each horse has its own unique number. Initially, the i-th left horse has number i. That is, the sequence of numbers of horses in a row looks as follows (from left to right): 1, 2, 3, ..., n.Xenia trains horses before the performance. During the practice sessions, she consistently gives them commands. Each command is a pair of numbers l, r (1 ≀ l < r ≀ n). The command l, r means that the horses that are on the l-th, (l + 1)-th, (l + 2)-th, ..., r-th places from the left must be rearranged. The horses that initially stand on the l-th and r-th places will swap. The horses on the (l + 1)-th and (r - 1)-th places will swap. The horses on the (l + 2)-th and (r - 2)-th places will swap and so on. In other words, the horses that were on the segment [l, r] change their order to the reverse one.For example, if Xenia commanded l = 2, r = 5, and the sequence of numbers of horses before the command looked as (2, 1, 3, 4, 5, 6), then after the command the sequence will be (2, 5, 4, 3, 1, 6).We know that during the practice Xenia gave at most three commands of the described form. You have got the final sequence of numbers of horses by the end of the practice. Find what commands Xenia gave during the practice. Note that you do not need to minimize the number of commands in the solution, find any valid sequence of at most three commands.InputThe first line contains an integer n (2 ≀ n ≀ 1000) β€” the number of horses in the row. The second line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ n), where ai is the number of the i-th left horse in the row after the practice.OutputThe first line should contain integer k (0 ≀ k ≀ 3) β€” the number of commads Xenia gave during the practice. In each of the next k lines print two integers. In the i-th line print numbers li, ri (1 ≀ li < ri ≀ n) β€” Xenia's i-th command during the practice.It is guaranteed that a solution exists. If there are several solutions, you are allowed to print any of them.ExamplesInput51 4 3 2 5Output12 4Input62 1 4 3 6 5Output31 23 45 6
Input51 4 3 2 5
Output12 4
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'greedy', '*2700']
D. Xenia and Bit Operationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.Namely, it takes several iterations to calculate value v. At the first iteration, Xenia writes a new sequence a1Β orΒ a2, a3Β orΒ a4, ..., a2n - 1Β orΒ a2n, consisting of 2n - 1 elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence a. At the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.Let's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1Β orΒ 2 = 3, 3Β orΒ 4 = 7)  →  (3Β xorΒ 7 = 4). The result is v = 4.You are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. Each query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. After each query, you need to print the new value v for the new sequence a.InputThe first line contains two integers n and m (1 ≀ n ≀ 17, 1 ≀ m ≀ 105). The next line contains 2n integers a1, a2, ..., a2n (0 ≀ ai < 230). Each of the next m lines contains queries. The i-th line contains integers pi, bi (1 ≀ pi ≀ 2n, 0 ≀ bi < 230) β€” the i-th query.OutputPrint m integers β€” the i-th integer denotes value v for sequence a after the i-th query.ExamplesInput2 41 6 3 51 43 41 21 2Output1333NoteFor more information on the bit operations, you can follow this link: http://en.wikipedia.org/wiki/Bitwise_operation
Input2 41 6 3 51 43 41 21 2
Output1333
2 seconds
256 megabytes
['data structures', 'trees', '*1700']
C. Xenia and Weightstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of m weights on the scalepans.Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes i-th should be different from the (i + 1)-th weight for any i (1 ≀ i < m). Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay m weights on ​​the scales or to say that it can't be done.InputThe first line contains a string consisting of exactly ten zeroes and ones: the i-th (i β‰₯ 1) character in the line equals "1" if Xenia has i kilo weights, otherwise the character equals "0". The second line contains integer m (1 ≀ m ≀ 1000).OutputIn the first line print "YES", if there is a way to put m weights on the scales by all rules. Otherwise, print in the first line "NO". If you can put m weights on the scales, then print in the next line m integers β€” the weights' weights in the order you put them on the scales.If there are multiple solutions, you can print any of them.ExamplesInput00000001013OutputYES8 10 8Input10000000002OutputNO
Input00000001013
OutputYES8 10 8
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'dp', 'graphs', 'greedy', 'shortest paths', '*1700']
B. Xenia and Ringroadtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.InputThe first line contains two integers n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105). The second line contains m integers a1, a2, ..., am (1 ≀ ai ≀ n). Note that Xenia can have multiple consecutive tasks in one house.OutputPrint a single integer β€” the time Xenia needs to complete all tasks.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput4 33 2 3Output6Input4 32 3 3Output2NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.
Input4 33 2 3
Output6
2 seconds
256 megabytes
['implementation', '*1000']
A. Helpful Mathstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.InputThe first line contains a non-empty string s β€” the sum Xenia needs to count. String s contains no spaces. It only contains digits and characters "+". Besides, string s is a correct sum of numbers 1, 2 and 3. String s is at most 100 characters long.OutputPrint the new sum that Xenia can count.ExamplesInput3+2+1Output1+2+3Input1+1+3+1+3Output1+1+1+3+3Input2Output2
Input3+2+1
Output1+2+3
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', 'strings', '*800']
E. Optimize!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputManao is solving a problem with the following statement: He came up with a solution that produces the correct answers but is too slow. You are given the pseudocode of his solution, where the function getAnswer calculates the answer to the problem:getAnswer(a[1..n], b[1..len], h) answer = 0 for i = 1 to n-len+1 answer = answer + f(a[i..i+len-1], b, h, 1) return answerf(s[1..len], b[1..len], h, index) if index = len+1 then return 1 for i = 1 to len if s[index] + b[i] >= h mem = b[i] b[i] = 0 res = f(s, b, h, index + 1) b[i] = mem if res > 0 return 1 return 0Your task is to help Manao optimize his algorithm.InputThe first line contains space-separated integers n, len and h (1 ≀ len ≀ n ≀ 150000;Β 1 ≀ h ≀ 109). The second line contains len space-separated integers b1, b2, ..., blen (1 ≀ bi ≀ 109). The third line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).OutputPrint a single number β€” the answer to Manao's problem.ExamplesInput5 2 105 31 8 5 5 7Output2
Input5 2 105 31 8 5 5 7
Output2
2 seconds
256 megabytes
['data structures', '*2600']
D. GCD Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a table G of size n × m such that G(i, j) = GCD(i, j) for all 1 ≀ i ≀ n, 1 ≀ j ≀ m. GCD(a, b) is the greatest common divisor of numbers a and b.You have a sequence of positive integer numbers a1, a2, ..., ak. We say that this sequence occurs in table G if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers 1 ≀ i ≀ n and 1 ≀ j ≀ m - k + 1 should exist that G(i, j + l - 1) = al for all 1 ≀ l ≀ k.Determine if the sequence a occurs in table G.InputThe first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1012; 1 ≀ k ≀ 10000). The second line contains k space-separated integers a1, a2, ..., ak (1 ≀ ai ≀ 1012).OutputPrint a single word "YES", if the given sequence occurs in table G, otherwise print "NO".ExamplesInput100 100 55 2 1 2 1OutputYESInput100 8 55 2 1 2 1OutputNOInput100 100 71 2 3 4 5 6 7OutputNONoteSample 1. The tenth row of table G starts from sequence {1, 2, 1, 2, 5, 2, 1, 2, 1, 10}. As you can see, elements from fifth to ninth coincide with sequence a.Sample 2. This time the width of table G equals 8. Sequence a doesn't occur there.
Input100 100 55 2 1 2 1
OutputYES
1 second
256 megabytes
['chinese remainder theorem', 'math', 'number theory', '*2900']
E. Divisor Treetime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA divisor tree is a rooted tree that meets the following conditions: Each vertex of the tree contains a positive integer number. The numbers written in the leaves of the tree are prime numbers. For any inner vertex, the number within it is equal to the product of the numbers written in its children. Manao has n distinct integers a1, a2, ..., an. He tries to build a divisor tree which contains each of these numbers. That is, for each ai, there should be at least one vertex in the tree which contains ai. Manao loves compact style, but his trees are too large. Help Manao determine the minimum possible number of vertices in the divisor tree sought.InputThe first line contains a single integer n (1 ≀ n ≀ 8). The second line contains n distinct space-separated integers ai (2 ≀ ai ≀ 1012).OutputPrint a single integer β€” the minimum number of vertices in the divisor tree that contains each of the numbers ai.ExamplesInput26 10Output7Input46 72 8 4Output12Input17Output1NoteSample 1. The smallest divisor tree looks this way: Sample 2. In this case you can build the following divisor tree: Sample 3. Note that the tree can consist of a single vertex.
Input26 10
Output7
0.5 seconds
256 megabytes
['brute force', 'number theory', 'trees', '*2200']
D. Book of Eviltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPaladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range d. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance d or less from the settlement where the Book resides.Manao has heard of m settlements affected by the Book of Evil. Their numbers are p1, p2, ..., pm. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.InputThe first line contains three space-separated integers n, m and d (1 ≀ m ≀ n ≀ 100000;Β 0 ≀ d ≀ n - 1). The second line contains m distinct space-separated integers p1, p2, ..., pm (1 ≀ pi ≀ n). Then n - 1 lines follow, each line describes a path made in the area. A path is described by a pair of space-separated integers ai and bi representing the ends of this path.OutputPrint a single number β€” the number of settlements that may contain the Book of Evil. It is possible that Manao received some controversial information and there is no settlement that may contain the Book. In such case, print 0.ExamplesInput6 2 31 21 52 33 44 55 6Output3NoteSample 1. The damage range of the Book of Evil equals 3 and its effects have been noticed in settlements 1 and 2. Thus, it can be in settlements 3, 4 or 5.
Input6 2 31 21 52 33 44 55 6
Output3
2 seconds
256 megabytes
['dfs and similar', 'divide and conquer', 'dp', 'trees', '*2000']
C. Quiztime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputManao is taking part in a quiz. The quiz consists of n consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number k, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero.Manao remembers that he has answered exactly m questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by 1000000009 (109 + 9).InputThe single line contains three space-separated integers n, m and k (2 ≀ k ≀ n ≀ 109;Β 0 ≀ m ≀ n).OutputPrint a single integer β€” the remainder from division of Manao's minimum possible score in the quiz by 1000000009 (109 + 9).ExamplesInput5 3 2Output3Input5 4 2Output6NoteSample 1. Manao answered 3 questions out of 5, and his score would double for each two consecutive correct answers. If Manao had answered the first, third and fifth questions, he would have scored as much as 3 points.Sample 2. Now Manao answered 4 questions. The minimum possible score is obtained when the only wrong answer is to the question 4.Also note that you are asked to minimize the score and not the remainder of the score modulo 1000000009. For example, if Manao could obtain either 2000000000 or 2000000020 points, the answer is 2000000000Β modΒ 1000000009, even though 2000000020Β modΒ 1000000009 is a smaller number.
Input5 3 2
Output3
1 second
256 megabytes
['binary search', 'greedy', 'math', 'matrices', 'number theory', '*1600']
B. Routine Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputManao has a monitor. The screen of the monitor has horizontal to vertical length ratio a:b. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio c:d. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the screen as possible and fits within it completely. Thus, he may have to zoom the movie in or out, but Manao will always change the frame proportionally in both dimensions.Calculate the ratio of empty screen (the part of the screen not occupied by the movie) to the total screen size. Print the answer as an irreducible fraction p / q.InputA single line contains four space-separated integers a, b, c, d (1 ≀ a, b, c, d ≀ 1000).OutputPrint the answer to the problem as "p/q", where p is a non-negative integer, q is a positive integer and numbers p and q don't have a common divisor larger than 1.ExamplesInput1 1 3 2Output1/3Input4 3 2 2Output1/4NoteSample 1. Manao's monitor has a square screen. The movie has 3:2 horizontal to vertical length ratio. Obviously, the movie occupies most of the screen if the width of the picture coincides with the width of the screen. In this case, only 2/3 of the monitor will project the movie in the horizontal dimension: Sample 2. This time the monitor's width is 4/3 times larger than its height and the movie's frame is square. In this case, the picture must take up the whole monitor in the vertical dimension and only 3/4 in the horizontal dimension:
Input1 1 3 2
Output1/3
1 second
256 megabytes
['greedy', 'math', 'number theory', '*1400']
A. Puzzlestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).The shop assistant told the teacher that there are m puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of f1 pieces, the second one consists of f2 pieces and so on.Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let A be the number of pieces in the largest puzzle that the teacher buys and B be the number of pieces in the smallest such puzzle. She wants to choose such n puzzles that A - B is minimum possible. Help the teacher and find the least possible value of A - B.InputThe first line contains space-separated integers n and m (2 ≀ n ≀ m ≀ 50). The second line contains m space-separated integers f1, f2, ..., fm (4 ≀ fi ≀ 1000) β€” the quantities of pieces in the puzzles sold in the shop.OutputPrint a single integer β€” the least possible difference the teacher can obtain.ExamplesInput4 610 12 10 7 5 22Output5NoteSample 1. The class has 4 students. The shop sells 6 puzzles. If Ms. Manana buys the first four puzzles consisting of 10, 12, 10 and 7 pieces correspondingly, then the difference between the sizes of the largest and the smallest puzzle will be equal to 5. It is impossible to obtain a smaller difference. Note that the teacher can also buy puzzles 1, 3, 4 and 5 to obtain the difference 5.
Input4 610 12 10 7 5 22
Output5
1 second
256 megabytes
['greedy', '*900']
E. Vasily the Bear and Painting Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasily the bear has two favorite integers n and k and a pencil. Besides, he's got k jars with different water color paints. All jars are numbered in some manner from 1 to k, inclusive. The jar number i contains the paint of the i-th color. Initially the bear took a pencil and drew four segments on the coordinate plane. All of them end at point (0, 0). They begin at: (0, 2n), (0,  - 2n), (2n, 0), ( - 2n, 0). Then for each i = 1, 2, ..., n, the bear drew two squares. The first square has the following vertex coordinates: (2i, 0), ( - 2i, 0), (0,  - 2i), (0, 2i). The second square has the following vertex coordinates: ( - 2i - 1,  - 2i - 1), ( - 2i - 1, 2i - 1), (2i - 1,  - 2i - 1), (2i - 1, 2i - 1). After that, the bear drew another square: (1, 0), ( - 1, 0), (0,  - 1), (0, 1). All points mentioned above form the set of points A.The sample of the final picture at n = 0The sample of the final picture at n = 2The bear decided to paint the resulting picture in k moves. The i-th move consists of the following stages: The bear chooses 3 distinct points in set А so that any pair of the chosen points has a segment on the picture between them. The chosen points and segments mark the area that mustn't contain any previously painted points. The bear paints the area bounded by the chosen points and segments the i-th color. Note that after the k-th move some parts of the picture can stay unpainted.The bear asked you to calculate, how many distinct ways there are to paint his picture. A way to paint the picture is a sequence of three-element sets of points he chose on each step. Two sequences are considered distinct if there is such number i (1 ≀ i ≀ k), that the i-th members of these sequences do not coincide as sets. As the sought number can be rather large, you only need to calculate the remainder after dividing it by number 1000000007 (109 + 7).InputThe first line contains two integers n and k, separated by a space (0 ≀ n, k ≀ 200).OutputPrint exactly one integer β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput0 0Output1Input0 1Output8Input0 2Output32Input1 1Output32
Input0 0
Output1
2 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'implementation', '*2700']
D. Vasily the Bear and Beautiful Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasily the Bear loves beautiful strings. String s is beautiful if it meets the following criteria: String s only consists of characters 0 and 1, at that character 0 must occur in string s exactly n times, and character 1 must occur exactly m times. We can obtain character g from string s with some (possibly, zero) number of modifications. The character g equals either zero or one. A modification of string with length at least two is the following operation: we replace two last characters from the string by exactly one other character. This character equals one if it replaces two zeros, otherwise it equals zero. For example, one modification transforms string "01010" into string "0100", two modifications transform it to "011". It is forbidden to modify a string with length less than two.Help the Bear, count the number of beautiful strings. As the number of beautiful strings can be rather large, print the remainder after dividing the number by 1000000007 (109 + 7). InputThe first line of the input contains three space-separated integers n, m, g (0 ≀ n, m ≀ 105, n + m β‰₯ 1, 0 ≀ g ≀ 1).OutputPrint a single integer β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput1 1 0Output2Input2 2 0Output4Input1 1 1Output0NoteIn the first sample the beautiful strings are: "01", "10".In the second sample the beautiful strings are: "0011", "1001", "1010", "1100".In the third sample there are no beautiful strings.
Input1 1 0
Output2
2 seconds
256 megabytes
['combinatorics', 'math', 'number theory', '*2100']
C. Vasily the Bear and Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1. Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal β€” by "and".InputThe first line contains integer n (1 ≀ n ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ a1 < a2 < ... < an ≀ 109).OutputIn the first line print a single integer k (k > 0), showing how many numbers to write out. In the second line print k integers b1, b2, ..., bk β€” the numbers to write out. You are allowed to print numbers b1, b2, ..., bk in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.ExamplesInput51 2 3 4 5Output24 5Input31 2 4Output14
Input51 2 3 4 5
Output24 5
1 second
256 megabytes
['brute force', 'greedy', 'implementation', 'number theory', '*1800']
B. Vasily the Bear and Flytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne beautiful day Vasily the bear painted 2m circles of the same radius R on a coordinate plane. Circles with numbers from 1 to m had centers at points (2R - R, 0), (4R - R, 0), ..., (2Rm - R, 0), respectively. Circles with numbers from m + 1 to 2m had centers at points (2R - R, 2R), (4R - R, 2R), ..., (2Rm - R, 2R), respectively. Naturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for m2 days. Each day of the experiment got its own unique number from 0 to m2 - 1, inclusive. On the day number i the following things happened: The fly arrived at the coordinate plane at the center of the circle with number ( is the result of dividing number x by number y, rounded down to an integer). The fly went along the coordinate plane to the center of the circle number ( is the remainder after dividing number x by number y). The bear noticed that the fly went from the center of circle v to the center of circle u along the shortest path with all points lying on the border or inside at least one of the 2m circles. After the fly reached the center of circle u, it flew away in an unknown direction. Help Vasily, count the average distance the fly went along the coordinate plane during each of these m2 days.InputThe first line contains two integers m, R (1 ≀ m ≀ 105, 1 ≀ R ≀ 10).OutputIn a single line print a single real number β€” the answer to the problem. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.ExamplesInput1 1Output2.0000000000Input2 2Output5.4142135624NoteFigure to the second sample
Input1 1
Output2.0000000000
1 second
256 megabytes
['math', '*1900']
A. Vasily the Bear and Triangletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasily the bear has a favorite rectangle, it has one vertex at point (0, 0), and the opposite vertex at point (x, y). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes. Vasya also loves triangles, if the triangles have one vertex at point B = (0, 0). That's why today he asks you to find two points A = (x1, y1) and C = (x2, y2), such that the following conditions hold: the coordinates of points: x1, x2, y1, y2 are integers. Besides, the following inequation holds: x1 < x2; the triangle formed by point A, B and C is rectangular and isosceles ( is right); all points of the favorite rectangle are located inside or on the border of triangle ABC; the area of triangle ABC is as small as possible. Help the bear, find the required points. It is not so hard to proof that these points are unique.InputThe first line contains two integers x, y ( - 109 ≀ x, y ≀ 109, x ≠ 0, y ≠ 0).OutputPrint in the single line four integers x1, y1, x2, y2 β€” the coordinates of the required points.ExamplesInput10 5Output0 15 15 0Input-10 5Output-15 0 0 15NoteFigure to the first sample
Input10 5
Output0 15 15 0
1 second
256 megabytes
['implementation', 'math', '*1000']
F. Buy One, Get One Freetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.InputInput will begin with an integer n (1 ≀ n ≀ 500000), the number of pies you wish to acquire. Following this is a line with n integers, each indicating the cost of a pie. All costs are positive integers not exceeding 109.OutputPrint the minimum cost to acquire all the pies.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput63 4 5 3 4 5Output14Input55 5 5 5 5Output25Input4309999 6000 2080 2080Output314159NoteIn the first test case you can pay for a pie with cost 5 and get a pie with cost 4 for free, then pay for a pie with cost 5 and get a pie with cost 3 for free, then pay for a pie with cost 4 and get a pie with cost 3 for free.In the second test case you have to pay full price for every pie.
Input63 4 5 3 4 5
Output14
5 seconds
256 megabytes
['dp', 'greedy', '*3000']
E. Counting Skyscraperstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between 2 and 314! (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height i having probability 2 - i for all positive integers i. The floors of a skyscraper with height i are numbered 0 through i - 1.To speed up transit times, a number of zip lines were installed between skyscrapers. Specifically, there is a zip line connecting the i-th floor of one skyscraper with the i-th floor of another skyscraper if and only if there are no skyscrapers between them that have an i-th floor.Alice and Bob decide to count the number of skyscrapers.Alice is thorough, and wants to know exactly how many skyscrapers there are. She begins at the leftmost skyscraper, with a counter at 1. She then moves to the right, one skyscraper at a time, adding 1 to her counter each time she moves. She continues until she reaches the rightmost skyscraper.Bob is impatient, and wants to finish as fast as possible. He begins at the leftmost skyscraper, with a counter at 1. He moves from building to building using zip lines. At each stage Bob uses the highest available zip line to the right, but ignores floors with a height greater than h due to fear of heights. When Bob uses a zip line, he travels too fast to count how many skyscrapers he passed. Instead, he just adds 2i to his counter, where i is the number of the floor he's currently on. He continues until he reaches the rightmost skyscraper.Consider the following example. There are 6 buildings, with heights 1, 4, 3, 4, 1, 2 from left to right, and h = 2. Alice begins with her counter at 1 and then adds 1 five times for a result of 6. Bob begins with his counter at 1, then he adds 1, 4, 4, and 2, in order, for a result of 12. Note that Bob ignores the highest zip line because of his fear of heights (h = 2). Bob's counter is at the top of the image, and Alice's counter at the bottom. All zip lines are shown. Bob's path is shown by the green dashed line and Alice's by the pink dashed line. The floors of the skyscrapers are numbered, and the zip lines Bob uses are marked with the amount he adds to his counter.When Alice and Bob reach the right-most skyscraper, they compare counters. You will be given either the value of Alice's counter or the value of Bob's counter, and must compute the expected value of the other's counter.InputThe first line of input will be a name, either string "Alice" or "Bob". The second line of input contains two integers n and h (2 ≀ n ≀ 30000, 0 ≀ h ≀ 30). If the name is "Alice", then n represents the value of Alice's counter when she reaches the rightmost skyscraper, otherwise n represents the value of Bob's counter when he reaches the rightmost skyscraper; h represents the highest floor number Bob is willing to use.OutputOutput a single real value giving the expected value of the Alice's counter if you were given Bob's counter, or Bob's counter if you were given Alice's counter. You answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.ExamplesInputAlice3 1Output3.500000000InputBob2 30Output2InputAlice2572 10Output3439.031415943NoteIn the first example, Bob's counter has a 62.5% chance of being 3, a 25% chance of being 4, and a 12.5% chance of being 5.
InputAlice3 1
Output3.500000000
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*2800']
D. Rectangles and Squaretime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given n rectangles, labeled 1 through n. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).Your task is to determine if there's a non-empty subset of the rectangles that forms a square. That is, determine if there exists a subset of the rectangles and some square for which every point that belongs to the interior or the border of that square belongs to the interior or the border of at least one of the rectangles in the subset, and every point that belongs to the interior or the border of at least one rectangle in the subset belongs to the interior or the border of that square.InputFirst line contains a single integer n (1 ≀ n ≀ 105) β€” the number of rectangles. Each of the next n lines contains a description of a rectangle, with the i-th such line describing the rectangle labeled i. Each rectangle description consists of four integers: x1, y1, x2, y2 β€” coordinates of the bottom left and the top right corners (0 ≀ x1 < x2 ≀ 3000, 0 ≀ y1 < y2 ≀ 3000).No two rectangles overlap (that is, there are no points that belong to the interior of more than one rectangle).OutputIf such a subset exists, print "YES" (without quotes) on the first line of the output file, followed by k, the number of rectangles in the subset. On the second line print k numbers β€” the labels of rectangles in the subset in any order. If more than one such subset exists, print any one. If no such subset exists, print "NO" (without quotes).ExamplesInput90 0 1 91 0 9 11 8 9 98 1 9 82 2 3 63 2 7 32 6 7 75 3 7 63 3 5 6OutputYES 55 6 7 8 9Input40 0 1 91 0 9 11 8 9 98 1 9 8OutputNONoteThe first test case looks as follows: Note that rectangles 6, 8, and 9 form a square as well, and would be an acceptable answer.The second test case looks as follows:
Input90 0 1 91 0 9 11 8 9 98 1 9 82 2 3 63 2 7 32 6 7 75 3 7 63 3 5 6
OutputYES 55 6 7 8 9
3 seconds
512 megabytes
['brute force', 'dp', '*2400']
C. More Reclamationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a far away land, there are two cities near a river. One day, the cities decide that they have too little space and would like to reclaim some of the river area into land.The river area can be represented by a grid with r rows and exactly two columns β€” each cell represents a rectangular area. The rows are numbered 1 through r from top to bottom, while the columns are numbered 1 and 2.Initially, all of the cells are occupied by the river. The plan is to turn some of those cells into land one by one, with the cities alternately choosing a cell to reclaim, and continuing until no more cells can be reclaimed.However, the river is also used as a major trade route. The cities need to make sure that ships will still be able to sail from one end of the river to the other. More formally, if a cell (r, c) has been reclaimed, it is not allowed to reclaim any of the cells (r - 1, 3 - c), (r, 3 - c), or (r + 1, 3 - c).The cities are not on friendly terms, and each city wants to be the last city to reclaim a cell (they don't care about how many cells they reclaim, just who reclaims a cell last). The cities have already reclaimed n cells. Your job is to determine which city will be the last to reclaim a cell, assuming both choose cells optimally from current moment.InputThe first line consists of two integers r and n (1 ≀ r ≀ 100, 0 ≀ n ≀ r). Then n lines follow, describing the cells that were already reclaimed. Each line consists of two integers: ri and ci (1 ≀ ri ≀ r, 1 ≀ ci ≀ 2), which represent the cell located at row ri and column ci. All of the lines describing the cells will be distinct, and the reclaimed cells will not violate the constraints above.OutputOutput "WIN" if the city whose turn it is to choose a cell can guarantee that they will be the last to choose a cell. Otherwise print "LOSE".ExamplesInput3 11 1OutputWINInput12 24 18 1OutputWINInput1 11 2OutputLOSENoteIn the first example, there are 3 possible cells for the first city to reclaim: (2, 1), (3, 1), or (3, 2). The first two possibilities both lose, as they leave exactly one cell for the other city. However, reclaiming the cell at (3, 2) leaves no more cells that can be reclaimed, and therefore the first city wins. In the third example, there are no cells that can be reclaimed.
Input3 11 1
OutputWIN
2 seconds
256 megabytes
['games', '*2100']
B. Palindrometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a string s, determine if it contains any palindrome of length exactly 100 as a subsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.InputThe only line of the input contains one string s of length n (1 ≀ n ≀ 5Β·104) containing only lowercase English letters.OutputIf s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.If there exists multiple answers, you are allowed to print any of them.ExamplesInputbbbabcbbbOutputbbbcbbbInputrquwmzexectvnbanemsmdufrgOutputrumenanemurNoteA subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward.
Inputbbbabcbbb
Outputbbbcbbb
2 seconds
256 megabytes
['constructive algorithms', 'dp', '*1900']
A. Bananatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPiegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.InputThe first line contains string s (1 ≀ |s| ≀ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≀ n ≀ 1000).OutputOn the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1.ExamplesInputbanana4Output2baanInputbanana3Output3nabInputbanana2Output-1NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana".
Inputbanana4
Output2baan
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'greedy', '*1400']
B. Eight Point Setstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers x1, x2, x3 and three more integers y1, y2, y3, such that x1 < x2 < x3, y1 < y2 < y3 and the eight point set consists of all points (xi, yj) (1 ≀ i, j ≀ 3), except for point (x2, y2).You have a set of eight points. Find out if Gerald can use this set?InputThe input consists of eight lines, the i-th line contains two space-separated integers xi and yi (0 ≀ xi, yi ≀ 106). You do not have any other conditions for these points.OutputIn a single line print word "respectable", if the given set of points corresponds to Gerald's decency rules, and "ugly" otherwise.ExamplesInput0 00 10 21 01 22 02 12 2OutputrespectableInput0 01 02 03 04 05 06 07 0OutputuglyInput1 11 21 32 12 22 33 13 2Outputugly
Input0 00 10 21 01 22 02 12 2
Outputrespectable
1 second
256 megabytes
['sortings', '*1400']
A. Candy Bagstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so that all brothers got the same number of candies.InputThe single line contains a single integer n (n is even, 2 ≀ n ≀ 100) β€” the number of Gerald's brothers.OutputLet's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers β€” the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order. It is guaranteed that the solution exists at the given limits.ExamplesInput2Output1 42 3NoteThe sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.
Input2
Output1 42 3
1 second
256 megabytes
['implementation', '*1000']
E. Summer Earningstime limit per test9 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMany schoolchildren look for a job for the summer, and one day, when Gerald was still a schoolboy, he also decided to work in the summer. But as Gerald was quite an unusual schoolboy, he found quite unusual work. A certain Company agreed to pay him a certain sum of money if he draws them three identical circles on a plane. The circles must not interfere with each other (but they may touch each other). He can choose the centers of the circles only from the n options granted by the Company. He is free to choose the radius of the circles himself (all three radiuses must be equal), but please note that the larger the radius is, the more he gets paid. Help Gerald earn as much as possible.InputThe first line contains a single integer n β€” the number of centers (3 ≀ n ≀ 3000). The following n lines each contain two integers xi, yi ( - 104 ≀ xi, yi ≀ 104) β€” the coordinates of potential circle centers, provided by the Company.All given points are distinct.OutputPrint a single real number β€” maximum possible radius of circles. The answer will be accepted if its relative or absolute error doesn't exceed 10 - 6.ExamplesInput30 11 01 1Output0.50000000000000000000Input72 -3-2 -33 0-3 -11 -22 -2-1 0Output1.58113883008418980000
Input30 11 01 1
Output0.50000000000000000000
9 seconds
256 megabytes
['binary search', 'bitmasks', 'brute force', 'geometry', 'sortings', '*2500']
D. Characteristics of Rectanglestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald found a table consisting of n rows and m columns. As a prominent expert on rectangular tables, he immediately counted the table's properties, that is, the minimum of the numbers in the corners of the table (minimum of four numbers). However, he did not like the final value β€” it seemed to be too small. And to make this value larger, he decided to crop the table a little: delete some columns on the left and some on the right, as well as some rows from the top and some from the bottom. Find what the maximum property of the table can be after such cropping. Note that the table should have at least two rows and at least two columns left in the end. The number of cropped rows or columns from each of the four sides can be zero.InputThe first line contains two space-separated integers n and m (2 ≀ n, m ≀ 1000). The following n lines describe the table. The i-th of these lines lists the space-separated integers ai, 1, ai, 2, ..., ai, m (0 ≀ ai, j ≀ 109) β€” the m numbers standing in the i-th row of the table.OutputPrint the answer to the problem.ExamplesInput2 21 23 4Output1Input3 31 0 00 1 11 0 0Output0NoteIn the first test case Gerald cannot crop the table β€” table contains only two rows and only two columns.In the second test case if we'll crop the table, the table will contain zero in some corner cell. Also initially it contains two zeros in the corner cells, so the answer is 0.
Input2 21 23 4
Output1
3 seconds
256 megabytes
['binary search', 'bitmasks', 'brute force', 'implementation', 'sortings', '*2100']
C. Lucky Ticketstime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such tickets and moved on to a more general question. Now he explores k-lucky tickets.Pollard sais that a ticket is k-lucky if we can add arithmetic operation signs between its digits to the left or right of them (i.e., "+", "-", " × ") and brackets so as to obtain the correct arithmetic expression whose value would equal k. For example, ticket "224201016" is 1000-lucky as ( - 2 - (2 + 4)) × (2 + 0) + 1016 = 1000.Pollard was so carried away by the lucky tickets that he signed up for a seminar on lucky tickets and, as far as Gerald knows, Pollard will attend it daily at 7 pm in some famous institute and will commute to it in the same tram for m days. In this tram tickets have eight digits. And Gerald wants to make a surprise for Pollard: each day Pollard will receive a tram k-lucky ticket. The conductor has already agreed to give Pollard certain tickets during all these m days and he only wants Gerald to tell him what kind of tickets to give out. In this regard, help Gerald pick exactly m distinct k-lucky tickets.InputThe single line contains two integers k and m (0 ≀ k ≀ 104, 1 ≀ m ≀ 3Β·105).OutputPrint m lines. Each line must contain exactly 8 digits β€” the k-winning ticket. The tickets may begin with 0, all tickets must be distinct. If there are more than m distinct k-lucky tickets, print any m of them. It is guaranteed that at least m distinct k-lucky tickets exist. The tickets can be printed in any order.ExamplesInput0 3Output000000000000000100000002Input7 4Output00000007000000160000001700000018
Input0 3
Output000000000000000100000002
6 seconds
256 megabytes
['brute force', 'constructive algorithms', '*2700']
B. Chipstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: At least one of the chips at least once fell to the banned cell. At least once two chips were on the same cell. At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.InputThe first line contains two space-separated integers n and m (2 ≀ n ≀ 1000, 0 ≀ m ≀ 105) β€” the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1 ≀ xi, yi ≀ n) β€” the coordinates of the i-th banned cell. All given cells are distinct.Consider the field rows numbered from top to bottom from 1 to n, and the columns β€” from left to right from 1 to n.OutputPrint a single integer β€” the maximum points Gerald can earn in this game.ExamplesInput3 12 2Output0Input3 0Output1Input4 33 13 23 3Output1NoteIn the first test the answer equals zero as we can't put chips into the corner cells.In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4).
Input3 12 2
Output0
1 second
256 megabytes
['greedy', '*1800']
A. Secretstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.InputThe single line contains a single integer n (1 ≀ n ≀ 1017).Please, do not use the %lld specifier to read or write 64 bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.OutputIn a single line print an integer: the maximum number of coins the unlucky buyer could have paid with.ExamplesInput1Output1Input4Output2NoteIn the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change.In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives.
Input1
Output1
1 second
256 megabytes
['greedy', '*1600']
E. Binary Keytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's assume that p and q are strings of positive length, called the container and the key correspondingly, string q only consists of characters 0 and 1. Let's take a look at a simple algorithm that extracts message s from the given container p:i = 0;j = 0;s = <>;while i is less than the length of the string p{ if q[j] == 1, then add to the right of string s character p[i]; increase variables i, j by one; if the value of the variable j equals the length of the string q, then j = 0; }In the given pseudocode i, j are integer variables, s is a string, '=' is an assignment operator, '==' is a comparison operation, '[]' is the operation of obtaining the string character with the preset index, '<>' is an empty string. We suppose that in all strings the characters are numbered starting from zero. We understand that implementing such algorithm is quite easy, so your task is going to be slightly different. You need to construct the lexicographically minimum key of length k, such that when it is used, the algorithm given above extracts message s from container p (otherwise find out that such key doesn't exist).InputThe first two lines of the input are non-empty strings p and s (1 ≀ |p| ≀ 106, 1 ≀ |s| ≀ 200), describing the container and the message, correspondingly. The strings can contain any characters with the ASCII codes from 32 to 126, inclusive.The third line contains a single integer k (1 ≀ k ≀ 2000) β€” the key's length.OutputPrint the required key (string of length k, consisting only of characters 0 and 1). If the key doesn't exist, print the single character 0.ExamplesInputabacabaaba6Output100001Inputabacabaaba3Output0NoteString x = x1x2... xp is lexicographically smaller than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there exists such integer r (0 ≀ r < min(p, q)) that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. Symbols are compared according to their ASCII codes.
Inputabacabaaba6
Output100001
4 seconds
256 megabytes
['dp', 'greedy', 'implementation', '*2400']
D. Theft of Blueprintstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInsurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!InputThe first line contains two integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ n - 1) β€” the number of silos and the number of scout groups, correspondingly. The next n - 1 lines describe the polygon plan: the i-th of these lines contains n - i integers ci, i + 1, ci, i + 2, ..., ci, n β€” the number of droids that patrol the corresponding passages (-1 ≀ ci, j ≀ 109; if ci, j =  -1, then silos i and j don't have a passage between them). All passages are bidirectional, that is, we can assume that ci, j = cj, i. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.OutputPrint the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type.Please do not use the %lld specifier to write 64-bit integers in Π‘++. It is preferred to use the cout stream or the %I64d specifier.ExamplesInput6 1-1 -1 -1 8 -1-1 5 -1 -1-1 -1 3-1 -1-1Output5Input3 210 011Output14NoteIn the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} β€” 3, for sets {2}, {4} β€” 5. The mathematical average equals .In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals .
Input6 1-1 -1 -1 8 -1-1 5 -1 -1-1 -1 3-1 -1-1
Output5
3 seconds
256 megabytes
['graphs', 'math', '*2400']
C. Students' Revengetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA student's life is fraught with complications. Some Berland University students know this only too well. Having studied for two years, they contracted strong antipathy towards the chairperson of some department. Indeed, the person in question wasn't the kindest of ladies to begin with: prone to reforming groups, banning automatic passes and other mean deeds. At last the students decided that she just can't get away with all this anymore...The students pulled some strings on the higher levels and learned that the next University directors' meeting is going to discuss n orders about the chairperson and accept exactly p of them. There are two values assigned to each order: ai is the number of the chairperson's hairs that turn grey if she obeys the order and bi β€” the displeasement of the directors if the order isn't obeyed. The students may make the directors pass any p orders chosen by them. The students know that the chairperson will obey exactly k out of these p orders. She will pick the orders to obey in the way that minimizes first, the directors' displeasement and second, the number of hairs on her head that turn grey.The students want to choose p orders in the way that maximizes the number of hairs on the chairperson's head that turn grey. If there are multiple ways to accept the orders, then the students are keen on maximizing the directors' displeasement with the chairperson's actions. Help them.InputThe first line contains three integers n (1 ≀ n ≀ 105), p (1 ≀ p ≀ n), k (1 ≀ k ≀ p) β€” the number of orders the directors are going to discuss, the number of orders to pass and the number of orders to be obeyed by the chairperson, correspondingly. Each of the following n lines contains two integers ai and bi (1 ≀ ai, bi ≀ 109), describing the corresponding order.OutputPrint in an arbitrary order p distinct integers β€” the numbers of the orders to accept so that the students could carry out the revenge. The orders are indexed from 1 to n in the order they occur in the input. If there are multiple solutions, you can print any of them.ExamplesInput5 3 25 65 81 34 34 11Output3 1 2 Input5 3 310 1818 1710 2020 1820 18Output2 4 5 NoteIn the first sample one of optimal solutions is to pass orders 1, 2, 3. In this case the chairperson obeys orders number 1 and 2. She gets 10 new grey hairs in the head and the directors' displeasement will equal 3. Note that the same result can be achieved with order 4 instead of order 3.In the second sample, the chairperson can obey all the orders, so the best strategy for the students is to pick the orders with the maximum sum of ai values. The chairperson gets 58 new gray hairs and the directors' displeasement will equal 0.
Input5 3 25 65 81 34 34 11
Output3 1 2
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*2200']
B. Maximum Absurditytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≀ a ≀ b ≀ n - k + 1, b - a β‰₯ k) and sign all laws with numbers lying in the segments [a;Β a + k - 1] and [b;Β b + k - 1] (borders are included).As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.InputThe first line contains two integers n and k (2 ≀ n ≀ 2Β·105, 0 < 2k ≀ n) β€” the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x1, x2, ..., xn β€” the absurdity of each law (1 ≀ xi ≀ 109).OutputPrint two integers a, b β€” the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a;Β a + k - 1] and [b;Β b + k - 1]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.ExamplesInput5 23 6 1 1 6Output1 4Input6 21 1 1 1 1 1Output1 3NoteIn the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3 + 6 + 1 + 6 = 16.In the second sample mr. Boosch signs laws with numbers from segments [1;2] and [3;4]. The total absurdity of the signed laws equals 1 + 1 + 1 + 1 = 4.
Input5 23 6 1 1 6
Output1 4
2 seconds
256 megabytes
['data structures', 'dp', 'implementation', '*1500']
A. Down the Hatch!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that: he pointed at the person with index (bi + 1)Β modΒ n either with an elbow or with a nod (xΒ modΒ y is the remainder after dividing x by y); if j β‰₯ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice; the turn went to person number (bi + 1)Β modΒ n. The person who was pointed on the last turn did not make any actions.The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.You can assume that in any scenario, there is enough juice for everybody.InputThe first line contains a single integer n (4 ≀ n ≀ 2000) β€” the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns. OutputPrint a single integer β€” the number of glasses of juice Vasya could have drunk if he had played optimally well.ExamplesInput4abbbaOutput1Input4abbabOutput0NoteIn both samples Vasya has got two turns β€” 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.
Input4abbba
Output1
2 seconds
256 megabytes
['implementation', '*1300']
E2. Deja Vutime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody knows that we have been living in the Matrix for a long time. And in the new seventh Matrix the world is ruled by beavers.So let's take beaver Neo. Neo has so-called "deja vu" outbursts when he gets visions of events in some places he's been at or is going to be at. Let's examine the phenomenon in more detail.We can say that Neo's city is represented by a directed graph, consisting of n shops and m streets that connect the shops. No two streets connect the same pair of shops (besides, there can't be one street from A to B and one street from B to A). No street connects a shop with itself. As Neo passes some streets, he gets visions. No matter how many times he passes street k, every time he will get the same visions in the same order. A vision is a sequence of shops.We know that Neo is going to get really shocked if he passes the way from some shop a to some shop b, possible coinciding with a, such that the list of visited shops in the real life and in the visions coincide.Suggest beaver Neo such path of non-zero length. Or maybe you can even count the number of such paths modulo 1000000007 (109 + 7)?..InputThe first line contains integers n and m β€” the number of shops and the number of streets, correspondingly, 1 ≀ n ≀ 50, . Next m lines contain the descriptions of the streets in the following format: xi yi ki v1 v2 ... vk, where xi and yi (1 ≀ xi, yi ≀ n, xi ≠ yi) are numbers of shops connected by a street, ki (0 ≀ ki ≀ n) is the number of visions on the way from xi to yi; v1, v2, ..., vk (1 ≀ vi ≀ n) describe the visions: the numbers of the shops Neo saw. Note that the order of the visions matters.It is guaranteed that the total number of visions on all streets doesn't exceed 105. to get 50 points, you need to find any (not necessarily simple) path of length at most 2Β·n, that meets the attributes described above (subproblem E1); to get 50 more points, you need to count for each length from 1 to 2Β·n the number of paths that have the attribute described above (subproblem E2). OutputSubproblem E1. In the first line print an integer k (1 ≀ k ≀ 2Β·n) β€” the numbers of shops on Neo's path. In the next line print k integers β€” the number of shops in the order Neo passes them. If the graph doesn't have such paths or the length of the shortest path includes more than 2Β·n shops, print on a single line 0.Subproblem E2. Print 2Β·n lines. The i-th line must contain a single integer β€” the number of required paths of length i modulo 1000000007 (109 + 7).ExamplesInput6 61 2 2 1 22 3 1 33 4 2 4 54 5 05 3 1 36 1 1 6Output46 1 2 3Input6 61 2 2 1 22 3 1 33 4 2 4 54 5 05 3 1 36 1 1 6Output121121121121NoteThe input in both samples are the same. The first sample contains the answer to the first subproblem, the second sample contains the answer to the second subproblem.
Input6 61 2 2 1 22 3 1 33 4 2 4 54 5 05 3 1 36 1 1 6
Output46 1 2 3
2 seconds
256 megabytes
['constructive algorithms', 'dp', '*3100']
E1. Deja Vutime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody knows that we have been living in the Matrix for a long time. And in the new seventh Matrix the world is ruled by beavers.So let's take beaver Neo. Neo has so-called "deja vu" outbursts when he gets visions of events in some places he's been at or is going to be at. Let's examine the phenomenon in more detail.We can say that Neo's city is represented by a directed graph, consisting of n shops and m streets that connect the shops. No two streets connect the same pair of shops (besides, there can't be one street from A to B and one street from B to A). No street connects a shop with itself. As Neo passes some streets, he gets visions. No matter how many times he passes street k, every time he will get the same visions in the same order. A vision is a sequence of shops.We know that Neo is going to get really shocked if he passes the way from some shop a to some shop b, possible coinciding with a, such that the list of visited shops in the real life and in the visions coincide.Suggest beaver Neo such path of non-zero length. Or maybe you can even count the number of such paths modulo 1000000007 (109 + 7)?..InputThe first line contains integers n and m β€” the number of shops and the number of streets, correspondingly, 1 ≀ n ≀ 50, . Next m lines contain the descriptions of the streets in the following format: xi yi ki v1 v2 ... vk, where xi and yi (1 ≀ xi, yi ≀ n, xi ≠ yi) are indices of shops connected by a street, ki (0 ≀ ki ≀ n) is the number of visions on the way from xi to yi; v1, v2, ..., vk (1 ≀ vi ≀ n) describe the visions: the numbers of the shops Neo saw. Note that the order of the visions matters.It is guaranteed that the total number of visions on all streets doesn't exceed 105. to get 50 points, you need to find any (not necessarily simple) path of length at most 2Β·n, that meets the attributes described above (subproblem E1); to get 50 more points, you need to count for each length from 1 to 2Β·n the number of paths that have the attribute described above (subproblem E2). OutputSubproblem E1. In the first line print an integer k (1 ≀ k ≀ 2Β·n) β€” the numbers of shops on Neo's path. In the next line print k integers β€” the number of shops in the order Neo passes them. If the graph doesn't have such paths or the length of the shortest path includes more than 2Β·n shops, print on a single line 0.Subproblem E2. Print 2Β·n lines. The i-th line must contain a single integer β€” the number of required paths of length i modulo 1000000007 (109 + 7).ExamplesInput6 61 2 2 1 22 3 1 33 4 2 4 54 5 05 3 1 36 1 1 6Output46 1 2 3Input6 61 2 2 1 22 3 1 33 4 2 4 54 5 05 3 1 36 1 1 6Output121121121121NoteThe input in both samples are the same. The first sample contains the answer to the first subproblem, the second sample contains the answer to the second subproblem.
Input6 61 2 2 1 22 3 1 33 4 2 4 54 5 05 3 1 36 1 1 6
Output46 1 2 3
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'implementation', '*2900']
D3. Escaping on Beaveractortime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDon't put up with what you're sick of! The Smart Beaver decided to escape from the campus of Beaver Science Academy (BSA). BSA is a b × b square on a plane. Each point x, y (0 ≀ x, y ≀ b) belongs to BSA. To make the path quick and funny, the Beaver constructed a Beaveractor, an effective and comfortable types of transport.The campus obeys traffic rules: there are n arrows, parallel to the coordinate axes. The arrows do not intersect and do not touch each other. When the Beaveractor reaches some arrow, it turns in the arrow's direction and moves on until it either reaches the next arrow or gets outside the campus. The Beaveractor covers exactly one unit of space per one unit of time. You can assume that there are no obstacles to the Beaveractor.The BSA scientists want to transport the brand new Beaveractor to the "Academic Tractor" research institute and send the Smart Beaver to do his postgraduate studies and sharpen pencils. They have q plans, representing the Beaveractor's initial position (xi, yi), the initial motion vector wi and the time ti that have passed after the escape started.Your task is for each of the q plans to determine the Smart Beaver's position after the given time.InputThe first line contains two integers: the number of traffic rules n and the size of the campus b, 0 ≀ n, 1 ≀ b. Next n lines contain the rules. Each line of the rules contains four space-separated integers x0, y0, x1, y1 β€” the beginning and the end of the arrow. It is guaranteed that all arrows are parallel to the coordinate axes and have no common points. All arrows are located inside the campus, that is, 0 ≀ x0, y0, x1, y1 ≀ b holds.Next line contains integer q β€” the number of plans the scientists have, 1 ≀ q ≀ 105. The i-th plan is represented by two integers, xi, yi are the Beaveractor's coordinates at the initial time, 0 ≀ xi, yi ≀ b, character wi, that takes value U, D, L, R and sets the initial direction up, down, to the left or to the right correspondingly (the Y axis is directed upwards), and ti β€” the time passed after the escape started, 0 ≀ ti ≀ 1015. to get 30 points you need to solve the problem with constraints n, b ≀ 30 (subproblem D1); to get 60 points you need to solve the problem with constraints n, b ≀ 1000 (subproblems D1+D2); to get 100 points you need to solve the problem with constraints n, b ≀ 105 (subproblems D1+D2+D3). OutputPrint q lines. Each line should contain two integers β€” the Beaveractor's coordinates at the final moment of time for each plan. If the Smart Beaver manages to leave the campus in time ti, print the coordinates of the last point in the campus he visited.ExamplesInput3 30 0 0 10 2 2 23 3 2 3120 0 L 00 0 L 10 0 L 20 0 L 30 0 L 40 0 L 50 0 L 62 0 U 22 0 U 33 0 U 51 3 D 21 3 R 2Output0 00 10 21 22 23 23 22 23 21 32 21 3
Input3 30 0 0 10 2 2 23 3 2 3120 0 L 00 0 L 10 0 L 20 0 L 30 0 L 40 0 L 50 0 L 62 0 U 22 0 U 33 0 U 51 3 D 21 3 R 2
Output0 00 10 21 22 23 23 22 23 21 32 21 3
6 seconds
512 megabytes
['data structures', 'implementation', 'trees', '*3000']
D2. Escaping on Beaveractortime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDon't put up with what you're sick of! The Smart Beaver decided to escape from the campus of Beaver Science Academy (BSA). BSA is a b × b square on a plane. Each point x, y (0 ≀ x, y ≀ b) belongs to BSA. To make the path quick and funny, the Beaver constructed a Beaveractor, an effective and comfortable types of transport.The campus obeys traffic rules: there are n arrows, parallel to the coordinate axes. The arrows do not intersect and do not touch each other. When the Beaveractor reaches some arrow, it turns in the arrow's direction and moves on until it either reaches the next arrow or gets outside the campus. The Beaveractor covers exactly one unit of space per one unit of time. You can assume that there are no obstacles to the Beaveractor.The BSA scientists want to transport the brand new Beaveractor to the "Academic Tractor" research institute and send the Smart Beaver to do his postgraduate studies and sharpen pencils. They have q plans, representing the Beaveractor's initial position (xi, yi), the initial motion vector wi and the time ti that have passed after the escape started.Your task is for each of the q plans to determine the Smart Beaver's position after the given time.InputThe first line contains two integers: the number of traffic rules n and the size of the campus b, 0 ≀ n, 1 ≀ b. Next n lines contain the rules. Each line of the rules contains four space-separated integers x0, y0, x1, y1 β€” the beginning and the end of the arrow. It is guaranteed that all arrows are parallel to the coordinate axes and have no common points. All arrows are located inside the campus, that is, 0 ≀ x0, y0, x1, y1 ≀ b holds.Next line contains integer q β€” the number of plans the scientists have, 1 ≀ q ≀ 105. The i-th plan is represented by two integers, xi, yi are the Beaveractor's coordinates at the initial time, 0 ≀ xi, yi ≀ b, character wi, that takes value U, D, L, R and sets the initial direction up, down, to the left or to the right correspondingly (the Y axis is directed upwards), and ti β€” the time passed after the escape started, 0 ≀ ti ≀ 1015. to get 30 points you need to solve the problem with constraints n, b ≀ 30 (subproblem D1); to get 60 points you need to solve the problem with constraints n, b ≀ 1000 (subproblems D1+D2); to get 100 points you need to solve the problem with constraints n, b ≀ 105 (subproblems D1+D2+D3). OutputPrint q lines. Each line should contain two integers β€” the Beaveractor's coordinates at the final moment of time for each plan. If the Smart Beaver manages to leave the campus in time ti, print the coordinates of the last point in the campus he visited.ExamplesInput3 30 0 0 10 2 2 23 3 2 3120 0 L 00 0 L 10 0 L 20 0 L 30 0 L 40 0 L 50 0 L 62 0 U 22 0 U 33 0 U 51 3 D 21 3 R 2Output0 00 10 21 22 23 23 22 23 21 32 21 3
Input3 30 0 0 10 2 2 23 3 2 3120 0 L 00 0 L 10 0 L 20 0 L 30 0 L 40 0 L 50 0 L 62 0 U 22 0 U 33 0 U 51 3 D 21 3 R 2
Output0 00 10 21 22 23 23 22 23 21 32 21 3
6 seconds
512 megabytes
['graphs', '*2600']
D1. Escaping on Beaveractortime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDon't put up with what you're sick of! The Smart Beaver decided to escape from the campus of Beaver Science Academy (BSA). BSA is a b × b square on a plane. Each point x, y (0 ≀ x, y ≀ b) belongs to BSA. To make the path quick and funny, the Beaver constructed a Beaveractor, an effective and comfortable types of transport.The campus obeys traffic rules: there are n arrows, parallel to the coordinate axes. The arrows do not intersect and do not touch each other. When the Beaveractor reaches some arrow, it turns in the arrow's direction and moves on until it either reaches the next arrow or gets outside the campus. The Beaveractor covers exactly one unit of space per one unit of time. You can assume that there are no obstacles to the Beaveractor.The BSA scientists want to transport the brand new Beaveractor to the "Academic Tractor" research institute and send the Smart Beaver to do his postgraduate studies and sharpen pencils. They have q plans, representing the Beaveractor's initial position (xi, yi), the initial motion vector wi and the time ti that have passed after the escape started.Your task is for each of the q plans to determine the Smart Beaver's position after the given time.InputThe first line contains two integers: the number of traffic rules n and the size of the campus b, 0 ≀ n, 1 ≀ b. Next n lines contain the rules. Each line of the rules contains four space-separated integers x0, y0, x1, y1 β€” the beginning and the end of the arrow. It is guaranteed that all arrows are parallel to the coordinate axes and have no common points. All arrows are located inside the campus, that is, 0 ≀ x0, y0, x1, y1 ≀ b holds.Next line contains integer q β€” the number of plans the scientists have, 1 ≀ q ≀ 105. The i-th plan is represented by two integers, xi, yi are the Beaveractor's coordinates at the initial time, 0 ≀ xi, yi ≀ b, character wi, that takes value U, D, L, R and sets the initial direction up, down, to the left or to the right correspondingly (the Y axis is directed upwards), and ti β€” the time passed after the escape started, 0 ≀ ti ≀ 1015. to get 30 points you need to solve the problem with constraints n, b ≀ 30 (subproblem D1); to get 60 points you need to solve the problem with constraints n, b ≀ 1000 (subproblems D1+D2); to get 100 points you need to solve the problem with constraints n, b ≀ 105 (subproblems D1+D2+D3). OutputPrint q lines. Each line should contain two integers β€” the Beaveractor's coordinates at the final moment of time for each plan. If the Smart Beaver manages to leave the campus in time ti, print the coordinates of the last point in the campus he visited.ExamplesInput3 30 0 0 10 2 2 23 3 2 3120 0 L 00 0 L 10 0 L 20 0 L 30 0 L 40 0 L 50 0 L 62 0 U 22 0 U 33 0 U 51 3 D 21 3 R 2Output0 00 10 21 22 23 23 22 23 21 32 21 3
Input3 30 0 0 10 2 2 23 3 2 3120 0 L 00 0 L 10 0 L 20 0 L 30 0 L 40 0 L 50 0 L 62 0 U 22 0 U 33 0 U 51 3 D 21 3 R 2
Output0 00 10 21 22 23 23 22 23 21 32 21 3
6 seconds
512 megabytes
['dfs and similar', 'implementation', '*2400']
C3. The Great Julya Calendartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.InputThe single line contains the magic integer n, 0 ≀ n. to get 20 points, you need to solve the problem with constraints: n ≀ 106 (subproblem C1); to get 40 points, you need to solve the problem with constraints: n ≀ 1012 (subproblems C1+C2); to get 100 points, you need to solve the problem with constraints: n ≀ 1018 (subproblems C1+C2+C3). OutputPrint a single integer β€” the minimum number of subtractions that turns the magic number to a zero.ExamplesInput24Output5NoteIn the first test sample the minimum number of operations can be reached by the following sequence of subtractions: 24 → 20 → 18 → 10 → 9 → 0
Input24
Output5
2 seconds
256 megabytes
['dp', '*2500']
C2. The Great Julya Calendartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.InputThe single line contains the magic integer n, 0 ≀ n. to get 20 points, you need to solve the problem with constraints: n ≀ 106 (subproblem C1); to get 40 points, you need to solve the problem with constraints: n ≀ 1012 (subproblems C1+C2); to get 100 points, you need to solve the problem with constraints: n ≀ 1018 (subproblems C1+C2+C3). OutputPrint a single integer β€” the minimum number of subtractions that turns the magic number to a zero.ExamplesInput24Output5NoteIn the first test sample the minimum number of operations can be reached by the following sequence of subtractions: 24 → 20 → 18 → 10 → 9 → 0
Input24
Output5
2 seconds
256 megabytes
['dp', '*2400']
C1. The Great Julya Calendartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!"Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero.InputThe single line contains the magic integer n, 0 ≀ n. to get 20 points, you need to solve the problem with constraints: n ≀ 106 (subproblem C1); to get 40 points, you need to solve the problem with constraints: n ≀ 1012 (subproblems C1+C2); to get 100 points, you need to solve the problem with constraints: n ≀ 1018 (subproblems C1+C2+C3). OutputPrint a single integer β€” the minimum number of subtractions that turns the magic number to a zero.ExamplesInput24Output5NoteIn the first test sample the minimum number of operations can be reached by the following sequence of subtractions: 24 → 20 → 18 → 10 → 9 → 0
Input24
Output5
2 seconds
256 megabytes
['dp', '*1100']
B2. Shave Beaver!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, "Beavershave 5000". Beavershave 5000 can shave beavers by families! How does it work? Very easily!There are n beavers, each of them has a unique id from 1 to n. Consider a permutation a1, a2, ..., an of n these beavers. Beavershave 5000 needs one session to shave beavers with ids from x to y (inclusive) if and only if there are such indices i1 < i2 < ... < ik, that ai1 = x, ai2 = x + 1, ..., aik - 1 = y - 1, aik = y. And that is really convenient. For example, it needs one session to shave a permutation of beavers 1, 2, 3, ..., n.If we can't shave beavers from x to y in one session, then we can split these beavers into groups [x, p1], [p1 + 1, p2], ..., [pm + 1, y] (x ≀ p1 < p2 < ... < pm < y), in such a way that the machine can shave beavers in each group in one session. But then Beavershave 5000 needs m + 1 working sessions to shave beavers from x to y.All beavers are restless and they keep trying to swap. So if we consider the problem more formally, we can consider queries of two types: what is the minimum number of sessions that Beavershave 5000 needs to shave beavers with ids from x to y, inclusive? two beavers on positions x and y (the beavers ax and ay) swapped. You can assume that any beaver can be shaved any number of times.InputThe first line contains integer n β€” the total number of beavers, 2 ≀ n. The second line contains n space-separated integers β€” the initial beaver permutation.The third line contains integer q β€” the number of queries, 1 ≀ q ≀ 105. The next q lines contain the queries. Each query i looks as pi xi yi, where pi is the query type (1 is to shave beavers from xi to yi, inclusive, 2 is to swap beavers on positions xi and yi). All queries meet the condition: 1 ≀ xi < yi ≀ n. to get 30 points, you need to solve the problem with constraints: n ≀ 100 (subproblem B1); to get 100 points, you need to solve the problem with constraints: n ≀ 3Β·105 (subproblems B1+B2). Note that the number of queries q is limited 1 ≀ q ≀ 105 in both subproblem B1 and subproblem B2.OutputFor each query with pi = 1, print the minimum number of Beavershave 5000 sessions.ExamplesInput51 3 4 2 561 1 51 3 42 2 31 1 52 1 51 1 5Output2135
Input51 3 4 2 561 1 51 3 42 2 31 1 52 1 51 1 5
Output2135
2 seconds
256 megabytes
['data structures', '*1900']
B1. Shave Beaver!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, "Beavershave 5000". Beavershave 5000 can shave beavers by families! How does it work? Very easily!There are n beavers, each of them has a unique id from 1 to n. Consider a permutation a1, a2, ..., an of n these beavers. Beavershave 5000 needs one session to shave beavers with ids from x to y (inclusive) if and only if there are such indices i1 < i2 < ... < ik, that ai1 = x, ai2 = x + 1, ..., aik - 1 = y - 1, aik = y. And that is really convenient. For example, it needs one session to shave a permutation of beavers 1, 2, 3, ..., n.If we can't shave beavers from x to y in one session, then we can split these beavers into groups [x, p1], [p1 + 1, p2], ..., [pm + 1, y] (x ≀ p1 < p2 < ... < pm < y), in such a way that the machine can shave beavers in each group in one session. But then Beavershave 5000 needs m + 1 working sessions to shave beavers from x to y.All beavers are restless and they keep trying to swap. So if we consider the problem more formally, we can consider queries of two types: what is the minimum number of sessions that Beavershave 5000 needs to shave beavers with ids from x to y, inclusive? two beavers on positions x and y (the beavers ax and ay) swapped. You can assume that any beaver can be shaved any number of times.InputThe first line contains integer n β€” the total number of beavers, 2 ≀ n. The second line contains n space-separated integers β€” the initial beaver permutation.The third line contains integer q β€” the number of queries, 1 ≀ q ≀ 105. The next q lines contain the queries. Each query i looks as pi xi yi, where pi is the query type (1 is to shave beavers from xi to yi, inclusive, 2 is to swap beavers on positions xi and yi). All queries meet the condition: 1 ≀ xi < yi ≀ n. to get 30 points, you need to solve the problem with constraints: n ≀ 100 (subproblem B1); to get 100 points, you need to solve the problem with constraints: n ≀ 3Β·105 (subproblems B1+B2). Note that the number of queries q is limited 1 ≀ q ≀ 105 in both subproblem B1 and subproblem B2.OutputFor each query with pi = 1, print the minimum number of Beavershave 5000 sessions.ExamplesInput51 3 4 2 561 1 51 3 42 2 31 1 52 1 51 1 5Output2135
Input51 3 4 2 561 1 51 3 42 2 31 1 52 1 51 1 5
Output2135
2 seconds
256 megabytes
['implementation', '*1700']
A2. Oh Sweet Beaverettetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output β€” Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me? β€” Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai β€” some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart: The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible; the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same; and of course, the walk should be successful: there must be at least two trees in the woodland belt left. Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?InputThe first line contains a single integer n β€” the initial number of trees in the woodland belt, 2 ≀ n. The second line contains space-separated integers ai β€” the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value. to get 30 points, you need to solve the problem with constraints: n ≀ 100 (subproblem A1); to get 100 points, you need to solve the problem with constraints: n ≀ 3Β·105 (subproblems A1+A2). OutputIn the first line print two integers β€” the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.In the next line print k integers β€” the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.ExamplesInput51 2 3 1 2Output8 11 Input51 -2 3 1 -2Output5 22 5
Input51 2 3 1 2
Output8 11
2 seconds
256 megabytes
['data structures', 'sortings', '*1500']
A1. Oh Sweet Beaverettetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output β€” Oh my sweet Beaverette, would you fancy a walk along a wonderful woodland belt with me? β€” Of course, my Smart Beaver! Let us enjoy the splendid view together. How about Friday night? At this point the Smart Beaver got rushing. Everything should be perfect by Friday, so he needed to prepare the belt to the upcoming walk. He needed to cut down several trees.Let's consider the woodland belt as a sequence of trees. Each tree i is described by the esthetic appeal ai β€” some trees are very esthetically pleasing, others are 'so-so', and some trees are positively ugly!The Smart Beaver calculated that he needed the following effects to win the Beaverette's heart: The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible; the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same; and of course, the walk should be successful: there must be at least two trees in the woodland belt left. Now help the Smart Beaver! Which trees does he need to cut down to win the Beaverette's heart?InputThe first line contains a single integer n β€” the initial number of trees in the woodland belt, 2 ≀ n. The second line contains space-separated integers ai β€” the esthetic appeals of each tree. All esthetic appeals do not exceed 109 in their absolute value. to get 30 points, you need to solve the problem with constraints: n ≀ 100 (subproblem A1); to get 100 points, you need to solve the problem with constraints: n ≀ 3Β·105 (subproblems A1+A2). OutputIn the first line print two integers β€” the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k.In the next line print k integers β€” the numbers of the trees the Beaver needs to cut down. Assume that the trees are numbered from 1 to n from left to right.If there are multiple solutions, print any of them. It is guaranteed that at least two trees have equal esthetic appeal.ExamplesInput51 2 3 1 2Output8 11 Input51 -2 3 1 -2Output5 22 5
Input51 2 3 1 2
Output8 11
2 seconds
256 megabytes
['brute force', 'implementation', '*1400']
B. Road Constructiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given m pairs of cities β€” roads cannot be constructed between these pairs of cities.Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.InputThe first line consists of two integers n and m .Then m lines follow, each consisting of two integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi), which means that it is not possible to construct a road connecting cities ai and bi. Consider the cities are numbered from 1 to n.It is guaranteed that every pair of cities will appear at most once in the input.OutputYou should print an integer s: the minimum number of roads that should be constructed, in the first line. Then s lines should follow, each consisting of two integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi), which means that a road should be constructed between cities ai and bi.If there are several solutions, you may print any of them.ExamplesInput4 11 3Output31 24 22 3NoteThis is one possible solution of the example: These are examples of wrong solutions: The above solution is wrong because it doesn't use the minimum number of edges (4 vs 3). In addition, it also tries to construct a road between cities 1 and 3, while the input specifies that it is not allowed to construct a road between the pair. The above solution is wrong because you need to traverse at least 3 roads to go from city 1 to city 3, whereas in your country it must be possible to go from any city to another by traversing at most 2 roads. Finally, the above solution is wrong because it must be possible to go from any city to another, whereas it is not possible in this country to go from city 1 to 3, 2 to 3, and 4 to 3.
Input4 11 3
Output31 24 22 3
2 seconds
256 megabytes
['constructive algorithms', 'graphs', '*1300']
A. Cakeminatortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows: The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.Please output the maximum number of cake cells that the cakeminator can eat.InputThe first line contains two integers r and c (2 ≀ r, c ≀ 10), denoting the number of rows and the number of columns of the cake. The next r lines each contains c characters β€” the j-th character of the i-th line denotes the content of the cell at row i and column j, and is either one of these: '.' character denotes a cake cell with no evil strawberry; 'S' character denotes a cake cell with an evil strawberry. OutputOutput the maximum number of cake cells that the cakeminator can eat.ExamplesInput3 4S.........S.Output8NoteFor the first example, one possible way to eat the maximum number of cake cells is as follows (perform 3 eats).
Input3 4S.........S.
Output8
1 second
256 megabytes
['brute force', 'implementation', '*800']
E. Eviltime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities on a two dimensional Cartesian plane. The distance between two cities is equal to the Manhattan distance between them (see the Notes for definition). A Hamiltonian cycle of the cities is defined as a permutation of all n cities. The length of this Hamiltonian cycle is defined as the sum of the distances between adjacent cities in the permutation plus the distance between the first and final city in the permutation. Please compute the longest possible length of a Hamiltonian cycle of the given cities.InputThe first line contains an integer n (3 ≀ n ≀ 105). Then n lines follow, each consisting of two integers xi and yi (0 ≀ xi, yi ≀ 109), denoting the coordinates of a city. All given points will be distinct.OutputA single line denoting the longest possible length of a Hamiltonian cycle of the given cities. You should not output the cycle, only its length.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput41 11 22 12 2Output6NoteIn the example, one of the possible Hamiltonian cycles with length 6 is (1, 1) (1, 2) (2, 1) (2, 2). There does not exist any other Hamiltonian cycle with a length greater than 6.The Manhattan distance between two cities (xi, yi) and (xj, yj) is |xi - xj| + |yi - yj|.
Input41 11 22 12 2
Output6
3 seconds
256 megabytes
['math', '*3100']
D. The Evil Temple and the Moving Rockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImportant: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an n × n grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The sound of clashing rocks will awaken the door! Being a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks: '^': this rock moves upwards; '<': this rock moves leftwards; '>': this rock moves rightwards; 'v': this rock moves downwards. To open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already 107 events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated.If a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least x. It is okay for the rocks to continue moving after producing x sounds.The following picture illustrates the four possible scenarios of moving rocks. Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated. Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end. Does not move because a rock is already standing in the path. The blocking rock becomes activated, but no sounds are produced. Does not move because the wall is in the way. No sounds are produced and the movements end. Assume there's an infinite number of rocks of each type in the neighboring room. You know what to do: place the rocks and open the door!InputThe first line will consists of two integers n and x, denoting the size of the room and the number of sounds required to open the door. There will be exactly three test cases for this problem: n = 5, x = 5; n = 3, x = 2; n = 100, x = 105. All of these testcases are in pretest.OutputOutput n lines. Each line consists of n characters β€” the j-th character of the i-th line represents the content of the tile at the i-th row and the j-th column, and should be one of these: '^', '<', '>', or 'v': a rock as described in the problem statement. '.': an empty tile. Then, output two integers r and c (1 ≀ r, c ≀ n) on the next line β€” this means that the rock you activate first is located at the r-th row from above and c-th column from the left. There must be a rock in this cell.If there are multiple solutions, you may output any of them.ExamplesInput5 5Output>...vv.<....^..>......^.<1 1Input3 2Output>vv^<.^.<1 3NoteHere's a simulation of the first example, accompanied with the number of sounds produced so far. 0 sound 1 sound 2 sounds 3 sounds 4 sounds still 4 sounds In the picture above, the activated rock switches between the '^' rock and the '<' rock. However, no sound is produced since the '^' rock didn't move even a single tile. So, still 4 sound. 5 sounds At this point, 5 sound are already produced, so this solution is already correct. However, for the sake of example, we will continue simulating what happens. 6 sounds 7 sounds still 7 sounds 8 sounds And the movement stops. In total, it produces 8 sounds. Notice that the last move produced sound.Here's a simulation of the second example: 0 sound 1 sound 2 sounds Now, the activated stone will switch continuously from one to another without producing a sound until it reaches the 107 limit, after which the movement will cease. In total, it produced exactly 2 sounds, so the solution is correct.
Input5 5
Output>...vv.<....^..>......^.<1 1
2 seconds
256 megabytes
['constructive algorithms', '*2500']
C. Graph Reconstructiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputI have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself.I would like to create a new graph in such a way that: The new graph consists of the same number of nodes and edges as the old graph. The properties in the first paragraph still hold. For each two nodes u and v, if there is an edge connecting them in the old graph, there is no edge connecting them in the new graph. Help me construct the new graph, or tell me if it is impossible.InputThe first line consists of two space-separated integers: n and m (1 ≀ m ≀ n ≀ 105), denoting the number of nodes and edges, respectively. Then m lines follow. Each of the m lines consists of two space-separated integers u and v (1 ≀ u, v ≀ n;Β u ≠ v), denoting an edge between nodes u and v.OutputIf it is not possible to construct a new graph with the mentioned properties, output a single line consisting of -1. Otherwise, output exactly m lines. Each line should contain a description of edge in the same way as used in the input format.ExamplesInput8 71 22 34 55 66 88 77 4Output1 44 61 62 77 58 52 8Input3 21 22 3Output-1Input5 41 22 33 44 1Output1 33 55 22 4NoteThe old graph of the first example:A possible new graph for the first example:In the second example, we cannot create any new graph.The old graph of the third example:A possible new graph for the third example:
Input8 71 22 34 55 66 88 77 4
Output1 44 61 62 77 58 52 8
3 seconds
256 megabytes
['constructive algorithms', '*2400']