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. The Same Calendartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe girl Taylor has a beautiful calendar for the year y. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.The calendar is so beautiful that she wants to know what is the next year after y when the calendar will be exactly the same. Help Taylor to find that year.Note that leap years has 366 days. The year is leap if it is divisible by 400 or it is divisible by 4, but not by 100 (https://en.wikipedia.org/wiki/Leap_year).InputThe only line contains integer y (1000 ≀ y < 100'000) β€” the year of the calendar.OutputPrint the only integer y' β€” the next year after y when the calendar will be the same. Note that you should find the first year after y with the same calendar.ExamplesInput2016Output2044Input2000Output2028Input50501Output50507NoteToday is Monday, the 13th of June, 2016.
Input2016
Output2044
1 second
256 megabytes
['implementation', '*1600']
A. Johny Likes Numberstime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.InputThe only line contains two integers n and k (1 ≀ n, k ≀ 109).OutputPrint the smallest integer x > n, so it is divisible by the number k.ExamplesInput5 3Output6Input25 13Output26Input26 13Output39
Input5 3
Output6
0.5 seconds
256 megabytes
['implementation', 'math', '*800']
E. Vanya and Balloonstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVanya plays a game of balloons on the field of size n × n, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:**o****o**ooooo**o****o**oro***o*o*o***o***o*o*o***oFormally, the cross is given by three integers r, c and d, such that d ≀ r, c ≀ n - d + 1. The normal cross consists of balloons located in cells (x, y) (where x stay for the number of the row and y for the number of the column), such that |x - r|Β·|y - c| = 0 and |x - r| + |y - c| < d. Rotated cross consists of balloons located in cells (x, y), such that |x - r| = |y - c| and |x - r| < d.Vanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo 109 + 7.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 1000)Β β€” the number of rows and columns in the table with balloons.The each of the following n lines contains n characters '0', '1', '2' or '3'Β β€” the description of the values in balloons.OutputPrint the maximum possible product modulo 109 + 7. Note, that you are not asked to maximize the remainder modulo 109 + 7, but to find the maximum value and print it this modulo.ExamplesInput41233021320200303Output108Input50030000300333330030000300Output19683Input50000302030003000302030000Output108Input52131210003100021000323231Output3Input51213112111121122131121212Output24NoteIn the first sample, the maximum product is achieved for a rotated cross with a center in the cell (3, 3) and radius 1: 2Β·2Β·3Β·3Β·3 = 108.
Input41233021320200303
Output108
3 seconds
512 megabytes
['binary search', 'brute force', 'dp', 'implementation', '*2300']
D. Vanya and Treasuretime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya is in the palace that can be represented as a grid n × m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type aij. Each chest of type x ≀ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (r1, c1) (the cell in the row r1 and column c1) and (r2, c2) is equal to |r1 - r2| + |c1 - c2|.InputThe first line of the input contains three integers n, m and p (1 ≀ n, m ≀ 300, 1 ≀ p ≀ nΒ·m)Β β€” the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively.Each of the following n lines contains m integers aij (1 ≀ aij ≀ p)Β β€” the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that arc = x). Also, it's guaranteed that there is exactly one chest of type p.OutputPrint one integerΒ β€” the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p.ExamplesInput3 4 32 1 1 11 1 1 12 1 1 3Output5Input3 3 91 3 58 9 74 6 2Output22Input3 4 121 2 3 48 7 6 59 10 11 12Output11
Input3 4 32 1 1 11 1 1 12 1 1 3
Output5
1.5 seconds
256 megabytes
['data structures', 'dp', 'graphs', 'shortest paths', '*2300']
C. Vanya and Labeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bitwise AND is equal to s. As this number can be large, output it modulo 109 + 7.To represent the string as a number in numeral system with base 64 Vanya uses the following rules: digits from '0' to '9' correspond to integers from 0 to 9; letters from 'A' to 'Z' correspond to integers from 10 to 35; letters from 'a' to 'z' correspond to integers from 36 to 61; letter '-' correspond to integer 62; letter '_' correspond to integer 63. InputThe only line of the input contains a single word s (1 ≀ |s| ≀ 100 000), consisting of digits, lowercase and uppercase English letters, characters '-' and '_'.OutputPrint a single integerΒ β€” the number of possible pairs of words, such that their bitwise AND is equal to string s modulo 109 + 7.ExamplesInputzOutput3InputV_VOutput9InputCodeforcesOutput130653412NoteFor a detailed definition of bitwise AND we recommend to take a look in the corresponding article in Wikipedia.In the first sample, there are 3 possible solutions: z&_ = 61&63 = 61 = z _&z = 63&61 = 61 = z z&z = 61&61 = 61 = z
Inputz
Output3
1 second
256 megabytes
['bitmasks', 'combinatorics', 'implementation', 'strings', '*1500']
B. Vanya and Food Processortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens: If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece. Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.InputThe first line of the input contains integers n, h and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ h ≀ 109)Β β€” the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively.The second line contains n integers ai (1 ≀ ai ≀ h)Β β€” the heights of the pieces.OutputPrint a single integerΒ β€” the number of seconds required to smash all the potatoes following the process described in the problem statement.ExamplesInput5 6 35 4 3 2 1Output5Input5 6 35 5 5 5 5Output10Input5 6 31 2 1 1 1Output2NoteConsider the first sample. First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside. Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining. Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second. Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3. During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2Β·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.
Input5 6 35 4 3 2 1
Output5
1 second
256 megabytes
['implementation', 'math', '*1400']
A. Vanya and Fencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?InputThe first line of the input contains two integers n and h (1 ≀ n ≀ 1000, 1 ≀ h ≀ 1000)Β β€” the number of friends and the height of the fence, respectively.The second line contains n integers ai (1 ≀ ai ≀ 2h), the i-th of them is equal to the height of the i-th person.OutputPrint a single integerΒ β€” the minimum possible valid width of the road.ExamplesInput3 74 5 14Output4Input6 11 1 1 1 1 1Output6Input6 57 6 8 9 10 5Output11NoteIn the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.
Input3 74 5 14
Output4
1 second
256 megabytes
['implementation', '*800']
E. The Last Fight Between Human and AItime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet.The following game was chosen for the fights: initially there is a polynomial P(x) = anxn + an - 1xn - 1 + ... + a1x + a0,  with yet undefined coefficients and the integer k. Players alternate their turns. At each turn, a player pick some index j, such that coefficient aj that stay near xj is not determined yet and sets it to any value (integer or real, positive or negative, 0 is also allowed). Computer moves first. The human will be declared the winner if and only if the resulting polynomial will be divisible by Q(x) = x - k.Polynomial P(x) is said to be divisible by polynomial Q(x) if there exists a representation P(x) = B(x)Q(x), where B(x) is also some polynomial.Some moves have been made already and now you wonder, is it true that human can guarantee the victory if he plays optimally?InputThe first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, |k| ≀ 10 000)Β β€” the size of the polynomial and the integer k.The i-th of the following n + 1 lines contain character '?' if the coefficient near xi - 1 is yet undefined or the integer value ai, if the coefficient is already known ( - 10 000 ≀ ai ≀ 10 000). Each of integers ai (and even an) may be equal to 0.Please note, that it's not guaranteed that you are given the position of the game where it's computer's turn to move.OutputPrint "Yes" (without quotes) if the human has winning strategy, or "No" (without quotes) otherwise.ExamplesInput1 2-1?OutputYesInput2 100-1000001OutputYesInput4 5?1?1?OutputNoNoteIn the first sample, computer set a0 to  - 1 on the first move, so if human can set coefficient a1 to 0.5 and win.In the second sample, all coefficients are already set and the resulting polynomial is divisible by x - 100, so the human has won.
Input1 2-1?
OutputYes
1 second
256 megabytes
['math', '*2400']
D. Theseus and labyrinthtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheseus has just arrived to Crete to fight Minotaur. He found a labyrinth that has a form of a rectangular field of size n × m and consists of blocks of size 1 × 1.Each block of the labyrinth has a button that rotates all blocks 90 degrees clockwise. Each block rotates around its center and doesn't change its position in the labyrinth. Also, each block has some number of doors (possibly none). In one minute, Theseus can either push the button in order to rotate all the blocks 90 degrees clockwise or pass to the neighbouring block. Theseus can go from block A to some neighbouring block B only if block A has a door that leads to block B and block B has a door that leads to block A.Theseus found an entrance to labyrinth and is now located in block (xT, yT)Β β€” the block in the row xT and column yT. Theseus know that the Minotaur is hiding in block (xM, yM) and wants to know the minimum number of minutes required to get there.Theseus is a hero, not a programmer, so he asks you to help him.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 1000)Β β€” the number of rows and the number of columns in labyrinth, respectively.Each of the following n lines contains m characters, describing the blocks of the labyrinth. The possible characters are: Β«+Β» means this block has 4 doors (one door to each neighbouring block); Β«-Β» means this block has 2 doorsΒ β€” to the left and to the right neighbours; Β«|Β» means this block has 2 doorsΒ β€” to the top and to the bottom neighbours; Β«^Β» means this block has 1 doorΒ β€” to the top neighbour; Β«>Β» means this block has 1 doorΒ β€” to the right neighbour; Β«<Β» means this block has 1 doorΒ β€” to the left neighbour; Β«vΒ» means this block has 1 doorΒ β€” to the bottom neighbour; Β«LΒ» means this block has 3 doorsΒ β€” to all neighbours except left one; Β«RΒ» means this block has 3 doorsΒ β€” to all neighbours except right one; Β«UΒ» means this block has 3 doorsΒ β€” to all neighbours except top one; Β«DΒ» means this block has 3 doorsΒ β€” to all neighbours except bottom one; Β«*Β» means this block is a wall and has no doors. Left, right, top and bottom are defined from representing labyrinth as a table, where rows are numbered from 1 to n from top to bottom and columns are numbered from 1 to m from left to right.Next line contains two integersΒ β€” coordinates of the block (xT, yT) (1 ≀ xT ≀ n, 1 ≀ yT ≀ m), where Theseus is initially located.Last line contains two integersΒ β€” coordinates of the block (xM, yM) (1 ≀ xM ≀ n, 1 ≀ yM ≀ m), where Minotaur hides.It's guaranteed that both the block where Theseus starts and the block where Minotaur is hiding have at least one door. Theseus and Minotaur may be initially located at the same block.OutputIf Theseus is not able to get to Minotaur, then print -1 in the only line of the output. Otherwise, print the minimum number of minutes required to get to the block where Minotaur is hiding.ExamplesInput2 2+**U1 12 2Output-1Input2 3<><><>1 12 1Output4NoteAssume that Theseus starts at the block (xT, yT) at the moment 0.
Input2 2+**U1 12 2
Output-1
3 seconds
256 megabytes
['graphs', 'implementation', 'shortest paths', '*2000']
C. Vasya and Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHigh school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?InputThe first line of the input contains two integers n and k (1 ≀ n ≀ 100 000, 0 ≀ k ≀ n)Β β€” the length of the string and the maximum number of characters to change.The second line contains the string, consisting of letters 'a' and 'b' only.OutputPrint the only integerΒ β€” the maximum beauty of the string Vasya can achieve by changing no more than k characters.ExamplesInput4 2abbaOutput4Input8 1aabaabaaOutput5NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
Input4 2abba
Output4
1 second
256 megabytes
['binary search', 'dp', 'strings', 'two pointers', '*1500']
B. Pyramid of Glassestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is n. The top level consists of only 1 glass, that stands on 2 glasses on the second level (counting from the top), then 3 glasses on the third level and so on.The bottom level consists of n glasses.Vlad has seen in the movies many times how the champagne beautifully flows from top levels to bottom ones, filling all the glasses simultaneously. So he took a bottle and started to pour it in the glass located at the top of the pyramid.Each second, Vlad pours to the top glass the amount of champagne equal to the size of exactly one glass. If the glass is already full, but there is some champagne flowing in it, then it pours over the edge of the glass and is equally distributed over two glasses standing under. If the overflowed glass is at the bottom level, then the champagne pours on the table. For the purpose of this problem we consider that champagne is distributed among pyramid glasses immediately. Vlad is interested in the number of completely full glasses if he stops pouring champagne in t seconds.Pictures below illustrate the pyramid consisting of three levels. InputThe only line of the input contains two integers n and t (1 ≀ n ≀ 10, 0 ≀ t ≀ 10 000)Β β€” the height of the pyramid and the number of seconds Vlad will be pouring champagne from the bottle.OutputPrint the single integerΒ β€” the number of completely full glasses after t seconds.ExamplesInput3 5Output4Input4 8Output6NoteIn the first sample, the glasses full after 5 seconds are: the top glass, both glasses on the second level and the middle glass at the bottom level. Left and right glasses of the bottom level will be half-empty.
Input3 5
Output4
1 second
256 megabytes
['implementation', 'math', 'math', '*1500']
A. Nicholas and Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n.Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance between the minimum and the maximum elements. The distance between two elements is considered to be equal to the absolute difference between their positions.InputThe first line of the input contains a single integer n (2 ≀ n ≀ 100)Β β€” the size of the permutation.The second line of the input contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ n), where ai is equal to the element at the i-th position.OutputPrint a single integerΒ β€” the maximum possible distance between the minimum and the maximum elements Nicholas can achieve by performing exactly one swap.ExamplesInput54 5 1 3 2Output3Input71 6 5 3 4 7 2Output6Input66 5 4 3 2 1Output5NoteIn the first sample, one may obtain the optimal answer by swapping elements 1 and 2.In the second sample, the minimum and the maximum elements will be located in the opposite ends of the array if we swap 7 and 2.In the third sample, the distance between the minimum and the maximum elements is already maximum possible, so we just perform some unnecessary swap, for example, one can swap 5 and 2.
Input54 5 1 3 2
Output3
1 second
256 megabytes
['constructive algorithms', 'implementation', '*800']
E. Trains and Statistictime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station.Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρi, j among all pairs 1 ≀ i < j ≀ n.InputThe first line of the input contains a single integer n (2 ≀ n ≀ 100 000)Β β€” the number of stations.The second line contains n - 1 integer ai (i + 1 ≀ ai ≀ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to ai inclusive.OutputPrint the sum of ρi, j among all pairs of 1 ≀ i < j ≀ n.ExamplesInput44 4 4Output6Input52 3 5 5Output17NoteIn the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.Consider the second sample: ρ1, 2 = 1 ρ1, 3 = 2 ρ1, 4 = 3 ρ1, 5 = 3 ρ2, 3 = 1 ρ2, 4 = 2 ρ2, 5 = 2 ρ3, 4 = 1 ρ3, 5 = 1 ρ4, 5 = 1 Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.
Input44 4 4
Output6
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', '*2300']
D. Tree Constructiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. First element a_1 becomes the root of the tree. Elements a_2, a_3, \ldots, a_n are added one by one. To add element a_i one needs to traverse the tree starting from the root and using the following rules: The pointer to the current node is set to the root. If a_i is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. If at some point there is no required child, the new node is created, it is assigned value a_i and becomes the corresponding child of the current node. InputThe first line of the input contains a single integer n (2 \leq n \leq 100\,000)Β β€” the length of the sequence a.The second line contains n distinct integers a_i (1 \leq a_i \leq 10^9)Β β€” the sequence a itself.OutputOutput n - 1 integers. For all i > 1 print the value written in the node that is the parent of the node with value a_i in it.ExamplesInput31 2 3Output1 2Input54 2 3 1 6Output4 2 2 4
Input31 2 3
Output1 2
2 seconds
256 megabytes
['data structures', 'trees', '*1800']
C. Money Transferstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of banks.The second line contains n integers ai ( - 109 ≀ ai ≀ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.OutputPrint the minimum number of operations required to change balance in each bank to zero.ExamplesInput35 0 -5Output1Input4-1 0 1 0Output2Input41 2 3 -6Output3NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer: transfer 1 from the first bank to the second bank; transfer 3 from the second bank to the third; transfer 6 from the third bank to the fourth.
Input35 0 -5
Output1
1 second
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'sortings', '*2100']
B. Restoring Paintingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya works as a watchman in the gallery. Unfortunately, one of the most expensive paintings was stolen while he was on duty. He doesn't want to be fired, so he has to quickly restore the painting. He remembers some facts about it. The painting is a square 3 × 3, each cell contains a single integer from 1 to n, and different cells may contain either different or equal integers. The sum of integers in each of four squares 2 × 2 is equal to the sum of integers in the top left square 2 × 2. Four elements a, b, c and d are known and are located as shown on the picture below. Help Vasya find out the number of distinct squares the satisfy all the conditions above. Note, that this number may be equal to 0, meaning Vasya remembers something wrong.Two squares are considered to be different, if there exists a cell that contains two different integers in different squares.InputThe first line of the input contains five integers n, a, b, c and d (1 ≀ n ≀ 100 000, 1 ≀ a, b, c, d ≀ n)Β β€” maximum possible value of an integer in the cell and four integers that Vasya remembers.OutputPrint one integerΒ β€” the number of distinct valid squares.ExamplesInput2 1 1 1 2Output2Input3 3 1 2 3Output6NoteBelow are all the possible paintings for the first sample. In the second sample, only paintings displayed below satisfy all the rules.
Input2 1 1 1 2
Output2
1 second
256 megabytes
['brute force', 'constructive algorithms', 'math', '*1400']
A. Infinite Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, there exists a positive integer i, such that si = b. Of course, you are the person he asks for a help.InputThe first line of the input contain three integers a, b and c ( - 109 ≀ a, b, c ≀ 109)Β β€” the first element of the sequence, Vasya's favorite number and the difference between any two neighbouring elements of the sequence, respectively.OutputIf b appears in the sequence s print "YES" (without quotes), otherwise print "NO" (without quotes).ExamplesInput1 7 3OutputYESInput10 10 0OutputYESInput1 -4 5OutputNOInput0 60 50OutputNONoteIn the first sample, the sequence starts from integers 1, 4, 7, so 7 is its element.In the second sample, the favorite integer of Vasya is equal to the first element of the sequence.In the third sample all elements of the sequence are greater than Vasya's favorite integer.In the fourth sample, the sequence starts from 0, 50, 100, and all the following elements are greater than Vasya's favorite integer.
Input1 7 3
OutputYES
1 second
256 megabytes
['math', '*1100']
B. Problems for Roundtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules: Problemset of each division should be non-empty. Each problem should be used in exactly one division (yes, it is unusual requirement). Each problem used in division 1 should be harder than any problem used in division 2. If two problems are similar, they should be used in different divisions. Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k.InputThe first line of the input contains two integers n and m (2 ≀ n ≀ 100 000, 0 ≀ m ≀ 100 000)Β β€” the number of problems prepared for the round and the number of pairs of similar problems, respectively.Each of the following m lines contains a pair of similar problems ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi). It's guaranteed, that no pair of problems meets twice in the input.OutputPrint one integerΒ β€” the number of ways to split problems in two divisions.ExamplesInput5 21 45 2Output2Input3 31 22 31 3Output0Input3 23 13 2Output1NoteIn the first sample, problems 1 and 2 should be used in division 2, while problems 4 and 5 in division 1. Problem 3 may be used either in division 1 or in division 2.In the second sample, all pairs of problems are similar and there is no way to split problem between two divisions without breaking any rules.Third sample reminds you that the similarity relation is not transitive. Problem 3 is similar to both 1 and 2, but 1 is not similar to 2, so they may be used together.
Input5 21 45 2
Output2
2 seconds
256 megabytes
['greedy', 'implementation', '*1300']
A. Bear and Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.You know that there will be n interesting minutes t1, t2, ..., tn. Your task is to calculate for how many minutes Limak will watch the game.InputThe first line of the input contains one integer n (1 ≀ n ≀ 90)Β β€” the number of interesting minutes.The second line contains n integers t1, t2, ..., tn (1 ≀ t1 < t2 < ... tn ≀ 90), given in the increasing order.OutputPrint the number of minutes Limak will watch the game.ExamplesInput37 20 88Output35Input916 20 30 40 50 60 70 80 90Output15Input915 20 30 40 50 60 70 80 90Output90NoteIn the first sample, minutes 21, 22, ..., 35 are all boring and thus Limak will turn TV off immediately after the 35-th minute. So, he would watch the game for 35 minutes.In the second sample, the first 15 minutes are boring.In the third sample, there are no consecutive 15 boring minutes. So, Limak will watch the whole game.
Input37 20 88
Output35
2 seconds
256 megabytes
['implementation', '*800']
B. Different is Goodtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.InputThe first line of the input contains an integer n (1 ≀ n ≀ 100 000)Β β€” the length of the string s.The second line contains the string s of length n consisting of only lowercase English letters.OutputIf it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.ExamplesInput2aaOutput1Input4kokoOutput2Input5muratOutput0NoteIn the first sample one of the possible solutions is to change the first character to 'b'.In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".
Input2aa
Output1
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'strings', '*1000']
A. Summer Camptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to print the n-th digit of this string (digits are numbered starting with 1.InputThe only line of the input contains a single integer n (1 ≀ n ≀ 1000)Β β€” the position of the digit you need to print.OutputPrint the n-th digit of the line.ExamplesInput3Output3Input11Output0NoteIn the first sample the digit at position 3 is '3', as both integers 1 and 2 consist on one digit.In the second sample, the digit at position 11 is '0', it belongs to the integer 10.
Input3
Output3
1 second
256 megabytes
['implementation', '*800']
E. Organizing a Racetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKekoland is a country with n beautiful cities numbered from left to right and connected by n - 1 roads. The i-th road connects cities i and i + 1 and length of this road is wi kilometers. When you drive in Kekoland, each time you arrive in city i by car you immediately receive gi liters of gas. There is no other way to get gas in Kekoland.You were hired by the Kekoland president Keko to organize the most beautiful race Kekoland has ever seen. Let race be between cities l and r (l ≀ r). Race will consist of two stages. On the first stage cars will go from city l to city r. After completing first stage, next day second stage will be held, now racers will go from r to l with their cars. Of course, as it is a race, racers drive directly from start city to finish city. It means that at the first stage they will go only right, and at the second stage they go only left. Beauty of the race between l and r is equal to r - l + 1 since racers will see r - l + 1 beautiful cities of Kekoland. Cars have infinite tank so racers will take all the gas given to them.At the beginning of each stage racers start the race with empty tank (0 liters of gasoline). They will immediately take their gasoline in start cities (l for the first stage and r for the second stage) right after the race starts. It may not be possible to organize a race between l and r if cars will run out of gas before they reach finish.You have k presents. Each time you give a present to city i its value gi increases by 1. You may distribute presents among cities in any way (also give many presents to one city, each time increasing gi by 1). What is the most beautiful race you can organize?Each car consumes 1 liter of gas per one kilometer.InputThe first line of the input contains two integers n and k (2 ≀ n ≀ 100 000, 0 ≀ k ≀ 109)Β β€” the number of cities in Kekoland and the number of presents you have, respectively.Next line contains n - 1 integers. The i-th of them is wi (1 ≀ wi ≀ 109)Β β€” the length of the road between city i and i + 1. Next line contains n integers. The i-th of them is gi (0 ≀ gi ≀ 109)Β β€” the amount of gas you receive every time you enter city i.OutputPrint a single lineΒ β€” the beauty of the most beautiful race you can organize.ExamplesInput4 42 2 21 1 1 1Output4Input8 52 2 2 3 7 3 11 3 1 5 4 0 2 5Output7NoteIn first sample if you give one present to each city then it will be possible to make a race between city 1 and city 4.In second sample you should add 1 to g5 and 4 to g6, then it will be possible to make a race between cities 2 and 8.
Input4 42 2 21 1 1 1
Output4
3 seconds
256 megabytes
['data structures', 'greedy', '*3300']
D. Roads in Yuslandtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMayor of Yusland just won the lottery and decided to spent money on something good for town. For example, repair all the roads in the town.Yusland consists of n intersections connected by n - 1 bidirectional roads. One can travel from any intersection to any other intersection using only these roads.There is only one road repairing company in town, named "RC company". Company's center is located at the intersection 1. RC company doesn't repair roads you tell them. Instead, they have workers at some intersections, who can repair only some specific paths. The i-th worker can be paid ci coins and then he repairs all roads on a path from ui to some vi that lies on the path from ui to intersection 1. Mayor asks you to choose the cheapest way to hire some subset of workers in order to repair all the roads in Yusland. It's allowed that some roads will be repaired more than once.If it's impossible to repair all roads print  - 1.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 300 000)Β β€” the number of cities in Yusland and the number of workers respectively.Then follow nβˆ’1 line, each of them contains two integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” indices of intersections connected by the i-th road.Last m lines provide the description of workers, each line containing three integers ui, vi and ci (1 ≀ ui, vi ≀ n, 1 ≀ ci ≀ 109). This means that the i-th worker can repair all roads on the path from vi to ui for ci coins. It's guaranteed that vi lies on the path from ui to 1. Note that vi and ui may coincide.OutputIf it's impossible to repair all roads then print  - 1. Otherwise print a single integerΒ β€” minimum cost required to repair all roads using "RC company" workers.ExampleInput6 51 21 33 44 54 62 1 23 1 44 1 35 3 16 3 2Output8NoteIn the first sample, we should choose workers with indices 1, 3, 4 and 5, some roads will be repaired more than once but it is OK. The cost will be equal to 2 + 3 + 1 + 2 = 8 coins.
Input6 51 21 33 44 54 62 1 23 1 44 1 35 3 16 3 2
Output8
4 seconds
256 megabytes
['data structures', 'dp', 'greedy', '*2900']
C. Ultimate Weirdness of an Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYasin has an array a containing n integers. Yasin is a 5 year old, so he loves ultimate weird things.Yasin denotes weirdness of an array as maximum gcd(ai,  aj) value among all 1 ≀ i < j ≀ n. For n ≀ 1 weirdness is equal to 0, gcd(x,  y) is the greatest common divisor of integers x and y.He also defines the ultimate weirdness of an array. Ultimate weirdness is where f(i,  j) is weirdness of the new array a obtained by removing all elements between i and j inclusive, so new array is [a1... ai - 1, aj + 1... an].Since 5 year old boys can't code, Yasin asks for your help to find the value of ultimate weirdness of the given array a!InputThe first line of the input contains a single integer n (1 ≀ n ≀ 200 000)Β β€” the number of elements in a.The next line contains n integers ai (1 ≀ ai ≀ 200 000), where the i-th number is equal to the i-th element of the array a. It is guaranteed that all ai are distinct.OutputPrint a single line containing the value of ultimate weirdness of the array a. ExampleInput32 6 3Output6NoteConsider the first sample. f(1,  1) is equal to 3. f(2,  2) is equal to 1. f(3,  3) is equal to 2. f(1,  2), f(1,  3) and f(2,  3) are equal to 0. Thus the answer is 3 + 0 + 0 + 1 + 0 + 2 = 6.
Input32 6 3
Output6
2 seconds
256 megabytes
['data structures', 'number theory', '*2800']
B. Robin Hoodtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people. After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too. Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.InputThe first line of the input contains two integers n and k (1 ≀ n ≀ 500 000, 0 ≀ k ≀ 109)Β β€” the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.The second line contains n integers, the i-th of them is ci (1 ≀ ci ≀ 109)Β β€” initial wealth of the i-th person.OutputPrint a single line containing the difference between richest and poorest peoples wealth.ExamplesInput4 11 1 4 2Output2Input3 12 2 2Output0NoteLets look at how wealth changes through day in the first sample. [1, 1, 4, 2] [2, 1, 3, 2] or [1, 2, 3, 2] So the answer is 3 - 1 = 2In second sample wealth will remain the same for each person.
Input4 11 1 4 2
Output2
1 second
256 megabytes
['binary search', 'greedy', '*2000']
A. Recycling Bottlestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows: Choose to stop or to continue to collect bottles. If the choice was to continue then choose some bottle and walk towards it. Pick this bottle and walk to the recycling bin. Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin.InputFirst line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≀ ax, ay, bx, by, tx, ty ≀ 109)Β β€” initial positions of Adil, Bera and recycling bin respectively.The second line contains a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of bottles on the ground.Then follow n lines, each of them contains two integers xi and yi (0 ≀ xi, yi ≀ 109)Β β€” position of the i-th bottle.It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct.OutputPrint one real numberΒ β€” the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput3 1 1 2 0 031 12 12 3Output11.084259940083Input5 0 4 2 2 055 23 05 53 53 3Output33.121375178000NoteConsider the first sample.Adil will use the following path: .Bera will use the following path: .Adil's path will be units long, while Bera's path will be units long.
Input3 1 1 2 0 031 12 12 3
Output11.084259940083
2 seconds
256 megabytes
['dp', 'geometry', 'greedy', 'implementation', '*1800']
F. Restore a Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer kΒ β€” the number of digits in n. Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substring of n (a substring of n is a sequence of consecutive digits of the number n).Vasya knows that there may be more than one way to restore the number n. Your task is to find the smallest possible initial integer n. Note that decimal representation of number n contained no leading zeroes, except the case the integer n was equal to zero itself (in this case a single digit 0 was used).InputThe first line of the input contains the string received by Kate. The number of digits in this string does not exceed 1 000 000.The second line contains the substring of n which Vasya remembers. This string can contain leading zeroes. It is guaranteed that the input data is correct, and the answer always exists.OutputPrint the smalles integer n which Vasya could pass to Kate.ExamplesInput003512021Output30021Input19996663330063Output3036366999
Input003512021
Output30021
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'strings', '*2300']
E. Correct Bracket Sequence Editortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS). Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))": 1st bracket is paired with 8th, 2d bracket is paired with 3d, 3d bracket is paired with 2d, 4th bracket is paired with 7th, 5th bracket is paired with 6th, 6th bracket is paired with 5th, 7th bracket is paired with 4th, 8th bracket is paired with 1st. Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported: Β«L» — move the cursor one position to the left, Β«R» — move the cursor one position to the right, Β«D» — delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to). After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted). There are pictures illustrated several usages of operation "D" below. All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.Polycarp is very proud of his development, can you implement the functionality of his editor?InputThe first line contains three positive integers n, m and p (2 ≀ n ≀ 500 000, 1 ≀ m ≀ 500 000, 1 ≀ p ≀ n)Β β€” the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even.It is followed by the string of n characters "(" and ")" forming the correct bracket sequence.Then follow a string of m characters "L", "R" and "D"Β β€” a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.OutputPrint the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.ExamplesInput8 4 5(())()()RDLDOutput()Input12 5 3((()())(()))RRDLDOutput(()(()))Input8 8 8(())()()LLLLLLDDOutput()()NoteIn the first sample the cursor is initially at position 5. Consider actions of the editor: command "R"Β β€” the cursor moves to the position 6 on the right; command "D"Β β€” the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5; command "L"Β β€” the cursor moves to the position 4 on the left; command "D"Β β€” the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1. Thus, the answer is equal to ().
Input8 4 5(())()()RDLD
Output()
2 seconds
256 megabytes
['data structures', 'dsu', 'strings', '*1700']
D2. Magic Powder - 2time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe term of this problem is the same as the previous one, the only exception β€” increased restrictions.InputThe first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109) β€” the number of ingredients and the number of grams of the magic powder.The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie.The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 109), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.OutputPrint the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.ExamplesInput1 100000000011000000000Output2000000000Input10 11000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 10000000001 1 1 1 1 1 1 1 1 1Output0Input3 12 1 411 3 16Output4Input4 34 3 5 611 12 14 20Output3
Input1 100000000011000000000
Output2000000000
1 second
256 megabytes
['binary search', 'implementation', '*1500']
D1. Magic Powder - 1time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs n ingredients, and for each ingredient she knows the value aiΒ β€” how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all n ingredients.Apollinaria has bi gram of the i-th ingredient. Also she has k grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the n ingredients and can be used for baking cookies.Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.InputThe first line of the input contains two positive integers n and k (1 ≀ n, k ≀ 1000)Β β€” the number of ingredients and the number of grams of the magic powder.The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie.The third line contains the sequence b1, b2, ..., bn (1 ≀ bi ≀ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.OutputPrint the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.ExamplesInput3 12 1 411 3 16Output4Input4 34 3 5 611 12 14 20Output3NoteIn the first sample it is profitably for Apollinaria to make the existing 1 gram of her magic powder to ingredient with the index 2, then Apollinaria will be able to bake 4 cookies.In the second sample Apollinaria should turn 1 gram of magic powder to ingredient with the index 1 and 1 gram of magic powder to ingredient with the index 3. Then Apollinaria will be able to bake 3 cookies. The remaining 1 gram of the magic powder can be left, because it can't be used to increase the answer.
Input3 12 1 411 3 16
Output4
1 second
256 megabytes
['binary search', 'brute force', 'implementation', '*1400']
C. Cinematime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMoscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 109.In the evening after the conference, all n scientists decided to go to the cinema. There are m movies in the cinema they came to. Each of the movies is characterized by two distinct numbersΒ β€” the index of audio language and the index of subtitles language. The scientist, who came to the movie, will be very pleased if he knows the audio language of the movie, will be almost satisfied if he knows the language of subtitles and will be not satisfied if he does not know neither one nor the other (note that the audio language and the subtitles language for each movie are always different). Scientists decided to go together to the same movie. You have to help them choose the movie, such that the number of very pleased scientists is maximum possible. If there are several such movies, select among them one that will maximize the number of almost satisfied scientists.InputThe first line of the input contains a positive integer n (1 ≀ n ≀ 200 000)Β β€” the number of scientists.The second line contains n positive integers a1, a2, ..., an (1 ≀ ai ≀ 109), where ai is the index of a language, which the i-th scientist knows.The third line contains a positive integer m (1 ≀ m ≀ 200 000)Β β€” the number of movies in the cinema. The fourth line contains m positive integers b1, b2, ..., bm (1 ≀ bj ≀ 109), where bj is the index of the audio language of the j-th movie.The fifth line contains m positive integers c1, c2, ..., cm (1 ≀ cj ≀ 109), where cj is the index of subtitles language of the j-th movie.It is guaranteed that audio languages and subtitles language are different for each movie, that is bj ≠ cj. OutputPrint the single integerΒ β€” the index of a movie to which scientists should go. After viewing this movie the number of very pleased scientists should be maximum possible. If in the cinema there are several such movies, you need to choose among them one, after viewing which there will be the maximum possible number of almost satisfied scientists. If there are several possible answers print any of them.ExamplesInput32 3 223 22 3Output2Input66 3 1 1 3 751 2 3 4 52 3 4 5 1Output1NoteIn the first sample, scientists must go to the movie with the index 2, as in such case the 1-th and the 3-rd scientists will be very pleased and the 2-nd scientist will be almost satisfied.In the second test case scientists can go either to the movie with the index 1 or the index 3. After viewing any of these movies exactly two scientists will be very pleased and all the others will be not satisfied.
Input32 3 223 22 3
Output2
2 seconds
256 megabytes
['implementation', 'sortings', '*1300']
B. Game of Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifierΒ β€” an integer from 1 to 109.At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the n-th robot says his identifier.Your task is to determine the k-th identifier to be pronounced.InputThe first line contains two positive integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ min(2Β·109, nΒ·(n + 1) / 2).The second line contains the sequence id1, id2, ..., idn (1 ≀ idi ≀ 109)Β β€” identifiers of roborts. It is guaranteed that all identifiers are different.OutputPrint the k-th pronounced identifier (assume that the numeration starts from 1).ExamplesInput2 21 2Output1Input4 510 4 18 3Output4NoteIn the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As k = 2, the answer equals to 1.In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As k = 5, the answer equals to 4.
Input2 21 2
Output1
1 second
256 megabytes
['implementation', '*1000']
A. Holidaystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlingsΒ β€” 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars.InputThe first line of the input contains a positive integer n (1 ≀ n ≀ 1 000 000)Β β€” the number of days in a year on Mars.OutputPrint two integersΒ β€” the minimum possible and the maximum possible number of days off per year on Mars.ExamplesInput14Output4 4Input2Output0 2NoteIn the first sample there are 14 days in a year on Mars, and therefore independently of the day a year starts with there will be exactly 4 days off .In the second sample there are only 2 days in a year on Mars, and they can both be either work days or days off.
Input14
Output4 4
1 second
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'math', '*900']
A. Little Artem and Presentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.How many times can Artem give presents to Masha?InputThe only line of the input contains a single integer n (1 ≀ n ≀ 109)Β β€” number of stones Artem received on his birthday.OutputPrint the maximum possible number of times Artem can give presents to Masha.ExamplesInput1Output1Input2Output1Input3Output2Input4Output3NoteIn the first sample, Artem can only give 1 stone to Masha.In the second sample, Atrem can give Masha 1 or 2 stones, though he can't give her 1 stone two times.In the third sample, Atrem can first give Masha 2 stones, a then 1 more stone.In the fourth sample, Atrem can first give Masha 1 stone, then 2 stones, and finally 1 stone again.
Input1
Output1
2 seconds
256 megabytes
['math', '*800']
B. Coat of Anticubismtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive β€” convex polygon.Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing. Help sculptor! InputThe first line contains an integer n (3 ≀ n ≀ 105) β€” a number of rod-blanks.The second line contains n integers li (1 ≀ li ≀ 109) β€” lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.OutputPrint the only integer z β€” the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.ExamplesInput31 2 1Output1Input520 4 3 2 1Output11NoteIn the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}. In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.
Input31 2 1
Output1
1 second
256 megabytes
['constructive algorithms', 'geometry', '*1100']
A. Pouring Raintime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition β€” when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do. Today everything had changed quietly. You went on the street with a cup contained water, your favorite drink. In a moment when you were drinking a water you noticed that the process became quite long: the cup still contained water because of rain. You decided to make a formal model of what was happening and to find if it was possible to drink all water in that situation. Thus, your cup is a cylinder with diameter equals d centimeters. Initial level of water in cup equals h centimeters from the bottom. You drink a water with a speed equals v milliliters per second. But rain goes with such speed that if you do not drink a water from the cup, the level of water increases on e centimeters per second. The process of drinking water from the cup and the addition of rain to the cup goes evenly and continuously. Find the time needed to make the cup empty or find that it will never happen. It is guaranteed that if it is possible to drink all water, it will happen not later than after 104 seconds.Note one milliliter equals to one cubic centimeter.InputThe only line of the input contains four integer numbers d, h, v, e (1 ≀ d, h, v, e ≀ 104), where: d β€” the diameter of your cylindrical cup, h β€” the initial level of water in the cup, v β€” the speed of drinking process from the cup in milliliters per second, e β€” the growth of water because of rain if you do not drink from the cup. OutputIf it is impossible to make the cup empty, print "NO" (without quotes).Otherwise print "YES" (without quotes) in the first line. In the second line print a real number β€” time in seconds needed the cup will be empty. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. It is guaranteed that if the answer exists, it doesn't exceed 104.ExamplesInput1 2 3 100OutputNOInput1 1 1 1OutputYES3.659792366325NoteIn the first example the water fills the cup faster than you can drink from it.In the second example area of the cup's bottom equals to , thus we can conclude that you decrease the level of water by centimeters per second. At the same time water level increases by 1 centimeter per second due to rain. Thus, cup will be empty in seconds.
Input1 2 3 100
OutputNO
1 second
256 megabytes
['geometry', 'math', '*1100']
E. Forensic Examinationtime limit per test6 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputThe country of Reberland is the archenemy of Berland. Recently the authorities of Berland arrested a Reberlandian spy who tried to bring the leaflets intended for agitational propaganda to Berland illegally . The most leaflets contain substrings of the Absolutely Inadmissible Swearword and maybe even the whole word.Berland legal system uses the difficult algorithm in order to determine the guilt of the spy. The main part of this algorithm is the following procedure.All the m leaflets that are brought by the spy are numbered from 1 to m. After that it's needed to get the answer to q queries of the following kind: "In which leaflet in the segment of numbers [l, r] the substring of the Absolutely Inadmissible Swearword [pl, pr] occurs more often?".The expert wants you to automate that procedure because this time texts of leaflets are too long. Help him!InputThe first line contains the string s (1 ≀ |s| ≀ 5Β·105) β€” the Absolutely Inadmissible Swearword. The string s consists of only lowercase English letters.The second line contains the only integer m (1 ≀ m ≀ 5Β·104) β€” the number of texts of leaflets for expertise.Each of the next m lines contains the only string ti β€” the text of the i-th leaflet. The sum of lengths of all leaflet texts doesn't exceed 5Β·104. The text of the leaflets consists of only lowercase English letters.The next line contains integer q (1 ≀ q ≀ 5Β·105) β€” the number of queries for expertise.Finally, each of the last q lines contains four integers l, r, pl, pr (1 ≀ l ≀ r ≀ m, 1 ≀ pl ≀ pr ≀ |s|), where |s| is the length of the Absolutely Inadmissible Swearword.OutputPrint q lines. The i-th of them should contain two integers β€” the number of the text with the most occurences and the number of occurences of the substring [pl, pr] of the string s. If there are several text numbers print the smallest one.ExamplesInputsuffixtree3suffixtreesareawesomecartesiantreeisworsethansegmenttreenyeeheeheee21 2 1 101 3 9 10Output1 13 4
Inputsuffixtree3suffixtreesareawesomecartesiantreeisworsethansegmenttreenyeeheeheee21 2 1 101 3 9 10
Output1 13 4
6 seconds
768 megabytes
['data structures', 'string suffix structures', '*3100']
D. Chain Reactiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGroup of Berland scientists, with whom you have a close business relationship, makes a research in the area of peaceful nuclear energy. In particular, they found that a group of four nanobots, placed on a surface of a plate, can run a powerful chain reaction under certain conditions. To be precise, researchers introduced a rectangular Cartesian coordinate system on a flat plate and selected four distinct points with integer coordinates where bots will be placed initially. Next each bot will be assigned with one of the four directions (up, down, left or right) parallel to the coordinate axes. After that, each bot is shifted by an integer distance (which may be different for different bots) along its direction. The chain reaction starts, if the bots are in the corners of a square with positive area with sides parallel to the coordinate axes. Each corner of the square must contain one nanobot. This reaction will be stronger, if bots spend less time to move. We can assume that bots move with unit speed. In other words, the lesser is the maximum length traveled by bot, the stronger is reaction.Scientists have prepared a set of plates and selected starting position for the bots for each plate. Now they ask you to assign the direction for each bot to move after landing such that the maximum length traveled by bot is as small as possible.InputThe first line contains an integer number t (1 ≀ t ≀ 50) β€” the number of plates.t descriptions of plates follow. A description of each plate consists of four lines. Each line consists of a pair of integers numbers xi, yi ( - 108 ≀ xi, yi ≀ 108) β€” coordinates of the next bot. All bots are in different locations.Note, though, the problem can include several records in one test, you can hack other people's submissions only with the test of one plate, i.e. parameter t in a hack test should be equal to 1.OutputPrint answers for all plates separately. First goes a single integer number in a separate line. If scientists have made an unfortunate mistake and nanobots are not able to form the desired square, print -1. Otherwise, print the minimum possible length of the longest bot's path.If a solution exists, in the next four lines print two integer numbers β€” positions of each bot after moving. Print bots' positions in the order they are specified in the input data.If there are multiple solution, you can print any of them.ExamplesInput21 11 -1-1 1-1 -11 12 24 46 6Output01 11 -1-1 1-1 -1-1
Input21 11 -1-1 1-1 -11 12 24 46 6
Output01 11 -1-1 1-1 -1-1
3 seconds
256 megabytes
['brute force', 'geometry', '*3000']
C. Codewordtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe famous sculptor Cicasso is a Reberlandian spy!These is breaking news in Berlandian papers today. And now the sculptor is hiding. This time you give the shelter to the maestro. You have a protected bunker and you provide it to your friend. You set the security system in such way that only you can open the bunker. To open it one should solve the problem which is hard for others but is simple for you.Every day the bunker generates a codeword s. Every time someone wants to enter the bunker, integer n appears on the screen. As the answer one should enter another integer β€” the residue modulo 109 + 7 of the number of strings of length n that consist only of lowercase English letters and contain the string s as the subsequence.The subsequence of string a is a string b that can be derived from the string a by removing some symbols from it (maybe none or all of them). In particular any string is the subsequence of itself. For example, the string "cfo" is the subsequence of the string "codeforces".You haven't implemented the algorithm that calculates the correct answers yet and you should do that ASAP.InputThe first line contains integer m (1 ≀ m ≀ 105) β€” the number of the events in the test case.The second line contains nonempty string s β€” the string generated by the bunker for the current day.The next m lines contain the description of the events. The description starts from integer t β€” the type of the event.If t = 1 consider a new day has come and now a new string s is used. In that case the same line contains a new value of the string s.If t = 2 integer n is given (1 ≀ n ≀ 105). This event means that it's needed to find the answer for the current string s and the value n.The sum of lengths of all generated strings doesn't exceed 105. All of the given strings consist only of lowercase English letters.OutputFor each query of the type 2 print the answer modulo 109 + 7 on the separate line.ExampleInput3a2 21 bc2 5Output51162626NoteIn the first event words of the form "a?" and "?a" are counted, where ? is an arbitrary symbol. There are 26 words of each of these types, but the word "aa" satisfies both patterns, so the answer is 51.
Input3a2 21 bc2 5
Output51162626
6 seconds
256 megabytes
['combinatorics', 'strings', '*2500']
B. World Tourtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA famous sculptor Cicasso goes to a world tour!Well, it is not actually a world-wide. But not everyone should have the opportunity to see works of sculptor, shouldn't he? Otherwise there will be no any exclusivity. So Cicasso will entirely hold the world tour in his native country β€” Berland.Cicasso is very devoted to his work and he wants to be distracted as little as possible. Therefore he will visit only four cities. These cities will be different, so no one could think that he has "favourites". Of course, to save money, he will chose the shortest paths between these cities. But as you have probably guessed, Cicasso is a weird person. Although he doesn't like to organize exhibitions, he likes to travel around the country and enjoy its scenery. So he wants the total distance which he will travel to be as large as possible. However, the sculptor is bad in planning, so he asks you for help. There are n cities and m one-way roads in Berland. You have to choose four different cities, which Cicasso will visit and also determine the order in which he will visit them. So that the total distance he will travel, if he visits cities in your order, starting from the first city in your list, and ending in the last, choosing each time the shortest route between a pair of cities β€” will be the largest. Note that intermediate routes may pass through the cities, which are assigned to the tour, as well as pass twice through the same city. For example, the tour can look like that: . Four cities in the order of visiting marked as overlines: [1, 5, 2, 4].Note that Berland is a high-tech country. So using nanotechnologies all roads were altered so that they have the same length. For the same reason moving using regular cars is not very popular in the country, and it can happen that there are such pairs of cities, one of which generally can not be reached by car from the other one. However, Cicasso is very conservative and cannot travel without the car. Choose cities so that the sculptor can make the tour using only the automobile. It is guaranteed that it is always possible to do. InputIn the first line there is a pair of integers n and m (4 ≀ n ≀ 3000, 3 ≀ m ≀ 5000) β€” a number of cities and one-way roads in Berland.Each of the next m lines contains a pair of integers ui, vi (1 ≀ ui, vi ≀ n) β€” a one-way road from the city ui to the city vi. Note that ui and vi are not required to be distinct. Moreover, it can be several one-way roads between the same pair of cities. OutputPrint four integers β€” numbers of cities which Cicasso will visit according to optimal choice of the route. Numbers of cities should be printed in the order that Cicasso will visit them. If there are multiple solutions, print any of them.ExampleInput8 91 22 33 44 14 55 66 77 88 5Output2 1 8 7NoteLet d(x, y) be the shortest distance between cities x and y. Then in the example d(2, 1) = 3, d(1, 8) = 7, d(8, 7) = 3. The total distance equals 13.
Input8 91 22 33 44 14 55 66 77 88 5
Output2 1 8 7
5 seconds
512 megabytes
['graphs', 'shortest paths', '*2000']
A. Reberland Linguisticstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFirst-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word β€” some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction β€” it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: , where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}. InputThe only line contains a string s (5 ≀ |s| ≀ 104) consisting of lowercase English letters.OutputOn the first line print integer k β€” a number of distinct possible suffixes. On the next k lines print suffixes. Print suffixes in lexicographical (alphabetical) order. ExamplesInputabacabacaOutput3acabacaInputabacaOutput0NoteThe first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.
Inputabacabaca
Output3acabaca
1 second
256 megabytes
['dp', 'implementation', 'strings', '*1800']
F. Four Divisorstime limit per test10 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputIf an integer a is divisible by another integer b, then b is called the divisor of a.For example: 12 has positive 6 divisors. They are 1, 2, 3, 4, 6 and 12.Let’s define a function D(n) β€” number of integers between 1 and n (inclusive) which has exactly four positive divisors.Between 1 and 10 only the integers 6, 8 and 10 has exactly four positive divisors. So, D(10) = 3.You are given an integer n. You have to calculate D(n).InputThe only line contains integer n (1 ≀ n ≀ 1011) β€” the parameter from the problem statement.OutputPrint the only integer c β€” the number of integers between 1 and n with exactly four divisors.ExamplesInput10Output3Input20Output5
Input10
Output3
10 seconds
768 megabytes
['data structures', 'dp', 'math', 'number theory', 'sortings', 'two pointers', '*2400']
E. Beautiful Subarraystime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOne day, ZS the Coder wrote down an array of integers a with elements a1,  a2,  ...,  an.A subarray of the array a is a sequence al,  al  +  1,  ...,  ar for some integers (l,  r) such that 1  ≀  l  ≀  r  ≀  n. ZS the Coder thinks that a subarray of a is beautiful if the bitwise xor of all the elements in the subarray is at least k.Help ZS the Coder find the number of beautiful subarrays of a!InputThe first line contains two integers n and k (1 ≀ n ≀ 106, 1 ≀ k ≀ 109) β€” the number of elements in the array a and the value of the parameter k.The second line contains n integers ai (0 ≀ ai ≀ 109) β€” the elements of the array a.OutputPrint the only integer c β€” the number of beautiful subarrays of the array a.ExamplesInput3 11 2 3Output5Input3 21 2 3Output3Input3 31 2 3Output2
Input3 11 2 3
Output5
3 seconds
512 megabytes
['data structures', 'divide and conquer', 'strings', 'trees', '*2100']
D. Simple Subsettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tuple of positive integers {x1, x2, ..., xk} is called simple if for all pairs of positive integers (i,  j) (1  ≀ i  <  j ≀ k), xi  +  xj is a prime.You are given an array a with n positive integers a1,  a2,  ...,  an (not necessary distinct). You want to find a simple subset of the array a with the maximum size.A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.Let's define a subset of the array a as a tuple that can be obtained from a by removing some (possibly all) elements of it.InputThe first line contains integer n (1 ≀ n ≀ 1000) β€” the number of integers in the array a.The second line contains n integers ai (1 ≀ ai ≀ 106) β€” the elements of the array a.OutputOn the first line print integer m β€” the maximum possible size of simple subset of a.On the second line print m integers bl β€” the elements of the simple subset of the array a with the maximum size.If there is more than one solution you can print any of them. You can print the elements of the subset in any order.ExamplesInput22 3Output23 2Input22 2Output12Input32 1 1Output31 1 2Input283 14Output214 83
Input22 3
Output23 2
1 second
256 megabytes
['constructive algorithms', 'greedy', 'number theory', '*1800']
C. Simple Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputzscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple.zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this task!InputThe only line contains the string s (1 ≀ |s| ≀ 2Β·105) β€” the string given to zscoder. The string s consists of only lowercase English letters.OutputPrint the simple string s' β€” the string s after the minimal number of changes. If there are multiple solutions, you may output any of them.Note that the string s' should also consist of only lowercase English letters.ExamplesInputaabOutputbabInputcaaabOutputcababInputzscoderOutputzscoder
Inputaab
Outputbab
2 seconds
256 megabytes
['dp', 'greedy', 'strings', '*1300']
B. Shoppingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyush is a cashier at the shopping center. Recently his department has started a ''click and collect" service which allows users to shop online. The store contains k items. n customers have already used the above service. Each user paid for m items. Let aij denote the j-th item in the i-th person's order.Due to the space limitations all the items are arranged in one single row. When Ayush receives the i-th order he will find one by one all the items aij (1 ≀ j ≀ m) in the row. Let pos(x) denote the position of the item x in the row at the moment of its collection. Then Ayush takes time equal to pos(ai1) + pos(ai2) + ... + pos(aim) for the i-th customer.When Ayush accesses the x-th element he keeps a new stock in the front of the row and takes away the x-th element. Thus the values are updating.Your task is to calculate the total time it takes for Ayush to process all the orders.You can assume that the market has endless stock.InputThe first line contains three integers n, m and k (1 ≀ n, k ≀ 100, 1 ≀ m ≀ k) β€” the number of users, the number of items each user wants to buy and the total number of items at the market.The next line contains k distinct integers pl (1 ≀ pl ≀ k) denoting the initial positions of the items in the store. The items are numbered with integers from 1 to k.Each of the next n lines contains m distinct integers aij (1 ≀ aij ≀ k) β€” the order of the i-th person.OutputPrint the only integer t β€” the total time needed for Ayush to process all the orders.ExampleInput2 2 53 4 1 2 51 53 1Output14NoteCustomer 1 wants the items 1 and 5.pos(1) = 3, so the new positions are: [1, 3, 4, 2, 5].pos(5) = 5, so the new positions are: [5, 1, 3, 4, 2].Time taken for the first customer is 3 + 5 = 8.Customer 2 wants the items 3 and 1.pos(3) = 3, so the new positions are: [3, 5, 1, 4, 2].pos(1) = 3, so the new positions are: [1, 3, 5, 4, 2].Time taken for the second customer is 3 + 3 = 6.Total time is 8 + 6 = 14.Formally pos(x) is the index of x in the current row.
Input2 2 53 4 1 2 51 53 1
Output14
1 second
256 megabytes
['brute force', '*1400']
A. Buses Between Citiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBuses run between the cities A and B, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city A departs every a minutes and arrives to the city B in a ta minutes, and a bus from the city B departs every b minutes and arrives to the city A in a tb minutes.The driver Simion wants to make his job diverse, so he counts the buses going towards him. Simion doesn't count the buses he meet at the start and finish.You know the time when Simion departed from the city A to the city B. Calculate the number of buses Simion will meet to be sure in his counting.InputThe first line contains two integers a, ta (1 ≀ a, ta ≀ 120) β€” the frequency of the buses from the city A to the city B and the travel time. Both values are given in minutes.The second line contains two integers b, tb (1 ≀ b, tb ≀ 120) β€” the frequency of the buses from the city B to the city A and the travel time. Both values are given in minutes.The last line contains the departure time of Simion from the city A in the format hh:mm. It is guaranteed that there are a bus from the city A at that time. Note that the hours and the minutes are given with exactly two digits.OutputPrint the only integer z β€” the number of buses Simion will meet on the way. Note that you should not count the encounters in cities A and B.ExamplesInput10 3010 3505:20Output5Input60 12024 10013:00Output9NoteIn the first example Simion departs form the city A at 05:20 AM and arrives to the city B at 05:50 AM. He will meet the first 5 buses from the city B that departed in the period [05:00 AM - 05:40 AM]. Also Simion will meet a bus in the city B at 05:50 AM, but he will not count it.Also note that the first encounter will be between 05:26 AM and 05:27 AM (if we suggest that the buses are go with the sustained speed).
Input10 3010 3505:20
Output5
1 second
256 megabytes
['implementation', '*1600']
A. Complicated GCDtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGreatest common divisor GCD(a, b) of two positive integers a and b is equal to the biggest integer d such that both integers a and b are divisible by d. There are many efficient algorithms to find greatest common divisor GCD(a, b), for example, Euclid algorithm. Formally, find the biggest integer d, such that all integers a, a + 1, a + 2, ..., b are divisible by d. To make the problem even more complicated we allow a and b to be up to googol, 10100Β β€” such number do not fit even in 64-bit integer type!InputThe only line of the input contains two integers a and b (1 ≀ a ≀ b ≀ 10100).OutputOutput one integerΒ β€” greatest common divisor of all integers from a to b inclusive.ExamplesInput1 2Output1Input61803398874989484820458683436563811772030917980576 61803398874989484820458683436563811772030917980576Output61803398874989484820458683436563811772030917980576
Input1 2
Output1
1 second
256 megabytes
['math', 'number theory', '*800']
A. Rebustime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds.InputThe only line of the input contains a rebus. It's guaranteed that it contains no more than 100 question marks, integer n is positive and doesn't exceed 1 000 000, all letters and integers are separated by spaces, arithmetic operations are located only between question marks.OutputThe first line of the output should contain "Possible" (without quotes) if rebus has a solution and "Impossible" (without quotes) otherwise.If the answer exists, the second line should contain any valid rebus with question marks replaced by integers from 1 to n. Follow the format given in the samples.ExamplesInput? + ? - ? + ? + ? = 42OutputPossible9 + 13 - 39 + 28 + 31 = 42Input? - ? = 1OutputImpossibleInput? = 1000000OutputPossible1000000 = 1000000
Input? + ? - ? + ? + ? = 42
OutputPossible9 + 13 - 39 + 28 + 31 = 42
1 second
256 megabytes
['constructive algorithms', 'expression parsing', 'greedy', 'math', '*1800']
E. To Hack or not to Hacktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a regular Codeforces round consisting of three problems that uses dynamic scoring.You are given an almost final scoreboard. For each participant (including yourself), the time of the accepted submission for each of the problems is given. Also, for each solution you already know whether you are able to hack it or not. The only changes in the scoreboard that will happen before the end of the round are your challenges.What is the best place you may take at the end?More formally, n people are participating (including yourself). For any problem, if it was solved by exactly k people at the end of the round, the maximum score for this problem is defined as: If n < 2k ≀ 2n, then the maximum possible score is 500; If n < 4k ≀ 2n, then the maximum possible score is 1000; If n < 8k ≀ 2n, then the maximum possible score is 1500; If n < 16k ≀ 2n, then the maximum possible score is 2000; If n < 32k ≀ 2n, then the maximum possible score is 2500; If 32k ≀ n, then the maximum possible score is 3000. Let the maximum possible score for some problem be equal to s. Then a contestant who didn't manage to get it accepted (or his solution was hacked) earns 0 points for this problem. If he got the the solution accepted t minutes after the beginning of the round (and his solution wasn't hacked), he earns points for this problem.The overall score of a participant is equal to the sum of points he earns for each problem plus 100 points for each successful hack (only you make hacks).The resulting place you get is equal to one plus the number of participants who's overall score is strictly greater than yours.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 5000)Β β€” the number of participants. You are the participant number 1.Each of the following n lines contains three integers ai, bi and ci. Here ai = 0 means that the participant number i didn't manage to accept first problem. If 1 ≀ ai ≀ 120, then the participant number i got the first problem accepted ai minutes after the start of the contest and you cannot hack this solution. Finally,  - 120 ≀ ai ≀  - 1 means that the participant number i got the first problem accepted  - ai minutes after the start of the contest and you can hack this solution. Similarly, bi and ci provide the information regarding second and third problems in the same format.It's guaranteed that integers a1, b1 and c1 are non-negative.OutputPrint the only integerΒ β€” the best place you can take at the end of the round.ExamplesInput4120 120 161 61 120-61 61 1200 0 0Output1Input40 0 119-3 -17 -420 7 051 0 0Output2NoteConsider the first sample. If you do not hack any solutions, you will win the contest (scoreboard to the left). However, if you hack the solution of the first problem of the third participant (the only one you can hack), the maximum score for the first problem will change and you will finish second (scoreboard to the right).
Input4120 120 161 61 120-61 61 1200 0 0
Output1
1 second
256 megabytes
['brute force', 'dp', 'greedy', '*3100']
D. International Olympiadtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInternational Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.You are given a list of abbreviations. For each of them determine the year it stands for.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 1000)Β β€” the number of abbreviations to process. Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.OutputFor each abbreviation given in the input, find the year of the corresponding Olympiad.ExamplesInput5IAO'15IAO'2015IAO'1IAO'9IAO'0Output201512015199119891990Input4IAO'9IAO'99IAO'999IAO'9999Output1989199929999999
Input5IAO'15IAO'2015IAO'1IAO'9IAO'0
Output201512015199119891990
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*2000']
C. Binary Tabletime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a table consisting of n rows and m columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa.What is the minimum number of cells with value 1 you can get after applying some number of operations?InputThe first line of the input contains two integers n and m (1 ≀ n ≀ 20, 1 ≀ m ≀ 100 000)Β β€” the number of rows and the number of columns, respectively.Then n lines follows with the descriptions of the rows. Each line has length m and contains only digits '0' and '1'.OutputOutput a single integerΒ β€” the minimum possible number of ones you can get after applying some sequence of operations.ExampleInput3 4011010100111Output2
Input3 4011010100111
Output2
6 seconds
256 megabytes
['bitmasks', 'brute force', 'divide and conquer', 'dp', 'fft', 'math', '*2600']
B. Graph Coloringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red.Find the minimum possible number of moves required to make the colors of all edges equal.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 100 000)Β β€” the number of vertices and edges, respectively.The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi)Β β€” the indices of the vertices connected by the i-th edge, and a character ci () providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges.OutputIf there is no way to make the colors of all edges equal output  - 1 in the only line of the output. Otherwise first output kΒ β€” the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move.If there are multiple optimal sequences of moves, output any of them.ExamplesInput3 31 2 B3 1 R3 2 BOutput12 Input6 51 3 R2 3 R3 4 B4 5 R4 6 ROutput23 4 Input4 51 2 R1 3 R2 3 B3 4 B1 4 BOutput-1
Input3 31 2 B3 1 R3 2 B
Output12
1 second
256 megabytes
['dfs and similar', 'graphs', '*2200']
A. Gambling Nimtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAs you know, the game of "Nim" is played with n piles of stones, where the i-th pile initially contains ai stones. Two players alternate the turns. During a turn a player picks any non-empty pile and removes any positive number of stones from it. The one who is not able to make a move loses the game.Petya and Vasya are tired of playing Nim, so they invented their own version of the game and named it the "Gambling Nim". They have n two-sided cards, one side of the i-th card has number ai written on it, while the other side has number bi. At the beginning of the game the players put all the cards on the table, each card only one of its sides up, and this side is chosen independently and uniformly. Thus they obtain a sequence c1, c2, ..., cn, where ci is equal to ai or bi. Then they take n piles of stones, with i-th pile containing exactly ci stones and play Nim. Petya takes the first turn.Given that both players play optimally, find the probability of Petya's victory. Output the answer as an irreducible fraction.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 500 000)Β β€” the number of cards in the deck.Each of the following n lines contains the description of one card, consisting of two integers ai and bi (0 ≀ ai, bi ≀ 1018).OutputOutput the answer as an irreducible fraction p / q. If the probability of Petya's victory is 0, print 0/1.ExamplesInput21 11 1Output0/1Input21 21 2Output1/2Input30 41 52 3Output1/1
Input21 11 1
Output0/1
2 seconds
512 megabytes
['bitmasks', 'math', 'matrices', 'probabilities', '*2400']
H. Rotate Matrixtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a square matrix of integer numbers. Rotate it 90 degrees clockwise (see examples for clarification of rotation).InputThe input consists of n lines (1 ≀ n ≀ 10, n is not given explicitly). Each of the lines contains n space-separated integers; j-th integer in i-th line corresponds to matrix element mij (1 ≀ mij ≀ 100).OutputOutput the rotated matrix in the same format as the input.ExamplesInput1 2 34 5 67 8 9Output7 4 18 5 29 6 3Input1 2 3 45 6 7 89 10 11 1213 14 15 16Output13 9 5 114 10 6 215 11 7 316 12 8 4
Input1 2 34 5 67 8 9
Output7 4 18 5 29 6 3
2 seconds
64 megabytes
['*special problem', '*2400']
G. Hungarian Notationtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIn Hungarian notation, a variable name is prefixed with a letter or a group of letters which are mnemonics for the type of that variable. For the purposes of this problem we will consider only two data types: integer and real.You are given the meaningful part of variable name in lowercase and a sample value that it will store. Integer values will be written as a sequence of digits. Real values will be written using fixed-point notation: the value is represented with a mandatory decimal point, one or more digits in the decimal part and without exponent part.Your task is to construct a name of this variable in Hungarian notation in the following way. Convert the first letter of meaningful part of the name to uppercase, and prepend a prefix: 'i' for integer variables and 'f' for real ones.InputThe first line of the input contains a string of lowercase letters of English alphabet. The length of the string will be between 1 and 10, inclusive.The second line of the input contains a string of digits and zero or one decimal point '.'. The length of the string will be between 1 and 11, inclusive. It's guaranteed that the decimal point '.' will not be the last character of the string.OutputOutput a single stringΒ β€” the name of the variable in Hungarian notation.ExamplesInputcount18OutputiCountInputweight3.95OutputfWeight
Inputcount18
OutputiCount
2 seconds
64 megabytes
['*special problem', '*2200']
F. Primes in Intervaltime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given two integers a and b (a ≀ b). How many prime numbers are there on the interval from a to b, inclusive?InputThe input contains two integers a and b (2 ≀ a ≀ b ≀ 1 000 000), separated by a single space.OutputOutput a single integerΒ β€” the number of primes between a and b, inclusive.ExamplesInput10 20Output4Input23 23Output1Input271 566Output46
Input10 20
Output4
2 seconds
64 megabytes
['*special problem', '*1900']
E. Divisibility Checktime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given an array of integers. Check whether there exists a number in this array which is divisible by all other numbers in this array. Output 1, if such a number exists, and 0 otherwise.InputThe only line of the input contains a list of space-separated integers ai (1 ≀ ai ≀ 100)Β β€” elements of the array. The size of the array is between 2 and 10, inclusive. Note that the size of the array is not given explicitly!OutputOutput 1 if there exists element of this array which is divisible by all other elements of the array, and 0 otherwise.ExamplesInput6 12 4Output1Input3 13Output0Input26 13 12Output0
Input6 12 4
Output1
2 seconds
64 megabytes
['*special problem', '*2000']
D. Maximal Differencetime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given an array of integers ai. Find the largest absolute value of difference between adjacent elements of the array max(abs(ai - ai + 1)).InputThe only line of the input contains a list of space-separated integers ai (1 ≀ ai ≀ 100)Β β€” elements of the array. The size of the array is between 2 and 10, inclusive. Note that the size of the array is not given explicitly!OutputOutput a single integerΒ β€” the largest absolute value of difference between adjacent elements of the array.ExamplesInput2 10 4 8 6 12Output8Input3 3Output0
Input2 10 4 8 6 12
Output8
2 seconds
64 megabytes
['*special problem', '*2100']
C. Array Sumtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given an array of integers. Calculate the sum of its elements.InputThe i-th line of the input contains an integer ai (0 ≀ a ≀ 1000)Β β€” the i-th element of the array. The size of the array is between 1 and 10, inclusive. Note that the size of the array is not given explicitly!OutputOutput a single integerΒ β€” the sum of the elements of the array.ExamplesInput2151103Output130Input9002133145Output487
Input2151103
Output130
2 seconds
64 megabytes
['*special problem', '*2000']
B. Seasonstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a name of a month. Output the season of the year to which it belongs (based on Northern hemisphere).InputThe input consists of a single string containing the name of one of the twelve months (January, February, March, April, May, June, July, August, September, October, November or December). The string is capitalized as given here.OutputOutput a single string β€” the season of the year to which the given month belongs (winter, spring, summer or autumn). The name of the season should be in lowercase.ExamplesInputAprilOutputspringInputNovemberOutputautumnNoteAssume that winter is December through February, spring is March through May, summer is June through August and autumn is September through November.
InputApril
Outputspring
2 seconds
64 megabytes
['*special problem', '*1900']
A. Lazy Caterer Sequencetime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputLazy caterer sequence is defined as the maximum number of pieces formed when slicing a convex pancake with n cuts (each cut is a straight line). The formula is Cn = nΒ·(n + 1) / 2 + 1. You are given n; calculate n-th element of the sequence.InputThe only line of the input contains an integer n (0 ≀ n ≀ 100).OutputOutput the n-th element of lazy caterer sequence.ExamplesInput2Output4Input5Output16
Input2
Output4
2 seconds
64 megabytes
['*special problem', '*1300']
F. Bear and Bowling 4time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record!For rolling a ball one gets a score β€” an integer (maybe negative) number of points. Score for the i-th roll is multiplied by i and scores are summed up. So, for k rolls with scores s1, s2, ..., sk, the total score is . The total score is 0 if there were no rolls.Limak made n rolls and got score ai for the i-th of them. He wants to maximize his total score and he came up with an interesting idea. He can say that some first rolls were only a warm-up, and that he wasn't focused during the last rolls. More formally, he can cancel any prefix and any suffix of the sequence a1, a2, ..., an. It is allowed to cancel all rolls, or to cancel none of them.The total score is calculated as if there were only non-canceled rolls. So, the first non-canceled roll has score multiplied by 1, the second one has score multiplied by 2, and so on, till the last non-canceled roll.What maximum total score can Limak get?InputThe first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” the total number of rolls made by Limak.The second line contains n integers a1, a2, ..., an (|ai| ≀ 107) β€” scores for Limak's rolls.OutputPrint the maximum possible total score after cancelling rolls.ExamplesInput65 -1000 1 -3 7 -8Output16Input51000 1000 1001 1000 1000Output15003Input3-60 -70 -80Output0NoteIn the first sample test, Limak should cancel the first two rolls, and one last roll. He will be left with rolls 1,  - 3, 7 what gives him the total score 1Β·1 + 2Β·( - 3) + 3Β·7 = 1 - 6 + 21 = 16.
Input65 -1000 1 -3 7 -8
Output16
2 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'geometry', 'ternary search', '*2500']
E. Different Subsets For All Tuplestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a sequence a of n integers between 1 and m, inclusive, denote f(a) as the number of distinct subsequences of a (including the empty subsequence).You are given two positive integers n and m. Let S be the set of all sequences of length n consisting of numbers from 1 to m. Compute the sum f(a) over all a in S modulo 109 + 7.InputThe only line contains two integers n and m (1 ≀ n, m ≀ 106) β€” the number of elements in arrays and the upper bound for elements.OutputPrint the only integer c β€” the desired sum modulo 109 + 7.ExamplesInput1 3Output6Input2 2Output14Input3 3Output174
Input1 3
Output6
2 seconds
256 megabytes
['combinatorics', 'math', '*2300']
D. Number of Parallelogramstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.InputThe first line of the input contains integer n (1 ≀ n ≀ 2000) β€” the number of points.Each of the next n lines contains two integers (xi, yi) (0 ≀ xi, yi ≀ 109) β€” the coordinates of the i-th point.OutputPrint the only integer c β€” the number of parallelograms with the vertices at the given points.ExampleInput40 11 01 12 0Output1
Input40 11 01 12 0
Output1
4 seconds
256 megabytes
['geometry', '*1900']
C. Hard Processtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a with n elements. Each element of a is either 0 or 1.Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).InputThe first line contains two integers n and k (1 ≀ n ≀ 3Β·105, 0 ≀ k ≀ n) β€” the number of elements in a and the parameter k.The second line contains n integers ai (0 ≀ ai ≀ 1) β€” the elements of a.OutputOn the first line print a non-negative integer z β€” the maximal value of f(a) after no more than k changes of zeroes to ones.On the second line print n integers aj β€” the elements of the array a after the changes.If there are multiple answers, you can print any one of them.ExamplesInput7 11 0 0 1 1 0 1Output41 0 0 1 1 1 1Input10 21 0 0 1 0 1 0 1 0 1Output51 0 0 1 1 1 1 1 0 1
Input7 11 0 0 1 1 0 1
Output41 0 0 1 1 1 1
1 second
256 megabytes
['binary search', 'dp', 'two pointers', '*1600']
B. Seating On Bustime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.Consider that m (m ≀ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order of their entering the bus). The pattern of the seat occupation is as below:1-st row left window seat, 1-st row right window seat, 2-nd row left window seat, 2-nd row right window seat, ... , n-th row left window seat, n-th row right window seat.After occupying all the window seats (for m > 2n) the non-window seats are occupied:1-st row left non-window seat, 1-st row right non-window seat, ... , n-th row left non-window seat, n-th row right non-window seat.All the passengers go to a single final destination. In the final destination, the passengers get off in the given order.1-st row left non-window seat, 1-st row left window seat, 1-st row right non-window seat, 1-st row right window seat, ... , n-th row left non-window seat, n-th row left window seat, n-th row right non-window seat, n-th row right window seat. The seating for n = 9 and m = 36. You are given the values n and m. Output m numbers from 1 to m, the order in which the passengers will get off the bus.InputThe only line contains two integers, n and m (1 ≀ n ≀ 100, 1 ≀ m ≀ 4n) β€” the number of pairs of rows and the number of passengers.OutputPrint m distinct integers from 1 to m β€” the order in which the passengers will get off the bus.ExamplesInput2 7Output5 1 6 2 7 3 4Input9 36Output19 1 20 2 21 3 22 4 23 5 24 6 25 7 26 8 27 9 28 10 29 11 30 12 31 13 32 14 33 15 34 16 35 17 36 18
Input2 7
Output5 1 6 2 7 3 4
1 second
256 megabytes
['implementation', '*1000']
A. Co-prime Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n elements, you must make it a co-prime array in as few moves as possible.In each move you can insert any positive integral number you want not greater than 109 in any place in the array.An array is co-prime if any two adjacent numbers of it are co-prime.In the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.InputThe first line contains integer n (1 ≀ n ≀ 1000) β€” the number of elements in the given array.The second line contains n integers ai (1 ≀ ai ≀ 109) β€” the elements of the array a.OutputPrint integer k on the first line β€” the least number of elements needed to add to the array a to make it co-prime.The second line should contain n + k integers aj β€” the elements of the array a after adding k elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array a by adding k elements to it.If there are multiple answers you can print any one of them.ExampleInput32 7 28Output12 7 9 28
Input32 7 28
Output12 7 9 28
1 second
256 megabytes
['greedy', 'implementation', 'math', 'number theory', '*1200']
G. Fence Divercitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLong ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (109 + 7).InputThe first line contains integer n (1 ≀ n ≀ 1 000 000)Β β€” the number of boards in Vasily's fence.The second line contains n space-separated numbers h1, h2, ..., hn (1 ≀ hi ≀ 109), where hi equals the height of the i-th board to the left.OutputPrint the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.ExamplesInput21 1Output0Input33 4 2Output13NoteFrom the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part):
Input21 1
Output0
2 seconds
256 megabytes
['combinatorics', 'dp', 'number theory', '*2300']
F. Polycarp and Haytime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe farmer Polycarp has a warehouse with hay, which can be represented as an n × m rectangular table, where n is the number of rows, and m is the number of columns in the table. Each cell of the table contains a haystack. The height in meters of the hay located in the i-th row and the j-th column is equal to an integer ai, j and coincides with the number of cubic meters of hay in the haystack, because all cells have the size of the base 1 × 1. Polycarp has decided to tidy up in the warehouse by removing an arbitrary integer amount of cubic meters of hay from the top of each stack. You can take different amounts of hay from different haystacks. Besides, it is allowed not to touch a stack at all, or, on the contrary, to remove it completely. If a stack is completely removed, the corresponding cell becomes empty and no longer contains the stack.Polycarp wants the following requirements to hold after the reorganization: the total amount of hay remaining in the warehouse must be equal to k, the heights of all stacks (i.e., cells containing a non-zero amount of hay) should be the same, the height of at least one stack must remain the same as it was, for the stability of the remaining structure all the stacks should form one connected region. The two stacks are considered adjacent if they share a side in the table. The area is called connected if from any of the stack in the area you can get to any other stack in this area, moving only to adjacent stacks. In this case two adjacent stacks necessarily belong to the same area.Help Polycarp complete this challenging task or inform that it is impossible.InputThe first line of the input contains three integers n, m (1 ≀ n, m ≀ 1000) and k (1 ≀ k ≀ 1018)Β β€” the number of rows and columns of the rectangular table where heaps of hay are lain and the required total number cubic meters of hay after the reorganization. Then n lines follow, each containing m positive integers ai, j (1 ≀ ai, j ≀ 109), where ai, j is equal to the number of cubic meters of hay making the hay stack on the i-th row and j-th column of the table.OutputIn the first line print "YES" (without quotes), if Polycarpus can perform the reorganisation and "NO" (without quotes) otherwise. If the answer is "YES" (without quotes), then in next n lines print m numbersΒ β€” the heights of the remaining hay stacks. All the remaining non-zero values should be equal, represent a connected area and at least one of these values shouldn't be altered.If there are multiple answers, print any of them.ExamplesInput2 3 3510 4 99 9 7OutputYES7 0 7 7 7 7 Input4 4 505 9 1 15 1 1 55 1 5 55 5 7 1OutputYES5 5 0 0 5 0 0 5 5 0 5 5 5 5 5 0 Input2 4 121 1 3 11 6 2 4OutputNONoteIn the first sample non-zero values make up a connected area, their values do not exceed the initial heights of hay stacks. All the non-zero values equal 7, and their number is 5, so the total volume of the remaining hay equals the required value k = 7Β·5 = 35. At that the stack that is on the second line and third row remained unaltered.
Input2 3 3510 4 99 9 7
OutputYES7 0 7 7 7 7
4 seconds
512 megabytes
['dfs and similar', 'dsu', 'graphs', 'greedy', 'sortings', '*2000']
E. New Reformtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.InputThe first line of the input contains two positive integers, n and m β€” the number of the cities and the number of roads in Berland (2 ≀ n ≀ 100 000, 1 ≀ m ≀ 100 000). Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi, yi (1 ≀ xi, yi ≀ n, xi ≠ yi), where xi and yi are the numbers of the cities connected by the i-th road.It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.OutputPrint a single integerΒ β€” the minimum number of separated cities after the reform.ExamplesInput4 32 11 34 3Output1Input5 52 11 32 32 54 3Output0Input6 51 22 34 54 65 6Output1NoteIn the first sample the following road orientation is allowed: , , .The second sample: , , , , .The third sample: , , , , .
Input4 32 11 34 3
Output1
1 second
256 megabytes
['data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', '*1600']
D. Bicycle Racetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMaria participates in a bicycle race.The speedway takes place on the shores of Lake Lucerne, just repeating its contour. As you know, the lake shore consists only of straight sections, directed to the north, south, east or west.Let's introduce a system of coordinates, directing the Ox axis from west to east, and the Oy axis from south to north. As a starting position of the race the southernmost point of the track is selected (and if there are several such points, the most western among them). The participants start the race, moving to the north. At all straight sections of the track, the participants travel in one of the four directions (north, south, east or west) and change the direction of movement only in bends between the straight sections. The participants, of course, never turn back, that is, they do not change the direction of movement from north to south or from east to west (or vice versa).Maria is still young, so she does not feel confident at some turns. Namely, Maria feels insecure if at a failed or untimely turn, she gets into the water. In other words, Maria considers the turn dangerous if she immediately gets into the water if it is ignored.Help Maria get ready for the competitionΒ β€” determine the number of dangerous turns on the track.InputThe first line of the input contains an integer n (4 ≀ n ≀ 1000)Β β€” the number of straight sections of the track.The following (n + 1)-th line contains pairs of integers (xi, yi) ( - 10 000 ≀ xi, yi ≀ 10 000). The first of these points is the starting position. The i-th straight section of the track begins at the point (xi, yi) and ends at the point (xi + 1, yi + 1).It is guaranteed that: the first straight section is directed to the north; the southernmost (and if there are several, then the most western of among them) point of the track is the first point; the last point coincides with the first one (i.e., the start position); any pair of straight sections of the track has no shared points (except for the neighboring ones, they share exactly one point); no pair of points (except for the first and last one) is the same; no two adjacent straight sections are directed in the same direction or in opposite directions. OutputPrint a single integerΒ β€” the number of dangerous turns on the track.ExamplesInput60 00 11 11 22 22 00 0Output1Input161 11 53 53 72 72 96 96 75 75 34 34 43 43 25 25 11 1Output6NoteThe first sample corresponds to the picture: The picture shows that you can get in the water under unfortunate circumstances only at turn at the point (1, 1). Thus, the answer is 1.
Input60 00 11 11 22 22 00 0
Output1
1 second
256 megabytes
['geometry', 'implementation', 'math', '*1500']
C. Tanya and Toystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.InputThe first line contains two integers n (1 ≀ n ≀ 100 000) and m (1 ≀ m ≀ 109)Β β€” the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys.The next line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the types of toys that Tanya already has.OutputIn the first line print a single integer kΒ β€” the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m.In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≀ ti ≀ 109)Β β€” the types of toys that Tanya should choose.If there are multiple answers, you may print any of them. Values of ti can be printed in any order.ExamplesInput3 71 3 4Output22 5 Input4 144 6 12 8Output47 2 3 1NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.
Input3 71 3 4
Output22 5
1 second
256 megabytes
['greedy', 'implementation', '*1200']
B. Qualifying Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVery soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.InputThe first line of the input contains two integers n and m (2 ≀ n ≀ 100 000, 1 ≀ m ≀ 10 000, n β‰₯ 2m)Β β€” the number of participants of the qualifying contest and the number of regions in Berland.Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive).It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.OutputPrint m lines. On the i-th line print the team of the i-th regionΒ β€” the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.ExamplesInput5 2Ivanov 1 763Andreev 2 800Petrov 1 595Sidorov 1 790Semenov 2 503OutputSidorov IvanovAndreev SemenovInput5 2Ivanov 1 800Andreev 2 763Petrov 1 800Sidorov 1 800Semenov 2 503Output?Andreev SemenovNoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.
Input5 2Ivanov 1 763Andreev 2 800Petrov 1 595Sidorov 1 790Semenov 2 503
OutputSidorov IvanovAndreev Semenov
1 second
256 megabytes
['constructive algorithms', 'sortings', '*1300']
A. Round Housetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direction of increasing numbers (in this order entrance n should be followed by entrance 1). The negative value of b corresponds to moving |b| entrances in the order of decreasing numbers (in this order entrance 1 is followed by entrance n). If b = 0, then Vasya prefers to walk beside his entrance. Illustration for n = 6, a = 2, b =  - 5. Help Vasya to determine the number of the entrance, near which he will be at the end of his walk.InputThe single line of the input contains three space-separated integers n, a and b (1 ≀ n ≀ 100, 1 ≀ a ≀ n,  - 100 ≀ b ≀ 100)Β β€” the number of entrances at Vasya's place, the number of his entrance and the length of his walk, respectively.OutputPrint a single integer k (1 ≀ k ≀ n)Β β€” the number of the entrance where Vasya will be at the end of his walk.ExamplesInput6 2 -5Output3Input5 1 3Output4Input3 2 7Output3NoteThe first example is illustrated by the picture in the statements.
Input6 2 -5
Output3
1 second
256 megabytes
['implementation', 'math', '*1000']
A. Bear and Reverse Radewooshtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficultyΒ β€” it's guaranteed that pi < pi + 1 and ti < ti + 1.A constant c is given too, representing the speed of loosing points. Then, submitting the i-th problem at time x (x minutes after the start of the contest) gives max(0,  pi - cΒ·x) points.Limak is going to solve problems in order 1, 2, ..., n (sorted increasingly by pi). Radewoosh is going to solve them in order n, n - 1, ..., 1 (sorted decreasingly by pi). Your task is to predict the outcomeΒ β€” print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie.You may assume that the duration of the competition is greater or equal than the sum of all ti. That means both Limak and Radewoosh will accept all n problems.InputThe first line contains two integers n and c (1 ≀ n ≀ 50, 1 ≀ c ≀ 1000)Β β€” the number of problems and the constant representing the speed of loosing points.The second line contains n integers p1, p2, ..., pn (1 ≀ pi ≀ 1000, pi < pi + 1)Β β€” initial scores.The third line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 1000, ti < ti + 1) where ti denotes the number of minutes one needs to solve the i-th problem.OutputPrint "Limak" (without quotes) if Limak will get more points in total. Print "Radewoosh" (without quotes) if Radewoosh will get more points in total. Print "Tie" (without quotes) if Limak and Radewoosh will get the same total number of points.ExamplesInput3 250 85 25010 15 25OutputLimakInput3 650 85 25010 15 25OutputRadewooshInput8 110 20 30 40 50 60 70 808 10 58 63 71 72 75 76OutputTieNoteIn the first sample, there are 3 problems. Limak solves them as follows: Limak spends 10 minutes on the 1-st problem and he gets 50 - cΒ·10 = 50 - 2Β·10 = 30 points. Limak spends 15 minutes on the 2-nd problem so he submits it 10 + 15 = 25 minutes after the start of the contest. For the 2-nd problem he gets 85 - 2Β·25 = 35 points. He spends 25 minutes on the 3-rd problem so he submits it 10 + 15 + 25 = 50 minutes after the start. For this problem he gets 250 - 2Β·50 = 150 points. So, Limak got 30 + 35 + 150 = 215 points.Radewoosh solves problem in the reversed order: Radewoosh solves 3-rd problem after 25 minutes so he gets 250 - 2Β·25 = 200 points. He spends 15 minutes on the 2-nd problem so he submits it 25 + 15 = 40 minutes after the start. He gets 85 - 2Β·40 = 5 points for this problem. He spends 10 minutes on the 1-st problem so he submits it 25 + 15 + 10 = 50 minutes after the start. He gets max(0, 50 - 2Β·50) = max(0,  - 50) = 0 points. Radewoosh got 200 + 5 + 0 = 205 points in total. Limak has 215 points so Limak wins.In the second sample, Limak will get 0 points for each problem and Radewoosh will first solve the hardest problem and he will get 250 - 6Β·25 = 100 points for that. Radewoosh will get 0 points for other two problems but he is the winner anyway.In the third sample, Limak will get 2 points for the 1-st problem and 2 points for the 2-nd problem. Radewoosh will get 4 points for the 8-th problem. They won't get points for other problems and thus there is a tie because 2 + 2 = 4.
Input3 250 85 25010 15 25
OutputLimak
2 seconds
256 megabytes
['implementation', '*800']
G. You're a Professionaltime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputA simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.You are given user's friends' opinions about a list of items. You are also given a threshold T β€” the minimal number of "likes" necessary for an item to be recommended to the user.Output the number of items in the list liked by at least T of user's friends.InputThe first line of the input will contain three space-separated integers: the number of friends F (1 ≀ F ≀ 10), the number of items I (1 ≀ I ≀ 10) and the threshold T (1 ≀ T ≀ F).The following F lines of input contain user's friends' opinions. j-th character of i-th line is 'Y' if i-th friend likes j-th item, and 'N' otherwise.OutputOutput an integer β€” the number of items liked by at least T of user's friends.ExamplesInput3 3 2YYYNNNYNYOutput2Input4 4 1NNNYNNYNNYNNYNNNOutput4
Input3 3 2YYYNNNYNY
Output2
2 seconds
64 megabytes
['*special problem', '*1900']
F. Ace It!time limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputInputThe only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid").OutputOutput a single integer.ExamplesInputA221033Output21InputA223635Output22InputA232726Output23
InputA221033
Output21
2 seconds
64 megabytes
['*special problem', '*1900']
E. Out of Controlstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.InputThe first line of the input contains a single integer N (3 ≀ N ≀ 10).The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≀ aij ≀ 100 for i ≠ j.OutputOutput the maximum length of the shortest path between any pair of vertices in the graph.ExamplesInput30 1 11 0 41 4 0Output2Input40 1 2 31 0 4 52 4 0 63 5 6 0Output5NoteYou're running short of keywords, so you can't use some of them:definedoforforeachwhilerepeatuntilifthenelseelifelsifelseifcaseswitch
Input30 1 11 0 41 4 0
Output2
2 seconds
64 megabytes
['*special problem', '*2000']
D. Rosetta Problemtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard output++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+ ++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>+++++++ +++++++++<<<<<<<<<<<<<<<<-]>>>>>>>>>>.<<<<<<<<<<>>>>>>>>>>>>>>++.--<<<<<<<<< <<<<<>>>>>>>>>>>>>+.-<<<<<<<<<<<<<>>>>>>>>>>>>>>--.++<<<<<<<<<<<<<<>>>>>>>>> >>>>>>----.++++<<<<<<<<<<<<<<<>>>>.<<<<>>>>>>>>>>>>>>--.++<<<<<<<<<<<<<<>>>> >>>>>>>>>>>---.+++<<<<<<<<<<<<<<<>>>>>>>>>>>>>>---.+++<<<<<<<<<<<<<<>>>>>>>> >>>>++.--<<<<<<<<<<<<>>>>>>>>>>>>>---.+++<<<<<<<<<<<<<>>>>>>>>>>>>>>++.--<<< <<<<<<<<<<<. DCBA:^!~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHdcbD`Y^]\UZYRv 9876543210/.-,+*)('&%$#"!~}|{zyxwvutsrqponm+*)('&%$#cya`=^]\[ZYXWVUTSRQPONML KJfe^cba`_X]VzTYRv98TSRQ3ONMLEi,+*)('&%$#"!~}|{zyxwvutsrqponmlkjihgfedcba`_^ ]\[ZYXWVUTSonPlkjchg`ed]#DCBA@?>=<;:9876543OHGLKDIHGFE>b%$#"!~}|{zyxwvutsrqp onmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMibafedcba`_X|?>Z<XWVUTSRKo\ v34*8+6+,78+9*3+,93+9*5+,28+9*1+,55+9*4+,23*6*2*,91,@,+7*9*25,*48,+3*9+38,+< >62*9*2+,34*9*3+,66+9*8+,52*9*7+,75+9*8+,92+9*6+,48+9*3+,43*9*2+,84*,26*9*3^InputThe input contains a single integer a (0 ≀ a ≀ 1 000 000).OutputOutput a single integer.ExampleInput129Output1
Input129
Output1
2 seconds
64 megabytes
['*special problem', '*2100']
C. Without Texttime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard output You can preview the image in better quality by the link: http://assets.codeforces.com/files/656/without-text.pngInputThe only line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be an alphanumeric character or a full stop ".".OutputOutput the required answer.ExamplesInputCodeforcesOutput-87InputAPRIL.1stOutput17
InputCodeforces
Output-87
2 seconds
64 megabytes
['*special problem', '*2000']
B. Scrambledtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputBtoh yuo adn yuor roomatme lhoate wianshg disehs, btu stlil sdmoeboy msut peorrfm tihs cohre dialy. Oen dya yuo decdie to idourtcne smoe syestm. Yuor rmmotaoe sstgegus teh fooniwllg dael. Yuo argee on tow arayrs of ientgres M adn R, nmebur upmicnog dyas (induiclng teh cunrret oen) wtih sicsescuve irnegets (teh ceurrnt dya is zreo), adn yuo wsah teh diehss on dya D if adn olny if terhe etsixs an iednx i scuh taht DΒ modΒ M[i] = R[i], otwsehrie yuor rmootmae deos it. Yuo lkie teh cncepot, btu yuor rmotaome's cuinnng simle meaks yuo ssecupt sthnoemig, so yuo itennd to vefriy teh fnerisas of teh aemnrgeet.Yuo aer geivn ayarrs M adn R. Cuaclatle teh pceanregte of dyas on wchih yuo edn up dnoig teh wisahng. Amsuse taht yuo hvae iiiftlneny mnay dyas aehad of yuo. InputThe first line of input contains a single integer N (1 ≀ N ≀ 16).The second and third lines of input contain N integers each, all between 0 and 16, inclusive, and represent arrays M and R, respectively. All M[i] are positive, for each i R[i] < M[i].OutputOutput a single real number. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 4.ExamplesInput120Output0.500000Input22 31 0Output0.666667
Input120
Output0.500000
2 seconds
64 megabytes
['*special problem', 'implementation', '*1700']
A. Da Vinci Powerstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputInputThe input contains a single integer a (0 ≀ a ≀ 35).OutputOutput a single integer.ExamplesInput3Output8Input10Output1024
Input3
Output8
2 seconds
64 megabytes
['*special problem', '*1900']
G. Move by Primetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPussycat Sonya has an array consisting of n positive integers. There are 2n possible subsequences of the array. For each subsequence she counts the minimum number of operations to make all its elements equal. Each operation must be one of two: Choose some element of the subsequence and multiply it by some prime number. Choose some element of the subsequence and divide it by some prime number. The chosen element must be divisible by the chosen prime number. What is the sum of minimum number of operations for all 2n possible subsequences? Find and print this sum modulo 109 + 7.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 300 000)Β β€” the size of the array.The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 300 000)Β β€” elements of the array.OutputPrint the sum of minimum number of operation for all possible subsequences of the given array modulo 109 + 7.ExamplesInput360 60 40Output6Input41 2 3 4Output24NoteIn the first sample, there are 8 possible subsequences: (60, 60, 40), (60, 60), (60, 40), (60, 40), (60), (60), (40) and () (empty subsequence).For a subsequence (60, 60, 40) we can make all elements equal by two operationsΒ β€” divide 40 by 2 to get 20, and then multiply 20 by 3 to get 60. It's impossible to achieve the goal using less operations and thus we add 2 to the answer.There are two subsequences equal to (60, 40) and for each of them the also need to make at least 2 operations.In each of other subsequences all numbers are already equal, so we need 0 operations for each of them. The sum is equal to 2 + 2 + 2 = 6.
Input360 60 40
Output6
5 seconds
256 megabytes
['combinatorics', 'math', 'number theory', '*3100']
F. Paper tasktime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlex was programming while Valentina (his toddler daughter) got there and started asking many questions about the round brackets (or parenthesis) in the code. He explained her a bit and when she got it he gave her a task in order to finish his code on time.For the purpose of this problem we consider only strings consisting of opening and closing round brackets, that is characters '(' and ')'.The sequence of brackets is called correct if: it's empty; it's a correct sequence of brackets, enclosed in a pair of opening and closing brackets; it's a concatenation of two correct sequences of brackets. For example, the sequences "()()" and "((()))(())" are correct, while ")(()", "(((((" and "())" are not.Alex took a piece of paper, wrote a string s consisting of brackets and asked Valentina to count the number of distinct non-empty substrings of s that are correct sequences of brackets. In other words, her task is to count the number of non-empty correct sequences of brackets that occur in a string s as a substring (don't mix up with subsequences).When Valentina finished the task, Alex noticed he doesn't know the answer. Help him don't loose face in front of Valentina and solve the problem!InputThe first line of the input contains an integer n (1 ≀ n ≀ 500 000)Β β€” the length of the string s.The second line contains a string s of length n consisting of only '(' and ')'.OutputPrint the number of distinct non-empty correct sequences that occur in s as substring.ExamplesInput10()()()()()Output5Input7)(())()Output3NoteIn the first sample, there are 5 distinct substrings we should count: "()", "()()", "()()()", "()()()()" and "()()()()()".In the second sample, there are 3 distinct substrings we should count: "()", "(())" and "(())()".
Input10()()()()()
Output5
3 seconds
512 megabytes
['data structures', 'string suffix structures', 'strings', '*2600']
E. Bear and Forgotten Tree 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is a connected undirected graph consisting of n vertices and n  -  1 edges. Vertices are numbered 1 through n.Limak is a little polar bear. He once had a tree with n vertices but he lost it. He still remembers something about the lost tree though.You are given m pairs of vertices (a1, b1), (a2, b2), ..., (am, bm). Limak remembers that for each i there was no edge between ai and bi. He also remembers that vertex 1 was incident to exactly k edges (its degree was equal to k).Is it possible that Limak remembers everything correctly? Check whether there exists a tree satisfying the given conditions.InputThe first line of the input contains three integers n, m and k ()Β β€” the number of vertices in Limak's tree, the number of forbidden pairs of vertices, and the degree of vertex 1, respectively.The i-th of next m lines contains two distinct integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi)Β β€” the i-th pair that is forbidden. It's guaranteed that each pair of vertices will appear at most once in the input.OutputPrint "possible" (without quotes) if there exists at least one tree satisfying the given conditions. Otherwise, print "impossible" (without quotes).ExamplesInput5 4 21 22 34 24 1OutputpossibleInput6 5 31 21 31 41 51 6OutputimpossibleNoteIn the first sample, there are n = 5 vertices. The degree of vertex 1 should be k = 2. All conditions are satisfied for a tree with edges 1 - 5, 5 - 2, 1 - 3 and 3 - 4.In the second sample, Limak remembers that none of the following edges existed: 1 - 2, 1 - 3, 1 - 4, 1 - 5 and 1 - 6. Hence, vertex 1 couldn't be connected to any other vertex and it implies that there is no suitable tree.
Input5 4 21 22 34 24 1
Outputpossible
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'trees', '*2400']
D. Delivery Bearstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNiwel is a little golden bear. As everyone knows, bears live in forests, but Niwel got tired of seeing all the trees so he decided to move to the city.In the city, Niwel took on a job managing bears to deliver goods. The city that he lives in can be represented as a directed graph with n nodes and m edges. Each edge has a weight capacity. A delivery consists of a bear carrying weights with their bear hands on a simple path from node 1 to node n. The total weight that travels across a particular edge must not exceed the weight capacity of that edge.Niwel has exactly x bears. In the interest of fairness, no bear can rest, and the weight that each bear carries must be exactly the same. However, each bear may take different paths if they like.Niwel would like to determine, what is the maximum amount of weight he can deliver (it's the sum of weights carried by bears). Find the maximum weight.InputThe first line contains three integers n, m and x (2 ≀ n ≀ 50, 1 ≀ m ≀ 500, 1 ≀ x ≀ 100 000)Β β€” the number of nodes, the number of directed edges and the number of bears, respectively.Each of the following m lines contains three integers ai, bi and ci (1 ≀ ai, bi ≀ n, ai ≠ bi, 1 ≀ ci ≀ 1 000 000). This represents a directed edge from node ai to bi with weight capacity ci. There are no self loops and no multiple edges from one city to the other city. More formally, for each i and j that i ≠ j it's guaranteed that ai ≠ aj or bi ≠ bj. It is also guaranteed that there is at least one path from node 1 to node n.OutputPrint one real value on a single lineΒ β€” the maximum amount of weight Niwel can deliver if he uses exactly x bears. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput4 4 31 2 22 4 11 3 13 4 2Output1.5000000000Input5 11 231 2 32 3 43 4 54 5 61 3 42 4 53 5 61 4 22 5 31 5 23 2 30Output10.2222222222NoteIn the first sample, Niwel has three bears. Two bears can choose the path , while one bear can choose the path . Even though the bear that goes on the path can carry one unit of weight, in the interest of fairness, he is restricted to carry 0.5 units of weight. Thus, the total weight is 1.5 units overall. Note that even though Niwel can deliver more weight with just 2 bears, he must use exactly 3 bears on this day.
Input4 4 31 2 22 4 11 3 13 4 2
Output1.5000000000
2 seconds
256 megabytes
['binary search', 'flows', 'graphs', '*2200']
C. Bear and Up-Downtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied: ti < ti + 1 for each odd i < n; ti > ti + 1 for each even i < n. For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.InputThe first line of the input contains one integer n (2 ≀ n ≀ 150 000)Β β€” the length of the sequence.The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 150 000) β€” the initial sequence. It's guaranteed that the given sequence is not nice.OutputPrint the number of ways to swap two elements exactly once in order to get a nice sequence.ExamplesInput52 8 4 7 7Output2Input4200 150 100 50Output1Input103 2 1 4 1 4 1 4 1 4Output8Input91 2 3 4 5 6 7 8 9Output0NoteIn the first sample, there are two ways to get a nice sequence with one swap: Swap t2 = 8 with t4 = 7. Swap t1 = 2 with t5 = 7. In the second sample, there is only one wayΒ β€” Limak should swap t1 = 200 with t4 = 50.
Input52 8 4 7 7
Output2
2 seconds
256 megabytes
['brute force', 'implementation', '*1900']
B. Bear and Compressingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.InputThe first line contains two integers n and q (2 ≀ n ≀ 6, 1 ≀ q ≀ 36)Β β€” the length of the initial string and the number of available operations.The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai ≠ aj for i ≠ j and that all ai and bi consist of only first six lowercase English letters.OutputPrint the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.ExamplesInput3 5ab acc cca aee cff dOutput4Input2 8af edc dcc fbc bda beb abb bff cOutput1Input6 2bb aba aOutput0NoteIn the first sample, we count initial strings of length 3 from which Limak can get a required string "a". There are 4 such strings: "abb", "cab", "cca", "eea". The first one Limak can compress using operation 1 two times (changing "ab" to a single "a"). The first operation would change "abb" to "ab" and the second operation would change "ab" to "a".Other three strings may be compressed as follows: "cab" "ab" "a" "cca" "ca" "a" "eea" "ca" "a" In the second sample, the only correct initial string is "eb" because it can be immediately compressed to "a".
Input3 5ab acc cca aee cff d
Output4
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'dp', 'strings', '*1300']
A. Bear and Three Ballstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little polar bear. He has n balls, the i-th ball has size ti.Limak wants to give one ball to each of his three friends. Giving gifts isn't easyΒ β€” there are two rules Limak must obey to make friends happy: No two friends can get balls of the same size. No two friends can get balls of sizes that differ by more than 2. For example, Limak can choose balls with sizes 4, 5 and 3, or balls with sizes 90, 91 and 92. But he can't choose balls with sizes 5, 5 and 6 (two friends would get balls of the same size), and he can't choose balls with sizes 30, 31 and 33 (because sizes 30 and 33 differ by more than 2).Your task is to check whether Limak can choose three balls that satisfy conditions above.InputThe first line of the input contains one integer n (3 ≀ n ≀ 50)Β β€” the number of balls Limak has.The second line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 1000) where ti denotes the size of the i-th ball.OutputPrint "YES" (without quotes) if Limak can choose three balls of distinct sizes, such that any two of them differ by no more than 2. Otherwise, print "NO" (without quotes).ExamplesInput418 55 16 17OutputYESInput640 41 43 44 44 44OutputNOInput85 972 3 4 1 4 970 971OutputYESNoteIn the first sample, there are 4 balls and Limak is able to choose three of them to satisfy the rules. He must must choose balls with sizes 18, 16 and 17.In the second sample, there is no way to give gifts to three friends without breaking the rules.In the third sample, there is even more than one way to choose balls: Choose balls with sizes 3, 4 and 5. Choose balls with sizes 972, 970, 971.
Input418 55 16 17
OutputYES
2 seconds
256 megabytes
['brute force', 'implementation', 'sortings', '*900']
F. Ants on a Circletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn ants are on a circle of length m. An ant travels one unit of distance per one unit of time. Initially, the ant number i is located at the position si and is facing in the direction di (which is either L or R). Positions are numbered in counterclockwise order starting from some point. Positions of the all ants are distinct.All the ants move simultaneously, and whenever two ants touch, they will both switch their directions. Note that it is possible for an ant to move in some direction for a half of a unit of time and in opposite direction for another half of a unit of time.Print the positions of the ants after t time units.InputThe first line contains three integers n, m and t (2 ≀ n ≀ 3Β·105, 2 ≀ m ≀ 109, 0 ≀ t ≀ 1018) β€” the number of ants, the length of the circle and the number of time units.Each of the next n lines contains integer si and symbol di (1 ≀ si ≀ m and di is either L or R) β€” the position and the direction of the i-th ant at the start. The directions L and R corresponds to the clockwise and counterclockwise directions, respectively.It is guaranteed that all positions si are distinct.OutputPrint n integers xj β€” the position of the j-th ant after t units of time. The ants are numbered from 1 to n in order of their appearing in input.ExamplesInput2 4 81 R3 LOutput1 3Input4 8 66 R5 L1 R8 LOutput7 4 2 7Input4 8 21 R5 L6 L8 ROutput3 3 4 2
Input2 4 81 R3 L
Output1 3
2 seconds
256 megabytes
['constructive algorithms', 'math', '*2800']
E. Pursuit For Artifactstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputJohnny is playing a well-known computer game. The game are in some country, where the player can freely travel, pass quests and gain an experience.In that country there are n islands and m bridges between them, so you can travel from any island to any other. In the middle of some bridges are lying ancient powerful artifacts. Johnny is not interested in artifacts, but he can get some money by selling some artifact.At the start Johnny is in the island a and the artifact-dealer is in the island b (possibly they are on the same island). Johnny wants to find some artifact, come to the dealer and sell it. The only difficulty is that bridges are too old and destroying right after passing over them. Johnnie's character can't swim, fly and teleport, so the problem became too difficult.Note that Johnny can't pass the half of the bridge, collect the artifact and return to the same island. Determine if Johnny can find some artifact and sell it.InputThe first line contains two integers n and m (1 ≀ n ≀ 3Β·105, 0 ≀ m ≀ 3Β·105) β€” the number of islands and bridges in the game.Each of the next m lines contains the description of the bridge β€” three integers xi, yi, zi (1 ≀ xi, yi ≀ n, xi ≠ yi, 0 ≀ zi ≀ 1), where xi and yi are the islands connected by the i-th bridge, zi equals to one if that bridge contains an artifact and to zero otherwise. There are no more than one bridge between any pair of islands. It is guaranteed that it's possible to travel between any pair of islands.The last line contains two integers a and b (1 ≀ a, b ≀ n) β€” the islands where are Johnny and the artifact-dealer respectively.OutputIf Johnny can find some artifact and sell it print the only word "YES" (without quotes). Otherwise print the word "NO" (without quotes).ExamplesInput6 71 2 02 3 03 1 03 4 14 5 05 6 06 4 01 6OutputYESInput5 41 2 02 3 03 4 02 5 11 4OutputNOInput5 61 2 02 3 03 1 03 4 04 5 15 3 01 2OutputYES
Input6 71 2 02 3 03 1 03 4 14 5 05 6 06 4 01 6
OutputYES
3 seconds
512 megabytes
['dfs and similar', 'dsu', 'graphs', 'trees', '*2300']
D. Nested Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.InputThe first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” the number of segments on a line.Each of the next n lines contains two integers li and ri ( - 109 ≀ li < ri ≀ 109) β€” the coordinates of the left and the right ends of the i-th segment. It is guaranteed that there are no ends of some segments that coincide.OutputPrint n lines. The j-th of them should contain the only integer aj β€” the number of segments contained in the j-th segment.ExamplesInput41 82 34 75 6Output3010Input33 41 52 6Output011
Input41 82 34 75 6
Output3010
2 seconds
256 megabytes
['data structures', 'sortings', '*1800']
C. Foe Pairstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of length n. Also you are given m foe pairs (ai, bi) (1 ≀ ai, bi ≀ n, ai ≠ bi). Your task is to count the number of different intervals (x, y) (1 ≀ x ≀ y ≀ n) that do not contain any foe pairs. So you shouldn't count intervals (x, y) that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important).Consider some example: p = [1, 3, 2, 4] and foe pairs are {(3, 2), (4, 2)}. The interval (1, 3) is incorrect because it contains a foe pair (3, 2). The interval (1, 4) is also incorrect because it contains two foe pairs (3, 2) and (4, 2). But the interval (1, 2) is correct because it doesn't contain any foe pair.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the length of the permutation p and the number of foe pairs.The second line contains n distinct integers pi (1 ≀ pi ≀ n) β€” the elements of the permutation p.Each of the next m lines contains two integers (ai, bi) (1 ≀ ai, bi ≀ n, ai ≠ bi) β€” the i-th foe pair. Note a foe pair can appear multiple times in the given list.OutputPrint the only integer c β€” the number of different intervals (x, y) that does not contain any foe pairs.Note that the answer can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.ExamplesInput4 21 3 2 43 22 4Output5Input9 59 7 2 3 1 4 6 5 81 64 52 77 22 7Output20NoteIn the first example the intervals from the answer are (1, 1), (1, 2), (2, 2), (3, 3) and (4, 4).
Input4 21 3 2 43 22 4
Output5
1 second
256 megabytes
['combinatorics', 'sortings', 'two pointers', '*1800']
B. z-sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold: ai β‰₯ ai - 1 for all even i, ai ≀ ai - 1 for all odd i > 1. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.Can you make the array z-sorted?InputThe first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of elements in the array a.The second line contains n integers ai (1 ≀ ai ≀ 109) β€” the elements of the array a.OutputIf it's possible to make the array a z-sorted print n space separated integers ai β€” the elements after z-sort. Otherwise print the only word "Impossible".ExamplesInput41 2 2 1Output1 2 1 2Input51 3 2 2 5Output1 5 2 3 2
Input41 2 2 1
Output1 2 1 2
1 second
256 megabytes
['sortings', '*1000']
A. Gabriel and Caterpillartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe 9-th grade student Gabriel noticed a caterpillar on a tree when walking around in a forest after the classes. The caterpillar was on the height h1 cm from the ground. On the height h2 cm (h2 > h1) on the same tree hung an apple and the caterpillar was crawling to the apple.Gabriel is interested when the caterpillar gets the apple. He noted that the caterpillar goes up by a cm per hour by day and slips down by b cm per hour by night.In how many days Gabriel should return to the forest to see the caterpillar get the apple. You can consider that the day starts at 10 am and finishes at 10 pm. Gabriel's classes finish at 2 pm. You can consider that Gabriel noticed the caterpillar just after the classes at 2 pm.Note that the forest is magic so the caterpillar can slip down under the ground and then lift to the apple.InputThe first line contains two integers h1, h2 (1 ≀ h1 < h2 ≀ 105) β€” the heights of the position of the caterpillar and the apple in centimeters.The second line contains two integers a, b (1 ≀ a, b ≀ 105) β€” the distance the caterpillar goes up by day and slips down by night, in centimeters per hour.OutputPrint the only integer k β€” the number of days Gabriel should wait to return to the forest and see the caterpillar getting the apple.If the caterpillar can't get the apple print the only integer  - 1.ExamplesInput10 302 1Output1Input10 131 1Output0Input10 191 2Output-1Input1 505 4Output1NoteIn the first example at 10 pm of the first day the caterpillar gets the height 26. At 10 am of the next day it slips down to the height 14. And finally at 6 pm of the same day the caterpillar gets the apple.Note that in the last example the caterpillar was slipping down under the ground and getting the apple on the next day.
Input10 302 1
Output1
1 second
256 megabytes
['implementation', 'math', '*1400']
B. Beautiful Paintingstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1 ≀ i ≀ n - 1), such that ai + 1 > ai.InputThe first line of the input contains integer n (1 ≀ n ≀ 1000)Β β€” the number of painting.The second line contains the sequence a1, a2, ..., an (1 ≀ ai ≀ 1000), where ai means the beauty of the i-th painting.OutputPrint one integerΒ β€” the maximum possible number of neighbouring pairs, such that ai + 1 > ai, after the optimal rearrangement.ExamplesInput520 30 10 50 40Output4Input4200 100 100 200Output2NoteIn the first sample, the optimal order is: 10, 20, 30, 40, 50.In the second sample, the optimal order is: 100, 200, 100, 200.
Input520 30 10 50 40
Output4
1 second
256 megabytes
['greedy', 'sortings', '*1200']
A. Joystickstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFriends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not connected to a charger) or charges by 1 percent (if connected to a charger).Game continues while both joysticks have a positive charge. Hence, if at the beginning of minute some joystick is charged by 1 percent, it has to be connected to a charger, otherwise the game stops. If some joystick completely discharges (its charge turns to 0), the game also stops.Determine the maximum number of minutes that game can last. It is prohibited to pause the game, i. e. at each moment both joysticks should be enabled. It is allowed for joystick to be charged by more than 100 percent.InputThe first line of the input contains two positive integers a1 and a2 (1 ≀ a1, a2 ≀ 100), the initial charge level of first and second joystick respectively.OutputOutput the only integer, the maximum number of minutes that the game can last. Game continues until some joystick is discharged.ExamplesInput3 5Output6Input4 4Output5NoteIn the first sample game lasts for 6 minute by using the following algorithm: at the beginning of the first minute connect first joystick to the charger, by the end of this minute first joystick is at 4%, second is at 3%; continue the game without changing charger, by the end of the second minute the first joystick is at 5%, second is at 1%; at the beginning of the third minute connect second joystick to the charger, after this minute the first joystick is at 3%, the second one is at 2%; continue the game without changing charger, by the end of the fourth minute first joystick is at 1%, second one is at 3%; at the beginning of the fifth minute connect first joystick to the charger, after this minute the first joystick is at 2%, the second one is at 1%; at the beginning of the sixth minute connect second joystick to the charger, after this minute the first joystick is at 0%, the second one is at 2%. After that the first joystick is completely discharged and the game is stopped.
Input3 5
Output6
1 second
256 megabytes
['dp', 'greedy', 'implementation', 'math', '*1100']
E. Clockwork Bombtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMy name is James diGriz, I'm the most clever robber and treasure hunter in the whole galaxy. There are books written about my adventures and songs about my operations, though you were able to catch me up in a pretty awkward moment.I was able to hide from cameras, outsmart all the guards and pass numerous traps, but when I finally reached the treasure box and opened it, I have accidentally started the clockwork bomb! Luckily, I have met such kind of bombs before and I know that the clockwork mechanism can be stopped by connecting contacts with wires on the control panel of the bomb in a certain manner.I see n contacts connected by n - 1 wires. Contacts are numbered with integers from 1 to n. Bomb has a security mechanism that ensures the following condition: if there exist k β‰₯ 2 contacts c1, c2, ..., ck forming a circuit, i. e. there exist k distinct wires between contacts c1 and c2, c2 and c3, ..., ck and c1, then the bomb immediately explodes and my story ends here. In particular, if two contacts are connected by more than one wire they form a circuit of length 2. It is also prohibited to connect a contact with itself.On the other hand, if I disconnect more than one wire (i. e. at some moment there will be no more than n - 2 wires in the scheme) then the other security check fails and the bomb also explodes. So, the only thing I can do is to unplug some wire and plug it into a new place ensuring the fact that no circuits appear.I know how I should put the wires in order to stop the clockwork. But my time is running out! Help me get out of this alive: find the sequence of operations each of which consists of unplugging some wire and putting it into another place so that the bomb is defused. InputThe first line of the input contains n (2 ≀ n ≀ 500 000), the number of contacts.Each of the following n - 1 lines contains two of integers xi and yi (1 ≀ xi, yi ≀ n, xi ≠ yi) denoting the contacts currently connected by the i-th wire.The remaining n - 1 lines contain the description of the sought scheme in the same format.It is guaranteed that the starting and the ending schemes are correct (i. e. do not contain cicuits nor wires connecting contact with itself).OutputThe first line should contain k (k β‰₯ 0)Β β€” the minimum number of moves of unplugging and plugging back some wire required to defuse the bomb.In each of the following k lines output four integers ai, bi, ci, di meaning that on the i-th step it is neccesary to unplug the wire connecting the contacts ai and bi and plug it to the contacts ci and di. Of course the wire connecting contacts ai and bi should be present in the scheme.If there is no correct sequence transforming the existing scheme into the sought one, output -1.ExamplesInput31 22 31 33 2Output11 2 1 3Input41 22 33 42 44 11 3Output31 2 1 34 3 4 12 3 2 4NotePicture with the clarification for the sample tests:
Input31 22 31 33 2
Output11 2 1 3
6 seconds
256 megabytes
['data structures', 'dfs and similar', 'dsu', 'greedy', 'trees', '*3200']
D. Zip-linetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has decided to build a zip-line on trees of a nearby forest. He wants the line to be as long as possible but he doesn't remember exactly the heights of all trees in the forest. He is sure that he remembers correct heights of all trees except, possibly, one of them.It is known that the forest consists of n trees staying in a row numbered from left to right with integers from 1 to n. According to Vasya, the height of the i-th tree is equal to hi. The zip-line of length k should hang over k (1 ≀ k ≀ n) trees i1, i2, ..., ik (i1 < i2 < ... < ik) such that their heights form an increasing sequence, that is hi1 < hi2 < ... < hik.Petya had been in this forest together with Vasya, and he now has q assumptions about the mistake in Vasya's sequence h. His i-th assumption consists of two integers ai and bi indicating that, according to Petya, the height of the tree numbered ai is actually equal to bi. Note that Petya's assumptions are independent from each other.Your task is to find the maximum length of a zip-line that can be built over the trees under each of the q assumptions.In this problem the length of a zip line is considered equal to the number of trees that form this zip-line.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 400 000)Β β€” the number of the trees in the forest and the number of Petya's assumptions, respectively.The following line contains n integers hi (1 ≀ hi ≀ 109)Β β€” the heights of trees according to Vasya.Each of the following m lines contains two integers ai and bi (1 ≀ ai ≀ n, 1 ≀ bi ≀ 109).OutputFor each of the Petya's assumptions output one integer, indicating the maximum length of a zip-line that can be built under this assumption.ExamplesInput4 41 2 3 41 11 44 34 5Output4334Input4 21 3 2 63 52 4Output43NoteConsider the first sample. The first assumption actually coincides with the height remembered by Vasya. In the second assumption the heights of the trees are (4, 2, 3, 4), in the third one they are (1, 2, 3, 3) and in the fourth one they are (1, 2, 3, 5).
Input4 41 2 3 41 11 44 34 5
Output4334
3 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'hashing', '*2600']