problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
βŒ€
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
B. Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou 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.InputThe only input line contains a single integer N (1 ≀ N ≀ 100).OutputOutput a single integer - the minimal number of layers required to draw the segments for the given N.ExamplesInput2Output2Input3Output4Input4Output6NoteAs an example, here are the segments and their optimal arrangement into layers for N = 4.
Input2
Output2
2 seconds
256 megabytes
['constructive algorithms', 'math', '*1300']
A. Generate Logintime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.You are given the first and the last name of a user. Return the alphabetically earliest login they can get (regardless of other potential Polygon users).As a reminder, a prefix of a string s is its substring which occurs at the beginning of s: "a", "ab", "abc" etc. are prefixes of string "{abcdef}" but "b" and 'bc" are not. A string a is alphabetically earlier than a string b, if a is a prefix of b, or a and b coincide up to some position, and then a has a letter that is alphabetically earlier than the corresponding letter in b: "a" and "ab" are alphabetically earlier than "ac" but "b" and "ba" are alphabetically later than "ac".InputThe input consists of a single line containing two space-separated strings: the first and the last names. Each character of each string is a lowercase English letter. The length of each string is between 1 and 10, inclusive. OutputOutput a single stringΒ β€” alphabetically earliest possible login formed from these names. The output should be given in lowercase as well.ExamplesInputharry potterOutputhapInputtom riddleOutputtomr
Inputharry potter
Outputhap
2 seconds
256 megabytes
['brute force', 'greedy', 'sortings', '*1000']
H. New Year and Boolean Bridgestime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour friend has a hidden directed graph with n nodes.Let f(u, v) be true if there is a directed path from node u to node v, and false otherwise. For each pair of distinct nodes, u, v, you know at least one of the three statements is true: Here AND, OR and XOR mean AND, OR and exclusive OR operations, respectively.You are given an n by n matrix saying which one of the three statements holds for each pair of vertices. The entry in the u-th row and v-th column has a single character. If the first statement holds, this is represented by the character 'A'. If the second holds, this is represented by the character 'O'. If the third holds, this is represented by the character 'X'. The diagonal of this matrix will only contain the character '-'. Note that it is possible that a pair of nodes may satisfy multiple statements, in which case, the character given will represent one of the true statements for that pair. This matrix is also guaranteed to be symmetric.You would like to know if there is a directed graph that is consistent with this matrix. If it is impossible, print the integer -1. Otherwise, print the minimum number of edges that could be consistent with this information.InputThe first line will contain an integer n (1 ≀ n ≀ 47), the number of nodes.The next n lines will contain n characters each: the matrix of what you know about the graph connectivity in the format described in the statement.OutputPrint the minimum number of edges that is consistent with the given information, or -1 if it is impossible.ExamplesInput4-AAAA-AAAA-AAAA-Output4Input3-XXX-XXX-Output2NoteSample 1: The hidden graph is a strongly connected graph. We can put all four nodes in a cycle.Sample 2: One valid graph is 3 → 1 → 2. For each distinct pair, exactly one of f(u, v), f(v, u) holds.
Input4-AAAA-AAAA-AAAA-
Output4
5 seconds
512 megabytes
['*3100']
G. New Year and Original Ordertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet S(n) denote the number that represents the digits of n in sorted order. For example, S(1) = 1, S(5) = 5, S(50394) = 3459, S(353535) = 333555.Given a number X, compute modulo 109 + 7.InputThe first line of input will contain the integer X (1 ≀ X ≀ 10700).OutputPrint a single integer, the answer to the question.ExamplesInput21Output195Input345342Output390548434NoteThe first few values of S are 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 12. The sum of these values is 195.
Input21
Output195
2 seconds
256 megabytes
['dp', 'math', '*2800']
F. New Year and Rainbow Roadstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRoy and Biv have a set of n points on the infinite number line.Each point has one of 3 colors: red, green, or blue.Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).Help them compute the minimum cost way to choose edges to satisfy the above constraints.InputThe first line will contain an integer n (1 ≀ n ≀ 300 000), the number of points.The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≀ pi ≀ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.OutputPrint a single integer, the minimum cost way to solve the problem.ExamplesInput41 G5 R10 B15 GOutput23Input41 G2 R3 B10 GOutput12NoteIn the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively.
Input41 G5 R10 B15 G
Output23
2 seconds
256 megabytes
['graphs', 'greedy', 'implementation', '*2400']
E. New Year and Entity Enumerationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer m.Let M = 2m - 1.You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.A set of integers S is called "good" if the following hold. If , then . If , then All elements of S are less than or equal to M. Here, and refer to the bitwise XOR and bitwise AND operators, respectively.Count the number of good sets S, modulo 109 + 7.InputThe first line will contain two integers m and n (1 ≀ m ≀ 1 000, 1 ≀ n ≀ min(2m, 50)).The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.OutputPrint a single integer, the number of good sets modulo 109 + 7. ExamplesInput5 3110100010111000Output4Input30 2010101010101010010101010101010110110110110110011011011011011Output860616440NoteAn example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Input5 3110100010111000
Output4
2 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'math', '*2500']
D. New Year and Arbitrary Arrangementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers k, pa and pb.You will construct a sequence with the following algorithm: Initially, start with the empty sequence. Each second, you do the following. With probability pa / (pa + pb), add 'a' to the end of the sequence. Otherwise (with probability pb / (pa + pb)), add 'b' to the end of the sequence.You stop once there are at least k subsequences that form 'ab'. Determine the expected number of times 'ab' is a subsequence in the resulting sequence. It can be shown that this can be represented by P / Q, where P and Q are coprime integers, and . Print the value of .InputThe first line will contain three integers integer k, pa, pb (1 ≀ k ≀ 1 000, 1 ≀ pa, pb ≀ 1 000 000).OutputPrint a single integer, the answer to the problem.ExamplesInput1 1 1Output2Input3 1 4Output370000006NoteThe first sample, we will keep appending to our sequence until we get the subsequence 'ab' at least once. For instance, we get the sequence 'ab' with probability 1/4, 'bbab' with probability 1/16, and 'aab' with probability 1/8. Note, it's impossible for us to end with a sequence like 'aabab', since we would have stopped our algorithm once we had the prefix 'aab'. The expected amount of times that 'ab' will occur across all valid sequences is 2. For the second sample, the answer is equal to .
Input1 1 1
Output2
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*2200']
C. New Year and Curlingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCarol is currently curling.She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100.She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.InputThe first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively.The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000)Β β€” the x-coordinates of the disks.OutputPrint a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6.Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if for all coordinates.ExampleInput6 25 5 6 8 3 12Output2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613NoteThe final positions of the disks will look as follows: In particular, note the position of the last disk.
Input6 25 5 6 8 3 12
Output2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613
2 seconds
256 megabytes
['brute force', 'geometry', 'implementation', 'math', '*1500']
B. New Year and Buggy Bottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob programmed a robot to navigate through a 2d maze.The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it.The robot can only move up, left, right, or down.When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits.The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions.Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.InputThe first line of input will contain two integers n and m (2 ≀ n, m ≀ 50), denoting the dimensions of the maze.The next n lines will contain exactly m characters each, denoting the maze.Each character of the maze will be '.', '#', 'S', or 'E'.There will be exactly one 'S' and exactly one 'E' in the maze.The last line will contain a single string s (1 ≀ |s| ≀ 100)Β β€” the instructions given to the robot. Each character of s is a digit from 0 to 3.OutputPrint a single integer, the number of mappings of digits to directions that will lead the robot to the exit.ExamplesInput5 6.....#S....#.#.....#.......E..333300012Output1Input6 6..............SE....................01232123212302123021Output14Input5 3....S.###.E....3Output0NoteFor the first sample, the only valid mapping is , where D is down, L is left, U is up, R is right.
Input5 6.....#S....#.#.....#.......E..333300012
Output1
1 second
256 megabytes
['brute force', 'implementation', '*1200']
A. New Year and Counting Cardstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend has n cards.You know that each card has a lowercase English letter on one side and a digit on the other.Currently, your friend has laid out the cards on a table so only one side of each card is visible.You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.InputThe first and only line of input will contain a string s (1 ≀ |s| ≀ 50), denoting the sides of the cards that you can see on the table currently. Each character of s is either a lowercase English letter or a digit.OutputPrint a single integer, the minimum number of cards you must turn over to verify your claim.ExamplesInputeeOutput2InputzOutput0Input0ay1Output2NoteIn the first sample, we must turn over both cards. Note that even though both cards have the same letter, they could possibly have different numbers on the other side.In the second sample, we don't need to turn over any cards. The statement is vacuously true, since you know your friend has no cards with a vowel on them.In the third sample, we need to flip the second and fourth cards.
Inputee
Output2
1 second
256 megabytes
['brute force', 'implementation', '*800']
B. Tic-Tac-Toetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo bears are playing tic-tac-toe via mail. It's boring for them to play usual tic-tac-toe game, so they are a playing modified version of this game. Here are its rules.The game is played on the following field. Players are making moves by turns. At first move a player can put his chip in any cell of any small field. For following moves, there are some restrictions: if during last move the opposite player put his chip to cell with coordinates (xl, yl) in some small field, the next move should be done in one of the cells of the small field with coordinates (xl, yl). For example, if in the first move a player puts his chip to lower left cell of central field, then the second player on his next move should put his chip into some cell of lower left field (pay attention to the first test case). If there are no free cells in the required field, the player can put his chip to any empty cell on any field.You are given current state of the game and coordinates of cell in which the last move was done. You should find all cells in which the current player can put his chip.A hare works as a postman in the forest, he likes to foul bears. Sometimes he changes the game field a bit, so the current state of the game could be unreachable. However, after his changes the cell where the last move was done is not empty. You don't need to find if the state is unreachable or not, just output possible next moves according to the rules.InputFirst 11 lines contains descriptions of table with 9 rows and 9 columns which are divided into 9 small fields by spaces and empty lines. Each small field is described by 9 characters without spaces and empty lines. character "x" (ASCII-code 120) means that the cell is occupied with chip of the first player, character "o" (ASCII-code 111) denotes a field occupied with chip of the second player, character "." (ASCII-code 46) describes empty cell.The line after the table contains two integers x and y (1 ≀ x, y ≀ 9). They describe coordinates of the cell in table where the last move was done. Rows in the table are numbered from up to down and columns are numbered from left to right.It's guaranteed that cell where the last move was done is filled with "x" or "o". Also, it's guaranteed that there is at least one empty cell. It's not guaranteed that current state of game is reachable.OutputOutput the field in same format with characters "!" (ASCII-code 33) on positions where the current player can put his chip. All other cells should not be modified.ExamplesInput... ... ...... ... ...... ... ...... ... ...... ... ...... x.. ...... ... ...... ... ...... ... ...6 4Output... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... x.. ... !!! ... ... !!! ... ... !!! ... ... Inputxoo x.. x..ooo ... ...ooo ... ...x.. x.. x..... ... ...... ... ...x.. x.. x..... ... ...... ... ...7 4Outputxoo x!! x!! ooo !!! !!! ooo !!! !!! x!! x!! x!! !!! !!! !!! !!! !!! !!! x!! x!! x!! !!! !!! !!! !!! !!! !!! Inputo.. ... ...... ... ...... ... ...... xxx ...... xox ...... ooo ...... ... ...... ... ...... ... ...5 5Outputo!! !!! !!! !!! !!! !!! !!! !!! !!! !!! xxx !!! !!! xox !!! !!! ooo !!! !!! !!! !!! !!! !!! !!! !!! !!! !!! NoteIn the first test case the first player made a move to lower left cell of central field, so the second player can put a chip only to cells of lower left field.In the second test case the last move was done to upper left cell of lower central field, however all cells in upper left field are occupied, so the second player can put his chip to any empty cell.In the third test case the last move was done to central cell of central field, so current player can put his chip to any cell of central field, which is already occupied, so he can move anywhere. Pay attention that this state of the game is unreachable.
Input... ... ...... ... ...... ... ...... ... ...... ... ...... x.. ...... ... ...... ... ...... ... ...6 4
Output... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... x.. ... !!! ... ... !!! ... ... !!! ... ...
2 seconds
256 megabytes
['implementation', '*1400']
A. Masha and Bearstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≀ b, he or she likes it if and only if he can climb into this car and 2a β‰₯ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.InputYou are given four integers V1, V2, V3, Vm(1 ≀ Vi ≀ 100)Β β€” sizes of father bear, mother bear, son bear and Masha, respectively. It's guaranteed that V1 > V2 > V3.OutputOutput three integersΒ β€” sizes of father bear's car, mother bear's car and son bear's car, respectively.If there are multiple possible solutions, print any.If there is no solution, print "-1" (without quotes).ExamplesInput50 30 10 10Output503010Input100 50 10 21Output-1NoteIn first test case all conditions for cars' sizes are satisfied.In second test case there is no answer, because Masha should be able to climb into smallest car (so size of smallest car in not less than 21), but son bear should like it, so maximum possible size of it is 20.
Input50 30 10 10
Output503010
2 seconds
256 megabytes
['brute force', 'implementation', '*1300']
E. Reversestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing minimum possible number of its substrings and find out which substrings you should reverse.You are given a string sΒ β€” original state of your string and string tΒ β€” state of the string after hurricane. You should select k non-intersecting substrings of t in such a way that after reverse of these substrings string will be equal s and k is minimum possible.InputFirst line of input contains string s and second line contains string t. Both strings have same length and consist of lowercase English letters. 1 ≀ |s| = |t| ≀ 5Β·105OutputIn first line print kΒ β€” minimum number of substrings you should reverse. Next output k lines. Each line should contain two integers li, ri meaning that you should reverse substring from symbol number li to symbol ri (strings are 1-indexed). These substrings shouldn't intersect. If there are multiple answers print any. If it's impossible to restore string output -1.ExampleInputabcxxxdefcbaxxxfedOutput27 91 3
Inputabcxxxdefcbaxxxfed
Output27 91 3
2 seconds
256 megabytes
['dp', 'string suffix structures', 'strings', '*3300']
D. Power Towertime limit per test4.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPriests of the Quetzalcoatl cult want to build a tower to represent a power of their god. Tower is usually made of power-charged rocks. It is built with the help of rare magic by levitating the current top of tower and adding rocks at its bottom. If top, which is built from k - 1 rocks, possesses power p and we want to add the rock charged with power wk then value of power of a new tower will be {wk}p. Rocks are added from the last to the first. That is for sequence w1, ..., wm value of power will beAfter tower is built, its power may be extremely large. But still priests want to get some information about it, namely they want to know a number called cumulative power which is the true value of power taken modulo m. Priests have n rocks numbered from 1 to n. They ask you to calculate which value of cumulative power will the tower possess if they will build it from rocks numbered l, l + 1, ..., r. InputFirst line of input contains two integers n (1 ≀ n ≀ 105) and m (1 ≀ m ≀ 109).Second line of input contains n integers wk (1 ≀ wk ≀ 109) which is the power of rocks that priests have.Third line of input contains single integer q (1 ≀ q ≀ 105) which is amount of queries from priests to you.kth of next q lines contains two integers lk and rk (1 ≀ lk ≀ rk ≀ n). OutputOutput q integers. k-th of them must be the amount of cumulative power the tower will have if is built from rocks lk, lk + 1, ..., rk.ExampleInput6 10000000001 2 2 3 3 381 11 62 22 32 44 44 54 6Output1124256327597484987Note327 = 7625597484987
Input6 10000000001 2 2 3 3 381 11 62 22 32 44 44 54 6
Output1124256327597484987
4.5 seconds
256 megabytes
['chinese remainder theorem', 'math', 'number theory', '*2700']
C. Partytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.At each step he selects one of his guests A, who pairwise introduces all of his friends to each other. After this action any two friends of A become friends. This process is run until all pairs of guests are friends.Arseny doesn't want to spend much time doing it, so he wants to finish this process using the minimum number of steps. Help Arseny to do it.InputThe first line contains two integers n and m (1 ≀ n ≀ 22; )Β β€” the number of guests at the party (including Arseny) and the number of pairs of people which are friends.Each of the next m lines contains two integers u and v (1 ≀ u, v ≀ n; u ≠ v), which means that people with numbers u and v are friends initially. It's guaranteed that each pair of friends is described not more than once and the graph of friendship is connected.OutputIn the first line print the minimum number of steps required to make all pairs of guests friends.In the second line print the ids of guests, who are selected at each step.If there are multiple solutions, you can output any of them.ExamplesInput5 61 21 32 32 53 44 5Output22 3 Input4 41 21 31 43 4Output11 NoteIn the first test case there is no guest who is friend of all other guests, so at least two steps are required to perform the task. After second guest pairwise introduces all his friends, only pairs of guests (4, 1) and (4, 2) are not friends. Guest 3 or 5 can introduce them.In the second test case guest number 1 is a friend of all guests, so he can pairwise introduce all guests in one step.
Input5 61 21 32 32 53 44 5
Output22 3
1 second
256 megabytes
['bitmasks', 'brute force', 'dp', 'graphs', '*2400']
B. Seating of Studentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudents went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."The class can be represented as a matrix with n rows and m columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.Let's enumerate students from 1 to nΒ·m in order of rows. So a student who initially sits in the cell in row i and column j has a number (i - 1)Β·m + j. You have to find a matrix with n rows and m columns in which all numbers from 1 to nΒ·m appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix.InputThe only line contains two integers n and m (1 ≀ n, m ≀ 105; nΒ·m ≀ 105)Β β€” the number of rows and the number of columns in the required matrix.OutputIf there is no such matrix, output "NO" (without quotes). Otherwise in the first line output "YES" (without quotes), and in the next n lines output m integers which form the required matrix.ExamplesInput2 4OutputYES5 4 7 2 3 6 1 8 Input2 1OutputNONoteIn the first test case the matrix initially looks like this:1 2 3 45 6 7 8It's easy to see that there are no two students that are adjacent in both matrices.In the second test case there are only two possible seatings and in both of them students with numbers 1 and 2 are neighbors.
Input2 4
OutputYES5 4 7 2 3 6 1 8
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'math', '*2200']
A. Shockerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for each incorrect guess he receives an electric shock too. The show ends when Valentin guesses the selected letter correctly.Valentin can't keep in mind everything, so he could guess the selected letter much later than it can be uniquely determined and get excessive electric shocks. Excessive electric shocks are those which Valentin got after the moment the selected letter can be uniquely determined. You should find out the number of excessive electric shocks.InputThe first line contains a single integer n (1 ≀ n ≀ 105)Β β€” the number of actions Valentin did.The next n lines contain descriptions of his actions, each line contains description of one action. Each action can be of one of three types: Valentin pronounced some word and didn't get an electric shock. This action is described by the string ". w" (without quotes), in which "." is a dot (ASCII-code 46), and w is the word that Valentin said. Valentin pronounced some word and got an electric shock. This action is described by the string "! w" (without quotes), in which "!" is an exclamation mark (ASCII-code 33), and w is the word that Valentin said. Valentin made a guess about the selected letter. This action is described by the string "? s" (without quotes), in which "?" is a question mark (ASCII-code 63), and s is the guessΒ β€” a lowercase English letter. All words consist only of lowercase English letters. The total length of all words does not exceed 105.It is guaranteed that last action is a guess about the selected letter. Also, it is guaranteed that Valentin didn't make correct guesses about the selected letter before the last action. Moreover, it's guaranteed that if Valentin got an electric shock after pronouncing some word, then it contains the selected letter; and also if Valentin didn't get an electric shock after pronouncing some word, then it does not contain the selected letter.OutputOutput a single integerΒ β€” the number of electric shocks that Valentin could have avoided if he had told the selected letter just after it became uniquely determined.ExamplesInput5! abc. ad. b! cd? cOutput1Input8! hello! codeforces? c. o? d? h. l? eOutput2Input7! ababahalamaha? a? b? a? b? a? hOutput0NoteIn the first test case after the first action it becomes clear that the selected letter is one of the following: a, b, c. After the second action we can note that the selected letter is not a. Valentin tells word "b" and doesn't get a shock. After that it is clear that the selected letter is c, but Valentin pronounces the word cd and gets an excessive electric shock. In the second test case after the first two electric shocks we understand that the selected letter is e or o. Valentin tries some words consisting of these letters and after the second word it's clear that the selected letter is e, but Valentin makes 3 more actions before he makes a correct hypothesis.In the third example the selected letter can be uniquely determined only when Valentin guesses it, so he didn't get excessive electric shocks.
Input5! abc. ad. b! cd? c
Output1
2 seconds
256 megabytes
['implementation', 'strings', '*1600']
G. Yet Another Maxflow Problemtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you will have to deal with a very special network.The network consists of two parts: part A and part B. Each part consists of n vertices; i-th vertex of part A is denoted as Ai, and i-th vertex of part B is denoted as Bi.For each index i (1 ≀ i < n) there is a directed edge from vertex Ai to vertex Ai + 1, and from Bi to Bi + 1, respectively. Capacities of these edges are given in the input. Also there might be several directed edges going from part A to part B (but never from B to A).You have to calculate the maximum flow value from A1 to Bn in this network. Capacities of edges connecting Ai to Ai + 1 might sometimes change, and you also have to maintain the maximum flow value after these changes. Apart from that, the network is fixed (there are no changes in part B, no changes of edges going from A to B, and no edge insertions or deletions).Take a look at the example and the notes to understand the structure of the network better.InputThe first line contains three integer numbers n, m and q (2 ≀ n, m ≀ 2Β·105, 0 ≀ q ≀ 2Β·105) β€” the number of vertices in each part, the number of edges going from A to B and the number of changes, respectively.Then n - 1 lines follow, i-th line contains two integers xi and yi denoting that the edge from Ai to Ai + 1 has capacity xi and the edge from Bi to Bi + 1 has capacity yi (1 ≀ xi, yi ≀ 109).Then m lines follow, describing the edges from A to B. Each line contains three integers x, y and z denoting an edge from Ax to By with capacity z (1 ≀ x, y ≀ n, 1 ≀ z ≀ 109). There might be multiple edges from Ax to By.And then q lines follow, describing a sequence of changes to the network. i-th line contains two integers vi and wi, denoting that the capacity of the edge from Avi to Avi + 1 is set to wi (1 ≀ vi < n, 1 ≀ wi ≀ 109).OutputFirstly, print the maximum flow value in the original network. Then print q integers, i-th of them must be equal to the maximum flow value after i-th change.ExampleInput4 3 21 23 45 62 2 71 4 84 3 91 1002 100Output91414NoteThis is the original network in the example:
Input4 3 21 23 45 62 2 71 4 84 3 91 1002 100
Output91414
4 seconds
256 megabytes
['data structures', 'flows', 'graphs', '*2700']
F. Clear The Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix f with 4 rows and n columns. Each element of the matrix is either an asterisk (*) or a dot (.).You may perform the following operation arbitrary number of times: choose a square submatrix of f with size k × k (where 1 ≀ k ≀ 4) and replace each element of the chosen submatrix with a dot. Choosing a submatrix of size k × k costs ak coins.What is the minimum number of coins you have to pay to replace all asterisks with dots?InputThe first line contains one integer n (4 ≀ n ≀ 1000) β€” the number of columns in f.The second line contains 4 integers a1, a2, a3, a4 (1 ≀ ai ≀ 1000) β€” the cost to replace the square submatrix of size 1 × 1, 2 × 2, 3 × 3 or 4 × 4, respectively.Then four lines follow, each containing n characters and denoting a row of matrix f. Each character is either a dot or an asterisk.OutputPrint one integer β€” the minimum number of coins to replace all asterisks with dots.ExamplesInput41 10 8 20***.***.***....*Output9Input72 1 8 2.***....***..*.***.......*..Output3Input410 10 1 10***.*..**..*.***Output2NoteIn the first example you can spend 8 coins to replace the submatrix 3 × 3 in the top-left corner, and 1 coin to replace the 1 × 1 submatrix in the bottom-right corner.In the second example the best option is to replace the 4 × 4 submatrix containing columns 2 – 5, and the 2 × 2 submatrix consisting of rows 2 – 3 and columns 6 – 7.In the third example you can select submatrix 3 × 3 in the top-left corner and then submatrix 3 × 3 consisting of rows 2 – 4 and columns 2 – 4.
Input41 10 8 20***.***.***....*
Output9
1 second
256 megabytes
['bitmasks', 'dp', '*2200']
E. Swapping Characterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s1, s2, ..., sk. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).You are given k strings s1, s2, ..., sk, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, kΒ·n ≀ 5000).InputThe first line contains two integers k and n (1 ≀ k ≀ 2500, 2 ≀ n ≀ 5000, kΒ Β·Β n ≀ 5000) β€” the number of strings we obtained, and the length of each of these strings.Next k lines contain the strings s1, s2, ..., sk, each consisting of exactly n lowercase Latin letters.OutputPrint any suitable string s, or -1 if such string doesn't exist.ExamplesInput3 4abaccaabacbaOutputacabInput3 4kbbukbububkbOutputkbubInput5 4abcddcbaacbddbcazzzzOutput-1NoteIn the first example s1 is obtained by swapping the second and the fourth character in acab, s2 is obtained by swapping the first and the second character, and to get s3, we swap the third and the fourth character.In the second example s1 is obtained by swapping the third and the fourth character in kbub, s2 β€” by swapping the second and the fourth, and s3 β€” by swapping the first and the third.In the third example it's impossible to obtain given strings by aforementioned operations.
Input3 4abaccaabacba
Outputacab
1 second
256 megabytes
['brute force', 'hashing', 'implementation', 'strings', '*2200']
D. Almost Differencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote a function You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≀ i ≀ j ≀ n.InputThe first line contains one integer n (1 ≀ n ≀ 200000) β€” the number of elements in a.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” elements of the array. OutputPrint one integer β€” the sum of d(ai, aj) over all pairs (i, j) such that 1 ≀ i ≀ j ≀ n.ExamplesInput51 2 3 1 3Output4Input46 6 5 5Output0Input46 6 4 4Output-8NoteIn the first example: d(a1, a2) = 0; d(a1, a3) = 2; d(a1, a4) = 0; d(a1, a5) = 2; d(a2, a3) = 0; d(a2, a4) = 0; d(a2, a5) = 0; d(a3, a4) =  - 2; d(a3, a5) = 0; d(a4, a5) = 2.
Input51 2 3 1 3
Output4
2 seconds
256 megabytes
['data structures', 'math', '*2200']
C. Boxes Packingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka has got n empty boxes. For every i (1 ≀ i ≀ n), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met: i-th box is not put into another box; j-th box doesn't contain any other boxes; box i is smaller than box j (ai < aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes!InputThe first line contains one integer n (1 ≀ n ≀ 5000) β€” the number of boxes Mishka has got.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109), where ai is the side length of i-th box.OutputPrint the minimum possible number of visible boxes.ExamplesInput31 2 3Output1Input44 2 4 3Output2NoteIn the first example it is possible to put box 1 into box 2, and 2 into 3.In the second example Mishka can put box 2 into box 3, and box 4 into box 1.
Input31 2 3
Output1
1 second
256 megabytes
['greedy', '*1200']
B. The Modcrabtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.InputThe first line contains three integers h1, a1, c1 (1 ≀ h1, a1 ≀ 100, 2 ≀ c1 ≀ 100) β€” Vova's health, Vova's attack power and the healing power of a potion.The second line contains two integers h2, a2 (1 ≀ h2 ≀ 100, 1 ≀ a2 < c1) β€” the Modcrab's health and his attack power.OutputIn the first line print one integer n denoting the minimum number of phases required to win the battle.Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab.The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.If there are multiple optimal solutions, print any of them.ExamplesInput10 6 10017 5Output4STRIKEHEALSTRIKESTRIKEInput11 6 10012 5Output2STRIKESTRIKENoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.
Input10 6 10017 5
Output4STRIKEHEALSTRIKESTRIKE
1 second
256 megabytes
['greedy', 'implementation', '*1200']
A. Hungry Student Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one β€” 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly this amount of chicken.Formally, Ivan wants to know if he can choose two non-negative integers a and b in such a way that a small portions and b large ones contain exactly x chunks.Help Ivan to answer this question for several values of x!InputThe first line contains one integer n (1 ≀ n ≀ 100) β€” the number of testcases.The i-th of the following n lines contains one integer xi (1 ≀ xi ≀ 100) β€” the number of chicken chunks Ivan wants to eat.OutputPrint n lines, in i-th line output YES if Ivan can buy exactly xi chunks. Otherwise, print NO.ExampleInput265OutputYESNONoteIn the first example Ivan can buy two small portions.In the second example Ivan cannot buy exactly 5 chunks, since one small portion is not enough, but two small portions or one large is too much.
Input265
OutputYESNO
1 second
256 megabytes
['greedy', 'implementation', '*900']
B. Coloring a Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu = x.It is guaranteed that you have to color each vertex in a color different from 0.You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).InputThe first line contains a single integer n (2 ≀ n ≀ 104)Β β€” the number of vertices in the tree.The second line contains n - 1 integers p2, p3, ..., pn (1 ≀ pi < i), where pi means that there is an edge between vertices i and pi.The third line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ n), where ci is the color you should color the i-th vertex into.It is guaranteed that the given graph is a tree. OutputPrint a single integerΒ β€” the minimum number of steps you have to perform to color the tree into given colors.ExamplesInput61 2 2 1 52 1 1 1 1 1Output3Input71 1 2 3 1 43 3 1 1 1 2 3Output5NoteThe tree from the first sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 2 (numbers are colors):On seond step we color all vertices in the subtree of vertex 5 into color 1:On third step we color all vertices in the subtree of vertex 2 into color 1:The tree from the second sample is shown on the picture (numbers are vetices' indices):On first step we color all vertices in the subtree of vertex 1 into color 3 (numbers are colors):On second step we color all vertices in the subtree of vertex 3 into color 1:On third step we color all vertices in the subtree of vertex 6 into color 2:On fourth step we color all vertices in the subtree of vertex 4 into color 1:On fith step we color all vertices in the subtree of vertex 7 into color 3:
Input61 2 2 1 52 1 1 1 1 1
Output3
1 second
256 megabytes
['dfs and similar', 'dsu', 'greedy', '*1200']
A. Visiting a Friendtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPig is visiting a friend.Pig's house is located at point 0, and his friend's house is located at point m on an axis.Pig can use teleports to move along the axis.To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x; y], including the bounds. Determine if Pig can visit the friend using teleports only, or he should use his car.InputThe first line contains two integers n and m (1 ≀ n ≀ 100, 1 ≀ m ≀ 100)Β β€” the number of teleports and the location of the friend's house.The next n lines contain information about teleports.The i-th of these lines contains two integers ai and bi (0 ≀ ai ≀ bi ≀ m), where ai is the location of the i-th teleport, and bi is its limit.It is guaranteed that ai β‰₯ ai - 1 for every i (2 ≀ i ≀ n).OutputPrint "YES" if there is a path from Pig's house to his friend's house that uses only teleports, and "NO" otherwise.You can print each letter in arbitrary case (upper or lower).ExamplesInput3 50 22 43 5OutputYESInput3 70 42 56 7OutputNONoteThe first example is shown on the picture below: Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives.The second example is shown on the picture below: You can see that there is no path from Pig's house to his friend's house that uses only teleports.
Input3 50 22 43 5
OutputYES
1 second
256 megabytes
['greedy', 'implementation', '*1100']
E. Cyclic Ciphertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Senor Vorpal Kickass'o invented an innovative method to encrypt integer sequences of length n. To encrypt a sequence, one has to choose a secret sequence , that acts as a key.Vorpal is very selective, so the key should be such a sequence bi, that its cyclic shifts are linearly independent, that is, there is no non-zero set of coefficients x0, x1, ..., xn - 1, such that for all k at the same time.After that for a sequence you should build the following cipher:In other words, you are to compute the quadratic deviation between each cyclic shift of bi and the sequence ai. The resulting sequence is the Kickass's cipher. The cipher is in development right now and Vorpal wants to decipher a sequence after it has been encrypted. You are to solve this problem for him. You are given sequences ci and bi. You are to find all suitable sequences ai.InputThe first line contains a single integer n ().The second line contains n integers b0, b1, ..., bn - 1 ().The third line contains n integers c0, c1, ..., cn - 1 ().It is guaranteed that all cyclic shifts of sequence bi are linearly independent.OutputIn the first line print a single integer kΒ β€” the number of sequences ai, such that after encrypting them with key bi you get the sequence ci.After that in each of k next lines print n integers a0, a1, ..., an - 1. Print the sequences in lexicographical order.Note that k could be equal to 0.ExamplesInput110Output11Input110081Output291109Input31 1 3165 185 197Output2-6 -9 -18 5 13
Input110
Output11
5 seconds
256 megabytes
['fft', 'math', '*3300']
D. Weighting a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a connected undirected graph with n vertices and m edges. The vertices are enumerated from 1 to n. You are given n integers c1, c2, ..., cn, each of them is between  - n and n, inclusive. It is also guaranteed that the parity of cv equals the parity of degree of vertex v. The degree of a vertex is the number of edges connected to it.You are to write a weight between  - 2Β·n2 and 2Β·n2 (inclusive) on each edge in such a way, that for each vertex v the sum of weights on edges connected to this vertex is equal to cv, or determine that this is impossible.InputThe first line contains two integers n and m (2 ≀ n ≀ 105, n - 1 ≀ m ≀ 105)Β β€” the number of vertices and the number of edges.The next line contains n integers c1, c2, ..., cn ( - n ≀ ci ≀ n), where ci is the required sum of weights of edges connected to vertex i. It is guaranteed that the parity of ci equals the parity of degree of vertex i.The next m lines describe edges of the graph. The i-th of these lines contains two integers ai and bi (1 ≀ ai, bi ≀ n; ai ≠ bi), meaning that the i-th edge connects vertices ai and bi.It is guaranteed that the given graph is connected and does not contain loops and multiple edges.OutputIf there is no solution, print "NO".Otherwise print "YES" and then m lines, the i-th of them is the weight of the i-th edge wi ( - 2Β·n2 ≀ wi ≀ 2Β·n2).ExamplesInput3 32 2 21 22 31 3OutputYES111Input4 3-1 0 2 11 22 33 4OutputYES-111Input6 63 5 5 5 1 51 43 24 34 53 55 6OutputYES353-1-35Input4 44 4 2 41 22 33 44 1OutputNO
Input3 32 2 21 22 31 3
OutputYES111
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', '*2700']
C. Bipartite Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph with n vertices. There are no edge-simple cycles with the even length in it. In other words, there are no cycles of even length that pass each edge at most once. Let's enumerate vertices from 1 to n. You have to answer q queries. Each query is described by a segment of vertices [l; r], and you have to count the number of its subsegments [x; y] (l ≀ x ≀ y ≀ r), such that if we delete all vertices except the segment of vertices [x; y] (including x and y) and edges between them, the resulting graph is bipartite.InputThe first line contains two integers n and m (1 ≀ n ≀ 3Β·105, 1 ≀ m ≀ 3Β·105)Β β€” the number of vertices and the number of edges in the graph.The next m lines describe edges in the graph. The i-th of these lines contains two integers ai and bi (1 ≀ ai, bi ≀ n; ai ≠ bi), denoting an edge between vertices ai and bi. It is guaranteed that this graph does not contain edge-simple cycles of even length.The next line contains a single integer q (1 ≀ q ≀ 3Β·105)Β β€” the number of queries.The next q lines contain queries. The i-th of these lines contains two integers li and ri (1 ≀ li ≀ ri ≀ n)Β β€” the query parameters.OutputPrint q numbers, each in new line: the i-th of them should be the number of subsegments [x; y] (li ≀ x ≀ y ≀ ri), such that the graph that only includes vertices from segment [x; y] and edges between them is bipartite.ExamplesInput6 61 22 33 14 55 66 431 34 61 6Output5514Input8 91 22 33 14 55 66 77 88 47 231 81 43 8Output27819NoteThe first example is shown on the picture below:For the first query, all subsegments of [1; 3], except this segment itself, are suitable.For the first query, all subsegments of [4; 6], except this segment itself, are suitable.For the third query, all subsegments of [1; 6] are suitable, except [1; 3], [1; 4], [1; 5], [1; 6], [2; 6], [3; 6], [4; 6].The second example is shown on the picture below:
Input6 61 22 33 14 55 66 431 34 61 6
Output5514
2 seconds
256 megabytes
['binary search', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'two pointers', '*2300']
B. GCD of Polynomialstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you have two polynomials and . Then polynomial can be uniquely represented in the following way:This can be done using long division. Here, denotes the degree of polynomial P(x). is called the remainder of division of polynomial by polynomial , it is also denoted as . Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials . If the polynomial is zero, the result is , otherwise the result is the value the algorithm returns for pair . On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question. You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair to pair . InputYou are given a single integer n (1 ≀ n ≀ 150)Β β€” the number of steps of the algorithm you need to reach.OutputPrint two polynomials in the following format.In the first line print a single integer m (0 ≀ m ≀ n)Β β€” the degree of the polynomial. In the second line print m + 1 integers between  - 1 and 1Β β€” the coefficients of the polynomial, from constant to leading. The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials.If there is no answer for the given n, print -1.If there are multiple answer, print any of them.ExamplesInput1Output10 101Input2Output2-1 0 110 1NoteIn the second example you can print polynomials x2 - 1 and x. The sequence of transitions is(x2 - 1, x) → (x,  - 1) → ( - 1, 0).There are two steps in it.
Input1
Output10 101
2 seconds
256 megabytes
['constructive algorithms', 'math', '*2200']
A. Hashing Treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.InputThe first line contains a single integer h (2 ≀ h ≀ 105)Β β€” the height of the tree.The second line contains h + 1 integersΒ β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence.OutputIf there is only one tree matching this sequence, print "perfect".Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root.These treese should be non-isomorphic and should match the given sequence.ExamplesInput21 1 1OutputperfectInput21 2 2Outputambiguous0 1 1 3 30 1 1 3 2NoteThe only tree in the first example and the two printed trees from the second example are shown on the picture:
Input21 1 1
Outputperfect
2 seconds
256 megabytes
['constructive algorithms', 'trees', '*1500']
E. Maximum Questionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya wrote down two strings s of length n and t of length m consisting of small English letters 'a' and 'b'. What is more, he knows that string t has a form "abab...", namely there are letters 'a' on odd positions and letters 'b' on even positions.Suddenly in the morning, Vasya found that somebody spoiled his string. Some letters of the string s were replaced by character '?'.Let's call a sequence of positions i, i + 1, ..., i + m - 1 as occurrence of string t in s, if 1 ≀ i ≀ n - m + 1 and t1 = si, t2 = si + 1, ..., tm = si + m - 1.The boy defines the beauty of the string s as maximum number of disjoint occurrences of string t in s. Vasya can replace some letters '?' with 'a' or 'b' (letters on different positions can be replaced with different letter). Vasya wants to make some replacements in such a way that beauty of string s is maximum possible. From all such options, he wants to choose one with the minimum number of replacements. Find the number of replacements he should make.InputThe first line contains a single integer n (1 ≀ n ≀ 105)Β β€” the length of s.The second line contains the string s of length n. It contains small English letters 'a', 'b' and characters '?' only.The third line contains a single integer m (1 ≀ m ≀ 105)Β β€” the length of t. The string t contains letters 'a' on odd positions and 'b' on even positions.OutputPrint the only integerΒ β€” the minimum number of replacements Vasya has to perform to make the beauty of string s the maximum possible.ExamplesInput5bb?a?1Output2Input9ab??ab???3Output2NoteIn the first sample string t has a form 'a'. The only optimal option is to replace all characters '?' by 'a'.In the second sample using two replacements we can make string equal to "aba?aba??". It is impossible to get more than two occurrences.
Input5bb?a?1
Output2
2 seconds
256 megabytes
['data structures', 'dp', 'strings', '*2100']
D. Unusual Sequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCount the number of distinct sequences a1, a2, ..., an (1 ≀ ai) consisting of positive integers such that gcd(a1, a2, ..., an) = x and . As this number could be large, print the answer modulo 109 + 7.gcd here means the greatest common divisor.InputThe only line contains two positive integers x and y (1 ≀ x, y ≀ 109).OutputPrint the number of such sequences modulo 109 + 7.ExamplesInput3 9Output3Input5 8Output0NoteThere are three suitable sequences in the first test: (3, 3, 3), (3, 6), (6, 3).There are no suitable sequences in the second test.
Input3 9
Output3
1 second
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'math', 'number theory', '*2000']
C. Remove Extra Onetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≀ j < i) the following holds: aj < ai. InputThe first line contains the only integer n (1 ≀ n ≀ 105)Β β€” the length of the permutation.The second line contains n integers p1, p2, ..., pn (1 ≀ pi ≀ n)Β β€” the permutation. All the integers are distinct.OutputPrint the only integerΒ β€” the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.ExamplesInput11Output1Input55 1 2 3 4Output5NoteIn the first example the only element can be removed.
Input11
Output1
2 seconds
256 megabytes
['brute force', 'data structures', 'math', '*1700']
B. Position in Fractiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a fraction . You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point.InputThe first contains three single positive integers a, b, c (1 ≀ a < b ≀ 105, 0 ≀ c ≀ 9).OutputPrint 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.ExamplesInput1 2 0Output2Input2 3 7Output-1NoteThe fraction in the first example has the following decimal notation: . The first zero stands on second position.The fraction in the second example has the following decimal notation: . There is no digit 7 in decimal notation of the fraction.
Input1 2 0
Output2
1 second
256 megabytes
['math', 'number theory', '*1300']
A. Find Extra Onetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis.InputThe first line contains a single positive integer n (2 ≀ n ≀ 105).The following n lines contain coordinates of the points. The i-th of these lines contains two single integers xi and yi (|xi|, |yi| ≀ 109, xi ≠ 0). No two points coincide.OutputPrint "Yes" if there is such a point, "No" β€” otherwise.You can print every letter in any case (upper or lower).ExamplesInput31 1-1 -12 -1OutputYesInput41 12 2-1 1-2 2OutputNoInput31 22 14 60OutputYesNoteIn the first example the second point can be removed.In the second example there is no suitable for the condition point.In the third example any point can be removed.
Input31 1-1 -12 -1
OutputYes
1 second
256 megabytes
['geometry', 'implementation', '*800']
F. Letters Removingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has a string of length n consisting of small and large English letters and digits.He performs m operations. Each operation is described with two integers l and r and a character c: Petya removes from the string all characters c on positions between l and r, inclusive. It's obvious that the length of the string remains the same or decreases after each operation.Find how the string will look like after Petya performs all m operations.InputThe first string contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the length of the string and the number of operations.The second line contains the string of length n, consisting of small and large English letters and digits. Positions in the string are enumerated from 1.Each of the next m lines contains two integers l and r (1 ≀ l ≀ r), followed by a character c, which is a small or large English letter or a digit. This line describes one operation. It is guaranteed that r doesn't exceed the length of the string s before current operation.OutputPrint the string Petya will obtain after performing all m operations. If the strings becomes empty after all operations, print an empty line.ExamplesInput4 2abac1 3 a2 2 cOutputbInput3 2A0z1 3 01 1 zOutputAzInput10 4agtFrgF4aF2 5 g4 9 F1 5 41 7 aOutputtFrg4Input9 5aAAaBBccD1 4 a5 6 c2 3 B4 4 D2 3 AOutputABNoteIn the first example during the first operation both letters 'a' are removed, so the string becomes "bc". During the second operation the letter 'c' (on the second position) is removed, and the string becomes "b".In the second example during the first operation Petya removes '0' from the second position. After that the string becomes "Az". During the second operations the string doesn't change.
Input4 2abac1 3 a2 2 c
Outputb
2 seconds
256 megabytes
['data structures', 'strings', '*2100']
E. Segments Removaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has an array of integers of length n.Vasya performs the following operations on the array: on each step he finds the longest segment of consecutive equal integers (the leftmost, if there are several such segments) and removes it. For example, if Vasya's array is [13, 13, 7, 7, 7, 2, 2, 2], then after one operation it becomes [13, 13, 2, 2, 2].Compute the number of operations Vasya should make until the array becomes empty, i.e. Vasya removes all elements from it.InputThe first line contains a single integer n (1 ≀ n ≀ 200 000) β€” the length of the array.The second line contains a sequence a1, a2, ..., an (1 ≀ ai ≀ 109) β€” Vasya's array.OutputPrint the number of operations Vasya should make to remove all elements from the array.ExamplesInput42 5 5 2Output2Input56 3 4 1 5Output5Input84 4 4 2 2 100 100 100Output3Input610 10 50 10 50 50Output4NoteIn the first example, at first Vasya removes two fives at the second and third positions. The array becomes [2, 2]. In the second operation Vasya removes two twos at the first and second positions. After that the array becomes empty.In the second example Vasya has to perform five operations to make the array empty. In each of them he removes the first element from the array.In the third example Vasya needs three operations. In the first operation he removes all integers 4, in the second β€” all integers 100, in the third β€” all integers 2.In the fourth example in the first operation Vasya removes the first two integers 10. After that the array becomes [50, 10, 50, 50]. Then in the second operation Vasya removes the two rightmost integers 50, so that the array becomes [50, 10]. In the third operation he removes the remaining 50, and the array becomes [10] after that. In the last, fourth operation he removes the only remaining 10. The array is empty after that.
Input42 5 5 2
Output2
2 seconds
256 megabytes
['data structures', 'dsu', 'flows', 'implementation', 'two pointers', '*2000']
D. Shovel Saletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs.Visitors are more likely to buy a pair of shovels if their total cost ends with several 9s. Because of this, Polycarp wants to choose a pair of shovels to sell in such a way that the sum of their costs ends with maximum possible number of nines. For example, if he chooses shovels with costs 12345 and 37454, their total cost is 49799, it ends with two nines.You are to compute the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Two pairs are considered different if there is a shovel presented in one pair, but not in the other.InputThe first line contains a single integer n (2 ≀ n ≀ 109) β€” the number of shovels in Polycarp's shop.OutputPrint the number of pairs of shovels such that their total cost ends with maximum possible number of nines. Note that it is possible that the largest number of 9s at the end is 0, then you should count all such ways.It is guaranteed that for every n ≀ 109 the answer doesn't exceed 2Β·109.ExamplesInput7Output3Input14Output9Input50Output1NoteIn the first example the maximum possible number of nines at the end is one. Polycarp cah choose the following pairs of shovels for that purpose: 2 and 7; 3 and 6; 4 and 5. In the second example the maximum number of nines at the end of total cost of two shovels is one. The following pairs of shovels suit Polycarp: 1 and 8; 2 and 7; 3 and 6; 4 and 5; 5 and 14; 6 and 13; 7 and 12; 8 and 11; 9 and 10. In the third example it is necessary to choose shovels 49 and 50, because the sum of their cost is 99, that means that the total number of nines is equal to two, which is maximum possible for n = 50.
Input7
Output3
1 second
256 megabytes
['constructive algorithms', 'math', '*1800']
C. Dividing the numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group.InputThe first line contains a single integer n (2 ≀ n ≀ 60 000) β€” the number of integers Petya has.OutputPrint the smallest possible absolute difference in the first line.In the second line print the size of the first group, followed by the integers in that group. You can print these integers in arbitrary order. If there are multiple answers, print any of them.ExamplesInput4Output02 1 4 Input2Output11 1 NoteIn the first example you have to put integers 1 and 4 in the first group, and 2 and 3 in the second. This way the sum in each group is 5, and the absolute difference is 0.In the second example there are only two integers, and since both groups should be non-empty, you have to put one integer in the first group and one in the second. This way the absolute difference of sums of integers in each group is 1.
Input4
Output02 1 4
1 second
256 megabytes
['constructive algorithms', 'graphs', 'math', '*1300']
B. Months and Yearstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December.A year is leap in one of two cases: either its number is divisible by 4, but not divisible by 100, or is divisible by 400. For example, the following years are leap: 2000, 2004, but years 1900 and 2018 are not leap.In this problem you are given n (1 ≀ n ≀ 24) integers a1, a2, ..., an, and you have to check if these integers could be durations in days of n consecutive months, according to Gregorian calendar. Note that these months could belong to several consecutive years. In other words, check if there is a month in some year, such that its duration is a1 days, duration of the next month is a2 days, and so on.InputThe first line contains single integer n (1 ≀ n ≀ 24) β€” the number of integers.The second line contains n integers a1, a2, ..., an (28 ≀ ai ≀ 31) β€” the numbers you are to check.OutputIf there are several consecutive months that fit the sequence, print "YES" (without quotes). Otherwise, print "NO" (without quotes).You can print each letter in arbitrary case (small or large).ExamplesInput431 31 30 31OutputYesInput230 30OutputNoInput529 31 30 31 30OutputYesInput331 28 30OutputNoInput331 31 28OutputYesNoteIn the first example the integers can denote months July, August, September and October.In the second example the answer is no, because there are no two consecutive months each having 30 days.In the third example the months are: February (leap year) β€” March β€” April – May β€” June.In the fourth example the number of days in the second month is 28, so this is February. March follows February and has 31 days, but not 30, so the answer is NO.In the fifth example the months are: December β€” January β€” February (non-leap year).
Input431 31 30 31
OutputYes
1 second
256 megabytes
['implementation', '*1200']
A. Splitting in Teamstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.InputThe first line contains single integer n (2 ≀ n ≀ 2Β·105) β€” the number of groups.The second line contains a sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 2), where ai is the number of people in group i.OutputPrint the maximum number of teams of three people the coach can form.ExamplesInput41 1 2 1Output1Input22 2Output0Input72 2 2 1 1 1 1Output3Input31 1 1Output1NoteIn the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.In the second example he can't make a single team.In the third example the coach can form three teams. For example, he can do this in the following way: The first group (of two people) and the seventh group (of one person), The second group (of two people) and the sixth group (of one person), The third group (of two people) and the fourth group (of one person).
Input41 1 2 1
Output1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*800']
F. Restoring the Expressiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA correct expression of the form a+b=c was written; a, b and c are non-negative integers without leading zeros. In this expression, the plus and equally signs were lost. The task is to restore the expression. In other words, one character '+' and one character '=' should be inserted into given sequence of digits so that: character'+' is placed on the left of character '=', characters '+' and '=' split the sequence into three non-empty subsequences consisting of digits (let's call the left part a, the middle partΒ β€” b and the right partΒ β€” c), all the three parts a, b and c do not contain leading zeros, it is true that a+b=c. It is guaranteed that in given tests answer always exists.InputThe first line contains a non-empty string consisting of digits. The length of the string does not exceed 106.OutputOutput the restored expression. If there are several solutions, you can print any of them.Note that the answer at first should contain two terms (divided with symbol '+'), and then the result of their addition, before which symbol'=' should be. Do not separate numbers and operation signs with spaces. Strictly follow the output format given in the examples.If you remove symbol '+' and symbol '=' from answer string you should get a string, same as string from the input data.ExamplesInput12345168Output123+45=168Input099Output0+9=9Input199100Output1+99=100Input123123123456456456579579579Output123123123+456456456=579579579
Input12345168
Output123+45=168
2 seconds
256 megabytes
['brute force', 'hashing', 'math', '*2300']
E. Squares and not squarestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnn and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile). Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer.InputFirst line contains one even integer n (2 ≀ n ≀ 200 000)Β β€” number of piles with candies.Second line contains sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 109)Β β€” amounts of candies in each pile.OutputOutput minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.ExamplesInput412 14 30 4Output2Input60 0 0 0 0 0Output6Input6120 110 23 34 25 45Output3Input10121 56 78 81 45 100 1 0 54 78Output0NoteIn first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).In second example you should add two candies to any three piles.
Input412 14 30 4
Output2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1600']
D. Alarm Clocktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer aiΒ β€” number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute. Vitalya will definitely wake up if during some m consecutive minutes at least k alarm clocks will begin ringing. Pay attention that Vitalya considers only alarm clocks which begin ringing during given period of time. He doesn't consider alarm clocks which started ringing before given period of time and continues ringing during given period of time.Vitalya is so tired that he wants to sleep all day long and not to wake up. Find out minimal number of alarm clocks Vitalya should turn off to sleep all next day. Now all alarm clocks are turned on. InputFirst line contains three integers n, m and k (1 ≀ k ≀ n ≀ 2Β·105, 1 ≀ m ≀ 106)Β β€” number of alarm clocks, and conditions of Vitalya's waking up. Second line contains sequence of distinct integers a1, a2, ..., an (1 ≀ ai ≀ 106) in which ai equals minute on which i-th alarm clock will ring. Numbers are given in arbitrary order. Vitalya lives in a Berland in which day lasts for 106 minutes. OutputOutput minimal number of alarm clocks that Vitalya should turn off to sleep all next day long.ExamplesInput3 3 23 5 1Output1Input5 10 312 8 18 25 1Output0Input7 7 27 3 4 1 6 5 2Output6Input2 2 21 3Output0NoteIn first example Vitalya should turn off first alarm clock which rings at minute 3.In second example Vitalya shouldn't turn off any alarm clock because there are no interval of 10 consequence minutes in which 3 alarm clocks will ring.In third example Vitalya should turn off any 6 alarm clocks.
Input3 3 23 5 1
Output1
2 seconds
256 megabytes
['greedy', '*1600']
C. Phone Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has several phone books, in which he recorded the telephone numbers of his friends. Each of his friends can have one or several phone numbers.Vasya decided to organize information about the phone numbers of friends. You will be given n strings β€” all entries from Vasya's phone books. Each entry starts with a friend's name. Then follows the number of phone numbers in the current entry, and then the phone numbers themselves. It is possible that several identical phones are recorded in the same record.Vasya also believes that if the phone number a is a suffix of the phone number b (that is, the number b ends up with a), and both numbers are written by Vasya as the phone numbers of the same person, then a is recorded without the city code and it should not be taken into account.The task is to print organized information about the phone numbers of Vasya's friends. It is possible that two different people have the same number. If one person has two numbers x and y, and x is a suffix of y (that is, y ends in x), then you shouldn't print number x. If the number of a friend in the Vasya's phone books is recorded several times in the same format, it is necessary to take it into account exactly once.Read the examples to understand statement and format of the output better.InputFirst line contains the integer n (1 ≀ n ≀ 20)Β β€” number of entries in Vasya's phone books. The following n lines are followed by descriptions of the records in the format described in statement. Names of Vasya's friends are non-empty strings whose length does not exceed 10. They consists only of lowercase English letters. Number of phone numbers in one entry is not less than 1 is not more than 10. The telephone numbers consist of digits only. If you represent a phone number as a string, then its length will be in range from 1 to 10. Phone numbers can contain leading zeros.OutputPrint out the ordered information about the phone numbers of Vasya's friends. First output mΒ β€” number of friends that are found in Vasya's phone books.The following m lines must contain entries in the following format "name number_of_phone_numbers phone_numbers". Phone numbers should be separated by a space. Each record must contain all the phone numbers of current friend.Entries can be displayed in arbitrary order, phone numbers for one record can also be printed in arbitrary order.ExamplesInput2ivan 1 00123masha 1 00123Output2masha 1 00123 ivan 1 00123 Input3karl 2 612 12petr 1 12katya 1 612Output3katya 1 612 petr 1 12 karl 1 612 Input4ivan 3 123 123 456ivan 2 456 456ivan 8 789 3 23 6 56 9 89 2dasha 2 23 789Output2dasha 2 23 789 ivan 4 789 123 2 456
Input2ivan 1 00123masha 1 00123
Output2masha 1 00123 ivan 1 00123
2 seconds
256 megabytes
['implementation', 'strings', '*1400']
B. Proper Nutritiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles.In other words, you should find two non-negative integers x and y such that Vasya can buy x bottles of Ber-Cola and y Bars bars and xΒ·a + yΒ·b = n or tell that it's impossible.InputFirst line contains single integer n (1 ≀ n ≀ 10 000 000)Β β€” amount of money, that Vasya has.Second line contains single integer a (1 ≀ a ≀ 10 000 000)Β β€” cost of one bottle of Ber-Cola.Third line contains single integer b (1 ≀ b ≀ 10 000 000)Β β€” cost of one Bars bar.OutputIf Vasya can't buy Bars and Ber-Cola in such a way to spend exactly n burles print Β«NOΒ» (without quotes).Otherwise in first line print Β«YESΒ» (without quotes). In second line print two non-negative integers x and yΒ β€” number of bottles of Ber-Cola and number of Bars bars Vasya should buy in order to spend exactly n burles, i.e. xΒ·a + yΒ·b = n. If there are multiple answers print any of them.Any of numbers x and y can be equal 0.ExamplesInput723OutputYES2 1Input1002510OutputYES0 10Input1548OutputNOInput996059425512557OutputYES1951 1949NoteIn first example Vasya can buy two bottles of Ber-Cola and one Bars bar. He will spend exactly 2Β·2 + 1Β·3 = 7 burles.In second example Vasya can spend exactly n burles multiple ways: buy two bottles of Ber-Cola and five Bars bars; buy four bottles of Ber-Cola and don't buy Bars bars; don't buy Ber-Cola and buy 10 Bars bars. In third example it's impossible to but Ber-Cola and Bars bars in order to spend exactly n burles.
Input723
OutputYES2 1
1 second
256 megabytes
['brute force', 'implementation', 'number theory', '*1100']
A. Roundingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded.For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct.For given n find out to which integer will Vasya round it.InputThe first line contains single integer n (0 ≀ n ≀ 109)Β β€” number that Vasya has.OutputPrint result of rounding n. Pay attention that in some cases answer isn't unique. In that case print any correct answer.ExamplesInput5Output0Input113Output110Input1000000000Output1000000000Input5432359Output5432360NoteIn the first example n = 5. Nearest integers, that ends up with zero are 0 and 10. Any of these answers is correct, so you can print 0 or 10.
Input5
Output0
1 second
256 megabytes
['implementation', 'math', '*800']
B. Chtholly's requesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output β€” Thanks a lot for today.β€” I experienced so many great things.β€” You gave me memories like dreams... But I have to leave now...β€” One last request, can you...β€” Help me solve a Codeforces problem?β€” ......β€” What?Chtholly has been thinking about a problem for days:If a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.Given integers k and p, calculate the sum of the k smallest zcy numbers and output this sum modulo p.Unfortunately, Willem isn't good at solving this kind of problems, so he asks you for help!InputThe first line contains two integers k and p (1 ≀ k ≀ 105, 1 ≀ p ≀ 109).OutputOutput single integerΒ β€” answer to the problem.ExamplesInput2 100Output33Input5 30Output15NoteIn the first example, the smallest zcy number is 11, and the second smallest zcy number is 22.In the second example, .
Input2 100
Output33
2 seconds
256 megabytes
['brute force', '*1300']
A. Scarborough Fairtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAre you going to Scarborough Fair?Parsley, sage, rosemary and thyme.Remember me to one who lives there.He once was the true love of mine.Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.Although the girl wants to help, Willem insists on doing it by himself.Grick gave Willem a string of length n.Willem needs to do m operations, each operation has four parameters l, r, c1, c2, which means that all symbols c1 in range [l, r] (from l-th to r-th, including l and r) are changed into c2. String is 1-indexed.Grick wants to know the final string after all the m operations.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 100).The second line contains a string s of length n, consisting of lowercase English letters.Each of the next m lines contains four parameters l, r, c1, c2 (1 ≀ l ≀ r ≀ n, c1, c2 are lowercase English letters), separated by space.OutputOutput string s after performing m operations described above.ExamplesInput3 1ioi1 1 i nOutputnoiInput5 3wxhak3 3 h x1 5 x a1 3 w gOutputgaaakNoteFor the second example:After the first operation, the string is wxxak.After the second operation, the string is waaak.After the third operation, the string is gaaak.
Input3 1ioi1 1 i n
Outputnoi
2 seconds
256 megabytes
['implementation', '*800']
E. Welcome home, Chthollytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputβ€” I... I survived.β€” Welcome home, Chtholly.β€” I kept my promise...β€” I made it... I really made it!After several days of fighting, Chtholly Nota Seniorious miraculously returned from the fierce battle.As promised, Willem is now baking butter cake for her.However, although Willem is skilled in making dessert, he rarely bakes butter cake.This time, Willem made a big mistake β€” he accidentally broke the oven!Fortunately, Chtholly decided to help him.Willem puts n cakes on a roll, cakes are numbered from 1 to n, the i-th cake needs ai seconds of baking.Willem needs Chtholly to do m operations to bake the cakes.Operation 1: 1 l r xWillem asks Chtholly to check each cake in the range [l, r], if the cake needs to be baked for more than x seconds, he would bake it for x seconds and put it back in its place. More precisely, for every i in range [l, r], if ai is strictly more than x, ai becomes equal ai - x.Operation 2: 2 l r xWillem asks Chtholly to count the number of cakes in the range [l, r] that needs to be cooked for exactly x seconds. More formally you should find number of such i in range [l, r], that ai = x.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 105).The second line contains n integers, i-th of them is ai (1 ≀ ai ≀ 105).The next m lines are the m operations described above. It is guaranteed that 1 ≀ l ≀ r ≀ n and 1 ≀ x ≀ 105.OutputFor each operation of the second type, print the answer.ExamplesInput5 61 5 5 5 82 2 5 51 2 4 32 2 5 22 2 5 51 3 5 12 1 5 1Output3303Input7 71 9 2 6 8 1 72 1 7 12 2 5 21 4 7 72 2 4 21 3 4 52 3 3 32 3 7 2Output21101Input8 1375 85 88 100 105 120 122 1281 1 8 702 3 8 301 3 8 32 2 5 151 2 4 102 1 5 51 2 7 272 1 5 51 3 7 121 1 7 42 1 8 11 4 8 52 1 8 1Output123456
Input5 61 5 5 5 82 2 5 51 2 4 32 2 5 22 2 5 51 3 5 12 1 5 1
Output3303
3 seconds
512 megabytes
['data structures', 'dsu', '*3100']
D. Nephren Runs a Cinematime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLakhesh loves to make movies, so Nephren helps her run a cinema. We may call it No. 68 Cinema.However, one day, the No. 68 Cinema runs out of changes (they don't have 50-yuan notes currently), but Nephren still wants to start their business. (Assume that yuan is a kind of currency in Regulu Ere.)There are three types of customers: some of them bring exactly a 50-yuan note; some of them bring a 100-yuan note and Nephren needs to give a 50-yuan note back to him/her; some of them bring VIP cards so that they don't need to pay for the ticket.Now n customers are waiting outside in queue. Nephren wants to know how many possible queues are there that they are able to run smoothly (i.e. every customer can receive his/her change), and that the number of 50-yuan notes they have after selling tickets to all these customers is between l and r, inclusive. Two queues are considered different if there exists a customer whose type is different in two queues. As the number can be large, please output the answer modulo p.InputOne line containing four integers n (1 ≀ n ≀ 105), p (1 ≀ p ≀ 2Β·109), l and r (0 ≀ l ≀ r ≀ n). OutputOne line indicating the answer modulo p.ExamplesInput4 97 2 3Output13Input4 100 0 4Output35NoteWe use A, B and C to indicate customers with 50-yuan notes, customers with 100-yuan notes and customers with VIP cards respectively.For the first sample, the different possible queues that there are 2 50-yuan notes left are AAAB, AABA, ABAA, AACC, ACAC, ACCA, CAAC, CACA and CCAA, and the different possible queues that there are 3 50-yuan notes left are AAAC, AACA, ACAA and CAAA. So there are 13 different queues satisfying the first sample. Similarly, there are 35 different queues satisfying the second sample.
Input4 97 2 3
Output13
2.5 seconds
256 megabytes
['chinese remainder theorem', 'combinatorics', 'math', 'number theory', '*2900']
C. Willem, Chtholly and Seniorioustime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputβ€” Willem...β€” What's the matter?β€” It seems that there's something wrong with Seniorious...β€” I'll have a look...Seniorious is made by linking special talismans in particular order.After over 500 years, the carillon is now in bad condition, so Willem decides to examine it thoroughly.Seniorious has n pieces of talisman. Willem puts them in a line, the i-th of which is an integer ai.In order to maintain it, Willem needs to perform m operations.There are four types of operations: 1 l r x: For each i such that l ≀ i ≀ r, assign ai + x to ai. 2 l r x: For each i such that l ≀ i ≀ r, assign x to ai. 3 l r x: Print the x-th smallest number in the index range [l, r], i.e. the element at the x-th position if all the elements ai such that l ≀ i ≀ r are taken and sorted into an array of non-decreasing integers. It's guaranteed that 1 ≀ x ≀ r - l + 1. 4 l r x y: Print the sum of the x-th power of ai such that l ≀ i ≀ r, modulo y, i.e. .InputThe only line contains four integers n, m, seed, vmax (1 ≀ n, m ≀ 105, 0 ≀ seed < 109 + 7, 1 ≀ vmax ≀ 109).The initial values and operations are generated using following pseudo code:def rnd(): ret = seed seed = (seed * 7 + 13) mod 1000000007 return retfor i = 1 to n: a[i] = (rnd() mod vmax) + 1for i = 1 to m: op = (rnd() mod 4) + 1 l = (rnd() mod n) + 1 r = (rnd() mod n) + 1 if (l > r): swap(l, r) if (op == 3): x = (rnd() mod (r - l + 1)) + 1 else: x = (rnd() mod vmax) + 1 if (op == 4): y = (rnd() mod vmax) + 1Here op is the type of the operation mentioned in the legend.OutputFor each operation of types 3 or 4, output a line containing the answer.ExamplesInput10 10 7 9Output2103Input10 10 9 9Output1133NoteIn the first example, the initial array is {8, 9, 7, 2, 3, 1, 5, 6, 4, 8}.The operations are: 2 6 7 9 1 3 10 8 4 4 6 2 4 1 4 5 8 2 1 7 1 4 7 9 4 4 1 2 7 9 4 5 8 1 1 2 5 7 5 4 3 10 8 5
Input10 10 7 9
Output2103
2 seconds
256 megabytes
['data structures', 'probabilities', '*2600']
B. Ithea Plays With Chthollytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. Refer to the Interaction section below for better understanding.Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game.Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.InputThe first line contains 3 integers n, m and c (, means rounded up)Β β€” the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process.InteractionIn each round, your program needs to read one line containing a single integer pi (1 ≀ pi ≀ c), indicating the number given to Chtholly.Your program should then output a line containing an integer between 1 and n, indicating the number of sheet to write down this number in.After outputting each line, don't forget to flush the output. For example: fflush(stdout) in C/C++; System.out.flush() in Java; sys.stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. If Chtholly wins at the end of a round, no more input will become available and your program should terminate normally. It can be shown that under the constraints, it's always possible for Chtholly to win the game.ExampleInput2 4 4213Output122NoteIn the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round.The input format for hacking: The first line contains 3 integers n, m and c; The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.
Input2 4 4213
Output122
1 second
256 megabytes
['binary search', 'constructive algorithms', 'games', 'greedy', 'interactive', '*2000']
A. Nephren gives a riddletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhat are you doing at the end of the world? Are you busy? Will you save us?Nephren is playing a game with little leprechauns.She gives them an infinite array of strings, f0... ∞.f0 is "What are you doing at the end of the world? Are you busy? Will you save us?".She wants to let more people know about it, so she defines fi =  "What are you doing while sending "fi - 1"? Are you busy? Will you send "fi - 1"?" for all i β‰₯ 1.For example, f1 is"What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?". Note that the quotes in the very beginning and in the very end are for clarity and are not a part of f1.It can be seen that the characters in fi are letters, question marks, (possibly) quotation marks and spaces.Nephren will ask the little leprechauns q times. Each time she will let them find the k-th character of fn. The characters are indexed starting from 1. If fn consists of less than k characters, output '.' (without quotes).Can you answer her queries?InputThe first line contains one integer q (1 ≀ q ≀ 10)Β β€” the number of Nephren's questions.Each of the next q lines describes Nephren's question and contains two integers n and k (0 ≀ n ≀ 105, 1 ≀ k ≀ 1018).OutputOne line containing q characters. The i-th character in it should be the answer for the i-th query.ExamplesInput31 11 21 111111111111OutputWh.Input50 691 1941 1390 471 66OutputabdefInput104 18253 753 5304 18294 16513 1874 5844 2554 7742 474OutputAreyoubusyNoteFor the first two examples, refer to f0 and f1 given in the legend.
Input31 11 21 111111111111
OutputWh.
2 seconds
256 megabytes
['binary search', 'dfs and similar', '*1700']
E. Eyes Closedtime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya and Petya were tired of studying so they decided to play a game. Before the game begins Vasya looks at array a consisting of n integers. As soon as he remembers all elements of a the game begins. Vasya closes his eyes and Petya does q actions of one of two types:1) Petya says 4 integers l1, r1, l2, r2Β β€” boundaries of two non-intersecting segments. After that he swaps one random element from the [l1, r1] segment with another random element from the [l2, r2] segment.2) Petya asks Vasya the sum of the elements of a in the [l, r] segment.Vasya is a mathematician so he answers Petya the mathematical expectation of the sum of the elements in the segment.Your task is to write a program which will answer the second type questions as Vasya would do it. In other words your program should print the mathematical expectation of the sum of the elements of a in the [l, r] segment for every second type query.InputThe first line contains two integers n, q (2 ≀ n ≀ 105, 1 ≀ q ≀ 105) Β β€” the number of elements in the array and the number of queries you need to handle.The second line contains n integers ai (1 ≀ ai ≀ 109) Β β€” elements of the array.The next q lines contain Petya's actions of type 1 or 2.If it is a type 1 action then the line contains 5 integers 1, l1, r1, l2, r2 (1 ≀ l1 ≀ r1 ≀ n, 1 ≀ l2 ≀ r2 ≀ n).If it is a type 2 query then the line contains 3 integers 2, l, r (1 ≀ l ≀ r ≀ n).It is guaranteed that there is at least one type 2 query and segments [l1, r1], [l2, r2] don't have common elements. OutputFor each type 2 query print one real numberΒ β€” the mathematical expectation of the sum of elements in the segment.Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 4 Β β€” formally, the answer is correct if where x is jury's answer and y is yours.ExamplesInput4 41 1 2 21 2 2 3 32 1 21 1 2 3 42 1 2Output3.00000003.0000000Input10 51 1 1 1 1 2 2 2 2 21 1 5 6 102 1 51 1 5 6 101 1 5 6 102 6 10Output6.00000008.0400000Input10 101 2 3 4 5 6 7 8 9 101 1 5 6 101 1 5 6 102 1 51 1 3 6 92 1 31 5 7 8 101 1 1 10 102 1 52 7 102 1 10Output23.000000014.000000028.013333321.573333355.0000000
Input4 41 1 2 21 2 2 3 32 1 21 1 2 3 42 1 2
Output3.00000003.0000000
2.5 seconds
256 megabytes
['data structures', 'probabilities', '*2300']
D. String Marktime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the Byteland State University marks are strings of the same length. Mark x is considered better than y if string y is lexicographically smaller than x.Recently at the BSU was an important test work on which Vasya recived the mark a. It is very hard for the teacher to remember the exact mark of every student, but he knows the mark b, such that every student recieved mark strictly smaller than b.Vasya isn't satisfied with his mark so he decided to improve it. He can swap characters in the string corresponding to his mark as many times as he like. Now he want to know only the number of different ways to improve his mark so that his teacher didn't notice something suspicious.More formally: you are given two strings a, b of the same length and you need to figure out the number of different strings c such that:1) c can be obtained from a by swapping some characters, in other words c is a permutation of a.2) String a is lexicographically smaller than c.3) String c is lexicographically smaller than b.For two strings x and y of the same length it is true that x is lexicographically smaller than y if there exists such i, that x1 = y1, x2 = y2, ..., xi - 1 = yi - 1, xi < yi.Since the answer can be very large, you need to find answer modulo 109 + 7.InputFirst line contains string a, second line contains string b. Strings a, b consist of lowercase English letters. Their lengths are equal and don't exceed 106.It is guaranteed that a is lexicographically smaller than b.OutputPrint one integer Β β€” the number of different strings satisfying the condition of the problem modulo 109 + 7.ExamplesInputabcdddOutput5InputabcdefabcdegOutput0InputabacabaubudubaOutput64NoteIn first sample from string abc can be obtained strings acb, bac, bca, cab, cba, all of them are larger than abc, but smaller than ddd. So the answer is 5.In second sample any string obtained from abcdef is larger than abcdeg. So the answer is 0.
Inputabcddd
Output5
4 seconds
256 megabytes
['combinatorics', 'math', 'strings', '*2100']
C. Square Subsetstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya was late for the lesson too. The teacher gave him an additional task. For some array a Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer.Two ways are considered different if sets of indexes of elements chosen by these ways are different.Since the answer can be very large, you should find the answer modulo 109 + 7.InputFirst line contains one integer n (1 ≀ n ≀ 105)Β β€” the number of elements in the array.Second line contains n integers ai (1 ≀ ai ≀ 70)Β β€” the elements of the array.OutputPrint one integerΒ β€” the number of different ways to choose some elements so that their product is a square of a certain integer modulo 109 + 7.ExamplesInput41 1 1 1Output15Input42 2 2 2Output7Input51 2 4 5 8Output7NoteIn first sample product of elements chosen by any way is 1 and 1 = 12. So the answer is 24 - 1 = 15.In second sample there are six different ways to choose elements so that their product is 4, and only one way so that their product is 16. So the answer is 6 + 1 = 7.
Input41 1 1 1
Output15
4 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'math', '*2000']
B. XK Segmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i, j) such that ai ≀ aj and there are exactly k integers y such that ai ≀ y ≀ aj and y is divisible by x.In this problem it is meant that pair (i, j) is equal to (j, i) only if i is equal to j. For example pair (1, 2) is not the same as (2, 1).InputThe first line contains 3 integers n, x, k (1 ≀ n ≀ 105, 1 ≀ x ≀ 109, 0 ≀ k ≀ 109), where n is the size of the array a and x and k are numbers from the statement.The second line contains n integers ai (1 ≀ ai ≀ 109)Β β€” the elements of the array a.OutputPrint one integerΒ β€” the answer to the problem.ExamplesInput4 2 11 3 5 7Output3Input4 2 05 3 1 7Output4Input5 3 13 3 3 3 3Output25NoteIn first sample there are only three suitable pairs of indexesΒ β€” (1, 2), (2, 3), (3, 4).In second sample there are four suitable pairs of indexes(1, 1), (2, 2), (3, 3), (4, 4).In third sample every pair (i, j) is suitable, so the answer is 5 * 5 = 25.
Input4 2 11 3 5 7
Output3
1 second
256 megabytes
['binary search', 'math', 'sortings', 'two pointers', '*1700']
A. Pizza Separationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudents Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to ai. Vasya and Petya want to divide all pieces of pizza into two continuous sectors in such way that the difference between angles of these sectors is minimal. Sector angle is sum of angles of all pieces in it. Pay attention, that one of sectors can be empty.InputThe first line contains one integer n (1 ≀ n ≀ 360) Β β€” the number of pieces into which the delivered pizza was cut.The second line contains n integers ai (1 ≀ ai ≀ 360) Β β€” the angles of the sectors into which the pizza was cut. The sum of all ai is 360.OutputPrint one integer Β β€” the minimal difference between angles of sectors that will go to Vasya and Petya.ExamplesInput490 90 90 90Output0Input3100 100 160Output40Input1360Output360Input4170 30 150 10Output0NoteIn first sample Vasya can take 1 and 2 pieces, Petya can take 3 and 4 pieces. Then the answer is |(90 + 90) - (90 + 90)| = 0.In third sample there is only one piece of pizza that can be taken by only one from Vasya and Petya. So the answer is |360 - 0| = 360.In fourth sample Vasya can take 1 and 4 pieces, then Petya will take 2 and 3 pieces. So the answer is |(170 + 10) - (30 + 150)| = 0.Picture explaning fourth sample:Both red and green sectors consist of two adjacent pieces of pizza. So Vasya can take green sector, then Petya will take red sector.
Input490 90 90 90
Output0
1 second
256 megabytes
['brute force', 'implementation', '*1200']
E. Ralph and Mushroomstime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRalph is going to collect mushrooms in the Mushroom Forest. There are m directed paths connecting n trees in the Mushroom Forest. On each path grow some mushrooms. When Ralph passes a path, he collects all the mushrooms on the path. The Mushroom Forest has a magical fertile ground where mushrooms grow at a fantastic speed. New mushrooms regrow as soon as Ralph finishes mushroom collection on a path. More specifically, after Ralph passes a path the i-th time, there regrow i mushrooms less than there was before this pass. That is, if there is initially x mushrooms on a path, then Ralph will collect x mushrooms for the first time, x - 1 mushrooms the second time, x - 1 - 2 mushrooms the third time, and so on. However, the number of mushrooms can never be less than 0.For example, let there be 9 mushrooms on a path initially. The number of mushrooms that can be collected from the path is 9, 8, 6 and 3 when Ralph passes by from first to fourth time. From the fifth time and later Ralph can't collect any mushrooms from the path (but still can pass it).Ralph decided to start from the tree s. How many mushrooms can he collect using only described paths?InputThe first line contains two integers n and m (1 ≀ n ≀ 106, 0 ≀ m ≀ 106), representing the number of trees and the number of directed paths in the Mushroom Forest, respectively.Each of the following m lines contains three integers x, y and w (1 ≀ x, y ≀ n, 0 ≀ w ≀ 108), denoting a path that leads from tree x to tree y with w mushrooms initially. There can be paths that lead from a tree to itself, and multiple paths between the same pair of trees.The last line contains a single integer s (1 ≀ s ≀ n)Β β€” the starting position of Ralph. OutputPrint an integer denoting the maximum number of the mushrooms Ralph can collect during his route. ExamplesInput2 21 2 42 1 41Output16Input3 31 2 42 3 31 3 81Output8NoteIn the first sample Ralph can pass three times on the circle and collect 4 + 4 + 3 + 3 + 1 + 1 = 16 mushrooms. After that there will be no mushrooms for Ralph to collect.In the second sample, Ralph can go to tree 3 and collect 8 mushrooms on the path from tree 1 to tree 3.
Input2 21 2 42 1 41
Output16
2.5 seconds
512 megabytes
['dp', 'graphs', '*2100']
D. Ralph And His Tour in Binary Countrytime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRalph is in the Binary Country. The Binary Country consists of n cities and (n - 1) bidirectional roads connecting the cities. The roads are numbered from 1 to (n - 1), the i-th road connects the city labeled (here ⌊ xβŒ‹ denotes the x rounded down to the nearest integer) and the city labeled (i + 1), and the length of the i-th road is Li.Now Ralph gives you m queries. In each query he tells you some city Ai and an integer Hi. He wants to make some tours starting from this city. He can choose any city in the Binary Country (including Ai) as the terminal city for a tour. He gains happiness (Hi - L) during a tour, where L is the distance between the city Ai and the terminal city.Ralph is interested in tours from Ai in which he can gain positive happiness. For each query, compute the sum of happiness gains for all such tours.Ralph will never take the same tour twice or more (in one query), he will never pass the same city twice or more in one tour.InputThe first line contains two integers n and m (1 ≀ n ≀ 106, 1 ≀ m ≀ 105).(n - 1) lines follow, each line contains one integer Li (1 ≀ Li ≀ 105), which denotes the length of the i-th road.m lines follow, each line contains two integers Ai and Hi (1 ≀ Ai ≀ n, 0 ≀ Hi ≀ 107).OutputPrint m lines, on the i-th line print one integerΒ β€” the answer for the i-th query.ExamplesInput2 251 82 4Output114Input6 4211322 41 33 21 7Output116328NoteHere is the explanation for the second sample.Ralph's first query is to start tours from city 2 and Hi equals to 4. Here are the options: He can choose city 5 as his terminal city. Since the distance between city 5 and city 2 is 3, he can gain happiness 4 - 3 = 1. He can choose city 4 as his terminal city and gain happiness 3. He can choose city 1 as his terminal city and gain happiness 2. He can choose city 3 as his terminal city and gain happiness 1. Note that Ralph can choose city 2 as his terminal city and gain happiness 4. Ralph won't choose city 6 as his terminal city because the distance between city 6 and city 2 is 5, which leads to negative happiness for Ralph. So the answer for the first query is 1 + 3 + 2 + 1 + 4 = 11.
Input2 251 82 4
Output114
2.5 seconds
512 megabytes
['brute force', 'data structures', 'trees', '*2200']
C. Marco and GCD Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1, a2, ..., an. He remembered that he calculated gcd(ai, ai + 1, ..., aj) for every 1 ≀ i ≀ j ≀ n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.InputThe first line contains a single integer m (1 ≀ m ≀ 1000)Β β€” the size of the set S.The second line contains m integers s1, s2, ..., sm (1 ≀ si ≀ 106)Β β€” the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1 < s2 < ... < sm.OutputIf there is no solution, print a single line containing -1.Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000.In the second line print n integers a1, a2, ..., an (1 ≀ ai ≀ 106)Β β€” the sequence.We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106.If there are multiple solutions, print any of them.ExamplesInput42 4 6 12Output34 6 12Input22 3Output-1NoteIn the first example 2 = gcd(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai, ai + 1, ..., aj) for every 1 ≀ i ≀ j ≀ n.
Input42 4 6 12
Output34 6 12
1 second
256 megabytes
['constructive algorithms', 'math', '*1900']
B. Ralph And His Magic Fieldtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRalph has a magic field which is divided into n × m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or -1.Now Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo 1000000007 = 109 + 7.Note that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity.InputThe only line contains three integers n, m and k (1 ≀ n, m ≀ 1018, k is either 1 or -1).OutputPrint a single number denoting the answer modulo 1000000007.ExamplesInput1 1 -1Output1Input1 3 1Output1Input3 3 -1Output16NoteIn the first example the only way is to put -1 into the only block.In the second example the only way is to put 1 into every block.
Input1 1 -1
Output1
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'math', 'number theory', '*1800']
A. QAQtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). illustration by ηŒ«ε±‹ https://twitter.com/nekoyaliu Bort wants to know how many subsequences "QAQ" are in the string Diamond has given. Note that the letters "QAQ" don't have to be consecutive, but the order of letters should be exact.InputThe only line contains a string of length n (1 ≀ n ≀ 100). It's guaranteed that the string only contains uppercase English letters.OutputPrint a single integerΒ β€” the number of subsequences "QAQ" in the string.ExamplesInputQAQAQYSYIOIWINOutput4InputQAQQQZZYNOIWINOutput3NoteIn the first example there are 4 subsequences "QAQ": "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN", "QAQAQYSYIOIWIN".
InputQAQAQYSYIOIWIN
Output4
1 second
256 megabytes
['brute force', 'dp', '*800']
F. Subtree Minimum Querytime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree consisting of n vertices. Each vertex has a number written on it; number ai is written on vertex i.Let's denote d(i, j) as the distance between vertices i and j in the tree (that is, the number of edges in the shortest path from i to j). Also let's denote the k-blocked subtree of vertex x as the set of vertices y such that both these conditions are met: x is an ancestor of y (every vertex is an ancestor of itself); d(x, y) ≀ k. You are given m queries to the tree. i-th query is represented by two numbers xi and ki, and the answer to this query is the minimum value of aj among such vertices j such that j belongs to ki-blocked subtree of xi.Write a program that would process these queries quickly!Note that the queries are given in a modified way.InputThe first line contains two integers n and r (1 ≀ r ≀ n ≀ 100000) β€” the number of vertices in the tree and the index of the root, respectively.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the numbers written on the vertices.Then n - 1 lines follow, each containing two integers x and y (1 ≀ x, y ≀ n) and representing an edge between vertices x and y. It is guaranteed that these edges form a tree.Next line contains one integer m (1 ≀ m ≀ 106) β€” the number of queries to process.Then m lines follow, i-th line containing two numbers pi and qi, which can be used to restore i-th query (1 ≀ pi, qi ≀ n).i-th query can be restored as follows:Let last be the answer for previous query (or 0 if i = 1). Then xi = ((pi + last) mod n) + 1, and ki = (qi + last) mod n.OutputPrint m integers. i-th of them has to be equal to the answer to i-th query.ExampleInput5 21 3 2 3 52 35 13 44 121 22 3Output25
Input5 21 3 2 3 52 35 13 44 121 22 3
Output25
6 seconds
512 megabytes
['data structures', 'trees', '*2300']
E. Counting Arraystime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met: There are y elements in F, and all of them are integer numbers; . You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two arrays A and B are considered different iff there exists at least one index i (1 ≀ i ≀ y) such that Ai ≠ Bi. Since the answer can be very large, print it modulo 109 + 7.InputThe first line contains one integer q (1 ≀ q ≀ 105) β€” the number of testcases to solve.Then q lines follow, each containing two integers xi and yi (1 ≀ xi, yi ≀ 106). Each of these lines represents a testcase.OutputPrint q integers. i-th integer has to be equal to the number of yi-factorizations of xi modulo 109 + 7.ExampleInput26 34 2Output366NoteIn the second testcase of the example there are six y-factorizations: { - 4,  - 1}; { - 2,  - 2}; { - 1,  - 4}; {1, 4}; {2, 2}; {4, 1}.
Input26 34 2
Output366
3 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'number theory', '*2000']
D. Credit Cardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be Β«-1Β».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!InputThe first line contains two integers n, d (1 ≀ n ≀ 105, 1 ≀ d ≀ 109) β€”the number of days and the money limitation.The second line contains n integer numbers a1, a2, ... an ( - 104 ≀ ai ≀ 104), where ai represents the transaction in i-th day.OutputPrint -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.ExamplesInput5 10-1 5 0 -5 3Output0Input3 4-10 0 20Output-1Input5 10-5 0 10 -11 0Output2
Input5 10-1 5 0 -5 3
Output0
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'implementation', '*1900']
C. Rumortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova promised himself that he would never play computer games... But recently Firestorm β€” a well-known game developing company β€” published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.InputThe first line contains two integer numbers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ 105) β€” the number of characters in Overcity and the number of pairs of friends.The second line contains n integer numbers ci (0 ≀ ci ≀ 109) β€” the amount of gold i-th character asks to start spreading the rumor.Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≀ xi, yi ≀ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.OutputPrint one number β€” the minimum amount of gold Vova has to spend in order to finish the quest.ExamplesInput5 22 5 3 4 81 44 5Output10Input10 01 2 3 4 5 6 7 8 9 10Output55Input10 51 6 2 7 3 8 4 9 5 101 23 45 67 89 10Output15NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.
Input5 22 5 3 4 81 44 5
Output10
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', '*1300']
B. Beautiful Divisorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes.Some examples of beautiful numbers: 12 (110); 1102 (610); 11110002 (12010); 1111100002 (49610). More formally, the number is beautiful iff there exists some positive integer k such that the number is equal to (2k - 1) * (2k - 1).Luba has got an integer number n, and she wants to find its greatest beautiful divisor. Help her to find it!InputThe only line of input contains one number n (1 ≀ n ≀ 105) β€” the number Luba has got.OutputOutput one number β€” the greatest beautiful divisor of Luba's number. It is obvious that the answer always exists.ExamplesInput3Output1Input992Output496
Input3
Output1
2 seconds
256 megabytes
['brute force', 'implementation', '*1000']
A. Chess For Threetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex, Bob and Carl will soon participate in a team chess tournament. Since they are all in the same team, they have decided to practise really hard before the tournament. But it's a bit difficult for them because chess is a game for two players, not three.So they play with each other according to following rules: Alex and Bob play the first game, and Carl is spectating; When the game ends, the one who lost the game becomes the spectator in the next game, and the one who was spectating plays against the winner. Alex, Bob and Carl play in such a way that there are no draws.Today they have played n games, and for each of these games they remember who was the winner. They decided to make up a log of games describing who won each game. But now they doubt if the information in the log is correct, and they want to know if the situation described in the log they made up was possible (that is, no game is won by someone who is spectating if Alex, Bob and Carl play according to the rules). Help them to check it!InputThe first line contains one integer n (1 ≀ n ≀ 100) β€” the number of games Alex, Bob and Carl played.Then n lines follow, describing the game log. i-th line contains one integer ai (1 ≀ ai ≀ 3) which is equal to 1 if Alex won i-th game, to 2 if Bob won i-th game and 3 if Carl won i-th game.OutputPrint YES if the situation described in the log was possible. Otherwise print NO.ExamplesInput3112OutputYESInput212OutputNONoteIn the first example the possible situation is: Alex wins, Carl starts playing instead of Bob; Alex wins, Bob replaces Carl; Bob wins. The situation in the second example is impossible because Bob loses the first game, so he cannot win the second one.
Input3112
OutputYES
1 second
256 megabytes
['implementation', '*900']
B. Wrathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j β‰₯ i - Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.InputThe first line contains one integer n (1 ≀ n ≀ 106) β€” the number of guilty people.Second line contains n space-separated integers L1, L2, ..., Ln (0 ≀ Li ≀ 109), where Li is the length of the i-th person's claw.OutputPrint one integer β€” the total number of alive people after the bell rings.ExamplesInput40 1 0 10Output1Input20 0Output2Input101 1 3 0 0 0 2 1 0 3Output3NoteIn first sample the last person kills everyone in front of him.
Input40 1 0 10
Output1
2 seconds
256 megabytes
['greedy', 'implementation', 'two pointers', '*1200']
A. Greedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai  ≀  bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!InputThe first line of the input contains one integer n (2 ≀ n ≀ 100 000)Β β€” number of cola cans.The second line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” volume of remaining cola in cans.The third line contains n space-separated integers that b1, b2, ..., bn (ai ≀ bi ≀ 109) β€” capacities of the cans.OutputPrint "YES" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print "NO" (without quotes).You can print each letter in any case (upper or lower).ExamplesInput23 53 6OutputYESInput36 8 96 10 12OutputNOInput50 0 5 0 01 1 8 10 5OutputYESInput44 1 0 35 2 2 3OutputYESNoteIn the first sample, there are already 2 cans, so the answer is "YES".
Input23 53 6
OutputYES
2 seconds
256 megabytes
['greedy', 'implementation', '*900']
E. Lusttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA false witness that speaketh lies!You are given a sequence containing n integers. There is a variable res that is equal to 0 initially. The following process repeats k times.Choose an index from 1 to n uniformly at random. Name it x. Add to res the multiply of all ai's such that 1 ≀ i ≀ n, but i ≠ x. Then, subtract ax by 1.You have to find expected value of res at the end of the process. It can be proved that the expected value of res can be represented as an irreducible fraction . You have to find .InputThe first line contains two integers n and k (1 ≀ n ≀ 5000, 1 ≀ k ≀ 109) β€” the number of elements and parameter k that is specified in the statement.The second line contains n space separated integers a1, a2, ..., an (0 ≀ ai ≀ 109).OutputOutput a single integerΒ β€” the value .ExamplesInput2 15 5Output5Input1 1080Output10Input2 20 0Output500000003Input9 40 11 12 9 20 7 8 18 2Output169316356
Input2 15 5
Output5
2 seconds
256 megabytes
['combinatorics', 'math', 'matrices', '*3000']
D. Slothtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSloth is bad, mkay? So we decided to prepare a problem to punish lazy guys.You are given a tree, you should count the number of ways to remove an edge from it and then add an edge to it such that the final graph is a tree and has a perfect matching. Two ways of this operation are considered different if their removed edges or their added edges aren't the same. The removed edge and the added edge can be equal.A perfect matching is a subset of edges such that each vertex is an endpoint of exactly one of these edges.InputThe first line contains n (2 ≀ n ≀ 5Β·105)Β β€” the number of vertices.Each of the next n - 1 lines contains two integers a and b (1 ≀ a, b ≀ n)Β β€” the endpoints of one edge. It's guaranteed that the graph is a tree.OutputOutput a single integerΒ β€” the answer to the problem.ExamplesInput41 22 33 4Output8Input51 22 33 43 5Output0Input81 22 33 41 55 66 71 8Output22NoteIn first sample, there are 8 ways: edge between 2 and 3 turns to edge between 1 and 3, edge between 2 and 3 turns to edge between 1 and 4, edge between 2 and 3 turns to edge between 2 and 3, edge between 2 and 3 turns to edge between 2 and 4, edge between 1 and 2 turns to edge between 1 and 2, edge between 1 and 2 turns to edge between 1 and 4, edge between 3 and 4 turns to edge between 1 and 4, edge between 3 and 4 turns to edge between 3 and 4.
Input41 22 33 4
Output8
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graph matchings', 'trees', '*3100']
C. Envytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a connected undirected weighted graph G, MST (minimum spanning tree) is a subgraph of G that contains all of G's vertices, is a tree, and sum of its edges is minimum possible.You are given a graph G. If you run a MST algorithm on graph it would give you only one MST and it causes other edges to become jealous. You are given some queries, each query contains a set of edges of graph G, and you should determine whether there is a MST containing all these edges or not.InputThe first line contains two integers n, m (2  ≀ n, m  ≀ 5Β·105, n - 1 ≀ m)Β β€” the number of vertices and edges in the graph and the number of queries.The i-th of the next m lines contains three integers ui, vi, wi (ui ≠ vi, 1 ≀ wi ≀ 5Β·105)Β β€” the endpoints and weight of the i-th edge. There can be more than one edges between two vertices. It's guaranteed that the given graph is connected.The next line contains a single integer q (1 ≀ q ≀ 5Β·105)Β β€” the number of queries.q lines follow, the i-th of them contains the i-th query. It starts with an integer ki (1 ≀ ki ≀ n - 1)Β β€” the size of edges subset and continues with ki distinct space-separated integers from 1 to mΒ β€” the indices of the edges. It is guaranteed that the sum of ki for 1 ≀ i ≀ q does not exceed 5Β·105.OutputFor each query you should print "YES" (without quotes) if there's a MST containing these edges and "NO" (of course without quotes again) otherwise.ExampleInput5 71 2 21 3 22 3 12 4 13 4 13 5 24 5 242 3 43 3 4 52 1 72 1 2OutputYESNOYESNONoteThis is the graph of sample: Weight of minimum spanning tree on this graph is 6.MST with edges (1, 3, 4, 6), contains all of edges from the first query, so answer on the first query is "YES".Edges from the second query form a cycle of length 3, so there is no spanning tree including these three edges. Thus, answer is "NO".
Input5 71 2 21 3 22 3 12 4 13 4 13 5 24 5 242 3 43 3 4 52 1 72 1 2
OutputYESNOYESNO
2 seconds
256 megabytes
['data structures', 'dsu', 'graphs', '*2300']
B. Gluttonytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≀ xi ≀ n, 0 < k < n) the sums of elements on that positions in a and b are different, i.Β e. InputThe first line contains one integer n (1 ≀ n ≀ 22)Β β€” the size of the array.The second line contains n space-separated distinct integers a1, a2, ..., an (0 ≀ ai ≀ 109)Β β€” the elements of the array.OutputIf there is no such array b, print -1.Otherwise in the only line print n space-separated integers b1, b2, ..., bn. Note that b must be a permutation of a.If there are multiple answers, print any of them.ExamplesInput21 2Output2 1 Input41000 100 10 1Output100 1 1000 10NoteAn array x is a permutation of y, if we can shuffle elements of y such that it will coincide with x.Note that the empty subset and the subset containing all indices are not counted.
Input21 2
Output2 1
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*2000']
A. Pridetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the greatest common divisor.What is the minimum number of operations you need to make all of the elements equal to 1?InputThe first line of the input contains one integer n (1 ≀ n ≀ 2000) β€” the number of elements in the array.The second line contains n space separated integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the elements of the array.OutputPrint -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.ExamplesInput52 2 3 4 6Output5Input42 4 6 8Output-1Input32 6 9Output4NoteIn the first sample you can turn all numbers to 1 using the following 5 moves: [2, 2, 3, 4, 6]. [2, 1, 3, 4, 6] [2, 1, 3, 1, 6] [2, 1, 1, 1, 6] [1, 1, 1, 1, 6] [1, 1, 1, 1, 1] We can prove that in this case it is not possible to make all numbers one using less than 5 moves.
Input52 2 3 4 6
Output5
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'math', 'number theory', '*1500']
E. Mod Mod Modtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of integers a1, a2, ..., an. Let , and for 1 ≀ i < n. Here, denotes the modulus operation. Find the maximum value of f(x, 1) over all nonnegative integers x. InputThe first line contains a single integer n (1 ≀ n ≀ 200000)Β β€” the length of the sequence.The second lines contains n integers a1, a2, ..., an (1 ≀ ai ≀ 1013)Β β€” the elements of the sequence.OutputOutput a single integerΒ β€” the maximum value of f(x, 1) over all nonnegative integers x.ExamplesInput210 5Output13Input55 4 3 2 1Output6Input45 10 5 10Output16NoteIn the first example you can choose, for example, x = 19.In the second example you can choose, for example, x = 3 or x = 2.
Input210 5
Output13
2 seconds
256 megabytes
['binary search', 'dp', 'math', '*3000']
G. Xor-MSTtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a complete undirected graph with n vertices. A number ai is assigned to each vertex, and the weight of an edge between vertices i and j is equal to ai xor aj.Calculate the weight of the minimum spanning tree in this graph.InputThe first line contains n (1 ≀ n ≀ 200000) β€” the number of vertices in the graph.The second line contains n integers a1, a2, ..., an (0 ≀ ai < 230) β€” the numbers assigned to the vertices.OutputPrint one number β€” the weight of the minimum spanning tree in the graph.ExamplesInput51 2 3 4 5Output8Input41 2 3 4Output8
Input51 2 3 4 5
Output8
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'data structures', '*2300']
F. Connecting Verticestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with each other (directly or indirectly).But there are some restrictions. Firstly, some pairs of points cannot be connected directly and have to be connected undirectly. Secondly, the segments you draw must not intersect in any point apart from the marked points (that is, if any two segments intersect and their intersection is not a marked point, then the picture you have drawn is invalid).How many ways are there to connect all vertices with n - 1 segments? Two ways are considered different iff there exist some pair of points such that a segment is drawn between them in the first way of connection, but it is not drawn between these points in the second one. Since the answer might be large, output it modulo 109 + 7.InputThe first line contains one number n (3 ≀ n ≀ 500) β€” the number of marked points.Then n lines follow, each containing n elements. ai, j (j-th element of line i) is equal to 1 iff you can connect points i and j directly (otherwise ai, j = 0). It is guaranteed that for any pair of points ai, j = aj, i, and for any point ai, i = 0.OutputPrint the number of ways to connect points modulo 109 + 7.ExamplesInput30 0 10 0 11 1 0Output1Input40 1 1 11 0 1 11 1 0 11 1 1 0Output12Input30 0 00 0 10 1 0Output0
Input30 0 10 0 11 1 0
Output1
4 seconds
256 megabytes
['dp', 'graphs', '*2500']
E. Maximum Subsequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers, and additionally an integer m. You have to choose some sequence of indices b1, b2, ..., bk (1 ≀ b1 < b2 < ... < bk ≀ n) in such a way that the value of is maximized. Chosen sequence can be empty.Print the maximum possible value of .InputThe first line contains two integers n and m (1 ≀ n ≀ 35, 1 ≀ m ≀ 109).The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109).OutputPrint the maximum possible value of .ExamplesInput4 45 2 4 1Output3Input3 20199 41 299Output19NoteIn the first example you can choose a sequence b = {1, 2}, so the sum is equal to 7 (and that's 3 after taking it modulo 4).In the second example you can choose a sequence b = {3}.
Input4 45 2 4 1
Output3
1 second
256 megabytes
['bitmasks', 'divide and conquer', 'meet-in-the-middle', '*1800']
D. Almost Identity Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array.Let's call a permutation an almost identity permutation iff there exist at least n - k indices i (1 ≀ i ≀ n) such that pi = i.Your task is to count the number of almost identity permutations for given numbers n and k.InputThe first line contains two integers n and k (4 ≀ n ≀ 1000, 1 ≀ k ≀ 4).OutputPrint the number of almost identity permutations for given n and k.ExamplesInput4 1Output1Input4 2Output7Input5 3Output31Input5 4Output76
Input4 1
Output1
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*1600']
C. K-Dominant Charactertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of lowercase Latin letters. Character c is called k-dominant iff each substring of s with length at least k contains this character c.You have to find minimum k such that there exists at least one k-dominant character.InputThe first line contains string s consisting of lowercase Latin letters (1 ≀ |s| ≀ 100000).OutputPrint one number β€” the minimum value of k such that there exists at least one k-dominant character.ExamplesInputabacabaOutput2InputzzzzzOutput1InputabcdeOutput3
Inputabacaba
Output2
2 seconds
256 megabytes
['binary search', 'implementation', 'two pointers', '*1400']
B. Buggy Robottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0, 0). The robot can process commands. There are four types of commands it can perform: U β€” move from the cell (x, y) to (x, y + 1); D β€” move from (x, y) to (x, y - 1); L β€” move from (x, y) to (x - 1, y); R β€” move from (x, y) to (x + 1, y). Ivan entered a sequence of n commands, and the robot processed it. After this sequence the robot ended up in the starting cell (0, 0), but Ivan doubts that the sequence is such that after performing it correctly the robot ends up in the same cell. He thinks that some commands were ignored by robot. To acknowledge whether the robot is severely bugged, he needs to calculate the maximum possible number of commands that were performed correctly. Help Ivan to do the calculations!InputThe first line contains one number n β€” the length of sequence of commands entered by Ivan (1 ≀ n ≀ 100).The second line contains the sequence itself β€” a string consisting of n characters. Each character can be U, D, L or R.OutputPrint the maximum possible number of commands from the sequence the robot could perform to end up in the starting cell.ExamplesInput4LDUROutput4Input5RRRUUOutput0Input6LLRRRROutput4
Input4LDUR
Output4
2 seconds
256 megabytes
['greedy', '*1000']
A. Local Extrematime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have only one neighbour each, they are neither local minima nor local maxima.An element is called a local extremum iff it is either local maximum or local minimum. Your task is to calculate the number of local extrema in the given array.InputThe first line contains one integer n (1 ≀ n ≀ 1000) β€” the number of elements in array a.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 1000) β€” the elements of array a.OutputPrint the number of local extrema in the given array.ExamplesInput31 2 3Output0Input41 5 2 5Output2
Input31 2 3
Output0
1 second
256 megabytes
['brute force', 'implementation', '*800']
F. Row of Modelstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDuring the final part of fashion show all models come to the stage and stay in one row and fashion designer stays to right to model on the right. During the rehearsal, Izabella noticed, that row isn't nice, but she can't figure out how to fix it. Like many other creative people, Izabella has a specific sense of beauty. Evaluating beauty of row of models Izabella looks at heights of models. She thinks that row is nice if for each model distance to nearest model with less height (model or fashion designer) to the right of her doesn't exceed k (distance between adjacent people equals 1, the distance between people with exactly one man between them equals 2, etc). She wants to make row nice, but fashion designer has his own sense of beauty, so she can at most one time select two models from the row and swap their positions if the left model from this pair is higher than the right model from this pair.Fashion designer (man to the right of rightmost model) has less height than all models and can't be selected for exchange.You should tell if it's possible to make at most one exchange in such a way that row becomes nice for Izabella. InputIn first line there are two integers n and k (1 ≀ n ≀ 5Β·105, 1 ≀ k ≀ n)Β β€” number of models and required distance.Second line contains n space-separated integers ai (1 ≀ ai ≀ 109)Β β€” height of each model. Pay attention that height of fashion designer is not given and can be less than 1.OutputPrint Β«YESΒ» (without quotes) if it's possible to make row nice using at most one exchange, and Β«NOΒ» (without quotes) otherwise.ExamplesInput5 42 3 5 2 5OutputNOInput5 23 6 2 2 1OutputYESInput5 25 3 6 5 2OutputYES
Input5 42 3 5 2 5
OutputNO
2 seconds
512 megabytes
['greedy', 'sortings', '*2500']
E. Little Brothertime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMasha's little brother draw two points on a sheet of paper. After that, he draws some circles and gave the sheet to his sister. Masha has just returned from geometry lesson so she instantly noticed some interesting facts about brother's drawing.At first, the line going through two points, that brother drew, doesn't intersect or touch any circle.Also, no two circles intersect or touch, and there is no pair of circles such that one circle is located inside another.Moreover, for each circle, Masha drew a square of the minimal area with sides parallel axis such that this circle is located inside the square and noticed that there is no two squares intersect or touch and there is no pair of squares such that one square is located inside other.Now Masha wants to draw circle of minimal possible radius such that it goes through two points that brother drew and doesn't intersect any other circle, but other circles can touch Masha's circle and can be located inside it.It's guaranteed, that answer won't exceed 1012. It should be held for hacks as well.InputFirst line contains four integers x1, y1, x2, y2 ( - 105 ≀ x1, y1, x2, y2 ≀ 105)Β β€” coordinates of points that brother drew. First point has coordinates (x1, y1) and second point has coordinates (x2, y2). These two points are different.The second line contains single integer n (1 ≀ n ≀ 105)Β β€” the number of circles that brother drew.Next n lines contains descriptions of circles. Each line contains three integers xi, yi, ri ( - 105 ≀ xi, yi ≀ 105, 1 ≀ ri ≀ 105) describing circle with center (xi, yi) and radius ri.OutputOutput smallest real number, that it's possible to draw a circle with such radius through given points in such a way that it doesn't intersect other circles.The output is considered correct if it has a relative or absolute error of at most 10 - 4.ExamplesInput2 4 7 1333 0 112 4 2-4 14 2Output5.1478150705Input-2 3 10 -1027 0 3-5 -5 2Output9.1481831923Note
Input2 4 7 1333 0 112 4 2-4 14 2
Output5.1478150705
3 seconds
512 megabytes
['binary search', 'geometry', 'sortings', '*2800']
D. Ratings and Reality Showstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two main kinds of events in the life of top-model: fashion shows and photo shoots. Participating in any of these events affects the rating of appropriate top-model. After each photo shoot model's rating increases by a and after each fashion show decreases by b (designers do too many experiments nowadays). Moreover, sometimes top-models participates in talk shows. After participating in talk show model becomes more popular and increasing of her rating after photo shoots become c and decreasing of her rating after fashion show becomes d.Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will never become negative. Help her to find a suitable moment for participating in the talk show. Let's assume that model's career begins in moment 0. At that moment Izabella's rating was equal to start. If talk show happens in moment t if will affect all events in model's life in interval of time [t..t + len) (including t and not including t + len), where len is duration of influence.Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will not become become negative before talk show or during period of influence of talk show. Help her to find a suitable moment for participating in the talk show. InputIn first line there are 7 positive integers n, a, b, c, d, start, len (1 ≀ n ≀ 3Β·105, 0 ≀ start ≀ 109, 1 ≀ a, b, c, d, len ≀ 109), where n is a number of fashion shows and photo shoots, a, b, c and d are rating changes described above, start is an initial rating of model and len is a duration of influence of talk show.In next n lines descriptions of events are given. Each of those lines contains two integers ti and qi (1 ≀ ti ≀ 109, 0 ≀ q ≀ 1)Β β€” moment, in which event happens and type of this event. Type 0 corresponds to the fashion show and type 1Β β€” to photo shoot. Events are given in order of increasing ti, all ti are different.OutputPrint one non-negative integer tΒ β€” the moment of time in which talk show should happen to make Izabella's rating non-negative before talk show and during period of influence of talk show. If there are multiple answers print smallest of them. If there are no such moments, print  - 1.ExamplesInput5 1 1 1 4 0 51 12 13 14 05 0Output6Input1 1 2 1 2 1 21 0Output-1
Input5 1 1 1 4 0 51 12 13 14 05 0
Output6
2 seconds
256 megabytes
['data structures', 'two pointers', '*2400']
C. Solution for Cubetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the breaks between competitions, top-model Izabella tries to develop herself and not to be bored. For example, now she tries to solve Rubik's cube 2x2x2.It's too hard to learn to solve Rubik's cube instantly, so she learns to understand if it's possible to solve the cube in some state using 90-degrees rotation of one face of the cube in any direction.To check her answers she wants to use a program which will for some state of cube tell if it's possible to solve it using one rotation, described above.Cube is called solved if for each face of cube all squares on it has the same color.https://en.wikipedia.org/wiki/Rubik's_CubeInputIn first line given a sequence of 24 integers ai (1 ≀ ai ≀ 6), where ai denotes color of i-th square. There are exactly 4 occurrences of all colors in this sequence.OutputPrint Β«YESΒ» (without quotes) if it's possible to solve cube using one rotation and Β«NOΒ» (without quotes) otherwise.ExamplesInput2 5 4 6 1 3 6 2 5 5 1 2 3 5 3 1 1 2 4 6 6 4 3 4OutputNOInput5 3 5 3 2 5 2 5 6 2 6 2 4 4 4 4 1 1 1 1 6 3 6 3OutputYESNoteIn first test case cube looks like this: In second test case cube looks like this: It's possible to solve cube by rotating face with squares with numbers 13, 14, 15, 16.
Input2 5 4 6 1 3 6 2 5 5 1 2 3 5 3 1 1 2 4 6 6 4 3 4
OutputNO
2 seconds
256 megabytes
['brute force', 'implementation', '*1500']
B. Cubes for Mashatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAbsent-minded Masha got set of n cubes for her birthday.At each of 6 faces of each cube, there is exactly one digit from 0 to 9. Masha became interested what is the largest natural x such she can make using her new cubes all integers from 1 to x.To make a number Masha can rotate her cubes and put them in a row. After that, she looks at upper faces of cubes from left to right and reads the number.The number can't contain leading zeros. It's not required to use all cubes to build a number.Pay attention: Masha can't make digit 6 from digit 9 and vice-versa using cube rotations.InputIn first line integer n is given (1 ≀ n ≀ 3)Β β€” the number of cubes, Masha got for her birthday.Each of next n lines contains 6 integers aij (0 ≀ aij ≀ 9)Β β€” number on j-th face of i-th cube.OutputPrint single integerΒ β€” maximum number x such Masha can make any integers from 1 to x using her cubes or 0 if Masha can't make even 1.ExamplesInput30 1 2 3 4 56 7 8 9 0 12 3 4 5 6 7Output87Input30 1 3 5 6 81 2 4 5 7 82 3 4 6 7 9Output98NoteIn the first test case, Masha can build all numbers from 1 to 87, but she can't make 88 because there are no two cubes with digit 8.
Input30 1 2 3 4 56 7 8 9 0 12 3 4 5 6 7
Output87
1 second
256 megabytes
['brute force', 'implementation', '*1300']
A. Div. 64time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTop-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills.Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisible by 64, in the binary numerical system.InputIn the only line given a non-empty binary string s with length up to 100.OutputPrint Β«yesΒ» (without quotes) if it's possible to remove digits required way and Β«noΒ» otherwise.ExamplesInput100010001OutputyesInput100OutputnoNoteIn the first test case, you can get string 1 000 000 after removing two ones which is a representation of number 64 in the binary numerical system.You can read more about binary numeral system representation here: https://en.wikipedia.org/wiki/Binary_system
Input100010001
Outputyes
1 second
256 megabytes
['implementation', '*1000']
F. Symmetric Projectionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of n points on the plane. A line containing the origin is called good, if projection of the given set to this line forms a symmetric multiset of points. Find the total number of good lines.Multiset is a set where equal elements are allowed.Multiset is called symmetric, if there is a point P on the plane such that the multiset is centrally symmetric in respect of point P.InputThe first line contains a single integer n (1 ≀ n ≀ 2000) β€” the number of points in the set.Each of the next n lines contains two integers xi and yi ( - 106  ≀  xi,  yi  ≀  106) β€” the coordinates of the points. It is guaranteed that no two points coincide.OutputIf there are infinitely many good lines, print -1.Otherwise, print single integerΒ β€” the number of good lines.ExamplesInput31 22 13 3Output3Input24 31 2Output-1NotePicture to the first sample test: In the second sample, any line containing the origin is good.
Input31 22 13 3
Output3
2 seconds
256 megabytes
['geometry', '*2900']
E. Maximum Elementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Petya was solving a very interesting problem. But although he used many optimization techniques, his solution still got Time limit exceeded verdict. Petya conducted a thorough analysis of his program and found out that his function for finding maximum element in an array of n positive integers was too slow. Desperate, Petya decided to use a somewhat unexpected optimization using parameter k, so now his function contains the following code:int fast_max(int n, int a[]) { int ans = 0; int offset = 0; for (int i = 0; i < n; ++i) if (ans < a[i]) { ans = a[i]; offset = 0; } else { offset = offset + 1; if (offset == k) return ans; } return ans;}That way the function iteratively checks array elements, storing the intermediate maximum, and if after k consecutive iterations that maximum has not changed, it is returned as the answer.Now Petya is interested in fault rate of his function. He asked you to find the number of permutations of integers from 1 to n such that the return value of his function on those permutations is not equal to n. Since this number could be very big, output the answer modulo 109 + 7.InputThe only line contains two integers n and k (1 ≀ n, k ≀ 106), separated by a spaceΒ β€” the length of the permutations and the parameter k.OutputOutput the answer to the problem modulo 109 + 7.ExamplesInput5 2Output22Input5 3Output6Input6 3Output84NotePermutations from second example: [4, 1, 2, 3, 5], [4, 1, 3, 2, 5], [4, 2, 1, 3, 5], [4, 2, 3, 1, 5], [4, 3, 1, 2, 5], [4, 3, 2, 1, 5].
Input5 2
Output22
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*2400']
D. Restoration of stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring.You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Restore the non-empty good string with minimum length. If several such strings exist, restore lexicographically minimum string. If there are no good strings, print "NO" (without quotes).A substring of a string is a contiguous subsequence of letters in the string. For example, "ab", "c", "abc" are substrings of string "abc", while "ac" is not a substring of that string.The number of occurrences of a substring in a string is the number of starting positions in the string where the substring occurs. These occurrences could overlap.String a is lexicographically smaller than string b, if a is a prefix of b, or a has a smaller letter at the first position where a and b differ.InputThe first line contains integer n (1 ≀ n ≀ 105)Β β€” the number of strings in the set.Each of the next n lines contains a non-empty string consisting of lowercase English letters. It is guaranteed that the strings are distinct.The total length of the strings doesn't exceed 105.OutputPrint the non-empty good string with minimum length. If several good strings exist, print lexicographically minimum among them. Print "NO" (without quotes) if there are no good strings.ExamplesInput4mailailrucfOutputcfmailruInput3kekpreceqcheburekOutputNONoteOne can show that in the first sample only two good strings with minimum length exist: "cfmailru" and "mailrucf". The first string is lexicographically minimum.
Input4mailailrucf
Outputcfmailru
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'implementation', '*2000']
C. Petya and Catacombstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute i, he makes a note in his logbook with number ti: If Petya has visited this room before, he writes down the minute he was in this room last time; Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute i. Initially, Petya was in one of the rooms at minute 0, he didn't write down number t0.At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?InputThe first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” then number of notes in Petya's logbook.The second line contains n non-negative integers t1, t2, ..., tn (0 ≀ ti < i) β€” notes in the logbook.OutputIn the only line print a single integer β€” the minimum possible number of rooms in Paris catacombs.ExamplesInput20 0Output2Input50 1 0 1 3Output3NoteIn the first sample, sequence of rooms Petya visited could be, for example 1 → 1 → 2, 1 → 2 → 1 or 1 → 2 → 3. The minimum possible number of rooms is 2.In the second sample, the sequence could be 1 → 2 → 3 → 1 → 2 → 1.
Input20 0
Output2
1 second
256 megabytes
['dsu', 'greedy', 'implementation', 'trees', '*1300']
B. Vlad and Cafestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.InputIn first line there is one integer n (1 ≀ n ≀ 2Β·105)Β β€” number of cafes indices written by Vlad.In second line, n numbers a1, a2, ..., an (0 ≀ ai ≀ 2Β·105) are writtenΒ β€” indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.OutputPrint one integerΒ β€” index of the cafe that Vlad hasn't visited for as long as possible.ExamplesInput51 3 2 1 2Output3Input62 1 2 2 4 1Output2NoteIn first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer. In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes.
Input51 3 2 1 2
Output3
2 seconds
256 megabytes
['*1000']
A. ACM ICPCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a small but very proud high school it was decided to win ACM ICPC. This goal requires to compose as many teams of three as possible, but since there were only 6 students who wished to participate, the decision was to build exactly two teams.After practice competition, participant number i got a score of ai. Team score is defined as sum of scores of its participants. High school management is interested if it's possible to build two teams with equal scores. Your task is to answer that question.InputThe single line contains six integers a1, ..., a6 (0 ≀ ai ≀ 1000) β€” scores of the participantsOutputPrint "YES" (quotes for clarity), if it is possible to build teams with equal score, and "NO" otherwise.You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").ExamplesInput1 3 2 1 2 1OutputYESInput1 1 1 1 1 99OutputNONoteIn the first sample, first team can be composed of 1st, 2nd and 6th participant, second β€” of 3rd, 4th and 5th: team scores are 1 + 3 + 1 = 2 + 1 + 2 = 5.In the second sample, score of participant number 6 is too high: his team score will be definitely greater.
Input1 3 2 1 2 1
OutputYES
2 seconds
256 megabytes
['brute force', '*1000']
F. Anti-Palindromizetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string a of length m is called antipalindromic iff m is even, and for each i (1 ≀ i ≀ m) ai ≠ am - i + 1.Ivan has a string s consisting of n lowercase Latin letters; n is even. He wants to form some string t that will be an antipalindromic permutation of s. Also Ivan has denoted the beauty of index i as bi, and the beauty of t as the sum of bi among all indices i such that si = ti.Help Ivan to determine maximum possible beauty of t he can get.InputThe first line contains one integer n (2 ≀ n ≀ 100, n is even) β€” the number of characters in s.The second line contains the string s itself. It consists of only lowercase Latin letters, and it is guaranteed that its letters can be reordered to form an antipalindromic string.The third line contains n integer numbers b1, b2, ..., bn (1 ≀ bi ≀ 100), where bi is the beauty of index i.OutputPrint one number β€” the maximum possible beauty of t.ExamplesInput8abacabac1 1 1 1 1 1 1 1Output8Input8abaccaba1 2 3 4 5 6 7 8Output26Input8abacabca1 2 3 4 4 3 2 1Output17
Input8abacabac1 1 1 1 1 1 1 1
Output8
2 seconds
256 megabytes
['flows', 'graphs', 'greedy', '*2500']
E. Binary Matrixtime limit per test3 secondsmemory limit per test16 megabytesinputstandard inputoutputstandard outputYou are given a matrix of size n × m. Each element of the matrix is either 1 or 0. You have to determine the number of connected components consisting of 1's. Two cells belong to the same component if they have a common border, and both elements in these cells are 1's.Note that the memory limit is unusual!InputThe first line contains two numbers n and m (1 ≀ n ≀ 212, 4 ≀ m ≀ 214) β€” the number of rows and columns, respectively. It is guaranteed that m is divisible by 4.Then the representation of matrix follows. Each of n next lines contains one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from 0 to 9 or as uppercase Latin letters from A to F). Binary representation of each of these numbers denotes next 4 elements of the matrix in the corresponding row. For example, if the number B is given, then the corresponding elements are 1011, and if the number is 5, then the corresponding elements are 0101.Elements are not separated by whitespaces.OutputPrint the number of connected components consisting of 1's. ExamplesInput3 41A8Output3Input2 85FE3Output2Input1 40Output0NoteIn the first example the matrix is: 000110101000It is clear that it has three components.The second example: 0101111111100011It is clear that the number of components is 2.There are no 1's in the third example, so the answer is 0.
Input3 41A8
Output3
3 seconds
16 megabytes
['dsu', '*2500']