task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Consider the following game for two players. There is one white token and some number of black tokens. Each token is placed on a plane in a point with integer coordinates *x* and *y*. The players take turn making moves, white starts. On each turn, a player moves all tokens of their color by 1 to up, down, left or right. Black player can choose directions for each token independently. After a turn of the white player the white token can not be in a point where a black token is located. There are no other constraints on locations of the tokens: positions of black tokens can coincide, after a turn of the black player and initially the white token can be in the same point with some black point. If at some moment the white player can't make a move, he loses. If the white player makes 10100500 moves, he wins. You are to solve the following problem. You are given initial positions of all black tokens. It is guaranteed that initially all these positions are distinct. In how many places can the white token be located initially so that if both players play optimally, the black player wins? Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of black points. The (*i*<=+<=1)-th line contains two integers *x**i*, *y**i* (<=-<=105<=≀<=*x**i*,<=*y**i*,<=<=≀<=105) β€” the coordinates of the point where the *i*-th black token is initially located. It is guaranteed that initial positions of black tokens are distinct. Output Specification: Print the number of points where the white token can be located initially, such that if both players play optimally, the black player wins. Demo Input: ['4\n-2 -1\n0 1\n0 -3\n2 -1\n', '4\n-2 0\n-1 1\n0 -2\n1 -1\n', '16\n2 1\n1 2\n-1 1\n0 1\n0 0\n1 1\n2 -1\n2 0\n1 0\n-1 -1\n1 -1\n2 2\n0 -1\n-1 0\n0 2\n-1 2\n'] Demo Output: ['4\n', '2\n', '4\n'] Note: In the first and second examples initial positions of black tokens are shown with black points, possible positions of the white token (such that the black player wins) are shown with white points. The first example: <img class="tex-graphics" src="https://espresso.codeforces.com/5054b8d2df2fac92c92f96fae82d21c365d12983.png" style="max-width: 100.0%;max-height: 100.0%;"/> The second example: <img class="tex-graphics" src="https://espresso.codeforces.com/eb795dd6abb95cfafb1d1cb7d8c8798825dcc180.png" style="max-width: 100.0%;max-height: 100.0%;"/> In the third example the white tokens should be located in the inner square 2 × 2, to make the black player win. <img class="tex-graphics" src="https://espresso.codeforces.com/6dfd863f649b92860dfd6b446ea004abc01b71a6.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,300
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to . Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it. He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles. Input Specification: The first and the single line of the input contains 6 space-separated integers *a*1,<=*a*2,<=*a*3,<=*a*4,<=*a*5 and *a*6 (1<=≀<=*a**i*<=≀<=1000) β€” the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists. Output Specification: Print a single integer β€” the number of triangles with the sides of one 1 centimeter, into which the hexagon is split. Demo Input: ['1 1 1 1 1 1\n', '1 2 1 2 1 2\n'] Demo Output: ['6\n', '13\n'] Note: This is what Gerald's hexagon looks like in the first sample: <img class="tex-graphics" src="https://espresso.codeforces.com/84d193e27b02c38eb1eadc536602a2ec0b9f9519.png" style="max-width: 100.0%;max-height: 100.0%;"/> And that's what it looks like in the second sample: <img class="tex-graphics" src="https://espresso.codeforces.com/e29076a96da8ca864654cc6195654d9bf07d31ce.png" style="max-width: 100.0%;max-height: 100.0%;"/>
1,301
Title: Purification Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an *n*<=Γ—<=*n* grid. The rows are numbered 1 through *n* from top to bottom, and the columns are numbered 1 through *n* from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells. The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once. You would like to purify all *n*<=Γ—<=*n* cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell. Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way. Input Specification: The first line will contain a single integer *n* (1<=≀<=*n*<=≀<=100). Then, *n* lines follows, each contains *n* characters. The *j*-th character in the *i*-th row represents the cell located at row *i* and column *j*. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise. Output Specification: If there exists no way to purify all the cells, output -1. Otherwise, if your solution casts *x* "Purification" spells (where *x* is the minimum possible number of spells), output *x* lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell. Demo Input: ['3\n.E.\nE.E\n.E.\n', '3\nEEE\nE..\nE.E\n', '5\nEE.EE\nE.EE.\nE...E\n.EE.E\nEE.EE\n'] Demo Output: ['1 1\n2 2\n3 3\n', '-1\n', '3 3\n1 3\n2 2\n4 4\n5 3'] Note: The first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. In the second example, it is impossible to purify the cell located at row 1 and column 1. For the third example:
1,302
Title: Position in Fraction Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have a fraction . You need to find the first occurrence of digit *c* into decimal notation of the fraction after decimal point. Input Specification: The first contains three single positive integers *a*, *b*, *c* (1<=≀<=*a*<=&lt;<=*b*<=≀<=105, 0<=≀<=*c*<=≀<=9). Output Specification: Print position of the first occurrence of digit *c* into the fraction. Positions are numbered from 1 after decimal point. It there is no such position, print -1. Demo Input: ['1 2 0\n', '2 3 7\n'] Demo Output: ['2', '-1'] Note: The fraction in the first example has the following decimal notation: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/896357459a466614a0542f34c9cfb0cef1afc9ed.png" style="max-width: 100.0%;max-height: 100.0%;"/>. The first zero stands on second position. The fraction in the second example has the following decimal notation: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/130ba579a8276fc53a1917606eee9db58817f28d.png" style="max-width: 100.0%;max-height: 100.0%;"/>. There is no digit 7 in decimal notation of the fraction.
1,303
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: In the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares. Bertown has *n* squares, numbered from 1 to *n*, they are numbered in the order of increasing distance between them and the city center. That is, square number 1 is central, and square number *n* is the farthest from the center. Naturally, the opposition wants to hold a meeting as close to the city center as possible (that is, they want an square with the minimum number). There are exactly *k* (*k*<=&lt;<=*n*) days left before the demonstration. Now all squares are free. But the Bertown city administration never sleeps, and the approval of an application for the demonstration threatens to become a very complex process. The process of approval lasts several days, but every day the following procedure takes place: - The opposition shall apply to hold a demonstration at a free square (the one which isn't used by the administration). - The administration tries to move the demonstration to the worst free square left. To do this, the administration organizes some long-term activities on the square, which is specified in the application of opposition. In other words, the administration starts using the square and it is no longer free. Then the administration proposes to move the opposition demonstration to the worst free square. If the opposition has applied for the worst free square then request is accepted and administration doesn't spend money. If the administration does not have enough money to organize an event on the square in question, the opposition's application is accepted. If administration doesn't have enough money to organize activity, then rest of administration's money spends and application is accepted - If the application is not accepted, then the opposition can agree to the administration's proposal (that is, take the worst free square), or withdraw the current application and submit another one the next day. If there are no more days left before the meeting, the opposition has no choice but to agree to the proposal of City Hall. If application is accepted opposition can reject it. It means than opposition still can submit more applications later, but square remains free. In order to organize an event on the square *i*, the administration needs to spend *a**i* bourles. Because of the crisis the administration has only *b* bourles to confront the opposition. What is the best square that the opposition can take, if the administration will keep trying to occupy the square in question each time? Note that the administration's actions always depend only on the actions of the opposition. Input Specification: The first line contains two integers *n* and *k* β€” the number of squares and days left before the meeting, correspondingly (1<=≀<=*k*<=&lt;<=*n*<=≀<=105). The second line contains a single integer *b* β€” the number of bourles the administration has (1<=≀<=*b*<=≀<=1018). The third line contains *n* space-separated integers *a**i* β€” the sum of money, needed to organise an event on square *i* (1<=≀<=*a**i*<=≀<=109). 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. Output Specification: Print a single number β€” the minimum number of the square where the opposition can organize the demonstration. Demo Input: ['5 2\n8\n2 4 5 3 1\n', '5 2\n8\n3 2 4 1 5\n', '5 4\n1000000000000000\n5 4 3 2 1\n'] Demo Output: ['2\n', '5\n', '5\n'] Note: In the first sample the opposition can act like this. On day one it applies for square 3. The administration has to organize an event there and end up with 3 bourles. If on the second day the opposition applies for square 2, the administration won't have the money to intervene. In the second sample the opposition has only the chance for the last square. If its first move occupies one of the first four squares, the administration is left with at least 4 bourles, which means that next day it can use its next move to move the opposition from any square to the last one. In the third sample administration has a lot of money, so opposition can occupy only last square.
1,304
Title: Berland Square Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Last year the world's largest square was built in Berland. It is known that the square can be represented as an infinite plane with an introduced Cartesian system of coordinates. On that square two sets of concentric circles were painted. Let's call the set of concentric circles with radii 1,<=2,<=...,<=*K* and the center in the point (*z*,<=0) a (*K*,<=*z*)-set. Thus, on the square were painted a (*N*,<=*x*)-set and a (*M*,<=*y*)-set. You have to find out how many parts those sets divided the square into. Input Specification: The first line contains integers *N*,<=*x*,<=*M*,<=*y*. (1<=≀<=*N*,<=*M*<=≀<=100000,<=<=-<=100000<=≀<=*x*,<=*y*<=≀<=100000,<=*x*<=β‰ <=*y*). Output Specification: Print the sought number of parts. Demo Input: ['1 0 1 1\n', '1 0 1 2\n', '3 3 4 7\n'] Demo Output: ['4\n', '3\n', '17\n'] Note: Picture for the third sample:
1,305
Title: Fibonacci Number Time Limit: None seconds Memory Limit: None megabytes Problem Description: John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013. John got interested in number *f* (0<=≀<=*f*<=&lt;<=1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number *f* in the list or otherwise state that number *f* does not occur in the list. The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0,<=1,<=1,<=2,<=3,<=5,<=8,<=13,<=21,<=... Input Specification: The first line contains the single integer *f* (0<=≀<=*f*<=&lt;<=1013) β€” the number, which position in the list we should find. 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. Output Specification: Print a single number β€” the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1. Demo Input: ['13\n', '377\n'] Demo Output: ['7\n', '14\n'] Note: none
1,306
Title: Lovely Matrix Time Limit: None seconds Memory Limit: None megabytes Problem Description: Lenny had an *n*<=Γ—<=*m* matrix of positive integers. He loved the matrix so much, because each row of the matrix was sorted in non-decreasing order. For the same reason he calls such matrices of integers lovely. One day when Lenny was at school his little brother was playing with Lenny's matrix in his room. He erased some of the entries of the matrix and changed the order of some of its columns. When Lenny got back home he was very upset. Now Lenny wants to recover his matrix. Help him to find an order for the columns of the matrix so that it's possible to fill in the erased entries of the matrix to achieve a lovely matrix again. Note, that you can fill the erased entries of the matrix with any integers. Input Specification: The first line of the input contains two positive integers *n* and *m* (1<=≀<=*n*Β·*m*<=≀<=105). Each of the next *n* lines contains *m* space-separated integers representing the matrix. An integer -1 shows an erased entry of the matrix. All other integers (each of them is between 0 and 109 inclusive) represent filled entries. Output Specification: If there exists no possible reordering of the columns print -1. Otherwise the output should contain *m* integers *p*1,<=*p*2,<=...,<=*p**m* showing the sought permutation of columns. So, the first column of the lovely matrix will be *p*1-th column of the initial matrix, the second column of the lovely matrix will be *p*2-th column of the initial matrix and so on. Demo Input: ['3 3\n1 -1 -1\n1 2 1\n2 -1 1\n', '2 3\n1 2 2\n2 5 4\n', '2 3\n1 2 3\n3 2 1\n'] Demo Output: ['3 1 2 \n', '1 3 2 \n', '-1\n'] Note: none
1,307
Title: How Many Squares? Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: You are given a 0-1 rectangular matrix. What is the number of squares in it? A square is a solid square frame (border) with linewidth equal to 1. A square should be at least 2<=Γ—<=2. We are only interested in two types of squares: 1. squares with each side parallel to a side of the matrix; 1. squares with each side parallel to a diagonal of the matrix. Regardless of type, a square must contain at least one 1 and can't touch (by side or corner) any foreign 1. Of course, the lengths of the sides of each square should be equal. How many squares are in the given matrix? Input Specification: The first line contains integer *t* (1<=≀<=*t*<=≀<=10000), where *t* is the number of test cases in the input. Then test cases follow. Each case starts with a line containing integers *n* and *m* (2<=≀<=*n*,<=*m*<=≀<=250), where *n* is the number of rows and *m* is the number of columns. The following *n* lines contain *m* characters each (0 or 1). The total number of characters in all test cases doesn't exceed 106 for any input file. Output Specification: You should output exactly *t* lines, with the answer to the *i*-th test case on the *i*-th line. Demo Input: ['2\n8 8\n00010001\n00101000\n01000100\n10000010\n01000100\n00101000\n11010011\n11000011\n10 10\n1111111000\n1000001000\n1011001000\n1011001010\n1000001101\n1001001010\n1010101000\n1001001000\n1000001000\n1111111000\n', '1\n12 11\n11111111111\n10000000001\n10111111101\n10100000101\n10101100101\n10101100101\n10100000101\n10100000101\n10111111101\n10000000001\n11111111111\n00000000000\n'] Demo Output: ['1\n2\n', '3\n'] Note: none
1,308
Title: Number of Parallelograms Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given *n* points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points. Input Specification: The first line of the input contains integer *n* (1<=≀<=*n*<=≀<=2000) β€” the number of points. Each of the next *n* lines contains two integers (*x**i*,<=*y**i*) (0<=≀<=*x**i*,<=*y**i*<=≀<=109) β€” the coordinates of the *i*-th point. Output Specification: Print the only integer *c* β€” the number of parallelograms with the vertices at the given points. Demo Input: ['4\n0 1\n1 0\n1 1\n2 0\n'] Demo Output: ['1\n'] Note: none
1,309
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2Β·*n* binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2Β·*n*, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string. Let's represent Yaroslav's word as *s*<==<=*s*1*s*2... *s*2*n*. Similarly, let's represent Andrey's word as *t*<==<=*t*1*t*2... *t*2*n*. Then, if Yaroslav choose number *k* during his move, then he is going to write out character *s**k* on the piece of paper. Similarly, if Andrey choose number *r* during his move, then he is going to write out character *t**r* on the piece of paper. The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw. You are given two strings *s* and *t*. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=106). The second line contains string *s* β€” Yaroslav's word. The third line contains string *t* β€” Andrey's word. It is guaranteed that both words consist of 2Β·*n* characters "0" and "1". Output Specification: Print "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes. Demo Input: ['2\n0111\n0001\n', '3\n110110\n001001\n', '3\n111000\n000111\n', '4\n01010110\n00101101\n', '4\n01100000\n10010011\n'] Demo Output: ['First\n', 'First\n', 'Draw\n', 'First\n', 'Second\n'] Note: none
1,310
Title: Little Elephant and Sorting Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Little Elephant loves sortings. He has an array *a* consisting of *n* integers. Let's number the array elements from 1 to *n*, then the *i*-th element will be denoted as *a**i*. The Little Elephant can make one move to choose an arbitrary pair of integers *l* and *r* (1<=≀<=*l*<=≀<=*r*<=≀<=*n*) and increase *a**i* by 1 for all *i* such that *l*<=≀<=*i*<=≀<=*r*. Help the Little Elephant find the minimum number of moves he needs to convert array *a* to an arbitrary array sorted in the non-decreasing order. Array *a*, consisting of *n* elements, is sorted in the non-decreasing order if for any *i* (1<=≀<=*i*<=&lt;<=*n*) *a**i*<=≀<=*a**i*<=+<=1 holds. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=105) β€” the size of array *a*. The next line contains *n* integers, separated by single spaces β€” array *a* (1<=≀<=*a**i*<=≀<=109). The array elements are listed in the line in the order of their index's increasing. Output Specification: In a single line print a single integer β€” the answer to the problem. 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. Demo Input: ['3\n1 2 3\n', '3\n3 2 1\n', '4\n7 4 1 47\n'] Demo Output: ['0\n', '2\n', '6\n'] Note: In the first sample the array is already sorted in the non-decreasing order, so the answer is 0. In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]). In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47].
1,311
Title: Cheap Travel Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ann has recently started commuting by subway. We know that a one ride subway ticket costs *a* rubles. Besides, Ann found out that she can buy a special ticket for *m* rides (she can buy it several times). It costs *b* rubles. Ann did the math; she will need to use subway *n* times. Help Ann, tell her what is the minimum sum of money she will have to spend to make *n* rides? Input Specification: The single line contains four space-separated integers *n*, *m*, *a*, *b* (1<=≀<=*n*,<=*m*,<=*a*,<=*b*<=≀<=1000) β€” the number of rides Ann has planned, the number of rides covered by the *m* ride ticket, the price of a one ride ticket and the price of an *m* ride ticket. Output Specification: Print a single integer β€” the minimum sum in rubles that Ann will need to spend. Demo Input: ['6 2 1 2\n', '5 2 2 3\n'] Demo Output: ['6\n', '8\n'] Note: In the first sample one of the optimal solutions is: each time buy a one ride ticket. There are other optimal solutions. For example, buy three *m* ride tickets.
1,312
Title: Mysterious strings Time Limit: None seconds Memory Limit: None megabytes Problem Description: The input contains a single integer *a* (1<=≀<=*a*<=≀<=40). Output a single string. Input Specification: The input contains a single integer *a* (1<=≀<=*a*<=≀<=40). Output Specification: Output a single string. Demo Input: ['2\n', '8\n', '29\n'] Demo Output: ['Adams\n', 'Van Buren\n', 'Harding\n'] Note: none
1,313
Title: An easy problem about trees Time Limit: None seconds Memory Limit: None megabytes Problem Description: Pieguy and Piegirl are playing a game. They have a rooted binary tree, that has a property that each node is either a leaf or has exactly two children. Each leaf has a number associated with it. On his/her turn a player can choose any two leafs that share their immediate parent, remove them, and associate either of their values with their parent, that now became a leaf (the player decides which of the two values to associate). The game ends when only one node (the one that was the root of the tree) is left. Pieguy goes first, and his goal is to maximize the value that will be associated with the root when the game ends. Piegirl wants to minimize that value. Assuming that both players are playing optimally, what number will be associated with the root when the game ends? Input Specification: First line contains a single integer *t* (1<=≀<=*t*<=≀<=100) β€” number of test cases. Then *t* test cases follow. Each test case begins with an empty line, followed by a line with a single integer *n* (1<=≀<=*n*<=≀<=250), followed by *n* lines describing *n* nodes of the tree. Each of those *n* lines either contains a non-negative number *a**i*, indicating a leaf node with value *a**i* (0<=≀<=*a**i*<=≀<=1000) associated with it, or <=-<=1 followed by integers *l* and *r*, indicating a non-leaf node with children *l* and *r* (0<=≀<=*l*,<=*r*<=≀<=*n*<=-<=1). Nodes are numbered from 0 to *n*<=-<=1. The root is always node 0. Output Specification: For each test case print one line with one integer on it β€” the number that will be associated with the root when the game ends. Demo Input: ['4\n\n3\n-1 1 2\n10\n5\n\n5\n-1 1 2\n-1 3 4\n10\n5\n20\n\n7\n-1 1 2\n-1 3 4\n-1 5 6\n1\n2\n3\n4\n\n11\n-1 1 2\n-1 3 4\n-1 5 6\n-1 7 8\n15\n7\n-1 9 10\n7\n8\n9\n11\n'] Demo Output: ['10\n10\n4\n8\n'] Note: none
1,314
Title: Triangle Time Limit: 2 seconds Memory Limit: 64 megabytes Problem Description: Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. Anne has perfectly solved this task, now she is asking Johnny to do the same. The boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. It can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. It can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, he asks you to help him. Input Specification: The first line of the input contains four space-separated positive integer numbers not exceeding 100 β€” lengthes of the sticks. Output Specification: Output TRIANGLE if it is possible to construct a non-degenerate triangle. Output SEGMENT if the first case cannot take place and it is possible to construct a degenerate triangle. Output IMPOSSIBLE if it is impossible to construct any triangle. Remember that you are to use three sticks. It is not allowed to break the sticks or use their partial length. Demo Input: ['4 2 1 3\n', '7 2 2 4\n', '3 5 9 1\n'] Demo Output: ['TRIANGLE\n', 'SEGMENT\n', 'IMPOSSIBLE\n'] Note: none
1,315
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: The game of Egg Roulette is played between two players. Initially 2*R* raw eggs and 2*C* cooked eggs are placed randomly into a carton. The shells are left on so there is no way to distinguish a raw egg from a cooked egg. One at a time, a player will select an egg, and then smash the egg on his/her forehead. If the egg was cooked, not much happens, but if the egg was raw, it will make quite the mess. This continues until one player has broken *R* raw eggs, at which point that player is declared the loser and the other player wins. The order in which players take turns can be described as a string of 'A' and 'B' characters, where the *i*-th character tells which player should choose the *i*-th egg. Traditionally, players take turns going one after the other. That is, they follow the ordering "ABABAB...". This isn't very fair though, because the second player will win more often than the first. We'd like you to find a better ordering for the players to take their turns. Let's define the unfairness of an ordering as the absolute difference between the first player's win probability and the second player's win probability. We're interested in orderings that minimize the unfairness. We only consider an ordering valid if it contains the same number of 'A's as 'B's. You will also be given a string *S* of length 2(*R*<=+<=*C*) containing only 'A', 'B', and '?' characters. An ordering is said to match *S* if it only differs from *S* in positions where *S* contains a '?'. Of the valid orderings that minimize unfairness, how many match *S*? Input Specification: The first line of input will contain integers *R* and *C* (1<=≀<=*R*,<=*C*<=≀<=20,<=*R*<=+<=*C*<=≀<=30). The second line of input will contain the string *S* of length 2(*R*<=+<=*C*) consisting only of characters 'A', 'B', '?'. Output Specification: Print the number of valid orderings that minimize unfairness and match *S*. Demo Input: ['1 1\n??BB\n', '2 4\n?BA??B??A???\n', '4 14\n????A??BB?????????????AB????????????\n'] Demo Output: ['0\n', '1\n', '314\n'] Note: In the first test case, the minimum unfairness is 0, and the orderings that achieve it are "ABBA" and "BAAB", neither of which match *S*. Note that an ordering such as "ABBB" would also have an unfairness of 0, but is invalid because it does not contain the same number of 'A's as 'B's. In the second example, the only matching ordering is "BBAAABABABBA".
1,316
Title: Parallel Programming Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarpus has a computer with *n* processors. Also, his computer has *n* memory cells. We'll consider the processors numbered by integers from 1 to *n* and that the memory cells are consecutively numbered by integers from 1 to *n*. Polycarpus needs to come up with a parallel program model. For each memory cell number *i* this program must record the value *n*<=-<=*i* to this cell. In other words, for each cell you've got to find the distance to cell *n*. Let's denote the value that is written in the *i*-th cell as *a**i*. Initially, *a**i*<==<=1 (1<=≀<=*i*<=&lt;<=*n*) and *a**n*<==<=0. We will consider that only processor *i* can write values in the memory cell number *i*. All processors can read an information from some cell (several processors can read an information from some cell simultaneously). The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows: 1. Each processor independently of the other ones chooses some memory cell. Let's say that processor *i* has chosen a cell with number *c**i* (1<=≀<=*c**i*<=≀<=*n*). 1. All processors simultaneously execute operation *a**i*<==<=*a**i*<=+<=*a**c**i*. Help Polycarpus come up with the parallel program model that is executed in exactly *k* steps. Calculate the operations that need to be executed. Note that after *k* steps for all *i*'s value *a**i* must be equal *n*<=-<=*i*. Input Specification: The first line contains two space-separated integers *n* and *k* (1<=≀<=*n*<=≀<=104,<=1<=≀<=*k*<=≀<=20). It is guaranteed that at the given *n* and *k* the required sequence of operations exists. Output Specification: Print exactly *n*Β·*k* integers in *k* lines. In the first line print numbers *c*1,<=*c*2,<=...,<=*c**n* (1<=≀<=*c**i*<=≀<=*n*) for the first increment operation. In the second line print the numbers for the second increment operation. In the *k*-th line print the numbers for the *k*-th increment operation. As a result of the printed operations for any *i* value *a**i* must equal *n*<=-<=*i*. Demo Input: ['1 1\n', '3 2\n'] Demo Output: ['1\n', '2 3 3\n3 3 3\n'] Note: none
1,317
Title: Number Busters Time Limit: None seconds Memory Limit: None megabytes Problem Description: Arthur and Alexander are number busters. Today they've got a competition. Arthur took a group of four integers *a*,<=*b*,<=*w*,<=*x* (0<=≀<=*b*<=&lt;<=*w*,<=0<=&lt;<=*x*<=&lt;<=*w*) and Alexander took integer *с*. Arthur and Alexander use distinct approaches to number bustings. Alexander is just a regular guy. Each second, he subtracts one from his number. In other words, he performs the assignment: *c*<==<=*c*<=-<=1. Arthur is a sophisticated guy. Each second Arthur performs a complex operation, described as follows: if *b*<=β‰₯<=*x*, perform the assignment *b*<==<=*b*<=-<=*x*, if *b*<=&lt;<=*x*, then perform two consecutive assignments *a*<==<=*a*<=-<=1;Β *b*<==<=*w*<=-<=(*x*<=-<=*b*). You've got numbers *a*,<=*b*,<=*w*,<=*x*,<=*c*. Determine when Alexander gets ahead of Arthur if both guys start performing the operations at the same time. Assume that Alexander got ahead of Arthur if *c*<=≀<=*a*. Input Specification: The first line contains integers *a*,<=*b*,<=*w*,<=*x*,<=*c* (1<=≀<=*a*<=≀<=2Β·109,<=1<=≀<=*w*<=≀<=1000,<=0<=≀<=*b*<=&lt;<=*w*,<=0<=&lt;<=*x*<=&lt;<=*w*,<=1<=≀<=*c*<=≀<=2Β·109). Output Specification: Print a single integer β€” the minimum time in seconds Alexander needs to get ahead of Arthur. You can prove that the described situation always occurs within the problem's limits. Demo Input: ['4 2 3 1 6\n', '4 2 3 1 7\n', '1 2 3 2 6\n', '1 1 2 1 1\n'] Demo Output: ['2\n', '4\n', '13\n', '0\n'] Note: none
1,318
Title: Bear and Contribution Time Limit: None seconds Memory Limit: None megabytes Problem Description: Codeforces is a wonderful platform and one its feature shows how much someone contributes to the community. Every registered user has contributionΒ β€” an integer number, not necessarily positive. There are *n* registered users and the *i*-th of them has contribution *t**i*. Limak is a little polar bear and he's new into competitive programming. He doesn't even have an account in Codeforces but he is able to upvote existing blogs and comments. We assume that every registered user has infinitely many blogs and comments. - Limak can spend *b* minutes to read one blog and upvote it. Author's contribution will be increased by 5. - Limak can spend *c* minutes to read one comment and upvote it. Author's contribution will be increased by 1. Note that it's possible that Limak reads blogs faster than comments. Limak likes ties. He thinks it would be awesome to see a tie between at least *k* registered users. To make it happen he is going to spend some time on reading and upvoting. After that, there should exist an integer value *x* that at least *k* registered users have contribution exactly *x*. How much time does Limak need to achieve his goal? Input Specification: The first line contains four integers *n*, *k*, *b* and *c* (2<=≀<=*k*<=≀<=*n*<=≀<=200<=000,<=1<=≀<=*b*,<=*c*<=≀<=1000)Β β€” the number of registered users, the required minimum number of users with the same contribution, time needed to read and upvote a blog, and time needed to read and upvote a comment, respectively. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (|*t**i*|<=≀<=109) where *t**i* denotes contribution of the *i*-th registered user. Output Specification: Print the minimum number of minutes Limak will spend to get a tie between at least *k* registered users. Demo Input: ['4 3 100 30\n12 2 6 1\n', '4 3 30 100\n12 2 6 1\n', '6 2 987 789\n-8 42 -4 -65 -8 -8\n'] Demo Output: ['220\n', '190\n', '0\n'] Note: In the first sample, there are 4 registered users and Limak wants a tie between at least 3 of them. Limak should behave as follows. - He spends 100 minutes to read one blog of the 4-th user and increase his contribution from 1 to 6. - Then he spends 4Β·30 = 120 minutes to read four comments of the 2-nd user and increase his contribution from 2 to 6 (four times it was increaded by 1). In the given scenario, Limak spends 100 + 4Β·30 = 220 minutes and after that each of users 2, 3, 4 has contribution 6. In the second sample, Limak needs 30 minutes to read a blog and 100 minutes to read a comment. This time he can get 3 users with contribution equal to 12 by spending 100 + 3Β·30 = 190 minutes: - Spend 2Β·30 = 60 minutes to read two blogs of the 1-st user to increase his contribution from 2 to 12. - Spend 30 + 100 minutes to read one blog and one comment of the 3-rd user. His contribution will change from 6 to 6 + 5 + 1 = 12.
1,319
Title: Pizza, Pizza, Pizza!!! Time Limit: None seconds Memory Limit: None megabytes Problem Description: Katie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems. Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro. She has ordered a very big round pizza, in order to serve her many friends. Exactly $n$ of Shiro's friends are here. That's why she has to divide the pizza into $n + 1$ slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over. Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator. As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem? Input Specification: A single line contains one non-negative integer $n$ ($0 \le n \leq 10^{18}$)Β β€” the number of Shiro's friends. The circular pizza has to be sliced into $n + 1$ pieces. Output Specification: A single integerΒ β€” the number of straight cuts Shiro needs. Demo Input: ['3\n', '4\n'] Demo Output: ['2', '5'] Note: To cut the round pizza into quarters one has to make two cuts through the center with angle $90^{\circ}$ between them. To cut the round pizza into five equal parts one has to make five cuts.
1,320
Title: Sleepy Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: Petya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of *n* vertices and *m* edges. One of the vertices contains a chip. Initially the chip is located at vertex *s*. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced. Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves. Your task is to help Petya find out if he can win the game or at least draw a tie. Input Specification: The first line of input contain two integers *n* and *m*Β β€” the number of vertices and the number of edges in the graph (2<=≀<=*n*<=≀<=105, 0<=≀<=*m*<=≀<=2Β·105). The next *n* lines contain the information about edges of the graph. *i*-th line (1<=≀<=*i*<=≀<=*n*) contains nonnegative integer *c**i*Β β€” number of vertices such that there is an edge from *i* to these vertices and *c**i* distinct integers *a**i*,<=*j*Β β€” indices of these vertices (1<=≀<=*a**i*,<=*j*<=≀<=*n*, *a**i*,<=*j*<=β‰ <=*i*). It is guaranteed that the total sum of *c**i* equals to *m*. The next line contains index of vertex *s*Β β€” the initial position of the chip (1<=≀<=*s*<=≀<=*n*). Output Specification: If Petya can win print Β«WinΒ» in the first line. In the next line print numbers *v*1,<=*v*2,<=...,<=*v**k* (1<=≀<=*k*<=≀<=106)Β β€” the sequence of vertices Petya should visit for the winning. Vertex *v*1 should coincide with *s*. For *i*<==<=1... *k*<=-<=1 there should be an edge from *v**i* to *v**i*<=+<=1 in the graph. There must be no possible move from vertex *v**k*. The sequence should be such that Petya wins the game. If Petya can't win but can draw a tie, print Β«DrawΒ» in the only line. Otherwise print Β«LoseΒ». Demo Input: ['5 6\n2 2 3\n2 4 5\n1 4\n1 5\n0\n1\n', '3 2\n1 3\n1 1\n0\n2\n', '2 2\n1 2\n1 1\n1\n'] Demo Output: ['Win\n1 2 4 5 \n', 'Lose\n', 'Draw\n'] Note: In the first example the graph is the following: Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins. In the second example the graph is the following: Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses. In the third example the graph is the following: Petya can't win, but he can move along the cycle, so the players will draw a tie.
1,321
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with *n* elements *a*1, *a*2, ..., *a**n* 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). For 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. Input Specification: The first line of the input contains an integer *n* (2<=≀<=*n*<=≀<=105). The next line contains *n* distinct integers *a*1, *a*2, ..., *a**n* (1<=≀<=*a**i*<=≀<=*n*). Output Specification: Output a single integer β€” the answer to the problem. Demo Input: ['3\n3 1 2\n'] Demo Output: ['2\n'] Note: Consider 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].
1,322
Title: Okabe and Boxes Time Limit: None seconds Memory Limit: None megabytes Problem Description: Okabe and Super Hacker Daru are stacking and removing boxes. There are *n* boxes numbered from 1 to *n*. Initially there are no boxes on the stack. Okabe, being a control freak, gives Daru 2*n* commands: *n* of which are to add a box to the top of the stack, and *n* of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to *n*. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack. That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it. Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed. Input Specification: The first line of input contains the integer *n* (1<=≀<=*n*<=≀<=3Β·105)Β β€” the number of boxes. Each of the next 2*n* lines of input starts with a string "add" or "remove". If the line starts with the "add", an integer *x* (1<=≀<=*x*<=≀<=*n*) follows, indicating that Daru should add the box with number *x* to the top of the stack. It is guaranteed that exactly *n* lines contain "add" operations, all the boxes added are distinct, and *n* lines contain "remove" operations. It is also guaranteed that a box is always added before it is required to be removed. Output Specification: Print the minimum number of times Daru needs to reorder the boxes to successfully complete all of Okabe's commands. Demo Input: ['3\nadd 1\nremove\nadd 2\nadd 3\nremove\nremove\n', '7\nadd 3\nadd 2\nadd 1\nremove\nadd 4\nremove\nremove\nremove\nadd 6\nadd 7\nadd 5\nremove\nremove\nremove\n'] Demo Output: ['1\n', '2\n'] Note: In the first sample, Daru should reorder the boxes after adding box 3 to the stack. In the second sample, Daru should reorder the boxes after adding box 4 and box 7 to the stack.
1,323
Title: System Administrator Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarpus is a system administrator. There are two servers under his strict guidance β€” *a* and *b*. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers *x* and *y* (*x*<=+<=*y*<==<=10;Β *x*,<=*y*<=β‰₯<=0). These numbers mean that *x* packets successfully reached the corresponding server through the network and *y* packets were lost. Today Polycarpus has performed overall *n* ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network. Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results. Input Specification: The first line contains a single integer *n* (2<=≀<=*n*<=≀<=1000) β€” the number of commands Polycarpus has fulfilled. Each of the following *n* lines contains three integers β€” the description of the commands. The *i*-th of these lines contains three space-separated integers *t**i*, *x**i*, *y**i* (1<=≀<=*t**i*<=≀<=2;Β *x**i*,<=*y**i*<=β‰₯<=0;Β *x**i*<=+<=*y**i*<==<=10). If *t**i*<==<=1, then the *i*-th command is "ping a", otherwise the *i*-th command is "ping b". Numbers *x**i*, *y**i* represent the result of executing this command, that is, *x**i* packets reached the corresponding server successfully and *y**i* packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command. Output Specification: In the first line print string "LIVE" (without the quotes) if server *a* is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server *b* in the similar format. Demo Input: ['2\n1 5 5\n2 6 4\n', '3\n1 0 10\n2 0 10\n1 10 0\n'] Demo Output: ['LIVE\nLIVE\n', 'LIVE\nDEAD\n'] Note: Consider the first test case. There 10 packets were sent to server *a*, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server *b*, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Consider the second test case. There were overall 20 packages sent to server *a*, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server *b*, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
1,324
Title: Depression Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels! There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle... Everybody was upset. The beautiful Belle was upset, so was the Beast, so was Lumiere the candlestick. But the worst thing was that Cogsworth was upset. Cogsworth is not a human, but is the mantel clock, which was often used as an alarm clock. Due to Cogsworth's frustration all the inhabitants of the castle were in trouble: now they could not determine when it was time to drink morning tea, and when it was time for an evening stroll. Fortunately, deep in the basement are lying digital clock showing the time in the format HH:MM. Now the residents of the castle face a difficult task. They should turn Cogsworth's hour and minute mustache hands in such a way, that Cogsworth began to show the correct time. Moreover they need to find turn angles in degrees for each mustache hands. The initial time showed by Cogsworth is 12:00. You can only rotate the hands forward, that is, as is shown in the picture: As since there are many ways too select such angles because of full rotations, choose the smallest angles in the right (non-negative) direction. Note that Cogsworth's hour and minute mustache hands move evenly and continuously. Hands are moving independently, so when turning one hand the other hand remains standing still. Input Specification: The only line of input contains current time according to the digital clock, formatted as HH:MM (00<=≀<=HH<=≀<=23, 00<=≀<=MM<=≀<=59). The mantel clock initially shows 12:00. Pretests contain times of the beginning of some morning TV programs of the Channel One Russia. Output Specification: Print two numbers *x* and *y* β€” the angles of turning the hour and minute hands, respectively (0<=≀<=*x*,<=*y*<=&lt;<=360). The absolute or relative error in the answer should not exceed 10<=-<=9. Demo Input: ['12:00\n', '04:30\n', '08:17\n'] Demo Output: ['0 0', '135 180', '248.5 102'] Note: A note to the second example: the hour hand will be positioned exactly in the middle, between 4 and 5.
1,325
Title: Segments Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an integer *N*. Consider all possible segments on the coordinate axis with endpoints at integer points with coordinates between 0 and *N*, inclusive; there will be of them. You want to draw these segments in several layers so that in each layer the segments don't overlap (they might touch at the endpoints though). You can not move the segments to a different location on the coordinate axis. Find the minimal number of layers you have to use for the given *N*. Input Specification: The only input line contains a single integer *N* (1<=≀<=*N*<=≀<=100). Output Specification: Output a single integer - the minimal number of layers required to draw the segments for the given *N*. Demo Input: ['2\n', '3\n', '4\n'] Demo Output: ['2\n', '4\n', '6\n'] Note: As an example, here are the segments and their optimal arrangement into layers for *N* = 4.
1,326
Title: Load Testing Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last *n* minutes and in the *i*-th minute friends will send *a**i* requests. Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load. Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable. For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp. Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to *n*. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=100<=000) β€” the duration of the load testing. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109), where *a**i* is the number of requests from friends in the *i*-th minute of the load testing. Output Specification: Print the minimum number of additional requests from Polycarp that would make the load strictly increasing in the beginning and then strictly decreasing afterwards. Demo Input: ['5\n1 4 3 2 5\n', '5\n1 2 2 2 1\n', '7\n10 20 40 50 70 90 30\n'] Demo Output: ['6\n', '1\n', '0\n'] Note: In the first example Polycarp must make two additional requests in the third minute and four additional requests in the fourth minute. So the resulting load will look like: [1, 4, 5, 6, 5]. In total, Polycarp will make 6 additional requests. In the second example it is enough to make one additional request in the third minute, so the answer is 1. In the third example the load already satisfies all conditions described in the statement, so the answer is 0.
1,327
Title: Landmarks Time Limit: None seconds Memory Limit: None megabytes Problem Description: We have an old building with *n*<=+<=2 columns in a row. These columns support the ceiling. These columns are located in points with coordinates 0<==<=*x*0<=&lt;<=*x*1<=&lt;<=...<=&lt;<=*x**n*<=&lt;<=*x**n*<=+<=1. The leftmost and the rightmost columns are special, we will call them bearing, the other columns are ordinary. For each column we know its durability *d**i*. Let's consider an ordinary column with coordinate *x*. Let's assume that the coordinate of the closest to it column to the left (bearing or ordinary) is *a* and the coordinate of the closest to it column to the right (also, bearing or ordinary) is *b*. In this task let's assume that this column supports the segment of the ceiling from point to point (here both fractions are considered as real division). If the length of the segment of the ceiling supported by the column exceeds *d**i*, then the column cannot support it and it crashes after a while, and after that the load is being redistributeed between the neighbouring columns according to the same principle. Thus, ordinary columns will be crashing for some time until the process stops at some state. One can prove that the set of the remaining columns doesn't depend on the order in which columns crash. If there are only two bearing columns left in the end, then we assume that the whole construction crashes under the weight of the roof. But if at least one ordinary column stays in addition to the bearing ones, then the building doesn't crash. To make the building stronger, we can add one extra ordinary column of arbitrary durability *d*' at any (not necessarily integer) point 0<=&lt;<=*x*'<=&lt;<=*x**n*<=+<=1. If point *x*' is already occupied by an ordinary column, it is replaced by a new one. Your task is to find out: what minimal durability can the added column have so that the building doesn't crash? Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of ordinary columns. The second line contains *n*<=+<=2 integers *x*0,<=*x*1,<=...,<=*x**n*,<=*x**n*<=+<=1 (*x*0<==<=0, *x**i*<=&lt;<=*x**i*<=+<=1 for 0<=≀<=*i*<=≀<=*n*, *x**n*<=+<=1<=≀<=109) β€” the coordinates of the columns. The third line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≀<=*d**i*<=≀<=109). Output Specification: Print a single number β€” the minimum possible durability of the column that you need to add in order to make the building stay. If you do not have to add the column, please print 0. Your answer will be checked with the relative or absolute error 10<=-<=4. Demo Input: ['2\n0 20 40 100\n15 40\n', '3\n0 4 10 28 30\n9 13 5\n'] Demo Output: ['10\n', '0\n'] Note: none
1,328
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Radewoosh is playing a computer game. There are *n* levels, numbered 1 through *n*. Levels are divided into *k* regions (groups). Each region contains some positive number of consecutive levels. The game repeats the the following process: 1. If all regions are beaten then the game ends immediately. Otherwise, the system finds the first region with at least one non-beaten level. Let *X* denote this region.1. The system creates an empty bag for tokens. Each token will represent one level and there may be many tokens representing the same level. For each already beaten level *i* in the region *X*, the system adds *t**i* tokens to the bag (tokens representing the *i*-th level). 1. Let *j* denote the first non-beaten level in the region *X*. The system adds *t**j* tokens to the bag. 1. Finally, the system takes a uniformly random token from the bag and a player starts the level represented by the token. A player spends one hour and beats the level, even if he has already beaten it in the past. Given *n*, *k* and values *t*1,<=*t*2,<=...,<=*t**n*, your task is to split levels into regions. Each level must belong to exactly one region, and each region must contain non-empty consecutive set of levels. What is the minimum possible expected number of hours required to finish the game? Input Specification: The first line of the input contains two integers *n* and *k* (1<=≀<=*n*<=≀<=200<=000, 1<=≀<=*k*<=≀<=*min*(50,<=*n*))Β β€” the number of levels and the number of regions, respectively. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≀<=*t**i*<=≀<=100<=000). Output Specification: Print one real numberΒ β€” the minimum possible expected value of the number of hours spent to finish the game if levels are distributed between regions in the optimal way. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=4. Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct if . Demo Input: ['4 2\n100 3 5 7\n', '6 2\n1 2 4 8 16 32\n'] Demo Output: ['5.7428571429\n', '8.5000000000\n'] Note: In the first sample, we are supposed to split 4 levels into 2 regions. It's optimal to create the first region with only one level (it must be the first level). Then, the second region must contain other three levels. In the second sample, it's optimal to split levels into two regions with 3 levels each.
1,329
Title: Shell Game Time Limit: None seconds Memory Limit: None megabytes Problem Description: Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess the current position of the ball. Bomboslav noticed that guys are not very inventive, so the operator always swaps the left shell with the middle one during odd moves (first, third, fifth, etc.) and always swaps the middle shell with the right one during even moves (second, fourth, etc.). Let's number shells from 0 to 2 from left to right. Thus the left shell is assigned number 0, the middle shell is 1 and the right shell is 2. Bomboslav has missed the moment when the ball was placed beneath the shell, but he knows that exactly *n* movements were made by the operator and the ball was under shell *x* at the end. Now he wonders, what was the initial position of the ball? Input Specification: The first line of the input contains an integer *n* (1<=≀<=*n*<=≀<=2Β·109)Β β€” the number of movements made by the operator. The second line contains a single integer *x* (0<=≀<=*x*<=≀<=2)Β β€” the index of the shell where the ball was found after *n* movements. Output Specification: Print one integer from 0 to 2Β β€” the index of the shell where the ball was initially placed. Demo Input: ['4\n2\n', '1\n1\n'] Demo Output: ['1\n', '0\n'] Note: In the first sample, the ball was initially placed beneath the middle shell and the operator completed four movements. 1. During the first move operator swapped the left shell and the middle shell. The ball is now under the left shell. 1. During the second move operator swapped the middle shell and the right one. The ball is still under the left shell. 1. During the third move operator swapped the left shell and the middle shell again. The ball is again in the middle. 1. Finally, the operators swapped the middle shell and the right shell. The ball is now beneath the right shell.
1,330
Title: Dormitory Time Limit: None seconds Memory Limit: None megabytes Problem Description: Student Vasya came to study in Berland State University from the country, so he is living in a dormitory. A semester has *n* days, and in each of those days his parents send him some food. In the morning of the *i*-th day he receives *a**i* kilograms of food that can be eaten on that day and on the next one (then the food goes bad and becomes unfit for consumption). Every day Vasya eats *v* kilograms of food. It is known that Vasya's parents do not allow him to starve, so there always is enough food for Vasya. Vasya has *m* friends who sometimes live with him. Let's index the friends from 1 to *m*. Friend number *j* lives with Vasya from day *l**j* to day *r**j*, inclusive. Also, the *j*-th friend requires *f**j* kilograms of food per day. Usually Vasya's friends eat in the canteen, but sometimes generous Vasya feeds some of them. Every day Vasya can feed some friends who live with him this day (or may feed nobody). Every time Vasya feeds his friend, he gives him as much food as the friend needs for the day, and Vasya's popularity rating at the University increases by one. Vasya cannot feed the same friend multiple times in one day. In addition, he knows that eating habits must be regular, so he always eats *v* kilograms of food per day. Vasya wants so choose whom he will feed each day of the semester to make his rating as high as possible. Originally Vasya's rating is 0 because he is a freshman. Input Specification: The first line contains two integers *n* and *v* (1<=≀<=*n*,<=*v*<=≀<=400). The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=400), separated by single spaces. Value *a**i* means that in the morning of the *i*-th day *a**i* kilograms of food come, the food is good for eating on day *i* and/or on day *i*<=+<=1 (then the food goes bad). It is guaranteed that if Vasya doesn't feed anyone, there is a way for him to eat so as to consume *v* kilograms of food every day. The third line contains integer *m* (1<=≀<=*m*<=≀<=400). Each of the following *m* lines describes one Vasya's friend: the *j*-th of these lines contains three integers *l**j*,<=*r**j*,<=*f**j* (1<=≀<=*l**j*<=≀<=*r**j*<=≀<=*n*,<=1<=≀<=*f**j*<=≀<=400), separated by single spaces. Output Specification: In the first line print the highest rating Vasya can reach. In the next *n* lines print, which friends Vasya needs to feed on each day. In the *i*-th of these lines first print the number of friends to feed on the *i*-th day, and then list the indexes of these friends. Print the friends in these lists in any order. If there are multiple optimal solutions, print any of them. Demo Input: ['4 1\n3 2 5 4\n3\n1 3 2\n1 4 1\n3 4 2\n'] Demo Output: ['7\n1 2\n1 2\n3 2 1 3\n2 2 3\n'] Note: none
1,331
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Furik and Rubik take part in a relay race. The race will be set up on a large square with the side of *n* meters. The given square is split into *n*<=Γ—<=*n* cells (represented as unit squares), each cell has some number. At the beginning of the race Furik stands in a cell with coordinates (1,<=1), and Rubik stands in a cell with coordinates (*n*,<=*n*). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (*i*,<=*j*), then he can move to cell (*i*<=+<=1,<=*j*) or (*i*,<=*j*<=+<=1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (*n*,<=*n*) to cell with coordinates (1,<=1). If Rubik stands in cell (*i*,<=*j*), then he can move to cell (*i*<=-<=1,<=*j*) or (*i*,<=*j*<=-<=1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum. Print the maximum number of points Furik and Rubik can earn on the relay race. Input Specification: The first line contains a single integer (1<=≀<=*n*<=≀<=300). The next *n* lines contain *n* integers each: the *j*-th number on the *i*-th line *a**i*,<=*j* (<=-<=1000<=≀<=*a**i*,<=*j*<=≀<=1000) is the number written in the cell with coordinates (*i*,<=*j*). Output Specification: On a single line print a single number β€” the answer to the problem. Demo Input: ['1\n5\n', '2\n11 14\n16 12\n', '3\n25 16 25\n12 18 19\n11 13 8\n'] Demo Output: ['5\n', '53\n', '136\n'] Note: Comments to the second sample: The profitable path for Furik is: (1, 1), (1, 2), (2, 2), and for Rubik: (2, 2), (2, 1), (1, 1). Comments to the third sample: The optimal path for Furik is: (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), and for Rubik: (3, 3), (3, 2), (2, 2), (2, 1), (1, 1). The figure to the sample:
1,332
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to *n* computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis. Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to *n*. So the *i*-th hacked computer is located at the point *x**i*. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task. Leha should calculate a sum of *F*(*a*) for all *a*, where *a* is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote *A* the set of all integers from 1 to *n*. Noora asks the hacker to find value of the expression . Here *F*(*a*) is calculated as the maximum among the distances between all pairs of computers from the set *a*. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109<=+<=7. Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date. Input Specification: The first line contains one integer *n* (1<=≀<=*n*<=≀<=3Β·105) denoting the number of hacked computers. The second line contains *n* integers *x*1,<=*x*2,<=...,<=*x**n* (1<=≀<=*x**i*<=≀<=109) denoting the coordinates of hacked computers. It is guaranteed that all *x**i* are distinct. Output Specification: Print a single integerΒ β€” the required sum modulo 109<=+<=7. Demo Input: ['2\n4 7\n', '3\n4 3 1\n'] Demo Output: ['3\n', '9\n'] Note: There are three non-empty subsets in the first sample test:<img align="middle" class="tex-formula" src="https://espresso.codeforces.com/02b2d12556dad85f1c6c6912786eb87d4be2ea17.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/22f6a537962c86b3e28ddb8aaca28a7cdd219a8c.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/7d0f73b3e94e13cb797f39e93d9da74835c5a02d.png" style="max-width: 100.0%;max-height: 100.0%;"/>. The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3. There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f368c407c8e85e2b5fedfffaff39d471d765f026.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bb8f2118a3ac352db393b1f067b28e398ce7f816.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/049032074c04b16bc0cc153f95471c40b222072b.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/dc93c7f5b3d122314c9c5a707fae556a8f72a574.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.
1,333
Title: Increase Sequence Time Limit: None seconds Memory Limit: None megabytes Problem Description: Peter has a sequence of integers *a*1,<=*a*2,<=...,<=*a**n*. Peter wants all numbers in the sequence to equal *h*. He can perform the operation of "adding one on the segment [*l*,<=*r*]": add one to all elements of the sequence with indices from *l* to *r* (inclusive). At that, Peter never chooses any element as the beginning of the segment twice. Similarly, Peter never chooses any element as the end of the segment twice. In other words, for any two segments [*l*1,<=*r*1] and [*l*2,<=*r*2], where Peter added one, the following inequalities hold: *l*1<=β‰ <=*l*2 and *r*1<=β‰ <=*r*2. How many distinct ways are there to make all numbers in the sequence equal *h*? Print this number of ways modulo 1000000007Β (109<=+<=7). Two ways are considered distinct if one of them has a segment that isn't in the other way. Input Specification: The first line contains two integers *n*,<=*h* (1<=≀<=*n*,<=*h*<=≀<=2000). The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=2000). Output Specification: Print a single integer β€” the answer to the problem modulo 1000000007Β (109<=+<=7). Demo Input: ['3 2\n1 1 1\n', '5 1\n1 1 1 1 1\n', '4 3\n3 2 1 1\n'] Demo Output: ['4\n', '1\n', '0\n'] Note: none
1,334
Title: On Sum of Fractions Time Limit: None seconds Memory Limit: None megabytes Problem Description: Let's assume that - *v*(*n*) is the largest prime number, that does not exceed *n*;- *u*(*n*) is the smallest prime number strictly greater than *n*. Find . Input Specification: The first line contains integer *t*Β (1<=≀<=*t*<=≀<=500) β€” the number of testscases. Each of the following *t* lines of the input contains integer *n* (2<=≀<=*n*<=≀<=109). Output Specification: Print *t* lines: the *i*-th of them must contain the answer to the *i*-th test as an irreducible fraction "*p*/*q*", where *p*,<=*q* are integers, *q*<=&gt;<=0. Demo Input: ['2\n2\n3\n'] Demo Output: ['1/6\n7/30\n'] Note: none
1,335
Title: Crunching Numbers Just for You Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done... You are given an array of integers. Sort it in non-descending order. Input Specification: The input consists of a single line of space-separated integers. The first number is *n* (1<=≀<=*n*<=≀<=10) β€” the size of the array. The following *n* numbers are the elements of the array (1<=≀<=*a**i*<=≀<=100). Output Specification: Output space-separated elements of the sorted array. Demo Input: ['3 3 1 2\n'] Demo Output: ['1 2 3 \n'] Note: Remember, this is a very important feature, and you have to make sure the customers appreciate it!
1,336
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya's got a birthday coming up and his mom decided to give him an array of positive integers *a* of length *n*. Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array *a* left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by *k* for each number). The seller can obtain array *b* from array *a* if the following conditions hold: *b**i*<=&gt;<=0; 0<=≀<=*a**i*<=-<=*b**i*<=≀<=*k* for all 1<=≀<=*i*<=≀<=*n*. Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain). Input Specification: The first line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=3Β·105;<=1<=≀<=*k*<=≀<=106). The second line contains *n* integers *a**i* (1<=≀<=*a**i*<=≀<=106) β€” array *a*. Output Specification: In the single line print a single number β€” the maximum possible beauty of the resulting array. Demo Input: ['6 1\n3 6 10 12 13 16\n', '5 3\n8 21 52 15 77\n'] Demo Output: ['3\n', '7\n'] Note: In the first sample we can obtain the array: 3 6 9 12 12 15 In the second sample we can obtain the next array: 7 21 49 14 77
1,337
Title: Garden Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya has a very beautiful country garden that can be represented as an *n*<=Γ—<=*m* rectangular field divided into *n*Β·*m* squares. One beautiful day Vasya remembered that he needs to pave roads between *k* important squares that contain buildings. To pave a road, he can cover some squares of his garden with concrete. For each garden square we know number *a**i**j* that represents the number of flowers that grow in the square with coordinates (*i*,<=*j*). When a square is covered with concrete, all flowers that grow in the square die. Vasya wants to cover some squares with concrete so that the following conditions were fulfilled: - all *k* important squares should necessarily be covered with concrete - from each important square there should be a way to any other important square. The way should go be paved with concrete-covered squares considering that neighboring squares are squares that have a common side - the total number of dead plants should be minimum As Vasya has a rather large garden, he asks you to help him. Input Specification: The first input line contains three integers *n*, *m* and *k* (1<=≀<=*n*,<=*m*<=≀<=100, *n*Β·*m*<=≀<=200, 1<=≀<=*k*<=≀<=*min*(*n*Β·*m*,<=7)) β€” the garden's sizes and the number of the important squares. Each of the next *n* lines contains *m* numbers *a**i**j* (1<=≀<=*a**i**j*<=≀<=1000) β€” the numbers of flowers in the squares. Next *k* lines contain coordinates of important squares written as "*x* *y*" (without quotes) (1<=≀<=*x*<=≀<=*n*, 1<=≀<=*y*<=≀<=*m*). The numbers written on one line are separated by spaces. It is guaranteed that all *k* important squares have different coordinates. Output Specification: In the first line print the single integer β€” the minimum number of plants that die during the road construction. Then print *n* lines each containing *m* characters β€” the garden's plan. In this plan use character "X" (uppercase Latin letter X) to represent a concrete-covered square and use character "." (dot) for a square that isn't covered with concrete. If there are multiple solutions, print any of them. Demo Input: ['3 3 2\n1 2 3\n1 2 3\n1 2 3\n1 2\n3 3\n', '4 5 4\n1 4 5 1 2\n2 2 2 2 7\n2 4 1 4 5\n3 2 1 7 1\n1 1\n1 5\n4 1\n4 4\n'] Demo Output: ['9\n.X.\n.X.\n.XX\n', '26\nX..XX\nXXXX.\nX.X..\nX.XX.\n'] Note: none
1,338
Title: New Year and Finding Roots Time Limit: None seconds Memory Limit: None megabytes Problem Description: This is an interactive problem. In the interaction section below you will find the information about flushing the output. The New Year tree of height *h* is a perfect binary tree with vertices numbered 1 through 2*h*<=-<=1 in some order. In this problem we assume that *h* is at least 2. The drawing below shows one example New Year tree of height 3: Polar bears love decorating the New Year tree and Limak is no exception. To decorate the tree, he must first find its root, i.e. a vertex with exactly two neighbours (assuming that *h*<=β‰₯<=2). It won't be easy because Limak is a little bear and he doesn't even see the whole tree. Can you help him? There are *t* testcases. In each testcase, you should first read *h* from the input. Then you can ask at most 16 questions of format "? x" (without quotes), where *x* is an integer between 1 and 2*h*<=-<=1, inclusive. As a reply you will get the list of neighbours of vertex *x* (more details in the "Interaction" section below). For example, for a tree on the drawing above after asking "? 1" you would get a response with 3 neighbours: 4, 5 and 7. Your goal is to find the index of the root *y* and print it in the format "! y". You will be able to read *h* for a next testcase only after printing the answer in a previous testcase and flushing the output. Each tree is fixed from the beginning and it doesn't change during your questions. Input Specification: The first line of the input contains a single integer *t* (1<=≀<=*t*<=≀<=500)Β β€” the number of testcases. At the beginning of each testcase you should read from the input a single integer *h* (2<=≀<=*h*<=≀<=7)Β β€” the height of the tree. You can't read the value of *h* in a next testcase until you answer a previous testcase. Output Specification: none Demo Input: ['1\n3\n3\n4 5 7\n2\n1 2\n1\n2\n', '2\n2\n1\n3\n2\n1 2\n2\n1 2\n4\n3\n3 12 13\n'] Demo Output: ['? 1\n? 5\n? 6\n! 5\n', '? 1\n? 3\n? 3\n! 3\n? 6\n! 1\n'] Note: In the first sample, a tree corresponds to the drawing from the statement. In the second sample, there are two two testcases. A tree in the first testcase has height 2 and thus 3 vertices. A tree in the second testcase has height 4 and thus 15 vertices. You can see both trees on the drawing below.
1,339
Title: Kamal-ol-molk's Painting Time Limit: None seconds Memory Limit: None megabytes Problem Description: Rumors say that one of Kamal-ol-molk's paintings has been altered. A rectangular brush has been moved right and down on the painting. Consider the painting as a *n*<=Γ—<=*m* rectangular grid. At the beginning an *x*<=Γ—<=*y* rectangular brush is placed somewhere in the frame, with edges parallel to the frame, (1<=≀<=*x*<=≀<=*n*,<=1<=≀<=*y*<=≀<=*m*). Then the brush is moved several times. Each time the brush is moved one unit right or down. The brush has been strictly inside the frame during the painting. The brush alters every cell it has covered at some moment. You have found one of the old Kamal-ol-molk's paintings. You want to know if it's possible that it has been altered in described manner. If yes, you also want to know minimum possible area of the brush. Input Specification: The first line of input contains two integers *n* and *m*, (1<=≀<=*n*,<=*m*<=≀<=1000), denoting the height and width of the painting. The next *n* lines contain the painting. Each line has *m* characters. Character 'X' denotes an altered cell, otherwise it's showed by '.'. There will be at least one altered cell in the painting. Output Specification: Print the minimum area of the brush in a line, if the painting is possibly altered, otherwise print <=-<=1. Demo Input: ['4 4\nXX..\nXX..\nXXXX\nXXXX\n', '4 4\n....\n.XXX\n.XXX\n....\n', '4 5\nXXXX.\nXXXX.\n.XX..\n.XX..\n'] Demo Output: ['4\n', '2\n', '-1\n'] Note: none
1,340
Title: Color Stripe Time Limit: None seconds Memory Limit: None megabytes Problem Description: A colored stripe is represented by a horizontal row of *n* square cells, each cell is pained one of *k* colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to *k* to repaint the cells. Input Specification: The first input line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=5Β·105;Β 2<=≀<=*k*<=≀<=26). The second line contains *n* uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first *k* English letters may be used. Each letter represents the color of the corresponding cell of the stripe. Output Specification: Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe. Demo Input: ['6 3\nABBACC\n', '3 2\nBBB\n'] Demo Output: ['2\nABCACA\n', '1\nBAB\n'] Note: none
1,341
Title: Hongcow Buys a Deck of Cards Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day, Hongcow goes to the store and sees a brand new deck of *n* special cards. Each individual card is either red or blue. He decides he wants to buy them immediately. To do this, he needs to play a game with the owner of the store. This game takes some number of turns to complete. On a turn, Hongcow may do one of two things: - Collect tokens. Hongcow collects 1 red token and 1 blue token by choosing this option (thus, 2 tokens in total per one operation). - Buy a card. Hongcow chooses some card and spends tokens to purchase it as specified below. The *i*-th card requires *r**i* red resources and *b**i* blue resources. Suppose Hongcow currently has *A* red cards and *B* blue cards. Then, the *i*-th card will require Hongcow to spend *max*(*r**i*<=-<=*A*,<=0) red tokens, and *max*(*b**i*<=-<=*B*,<=0) blue tokens. Note, only tokens disappear, but the cards stay with Hongcow forever. Each card can be bought only once. Given a description of the cards and their costs determine the minimum number of turns Hongcow needs to purchase all cards. Input Specification: The first line of input will contain a single integer *n* (1<=≀<=*n*<=≀<=16). The next *n* lines of input will contain three tokens *c**i*, *r**i* and *b**i*. *c**i* will be 'R' or 'B', denoting the color of the card as red or blue. *r**i* will be an integer denoting the amount of red resources required to obtain the card, and *b**i* will be an integer denoting the amount of blue resources required to obtain the card (0<=≀<=*r**i*,<=*b**i*<=≀<=107). Output Specification: Output a single integer, denoting the minimum number of turns needed to acquire all the cards. Demo Input: ['3\nR 0 1\nB 1 0\nR 1 1\n', '3\nR 3 0\nR 2 0\nR 1 0\n'] Demo Output: ['4\n', '6\n'] Note: For the first sample, Hongcow's four moves are as follows: 1. Collect tokens 1. Buy card 1 1. Buy card 2 1. Buy card 3 For the second sample, one optimal strategy is as follows: 1. Collect tokens 1. Collect tokens 1. Buy card 2 1. Collect tokens 1. Buy card 3 1. Buy card 1
1,342
Title: Kayaking Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers. Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2Β·*n* people in the group (including Vadim), and they have exactly *n*<=-<=1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. *i*-th person's weight is *w**i*, and weight is an important matter in kayaking β€” if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash. Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks. Help the party to determine minimum possible total instability! Input Specification: The first line contains one number *n* (2<=≀<=*n*<=≀<=50). The second line contains 2Β·*n* integer numbers *w*1, *w*2, ..., *w*2*n*, where *w**i* is weight of person *i* (1<=≀<=*w**i*<=≀<=1000). Output Specification: Print minimum possible total instability. Demo Input: ['2\n1 2 3 4\n', '4\n1 3 4 6 3 4 100 200\n'] Demo Output: ['1\n', '5\n'] Note: none
1,343
Title: Voting for Photos Time Limit: None seconds Memory Limit: None megabytes Problem Description: After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first. Help guys determine the winner photo by the records of likes. Input Specification: The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=1000) β€” the total likes to the published photoes. The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=1<=000<=000), where *a**i* is the identifier of the photo which got the *i*-th like. Output Specification: Print the identifier of the photo which won the elections. Demo Input: ['5\n1 3 2 2 1\n', '9\n100 200 300 200 100 300 300 100 200\n'] Demo Output: ['2\n', '300\n'] Note: In the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second). Thus, the winner is the photo with identifier 2, as it got: - more likes than the photo with id 3; - as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier.
1,344
Title: Lucky Ticket Time Limit: None seconds Memory Limit: None megabytes Problem Description: Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals *n* (*n* is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first *n*<=/<=2 digits) equals the sum of digits in the second half (the sum of the last *n*<=/<=2 digits). Check if the given ticket is lucky. Input Specification: The first line contains an even integer *n* (2<=≀<=*n*<=≀<=50) β€” the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly *n* β€” the ticket number. The number may contain leading zeros. Output Specification: On the first line print "YES" if the given ticket number is lucky. Otherwise, print "NO" (without the quotes). Demo Input: ['2\n47\n', '4\n4738\n', '4\n4774\n'] Demo Output: ['NO\n', 'NO\n', 'YES\n'] Note: In the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 ≠ 7). In the second sample the ticket number is not the lucky number.
1,345
Title: Sereja and Stairs Time Limit: None seconds Memory Limit: None megabytes Problem Description: Sereja loves integer sequences very much. He especially likes stairs. Sequence *a*1,<=*a*2,<=...,<=*a*|*a*| (|*a*| is the length of the sequence) is stairs if there is such index *i* (1<=≀<=*i*<=≀<=|*a*|), that the following condition is met: For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't. Sereja has *m* cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table? Input Specification: The first line contains integer *m* (1<=≀<=*m*<=≀<=105) β€” the number of Sereja's cards. The second line contains *m* integers *b**i* (1<=≀<=*b**i*<=≀<=5000) β€” the numbers on the Sereja's cards. Output Specification: In the first line print the number of cards you can put on the table. In the second line print the resulting stairs. Demo Input: ['5\n1 2 3 4 5\n', '6\n1 1 2 2 3 3\n'] Demo Output: ['5\n5 4 3 2 1\n', '5\n1 2 3 2 1\n'] Note: none
1,346
Title: Ilya and Roads Time Limit: None seconds Memory Limit: None megabytes Problem Description: Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as *n* holes in a row. We will consider the holes numbered from 1 to *n*, from left to right. Ilya is really keep on helping his city. So, he wants to fix at least *k* holes (perharps he can fix more) on a single ZooVille road. The city has *m* building companies, the *i*-th company needs *c**i* money units to fix a road segment containing holes with numbers of at least *l**i* and at most *r**i*. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment. Determine the minimum money Ilya will need to fix at least *k* holes. Input Specification: The first line contains three integers *n*,<=*m*,<=*k* (1<=≀<=*n*<=≀<=300,<=1<=≀<=*m*<=≀<=105,<=1<=≀<=*k*<=≀<=*n*). The next *m* lines contain the companies' description. The *i*-th line contains three integers *l**i*,<=*r**i*,<=*c**i* (1<=≀<=*l**i*<=≀<=*r**i*<=≀<=*n*,<=1<=≀<=*c**i*<=≀<=109). Output Specification: Print a single integer β€” the minimum money Ilya needs to fix at least *k* holes. If it is impossible to fix at least *k* holes, print -1. 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. Demo Input: ['10 4 6\n7 9 11\n6 9 13\n7 7 7\n3 5 6\n', '10 7 1\n3 4 15\n8 9 8\n5 6 8\n9 10 6\n1 4 2\n1 4 10\n8 10 13\n', '10 1 9\n5 10 14\n'] Demo Output: ['17\n', '2\n', '-1\n'] Note: none
1,347
Title: Borya's Diagnosis Time Limit: None seconds Memory Limit: None megabytes Problem Description: It seems that Borya is seriously sick. He is going visit *n* doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor. Doctors have a strange working schedule. The doctor *i* goes to work on the *s**i*-th day and works every *d**i* day. So, he works on days *s**i*,<=*s**i*<=+<=*d**i*,<=*s**i*<=+<=2*d**i*,<=.... The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors? Input Specification: First line contains an integer *n* β€” number of doctors (1<=≀<=*n*<=≀<=1000). Next *n* lines contain two numbers *s**i* and *d**i* (1<=≀<=*s**i*,<=*d**i*<=≀<=1000). Output Specification: Output a single integer β€” the minimum day at which Borya can visit the last doctor. Demo Input: ['3\n2 2\n1 2\n2 2\n', '2\n10 1\n6 5\n'] Demo Output: ['4\n', '11\n'] Note: In the first sample case, Borya can visit all doctors on days 2, 3 and 4. In the second sample case, Borya can visit all doctors on days 10 and 11.
1,348
Title: Car Repair Shop Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time. Polycarp is good at marketing, so he has already collected *n* requests from clients. The requests are numbered from 1 to *n* in order they came. The *i*-th request is characterized by two values: *s**i* β€” the day when a client wants to start the repair of his car, *d**i* β€” duration (in days) to repair the car. The days are enumerated from 1, the first day is tomorrow, the second day is the day after tomorrow and so on. Polycarp is making schedule by processing requests in the order from the first to the *n*-th request. He schedules the *i*-th request as follows: - If the car repair shop is idle for *d**i* days starting from *s**i* (*s**i*,<=*s**i*<=+<=1,<=...,<=*s**i*<=+<=*d**i*<=-<=1), then these days are used to repair a car of the *i*-th client. - Otherwise, Polycarp finds the first day *x* (from 1 and further) that there are *d**i* subsequent days when no repair is scheduled starting from *x*. In other words he chooses the smallest positive *x* that all days *x*,<=*x*<=+<=1,<=...,<=*x*<=+<=*d**i*<=-<=1 are not scheduled for repair of any car. So, the car of the *i*-th client will be repaired in the range [*x*,<=*x*<=+<=*d**i*<=-<=1]. It is possible that the day *x* when repair is scheduled to start will be less than *s**i*. Given *n* requests, you are asked to help Polycarp schedule all of them according to the rules above. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=200) β€” the number of requests from clients. The following *n* lines contain requests, one request per line. The *i*-th request is given as the pair of integers *s**i*,<=*d**i* (1<=≀<=*s**i*<=≀<=109, 1<=≀<=*d**i*<=≀<=5Β·106), where *s**i* is the preferred time to start repairing the *i*-th car, *d**i* is the number of days to repair the *i*-th car. The requests should be processed in the order they are given in the input. Output Specification: Print *n* lines. The *i*-th line should contain two integers β€” the start day to repair the *i*-th car and the finish day to repair the *i*-th car. Demo Input: ['3\n9 2\n7 3\n2 4\n', '4\n1000000000 1000000\n1000000000 1000000\n100000000 1000000\n1000000000 1000000\n'] Demo Output: ['9 10\n1 3\n4 7\n', '1000000000 1000999999\n1 1000000\n100000000 100999999\n1000001 2000000\n'] Note: none
1,349
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him. Thus, he came up with a puzzle to tell his mom his coordinates. His coordinates are the answer to the following problem. A string consisting only of parentheses ('(' and ')') is called a bracket sequence. Some bracket sequence are called correct bracket sequences. More formally: - Empty string is a correct bracket sequence. - if *s* is a correct bracket sequence, then (*s*) is also a correct bracket sequence. - if *s* and *t* are correct bracket sequences, then *st* (concatenation of *s* and *t*) is also a correct bracket sequence. A string consisting of parentheses and question marks ('?') is called pretty if and only if there's a way to replace each question mark with either '(' or ')' such that the resulting string is a non-empty correct bracket sequence. Will gave his mom a string *s* consisting of parentheses and question marks (using Morse code through the lights) and his coordinates are the number of pairs of integers (*l*,<=*r*) such that 1<=≀<=*l*<=≀<=*r*<=≀<=|*s*| and the string *s**l**s**l*<=+<=1... *s**r* is pretty, where *s**i* is *i*-th character of *s*. Joyce doesn't know anything about bracket sequences, so she asked for your help. Input Specification: The first and only line of input contains string *s*, consisting only of characters '(', ')' and '?' (2<=≀<=|*s*|<=≀<=5000). Output Specification: Print the answer to Will's puzzle in the first and only line of output. Demo Input: ['((?))\n', '??()??\n'] Demo Output: ['4\n', '7\n'] Note: For the first sample testcase, the pretty substrings of *s* are: 1. "(?" which can be transformed to "()". 1. "?)" which can be transformed to "()". 1. "((?)" which can be transformed to "(())". 1. "(?))" which can be transformed to "(())". For the second sample testcase, the pretty substrings of *s* are: 1. "??" which can be transformed to "()". 1. "()". 1. "??()" which can be transformed to "()()". 1. "?()?" which can be transformed to "(())". 1. "??" which can be transformed to "()". 1. "()??" which can be transformed to "()()". 1. "??()??" which can be transformed to "()()()".
1,350
Title: Flawed Flow Time Limit: None seconds Memory Limit: None megabytes Problem Description: Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet β€” it calculates the maximum flow in an undirected graph. The graph consists of *n* vertices and *m* edges. Vertices are numbered from 1 to *n*. Vertices 1 and *n* being the source and the sink respectively. However, his max-flow algorithm seems to have a little flaw β€” it only finds the flow volume for each edge, but not its direction. Help him find for each edge the direction of the flow through this edges. Note, that the resulting flow should be correct maximum flow. More formally. You are given an undirected graph. For each it's undirected edge (*a**i*, *b**i*) you are given the flow volume *c**i*. You should direct all edges in such way that the following conditions hold: 1. for each vertex *v* (1<=&lt;<=*v*<=&lt;<=*n*), sum of *c**i* of incoming edges is equal to the sum of *c**i* of outcoming edges; 1. vertex with number 1 has no incoming edges; 1. the obtained directed graph does not have cycles. Input Specification: The first line of input contains two space-separated integers *n* and *m* (2<=≀<=*n*<=≀<=2Β·105, *n*<=-<=1<=≀<=*m*<=≀<=2Β·105), the number of vertices and edges in the graph. The following *m* lines contain three space-separated integers *a**i*, *b**i* and *c**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*, *a**i*<=β‰ <=*b**i*, 1<=≀<=*c**i*<=≀<=104), which means that there is an undirected edge from *a**i* to *b**i* with flow volume *c**i*. It is guaranteed that there are no two edges connecting the same vertices; the given graph is connected; a solution always exists. Output Specification: Output *m* lines, each containing one integer *d**i*, which should be 0 if the direction of the *i*-th edge is *a**i*<=β†’<=*b**i* (the flow goes from vertex *a**i* to vertex *b**i*) and should be 1 otherwise. The edges are numbered from 1 to *m* in the order they are given in the input. If there are several solutions you can print any of them. Demo Input: ['3 3\n3 2 10\n1 2 10\n3 1 5\n', '4 5\n1 2 10\n1 3 10\n2 3 5\n4 2 15\n3 4 5\n'] Demo Output: ['1\n0\n1\n', '0\n0\n1\n1\n0\n'] Note: In the first test case, 10 flow units pass through path <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/609340f155794c4e9eebcd9cdfa23c73cf982f28.png" style="max-width: 100.0%;max-height: 100.0%;"/>, and 5 flow units pass directly from source to sink: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/04481aced8a9d501ae5d785ab654c542ff5497a1.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
1,351
Title: Sum of Nestings Time Limit: None seconds Memory Limit: None megabytes Problem Description: Recall that the bracket sequence is considered regular if it is possible to insert symbols '+' and '1' into it so that the result is a correct arithmetic expression. For example, a sequence "(()())" is regular, because we can get correct arithmetic expression insering symbols '+' and '1': "((1+1)+(1+1))". Also the following sequences are regular: "()()()", "(())" and "()". The following sequences are not regular bracket sequences: ")(", "(()" and "())(()". In this problem you are given two integers *n* and *k*. Your task is to construct a regular bracket sequence consisting of round brackets with length 2Β·*n* with total sum of nesting of all opening brackets equals to exactly *k*. The nesting of a single opening bracket equals to the number of pairs of brackets in which current opening bracket is embedded. For example, in the sequence "()(())" the nesting of first opening bracket equals to 0, the nesting of the second opening bracket equals to 0 and the nesting of the third opening bracket equal to 1. So the total sum of nestings equals to 1. Input Specification: The first line contains two integers *n* and *k* (1<=≀<=*n*<=≀<=3Β·105, 0<=≀<=*k*<=≀<=1018)Β β€” the number of opening brackets and needed total nesting. Output Specification: Print the required regular bracket sequence consisting of round brackets. If there is no solution print "Impossible" (without quotes). Demo Input: ['3 1\n', '4 6\n', '2 5\n'] Demo Output: ['()(())', '(((())))', 'Impossible\n'] Note: The first example is examined in the statement. In the second example the answer is "(((())))". The nesting of the first opening bracket is 0, the nesting of the second is 1, the nesting of the third is 2, the nesting of fourth is 3. So the total sum of nestings equals to 0 + 1 + 2 + 3 = 6. In the third it is impossible to construct a regular bracket sequence, because the maximum possible total sum of nestings for two opening brackets equals to 1. This total sum of nestings is obtained for the sequence "(())".
1,352
Title: Magic, Wizardry and Wonders Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones. This morning he has *n* cards with integers lined up in front of him. Each integer is not less than 1, but not greater than *l*. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left. Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1. Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than *l*, the numbers on the appearing cards can be anything, no restrictions are imposed on them. It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were *n* cards, they contained integers from 1 to *l*, and after all magical actions he was left with a single card containing number *d*. Help Vasya to recover the initial set of cards with numbers. Input Specification: The single line contains three space-separated integers: *n* (2<=≀<=*n*<=≀<=100) β€” the initial number of cards on the table, *d* (|*d*|<=≀<=104) β€” the number on the card that was left on the table after all the magical actions, and *l* (1<=≀<=*l*<=≀<=100) β€” the limits for the initial integers. Output Specification: If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing *n* integers from 1 to *l*. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them. Demo Input: ['3 3 2\n', '5 -4 3\n', '5 -4 4\n'] Demo Output: ['2 1 2 ', '-1\n', '2 4 1 4 1 '] Note: none
1,353
Title: Rat Kwesh and Cheese Time Limit: None seconds Memory Limit: None megabytes Problem Description: Wet Shark asked Rat Kwesh to generate three positive real numbers *x*, *y* and *z*, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point. Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers *x*, *y* and *z* to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options: 1. *a*1<==<=*x**y**z*; 1. *a*2<==<=*x**z**y*; 1. *a*3<==<=(*x**y*)*z*; 1. *a*4<==<=(*x**z*)*y*; 1. *a*5<==<=*y**x**z*; 1. *a*6<==<=*y**z**x*; 1. *a*7<==<=(*y**x*)*z*; 1. *a*8<==<=(*y**z*)*x*; 1. *a*9<==<=*z**x**y*; 1. *a*10<==<=*z**y**x*; 1. *a*11<==<=(*z**x*)*y*; 1. *a*12<==<=(*z**y*)*x*. Let *m* be the maximum of all the *a**i*, and *c* be the smallest index (from 1 to 12) such that *a**c*<==<=*m*. Rat's goal is to find that *c*, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that *a**c*. Input Specification: The only line of the input contains three space-separated real numbers *x*, *y* and *z* (0.1<=≀<=*x*,<=*y*,<=*z*<=≀<=200.0). Each of *x*, *y* and *z* is given with exactly one digit after the decimal point. Output Specification: Find the maximum value of expression among *x**y**z*, *x**z**y*, (*x**y*)*z*, (*x**z*)*y*, *y**x**z*, *y**z**x*, (*y**x*)*z*, (*y**z*)*x*, *z**x**y*, *z**y**x*, (*z**x*)*y*, (*z**y*)*x* and print the corresponding expression. If there are many maximums, print the one that comes first in the list. *x**y**z* should be outputted as x^y^z (without brackets), and (*x**y*)*z* should be outputted as (x^y)^z (quotes for clarity). Demo Input: ['1.1 3.4 2.5\n', '2.0 2.0 2.0\n', '1.9 1.8 1.7\n'] Demo Output: ['z^y^x\n', 'x^y^z\n', '(x^y)^z\n'] Note: none
1,354
Title: Dreamoon and Binary Time Limit: None seconds Memory Limit: None megabytes Problem Description: Dreamoon saw a large integer *x* written on the ground and wants to print its binary form out. Dreamoon has accomplished the part of turning *x* into its binary format. Now he is going to print it in the following manner. He has an integer *n*<==<=0 and can only perform the following two operations in any order for unlimited times each: 1. Print n in binary form without leading zeros, each print will append to the right of previous prints. 1. Increase n by 1. Let's define an ideal sequence as a sequence of operations that can successfully print binary representation of *x* without leading zeros and ends with a print operation (i.e. operation 1). Dreamoon wants to know how many different ideal sequences are there and the length (in operations) of the shortest ideal sequence. The answers might be large so please print them modulo 1000000007 (109<=+<=7). Let's define the string representation of an ideal sequence as a string of '1' and '2' where the *i*-th character in the string matches the *i*-th operation performed. Two ideal sequences are called different if their string representations are different. Input Specification: The single line of the input contains a binary integer representing *x* (1<=≀<=*x*<=&lt;<=25000) without leading zeros. Output Specification: The first line of the output should contain an integer representing the number of different ideal sequences modulo 1000000007 (109<=+<=7). The second line of the output contains an integer representing the minimal length of an ideal sequence modulo 1000000007 (109<=+<=7). Demo Input: ['101\n', '11010\n'] Demo Output: ['1\n6\n', '3\n5\n'] Note: For the first sample, the shortest and the only ideal sequence is Β«222221Β» of length 6. For the second sample, there are three ideal sequences Β«21211Β», Β«212222222221Β», Β«222222222222222222222222221Β». Among them the shortest one has length 5.
1,355
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You have a map as a rectangle table. Each cell of the table is either an obstacle, or a treasure with a certain price, or a bomb, or an empty cell. Your initial position is also given to you. You can go from one cell of the map to a side-adjacent one. At that, you are not allowed to go beyond the borders of the map, enter the cells with treasures, obstacles and bombs. To pick the treasures, you need to build a closed path (starting and ending in the starting cell). The closed path mustn't contain any cells with bombs inside. Let's assume that the sum of the treasures' values that are located inside the closed path equals *v*, and besides, you've made *k* single moves (from one cell to another) while you were going through the path, then such path brings you the profit of *v*<=-<=*k* rubles. Your task is to build a closed path that doesn't contain any bombs and brings maximum profit. Note that the path can have self-intersections. In order to determine if a cell lies inside a path or not, use the following algorithm: 1. Assume that the table cells are points on the plane (the table cell on the intersection of the *i*-th column and the *j*-th row is point (*i*,<=*j*)). And the given path is a closed polyline that goes through these points. 1. You need to find out if the point *p* of the table that is not crossed by the polyline lies inside the polyline. 1. Let's draw a ray that starts from point *p* and does not intersect other points of the table (such ray must exist). 1. Let's count the number of segments of the polyline that intersect the painted ray. If this number is odd, we assume that point *p* (and consequently, the table cell) lie inside the polyline (path). Otherwise, we assume that it lies outside. Input Specification: The first line contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=20) β€” the sizes of the table. Next *n* lines each contains *m* characters β€” the description of the table. The description means the following: - character "B" is a cell with a bomb; - character "S" is the starting cell, you can assume that it's empty; - digit *c* (1-8) is treasure with index *c*; - character "." is an empty cell; - character "#" is an obstacle. Assume that the map has *t* treasures. Next *t* lines contain the prices of the treasures. The *i*-th line contains the price of the treasure with index *i*, *v**i* (<=-<=200<=≀<=*v**i*<=≀<=200). It is guaranteed that the treasures are numbered from 1 to *t*. It is guaranteed that the map has not more than 8 objects in total. Objects are bombs and treasures. It is guaranteed that the map has exactly one character "S". Output Specification: Print a single integer β€” the maximum possible profit you can get. Demo Input: ['4 4\n....\n.S1.\n....\n....\n10\n', '7 7\n.......\n.1###2.\n.#...#.\n.#.B.#.\n.3...4.\n..##...\n......S\n100\n100\n100\n100\n', '7 8\n........\n........\n....1B..\n.S......\n....2...\n3.......\n........\n100\n-100\n100\n', '1 1\nS\n'] Demo Output: ['2\n', '364\n', '0\n', '0\n'] Note: In the first example the answer will look as follows. In the second example the answer will look as follows. In the third example you cannot get profit. In the fourth example you cannot get profit as you cannot construct a closed path with more than one cell.
1,356
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given a table consisting of *n* rows and *m* columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa. What is the minimum number of cells with value 1 you can get after applying some number of operations? Input Specification: The first line of the input contains two integers *n* and *m* (1<=≀<=*n*<=≀<=20, 1<=≀<=*m*<=≀<=100<=000)Β β€” the number of rows and the number of columns, respectively. Then *n* lines follows with the descriptions of the rows. Each line has length *m* and contains only digits '0' and '1'. Output Specification: Output a single integerΒ β€” the minimum possible number of ones you can get after applying some sequence of operations. Demo Input: ['3 4\n0110\n1010\n0111\n'] Demo Output: ['2\n'] Note: none
1,357
Title: Comb Time Limit: 1 seconds Memory Limit: 256 megabytes Problem Description: Having endured all the hardships, Lara Croft finally found herself in a room with treasures. To her surprise she didn't find golden mountains there. Lara looked around and noticed on the floor a painted table *n*<=Γ—<=*m* panels in size with integers written on the panels. There also was a huge number of stones lying by the wall. On the pillar near the table Lara found a guidance note which said that to get hold of the treasures one has to choose some non-zero number of the first panels in each row of the table and put stones on all those panels to push them down. After that she will receive a number of golden coins equal to the sum of numbers written on the chosen panels. Lara quickly made up her mind on how to arrange the stones and was about to start when she noticed an addition to the note in small font below. According to the addition, for the room ceiling not to crush and smash the adventurer, the chosen panels should form a comb. It was explained that the chosen panels form a comb when the sequence *c*1,<=*c*2,<=...,<=*c**n* made from the quantities of panels chosen in each table line satisfies the following property: *c*1<=&gt;<=*c*2<=&lt;<=*c*3<=&gt;<=*c*4<=&lt;<=..., i.e. the inequation mark interchanges between the neighboring elements. Now Lara is bewildered and doesn't know what to do. Help her to determine the largest number of coins she can get and survive at the same time. Input Specification: The first line contains a pair of integers *n*,<=*m* (2<=≀<=*n*,<=*m*<=≀<=1500). Next *n* lines contain *m* integers each β€” that is the table itself. The absolute value of the numbers in the table does not exceed 10000. Output Specification: Print the single number β€” the maximum number of coins Lara can get. Demo Input: ['2 2\n-1 2\n1 3\n'] Demo Output: ['2\n'] Note: none
1,358
Title: Perfect Squares Time Limit: None seconds Memory Limit: None megabytes Problem Description: Given an array *a*1,<=*a*2,<=...,<=*a**n* of *n* integers, find the largest number in the array that is not a perfect square. A number *x* is said to be a perfect square if there exists an integer *y* such that *x*<==<=*y*2. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=1000)Β β€” the number of elements in the array. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=106<=≀<=*a**i*<=≀<=106)Β β€” the elements of the array. It is guaranteed that at least one element of the array is not a perfect square. Output Specification: Print the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists. Demo Input: ['2\n4 2\n', '8\n1 2 4 8 16 32 64 576\n'] Demo Output: ['2\n', '32\n'] Note: In the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2.
1,359
Title: Traffic Jams in the Land Time Limit: None seconds Memory Limit: None megabytes Problem Description: Some country consists of (*n*<=+<=1) cities, located along a straight highway. Let's number the cities with consecutive integers from 1 to *n*<=+<=1 in the order they occur along the highway. Thus, the cities are connected by *n* segments of the highway, the *i*-th segment connects cities number *i* and *i*<=+<=1. Every segment of the highway is associated with a positive integer *a**i*<=&gt;<=1 β€” the period of traffic jams appearance on it. In order to get from city *x* to city *y* (*x*<=&lt;<=*y*), some drivers use the following tactics. Initially the driver is in city *x* and the current time *t* equals zero. Until the driver arrives in city *y*, he perfors the following actions: - if the current time *t* is a multiple of *a**x*, then the segment of the highway number *x* is now having traffic problems and the driver stays in the current city for one unit of time (formally speaking, we assign *t*<==<=*t*<=+<=1); - if the current time *t* is not a multiple of *a**x*, then the segment of the highway number *x* is now clear and that's why the driver uses one unit of time to move to city *x*<=+<=1 (formally, we assign *t*<==<=*t*<=+<=1 and *x*<==<=*x*<=+<=1). You are developing a new traffic control system. You want to consecutively process *q* queries of two types: 1. determine the final value of time *t* after the ride from city *x* to city *y* (*x*<=&lt;<=*y*) assuming that we apply the tactics that is described above. Note that for each query *t* is being reset to 0. 1. replace the period of traffic jams appearing on the segment number *x* by value *y* (formally, assign *a**x*<==<=*y*). Write a code that will effectively process the queries given above. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of highway segments that connect the *n*<=+<=1 cities. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (2<=≀<=*a**i*<=≀<=6) β€” the periods of traffic jams appearance on segments of the highway. The next line contains a single integer *q* (1<=≀<=*q*<=≀<=105) β€” the number of queries to process. The next *q* lines contain the descriptions of the queries in the format *c*, *x*, *y* (*c* β€” the query type). If *c* is character 'A', then your task is to process a query of the first type. In this case the following constraints are satisfied: 1<=≀<=*x*<=&lt;<=*y*<=≀<=*n*<=+<=1. If *c* is character 'C', then you need to process a query of the second type. In such case, the following constraints are satisfied: 1<=≀<=*x*<=≀<=*n*, 2<=≀<=*y*<=≀<=6. Output Specification: For each query of the first type output a single integer β€” the final value of time *t* after driving from city *x* to city *y*. Process the queries in the order in which they are given in the input. Demo Input: ['10\n2 5 3 2 3 5 3 4 2 4\n10\nC 10 6\nA 2 6\nA 1 3\nC 3 4\nA 3 11\nA 4 9\nA 5 6\nC 7 3\nA 8 10\nA 2 5\n'] Demo Output: ['5\n3\n14\n6\n2\n4\n4\n'] Note: none
1,360
Title: Exams Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day the Codeforces round author sat exams. He had *n* exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2. The author would need to spend too much time and effort to make the sum of his marks strictly more than *k*. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than *k*, the author's mum won't be pleased at all. The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams. Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all *n* exams equal exactly *k*. Input Specification: The single input line contains space-separated integers *n* and *k* (1<=≀<=*n*<=≀<=50, 1<=≀<=*k*<=≀<=250) β€” the number of exams and the required sum of marks. It is guaranteed that there exists a way to pass *n* exams in the way that makes the sum of marks equal exactly *k*. Output Specification: Print the single number β€” the minimum number of exams that the author will get a 2 for, considering that the sum of marks for all exams must equal *k*. Demo Input: ['4 8\n', '4 10\n', '1 3\n'] Demo Output: ['4\n', '2\n', '0\n'] Note: In the first sample the author has to get a 2 for all his exams. In the second sample he should get a 3 for two exams and a 2 for two more. In the third sample he should get a 3 for one exam.
1,361
Title: Jeff and Periods Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day Jeff got hold of an integer sequence *a*1, *a*2, ..., *a**n* of length *n*. The boy immediately decided to analyze the sequence. For that, he needs to find all values of *x*, for which these conditions hold: - *x* occurs in sequence *a*. - Consider all positions of numbers *x* in the sequence *a* (such *i*, that *a**i*<==<=*x*). These numbers, sorted in the increasing order, must form an arithmetic progression. Help Jeff, find all *x* that meet the problem conditions. Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105). The next line contains integers *a*1, *a*2, ..., *a**n* (1<=≀<=*a**i*<=≀<=105). The numbers are separated by spaces. Output Specification: In the first line print integer *t* β€” the number of valid *x*. On each of the next *t* lines print two integers *x* and *p**x*, where *x* is current suitable value, *p**x* is the common difference between numbers in the progression (if *x* occurs exactly once in the sequence, *p**x* must equal 0). Print the pairs in the order of increasing *x*. Demo Input: ['1\n2\n', '8\n1 2 1 3 1 2 1 5\n'] Demo Output: ['1\n2 0\n', '4\n1 2\n2 4\n3 0\n5 0\n'] Note: In the first test 2 occurs exactly once in the sequence, ergo *p*<sub class="lower-index">2</sub> = 0.
1,362
Title: Roman and Numbers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number *n*, modulo *m*. Number *x* is considered close to number *n* modulo *m*, if: - it can be obtained by rearranging the digits of number *n*, - it doesn't have any leading zeroes, - the remainder after dividing number *x* by *m* equals 0. Roman is a good mathematician, but the number of such numbers is too huge for him. So he asks you to help him. Input Specification: The first line contains two integers: *n* (1<=≀<=*n*<=&lt;<=1018) and *m* (1<=≀<=*m*<=≀<=100). Output Specification: In a single line print a single integer β€” the number of numbers close to number *n* modulo *m*. Demo Input: ['104 2\n', '223 4\n', '7067678 8\n'] Demo Output: ['3\n', '1\n', '47\n'] Note: In the first sample the required numbers are: 104, 140, 410. In the second sample the required number is 232.
1,363
Title: Geometric Progression Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer *k* and a sequence *a*, consisting of *n* integers. He wants to know how many subsequences of length three can be selected from *a*, so that they form a geometric progression with common ratio *k*. A subsequence of length three is a combination of three such indexes *i*1,<=*i*2,<=*i*3, that 1<=≀<=*i*1<=&lt;<=*i*2<=&lt;<=*i*3<=≀<=*n*. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing. A geometric progression with common ratio *k* is a sequence of numbers of the form *b*Β·*k*0,<=*b*Β·*k*1,<=...,<=*b*Β·*k**r*<=-<=1. Polycarp is only three years old, so he can not calculate this number himself. Help him to do it. Input Specification: The first line of the input contains two integers, *n* and *k* (1<=≀<=*n*,<=*k*<=≀<=2Β·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≀<=*a**i*<=≀<=109) β€” elements of the sequence. Output Specification: Output a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio *k*. Demo Input: ['5 2\n1 1 2 2 4\n', '3 1\n1 1 1\n', '10 3\n1 2 6 2 3 6 9 18 3 9\n'] Demo Output: ['4', '1', '6'] Note: In the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
1,364
Title: Palindromic Times Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues. On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome. In his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment. However, he still hasn't mastered the skill of programming while sleeping, so your task is to help him. Input Specification: The first and only line of the input starts with a string with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59". Both "HH" and "MM" have exactly two digits. Output Specification: Print the palindromic time of day that comes soonest after the time given in the input. If the input time is palindromic, output the soonest palindromic time after the input time. Demo Input: ['12:21\n', '23:59\n'] Demo Output: ['13:31\n', '00:00\n'] Note: none
1,365
Title: Hiring Staff Time Limit: None seconds Memory Limit: None megabytes Problem Description: A new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff. The store will work seven days a week, but not around the clock. Every day at least *k* people must work in the store. Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly *n* consecutive days, then rest for exactly *m* days, then work for *n* more days and rest for *m* more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day *x*, then he should work on days [*x*,<=*x*<=+<=1,<=...,<=*x*<=+<=*n*<=-<=1], [*x*<=+<=*m*<=+<=*n*,<=*x*<=+<=*m*<=+<=*n*<=+<=1,<=...,<=*x*<=+<=*m*<=+<=2*n*<=-<=1], and so on. Day *x* can be chosen arbitrarily by Vitaly. There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day β€” otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day. Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least *k* working employees, and one of the working employees should have the key to the store. Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired. Input Specification: The first line contains three integers *n*, *m* and *k* (1<=≀<=*m*<=≀<=*n*<=≀<=1000, *n*<=β‰ <=1, 1<=≀<=*k*<=≀<=1000). Output Specification: In the first line print a single integer *z* β€” the minimum required number of employees. In the second line print *z* positive integers, separated by spaces: the *i*-th integer *a**i* (1<=≀<=*a**i*<=≀<=104) should represent the number of the day, on which Vitaly should hire the *i*-th employee. If there are multiple answers, print any of them. Demo Input: ['4 3 2\n', '3 3 1\n'] Demo Output: ['4\n1 1 4 5', '3\n1 3 5'] Note: none
1,366
Title: Felicity is Coming! Time Limit: None seconds Memory Limit: None megabytes Problem Description: It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has *n* gyms. The *i*-th gym has *g**i* Pokemon in it. There are *m* distinct Pokemon types in the Himalayan region numbered from 1 to *m*. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation *f* of {1,<=2,<=...,<=*m*}, such that *f*(*x*)<==<=*y* means that a Pokemon of type *x* evolves into a Pokemon of type *y*. The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol. Two evolution plans *f*1 and *f*2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an *i* such that *f*1(*i*)<=β‰ <=*f*2(*i*). Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 109<=+<=7. Input Specification: The first line contains two integers *n* and *m* (1<=≀<=*n*<=≀<=105, 1<=≀<=*m*<=≀<=106)Β β€” the number of gyms and the number of Pokemon types. The next *n* lines contain the description of Pokemons in the gyms. The *i*-th of these lines begins with the integer *g**i* (1<=≀<=*g**i*<=≀<=105)Β β€” the number of Pokemon in the *i*-th gym. After that *g**i* integers follow, denoting types of the Pokemons in the *i*-th gym. Each of these integers is between 1 and *m*. The total number of Pokemons (the sum of all *g**i*) does not exceed 5Β·105. Output Specification: Output the number of valid evolution plans modulo 109<=+<=7. Demo Input: ['2 3\n2 1 2\n2 2 3\n', '1 3\n3 1 2 3\n', '2 4\n2 1 2\n3 2 3 4\n', '2 2\n3 2 2 1\n2 1 2\n', '3 7\n2 1 2\n2 3 4\n3 5 6 7\n'] Demo Output: ['1\n', '6\n', '2\n', '1\n', '24\n'] Note: In the first case, the only possible evolution plan is: In the second case, any permutation of (1,  2,  3) is valid. In the third case, there are two possible plans: In the fourth case, the only possible evolution plan is:
1,367
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: 1. He looks through all the coins from left to right; 1. If he sees that the *i*-th coin is still in circulation, and (*i*<=+<=1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (*i*<=+<=1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one. Today Sasha invited Dima and proposed him a game. First he puts *n* coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for *n* times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. Input Specification: The first line contains single integer *n* (1<=≀<=*n*<=≀<=300<=000)Β β€” number of coins that Sasha puts behind Dima. Second line contains *n* distinct integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≀<=*p**i*<=≀<=*n*)Β β€” positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position *p*1, then coin located at position *p*2 and so on. Coins are numbered from left to right. Output Specification: Print *n*<=+<=1 numbers *a*0,<=*a*1,<=...,<=*a**n*, where *a*0 is a hardness of ordering at the beginning, *a*1 is a hardness of ordering after the first replacement and so on. Demo Input: ['4\n1 3 4 2\n', '8\n6 8 3 4 7 2 1 5\n'] Demo Output: ['1 2 3 2 1\n', '1 2 2 3 4 3 4 5 1\n'] Note: Let's denote as O coin out of circulation, and as X β€” coin is circulation. At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges. After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process. XOOO  →  OOOX After replacement of the third coin, Dima's actions look this way: XOXO  →  OXOX  →  OOXX After replacement of the fourth coin, Dima's actions look this way: XOXX  →  OXXX Finally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges.
1,368
Title: Programming Language Time Limit: None seconds Memory Limit: None megabytes Problem Description: Recently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, default values). Valery decided to examine template procedures in this language in more detail. The description of a template procedure consists of the procedure name and the list of its parameter types. The generic type T parameters can be used as parameters of template procedures. A procedure call consists of a procedure name and a list of variable parameters. Let's call a procedure suitable for this call if the following conditions are fulfilled: - its name equals to the name of the called procedure; - the number of its parameters equals to the number of parameters of the procedure call; - the types of variables in the procedure call match the corresponding types of its parameters. The variable type matches the type of a parameter if the parameter has a generic type T or the type of the variable and the parameter are the same. You are given a description of some set of template procedures. You are also given a list of variables used in the program, as well as direct procedure calls that use the described variables. For each call you need to count the number of procedures that are suitable for this call. Input Specification: The first line contains a single integer *n* (1<=≀<=*n*<=≀<=1000) β€” the number of template procedures. The next *n* lines contain the description of the procedures specified in the following format: "void procedureName (type_1, type_2, ..., type_t)" (1<=≀<=*t*<=≀<=5), where void is the keyword, procedureName is the procedure name, type_i is the type of the next parameter. Types of language parameters can be "int", "string", "double", and the keyword "T", which denotes the generic type. The next line contains a single integer *m* (1<=≀<=*m*<=≀<=1000) β€” the number of used variables. Next *m* lines specify the description of the variables in the following format: "type variableName", where type is the type of variable that can take values "int", "string", "double", variableName β€” the name of the variable. The next line contains a single integer *k* (1<=≀<=*k*<=≀<=1000) β€” the number of procedure calls. Next *k* lines specify the procedure calls in the following format: "procedureName (var_1, var_2, ..., var_t)" (1<=≀<=*t*<=≀<=5), where procedureName is the name of the procedure, var_i is the name of a variable. The lines describing the variables, template procedures and their calls may contain spaces at the beginning of the line and at the end of the line, before and after the brackets and commas. Spaces may be before and after keyword void. The length of each input line does not exceed 100 characters. The names of variables and procedures are non-empty strings of lowercase English letters and numbers with lengths of not more than 10 characters. Note that this is the only condition at the names. Only the specified variables are used in procedure calls. The names of the variables are distinct. No two procedures are the same. Two procedures are the same, if they have identical names and identical ordered sets of types of their parameters. Output Specification: On each of *k* lines print a single number, where the *i*-th number stands for the number of suitable template procedures for the *i*-th call. Demo Input: ['4\nvoid f(int,T)\nvoid f(T, T)\n void foo123 ( int, double, string,string ) \n void p(T,double)\n3\nint a\n string s\ndouble x123 \n5\nf(a, a)\n f(s,a )\nfoo (a,s,s)\n f ( s ,x123)\nproc(a)\n', '6\nvoid f(string,double,int)\nvoid f(int)\n void f ( T )\nvoid procedure(int,double)\nvoid f (T, double,int) \nvoid f(string, T,T)\n4\n int a\n int x\nstring t\ndouble val \n5\nf(t, a, a)\nf(t,val,a)\nf(val,a, val)\n solve300(val, val)\nf (x)\n'] Demo Output: ['2\n1\n0\n1\n0\n', '1\n3\n0\n0\n2\n'] Note: none
1,369
Title: On Segment's Own Points Time Limit: None seconds Memory Limit: None megabytes Problem Description: Our old friend Alexey has finally entered the University of City N β€” the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer β€” a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has *n* students. Dean's office allows *i*-th student to use the segment (*l**i*,<=*r**i*) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students! Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (*n*<=-<=1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1. Input Specification: The first line contains a positive integer *n* (1<=≀<=*n*<=≀<=100). The (*i*<=+<=1)-th line contains integers *l**i* and *r**i* (0<=≀<=*l**i*<=&lt;<=*r**i*<=≀<=100) β€”Β the endpoints of the corresponding segment for the *i*-th student. Output Specification: On a single line print a single number *k*, equal to the sum of lengths of the parts of the dryer which are inside Alexey's segment and are outside all other segments. Demo Input: ['3\n0 5\n2 8\n1 6\n', '3\n0 10\n1 5\n7 15\n'] Demo Output: ['1\n', '3\n'] Note: Note that it's not important are clothes drying on the touching segments (e.g. (0, 1) and (1, 2)) considered to be touching or not because you need to find the length of segments. In the first test sample Alexey may use the only segment (0, 1). In such case his clothes will not touch clothes on the segments (1, 6) and (2, 8). The length of segment (0, 1) is 1. In the second test sample Alexey may dry his clothes on segments (0, 1) and (5, 7). Overall length of these segments is 3.
1,370
Title: Newspaper Headline Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: A newspaper is published in Walrusland. Its heading is *s*1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word *s*2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters. For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac". Which least number of newspaper headings *s*1 will Fangy need to glue them, erase several letters and get word *s*2? Input Specification: The input data contain two lines. The first line contain the heading *s*1, the second line contains the word *s*2. The lines only consist of lowercase Latin letters (1<=≀<=|*s*1|<=≀<=104,<=1<=≀<=|*s*2|<=≀<=106). Output Specification: If it is impossible to get the word *s*2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings *s*1, which Fangy will need to receive the word *s*2. Demo Input: ['abc\nxyz\n', 'abcd\ndabc\n'] Demo Output: ['-1\n', '2\n'] Note: none
1,371
Title: Little Pony and Sort by Shift Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day, Twilight Sparkle is interested in how to sort a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning: Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence? Input Specification: The first line contains an integer *n* (2<=≀<=*n*<=≀<=105). The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=105). Output Specification: If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it. Demo Input: ['2\n2 1\n', '3\n1 3 2\n', '2\n1 2\n'] Demo Output: ['1\n', '-1\n', '0\n'] Note: none
1,372
Title: Multi-judge Solving Time Limit: None seconds Memory Limit: None megabytes Problem Description: Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty β€” a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty *d* on Decoforces is as hard as the problem with difficulty *d* on any other judge). Makes has chosen *n* problems to solve on Decoforces with difficulties *a*1,<=*a*2,<=...,<=*a**n*. He can solve these problems in arbitrary order. Though he can solve problem *i* with difficulty *a**i* only if he had already solved some problem with difficulty (no matter on what online judge was it). Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty *k*. With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list. For every positive integer *y* there exist some problem with difficulty *y* on at least one judge besides Decoforces. Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another. Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces. Input Specification: The first line contains two integer numbers *n*, *k* (1<=≀<=*n*<=≀<=103, 1<=≀<=*k*<=≀<=109). The second line contains *n* space-separated integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109). Output Specification: Print minimum number of problems Makes should solve on other judges in order to solve all chosen problems on Decoforces. Demo Input: ['3 3\n2 1 9\n', '4 20\n10 3 6 3\n'] Demo Output: ['1\n', '0\n'] Note: In the first example Makes at first solves problems 1 and 2. Then in order to solve the problem with difficulty 9, he should solve problem with difficulty no less than 5. The only available are difficulties 5 and 6 on some other judge. Solving any of these will give Makes opportunity to solve problem 3. In the second example he can solve every problem right from the start.
1,373
Title: Restoring Numbers Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vasya had two arrays consisting of non-negative integers: *a* of size *n* and *b* of size *m*. Vasya chose a positive integer *k* and created an *n*<=Γ—<=*m* matrix *v* using the following formula: Vasya wrote down matrix *v* on a piece of paper and put it in the table. A year later Vasya was cleaning his table when he found a piece of paper containing an *n*<=Γ—<=*m* matrix *w*. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix *v* from those days. Your task is to find out if the matrix *w* that you've found could have been obtained by following these rules and if it could, then for what numbers *k*,<=*a*1,<=*a*2,<=...,<=*a**n*,<=*b*1,<=*b*2,<=...,<=*b**m* it is possible. Input Specification: The first line contains integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=100), separated by a space β€” the number of rows and columns in the found matrix, respectively. The *i*-th of the following lines contains numbers *w**i*,<=1,<=*w**i*,<=2,<=...,<=*w**i*,<=*m* (0<=≀<=*w**i*,<=*j*<=≀<=109), separated by spaces β€” the elements of the *i*-th row of matrix *w*. Output Specification: If the matrix *w* could not have been obtained in the manner described above, print "NO" (without quotes) in the single line of output. Otherwise, print four lines. In the first line print "YES" (without quotes). In the second line print an integer *k* (1<=≀<=*k*<=≀<=1018). Note that each element of table *w* should be in range between 0 and *k*<=-<=1 inclusively. In the third line print *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=1018), separated by spaces. In the fourth line print *m* integers *b*1,<=*b*2,<=...,<=*b**m* (0<=≀<=*b**i*<=≀<=1018), separated by spaces. Demo Input: ['2 3\n1 2 3\n2 3 4\n', '2 2\n1 2\n2 0\n', '2 2\n1 2\n2 1\n'] Demo Output: ['YES\n1000000007\n0 1 \n1 2 3 ', 'YES\n3\n0 1 \n1 2 ', 'NO\n'] Note: By <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e4ee2bc16f1508a982cfc739e1c7ddc442223116.png" style="max-width: 100.0%;max-height: 100.0%;"/> we denote the remainder of integer division of *b* by *c*. It is guaranteed that if there exists some set of numbers *k*, *a*<sub class="lower-index">1</sub>, ..., *a*<sub class="lower-index">*n*</sub>, *b*<sub class="lower-index">1</sub>, ..., *b*<sub class="lower-index">*m*</sub>, that you could use to make matrix *w*, then there also exists a set of numbers that meets the limits 1 ≀ *k* ≀ 10<sup class="upper-index">18</sup>, 1 ≀ *a*<sub class="lower-index">*i*</sub> ≀ 10<sup class="upper-index">18</sup>, 1 ≀ *b*<sub class="lower-index">*i*</sub> ≀ 10<sup class="upper-index">18</sup> in the output format. In other words, these upper bounds are introduced only for checking convenience purposes.
1,374
Title: Qualification Rounds Time Limit: None seconds Memory Limit: None megabytes Problem Description: Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of *n* problems, and they want to select any non-empty subset of it as a problemset. *k* experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems. Determine if Snark and Philip can make an interesting problemset! Input Specification: The first line contains two integers *n*, *k* (1<=≀<=*n*<=≀<=105, 1<=≀<=*k*<=≀<=4)Β β€” the number of problems and the number of experienced teams. Each of the next *n* lines contains *k* integers, each equal to 0 or 1. The *j*-th number in the *i*-th line is 1 if *j*-th team knows *i*-th problem and 0 otherwise. Output Specification: Print "YES" (quotes for clarity), if it is possible to make an interesting problemset, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES"). Demo Input: ['5 3\n1 0 1\n1 1 0\n1 0 0\n1 0 0\n1 0 0\n', '3 2\n1 0\n1 1\n0 1\n'] Demo Output: ['NO\n', 'YES\n'] Note: In the first example you can't make any interesting problemset, because the first team knows all problems. In the second example you can choose the first and the third problems.
1,375
Title: Cards Time Limit: None seconds Memory Limit: None megabytes Problem Description: User ainta loves to play with cards. He has *a* cards containing letter "o" and *b* cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below. 1. At first, the score is 0. 1. For each block of contiguous "o"s with length *x* the score increases by *x*2. 1. For each block of contiguous "x"s with length *y* the score decreases by *y*2. For example, if *a*<==<=6,<=*b*<==<=3 and ainta have arranged the cards in the order, that is described by string "ooxoooxxo", the score of the deck equals 22<=-<=12<=+<=32<=-<=22<=+<=12<==<=9. That is because the deck has 5 blocks in total: "oo", "x", "ooo", "xx", "o". User ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards. Input Specification: The first line contains two space-separated integers *a* and *b* (0<=≀<=*a*,<=*b*<=≀<=105;Β *a*<=+<=*b*<=β‰₯<=1) β€” the number of "o" cards and the number of "x" cards. Output Specification: In the first line print a single integer *v* β€” the maximum score that ainta can obtain. In the second line print *a*<=+<=*b* characters describing the deck. If the *k*-th card of the deck contains "o", the *k*-th character must be "o". If the *k*-th card of the deck contains "x", the *k*-th character must be "x". The number of "o" characters must be equal to *a*, and the number of "x " characters must be equal to *b*. If there are many ways to maximize *v*, print any. 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. Demo Input: ['2 3\n', '4 0\n', '0 4\n'] Demo Output: ['-1\nxoxox\n', '16\noooo', '-16\nxxxx'] Note: none
1,376
Title: Marvolo Gaunt's Ring Time Limit: None seconds Memory Limit: None megabytes Problem Description: Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly *x* drops of the potion he made. Value of *x* is calculated as maximum of *p*Β·*a**i*<=+<=*q*Β·*a**j*<=+<=*r*Β·*a**k* for given *p*,<=*q*,<=*r* and array *a*1,<=*a*2,<=... *a**n* such that 1<=≀<=*i*<=≀<=*j*<=≀<=*k*<=≀<=*n*. Help Snape find the value of *x*. Do note that the value of *x* may be negative. Input Specification: First line of input contains 4 integers *n*,<=*p*,<=*q*,<=*r* (<=-<=109<=≀<=*p*,<=*q*,<=*r*<=≀<=109,<=1<=≀<=*n*<=≀<=105). Next line of input contains *n* space separated integers *a*1,<=*a*2,<=... *a**n* (<=-<=109<=≀<=*a**i*<=≀<=109). Output Specification: Output a single integer the maximum value of *p*Β·*a**i*<=+<=*q*Β·*a**j*<=+<=*r*Β·*a**k* that can be obtained provided 1<=≀<=*i*<=≀<=*j*<=≀<=*k*<=≀<=*n*. Demo Input: ['5 1 2 3\n1 2 3 4 5\n', '5 1 2 -3\n-1 -2 -3 -4 -5\n'] Demo Output: ['30\n', '12\n'] Note: In the first sample case, we can take *i* = *j* = *k* = 5, thus making the answer as 1Β·5 + 2Β·5 + 3Β·5 = 30. In second sample case, selecting *i* = *j* = 1 and *k* = 5 gives the answer 12.
1,377
Title: Physical Education and Buns Time Limit: None seconds Memory Limit: None megabytes Problem Description: The Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression. To achieve the goal, the gym teacher ordered a lot of magical buns from the dining room. The magic buns come in two types: when a student eats one magic bun of the first type, his height increases by one, when the student eats one magical bun of the second type, his height decreases by one. The physical education teacher, as expected, cares about the health of his students, so he does not want them to eat a lot of buns. More precisely, he wants the maximum number of buns eaten by some student to be minimum. Help the teacher, get the maximum number of buns that some pupils will have to eat to achieve the goal of the teacher. Also, get one of the possible ways for achieving the objective, namely, the height of the lowest student in the end and the step of the resulting progression. Input Specification: The single line contains integer *n* (2<=≀<=*n*<=≀<=103) β€” the number of students. The second line contains *n* space-separated integers β€” the heights of all students. The height of one student is an integer which absolute value doesn't exceed 104. Output Specification: In the first line print the maximum number of buns eaten by some student to achieve the teacher's aim. In the second line, print two space-separated integers β€” the height of the lowest student in the end and the step of the progression. Please, pay attention that the step should be non-negative. If there are multiple possible answers, you can print any of them. Demo Input: ['5\n-3 -4 -2 -3 3\n', '5\n2 -3 -1 -4 3\n'] Demo Output: ['2\n-3 1\n', '1\n-4 2\n'] Note: Lets look at the first sample. We can proceed in the following manner: - don't feed the 1-st student, his height will stay equal to -3; - give two buns of the first type to the 2-nd student, his height become equal to -2; - give two buns of the first type to the 3-rd student, his height become equal to 0; - give two buns of the first type to the 4-th student, his height become equal to -1; - give two buns of the second type to the 5-th student, his height become equal to 1. To sum it up, when the students line up in non-decreasing height it will be an arithmetic progression: -3, -2, -1, 0, 1. The height of the lowest student is equal to -3, the step of the progression is equal to 1. The maximum number of buns eaten by one student is equal to 2.
1,378
Title: Polo the Penguin and Houses Time Limit: None seconds Memory Limit: None megabytes Problem Description: Little penguin Polo loves his home village. The village has *n* houses, indexed by integers from 1 to *n*. Each house has a plaque containing an integer, the *i*-th house has a plaque containing integer *p**i* (1<=≀<=*p**i*<=≀<=*n*). Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number *x*. Then he goes to the house whose number is written on the plaque of house *x* (that is, to house *p**x*), then he goes to the house whose number is written on the plaque of house *p**x* (that is, to house *p**p**x*), and so on. We know that: 1. When the penguin starts walking from any house indexed from 1 to *k*, inclusive, he can walk to house number 1. 1. When the penguin starts walking from any house indexed from *k*<=+<=1 to *n*, inclusive, he definitely cannot walk to house number 1. 1. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house. You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109<=+<=7). Input Specification: The single line contains two space-separated integers *n* and *k* (1<=≀<=*n*<=≀<=1000,<=1<=≀<=*k*<=≀<=*min*(8,<=*n*)) β€” the number of the houses and the number *k* from the statement. Output Specification: In a single line print a single integer β€” the answer to the problem modulo 1000000007 (109<=+<=7). Demo Input: ['5 2\n', '7 4\n'] Demo Output: ['54\n', '1728\n'] Note: none
1,379
Title: Vika and Segments Time Limit: None seconds Memory Limit: None megabytes Problem Description: Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew *n* black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column. Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once. Input Specification: The first line of the input contains a single integer *n* (1<=≀<=*n*<=≀<=100<=000)Β β€” the number of segments drawn by Vika. Each of the next *n* lines contains four integers *x*1, *y*1, *x*2 and *y*2 (<=-<=109<=≀<=*x*1,<=*y*1,<=*x*2,<=*y*2<=≀<=109)Β β€” the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide. Output Specification: Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer. Demo Input: ['3\n0 1 2 1\n1 4 1 2\n0 3 2 3\n', '4\n-2 -1 2 -1\n2 1 -2 1\n-1 -2 -1 2\n1 2 1 -2\n'] Demo Output: ['8\n', '16\n'] Note: In the first sample Vika will paint squares (0, 1), (1, 1), (2, 1), (1, 2), (1, 3), (1, 4), (0, 3) and (2, 3).
1,380
Title: Special Matrices Time Limit: None seconds Memory Limit: None megabytes Problem Description: An *n*<=Γ—<=*n* square matrix is special, if: - it is binary, that is, each cell contains either a 0, or a 1; - the number of ones in each row and column equals 2. You are given *n* and the first *m* rows of the matrix. Print the number of special *n*<=Γ—<=*n* matrices, such that the first *m* rows coincide with the given ones. As the required value can be rather large, print the remainder after dividing the value by the given number *mod*. Input Specification: The first line of the input contains three integers *n*, *m*, *mod* (2<=≀<=*n*<=≀<=500, 0<=≀<=*m*<=≀<=*n*, 2<=≀<=*mod*<=≀<=109). Then *m* lines follow, each of them contains *n* characters β€” the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given *m*<=Γ—<=*n* table contains at most two numbers one. Output Specification: Print the remainder after dividing the required value by number *mod*. Demo Input: ['3 1 1000\n011\n', '4 4 100500\n0110\n1010\n0101\n1001\n'] Demo Output: ['2\n', '1\n'] Note: For the first test the required matrices are: In the second test the required matrix is already fully given, so the answer is 1.
1,381
Title: Ostap and Grasshopper Time Limit: None seconds Memory Limit: None megabytes Problem Description: On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length *n* such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect. Ostap knows that grasshopper is able to jump to any empty cell that is exactly *k* cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if *k*<==<=1 the grasshopper can jump to a neighboring cell only, and if *k*<==<=2 the grasshopper can jump over a single cell. Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect. Input Specification: The first line of the input contains two integers *n* and *k* (2<=≀<=*n*<=≀<=100, 1<=≀<=*k*<=≀<=*n*<=-<=1)Β β€” the number of cells in the line and the length of one grasshopper's jump. The second line contains a string of length *n* consisting of characters '.', '#', 'G' and 'T'. Character '.' means that the corresponding cell is empty, character '#' means that the corresponding cell contains an obstacle and grasshopper can't jump there. Character 'G' means that the grasshopper starts at this position and, finally, 'T' means that the target insect is located at this cell. It's guaranteed that characters 'G' and 'T' appear in this line exactly once. Output Specification: If there exists a sequence of jumps (each jump of length *k*), such that the grasshopper can get from his initial position to the cell with the insect, print "YES" (without quotes) in the only line of the input. Otherwise, print "NO" (without quotes). Demo Input: ['5 2\n#G#T#\n', '6 1\nT....G\n', '7 3\nT..#..G\n', '6 2\n..GT..\n'] Demo Output: ['YES\n', 'YES\n', 'NO\n', 'NO\n'] Note: In the first sample, the grasshopper can make one jump to the right in order to get from cell 2 to cell 4. In the second sample, the grasshopper is only able to jump to neighboring cells but the way to the insect is freeΒ β€” he can get there by jumping left 5 times. In the third sample, the grasshopper can't make a single jump. In the fourth sample, the grasshopper can only jump to the cells with odd indices, thus he won't be able to reach the insect.
1,382
Title: Hamsters and Tigers Time Limit: 2 seconds Memory Limit: 256 megabytes Problem Description: Today there is going to be an unusual performance at the circus β€” hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him. Input Specification: The first line contains number *n* (2<=≀<=*n*<=≀<=1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of *n* symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one. Output Specification: Print the single number which is the minimal number of swaps that let the trainer to achieve his goal. Demo Input: ['3\nHTH\n', '9\nHTHTHTHHT\n'] Demo Output: ['0\n', '2\n'] Note: In the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then β€” the tiger in position 9 with the hamster in position 7.
1,383
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: The GCD table *G* of size *n*<=Γ—<=*n* for an array of positive integers *a* of length *n* is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers *x* and *y* is the greatest integer that is divisor of both *x* and *y*, it is denoted as . For example, for array *a*<==<={4,<=3,<=6,<=2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table *G*, restore array *a*. Input Specification: The first line contains number *n* (1<=≀<=*n*<=≀<=500) β€” the length of array *a*. The second line contains *n*2 space-separated numbers β€” the elements of the GCD table of *G* for array *a*. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array *a*. Output Specification: In the single line print *n* positive integers β€” the elements of array *a*. If there are multiple possible solutions, you are allowed to print any of them. Demo Input: ['4\n2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2\n', '1\n42\n', '2\n1 1 1 1\n'] Demo Output: ['4 3 6 2', '42 ', '1 1 '] Note: none
1,384
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon. A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence *a*1,<=*a*2,<=...,<=*a**n*. Little Tommy is among them. He would like to choose an interval [*l*,<=*r*] (1<=≀<=*l*<=≀<=*r*<=≀<=*n*), then reverse *a**l*,<=*a**l*<=+<=1,<=...,<=*a**r* so that the length of the longest non-decreasing subsequence of the new sequence is maximum. A non-decreasing subsequence is a sequence of indices *p*1,<=*p*2,<=...,<=*p**k*, such that *p*1<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*p**k* and *a**p*1<=≀<=*a**p*2<=≀<=...<=≀<=*a**p**k*. The length of the subsequence is *k*. Input Specification: The first line contains an integer *n* (1<=≀<=*n*<=≀<=2000), denoting the length of the original sequence. The second line contains *n* space-separated integers, describing the original sequence *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=2,<=*i*<==<=1,<=2,<=...,<=*n*). Output Specification: Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence. Demo Input: ['4\n1 2 1 2\n', '10\n1 1 2 2 2 1 1 2 2 1\n'] Demo Output: ['4\n', '9\n'] Note: In the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4. In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9.
1,385
Title: Weak Memory Time Limit: None seconds Memory Limit: None megabytes Problem Description: Zart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them. The park has *n* intersections numbered 1 through *n*. There are *m* bidirectional roads that connect some pairs of these intersections. At *k* intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct. When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most *q* intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most *q* that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most *q* intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it. PMP's initial location is intersection *s* and the buses are at intersection *t*. There will always be a volunteer at intersection *s*. Your job is to find out the minimum *q* which guarantees that PMP can find the buses. Input Specification: The first line contains three space-separated integers *n*,<=*m*,<=*k* (2<=≀<=*n*<=≀<=105,<=0<=≀<=*m*<=≀<=2Β·105,<=1<=≀<=*k*<=≀<=*n*) β€” the number of intersections, roads and volunteers, respectively. Next line contains *k* distinct space-separated integers between 1 and *n* inclusive β€” the numbers of cities where volunteers are located. Next *m* lines describe the roads. The *i*-th of these lines contains two space-separated integers *u**i*,<=*v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*,<=*u**i*<=β‰ <=*v**i*) β€” two intersections that *i*-th road connects. There will be at most one road between any two intersections. Last line of input contains two space-separated integers *s*,<=*t* (1<=≀<=*s*,<=*t*<=≀<=*n*,<=*s*<=β‰ <=*t*) β€” the initial location of PMP and the location of the buses. It might not always be possible to reach *t* from *s*. It is guaranteed that there is always a volunteer at intersection *s*. Output Specification: Print on the only line the answer to the problem β€” the minimum value of *q* which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead. Demo Input: ['6 6 3\n1 3 6\n1 2\n2 3\n4 2\n5 6\n4 5\n3 4\n1 6\n', '6 5 3\n1 5 6\n1 2\n2 3\n3 4\n4 5\n6 3\n1 5\n'] Demo Output: ['3\n', '3\n'] Note: The first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with *q* = 3: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3.
1,386
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: Pavel loves grid mazes. A grid maze is an *n*<=Γ—<=*m* rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly *k* empty cells into walls so that all the remaining cells still formed a connected area. Help him. Input Specification: The first line contains three integers *n*, *m*, *k* (1<=≀<=*n*,<=*m*<=≀<=500, 0<=≀<=*k*<=&lt;<=*s*), where *n* and *m* are the maze's height and width, correspondingly, *k* is the number of walls Pavel wants to add and letter *s* represents the number of empty cells in the original maze. Each of the next *n* lines contains *m* characters. They describe the original maze. If a character on a line equals ".", then the corresponding cell is empty and if the character equals "#", then the cell is a wall. Output Specification: Print *n* lines containing *m* characters each: the new maze that fits Pavel's requirements. Mark the empty cells that you transformed into walls as "X", the other cells must be left without changes (that is, "." and "#"). It is guaranteed that a solution exists. If there are multiple solutions you can output any of them. Demo Input: ['3 4 2\n#..#\n..#.\n#...\n', '5 4 5\n#...\n#.#.\n.#..\n...#\n.#.#\n'] Demo Output: ['#.X#\nX.#.\n#...\n', '#XXX\n#X#.\nX#..\n...#\n.#.#\n'] Note: none
1,387
Title: Ksusha and Array Time Limit: None seconds Memory Limit: None megabytes Problem Description: Ksusha is a beginner coder. Today she starts studying arrays. She has array *a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* positive integers. Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number! Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105), showing how many numbers the array has. The next line contains integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109) β€” the array elements. Output Specification: Print a single integer β€” the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1. If there are multiple answers, you are allowed to print any of them. Demo Input: ['3\n2 2 4\n', '5\n2 1 3 1 6\n', '3\n2 3 5\n'] Demo Output: ['2\n', '1\n', '-1\n'] Note: none
1,388
Title: Fox And Snake Time Limit: None seconds Memory Limit: None megabytes Problem Description: Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a *n* by *m* table. Denote *c*-th cell of *r*-th row as (*r*,<=*c*). The tail of the snake is located at (1,<=1), then it's body extends to (1,<=*m*), then goes down 2 rows to (3,<=*m*), then goes left to (3,<=1) and so on. Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#'). Consider sample tests in order to understand the snake pattern. Input Specification: The only line contains two integers: *n* and *m* (3<=≀<=*n*,<=*m*<=≀<=50). *n* is an odd number. Output Specification: Output *n* lines. Each line should contain a string consisting of *m* characters. Do not output spaces. Demo Input: ['3 3\n', '3 4\n', '5 3\n', '9 9\n'] Demo Output: ['###\n..#\n###\n', '####\n...#\n####\n', '###\n..#\n###\n#..\n###\n', '#########\n........#\n#########\n#........\n#########\n........#\n#########\n#........\n#########\n'] Note: none
1,389
Title: Replacing Digits Time Limit: None seconds Memory Limit: None megabytes Problem Description: You are given an integer *a* that consists of *n* digits. You are also given a sequence of digits *s* of length *m*. The digit in position *j* (1<=≀<=*j*<=≀<=*m*) of sequence *s* means that you can choose an arbitrary position *i* (1<=≀<=*i*<=≀<=*n*) in *a* and replace the digit in the chosen position *i* with *s**j*. Each element in the sequence *s* can participate in no more than one replacing operation. Your task is to perform such sequence of replacements, that the given number *a* gets maximum value. You are allowed to use not all elements from *s*. Input Specification: The first line contains positive integer *a*. Its length *n* is positive and doesn't exceed 105. The second line contains sequence of digits *s*. Its length *m* is positive and doesn't exceed 105. The digits in the sequence *s* are written consecutively without any separators. The given number *a* doesn't contain leading zeroes. Output Specification: Print the maximum value that can be obtained from *a* after a series of replacements. You are allowed to use not all elements from *s*. The printed number shouldn't contain any leading zeroes. Demo Input: ['1024\n010\n', '987\n1234567\n'] Demo Output: ['1124\n', '987\n'] Note: none
1,390
Title: Salazar Slytherin's Locket Time Limit: None seconds Memory Limit: None megabytes Problem Description: Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers *l* and *r* (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base *b*, all the digits from 0 to *b*<=-<=1 appear even number of times in its representation without any leading zeros. You have to answer *q* queries to unlock the office. Each query has three integers *b**i*, *l**i* and *r**i*, the base and the range for which you have to find the count of magic numbers. Input Specification: First line of input contains *q* (1<=≀<=*q*<=≀<=105)Β β€” number of queries. Each of the next *q* lines contain three space separated integers *b**i*, *l**i*, *r**i* (2<=≀<=*b**i*<=≀<=10, 1<=≀<=*l**i*<=≀<=*r**i*<=≀<=1018). Output Specification: You have to output *q* lines, each containing a single integer, the answer to the corresponding query. Demo Input: ['2\n2 4 9\n3 1 10\n', '2\n2 1 100\n5 1 100\n'] Demo Output: ['1\n2\n', '21\n4\n'] Note: In sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: - 4 = 100<sub class="lower-index">2</sub>, - 5 = 101<sub class="lower-index">2</sub>, - 6 = 110<sub class="lower-index">2</sub>, - 7 = 111<sub class="lower-index">2</sub>, - 8 = 1000<sub class="lower-index">2</sub>, - 9 = 1001<sub class="lower-index">2</sub>. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1.
1,391
Title: Kefa and First Steps Time Limit: None seconds Memory Limit: None megabytes Problem Description: Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≀<=*i*<=≀<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order. Help Kefa cope with this task! Input Specification: The first line contains integer *n* (1<=≀<=*n*<=≀<=105). The second line contains *n* integers *a*1,<=<=*a*2,<=<=...,<=<=*a**n* (1<=≀<=*a**i*<=≀<=109). Output Specification: Print a single integer β€” the length of the maximum non-decreasing subsegment of sequence *a*. Demo Input: ['6\n2 2 1 3 4 1\n', '3\n2 2 9\n'] Demo Output: ['3', '3'] Note: In the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one. In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
1,392
Title: Free Ice Cream Time Limit: None seconds Memory Limit: None megabytes Problem Description: After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue). If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress. Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids. Input Specification: The first line contains two space-separated integers *n* and *x* (1<=≀<=*n*<=≀<=1000, 0<=≀<=*x*<=≀<=109). Each of the next *n* lines contains a character '+' or '-', and an integer *d**i*, separated by a space (1<=≀<=*d**i*<=≀<=109). Record "+ *d**i*" in *i*-th line means that a carrier with *d**i* ice cream packs occupies *i*-th place from the start of the queue, and record "- *d**i*" means that a child who wants to take *d**i* packs stands in *i*-th place. Output Specification: Print two space-separated integersΒ β€” number of ice cream packs left after all operations, and number of kids that left the house in distress. Demo Input: ['5 7\n+ 5\n- 10\n- 20\n+ 40\n- 20\n', '5 17\n- 16\n- 2\n- 98\n+ 100\n- 98\n'] Demo Output: ['22 1\n', '3 2\n'] Note: Consider the first sample. 1. Initially Kay and Gerda have 7 packs of ice cream. 1. Carrier brings 5 more, so now they have 12 packs. 1. A kid asks for 10 packs and receives them. There are only 2 packs remaining. 1. Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed. 1. Carrier bring 40 packs, now Kay and Gerda have 42 packs. 1. Kid asks for 20 packs and receives them. There are 22 packs remaining.
1,393
Title: Bayan Bus Time Limit: None seconds Memory Limit: None megabytes Problem Description: The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows. The event coordinator has a list of *k* participants who should be picked up at the airport. When a participant gets on the bus, he will sit in the last row with an empty seat. If there is more than one empty seat in that row, he will take the leftmost one. In order to keep track of the people who are on the bus, the event coordinator needs a figure showing which seats are going to be taken by *k* participants. Your task is to draw the figure representing occupied seats. Input Specification: The only line of input contains integer *k*, (0<=≀<=*k*<=≀<=34), denoting the number of participants. Output Specification: Print the figure of a bus with *k* passengers as described in sample tests. Character '#' denotes an empty seat, while 'O' denotes a taken seat. 'D' is the bus driver and other characters in the output are for the purpose of beautifying the figure. Strictly follow the sample test cases output format. Print exactly six lines. Do not output extra space or other characters. Demo Input: ['9\n', '20\n'] Demo Output: ['+------------------------+\n|O.O.O.#.#.#.#.#.#.#.#.|D|)\n|O.O.O.#.#.#.#.#.#.#.#.|.|\n|O.......................|\n|O.O.#.#.#.#.#.#.#.#.#.|.|)\n+------------------------+\n', '+------------------------+\n|O.O.O.O.O.O.O.#.#.#.#.|D|)\n|O.O.O.O.O.O.#.#.#.#.#.|.|\n|O.......................|\n|O.O.O.O.O.O.#.#.#.#.#.|.|)\n+------------------------+\n'] Note: none
1,394
Title: Vasya and the Bus Time Limit: None seconds Memory Limit: None megabytes Problem Description: One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had *n* grown-ups and *m* kids..." The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could have paid for the ride. The bus fare equals one berland ruble in High Bertown. However, not everything is that easy β€” no more than one child can ride for free with each grown-up passenger. That means that a grown-up passenger who rides with his *k* (*k*<=&gt;<=0) children, pays overall *k* rubles: a ticket for himself and (*k*<=-<=1) tickets for his children. Also, a grown-up can ride without children, in this case he only pays one ruble. We know that in High Bertown children can't ride in a bus unaccompanied by grown-ups. Help Vasya count the minimum and the maximum sum in Berland rubles, that all passengers of this bus could have paid in total. Input Specification: The input file consists of a single line containing two space-separated numbers *n* and *m* (0<=≀<=*n*,<=*m*<=≀<=105) β€” the number of the grown-ups and the number of the children in the bus, correspondingly. Output Specification: If *n* grown-ups and *m* children could have ridden in the bus, then print on a single line two space-separated integers β€” the minimum and the maximum possible total bus fare, correspondingly. Otherwise, print "Impossible" (without the quotes). Demo Input: ['1 2\n', '0 5\n', '2 2\n'] Demo Output: ['2 2', 'Impossible', '2 3'] Note: In the first sample a grown-up rides with two children and pays two rubles. In the second sample there are only children in the bus, so the situation is impossible. In the third sample there are two cases: - Each of the two grown-ups rides with one children and pays one ruble for the tickets. In this case the passengers pay two rubles in total. - One of the grown-ups ride with two children's and pays two rubles, the another one rides alone and pays one ruble for himself. So, they pay three rubles in total.
1,395
Title: Cube Problem Time Limit: None seconds Memory Limit: None megabytes Problem Description: Yaroslav, Andrey and Roman love playing cubes. Sometimes they get together and play cubes for hours and hours! Today they got together again and they are playing cubes. Yaroslav took unit cubes and composed them into an *a*<=Γ—<=*a*<=Γ—<=*a* cube, Andrey made a *b*<=Γ—<=*b*<=Γ—<=*b* cube and Roman made a *c*<=Γ—<=*c*<=Γ—<=*c* cube. After that the game was finished and the guys left. But later, Vitaly entered the room. He saw the cubes and wanted to make a cube as well. But what size should the cube be? Of course it should be a large cube with the side of length *a*<=+<=*b*<=+<=*c*. Besides, Vitaly decided to decompose the cubes built by Yaroslav, Andrey and Roman and compose his own large cube out of them. However, it turned out that the unit cubes he got from destroying the three cubes just weren't enough to make a large cube. We know that Vitaly was short of exactly *n* cubes. Vitaly got upset, demolished everything and left. As he was leaving, he met Petya and told him that there had been three cubes in the room and that he needed another *n* unit cubes to make his own large cube. Petya entered the room and saw the messily scattered cubes. He wanted to make it neat and orderly again. But he only knows that there had been three cubes, made of small unit cubes and that Vitaly needed *n* more unit cubes to make a large one! Help Petya understand, how many ways of sizes *a*, *b*, *c* are there to restore Yaroslav's, Andrey's and Roman's cubes. Input Specification: The single line of the input contains integer *n* (1<=≀<=*n*<=≀<=1014). We know that all numbers *a*, *b*, *c* are positive integers. 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. Output Specification: In the single line print the required number of ways. If it turns out that there isn't a single way of suitable sizes of *a*, *b*, *c*, print 0. Demo Input: ['24\n', '648\n', '5\n', '93163582512000\n'] Demo Output: ['1\n', '7\n', '0\n', '39090\n'] Note: none
1,396
Title: none Time Limit: None seconds Memory Limit: None megabytes Problem Description: As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers *k* and *p*, where *p* is an odd prime number, the functional equation states that for some function . (This equation should hold for any integer *x* in the range 0 to *p*<=-<=1, inclusive.) It turns out that *f* can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions *f* that satisfy this equation. Since the answer may be very large, you should print your result modulo 109<=+<=7. Input Specification: The input consists of two space-separated integers *p* and *k* (3<=≀<=*p*<=≀<=1<=000<=000, 0<=≀<=*k*<=≀<=*p*<=-<=1) on a single line. It is guaranteed that *p* is an odd prime number. Output Specification: Print a single integer, the number of distinct functions *f* modulo 109<=+<=7. Demo Input: ['3 2\n', '5 4\n'] Demo Output: ['3\n', '25\n'] Note: In the first sample, *p* = 3 and *k* = 2. The following functions work: 1. *f*(0) = 0, *f*(1) = 1, *f*(2) = 2. 1. *f*(0) = 0, *f*(1) = 2, *f*(2) = 1. 1. *f*(0) = *f*(1) = *f*(2) = 0.
1,397
Title: News About Credit Time Limit: None seconds Memory Limit: None megabytes Problem Description: Polycarp studies at the university in the group which consists of *n* students (including himself). All they are registrated in the social net "TheContacnt!". Not all students are equally sociable. About each student you know the value *a**i* β€” the maximum number of messages which the *i*-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that: - the student *i* sends no more than *a**i* messages (for all *i* from 1 to *n*); - all students knew the news about the credit (initially only Polycarp knew it); - the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to *n*, and Polycarp always has the number 1. In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above. Input Specification: The first line contains the positive integer *n* (2<=≀<=*n*<=≀<=100) β€” the number of students. The second line contains the sequence *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=100), where *a**i* equals to the maximum number of messages which can the *i*-th student agree to send. Consider that Polycarp always has the number 1. Output Specification: Print -1 to the first line if it is impossible to inform all students about credit. Otherwise, in the first line print the integer *k* β€” the number of messages which will be sent. In each of the next *k* lines print two distinct integers *f* and *t*, meaning that the student number *f* sent the message with news to the student number *t*. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can receive repeated messages with news of the credit. If there are several answers, it is acceptable to print any of them. Demo Input: ['4\n1 2 1 0\n', '6\n2 0 1 3 2 0\n', '3\n0 2 2\n'] Demo Output: ['3\n1 2\n2 4\n2 3\n', '6\n1 3\n3 4\n1 2\n4 5\n5 6\n4 6\n', '-1\n'] Note: In the first test Polycarp (the student number 1) can send the message to the student number 2, who after that can send the message to students number 3 and 4. Thus, all students knew about the credit.
1,398
Title: Ilya and Sticks Time Limit: None seconds Memory Limit: None megabytes Problem Description: In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of *n* sticks and an instrument. Each stick is characterized by its length *l**i*. Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed. Sticks with lengths *a*1, *a*2, *a*3 and *a*4 can make a rectangle if the following properties are observed: - *a*1<=≀<=*a*2<=≀<=*a*3<=≀<=*a*4 - *a*1<==<=*a*2 - *a*3<==<=*a*4 A rectangle can be made of sticks with lengths of, for example, 3Β 3Β 3Β 3 or 2Β 2Β 4Β 4. A rectangle cannot be made of, for example, sticks 5Β 5Β 5Β 7. Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length 5 can either stay at this length or be transformed into a stick of length 4. You have to answer the question β€” what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks? Input Specification: The first line of the input contains a positive integer *n* (1<=≀<=*n*<=≀<=105)Β β€”Β the number of the available sticks. The second line of the input contains *n* positive integers *l**i* (2<=≀<=*l**i*<=≀<=106)Β β€”Β the lengths of the sticks. Output Specification: The first line of the output must contain a single non-negative integerΒ β€”Β the maximum total area of the rectangles that Ilya can make from the available sticks. Demo Input: ['4\n2 4 4 2\n', '4\n2 2 3 5\n', '4\n100003 100004 100005 100006\n'] Demo Output: ['8\n', '0\n', '10000800015\n'] Note: none
1,399