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
A. Turing Tapetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputINTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method.The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps:1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0.2. The i-th element of the array is subtracted from the result of the previous step modulo 256.3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed.You are given the text printed using this method. Restore the array used to produce this text.InputThe input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive.OutputOutput the initial array, which was used to produce text, one integer per line.ExamplesInputHello, World!Output23810811206419448262441682416162NoteLet's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
InputHello, World!
Output23810811206419448262441682416162
2 seconds
256 megabytes
['implementation', '*1300']
F. Present to Momtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHow many stars are there in the sky? A young programmer Polycarpus can't get this question out of his head! He took a photo of the starry sky using his digital camera and now he analyzes the resulting monochrome digital picture. The picture is represented by a rectangular matrix consisting of n lines each containing m characters. A character equals '1', if the corresponding photo pixel is white and '0', if it is black.Polycarpus thinks that he has found a star on the photo if he finds a white pixel surrounded by four side-neighboring pixels that are also white: 1 111 1 a star on the photo Polycarpus whats to cut out a rectangular area from the photo and give his mom as a present. This area should contain no less than k stars. The stars can intersect, have shared white pixels on the photo. The boy will cut out the rectangular area so that its borders will be parallel to the sides of the photo and the cuts will go straight between the pixel borders.Now Polycarpus keeps wondering how many ways there are to cut an area out of the photo so that it met the conditions given above. Help Polycarpus find this number.InputThe first line of the input data contains three integers n, m and k (1 ≀ n, m ≀ 500;1 ≀ k ≀ nm). Then follow n lines, containing the description of the given photo as a sequence of lines. Each line contains m characters '0' or '1'.OutputPrint the required number of areas on the given photo.ExamplesInput4 6 2111000111100011011000111Output6Input5 5 41111111111111111111111111Output9NoteWe'll number the rows and columns below starting from 1, the coordinates (p, q) will denote a cell in row p, column q.In the first sample Polycarpus should cut out any area containing a rectangle whose opposite corners lie in cells (1, 1) and (3, 4). Only rectangles with opposite corners in (1, 1) and (x, y), where x β‰₯ 3 and y β‰₯ 4 fit the conditions.In the second sample any rectangle whose each side is no less than four, will do. The possible rectangle sizes are 4 × 4, 4 × 5, 5 × 4 and 5 × 5. Such figures can be cut in 4 ways, 2 ways, 2 ways and 1 way correspondingly.Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cin, cout streams or the %I64d specificator.
Input4 6 2111000111100011011000111
Output6
5 seconds
256 megabytes
['binary search', 'two pointers', '*2000']
E. Yet Another Task with Queenstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop.There are m queens on a square n × n chessboard. You know each queen's positions, the i-th queen is positioned in the square (ri, ci), where ri is the board row number (numbered from the top to the bottom from 1 to n), and ci is the board's column number (numbered from the left to the right from 1 to n). No two queens share the same position.For each queen one can count w β€” the number of other queens that the given queen threatens (attacks). For a fixed attack direction only the first queen in this direction is under attack if there are many queens are on the ray of the attack. Obviously, for any queen w is between 0 and 8, inclusive.Print the sequence t0, t1, ..., t8, where ti is the number of queens that threaten exactly i other queens, i.e. the number of queens that their w equals i.InputThe first line of the input contains a pair of integers n, m (1 ≀ n, m ≀ 105), where n is the size of the board and m is the number of queens on the board. Then m following lines contain positions of the queens, one per line. Each line contains a pair of integers ri, ci (1 ≀ ri, ci ≀ n) β€” the queen's position. No two queens stand on the same square.OutputPrint the required sequence t0, t1, ..., t8, separating the numbers with spaces.ExamplesInput8 44 34 86 51 6Output0 3 0 1 0 0 0 0 0 Input10 31 11 21 3Output0 2 1 0 0 0 0 0 0
Input8 44 34 86 51 6
Output0 3 0 1 0 0 0 0 0
2 seconds
256 megabytes
['sortings', '*1700']
D. Subwaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA subway scheme, classic for all Berland cities is represented by a set of n stations connected by n passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage.Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once.This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say "I live in three passages from the ringroad" and another one could reply "you loser, I live in one passage from the ringroad". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...).The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.InputThe first line contains an integer n (3 ≀ n ≀ 3000), n is the number of stations (and trains at the same time) in the subway scheme. Then n lines contain descriptions of the trains, one per line. Each line contains a pair of integers xi, yi (1 ≀ xi, yi ≀ n) and represents the presence of a passage from station xi to station yi. The stations are numbered from 1 to n in an arbitrary order. It is guaranteed that xi ≠ yi and that no pair of stations contain more than one passage. The passages can be used to travel both ways. It is guaranteed that the given description represents a classic subway scheme.OutputPrint n numbers. Separate the numbers by spaces, the i-th one should be equal to the distance of the i-th station from the ringroad. For the ringroad stations print number 0.ExamplesInput41 34 34 21 2Output0 0 0 0 Input61 23 46 42 31 33 5Output0 0 0 1 1 2
Input41 34 34 21 2
Output0 0 0 0
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*1600']
C. The World is a Theatretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly t actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the troupe are considered different.Perform all calculations in the 64-bit type: long long for Π‘/Π‘++, int64 for Delphi and long for Java.InputThe only line of the input data contains three integers n, m, t (4 ≀ n ≀ 30, 1 ≀ m ≀ 30, 5 ≀ t ≀ n + m).OutputFind the required number of ways.Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.ExamplesInput5 2 5Output10Input4 3 5Output3
Input5 2 5
Output10
2 seconds
256 megabytes
['combinatorics', 'math', '*1400']
B. Opposites Attracttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≀ ti ≀ 10). Of course, one number can be assigned to any number of customers."Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, ..., tn. For example, if t = (1,  - 1, 1,  - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.Of course, a client can't form a couple with him/herself.InputThe first line of the input data contains an integer n (1 ≀ n ≀ 105) which represents the number of registered clients of the "Couple Matching". The second line contains a sequence of integers t1, t2, ..., tn ( - 10 ≀ ti ≀ 10), ti β€” is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.OutputPrint the number of couples of customs with opposite t. The opposite number for x is number  - x (0 is opposite to itself). Couples that only differ in the clients' order are considered the same.Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.ExamplesInput5-3 3 0 0 3Output3Input30 0 0Output3NoteIn the first sample the couples of opposite clients are: (1,2), (1,5) ΠΈ (3,4).In the second sample any couple of clients is opposite.
Input5-3 3 0 0 3
Output3
2 seconds
256 megabytes
['implementation', 'math', '*1200']
A. cAPS lOCKtime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputwHAT DO WE NEED cAPS LOCK FOR?Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentally switched on, if: either it only contains uppercase letters; or all letters except for the first one are uppercase. In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.InputThe first line of the input data contains a word consisting of uppercase and lowercase Latin letters. The word's length is from 1 to 100 characters, inclusive.OutputPrint the result of the given word's processing.ExamplesInputcAPSOutputCapsInputLockOutputLock
InputcAPS
OutputCaps
0.5 second
256 megabytes
['implementation', 'strings', '*1000']
J. Date calculationtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIn Gregorian calendar a typical year consists of 365 days and 12 months. The numbers of days in the months are: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31. If year index is divisible by 400, or divisible by 4 but not by 100, the year becomes leap year, with one extra day in the second month (the one which typically has 28 days).You are given the index of the year and the index of the day in the year. Find out the date of this day (day and month it will fall upon).InputThe first line of input contains the year index, between 1600 and 2400, inclusive. The second line contains the day index, between 1 and 366, inclusive. It is guaranteed that the day index will be valid for this year, i.e., day 366 will occur only in a leap year.OutputOutput the index of the day and the index of the month, separated with a space.ExamplesInput2011324Output20 11Input2012274Output30 9NoteAll indexes are 1-based.
Input2011324
Output20 11
2 seconds
64 megabytes
['*special problem', '*1800']
I. Array sortingtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputSorting arrays is traditionally associated with high-level languages. How hard can it be in Befunge? Sort the given array in non-descending order.InputThe first line of input contains an integer n (1 ≀ n ≀ 100) β€” the size of the array. The following n lines contain the elements of the array, one per line. Each element of the array is an integer between 1 and 60, inclusive. The array might contain duplicate elements.OutputOutput space-separated elements of the sorted array.ExamplesInput571973Output1 3 7 7 9 Input10601601601601601Output1 1 1 1 1 60 60 60 60 60
Input571973
Output1 3 7 7 9
2 seconds
64 megabytes
['*special problem', 'sortings', '*2300']
H. Balanced bracketstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputA sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters Β«+Β» and Β«1Β». For example, sequences Β«(())()Β», Β«()Β» and Β«(()(()))Β» are balanced, while Β«)(Β», Β«(()Β» and Β«(()))(Β» are not.You are given a string which consists of opening and closing round brackets. Check whether it is a balanced bracket sequence.InputThe only line of input contains a string between 1 and 100 characters long, inclusive. Each character in the string will be Β«(Β» or Β«)Β».OutputOutput Β«YESΒ» if the bracket sequence is balanced, and Β«NOΒ» otherwise (quotes for clarity only).ExamplesInput(()(()))()OutputYESInput())()OutputNO
Input(()(()))()
OutputYES
2 seconds
64 megabytes
['*special problem', '*1600']
G. CAPS LOCK ONtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a string which consists of letters and other characters. Convert it to uppercase, i.e., replace all lowercase letters with corresponding uppercase ones. Keep the rest of characters unchanged.InputThe only line of input contains a string between 1 and 100 characters long. Each character of the string has ASCII-code between 33 (exclamation mark) and 126 (tilde), inclusive.OutputOutput the given string, converted to uppercase.ExamplesInputcOdEfOrCeSOutputCODEFORCESInputulr#4:befunge-RULES!OutputULR#4:BEFUNGE-RULES!
InputcOdEfOrCeS
OutputCODEFORCES
2 seconds
64 megabytes
['*special problem', '*1700']
F. Prime factorizationtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given an integer n. Output its prime factorization.If n = a1b1a2b2 ... akbk, where ak are prime numbers, the output of your program should look as follows: a1 a1 ... a1 a2 a2 ... a2 ... ak ak ... ak, where factors are ordered in non-decreasing order, and each factor ai is printed bi times.InputThe only line of input contains an integer n (2 ≀ n ≀ 250).OutputOutput the prime factorization of n, as described above.ExamplesInput245Output5 7 7 Input13Output13
Input245
Output5 7 7
2 seconds
64 megabytes
['*special problem', '*1600']
E. Tribonacci numberstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputTribonacci numbers are a sequence of numbers, defined as follows: t0 = t1 = 0, t2 = 1, ti = ti - 1 + ti - 2 + ti - 3.You are given n; calculate n-th tribonacci number modulo 26.InputThe only line of input contains an integer n (1 ≀ n ≀ 1000).OutputOutput n-th tribonacci number modulo 26.ExamplesInput4Output2Input9Output18
Input4
Output2
2 seconds
64 megabytes
['*special problem', '*1600']
D. Exponentiationtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given integers a, b and c. Calculate ab modulo c.InputInput data contains numbers a, b and c, one number per line. Each number is an integer between 1 and 100, inclusive.OutputOutput ab mod c.ExamplesInput2540Output32Input2526Output6
Input2540
Output32
2 seconds
64 megabytes
['*special problem', '*1500']
C. Decimal sumtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given an array of integer numbers. Calculate the sum of its elements.InputThe first line of the input contains an integer n (1 ≀ n ≀ 100) β€” the size of the array. Next n lines contain the elements of the array, one per line. Each element is an integer between 1 and 100, inclusive.OutputOutput the sum of the elements of the array.ExamplesInput512345Output15Input710054586142030Output300
Input512345
Output15
2 seconds
64 megabytes
['*special problem', '*1500']
B. Gnikool Ssalgtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a string. Reverse its characters.InputThe only line of input contains a string between 1 and 100 characters long. Each character of the string has ASCII-code between 33 (exclamation mark) and 126 (tilde), inclusive.OutputOutput the characters of this string in reverse order.ExamplesInputsecrofedocOutputcodeforcesInput!ssalg-gnikool5Output5looking-glass!
Inputsecrofedoc
Outputcodeforces
2 seconds
64 megabytes
['*special problem', 'implementation', 'strings', '*1400']
A. Hexagonal numberstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputHexagonal numbers are figurate numbers which can be calculated using the formula hn = 2n2 - n. You are given n; calculate n-th hexagonal number.InputThe only line of input contains an integer n (1 ≀ n ≀ 100).OutputOutput the n-th hexagonal number.ExamplesInput2Output6Input5Output45
Input2
Output6
2 seconds
64 megabytes
['*special problem', 'implementation', '*900']
B. Students and Shoelacestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.InputThe first line contains two integers n and m β€” the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b β€” the numbers of students tied by the i-th lace (1 ≀ a, b ≀ n, a ≠ b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.OutputPrint the single number β€” the number of groups of students that will be kicked out from the club.ExamplesInput3 31 22 33 1Output0Input6 31 22 33 4Output2Input6 51 42 43 45 46 4Output1NoteIn the first sample Anna and Maria won't kick out any group of students β€” in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then β€” two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.
Input3 31 22 33 1
Output0
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'graphs', 'implementation', '*1200']
A. Cookiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOlga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?InputThe first line contains the only integer n (1 ≀ n ≀ 100) β€” the number of cookie bags Anna and Maria have. The second line contains n integers ai (1 ≀ ai ≀ 100) β€” the number of cookies in the i-th bag.OutputPrint in the only line the only number β€” the sought number of ways. If there are no such ways print 0.ExamplesInput11Output1Input101 2 2 3 4 4 4 2 2 2Output8Input112 2 2 2 2 2 2 2 2 2 99Output1NoteIn the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies β€” 5 + 3 = 8 ways in total.In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2 * 9 + 99 = 117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies.
Input11
Output1
2 seconds
256 megabytes
['implementation', '*900']
E. Birthdaytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnna's got a birthday today. She invited many guests and cooked a huge (nearly infinite) birthday cake decorated by n banana circles of different sizes. Maria's birthday is about to start in 7 minutes too, and while Anna is older, she decided to play the boss a little. She told Maria to cut the cake by k straight-line cuts (the cutting lines can intersect) to divide banana circles into banana pieces. Anna has many guests and she wants everyone to get at least one banana piece. That's why she told Maria to make the total number of banana pieces maximum. It's not a problem if some banana pieces end up on the same cake piece β€” the key is to make the maximum number of banana pieces. Determine what result Maria will achieve.InputThe first line contains two integers n and k β€” the number of banana circles and the number of cuts Maria should perform (1 ≀ n ≀ 1000, 1 ≀ k ≀ 105). Next n lines contain the positions and sizes of the banana circles (all banana circles are round). On the cake the Cartesian coordinate system is defined. Each line contains three integers x, y and r β€” the coordinates of the center of the corresponding banana piece and its radius ( - 1000 ≀ x, y ≀ 1000, 1 ≀ r ≀ 1000).It is guaranteed that the banana circles do not intersect, do not touch each other and do not overlap with each other.Pretest 10 is big test with n = k = 1000.OutputPrint the only integer β€” the largest number of banana pieces that Maria can get after she performs the k straight-line cuts.Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInput1 10 0 1Output2Input3 10 0 13 0 16 0 1Output6Input1 30 0 1Output7
Input1 10 0 1
Output2
4 seconds
256 megabytes
['geometry', 'math', '*2900']
D. Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her younger sister Maria came and shuffled all numbers. Anna got sick with anger but what's done is done and the results of her work had been destroyed. But please tell Anna: could she have hypothetically completed the task using all those given numbers?InputThe first line contains an integer n β€” how many numbers Anna had (3 ≀ n ≀ 105). The next line contains those numbers, separated by a space. All numbers are integers and belong to the range from 1 to 109.OutputPrint the single line "YES" (without the quotes), if Anna could have completed the task correctly using all those numbers (using all of them is necessary). If Anna couldn't have fulfilled the task, no matter how hard she would try, print "NO" (without the quotes).ExamplesInput41 2 3 2OutputYESInput61 1 2 2 2 3OutputYESInput62 4 1 1 2 2OutputNO
Input41 2 3 2
OutputYES
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*2000']
C. Games with Rectangletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this task Anna and Maria play the following game. Initially they have a checkered piece of paper with a painted n × m rectangle (only the border, no filling). Anna and Maria move in turns and Anna starts. During each move one should paint inside the last-painted rectangle a new lesser rectangle (along the grid lines). The new rectangle should have no common points with the previous one. Note that when we paint a rectangle, we always paint only the border, the rectangles aren't filled.Nobody wins the game β€” Anna and Maria simply play until they have done k moves in total. Count the number of different ways to play this game.InputThe first and only line contains three integers: n, m, k (1 ≀ n, m, k ≀ 1000).OutputPrint the single number β€” the number of the ways to play the game. As this number can be very big, print the value modulo 1000000007 (109 + 7).ExamplesInput3 3 1Output1Input4 4 1Output9Input6 7 2Output75NoteTwo ways to play the game are considered different if the final pictures are different. In other words, if one way contains a rectangle that is not contained in the other way.In the first sample Anna, who performs her first and only move, has only one possible action plan β€” insert a 1 × 1 square inside the given 3 × 3 square.In the second sample Anna has as much as 9 variants: 4 ways to paint a 1 × 1 square, 2 ways to insert a 1 × 2 rectangle vertically, 2 more ways to insert it horizontally and one more way is to insert a 2 × 2 square.
Input3 3 1
Output1
2 seconds
256 megabytes
['combinatorics', 'dp', '*2000']
B. Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day in the IT lesson Anna and Maria learned about the lexicographic order.String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≀ i ≀ min(|x|, |y|)), that xi < yi, and for any j (1 ≀ j < i) xj = yj. Here |a| denotes the length of the string a. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​.The teacher gave Anna and Maria homework. She gave them a string of length n. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the k-th string from the list. Help Anna and Maria do the homework.InputThe first line contains a non-empty string that only consists of small Latin letters ("a"-"z"), whose length does not exceed 105. The second line contains the only integer k (1 ≀ k ≀ 105).OutputPrint the string Anna and Maria need β€” the k-th (in the lexicographical order) substring of the given string. If the total number of substrings is less than k, print a string saying "No such line." (without the quotes).ExamplesInputaa2OutputaInputabc5OutputbcInputabab7OutputbNoteIn the second sample before string "bc" follow strings "a", "ab", "abc", "b".
Inputaa2
Outputa
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'hashing', 'implementation', 'string suffix structures', 'strings', '*2100']
A. Statuestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 × 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains a statue cannot have anything or anyone β€” neither any other statues, nor Anna, nor Maria.Anna is present on the board as a figurant (she stands still and never moves), and Maria has been actively involved in the game. Her goal is β€” to come to Anna's square. Maria and statues move in turn, Maria moves first. During one move Maria can go to any adjacent on the side or diagonal cell in which there is no statue, or she can stay in the cell where she is. The statues during their move must go one square down simultaneously, and those statues that were in the bottom row fall from the board and are no longer appeared.At that moment, when one of the statues is in the cell in which the Maria is, the statues are declared winners. At the moment when Maria comes into the cell where Anna has been waiting, Maria is declared the winner.Obviously, nothing depends on the statues, so it all depends on Maria. Determine who will win, if Maria does not make a strategic error.InputYou are given the 8 strings whose length equals 8, describing the initial position on the board. The first line represents the top row of the board, the next one β€” for the second from the top, and so on, the last line represents the bottom row. Each character string matches a single cell board in the appropriate row, and the characters are in the same manner as that of the corresponding cell. If the cell is empty, the corresponding character is ".". If a cell has Maria, then it is represented by character "M". If a cell has Anna, it is represented by the character "A". If a cell has a statue, then the cell is represented by character "S".It is guaranteed that the last character of the first row is always "A", the first character of the last line is always "M". The remaining characters are "." or "S".OutputIf Maria wins, print string "WIN". If the statues win, print string "LOSE".ExamplesInput.......A................................................M.......OutputWINInput.......A........................................SS......M.......OutputLOSEInput.......A.................................S......S.......MS......OutputLOSE
Input.......A................................................M.......
OutputWIN
2 seconds
256 megabytes
['dfs and similar', '*1500']
B. Canvas Framestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has n sticks whose lengths equal a1, a2, ... an. Nicholas does not want to break the sticks or glue them together. To make a h × w-sized frame, he needs two sticks whose lengths equal h and two sticks whose lengths equal w. Specifically, to make a square frame (when h = w), he needs four sticks of the same length.Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.InputThe first line contains an integer n (1 ≀ n ≀ 100) β€” the number of sticks. The second line contains n space-separated integers. The i-th integer equals the length of the i-th stick ai (1 ≀ ai ≀ 100).OutputPrint the single number β€” the maximum number of frames Nicholas can make for his future canvases.ExamplesInput52 4 3 2 3Output1Input132 2 4 4 4 4 6 6 6 7 7 9 9Output3Input43 3 3 5Output0
Input52 4 3 2 3
Output1
1 second
256 megabytes
['implementation', '*1000']
A. Wasted Timetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers.Mr. Scrooge's signature can be represented as a polyline A1A2... An. Scrooge signs like that: first it places a pen at the point A1, then draws a segment from point A1 to point A2, then he draws a segment from point A2 to point A3 and so on to point An, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant β€” 50 millimeters per second.Scrooge signed exactly k papers throughout his life and all those signatures look the same.Find the total time Scrooge wasted signing the papers.InputThe first line contains two integers n and k (2 ≀ n ≀ 100, 1 ≀ k ≀ 1000). Each of the following n lines contains the coordinates of the polyline's endpoints. The i-th one contains coordinates of the point Ai β€” integers xi and yi, separated by a space.All points Ai are different. The absolute value of all coordinates does not exceed 20. The coordinates are measured in millimeters.OutputPrint one real number β€” the total time Scrooges wastes on signing the papers in seconds. The absolute or relative error should not exceed 10 - 6.ExamplesInput2 10 010 0Output0.200000000Input5 103 1-5 6-2 -13 210 0Output6.032163204Input6 105 04 06 03 07 02 0Output3.000000000
Input2 10 010 0
Output0.200000000
2 seconds
256 megabytes
['geometry', '*900']
E. Pillstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDoctor prescribed medicine to his patient. The medicine is represented by pills. Each pill consists of a shell and healing powder. The shell consists of two halves; each half has one of four colors β€” blue, red, white or yellow.The doctor wants to put 28 pills in a rectangular box 7 × 8 in size. Besides, each pill occupies exactly two neighboring cells and any cell contains exactly one half of a pill. Thus, the result is a four colored picture 7 × 8 in size.The doctor thinks that a patient will recover sooner if the picture made by the pills will be special. Unfortunately, putting the pills in the box so as to get the required picture is not a very easy task. That's why doctor asks you to help. Doctor has some amount of pills of each of 10 painting types. They all contain the same medicine, that's why it doesn't matter which 28 of them will be stored inside the box.Place the pills in the box so that the required picture was formed. If it is impossible to place the pills in the required manner, then place them so that the number of matching colors in all 56 cells in the final arrangement and the doctor's picture were maximum.InputFirst 7 lines contain the doctor's picture. Each line contains 8 characters, each character can be "B", "R", "W" and "Y" that stands for blue, red, white and yellow colors correspondingly.Next four lines contain 10 numbers that stand for, correspondingly, the number of pills painted:"BY" "BW" "BR" "BB""RY" "RW" "RR""WY" "WW""YY"Those numbers lie within range from 0 to 28 inclusively. It is guaranteed that the total number of pills in no less than 28.OutputPrint on the first line the maximal number cells for which the colors match.Then print 13 lines each containing 15 characters β€” the pills' position in the optimal arrangement. The intersections of odd lines and odd columns should contain characters "B", "R", "W" and "Y". All other positions should contain characters ".", "-" and "|". Use "-" and "|" to show which halves belong to one pill. See the samples for more clarification.If there are several possible solutions, print any of them.ExamplesInputWWWBBWWWWWWBBWWWYYWBBWWWYYWBBWRRYYWBBWRRYYWBBWRRYYWBBWRR0 0 0 80 1 51 105Output53W.W.W.B.B.W.W.W|.|.|.|.|.|.|.|W.W.W.B.B.W.W.W...............Y.Y.W.B.B.W.W-W|.|.|.|.|.|....Y.Y.W.B.B.W.R.R............|.|Y.Y.W.B.B.R.R.R|.|.|.|.|.|....Y.Y.W.B.B.W.R.R............|.|Y-Y.B-B.B-B.R.RInputWWWWWWWWWBYWRBBYBRYRBWYYWWBRYWBBBWWRWBYWRBWRBWYYWWWWWWWW0 0 0 10 0 10 125Output15W.Y.Y-Y.Y-Y.Y-Y|.|............W.Y.Y.Y.Y.B-B.Y....|.|.|.....|Y-Y.Y.Y.Y.Y-Y.Y...............Y.Y.Y.R.Y.Y.Y-Y|.|.|.|.|.|....Y.Y.Y.R.Y.Y.Y.Y............|.|Y-Y.Y.Y-Y.Y.Y.Y....|.....|....Y-Y.Y.Y-Y.Y.Y-Y
InputWWWBBWWWWWWBBWWWYYWBBWWWYYWBBWRRYYWBBWRRYYWBBWRRYYWBBWRR0 0 0 80 1 51 105
Output53W.W.W.B.B.W.W.W|.|.|.|.|.|.|.|W.W.W.B.B.W.W.W...............Y.Y.W.B.B.W.W-W|.|.|.|.|.|....Y.Y.W.B.B.W.R.R............|.|Y.Y.W.B.B.R.R.R|.|.|.|.|.|....Y.Y.W.B.B.W.R.R............|.|Y-Y.B-B.B-B.R.R
1.5 seconds
256 megabytes
['brute force', 'flows', '*2900']
D. Fibonacci Sumstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFibonacci numbers have the following form:F1 = 1,  F2 = 2,  Fi = Fi - 1 + Fi - 2, i > 2.Let's consider some non-empty set S = {s1, s2, ..., sk}, consisting of different Fibonacci numbers. Let's find the sum of values of this set's elements:Let's call the set S a number n's decomposition into Fibonacci sum. It's easy to see that several numbers have several decompositions into Fibonacci sum. For example, for 13 we have 13, 5 + 8, 2 + 3 + 8 β€” three decompositions, and for 16: 3 + 13, 1 + 2 + 13, 3 + 5 + 8, 1 + 2 + 5 + 8 β€” four decompositions.By the given number n determine the number of its possible different decompositions into Fibonacci sum.InputThe first line contains an integer t β€” the number of tests (1 ≀ t ≀ 105). Each of the following t lines contains one test.Each test is an integer n (1 ≀ n ≀ 1018).Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.OutputFor each input data test print a single number on a single line β€” the answer to the problem.ExamplesInput21316Output34NoteTwo decompositions are different if there exists a number that is contained in the first decomposition, but is not contained in the second one. Decompositions that differ only in the order of summands are considered equal.
Input21316
Output34
1 second
256 megabytes
['dp', 'math', '*2300']
C. E-reader Displaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers.The display is represented by n × n square of pixels, each of which can be either black or white. The display rows are numbered with integers from 1 to n upside down, the columns are numbered with integers from 1 to n from the left to the right. The display can perform commands like "x, y". When a traditional display fulfills such command, it simply inverts a color of (x, y), where x is the row number and y is the column number. But in our new display every pixel that belongs to at least one of the segments (x, x) - (x, y) and (y, y) - (x, y) (both ends of both segments are included) inverts a color.For example, if initially a display 5 × 5 in size is absolutely white, then the sequence of commands (1, 4), (3, 5), (5, 1), (3, 3) leads to the following changes: You are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white.InputThe first line contains number n (1 ≀ n ≀ 2000).Next n lines contain n characters each: the description of the picture that needs to be shown. "0" represents the white color and "1" represents the black color. OutputPrint one integer z β€” the least number of commands needed to display the picture.ExamplesInput50111010010100011001111110Output4
Input50111010010100011001111110
Output4
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*2000']
B. Passwordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAsterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.InputYou are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.OutputPrint the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.ExamplesInputfixprefixsuffixOutputfixInputabcdabcOutputJust a legend
Inputfixprefixsuffix
Outputfix
2 seconds
256 megabytes
['binary search', 'dp', 'hashing', 'string suffix structures', 'strings', '*1700']
A. Hot Bathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can transmit from 0 to x2 water units per second.If y1 water units per second flow through the first tap and y2 water units per second flow through the second tap, then the resulting bath water temperature will be:Bob wants to open both taps so that the bath water temperature was not less than t0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible.Determine how much each tap should be opened so that Bob was pleased with the result in the end.InputYou are given five integers t1, t2, x1, x2 and t0 (1 ≀ t1 ≀ t0 ≀ t2 ≀ 106, 1 ≀ x1, x2 ≀ 106).OutputPrint two space-separated integers y1 and y2 (0 ≀ y1 ≀ x1, 0 ≀ y2 ≀ x2).ExamplesInput10 70 100 100 25Output99 33Input300 500 1000 1000 300Output1000 0Input143 456 110 117 273Output76 54NoteIn the second sample the hot water tap shouldn't be opened, but the cold water tap should be opened at full capacity in order to fill the bath in the quickest way possible.
Input10 70 100 100 25
Output99 33
2 seconds
256 megabytes
['binary search', 'brute force', 'math', '*1900']
E. MST Companytime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe MST (Meaningless State Team) company won another tender for an important state reform in Berland.There are n cities in Berland, some pairs of the cities are connected by roads. Each road has its price. One can move along any road in any direction. The MST team should carry out the repair works on some set of roads such that one can get from any city to any other one moving only along the repaired roads. Moreover, this set should contain exactly k capital roads (that is, the roads that start or finish in the capital). The number of the capital is 1.As the budget has already been approved, the MST Company will profit by finding the set with minimum lengths of roads.InputThe first input line contains three integers n, m, k (1 ≀ n ≀ 5000;0 ≀ m ≀ 105;0 ≀ k < 5000), where n is the number of cities in the country, m is the number of roads in the country, k is the number of capital roads in the required set. Then m lines enumerate the roads in question. Each road is specified by three numbers ai, bi, wi (1 ≀ ai, bi ≀ n; 1 ≀ w ≀ 105), where ai, bi are the numbers of cities linked by a road and wi is its length. Between each pair of cities no more than one road exists. There are no roads that start and finish in one city. The capital's number is 1.OutputIn the first line print the number of roads in the required set. The second line should contain the numbers of roads included in the sought set. If the sought set does not exist, print -1.ExamplesInput4 5 21 2 12 3 13 4 11 3 31 4 2Output31 5 2
Input4 5 21 2 12 3 13 4 11 3 31 4 2
Output31 5 2
8 seconds
256 megabytes
['binary search', 'graphs', '*2400']
D. Two progressionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn arithmetic progression is such a non-empty sequence of numbers where the difference between any two successive numbers is constant. This constant number is called common difference. For example, the sequence 3, 7, 11, 15 is an arithmetic progression. The definition implies that any sequences whose length equals 1 or 2 are arithmetic and all sequences whose length equals 0 are non-arithmetic.You are given a sequence of different integers a1, a2, ..., an. You should either split it into two arithmetic progressions or find out that the operation is impossible to perform. Splitting assigns each member of the given sequence to one of two progressions, but the relative order of numbers does not change. Splitting is an inverse operation to merging.InputThe first line contains a positive integer n (2 ≀ n ≀ 30000), n is the length of the given sequence. The second line contains elements of the given sequence a1, a2, ..., an ( - 108 ≀ ai ≀ 108). The elements of the progression are different integers.OutputPrint the required arithmetic progressions, one per line. The progressions can be positioned in any order. Each progression should contain at least one number. If there's no solution, then print "No solution" (without the quotes)in the only line of the input file. If there are several solutions, print any of them.ExamplesInput64 1 2 7 3 10Output1 2 3 4 7 10 Input51 2 3 -2 -7Output1 2 3 -2 -7 NoteIn the second sample another solution is also possible (number three can be assigned to the second progression): 1, 2 and 3, -2, -7.
Input64 1 2 7 3 10
Output1 2 3 4 7 10
1 second
256 megabytes
['constructive algorithms', 'greedy', '*2200']
C. Hobbits' Partytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEveryone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.InputThe first line contains an integer n (3 ≀ n ≀ 10000), representing the number of hobbits.OutputIn the first output line print a number k β€” the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.ExamplesInput4Output31 2 1 3 2 3 Input5Output31 2 1 3 2 3
Input4
Output31 2 1 3 2 3
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1600']
B. Simple XMLtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter.Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair.Let's define the notion of a XML-text: an empty string is a XML-text if s is a XML-text, then s'=<a>+s+</a> also is a XML-text, where a is any small Latin letter if s1, s2 are XML-texts, then s1+s2 also is a XML-text You are given a XML-text (it is guaranteed that the text is valid), your task is to print in the following form: each tag (opening and closing) is located on a single line print before the tag 2 * h spaces, where h is the level of the tag's nestedness. InputThe input data consists on the only non-empty string β€” the XML-text, its length does not exceed 1000 characters. It is guaranteed that the text is valid. The text contains no spaces.OutputPrint the given XML-text according to the above-given rules.ExamplesInput<a><b><c></c></b></a>Output<a> <b> <c> </c> </b></a>Input<a><b></b><d><c></c></d></a>Output<a> <b> </b> <d> <c> </c> </d></a>
Input<a><b><c></c></b></a>
Output<a> <b> <c> </c> </b></a>
2 seconds
256 megabytes
['implementation', '*1000']
A. Measuring Lengths in Badentime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLengths are measures in Baden in inches and feet. To a length from centimeters it is enough to know that an inch equals three centimeters in Baden and one foot contains 12 inches.You are given a length equal to n centimeters. Your task is to convert it to feet and inches so that the number of feet was maximum. The result should be an integer rounded to the closest value containing an integral number of inches.Note that when you round up, 1 cm rounds up to 0 inches and 2 cm round up to 1 inch.InputThe only line contains an integer n (1 ≀ n ≀ 10000).OutputPrint two non-negative space-separated integers a and b, where a is the numbers of feet and b is the number of inches.ExamplesInput42Output1 2Input5Output0 2
Input42
Output1 2
2 seconds
256 megabytes
['math', '*1400']
B. Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n k-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers.InputThe first line contains integers n and k β€” the number and digit capacity of numbers correspondingly (1 ≀ n, k ≀ 8). Next n lines contain k-digit positive integers. Leading zeroes are allowed both in the initial integers and the integers resulting from the rearranging of digits.OutputPrint a single number: the minimally possible difference between the largest and the smallest number after the digits are rearranged in all integers by the same rule.ExamplesInput6 4523727537523572353272537Output2700Input3 3010909012Output3Input7 550808366033719844911299944254350156Output20522NoteIn the first sample, if we rearrange the digits in numbers as (3,1,4,2), then the 2-nd and the 4-th numbers will equal 5237 and 2537 correspondingly (they will be maximum and minimum for such order of digits).In the second sample, if we swap the second digits and the first ones, we get integers 100, 99 and 102.
Input6 4523727537523572353272537
Output2700
1 second
256 megabytes
['brute force', 'combinatorics', 'implementation', '*1400']
A. The number of positionstime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy.InputThe only line contains three integers n, a and b (0 ≀ a, b < n ≀ 100).OutputPrint the single number β€” the number of the sought positions.ExamplesInput3 1 1Output2Input5 2 3Output3NoteThe possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1).In the second sample they are 3, 4 and 5.
Input3 1 1
Output2
0.5 second
256 megabytes
['math', '*1000']
E. Mazetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA maze is represented by a tree (an undirected graph, where exactly one way exists between each pair of vertices). In the maze the entrance vertex and the exit vertex are chosen with some probability. The exit from the maze is sought by Deep First Search. If there are several possible ways to move, the move is chosen equiprobably. Consider the following pseudo-code:DFS(x) if x == exit vertex then finish search flag[x] <- TRUE random shuffle the vertices' order in V(x) // here all permutations have equal probability to be chosen for i <- 1 to length[V] do if flag[V[i]] = FALSE then count++; DFS(y); count++;V(x) is the list vertices adjacent to x. The flag array is initially filled as FALSE. DFS initially starts with a parameter of an entrance vertex. When the search is finished, variable count will contain the number of moves.Your task is to count the mathematical expectation of the number of moves one has to do to exit the maze.InputThe first line determines the number of vertices in the graph n (1 ≀ n ≀ 105). The next n - 1 lines contain pairs of integers ai and bi, which show the existence of an edge between ai and bi vertices (1 ≀ ai, bi ≀ n). It is guaranteed that the given graph is a tree.Next n lines contain pairs of non-negative numbers xi and yi, which represent the probability of choosing the i-th vertex as an entrance and exit correspondingly. The probabilities to choose vertex i as an entrance and an exit equal and correspondingly. The sum of all xi and the sum of all yi are positive and do not exceed 106.OutputPrint the expectation of the number of moves. The absolute or relative error should not exceed 10 - 9.ExamplesInput21 20 11 0Output1.00000000000000000000Input31 21 31 00 20 3Output2.00000000000000000000Input71 21 32 42 53 63 71 11 11 11 11 11 11 1Output4.04081632653NoteIn the first sample the entrance vertex is always 1 and the exit vertex is always 2.In the second sample the entrance vertex is always 1 and the exit vertex with the probability of 2/5 will be 2 of with the probability if 3/5 will be 3. The mathematical expectations for the exit vertices 2 and 3 will be equal (symmetrical cases). During the first move one can go to the exit vertex with the probability of 0.5 or to go to a vertex that's not the exit vertex with the probability of 0.5. In the first case the number of moves equals 1, in the second one it equals 3. The total mathematical expectation is counted as 2 / 5 × (1 × 0.5 + 3 × 0.5) + 3 / 5 × (1 × 0.5 + 3 × 0.5)
Input21 20 11 0
Output1.00000000000000000000
1 second
256 megabytes
['dfs and similar', 'dp', 'probabilities', 'trees', '*2500']
D. Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s. Each pair of numbers l and r that fulfill the condition 1 ≀ l ≀ r ≀ |s|, correspond to a substring of the string s, starting in the position l and ending in the position r (inclusive).Let's define the function of two strings F(x, y) like this. We'll find a list of such pairs of numbers for which the corresponding substrings of string x are equal to string y. Let's sort this list of pairs according to the pair's first number's increasing. The value of function F(x, y) equals the number of non-empty continuous sequences in the list.For example: F(babbabbababbab, babb) = 6. The list of pairs is as follows:(1, 4), (4, 7), (9, 12)Its continuous sequences are: (1, 4) (4, 7) (9, 12) (1, 4), (4, 7) (4, 7), (9, 12) (1, 4), (4, 7), (9, 12) Your task is to calculate for the given string s the sum F(s, x) for all x, that x belongs to the set of all substrings of a string s.InputThe only line contains the given string s, consisting only of small Latin letters (1 ≀ |s| ≀ 105).OutputPrint the single number β€” the sought sum.Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInputaaaaOutput20InputabcdefOutput21InputabacabadabacabaOutput188NoteIn the first sample the function values at x equal to "a", "aa", "aaa" and "aaaa" equal 10, 6, 3 and 1 correspondingly.In the second sample for any satisfying x the function value is 1.
Inputaaaa
Output20
2 seconds
256 megabytes
['string suffix structures', '*2300']
C. Bracketstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA two dimensional array is called a bracket array if each grid contains one of the two possible brackets β€” "(" or ")". A path through the two dimensional array cells is called monotonous if any two consecutive cells in the path are side-adjacent and each cell of the path is located below or to the right from the previous one. A two dimensional array whose size equals n × m is called a correct bracket array, if any string formed by writing out the brackets on some monotonous way from cell (1, 1) to cell (n, m) forms a correct bracket sequence. Let's define the operation of comparing two correct bracket arrays of equal size (a and b) like that. Let's consider a given two dimensional array of priorities (c) β€” a two dimensional array of same size, containing different integers from 1 to nm. Let's find such position (i, j) in the two dimensional array, that ai, j ≠ bi, j. If there are several such positions, let's choose the one where number ci, j is minimum. If ai, j = "(", then a < b, otherwise a > b. If the position (i, j) is not found, then the arrays are considered equal.Your task is to find a k-th two dimensional correct bracket array. It is guaranteed that for the given sizes of n and m there will be no less than k two dimensional correct bracket arrays.InputThe first line contains integers n, m and k β€” the sizes of the array and the number of the sought correct bracket array (1 ≀ n, m ≀ 100, 1 ≀ k ≀ 1018). Then an array of priorities is given, n lines each containing m numbers, number pi, j shows the priority of character j in line i (1 ≀ pi, j ≀ nm, all pi, j are different).Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.OutputPrint the k-th two dimensional correct bracket array.ExamplesInput1 2 11 2Output()Input2 3 11 2 34 5 6Output(()())Input3 2 23 61 42 5Output())(()NoteIn the first sample exists only one correct two-dimensional bracket array.In the second and in the third samples two arrays exist.A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters Β«+Β» and Β«1Β» into this sequence. For example, sequences Β«(())()Β», Β«()Β» and Β«(()(()))Β» are regular, while Β«)(Β», Β«(()Β» and Β«(()))(Β» are not.
Input1 2 11 2
Output()
1 second
256 megabytes
['combinatorics', 'dp', 'greedy', '*2300']
B. Squarestime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: |x + y| ≑ 0 (modΒ 2a), |x - y| ≑ 0 (modΒ 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2).InputThe only line contains integers a, b, x1, y1, x2 and y2 β€” the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≀ a, b ≀ 109 and |x1|,|y1|,|x2|,|y2| ≀ 109). It is guaranteed that the initial and the final square aren't bad.OutputPrint a single number β€” the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2).ExamplesInput2 2 1 0 0 1Output1Input2 2 10 11 0 1Output5Input2 4 3 -1 3 7Output2NoteIn the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad.
Input2 2 1 0 0 1
Output1
0.5 second
256 megabytes
['math', '*1800']
A. Prime Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≀ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.InputThe only line contains the initial string s, consisting of small Latin letters (1 ≀ |s| ≀ 1000).OutputIf it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".ExamplesInputabcOutputYESabcInputabcdOutputNOInputxxxyxxxOutputYESxxxxxxyNoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.
Inputabc
OutputYESabc
1 second
256 megabytes
['implementation', 'number theory', 'strings', '*1300']
B. Lucky Substringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya was delivered a string s, containing only digits. He needs to find a string that represents a lucky number without leading zeroes, is not empty, is contained in s as a substring the maximum number of times.Among all the strings for which the three conditions given above are fulfilled, Petya only needs the lexicographically minimum one. Find this string for Petya.InputThe single line contains a non-empty string s whose length can range from 1 to 50, inclusive. The string only contains digits. The string can contain leading zeroes.OutputIn the only line print the answer to Petya's problem. If the sought string does not exist, print "-1" (without quotes).ExamplesInput047Output4Input16Output-1Input472747Output7NoteThe lexicographical comparison of strings is performed by the < operator in the modern programming languages. String x is lexicographically less than string y either if x is a prefix of y, or exists such i (1 ≀ i ≀ min(|x|, |y|)), that xi < yi and for any j (1 ≀ j < i) xj = yj. Here |a| denotes the length of string a.In the first sample three conditions are fulfilled for strings "4", "7" and "47". The lexicographically minimum one is "4".In the second sample s has no substrings which are lucky numbers.In the third sample the three conditions are only fulfilled for string "7".
Input047
Output4
2 seconds
256 megabytes
['brute force', 'implementation', '*1000']
A. Lucky Divisiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find out if the given number n is almost lucky.InputThe single line contains an integer n (1 ≀ n ≀ 1000) β€” the number that needs to be checked.OutputIn the only line print "YES" (without the quotes), if number n is almost lucky. Otherwise, print "NO" (without the quotes).ExamplesInput47OutputYESInput16OutputYESInput78OutputNONoteNote that all lucky numbers are almost lucky as any number is evenly divisible by itself.In the first sample 47 is a lucky number. In the second sample 16 is divisible by 4.
Input47
OutputYES
2 seconds
256 megabytes
['brute force', 'number theory', '*1000']
E. Lucky Arraytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has an array consisting of n numbers. He wants to perform m operations of two types: add l r d β€” add an integer d to all elements whose indexes belong to the interval from l to r, inclusive (1 ≀ l ≀ r ≀ n, 1 ≀ d ≀ 104); count l r β€” find and print on the screen how many lucky numbers there are among elements with indexes that belong to the interval from l to r inclusive (1 ≀ l ≀ r ≀ n). Each lucky number should be counted as many times as it appears in the interval. Petya has a list of all operations. The operations are such that after all additions the array won't have numbers that would exceed 104. Help Petya write a program that would perform these operations.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 105) β€” the number of numbers in the array and the number of operations correspondingly. The second line contains n positive integers, none of which exceeds 104 β€” those are the array numbers. Next m lines contain operations, one per line. They correspond to the description given in the statement.It is guaranteed that after all operations are fulfilled each number in the array will not exceed 104.OutputFor each operation of the second type print the single number on the single line β€” the number of lucky numbers in the corresponding interval.ExamplesInput3 62 3 4count 1 3count 1 2add 1 3 2count 1 3add 2 3 3count 1 3Output1011Input4 54 4 4 4count 1 4add 1 4 3count 1 4add 2 3 40count 1 4Output444NoteIn the first sample after the first addition the array will look in the following manner:4 5 6After the second addition:4 8 9The second sample after the first addition:7 7 7 7After the second addition:7 47 47 7
Input3 62 3 4count 1 3count 1 2add 1 3 2count 1 3add 2 3 3count 1 3
Output1011
4 seconds
256 megabytes
['data structures', '*2400']
D. Lucky Segmentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has n number segments [l1;Β r1], [l2;Β r2], ..., [ln;Β rn]. During one move Petya can take any segment (let it be segment number i) and replace it with segment [li + 1;Β ri + 1] or [li - 1;Β ri - 1]. In other words, during one move Petya can shift any segment to the left or to the right by a unit distance. Petya calls a number full if it belongs to each segment. That is, number x is full if for any i (1 ≀ i ≀ n) the condition li ≀ x ≀ ri is fulfilled.Petya makes no more than k moves. After that he counts the quantity of full lucky numbers. Find the maximal quantity that he can get.InputThe first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ 1018) β€” the number of segments and the maximum number of moves. Next n lines contain pairs of integers li and ri (1 ≀ li ≀ ri ≀ 1018).Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the %I64d specificator.OutputPrint on the single line the single number β€” the answer to the problem.ExamplesInput4 71 46 94 73 5Output1Input2 740 4547 74Output2NoteIn the first sample Petya shifts the second segment by two units to the left (it turns into [4;Β 7]), after that number 4 becomes full.In the second sample Petya shifts the first segment by two units to the right (it turns into [42;Β 47]), and shifts the second segment by three units to the left (it turns into [44;Β 71]), after that numbers 44 and 47 become full.
Input4 71 46 94 73 5
Output1
4 seconds
256 megabytes
['binary search', 'implementation', 'two pointers', '*2500']
C. Lucky Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.InputThe first line contains two integers n and k (1 ≀ n, k ≀ 109) β€” the number of elements in the permutation and the lexicographical number of the permutation.OutputIf the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers.ExamplesInput7 4Output1Input4 7Output1NoteA permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≀ i ≀ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations.In the first sample the permutation looks like that:1 2 3 4 6 7 5The only suitable position is 4.In the second sample the permutation looks like that:2 1 3 4The only suitable position is 4.
Input7 4
Output1
2 seconds
256 megabytes
['brute force', 'combinatorics', 'number theory', '*1900']
B. Lucky Transformationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has a number consisting of n digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it d. The numeration starts with 1, starting from the most significant digit. Petya wants to perform the following operation k times: find the minimum x (1 ≀ x < n) such that dx = 4 and dx + 1 = 7, if x is odd, then to assign dx = dx + 1 = 4, otherwise to assign dx = dx + 1 = 7. Note that if no x was found, then the operation counts as completed and the array doesn't change at all.You are given the initial number as an array of digits and the number k. Help Petya find the result of completing k operations.InputThe first line contains two integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 109) β€” the number of digits in the number and the number of completed operations. The second line contains n digits without spaces representing the array of digits d, starting with d1. It is guaranteed that the first digit of the number does not equal zero.OutputIn the single line print the result without spaces β€” the number after the k operations are fulfilled.ExamplesInput7 44727447Output4427477Input4 24478Output4478NoteIn the first sample the number changes in the following sequence: 4727447 → 4427447 → 4427477 → 4427447 → 4427477.In the second sample: 4478 → 4778 → 4478.
Input7 44727447
Output4427477
2 seconds
256 megabytes
['strings', '*1500']
A. Lucky Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Let next(x) be the minimum lucky number which is larger than or equals x. Petya is interested what is the value of the expression next(l) + next(l + 1) + ... + next(r - 1) + next(r). Help him solve this problem.InputThe single line contains two integers l and r (1 ≀ l ≀ r ≀ 109) β€” the left and right interval limits.OutputIn the single line print the only number β€” the sum next(l) + next(l + 1) + ... + next(r - 1) + next(r).Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInput2 7Output33Input7 7Output7NoteIn the first sample: next(2) + next(3) + next(4) + next(5) + next(6) + next(7) = 4 + 4 + 4 + 7 + 7 + 7 = 33In the second sample: next(7) = 7
Input2 7
Output33
2 seconds
256 megabytes
['implementation', '*1100']
J. Minimum Sumtime limit per test2 secondsmemory limit per test256 megabytesinputinput.txtoutputoutput.txtYou are given a set of n vectors on a plane. For each vector you are allowed to multiply any of its coordinates by -1. Thus, each vector vi = (xi, yi) can be transformed into one of the following four vectors: vi1 = (xi, yi), vi2 = ( - xi, yi), vi3 = (xi,  - yi), vi4 = ( - xi,  - yi). You should find two vectors from the set and determine which of their coordinates should be multiplied by -1 so that the absolute value of the sum of the resulting vectors was minimally possible. More formally, you should choose two vectors vi, vj (1 ≀ i, j ≀ n, i ≠ j) and two numbers k1, k2 (1 ≀ k1, k2 ≀ 4), so that the value of the expression |vik1 + vjk2| were minimum.InputThe first line contains a single integer n (2 ≀ n ≀ 105). Then n lines contain vectors as pairs of integers "xi yi" ( - 10000 ≀ xi, yi ≀ 10000), one pair per line.OutputPrint on the first line four space-separated numbers "i k1 j k2" β€” the answer to the problem. If there are several variants the absolute value of whose sums is minimum, you can print any of them. ExamplesInput5-7 -39 0-8 67 -84 -5Output3 2 4 2Input53 2-4 7-6 0-8 45 1Output3 4 5 4NoteA sum of two vectors v = (xv, yv) and u = (xu, yu) is vector s = v + u = (xv + xu, yv + yu).An absolute value of vector v = (x, y) is number . In the second sample there are several valid answers, such as:(3 1 4 2), (3 1 4 4), (3 4 4 1), (3 4 4 3), (4 1 3 2), (4 1 3 4), (4 2 3 1).
Input5-7 -39 0-8 67 -84 -5
Output3 2 4 2
2 seconds
256 megabytes
['divide and conquer', 'geometry', 'sortings', '*1900']
I. Luck is in Numberstime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtVasya has been collecting transport tickets for quite a while now. His collection contains several thousands of tram, trolleybus and bus tickets. Vasya is already fed up with the traditional definition of what a lucky ticket is. Thus, he's looking for new perspectives on that. Besides, Vasya cannot understand why all tickets are only divided into lucky and unlucky ones. He thinks that all tickets are lucky but in different degrees. Having given the matter some thought, Vasya worked out the definition of a ticket's degree of luckiness. Let a ticket consist of 2n digits. Let's regard each digit as written as is shown on the picture: You have seen such digits on electronic clocks: seven segments are used to show digits. Each segment can either be colored or not. The colored segments form a digit. Vasya regards the digits as written in this very way and takes the right half of the ticket and puts it one the left one, so that the first digit coincides with the n + 1-th one, the second digit coincides with the n + 2-th one, ..., the n-th digit coincides with the 2n-th one. For each pair of digits, put one on another, he counts the number of segments colored in both digits and summarizes the resulting numbers. The resulting value is called the degree of luckiness of a ticket. For example, the degree of luckiness of ticket 03 equals four and the degree of luckiness of ticket 2345 equals six.You are given the number of a ticket containing 2n digits. Your task is to find among the tickets whose number exceeds the number of this ticket but also consists of 2n digits such ticket, whose degree of luckiness exceeds the degrees of luckiness of the given ticket. Moreover, if there are several such tickets, you should only choose the one with the smallest number.InputThe first line contains the number of the ticket that consists of k characters (k = 2n, 1 ≀ n ≀ 105). OutputPrint the number of the sought ticket or "-1" (without the quotes) if no such ticket exists.ExamplesInput13Output20Input2345Output2348Input88Output-1
Input13
Output20
1 second
256 megabytes
['greedy', '*2200']
H. Brevity is Soul of Wittime limit per test2 secondsmemory limit per test256 megabytesinputinput.txtoutputoutput.txtAs we communicate, we learn much new information. However, the process of communication takes too much time. It becomes clear if we look at the words we use in our everyday speech.We can list many simple words consisting of many letters: "information", "technologies", "university", "construction", "conservatoire", "refrigerator", "stopwatch", "windowsill", "electricity", "government" and so on. Of course, we can continue listing those words ad infinitum. Fortunately, the solution for that problem has been found. To make our speech clear and brief, we should replace the initial words with those that resemble them but are much shorter. This idea hasn't been brought into life yet, that's why you are chosen to improve the situation. Let's consider the following formal model of transforming words: we shall assume that one can use n words in a chat. For each words we shall introduce a notion of its shorter variant. We shall define shorter variant of an arbitrary word s as such word t, that meets the following conditions: it occurs in s as a subsequence, its length ranges from one to four characters. In other words, the word t consists at least of one and at most of four characters that occur in the same order in the word s. Note that those characters do not necessarily follow in s immediately one after another. You are allowed not to shorten the initial word if its length does not exceed four characters.You are given a list of n different words. Your task is to find a set of their shortened variants. The shortened variants of all words from the list should be different.InputThe first line of the input file contains the only integer n (1 ≀ n ≀ 200). Then n lines contain a set of different non-empty words that consist of lowercase Latin letters. The length of each word does not exceed 10 characters.OutputIf the solution exists, print in the output file exactly n lines, where the i-th line represents the shortened variant of the i-th word from the initial set. If there are several variants to solve the problem, print any of them. If there is no solution, print -1.ExamplesInput6privetspasibocodeforcesjavamarmeladnormalnoOutputpretspscdfsjavamamanormInput5aaaaaaaaaaaaaaaOutput-1
Input6privetspasibocodeforcesjavamarmeladnormalno
Outputpretspscdfsjavamamanorm
2 seconds
256 megabytes
['graph matchings', '*1800']
G. Boomtime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtLet's consider the famous game called Boom (aka Hat) with simplified rules.There are n teams playing the game. Each team has two players. The purpose of the game is to explain the words to the teammate without using any words that contain the same root or that sound similarly. Player j from team i (1 ≀ i ≀ n, 1 ≀ j ≀ 2) is characterized by two numbers: aij and bij. The numbers correspondingly represent the skill of explaining and the skill of understanding this particular player has. Besides, m cards are used for the game. Each card has a word written on it. The card number k (1 ≀ k ≀ m) is characterized by number ck β€” the complexity of the word it contains.Before the game starts the cards are put in a deck and shuffled. Then the teams play in turns like that: the 1-st player of the 1-st team, the 1-st player of the 2-nd team, ... , the 1-st player of the n-th team, the 2-nd player of the 1-st team, ... , the 2-nd player of the n-th team, the 1-st player of the 1-st team and so on.Each turn continues for t seconds. It goes like that: Initially the time for each turn is t. While the time left to a player is more than 0, a player takes a card from the top of the deck and starts explaining the word it has to his teammate. The time needed for the j-th player of the i-th team to explain the word from the card k to his teammate (the q-th player of the i-th team) equals max(1, ck - (aij + biq) - dik) (if j = 1,  then q = 2,  else q = 1). The value dik is the number of seconds the i-th team has already spent explaining the word k during the previous turns. Initially, all dik equal 0. If a team manages to guess the word before the end of the turn, then the time given above is substracted from the duration of the turn, the card containing the guessed word leaves the game, the team wins one point and the game continues. If the team doesn't manage to guess the word, then the card is put at the bottom of the deck, dik increases on the amount of time of the turn, spent on explaining the word. Thus, when this team gets the very same word, they start explaining it not from the beginning, but from the point where they stopped. The game ends when words from all m cards are guessed correctly.You are given n teams and a deck of m cards. You should determine for each team, how many points it will have by the end of the game and which words the team will have guessed.InputThe first line contains two integers n, t (1 ≀ n, t ≀ 100), which correspondingly denote the number of teams and a turn's duration.Next n lines of the input file contain four integers each: ai1, bi1, ai2, bi2 (1 ≀ aij, bij ≀ 100) β€” the skills of the first and the second player of the i-th team. The teams are given in the order in which they play.The next line of the input file contains integer m (1 ≀ m ≀ 100) the number of cards.Next 2m lines contain the cards' descriptions. Two lines describe each card. The first line of the description contains the word that consists of no more than 20 characters. The words only contain small Latin letters. The second line of the description contains an integer ck (1 ≀ ck ≀ 100) β€” the complexity of the word written on the k-th card. The cards are listed in the order in which the lie in the deck from top to bottom. The words on all cards are different.OutputPrint n lines. On the i-th line first print number si the number of points the i-th team wins. Then print si space-separated words β€” the words from the cards guessed by team i in the order in which they were guessed.ExamplesInput2 21 1 1 11 1 1 13home1car1brother1Output2 home car 1 brother Input2 41 2 2 12 3 2 24armchair3quetzalcoatl10pilotage5defibrillator7Output2 armchair quetzalcoatl 2 pilotage defibrillator
Input2 21 1 1 11 1 1 13home1car1brother1
Output2 home car 1 brother
1 second
256 megabytes
['implementation', '*1800']
F. Spiderstime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtOne day mum asked Petya to sort his toys and get rid of some of them. Petya found a whole box of toy spiders. They were quite dear to him and the boy didn't want to throw them away. Petya conjured a cunning plan: he will glue all the spiders together and attach them to the ceiling. Besides, Petya knows that the lower the spiders will hang, the more mum is going to like it and then she won't throw his favourite toys away. Help Petya carry out the plan.A spider consists of k beads tied together by k - 1 threads. Each thread connects two different beads, at that any pair of beads that make up a spider is either directly connected by a thread, or is connected via some chain of threads and beads.Petya may glue spiders together directly gluing their beads. The length of each thread equals 1. The sizes of the beads can be neglected. That's why we can consider that gluing spiders happens by identifying some of the beads (see the picture). Besides, the construction resulting from the gluing process should also represent a spider, that is, it should have the given features. After Petya glues all spiders together, he measures the length of the resulting toy. The distance between a pair of beads is identified as the total length of the threads that connect these two beads. The length of the resulting construction is the largest distance between all pairs of beads. Petya wants to make the spider whose length is as much as possible. The picture two shows two spiders from the second sample. We can glue to the bead number 2 of the first spider the bead number 1 of the second spider. The threads in the spiders that form the sequence of threads of maximum lengths are highlighted on the picture.InputThe first input file line contains one integer n (1 ≀ n ≀ 100) β€” the number of spiders. Next n lines contain the descriptions of each spider: integer ni (2 ≀ ni ≀ 100) β€” the number of beads, then ni - 1 pairs of numbers denoting the numbers of the beads connected by threads. The beads that make up each spider are numbered from 1 to ni.OutputPrint a single number β€” the length of the required construction.ExamplesInput13 1 2 2 3Output2Input23 1 2 1 34 1 2 2 3 2 4Output4Input25 1 2 2 3 3 4 3 57 3 4 1 2 2 4 4 6 2 7 6 5Output7
Input13 1 2 2 3
Output2
1 second
256 megabytes
['dp', 'greedy', 'trees', '*1400']
E. Put Knight!time limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtPetya and Gena play a very interesting game "Put a Knight!" on a chessboard n × n in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (r, c) can threat squares (r - 1, c + 2), (r - 1, c - 2), (r + 1, c + 2), (r + 1, c - 2), (r - 2, c + 1), (r - 2, c - 1), (r + 2, c + 1) and (r + 2, c - 1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.InputThe first line contains integer T (1 ≀ T ≀ 100) β€” the number of boards, for which you should determine the winning player. Next T lines contain T integers ni (1 ≀ ni ≀ 10000) β€” the sizes of the chessboards.OutputFor each ni × ni board print on a single line "0" if Petya wins considering both players play optimally well. Otherwise, print "1".ExamplesInput221Output10
Input221
Output10
1 second
256 megabytes
['games', 'math', '*1400']
D. Three Sonstime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtThree sons inherited from their father a rectangular corn fiend divided into n × m squares. For each square we know how many tons of corn grows on it. The father, an old farmer did not love all three sons equally, which is why he bequeathed to divide his field into three parts containing A, B and C tons of corn.The field should be divided by two parallel lines. The lines should be parallel to one side of the field and to each other. The lines should go strictly between the squares of the field. Each resulting part of the field should consist of at least one square. Your task is to find the number of ways to divide the field as is described above, that is, to mark two lines, dividing the field in three parts so that on one of the resulting parts grew A tons of corn, B on another one and C on the remaining one.InputThe first line contains space-separated integers n and m β€” the sizes of the original (1 ≀ n, m ≀ 50, max(n, m) β‰₯ 3). Then the field's description follows: n lines, each containing m space-separated integers cij, (0 ≀ cij ≀ 100) β€” the number of tons of corn each square contains. The last line contains space-separated integers A, B, C (0 ≀ A, B, C ≀ 106).OutputPrint the answer to the problem: the number of ways to divide the father's field so that one of the resulting parts contained A tons of corn, another one contained B tons, and the remaining one contained C tons. If no such way exists, print 0.ExamplesInput3 31 1 11 1 11 1 13 3 3Output2Input2 51 1 1 1 12 2 2 2 23 6 6Output3Input3 31 2 33 1 22 3 15 6 7Output0NoteThe lines dividing the field can be horizontal or vertical, but they should be parallel to each other.
Input3 31 1 11 1 11 1 13 3 3
Output2
1 second
256 megabytes
['brute force', '*1400']
C. Winnie-the-Pooh and honeytime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtAs we all know, Winnie-the-Pooh just adores honey. Ones he and the Piglet found out that the Rabbit has recently gotten hold of an impressive amount of this sweet and healthy snack. As you may guess, Winnie and the Piglet asked to come at the Rabbit's place. Thus, there are n jars of honey lined up in front of Winnie-the-Pooh, jar number i contains ai kilos of honey. Winnie-the-Pooh eats the honey like that: each time he chooses a jar containing most honey. If the jar has less that k kilos of honey or if Winnie-the-Pooh has already eaten from it three times, he gives the jar to Piglet. Otherwise he eats exactly k kilos of honey from the jar and puts it back. Winnie does so until he gives all jars to the Piglet. Count how much honey Piglet will overall get after Winnie satisfies his hunger.InputThe first line contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 100). The second line contains n integers a1, a2, ..., an, separated by spaces (1 ≀ ai ≀ 100).OutputPrint a single number β€” how many kilos of honey gets Piglet.ExamplesInput3 315 8 10Output9
Input3 315 8 10
Output9
1 second
256 megabytes
['implementation', 'math', '*1100']
B. Quiz Leaguetime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtA team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.InputThe first line contains two positive integers n and k (1 ≀ n ≀ 1000 and 1 ≀ k ≀ n) β€” the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 ≀ i ≀ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.OutputPrint the single number β€” the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.ExamplesInput5 50 1 0 1 0Output2Input2 11 1Output1
Input5 50 1 0 1 0
Output2
1 second
256 megabytes
['implementation', '*1100']
A. Elevatortime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtA sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand. One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.InputThe first line indicates the door through which the very important person entered the elevator. It contains "front" if the person enters the elevator through the front door and "back" if he entered the elevator through the back door. The second line contains integer a (1 ≀ a ≀ 2) which denotes the number of the rail at which the person was holding.OutputPrint character "R" if the VIP is right-handed or "L" if he is left-handed.ExamplesInputfront1OutputL
Inputfront1
OutputL
1 second
256 megabytes
['brute force', 'implementation', 'math', '*1000']
E. Alternative Realitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the year of 3000 travelling around parallel realities became a routine thing. However one has to take into consideration that travelling like that is highly dangerous as you never know beforehand where you're gonna get...Little Vasya, for instance, found himself in a gaming reality and now he has to successfully complete all levels of a very weird game to get back. The gaming reality is a three-dimensional space where n points are given. The game has m levels and at the beginning of the i-th level the player is positioned at some plane Qi that passes through the origin. On each level Vasya has to use special robots to construct and activate n powerful energy spheres of the equal radius with centers at the given points. The player chooses the radius of the spheres himself. The player has to spend R units of money to construct spheres whose radius equals R (consequently, one can construct spheres whose radius equals zero for free). Besides, once for each level a player can choose any point in space and release a laser ray from there, perpendicular to plane Qi (this action costs nothing). The ray can either be directed towards the plane or from the plane. The spheres that share at least one point with the ray will be immediately activated. The level is considered completed if the player has managed to activate all spheres. Note that the centers of the spheres are the same for all m levels but the spheres do not remain: the player should construct them anew on each new level.Help Vasya find out what minimum sum of money will be enough to complete each level.InputThe first line contains two integers n and m (1 ≀ n ≀ 900, 1 ≀ m ≀ 100) β€” the number of energetic spheres and the number of levels in the game correspondingly. Each of the following n lines contains three integers xi, yi, zi (0 ≀ xi, yi, zi ≀ 104) β€” the coordinates of the center of the i-th sphere. Assume that these points do not change their positions throughout the game.Then follow m lines, each containing three integers ai, bi, ci (0 ≀ ai, bi, ci ≀ 100, ai2 + bi2 + ci2 > 0). These numbers are the coefficients in the equation of plane Qi (aix + biy + ciz = 0), where the player is positioned at the beginning of the i-th level.OutputPrint m numbers, one per line: the i-th line should contain the minimum sum of money needed to complete the i-th level. The absolute or relative error should not exceed 10 - 6.ExamplesInput4 10 0 00 1 01 0 01 1 00 0 1Output0.7071067812Input5 30 1 01 0 11 2 12 0 11 3 01 1 11 2 33 0 3Output1.63299316191.63663417681.5411035007Input2 10 20 00 0 00 10 0Output0.0000000000
Input4 10 0 00 1 01 0 01 1 00 0 1
Output0.7071067812
2 seconds
256 megabytes
['geometry', '*2400']
D. String Transformationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet s be a string whose length equals n. Its characters are numbered from 0 to n - 1, i and j are integers, 0 ≀ i < j < n. Let's define function f as follows:f(s, i, j) = s[i + 1... j - 1] + r(s[j... n - 1]) + r(s[0... i]).Here s[p... q] is a substring of string s, that starts in position p and ends in position q (inclusive); "+" is the string concatenation operator; r(x) is a string resulting from writing the characters of the x string in the reverse order. If j = i + 1, then the substring s[i + 1... j - 1] is considered empty.You are given two strings a and b. Find such values of i and j, that f(a, i, j) = b. Number i should be maximally possible. If for this i there exists several valid values of j, choose the minimal j.InputThe first two input lines are non-empty strings a and b correspondingly. Each string's length does not exceed 106 characters. The strings can contain any characters with ASCII codes from 32 to 126 inclusive.OutputPrint two integers i, j β€” the answer to the problem. If no solution exists, print "-1 -1" (without the quotes).ExamplesInputDie Polizei untersucht eine Straftat im IT-Bereich.untersucht eine Straftat.hciereB-TI mi ieziloP eiDOutput11 36InputcbaaaaaaaabcOutput4 5Input1233423324212Output-1 -1
InputDie Polizei untersucht eine Straftat im IT-Bereich.untersucht eine Straftat.hciereB-TI mi ieziloP eiD
Output11 36
2 seconds
256 megabytes
['hashing', 'strings', '*2500']
C. Education Reformtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYet another education system reform has been carried out in Berland recently. The innovations are as follows:An academic year now consists of n days. Each day pupils study exactly one of m subjects, besides, each subject is studied for no more than one day. After the lessons of the i-th subject pupils get the home task that contains no less than ai and no more than bi exercises. Besides, each subject has a special attribute, the complexity (ci). A school can make its own timetable, considering the following conditions are satisfied: the timetable should contain the subjects in the order of the complexity's strict increasing; each day, except for the first one, the task should contain either k times more exercises, or more by k compared to the previous day (more formally: let's call the number of home task exercises in the i-th day as xi, then for each i (1 < i ≀ n): either xi = k + xi - 1 or xi = kΒ·xi - 1 must be true); the total number of exercises in all home tasks should be maximal possible. All limitations are separately set for each school.It turned out that in many cases ai and bi reach 1016 (however, as the Berland Minister of Education is famous for his love to half-measures, the value of bi - ai doesn't exceed 100). That also happened in the Berland School β„–256. Nevertheless, you as the school's principal still have to work out the timetable for the next academic year...InputThe first line contains three integers n, m, k (1 ≀ n ≀ m ≀ 50, 1 ≀ k ≀ 100) which represent the number of days in an academic year, the number of subjects and the k parameter correspondingly. Each of the following m lines contains the description of a subject as three integers ai, bi, ci (1 ≀ ai ≀ bi ≀ 1016, bi - ai ≀ 100, 1 ≀ ci ≀ 100) β€” two limitations to the number of exercises on the i-th subject and the complexity of the i-th subject, correspondingly. Distinct subjects can have the same complexity. The subjects are numbered with integers from 1 to m. Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use the cin stream or the %I64d specificator.OutputIf no valid solution exists, print the single word "NO" (without the quotes). Otherwise, the first line should contain the word "YES" (without the quotes) and the next n lines should contain any timetable that satisfies all the conditions. The i + 1-th line should contain two positive integers: the number of the subject to study on the i-th day and the number of home task exercises given for this subject. The timetable should contain exactly n subjects.ExamplesInput4 5 21 10 11 10 21 10 31 20 41 100 5OutputYES2 83 104 205 40Input3 4 31 3 12 4 42 3 32 2 2OutputNO
Input4 5 21 10 11 10 21 10 31 20 41 100 5
OutputYES2 83 104 205 40
1 second
256 megabytes
['dp', '*2000']
B. Before Examtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is about to take his first university exam in about several minutes. And it's not just some ordinary exam, it's on mathematical analysis. Of course, right now Vasya can only think of one thing: what the result of his talk with the examiner will be...To prepare for the exam, one has to study proofs of n theorems. It is known that there will be k examination cards on the exam and each card contains distinct theorems. Besides, no theorem is mentioned in more than one card (that is, theorems won't be mentioned in any card). During the exam several students may get the same card.We do not know the exact way theorems are distributed by cards, however the students that took the exam before Vasya told him what theorems their cards contained. Vasya evaluates his level of proficiency in the i-th theorem by some number ai. The level of proficiency in some card is the average of the levels of proficiency in the theorems that are included in the card. Now Vasya wants to know the minimally and maximally possible levels of his proficiency in the card he gets on the exam. Vasya wants to determine it by the data he has collected from other students. Unfortunately, Vasya has no time left to do the math and he asked you to help him.InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 100) β€” the number of theorems and the number of cards correspondingly. The second line contains n integers ai (0 ≀ ai ≀ 100), the i-th number (1 ≀ i ≀ n) corresponds to Vasya's proficiency in the i-th theorem.The third line contains number q (0 ≀ q ≀ 100) β€” the number of people that have taken the exam before Vasya. Each of the following q lines contains the description of a student's card: integers from 1 to n inclusive. They are the numbers of theorems included in the card in the order in which they are enumerated in the input data. The numbers are given in an arbitrary order. It is guaranteed that the given cards are valid (that is, that all theorems in one card are different and that different people get cards that either don't contain the same theorems or coincide up to the theorems' permutation).OutputPrint two real numbers, representing Vasya's minimum and maximum proficiency in the card he will get on the exam. The absolute or relative error should not exceed 10 - 6.ExamplesInput7 37 15 0 19 10 5 1221 67 4Output5.0000000000 15.5000000000Input4 210 8 1 1722 33 2Output4.5000000000 13.5000000000NoteLet's analyze the first sample. Vasya's proficiency in the cards whose content he already knows equals 6 and 15.5 correspondingly. The three theorems that are left are only enough to make one exam card. If we consider all possible variants of theorems included in the card we can see that in the best case scenario Vasya gets the card that contains theorems 4 and 7 (his proficiency would equal 15.5) and in the worst case scenario he gets theorems 3 and 5 (his proficiency would equal 5).The ⌊ xβŒ‹ operation denotes taking integer part of real number x (rounding down).
Input7 37 15 0 19 10 5 1221 67 4
Output5.0000000000 15.5000000000
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'sortings', '*1900']
A. Epic Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSimon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take). Your task is to determine by the given a, b and n who wins the game.InputThe only string contains space-separated integers a, b and n (1 ≀ a, b, n ≀ 100) β€” the fixed numbers Simon and Antisimon have received correspondingly and the initial number of stones in the pile.OutputIf Simon wins, print "0" (without the quotes), otherwise print "1" (without the quotes).ExamplesInput3 5 9Output0Input1 1 100Output1NoteThe greatest common divisor of two non-negative integers a and b is such maximum positive integer k, that a is divisible by k without remainder and similarly, b is divisible by k without remainder. Let gcd(a, b) represent the operation of calculating the greatest common divisor of numbers a and b. Specifically, gcd(x, 0) = gcd(0, x) = x.In the first sample the game will go like that: Simon should take gcd(3, 9) = 3 stones from the heap. After his move the heap has 6 stones left. Antisimon should take gcd(5, 6) = 1 stone from the heap. After his move the heap has 5 stones left. Simon should take gcd(3, 5) = 1 stone from the heap. After his move the heap has 4 stones left. Antisimon should take gcd(5, 4) = 1 stone from the heap. After his move the heap has 3 stones left. Simon should take gcd(3, 3) = 3 stones from the heap. After his move the heap has 0 stones left. Antisimon should take gcd(5, 0) = 5 stones from the heap. As 0 < 5, it is impossible and Antisimon loses.In the second sample each player during each move takes one stone from the heap. As n is even, Antisimon takes the last stone and Simon can't make a move after that.
Input3 5 9
Output0
2 seconds
256 megabytes
['implementation', '*800']
E. Bertown roadstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads. As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads, thus easing down the traffic. Your task is to determine whether there is a way to make the traffic one-directional so that there still is the possibility to get from any junction to any other one. If the answer is positive, you should also find one of the possible ways to orient the roads.InputThe first line contains two space-separated integers n and m (2 ≀ n ≀ 105, n - 1 ≀ m ≀ 3Β·105) which represent the number of junctions and the roads in the town correspondingly. Then follow m lines, each containing two numbers which describe the roads in the city. Each road is determined by two integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi) β€” the numbers of junctions it connects.It is guaranteed that one can get from any junction to any other one along the existing bidirectional roads. Each road connects different junctions, there is no more than one road between each pair of junctions.OutputIf there's no solution, print the single number 0. Otherwise, print m lines each containing two integers pi and qi β€” each road's orientation. That is the traffic flow will move along a one-directional road from junction pi to junction qi. You can print the roads in any order. If there are several solutions to that problem, print any of them.ExamplesInput6 81 22 31 34 54 65 62 43 5Output1 22 33 14 55 66 44 23 5Input6 71 22 31 34 54 65 62 4Output0
Input6 81 22 31 34 54 65 62 43 5
Output1 22 33 14 55 66 44 23 5
5 seconds
256 megabytes
['dfs and similar', 'graphs', '*2000']
D. Caesar's Legionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen standing successively one after another. Find the number of beautiful arrangements of the soldiers. Note that all n1 + n2 warriors should be present at each arrangement. All footmen are considered indistinguishable among themselves. Similarly, all horsemen are considered indistinguishable among themselves.InputThe only line contains four space-separated integers n1, n2, k1, k2 (1 ≀ n1, n2 ≀ 100, 1 ≀ k1, k2 ≀ 10) which represent how many footmen and horsemen there are and the largest acceptable number of footmen and horsemen standing in succession, correspondingly.OutputPrint the number of beautiful arrangements of the army modulo 100000000 (108). That is, print the number of such ways to line up the soldiers, that no more than k1 footmen stand successively, and no more than k2 horsemen stand successively.ExamplesInput2 1 1 10Output1Input2 3 1 2Output5Input2 4 1 1Output0NoteLet's mark a footman as 1, and a horseman as 2.In the first sample the only beautiful line-up is: 121In the second sample 5 beautiful line-ups exist: 12122, 12212, 21212, 21221, 22121
Input2 1 1 10
Output1
2 seconds
256 megabytes
['dp', '*1700']
C. Fancy Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA car number in Berland consists of exactly n digits. A number is called beautiful if it has at least k equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of n digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one.Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.InputThe first line contains two space-separated integers n and k (2 ≀ n ≀ 104, 2 ≀ k ≀ n) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of n digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits.OutputOn the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one.ExamplesInput6 5898196Output4888188Input3 2533Output0533Input10 60001112223Output30000002223NoteIn the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188".The lexicographical comparison of strings is performed by the < operator in modern programming languages. The string x is lexicographically smaller than the string y, if there exists such i (1 ≀ i ≀ n), that xi < yi, and for any j (1 ≀ j < i) xj = yj. The strings compared in this problem will always have the length n.
Input6 5898196
Output4888188
2 seconds
256 megabytes
['brute force', 'greedy', 'sortings', 'strings', '*1900']
B. Present from Lenatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handkerchief pattern should look like that: Β Β Β Β Β Β Β Β Β Β 0Β Β Β Β Β Β Β Β 0Β 1Β 0Β Β Β Β Β Β 0Β 1Β 2Β 1Β 0Β Β Β Β 0Β 1Β 2Β 3Β 2Β 1Β 0Β Β 0Β 1Β 2Β 3Β 4Β 3Β 2Β 1Β 00Β 1Β 2Β 3Β 4Β 5Β 4Β 3Β 2Β 1Β 0Β Β 0Β 1Β 2Β 3Β 4Β 3Β 2Β 1Β 0Β Β Β Β 0Β 1Β 2Β 3Β 2Β 1Β 0Β Β Β Β Β Β 0Β 1Β 2Β 1Β 0Β Β Β Β Β Β Β Β 0Β 1Β 0Β Β Β Β Β Β Β Β Β Β 0Your task is to determine the way the handkerchief will look like by the given n.InputThe first line contains the single integer n (2 ≀ n ≀ 9).OutputPrint a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.ExamplesInput2Output 0 0 1 00 1 2 1 0 0 1 0 0Input3Output 0 0 1 0 0 1 2 1 00 1 2 3 2 1 0 0 1 2 1 0 0 1 0 0
Input2
Output 0 0 1 00 1 2 1 0 0 1 0 0
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1000']
A. String Tasktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: deletes all the vowels, inserts a character "." before each consonant, replaces all uppercase consonants with corresponding lowercase ones. Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.Help Petya cope with this easy task.InputThe first line represents input string of Petya's program. This string only consists of uppercase and lowercase Latin letters and its length is from 1 to 100, inclusive.OutputPrint the resulting string. It is guaranteed that this string is not empty.ExamplesInputtourOutput.t.rInputCodeforcesOutput.c.d.f.r.c.sInputaBAcAbaOutput.b.c.b
Inputtour
Output.t.r
2 seconds
256 megabytes
['implementation', 'strings', '*1000']
E. Tree or not Treetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected connected graph G consisting of n vertexes and n edges. G contains no self-loops or multiple edges. Let each edge has two states: on and off. Initially all edges are switched off.You are also given m queries represented as (v, u) β€” change the state of all edges on the shortest path from vertex v to vertex u in graph G. If there are several such paths, the lexicographically minimal one is chosen. More formally, let us consider all shortest paths from vertex v to vertex u as the sequences of vertexes v, v1, v2, ..., u. Among such sequences we choose the lexicographically minimal one.After each query you should tell how many connected components has the graph whose vertexes coincide with the vertexes of graph G and edges coincide with the switched on edges of graph G.InputThe first line contains two integers n and m (3 ≀ n ≀ 105, 1 ≀ m ≀ 105). Then n lines describe the graph edges as a b (1 ≀ a, b ≀ n). Next m lines contain the queries as v u (1 ≀ v, u ≀ n). It is guaranteed that the graph is connected, does not have any self-loops or multiple edges.OutputPrint m lines, each containing one integer β€” the query results.ExamplesInput5 22 14 32 42 54 15 41 5Output33Input6 24 64 31 26 51 51 42 52 6Output43NoteLet's consider the first sample. We'll highlight the switched on edges blue on the image. The graph before applying any operations. No graph edges are switched on, that's why there initially are 5 connected components. The graph after query v = 5, u = 4. We can see that the graph has three components if we only consider the switched on edges. The graph after query v = 1, u = 5. We can see that the graph has three components if we only consider the switched on edges. Lexicographical comparison of two sequences of equal length of k numbers should be done as follows. Sequence x is lexicographically less than sequence y if exists such i (1 ≀ i ≀ k), so that xi < yi, and for any j (1 ≀ j < i) xj = yj.
Input5 22 14 32 42 54 15 41 5
Output33
5 seconds
256 megabytes
['data structures', 'divide and conquer', 'implementation', 'trees', '*2900']
D. Not Quick Transformationtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet a be an array consisting of n numbers. The array's elements are numbered from 1 to n, even is an array consisting of the numerals whose numbers are even in a (eveni = a2i, 1 ≀ 2i ≀ n), odd is an array consisting of the numberals whose numbers are odd in Π° (oddi = a2i - 1, 1 ≀ 2i - 1 ≀ n). Then let's define the transformation of array F(a) in the following manner: if n > 1, F(a) = F(odd) + F(even), where operation " + " stands for the arrays' concatenation (joining together) if n = 1, F(a) = a Let a be an array consisting of n numbers 1, 2, 3, ..., n. Then b is the result of applying the transformation to the array a (so b = F(a)). You are given m queries (l, r, u, v). Your task is to find for each query the sum of numbers bi, such that l ≀ i ≀ r and u ≀ bi ≀ v. You should print the query results modulo mod.InputThe first line contains three integers n, m, mod (1 ≀ n ≀ 1018, 1 ≀ m ≀ 105, 1 ≀ mod ≀ 109). Next m lines describe the queries. Each query is defined by four integers l, r, u, v (1 ≀ l ≀ r ≀ n, 1 ≀ u ≀ v ≀ 1018).Please do not use the %lld specificator to read or write 64-bit integers in C++. Use %I64d specificator.OutputPrint m lines each containing an integer β€” remainder modulo mod of the query result.ExamplesInput4 5 100002 3 4 52 4 1 31 2 2 42 3 3 51 3 3 4Output05333Input2 5 100001 2 2 21 1 4 51 1 2 51 1 1 31 2 5 5Output20010NoteLet's consider the first example. First let's construct an array b = F(a) = F([1, 2, 3, 4]). Step 1. F([1, 2, 3, 4]) = F([1, 3]) + F([2, 4]) Step 2. F([1, 3]) = F([1]) + F([3]) = [1] + [3] = [1, 3] Step 3. F([2, 4]) = F([2]) + F([4]) = [2] + [4] = [2, 4] Step 4. b = F([1, 2, 3, 4]) = F([1, 3]) + F([2, 4]) = [1, 3] + [2, 4] = [1, 3, 2, 4] Thus b = [1, 3, 2, 4]. Let's consider the first query l = 2, r = 3, u = 4, v = 5. The second and third positions in the array b do not have numbers in the range [4, 5], so the sum obviously equals zero. Let's consider the second query l = 2, r = 4, u = 1, v = 3. The second and third positions have two numbers that belong to the range [1, 3], their sum equals 5.
Input4 5 100002 3 4 52 4 1 31 2 2 42 3 3 51 3 3 4
Output05333
6 seconds
256 megabytes
['divide and conquer', 'math', '*2500']
C. Cycletime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tournament is a directed graph without self-loops in which every pair of vertexes is connected by exactly one directed edge. That is, for any two vertexes u and v (u ≠ v) exists either an edge going from u to v, or an edge from v to u.You are given a tournament consisting of n vertexes. Your task is to find there a cycle of length three.InputThe first line contains an integer n (1 ≀ n ≀ 5000). Next n lines contain the adjacency matrix A of the graph (without spaces). Ai, j = 1 if the graph has an edge going from vertex i to vertex j, otherwise Ai, j = 0. Ai, j stands for the j-th character in the i-th line.It is guaranteed that the given graph is a tournament, that is, Ai, i = 0, Ai, j ≠ Aj, i (1 ≀ i, j ≀ n, i ≠ j).OutputPrint three distinct vertexes of the graph a1, a2, a3 (1 ≀ ai ≀ n), such that Aa1, a2 = Aa2, a3 = Aa3, a1 = 1, or "-1", if a cycle whose length equals three does not exist. If there are several solutions, print any of them.ExamplesInput50010010000010011110111000Output1 3 2 Input50111100000010000110001110Output-1
Input50010010000010011110111000
Output1 3 2
2.5 seconds
256 megabytes
['dfs and similar', 'graphs', '*2000']
B. Very Interesting Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a very ancient country the following game was popular. Two people play the game. Initially first player writes a string s1, consisting of exactly nine digits and representing a number that does not exceed a. After that second player looks at s1 and writes a string s2, consisting of exactly nine digits and representing a number that does not exceed b. Here a and b are some given constants, s1 and s2 are chosen by the players. The strings are allowed to contain leading zeroes.If a number obtained by the concatenation (joining together) of strings s1 and s2 is divisible by mod, then the second player wins. Otherwise the first player wins. You are given numbers a, b, mod. Your task is to determine who wins if both players play in the optimal manner. If the first player wins, you are also required to find the lexicographically minimum winning move.InputThe first line contains three integers a, b, mod (0 ≀ a, b ≀ 109, 1 ≀ mod ≀ 107).OutputIf the first player wins, print "1" and the lexicographically minimum string s1 he has to write to win. If the second player wins, print the single number "2".ExamplesInput1 10 7Output2Input4 0 9Output1 000000001NoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String x is lexicographically less than string y if exists such i (1 ≀ i ≀ 9), that xi < yi, and for any j (1 ≀ j < i) xj = yj. These strings always have length 9.
Input1 10 7
Output2
2 seconds
256 megabytes
['brute force', 'number theory', '*1800']
A. Elevatortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnd now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All n participants who have made it to the finals found themselves in a huge m-floored 108-star hotel. Of course the first thought to come in a place like this is "How about checking out the elevator?".The hotel's elevator moves between floors according to one never changing scheme. Initially (at the moment of time 0) the elevator is located on the 1-st floor, then it moves to the 2-nd floor, then β€” to the 3-rd floor and so on until it reaches the m-th floor. After that the elevator moves to floor m - 1, then to floor m - 2, and so on until it reaches the first floor. This process is repeated infinitely. We know that the elevator has infinite capacity; we also know that on every floor people get on the elevator immediately. Moving between the floors takes a unit of time.For each of the n participant you are given si, which represents the floor where the i-th participant starts, fi, which represents the floor the i-th participant wants to reach, and ti, which represents the time when the i-th participant starts on the floor si.For each participant print the minimum time of his/her arrival to the floor fi. If the elevator stops on the floor si at the time ti, then the i-th participant can enter the elevator immediately. If the participant starts on the floor si and that's the floor he wanted to reach initially (si = fi), then the time of arrival to the floor fi for this participant is considered equal to ti.InputThe first line contains two space-separated integers n and m (1 ≀ n ≀ 105, 2 ≀ m ≀ 108). Next n lines contain information about the participants in the form of three space-separated integers si fi ti (1 ≀ si, fi ≀ m, 0 ≀ ti ≀ 108), described in the problem statement.OutputPrint n lines each containing one integer β€” the time of the arrival for each participant to the required floor.ExamplesInput7 42 4 31 2 02 2 01 2 14 3 51 2 24 2 0Output91071075Input5 51 5 41 3 11 3 43 1 54 2 5Output12101087NoteLet's consider the first sample. The first participant starts at floor s = 2 by the time equal to t = 3. To get to the floor f = 4, he has to wait until the time equals 7, that's the time when the elevator will go upwards for the second time. Then the first participant should get on the elevator and go two floors up. In this case the first participant gets to the floor f at time equal to 9. The second participant starts at the time t = 0 on the floor s = 1, enters the elevator immediately, and arrives to the floor f = 2. The third participant doesn't wait for the elevator, because he needs to arrive to the same floor where he starts.
Input7 42 4 31 2 02 2 01 2 14 3 51 2 24 2 0
Output91071075
1 second
256 megabytes
['implementation', 'math', '*1300']
B. Little Pigs and Wolvestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time there were several little pigs and several wolves on a two-dimensional grid of size n × m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of wolves, so there will be at most one wolf adjacent to each little pig. But each wolf may be adjacent to any number of little pigs.They have been living peacefully for several years. But today the wolves got hungry. One by one, each wolf will choose one of the little pigs adjacent to it (if any), and eats the poor little pig. This process is not repeated. That is, each wolf will get to eat at most one little pig. Once a little pig gets eaten, it disappears and cannot be eaten by any other wolf.What is the maximum number of little pigs that may be eaten by the wolves?InputThe first line contains integers n and m (1 ≀ n, m ≀ 10) which denotes the number of rows and columns in our two-dimensional grid, respectively. Then follow n lines containing m characters each β€” that is the grid description. "." means that this cell is empty. "P" means that this cell contains a little pig. "W" means that this cell contains a wolf. It is guaranteed that there will be at most one wolf adjacent to any little pig.OutputPrint a single number β€” the maximal number of little pigs that may be eaten by the wolves.ExamplesInput2 3PPWW.POutput2Input3 3P.W.P.W.POutput0NoteIn the first example, one possible scenario in which two little pigs get eaten by the wolves is as follows.
Input2 3PPWW.P
Output2
2 seconds
256 megabytes
['greedy', 'implementation', '*1100']
A. Tramtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLinear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.InputThe first line contains a single number n (2 ≀ n ≀ 1000) β€” the number of the tram's stops. Then n lines follow, each contains two integers ai and bi (0 ≀ ai, bi ≀ 1000) β€” the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement. The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that a1 = 0. At the last stop, all the passengers exit the tram and it becomes empty. More formally, . No passenger will enter the train at the last stop. That is, bn = 0. OutputPrint a single integer denoting the minimum possible capacity of the tram (0 is allowed).ExamplesInput40 32 54 24 0Output6NoteFor the first example, a capacity of 6 is sufficient: At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3. At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now. At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now. Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints. Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.
Input40 32 54 24 0
Output6
2 seconds
256 megabytes
['implementation', '*800']
E. Linear Kingdom Racestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a car race organizer and would like to arrange some races in Linear Kingdom.Linear Kingdom has n consecutive roads spanning from left to right. The roads are numbered from 1 to n from left to right, thus the roads follow in the order of their numbers' increasing. There will be several races that may be held on these roads. Each race will use a consecutive subset of these roads. Also, each race will pay some amount of money to you if this race is held. No races overlap in time, so some roads can be used in several races.Unfortunately, some of the roads are in a bad condition and they need repair. Each road has repair costs associated with it, you are required to pay this cost to repair the road. A race can only take place if all the roads used in the race are renovated. Your task is to repair such roads (possibly all or none) that will maximize your profit. Your profit is defined as the total money you get from the races that are held minus the total money you spent to repair the roads. Note that you may decide not to repair any road and gain zero profit.Print the maximum profit you can gain.InputThe first line contains two single-space separated integers, n and m (1 ≀ n, m ≀ 2Β·105), denoting the number of roads and the number of races, respectively.Then n lines follow, each line will contain a single non-negative integer not exceeding 109 denoting the cost to repair a road. The costs are given in order from road 1 to road n.Finally, m lines follow. Each line is single-space-separated triplets of integers. Each triplet will be given as lb, ub, and p (1 ≀ lb ≀ ub ≀ n, 1 ≀ p ≀ 109), which means that the race these three integers describe will use all the roads from lb to ub, inclusive, and if it's held you get p.OutputPrint a single integer denoting the maximum possible profit you can gain.Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is recommended to use cin, cout stream (also you may use %I64d specificator).ExamplesInput7 432321231 2 52 3 53 5 37 7 5Output4Input2 1031 2 5Output2Input3 11010101 3 10Output0NoteIn the first sample the optimal solution is to repair roads 1, 2, 3, and 7. Three races will take place which nets you 15. The road repair costs 11, hence your profit is 4.
Input7 432321231 2 52 3 53 5 37 7 5
Output4
3 seconds
256 megabytes
['data structures', 'dp', '*2400']
D. Unambiguous Arithmetic Expressiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define an unambiguous arithmetic expression (UAE) as follows. All non-negative integers are UAE's. Integers may have leading zeroes (for example, 0000 and 0010 are considered valid integers). If X and Y are two UAE's, then "(X) + (Y)", "(X) - (Y)", "(X) * (Y)", and "(X) / (Y)" (all without the double quotes) are UAE's. If X is an UAE, then " - (X)" and " + (X)" (both without the double quotes) are UAE's.You are given a string consisting only of digits ("0" - "9") and characters "-", "+", "*", and "/". Your task is to compute the number of different possible unambiguous arithmetic expressions such that if all brackets (characters "(" and ")") of that unambiguous arithmetic expression are removed, it becomes the input string. Since the answer may be very large, print it modulo 1000003 (106 + 3).InputThe first line is a non-empty string consisting of digits ('0'-'9') and characters '-', '+', '*', and/or '/'. Its length will not exceed 2000. The line doesn't contain any spaces.OutputPrint a single integer representing the number of different unambiguous arithmetic expressions modulo 1000003 (106 + 3) such that if all its brackets are removed, it becomes equal to the input string (character-by-character).ExamplesInput1+2*3Output2Input03+-30+40Output3Input5//4Output0Input5/0Output1Input1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1Output100728NoteFor the first example, the two possible unambiguous arithmetic expressions are:((1) + (2)) * (3)(1) + ((2) * (3))For the second example, the three possible unambiguous arithmetic expressions are:(03) + (( - (30)) + (40))(03) + ( - ((30) + (40)))((03) + ( - (30))) + (40)
Input1+2*3
Output2
2 seconds
256 megabytes
['dp', 'expression parsing', '*2600']
C. Plumbertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n × m square cells.In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows: Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment 1 has ends at top and left side of it.Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size 1 × 2. Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling all of the empty cells with pipe segments. Print this number modulo 1000003 (106 + 3).Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.InputThe first line will contain two single-space separated integers n and m (1 ≀ n, m, nΒ·m ≀ 5Β·105) β€” the number of rows and columns respectively. Then n lines follow, each contains exactly m characters β€” the description of the grid. Each character describes a cell and is either one of these: "1" - "4" β€” a pipe segment of one of four types as described above "." β€” an empty cell OutputPrint a single integer denoting the number of possible final non-leaking pipe systems modulo 1000003 (106 + 3). If there are no such configurations, print 0.ExamplesInput2 213..Output2Input3 114.Output0Input2 23..1Output1NoteFor the first example, the initial configuration of the grid is as follows. The only two possible final non-leaking pipe configurations are as follows: For the second example, the initial grid is already leaking, so there will be no final grid that is non-leaking.For the final example, there's only one possible non-leaking final grid as follows.
Input2 213..
Output2
3 seconds
256 megabytes
['math', '*2200']
B. Lawnmowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a garden consisting entirely of grass and weeds. Your garden is described by an n × m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either grass or weeds. For example, a 4 × 5 garden may look as follows (empty cells denote grass): You have a land-mower with you to mow all the weeds. Initially, you are standing with your lawnmower at the top-left corner of the garden. That is, at cell (1, 1). At any moment of time you are facing a certain direction β€” either left or right. And initially, you face right.In one move you can do either one of these:1) Move one cell in the direction that you are facing. if you are facing right: move from cell (r, c) to cell (r, c + 1) if you are facing left: move from cell (r, c) to cell (r, c - 1) 2) Move one cell down (that is, from cell (r, c) to cell (r + 1, c)), and change your direction to the opposite one. if you were facing right previously, you will face left if you were facing left previously, you will face right You are not allowed to leave the garden. Weeds will be mowed if you and your lawnmower are standing at the cell containing the weeds (your direction doesn't matter). This action isn't counted as a move.What is the minimum number of moves required to mow all the weeds?InputThe first line contains two integers n and m (1 ≀ n, m ≀ 150) β€” the number of rows and columns respectively. Then follow n lines containing m characters each β€” the content of the grid. "G" means that this cell contains grass. "W" means that this cell contains weeds. It is guaranteed that the top-left corner of the grid will contain grass.OutputPrint a single number β€” the minimum number of moves required to mow all the weeds.ExamplesInput4 5GWGGWGGWGGGWGGGWGGGGOutput11Input3 3GWWWWWWWGOutput7Input1 1GOutput0NoteFor the first example, this is the picture of the initial state of the grid: A possible solution is by mowing the weeds as illustrated below:
Input4 5GWGGWGGWGGGWGGGWGGGG
Output11
2 seconds
256 megabytes
['greedy', 'sortings', '*1500']
A. Partytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?InputThe first line contains integer n (1 ≀ n ≀ 2000) β€” the number of employees.The next n lines contain the integers pi (1 ≀ pi ≀ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.OutputPrint a single integer denoting the minimum number of groups that will be formed in the party.ExamplesInput5-1121-1Output3NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Input5-1121-1
Output3
3 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*900']
B. PFAST Inc.time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen little Petya grew up and entered the university, he started to take part in АБМ contests. Later he realized that he doesn't like how the АБМ contests are organised: the team could only have three members (and he couldn't take all his friends to the competitions and distribute the tasks between the team members efficiently), so he decided to organize his own contests PFAST Inc. β€” Petr and Friends Are Solving Tasks Corporation. PFAST Inc. rules allow a team to have unlimited number of members.To make this format of contests popular he organised his own tournament. To create the team he will prepare for the contest organised by the PFAST Inc. rules, he chose several volunteers (up to 16 people) and decided to compile a team from them. Petya understands perfectly that if a team has two people that don't get on well, then the team will perform poorly. Put together a team with as many players as possible given that all players should get on well with each other.InputThe first line contains two integer numbers n (1 ≀ n ≀ 16) β€” the number of volunteers, and m () β€” the number of pairs that do not get on. Next n lines contain the volunteers' names (each name is a non-empty string consisting of no more than 10 uppercase and/or lowercase Latin letters). Next m lines contain two names β€” the names of the volunteers who do not get on. The names in pair are separated with a single space. Each pair of volunteers who do not get on occurs exactly once. The strings are case-sensitive. All n names are distinct.OutputThe first output line should contain the single number k β€” the number of people in the sought team. Next k lines should contain the names of the sought team's participants in the lexicographical order. If there are several variants to solve the problem, print any of them. Petya might not be a member of the sought team. ExamplesInput3 1PetyaVasyaMashaPetya VasyaOutput2MashaPetyaInput3 0PashaLeshaVanyaOutput3LeshaPashaVanya
Input3 1PetyaVasyaMashaPetya Vasya
Output2MashaPetya
2 seconds
256 megabytes
['bitmasks', 'brute force', 'graphs', '*1500']
A. Ciferatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million.Petya wanted to modernize the words we use for numbers and invented a word petricium that represents number k. Moreover, petricium la petricium stands for number k2, petricium la petricium la petricium stands for k3 and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.Petya's invention brought on a challenge that needed to be solved quickly: does some number l belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.InputThe first input line contains integer number k, the second line contains integer number l (2 ≀ k, l ≀ 231 - 1).OutputYou should print in the first line of the output "YES", if the number belongs to the set petriciumus cifera and otherwise print "NO". If the number belongs to the set, then print on the seconds line the only number β€” the importance of number l.ExamplesInput525OutputYES1Input38OutputNO
Input525
OutputYES1
2 seconds
256 megabytes
['math', '*1000']
E. Sleepingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya was lying in bed watching his electronic clock to fall asleep quicker.Vasya lives in a strange country, where days have h hours, and every hour has m minutes. Clock shows time in decimal number system, in format H:M, where the string H always has a fixed length equal to the number of digits in the decimal representation of number h - 1. To achieve this, leading zeros are added if necessary. The string M has a similar format, and its length is always equal to the number of digits in the decimal representation of number m - 1. For example, if h = 17, m = 1000, then time equal to 13 hours and 75 minutes will be displayed as "13:075".Vasya had been watching the clock from h1 hours m1 minutes to h2 hours m2 minutes inclusive, and then he fell asleep. Now he asks you to count how many times he saw the moment at which at least k digits changed on the clock simultaneously.For example, when switching 04:19  →  04:20 two digits change. When switching 23:59  →  00:00, four digits change.Consider that Vasya has been watching the clock for strictly less than one day. Note that the last time Vasya saw on the clock before falling asleep was "h2:m2". That is, Vasya didn't see the moment at which time "h2:m2" switched to the next value.InputThe first line of the input file contains three space-separated integers h, m and k (2 ≀ h, m ≀ 109, 1 ≀ k ≀ 20). The second line contains space-separated integers h1, m1 (0 ≀ h1 < h, 0 ≀ m1 < m). The third line contains space-separated integers h2, m2 (0 ≀ h2 < h, 0 ≀ m2 < m).OutputPrint a single number β€” the number of times Vasya saw the moment of changing at least k digits simultaneously.Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin stream (also you may use the %I64d specificator).ExamplesInput5 5 24 42 1Output3Input24 60 10 023 59Output1439Input24 60 323 5923 59Output0NoteIn the first example Vasya will see the following moments of time: 4:4 0:0  →  0:1  →  0:2  →  0:3  →  0:4 1:0  →  1:1  →  1:2  →  1:3  →  1:4 2:0  →  2:1  →  2:2  →  2:3  →  2:4. Double arrow () marks the sought moments of time (in this example β€” when Vasya sees two numbers changing simultaneously).In the second example k = 1. Any switching time can be accepted, since during switching of the clock at least one digit is changed. Total switching equals to 24Β·60 = 1440, but Vasya have not seen one of them β€” the switching of 23:59 00:00.In the third example Vasya fell asleep immediately after he began to look at the clock, so he did not see any change.
Input5 5 24 42 1
Output3
2 seconds
256 megabytes
['combinatorics', 'implementation', 'math', '*2700']
D. Museumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day as Petya and his friend Vasya were having one of their numerous trips, they decided to visit a museum castle. The museum has a specific shape: it consists of n rooms connected with m corridors so that one can access any room from any other one.After the two friends had a little walk around the museum, they decided to split and watch the pieces of art each of them found interesting. They agreed to meet in one of the rooms at six p.m. However, they forgot one quite essential thing: they didn't specify the place to meet and when the time came, they started to rush about the museum looking for each other (they couldn't call each other as roaming made a call's cost skyrocket).Yet, even despite the whole rush, they couldn't get enough of the pieces of art, that's why each of them has the following strategy: each minute he make a decision where to go β€” with probability pi he doesn't move to any other place during this minute (i.e. he stays in the room). With probability 1 - pi he equiprobably choose one of the adjacent rooms and went there along the corridor. Here i is the ordinal number of the current room. Building was expensive in ancient times, that's why each corridor connected two different rooms, and any two rooms had no more than one corridor between them. The boys act simultaneously. As the corridors are dark, it is impossible to meet there; however, one can walk along the corridors in both directions (besides, the two boys can be going through the same corridor simultaneously without meeting). The boys act like that until they meet each other. More formally, the two friends meet when at some moment of time both of them decided to appear in the same room.For each room find the probability that the boys will meet there considering that at 6 p.m. they are positioned in rooms a and b correspondingly.InputThe first line contains four integers: n (1 ≀ n ≀ 22), representing the numbers of rooms; m , representing the number of corridors; a, b (1 ≀ a, b ≀ n), representing the numbers of Petya's and Vasya's starting rooms correspondingly.Next m lines contain pairs of numbers β€” the numbers of rooms connected by a corridor. Next n lines contain probabilities pi (0.01 ≀ pi ≀ 0.99) with the accuracy of up to four digits after the decimal point β€” the probability to stay in room i.It is guaranteed that every room can be reached from every other room by corridors.OutputIn the only line print n space-separated numbers, the i-th number should represent the probability that the friends meet in the i-th room with absolute or relative error of no more than 10 - 6.ExamplesInput2 1 1 21 20.50.5Output0.5000000000 0.5000000000 Input4 4 1 21 22 33 44 10.50.50.50.5Output0.3333333333 0.3333333333 0.1666666667 0.1666666667 NoteIn the first sample the museum is symmetric. That means the probabilities to meet in rooms 1 and 2 are equal. And their sum equals to one. So, each probability equals 0.5.
Input2 1 1 21 20.50.5
Output0.5000000000 0.5000000000
2 seconds
256 megabytes
['math', 'matrices', 'probabilities', '*2700']
C. Double Happinesstime limit per test3 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputOn the math lesson a teacher asked each pupil to come up with his own lucky numbers. As a fan of number theory Peter chose prime numbers. Bob was more original. He said that number t is his lucky number, if it can be represented as: t = a2 + b2,  where a, b are arbitrary positive integers.Now, the boys decided to find out how many days of the interval [l, r] (l ≀ r) are suitable for pair programming. They decided that the day i (l ≀ i ≀ r) is suitable for pair programming if and only if the number i is lucky for Peter and lucky for Bob at the same time. Help the boys to find the number of such days.InputThe first line of the input contains integer numbers l, r (1 ≀ l, r ≀ 3Β·108).OutputIn the only line print the number of days on the segment [l, r], which are lucky for Peter and Bob at the same time.ExamplesInput3 5Output1Input6 66Output7
Input3 5
Output1
3 seconds
128 megabytes
['brute force', 'math', 'number theory', '*2200']
B. Petr#time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLong ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the sbegin and ending with the send (it is possible sbegin = send), the given string t has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him!InputThe input file consists of three lines. The first line contains string t. The second and the third lines contain the sbegin and send identificators, correspondingly. All three lines are non-empty strings consisting of lowercase Latin letters. The length of each string doesn't exceed 2000 characters.OutputOutput the only number β€” the amount of different substrings of t that start with sbegin and end with send.ExamplesInputroundroouOutput1InputcodeforcescodeforcaOutput0InputabababababOutput4InputabaabbaOutput1NoteIn the third sample there are four appropriate different substrings. They are: ab, abab, ababab, abababab.In the fourth sample identificators intersect.
Inputroundroou
Output1
2 seconds
256 megabytes
['brute force', 'data structures', 'hashing', 'strings', '*2000']
A. Grammar Lessonstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. Masculine adjectives end with -lios, and feminine adjectives end with -liala. Masculine nouns end with -etr, and feminime nouns end with -etra. Masculine verbs end with -initis, and feminime verbs end with -inites. Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.InputThe first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105.It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.OutputIf some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).ExamplesInputpetrOutputYESInputetis atis animatis etis atis amatisOutputNOInputnataliala kataliala vetra feinitesOutputYES
Inputpetr
OutputYES
5 seconds
256 megabytes
['implementation', 'strings', '*1600']
B. Petya and Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya loves playing with squares. Mum bought him a square 2n × 2n in size. Petya marked a cell inside the square and now he is solving the following task.The task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any common points with the marked cell and the resulting two parts should be equal up to rotation.Petya wants to determine whether it is possible to cut the square in the required manner given the sizes of the square side and the coordinates of the marked cell. Help him.InputThe first line contains three space-separated integers 2n, x and y (2 ≀ 2n ≀ 100, 1 ≀ x, y ≀ 2n), representing the length of a square's side and the coordinates of the marked cell. It is guaranteed that 2n is even.The coordinates of the marked cell are represented by a pair of numbers x y, where x represents the number of the row and y represents the number of the column. The rows and columns are numbered by consecutive integers from 1 to 2n. The rows are numbered from top to bottom and the columns are numbered from the left to the right.OutputIf the square is possible to cut, print "YES", otherwise print "NO" (without the quotes).ExamplesInput4 1 1OutputYESInput2 2 2OutputNONoteA sample test from the statement and one of the possible ways of cutting the square are shown in the picture:
Input4 1 1
OutputYES
2 seconds
256 megabytes
['implementation', 'math', '*1200']
A. Petya and Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.InputEach of the first two lines contains a bought string. The strings' lengths range from 1 to 100 inclusive. It is guaranteed that the strings are of the same length and also consist of uppercase and lowercase Latin letters.OutputIf the first string is less than the second one, print "-1". If the second string is less than the first one, print "1". If the strings are equal, print "0". Note that the letters' case is not taken into consideration when the strings are compared.ExamplesInputaaaaaaaAOutput0InputabsAbzOutput-1InputabcdefgAbCdEfFOutput1NoteIf you want more formal information about the lexicographical order (also known as the "dictionary order" or "alphabetical order"), you can visit the following site: http://en.wikipedia.org/wiki/Lexicographical_order
InputaaaaaaaA
Output0
2 seconds
256 megabytes
['implementation', 'strings', '*800']
E. Petya and Rectangletime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya loves playing with rectangles. Mom bought Petya a rectangle divided into cells n × m in size (containing n rows, m columns). Petya marked two different cells of the rectangle and now he is solving the following task:Let's define a simple path between those two cells as a sequence of distinct cells a1, a2, ..., ak, where a1 and ak are the two marked cells. Besides, ai and ai + 1 are side-neighboring cells of the path (1 ≀ i < k). Let's denote the path length as number k (the sequence length). Petya's task is to find the longest simple path's length and to print the path. Help him.InputThe first line contains space-separated integers n and m (4 ≀ n, m ≀ 1000) β€” the number of rows and the number of columns in the rectangle, correspondingly. The second line contains space-separated integers x1 and y1 β€” the coordinates of the first marked cell. The third line contains space-separated integers x2 y2 β€” the coordinates of the second marked cell (1 < x1, x2 < n, 1 < y1, y2 < m, x1 ≠ x2, y1 ≠ y2).The coordinates of a marked cell are a pair of integers x y, where x represents the row's number and y represents the column's number. The rows are numbered from top to bottom with consecutive integers from 1 to n. The columns are numbered from the left to the right by consecutive integers from 1 to m.It is guaranteed that the marked cells are not positioned in one row or column.OutputIn the first line print the length of the found path β€” k. In the next lines print k pairs of integers, one per line β€” coordinates of the cells that constitute the found path in the order, in which they follow in the path (the path must go from cell (x1, y1) to cell (x2, y2)). If there are several solutions, print any of them.ExamplesInput4 42 23 3Output152 21 21 12 13 14 14 24 34 43 42 41 41 32 33 3NoteThe statement test is described in the picture:
Input4 42 23 3
Output152 21 21 12 13 14 14 24 34 43 42 41 41 32 33 3
5 seconds
256 megabytes
['*2900']
D. Petya and Coloringtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya loves counting. He wants to count the number of ways to paint a rectangular checkered board of size n × m (n rows, m columns) in k colors. Besides, the coloring should have the following property: for any vertical line that passes along the grid lines and divides the board in two non-empty parts the number of distinct colors in both these parts should be the same. Help Petya to count these colorings.InputThe first line contains space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 106) β€” the board's vertical and horizontal sizes and the number of colors respectively.OutputPrint the answer to the problem. As the answer can be quite a large number, you should print it modulo 109 + 7 (1000000007).ExamplesInput2 2 1Output1Input2 2 2Output8Input3 2 2Output40
Input2 2 1
Output1
5 seconds
256 megabytes
['combinatorics', 'dp', '*2300']
C. Petya and Spiderstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya loves training spiders. Petya has a board n × m in size. Each cell of the board initially has a spider sitting on it. After one second Petya chooses a certain action for each spider, and all of them humbly perform its commands. There are 5 possible commands: to stay idle or to move from current cell to some of the four side-neighboring cells (that is, one command for each of the four possible directions). Petya gives the commands so that no spider leaves the field. It is allowed for spiders to pass through each other when they crawl towards each other in opposite directions. All spiders crawl simultaneously and several spiders may end up in one cell. Petya wants to know the maximum possible number of spider-free cells after one second.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 40, nΒ·m ≀ 40) β€” the board sizes.OutputIn the first line print the maximum number of cells without spiders.ExamplesInput1 1Output0Input2 3Output4NoteIn the first sample the only possible answer is:sIn the second sample one of the possible solutions is: rdlruls denotes command "stay idle", l, r, d, u denote commands "crawl left", "crawl right", "crawl down", "crawl up", correspondingly.
Input1 1
Output0
2 seconds
256 megabytes
['bitmasks', 'dp', 'dsu', '*2100']
B. Petya and Divisorstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya loves looking for numbers' divisors. One day Petya came across the following problem:You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him.InputThe first line contains an integer n (1 ≀ n ≀ 105). Each of the following n lines contain two space-separated integers xi and yi (1 ≀ xi ≀ 105, 0 ≀ yi ≀ i - 1, where i is the query's ordinal number; the numeration starts with 1). If yi = 0 for the query, then the answer to the query will be the number of divisors of the number xi. In this case you do not need to take the previous numbers x into consideration.OutputFor each query print the answer on a single line: the number of positive integers k such that ExamplesInput64 03 15 26 218 410000 3Output3112222NoteLet's write out the divisors that give answers for the first 5 queries:1) 1, 2, 4 2) 33) 54) 2, 65) 9, 18
Input64 03 15 26 218 410000 3
Output3112222
5 seconds
256 megabytes
['binary search', 'data structures', 'number theory', '*1900']
A. Petya and Inequiationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya loves inequations. Help him find n positive integers a1, a2, ..., an, such that the following two conditions are satisfied: a12 + a22 + ... + an2 β‰₯ x a1 + a2 + ... + an ≀ yInputThe first line contains three space-separated integers n, x and y (1 ≀ n ≀ 105, 1 ≀ x ≀ 1012, 1 ≀ y ≀ 106).Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use cin, cout streams or the %I64d specificator.OutputPrint n positive integers that satisfy the conditions, one integer per line. If such numbers do not exist, print a single number "-1". If there are several solutions, print any of them.ExamplesInput5 15 15Output44112Input2 3 2Output-1Input1 99 11Output11
Input5 15 15
Output44112
2 seconds
256 megabytes
['greedy', '*1400']
B. Lucky Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each individual letter all its positions in the string are written out in the increasing order. This results in 26 lists of numbers; some of them can be empty. A string is considered lucky if and only if in each list the absolute difference of any two adjacent numbers is a lucky number. For example, let's consider string "zbcdzefdzc". The lists of positions of equal letters are: b: 2 c: 3, 10 d: 4, 8 e: 6 f: 7 z: 1, 5, 9 Lists of positions of letters a, g, h, ..., y are empty.This string is lucky as all differences are lucky numbers. For letters z: 5 - 1 = 4, 9 - 5 = 4, for letters c: 10 - 3 = 7, for letters d: 8 - 4 = 4. Note that if some letter occurs only once in a string, it doesn't influence the string's luckiness after building the lists of positions of equal letters. The string where all the letters are distinct is considered lucky.Find the lexicographically minimal lucky string whose length equals n.InputThe single line contains a positive integer n (1 ≀ n ≀ 105) β€” the length of the sought string.OutputPrint on the single line the lexicographically minimal lucky string whose length equals n.ExamplesInput5OutputabcdaInput3OutputabcNoteThe lexical comparison of strings is performed by the < operator in modern programming languages. String a is lexicographically less than string b if exists such i (1 ≀ i ≀ n), that ai < bi, and for any j (1 ≀ j < i) aj = bj.
Input5
Outputabcda
2 seconds
256 megabytes
['constructive algorithms', 'strings', '*1100']
A. Nearly Lucky Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.InputThe only line contains an integer n (1 ≀ n ≀ 1018).Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.OutputPrint on the single line "YES" if n is a nearly lucky number. Otherwise, print "NO" (without the quotes).ExamplesInput40047OutputNOInput7747774OutputYESInput1000000000000000000OutputNONoteIn the first sample there are 3 lucky digits (first one and last two), so the answer is "NO".In the second sample there are 7 lucky digits, 7 is lucky number, so the answer is "YES".In the third sample there are no lucky digits, so the answer is "NO".
Input40047
OutputNO
2 seconds
256 megabytes
['implementation', '*800']
E. Lucky Intervaltime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya came across an interval of numbers [a, a + l - 1]. Let F(x) be the number of lucky digits of number x. Find the minimum b (a < b) such, that F(a) = F(b), F(a + 1) = F(b + 1), ..., F(a + l - 1) = F(b + l - 1).InputThe single line contains two integers a and l (1 ≀ a, l ≀ 109) β€” the interval's first number and the interval's length correspondingly.OutputOn the single line print number b β€” the answer to the problem.ExamplesInput7 4Output17Input4 7Output14NoteConsider that [a, b] denotes an interval of integers; this interval includes the boundaries. That is,
Input7 4
Output17
4 seconds
512 megabytes
['brute force', 'math', '*2700']
D. Lucky Sortingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya got an array consisting of n numbers, it is the gift for his birthday. Now he wants to sort it in the non-decreasing order. However, a usual sorting is boring to perform, that's why Petya invented the following limitation: one can swap any two numbers but only if at least one of them is lucky. Your task is to sort the array according to the specified limitation. Find any possible sequence of the swaps (the number of operations in the sequence should not exceed 2n).InputThe first line contains an integer n (1 ≀ n ≀ 105) β€” the number of elements in the array. The second line contains n positive integers, not exceeding 109 β€” the array that needs to be sorted in the non-decreasing order.OutputOn the first line print number k (0 ≀ k ≀ 2n) β€” the number of the swaps in the sorting. On the following k lines print one pair of distinct numbers (a pair per line) β€” the indexes of elements to swap. The numbers in the array are numbered starting from 1. If it is impossible to sort the given sequence, print the single number -1.If there are several solutions, output any. Note that you don't have to minimize k. Any sorting with no more than 2n swaps is accepted.ExamplesInput24 7Output0Input34 2 1Output11 3Input777 66 55 44 33 22 11Output71 77 22 66 73 45 34 5
Input24 7
Output0
3 seconds
256 megabytes
['constructive algorithms', 'sortings', '*2000']