problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
β | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
B. Batch Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a table consisting of n rows and m columns.Numbers in each row form a permutation of integers from 1 to m.You are allowed to pick two elements in one row and swap them, but no more than once for each row. Also, no more than once you are allowed to pick two columns and swap them. Thus, you are allowed to perform from 0 to nβ+β1 actions in total. Operations can be performed in any order.You have to check whether it's possible to obtain the identity permutation 1,β2,β...,βm in each row. In other words, check if one can perform some of the operation following the given rules and make each row sorted in increasing order.InputThe first line of the input contains two integers n and m (1ββ€βn,βmββ€β20)Β β the number of rows and the number of columns in the given table. Each of next n lines contains m integersΒ β elements of the table. It's guaranteed that numbers in each line form a permutation of integers from 1 to m.OutputIf there is a way to obtain the identity permutation in each row by following the given rules, print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).ExamplesInput2 41 3 2 41 3 4 2OutputYESInput4 41 2 3 42 3 4 13 4 1 24 1 2 3OutputNOInput3 62 1 3 4 5 61 2 4 3 5 61 2 3 4 6 5OutputYESNoteIn the first sample, one can act in the following way: Swap second and third columns. Now the table is 1Β 2Β 3Β 4 1Β 4Β 3Β 2 In the second row, swap the second and the fourth elements. Now the table is 1Β 2Β 3Β 4 1Β 2Β 3Β 4 | Input2 41 3 2 41 3 4 2 | OutputYES | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'implementation', 'math', '*1500'] |
A. Checking the Calendartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given names of two days of the week.Please, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, while the first day of the next month was equal to the second day of the week you are given. Both months should belong to one year.In this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. The number of days in months during any non-leap year is: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31.Names of the days of the week are given with lowercase English letters: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".InputThe input consists of two lines, each of them containing the name of exactly one day of the week. It's guaranteed that each string in the input is from the set "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday".OutputPrint "YES" (without quotes) if such situation is possible during some non-leap year. Otherwise, print "NO" (without quotes).ExamplesInputmondaytuesdayOutputNOInputsundaysundayOutputYESInputsaturdaytuesdayOutputYESNoteIn the second sample, one can consider February 1 and March 1 of year 2015. Both these days were Sundays.In the third sample, one can consider July 1 and August 1 of year 2017. First of these two days is Saturday, while the second one is Tuesday. | Inputmondaytuesday | OutputNO | 1 second | 256 megabytes | ['implementation', '*1000'] |
F. st-Spanning Treetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex s doesn't exceed ds, and the degree of the vertex t doesn't exceed dt, or determine, that there is no such spanning tree.The spanning tree of the graph G is a subgraph which is a tree and contains all vertices of the graph G. In other words, it is a connected graph which contains nβ-β1 edges and can be obtained by removing some of the edges from G.The degree of a vertex is the number of edges incident to this vertex.InputThe first line of the input contains two integers n and m (2ββ€βnββ€β200β000, 1ββ€βmββ€βmin(400β000,βnΒ·(nβ-β1)β/β2))Β β the number of vertices and the number of edges in the graph. The next m lines contain the descriptions of the graph's edges. Each of the lines contains two integers u and v (1ββ€βu,βvββ€βn, uββ βv)Β β the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected.The last line contains four integers s, t, ds, dt (1ββ€βs,βtββ€βn, sββ βt, 1ββ€βds,βdtββ€βnβ-β1).OutputIf the answer doesn't exist print "No" (without quotes) in the only line of the output. Otherwise, in the first line print "Yes" (without quotes). In the each of the next (nβ-β1) lines print two integers β the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once.You can output edges in any order. You can output the ends of each edge in any order.If there are several solutions, print any of them.ExamplesInput3 31 22 33 11 2 1 1OutputYes3 21 3Input7 87 41 35 45 73 22 46 11 26 4 1 4OutputYes1 35 73 27 42 46 1 | Input3 31 22 33 11 2 1 1 | OutputYes3 21 3 | 4 seconds | 256 megabytes | ['dsu', 'graphs', 'greedy', 'implementation', '*2300'] |
E. One-Way Reformtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities and m two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads.The road minister decided to make a reform in Berland and to orient all roads in the country, i.e. to make each road one-way. The minister wants to maximize the number of cities, for which the number of roads that begins in the city equals to the number of roads that ends in it.InputThe first line contains a positive integer t (1ββ€βtββ€β200)Β β the number of testsets in the input.Each of the testsets is given in the following way. The first line contains two integers n and m (1ββ€βnββ€β200, 0ββ€βmββ€βnΒ·(nβ-β1)β/β2)Β β the number of cities and the number of roads in Berland. The next m lines contain the description of roads in Berland. Each line contains two integers u and v (1ββ€βu,βvββ€βn)Β β the cities the corresponding road connects. It's guaranteed that there are no self-loops and multiple roads. It is possible that there is no way along roads between a pair of cities.It is guaranteed that the total number of cities in all testset of input data doesn't exceed 200.Pay attention that for hacks, you can only use tests consisting of one testset, so t should be equal to one.OutputFor each testset print the maximum number of such cities that the number of roads that begins in the city, is equal to the number of roads that ends in it.In the next m lines print oriented roads. First print the number of the city where the road begins and then the number of the city where the road ends. If there are several answers, print any of them. It is allowed to print roads in each test in arbitrary order. Each road should be printed exactly once. ExampleInput25 52 14 52 31 33 57 23 74 2Output31 33 55 43 22 132 43 7 | Input25 52 14 52 31 33 57 23 74 2 | Output31 33 55 43 22 132 43 7 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'flows', 'graphs', 'greedy', '*2200'] |
D. Lakes in Berlandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe map of Berland is a rectangle of the size nβΓβm, which consists of cells of size 1βΓβ1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k. InputThe first line of the input contains three integers n, m and k (1ββ€βn,βmββ€β50, 0ββ€βkββ€β50)Β β the sizes of the map and the number of lakes which should be left on the map.The next n lines contain m characters each β the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land).It is guaranteed that the map contain at least k lakes.OutputIn the first line print the minimum number of cells which should be transformed from water to land. In the next n lines print m symbols β the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them. It is guaranteed that the answer exists on the given data.ExamplesInput5 4 1*****..*******.*..**Output1*****..*********..**Input3 3 0****.****Output1*********NoteIn the first example there are only two lakes β the first consists of the cells (2,β2) and (2,β3), the second consists of the cell (4,β3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean. | Input5 4 1*****..*******.*..** | Output1*****..*********..** | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', 'greedy', 'implementation', '*1600'] |
C. Polycarp at the Radiotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1,βa2,β...,βan, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others. We define as bj the number of songs the group j is going to perform tomorrow. Polycarp wants to change the playlist in such a way that the minimum among the numbers b1,βb2,β...,βbm will be as large as possible.Find this maximum possible value of the minimum among the bj (1ββ€βjββ€βm), and the minimum number of changes in the playlist Polycarp needs to make to achieve it. One change in the playlist is a replacement of the performer of the i-th song with any other group.InputThe first line of the input contains two integers n and m (1ββ€βmββ€βnββ€β2000).The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109), where ai is the performer of the i-th song.OutputIn the first line print two integers: the maximum possible value of the minimum among the bj (1ββ€βjββ€βm), where bj is the number of songs in the changed playlist performed by the j-th band, and the minimum number of changes in the playlist Polycarp needs to make.In the second line print the changed playlist.If there are multiple answers, print any of them.ExamplesInput4 21 2 3 2Output2 11 2 1 2 Input7 31 3 2 2 2 2 1Output2 11 3 3 2 2 2 1 Input4 41000000000 100 7 1000000000Output1 41 2 3 4 NoteIn the first sample, after Polycarp's changes the first band performs two songs (b1β=β2), and the second band also performs two songs (b2β=β2). Thus, the minimum of these values equals to 2. It is impossible to achieve a higher minimum value by any changes in the playlist. In the second sample, after Polycarp's changes the first band performs two songs (b1β=β2), the second band performs three songs (b2β=β3), and the third band also performs two songs (b3β=β2). Thus, the best minimum value is 2. | Input4 21 2 3 2 | Output2 11 2 1 2 | 2 seconds | 256 megabytes | ['greedy', '*1600'] |
B. Text Document Analysistime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputModern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.In this problem you should implement the similar functionality.You are given a string which only consists of: uppercase and lowercase English letters, underscore symbols (they are used as separators), parentheses (both opening and closing). It is guaranteed that each opening parenthesis has a succeeding closing parenthesis. Similarly, each closing parentheses has a preceding opening parentheses matching it. For each pair of matching parentheses there are no other parenthesis between them. In other words, each parenthesis in the string belongs to a matching "opening-closing" pair, and such pairs can't be nested.For example, the following string is valid: "_Hello_Vasya(and_Petya)__bye_(and_OK)".Word is a maximal sequence of consecutive letters, i.e. such sequence that the first character to the left and the first character to the right of it is an underscore, a parenthesis, or it just does not exist. For example, the string above consists of seven words: "Hello", "Vasya", "and", "Petya", "bye", "and" and "OK". Write a program that finds: the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses), the number of words inside the parentheses (print 0, if there is no word inside the parentheses). InputThe first line of the input contains a single integer n (1ββ€βnββ€β255)Β β the length of the given string. The second line contains the string consisting of only lowercase and uppercase English letters, parentheses and underscore symbols. OutputPrint two space-separated integers: the length of the longest word outside the parentheses (print 0, if there is no word outside the parentheses), the number of words inside the parentheses (print 0, if there is no word inside the parentheses). ExamplesInput37_Hello_Vasya(and_Petya)__bye_(and_OK)Output5 4Input37_a_(_b___c)__de_f(g_)__h__i(j_k_l)m__Output2 6Input27(LoooonG)__shOrt__(LoooonG)Output5 2Input5(___)Output0 0NoteIn the first sample, the words "Hello", "Vasya" and "bye" are outside any of the parentheses, and the words "and", "Petya", "and" and "OK" are inside. Note, that the word "and" is given twice and you should count it twice in the answer. | Input37_Hello_Vasya(and_Petya)__bye_(and_OK) | Output5 4 | 1 second | 256 megabytes | ['expression parsing', 'implementation', 'strings', '*1100'] |
A. The New Year: Meeting Friendstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?It's guaranteed that the optimal answer is always integer.InputThe first line of the input contains three distinct integers x1, x2 and x3 (1ββ€βx1,βx2,βx3ββ€β100)Β β the coordinates of the houses of the first, the second and the third friends respectively. OutputPrint one integerΒ β the minimum total distance the friends need to travel in order to meet together.ExamplesInput7 1 4Output6Input30 20 10Output20NoteIn the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4. | Input7 1 4 | Output6 | 1 second | 256 megabytes | ['implementation', 'math', 'sortings', '*800'] |
F. Cyclic Ciphertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n sequences. Each sequence consists of positive integers, not exceeding m. All integers in one sequence are distinct, but the same integer may appear in multiple sequences. The length of the i-th sequence is ki.Each second integers in each of the sequences are shifted by one to the left, i.e. integers at positions iβ>β1 go to positions iβ-β1, while the first integers becomes the last.Each second we take the first integer of each sequence and write it down to a new array. Then, for each value x from 1 to m we compute the longest segment of the array consisting of element x only.The above operation is performed for 10100 seconds. For each integer from 1 to m find out the longest segment found at this time.InputThe first line of the input contains two integers n and m (1ββ€βn,βmββ€β100β000)Β β the number of sequences and the maximum integer that can appear in the sequences. Then follow n lines providing the sequences. Each of them starts with an integer ki (1ββ€βkiββ€β40)Β β the number of integers in the sequence, proceeded by ki positive integersΒ β elements of the sequence. It's guaranteed that all integers in each sequence are pairwise distinct and do not exceed m.The total length of all sequences doesn't exceed 200β000.OutputPrint m integers, the i-th of them should be equal to the length of the longest segment of the array with all its values equal to i during the first 10100 seconds.ExamplesInput3 43 3 4 14 1 3 4 23 3 1 4Output2132Input5 52 3 14 5 1 3 24 2 1 3 51 32 5 3Output31401Input4 63 4 5 32 6 32 3 63 3 6 5Output002112 | Input3 43 3 4 14 1 3 4 23 3 1 4 | Output2132 | 2 seconds | 256 megabytes | ['chinese remainder theorem', 'data structures', 'implementation', 'number theory', 'two pointers', '*2800'] |
E. Research Rovertime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUnfortunately, the formal description of the task turned out to be too long, so here is the legend.Research rover finally reached the surface of Mars and is ready to complete its mission. Unfortunately, due to the mistake in the navigation system design, the rover is located in the wrong place.The rover will operate on the grid consisting of n rows and m columns. We will define as (r,βc) the cell located in the row r and column c. From each cell the rover is able to move to any cell that share a side with the current one.The rover is currently located at cell (1,β1) and has to move to the cell (n,βm). It will randomly follow some shortest path between these two cells. Each possible way is chosen equiprobably.The cargo section of the rover contains the battery required to conduct the research. Initially, the battery charge is equal to s units of energy.Some of the cells contain anomaly. Each time the rover gets to the cell with anomaly, the battery looses half of its charge rounded down. Formally, if the charge was equal to x before the rover gets to the cell with anomaly, the charge will change to .While the rover picks a random shortest path to proceed, compute the expected value of the battery charge after it reaches cell (n,βm). If the cells (1,β1) and (n,βm) contain anomaly, they also affect the charge of the battery.InputThe first line of the input contains four integers n, m, k and s (1ββ€βn,βmββ€β100β000, 0ββ€βkββ€β2000, 1ββ€βsββ€β1β000β000)Β β the number of rows and columns of the field, the number of cells with anomaly and the initial charge of the battery respectively.The follow k lines containing two integers ri and ci (1ββ€βriββ€βn, 1ββ€βciββ€βm)Β β coordinates of the cells, containing anomaly. It's guaranteed that each cell appears in this list no more than once.OutputThe answer can always be represented as an irreducible fraction . Print the only integer PΒ·Qβ-β1 modulo 109β+β7.ExamplesInput3 3 2 112 12 3Output333333342Input4 5 3 171 23 34 1Output514285727Input1 6 2 151 11 5Output4NoteIn the first sample, the rover picks one of the following six routes: , after passing cell (2,β3) charge is equal to 6. , after passing cell (2,β3) charge is equal to 6. , charge remains unchanged and equals 11. , after passing cells (2,β1) and (2,β3) charge equals 6 and then 3. , after passing cell (2,β1) charge is equal to 6. , after passing cell (2,β1) charge is equal to 6. Expected value of the battery charge is calculated by the following formula:.Thus Pβ=β19, and Qβ=β3.3β-β1 modulo 109β+β7 equals 333333336.19Β·333333336β=β333333342Β (modΒ 109β+β7) | Input3 3 2 112 12 3 | Output333333342 | 2.5 seconds | 256 megabytes | ['combinatorics', 'dp', '*2900'] |
D. Generating Setstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set Y of n distinct positive integers y1,βy2,β...,βyn.Set X of n distinct positive integers x1,βx2,β...,βxn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X: Take any integer xi and multiply it by two, i.e. replace xi with 2Β·xi. Take any integer xi, multiply it by two and add one, i.e. replace xi with 2Β·xiβ+β1. Note that integers in X are not required to be distinct after each operation.Two sets of distinct integers X and Y are equal if they are equal as sets. In other words, if we write elements of the sets in the array in the increasing order, these arrays would be equal.Note, that any set of integers (or its permutation) generates itself.You are given a set Y and have to find a set X that generates Y and the maximum element of X is mininum possible.InputThe first line of the input contains a single integer n (1ββ€βnββ€β50β000)Β β the number of elements in Y.The second line contains n integers y1,β...,βyn (1ββ€βyiββ€β109), that are guaranteed to be distinct.OutputPrint n integersΒ β set of distinct integers that generate Y and the maximum element of which is minimum possible. If there are several such sets, print any of them.ExamplesInput51 2 3 4 5Output4 5 2 3 1 Input615 14 3 13 1 12Output12 13 14 7 3 1 Input69 7 13 17 5 11Output4 5 2 6 3 1 | Input51 2 3 4 5 | Output4 5 2 3 1 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', 'greedy', 'strings', 'trees', '*1900'] |
C. Destroying Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array consisting of n non-negative integers a1,βa2,β...,βan.You are going to destroy integers in the array one by one. Thus, you are given the permutation of integers from 1 to n defining the order elements of the array are destroyed.After each element is destroyed you have to find out the segment of the array, such that it contains no destroyed elements and the sum of its elements is maximum possible. The sum of elements in the empty segment is considered to be 0.InputThe first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the length of the array.The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β109). The third line contains a permutation of integers from 1 to nΒ β the order used to destroy elements.OutputPrint n lines. The i-th line should contain a single integerΒ β the maximum possible sum of elements on the segment containing no destroyed elements, after first i operations are performed.ExamplesInput41 3 2 53 4 1 2Output5430Input51 2 3 4 54 2 3 5 1Output65510Input85 5 4 4 6 6 5 55 2 8 7 1 3 4 6Output18161188660NoteConsider the first sample: Third element is destroyed. Array is now 1Β 3Β β*βΒ 5. Segment with maximum sum 5 consists of one integer 5. Fourth element is destroyed. Array is now 1Β 3Β β*βΒ β*β. Segment with maximum sum 4 consists of two integers 1Β 3. First element is destroyed. Array is now β*βΒ 3Β β*βΒ β*β. Segment with maximum sum 3 consists of one integer 3. Last element is destroyed. At this moment there are no valid nonempty segments left in this array, so the answer is equal to 0. | Input41 3 2 53 4 1 2 | Output5430 | 1 second | 256 megabytes | ['data structures', 'dsu', '*1600'] |
B. Verse Patterntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.The verse patterns for the given text is a sequence of n integers p1,βp2,β...,βpn. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to pi.You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.InputThe first line of the input contains a single integer n (1ββ€βnββ€β100)Β β the number of lines in the text.The second line contains integers p1,β...,βpn (0ββ€βpiββ€β100)Β β the verse pattern.Next n lines contain the text itself. Text consists of lowercase English letters and spaces. It's guaranteed that all lines are non-empty, each line starts and ends with a letter and words are separated by exactly one space. The length of each line doesn't exceed 100 characters.OutputIf the given text matches the given verse pattern, then print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).ExamplesInput32 2 3intelcodech allengeOutputYESInput41 2 3 1abcdefghijklmnopqrstuvwxyzOutputNOInput413 11 15 15to be or not to be that is the questionwhether tis nobler in the mind to sufferthe slings and arrows of outrageous fortuneor to take arms against a sea of troublesOutputYESNoteIn the first sample, one can split words into syllables in the following way: in-telco-dech al-len-geSince the word "ch" in the third line doesn't contain vowels, we can ignore it. As the result we get 2 syllabels in first two lines and 3 syllables in the third one. | Input32 2 3intelcodech allenge | OutputYES | 1 second | 256 megabytes | ['implementation', 'strings', '*1200'] |
A. Broken Clocktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.InputThe first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively.The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.OutputThe only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.ExamplesInput2417:30Output17:30Input1217:30Output07:30Input2499:99Output09:09 | Input2417:30 | Output17:30 | 1 second | 256 megabytes | ['brute force', 'implementation', '*1300'] |
E. Road to Hometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Danil the student was returning home from tram stop lately by straight road of length L. The stop is located at the point xβ=β0, but the Danil's homeΒ β at the point xβ=βL. Danil goes from xβ=β0 to xβ=βL with a constant speed and does not change direction of movement.There are n street lights at the road, each of which lights some continuous segment of the road. All of the n lightened segments do not share common points.Danil loves to sing, thus he wants to sing his favourite song over and over again during his walk. As soon as non-lightened segments of the road scare him, he sings only when he goes through the lightened segments.Danil passes distance p while performing his favourite song once. Danil can't start another performance if the segment passed while performing is not fully lightened. Moreover, if Danil has taken a pause between two performances, he is not performing while not having passed a segment of length at least t. Formally, Danil can start single performance at a point x only if every point of segment [x,βxβ+βp] is lightened; If Danil has finished performing at a point xβ+βp, then the next performance can be started only at a point y such that yβ=βxβ+βp or yββ₯βxβ+βpβ+βt satisfying the statement under the point 1. Blue half-circles denote performances. Please note that just after Danil has taken a pause in performing, he has not sang for a path of length of at least t. Determine how many times Danil can perform his favourite song during his walk from xβ=β0 to xβ=βL.Please note that Danil does not break a single performance, thus, started singing another time, he finishes singing when having a segment of length of p passed from the performance start point.InputThe first line of the input contains four integers L, n, p and t (1ββ€βLββ€β109, 0ββ€βnββ€β100β000, 1ββ€βpββ€β109, 1ββ€βtββ€β109)Β β the length of the Danil's path, the number of street lights at the road, the distance Danil passes while doing single performance and the minimum distance of pause respectively.The next n lines describe segments lightened by street lights. i-th of them contains two integers li,βri (0ββ€βliβ<βriββ€βL)Β β the endpoints of the segment lightened by i-th street light. It is guaranteed that no two segments are intersecting, nesting, or touching each other. The segments are given in the order from left to right.OutputPrint the only integerΒ β the maximum number of performances of Danil's favourite song on the path from xβ=β0 to xβ=βL.ExamplesInput17 2 2 60 913 17Output5Input12 2 2 20 56 11Output4Input12 2 2 40 56 11Output3NoteThe first sample case is just about corresponding to the picture from the statement. | Input17 2 2 60 913 17 | Output5 | 2 seconds | 256 megabytes | ['binary search', 'dp', '*2700'] |
D. Maxim and Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1ββ€βiββ€βn) and replaces the i-th element of array ai either with aiβ+βx or with aiβ-βx. Please note that the operation may be applied more than once to the same position.Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. ) can reach, if Maxim would apply no more than k operations to it. Please help him in that.InputThe first line of the input contains three integers n,βk and x (1ββ€βn,βkββ€β200β000,β1ββ€βxββ€β109)Β β the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.The second line contains n integers a1,βa2,β...,βan ()Β β the elements of the array found by Maxim.OutputPrint n integers b1,βb2,β...,βbn in the only lineΒ β the array elements after applying no more than k operations to the array. In particular, should stay true for every 1ββ€βiββ€βn, but the product of all array elements should be minimum possible.If there are multiple answers, print any of them.ExamplesInput5 3 15 4 3 5 2Output5 4 3 5 -1 Input5 3 15 4 3 5 5Output5 4 0 5 5 Input5 3 15 4 4 5 5Output5 1 4 5 5 Input3 2 75 4 2Output5 11 -5 | Input5 3 15 4 3 5 2 | Output5 4 3 5 -1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'greedy', 'math', '*2000'] |
C. Journeytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Irina arrived to one of the most famous cities of BerlandΒ β the Berlatov city. There are n showplaces in the city, numbered from 1 to n, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces.Initially Irina stands at the showplace 1, and the endpoint of her journey is the showplace n. Naturally, Irina wants to visit as much showplaces as she can during her journey. However, Irina's stay in Berlatov is limited and she can't be there for more than T time units.Help Irina determine how many showplaces she may visit during her journey from showplace 1 to showplace n within a time not exceeding T. It is guaranteed that there is at least one route from showplace 1 to showplace n such that Irina will spend no more than T time units passing it.InputThe first line of the input contains three integers n,βm and T (2ββ€βnββ€β5000,ββ1ββ€βmββ€β5000,ββ1ββ€βTββ€β109)Β β the number of showplaces, the number of roads between them and the time of Irina's stay in Berlatov respectively.The next m lines describes roads in Berlatov. i-th of them contains 3 integers ui,βvi,βti (1ββ€βui,βviββ€βn,βuiββ βvi,β1ββ€βtiββ€β109), meaning that there is a road starting from showplace ui and leading to showplace vi, and Irina spends ti time units to pass it. It is guaranteed that the roads do not form cyclic routes.It is guaranteed, that there is at most one road between each pair of showplaces.OutputPrint the single integer k (2ββ€βkββ€βn)Β β the maximum number of showplaces that Irina can visit during her journey from showplace 1 to showplace n within time not exceeding T, in the first line.Print k distinct integers in the second lineΒ β indices of showplaces that Irina will visit on her route, in the order of encountering them.If there are multiple answers, print any of them.ExamplesInput4 3 131 2 52 3 72 4 8Output31 2 4 Input6 6 71 2 21 3 33 6 32 4 24 6 26 5 1Output41 2 4 6 Input5 5 61 3 33 5 31 2 22 4 34 5 2Output31 3 5 | Input4 3 131 2 52 3 72 4 8 | Output31 2 4 | 3 seconds | 256 megabytes | ['dp', 'graphs', '*1800'] |
B. Passwordstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrary order. Just when Vanya will have entered the correct password, he is immediately authorized on the site. Vanya will not enter any password twice.Entering any passwords takes one second for Vanya. But if Vanya will enter wrong password k times, then he is able to make the next try only 5 seconds after that. Vanya makes each try immediately, that is, at each moment when Vanya is able to enter password, he is doing that.Determine how many seconds will Vanya need to enter Codehorses in the best case for him (if he spends minimum possible number of second) and in the worst case (if he spends maximum possible amount of seconds).InputThe first line of the input contains two integers n and k (1ββ€βn,βkββ€β100)Β β the number of Vanya's passwords and the number of failed tries, after which the access to the site is blocked for 5 seconds.The next n lines contains passwords, one per lineΒ β pairwise distinct non-empty strings consisting of latin letters and digits. Each password length does not exceed 100 characters.The last line of the input contains the Vanya's Codehorses password. It is guaranteed that the Vanya's Codehorses password is equal to some of his n passwords.OutputPrint two integersΒ β time (in seconds), Vanya needs to be authorized to Codehorses in the best case for him and in the worst case respectively.ExamplesInput5 2cbaabcbb1abCABCabcOutput1 15Input4 10011221222Output3 4NoteConsider the first sample case. As soon as all passwords have the same length, Vanya can enter the right password at the first try as well as at the last try. If he enters it at the first try, he spends exactly 1 second. Thus in the best case the answer is 1. If, at the other hand, he enters it at the last try, he enters another 4 passwords before. He spends 2 seconds to enter first 2 passwords, then he waits 5 seconds as soon as he made 2 wrong tries. Then he spends 2 more seconds to enter 2 wrong passwords, again waits 5 seconds and, finally, enters the correct password spending 1 more second. In summary in the worst case he is able to be authorized in 15 seconds.Consider the second sample case. There is no way of entering passwords and get the access to the site blocked. As soon as the required password has length of 2, Vanya enters all passwords of length 1 anyway, spending 2 seconds for that. Then, in the best case, he immediately enters the correct password and the answer for the best case is 3, but in the worst case he enters wrong password of length 2 and only then the right one, spending 4 seconds at all. | Input5 2cbaabcbb1abCABCabc | Output1 15 | 2 seconds | 256 megabytes | ['implementation', 'math', 'sortings', 'strings', '*1100'] |
A. One-dimensional Japanese Crosswordtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized aβΓβb squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents how many groups of black squares there are in corresponding row or column, and the integers themselves represents the number of consecutive black squares in corresponding group (you can find more detailed explanation in Wikipedia https://en.wikipedia.org/wiki/Japanese_crossword).Adaltik decided that the general case of japanese crossword is too complicated and drew a row consisting of n squares (e.g. japanese crossword sized 1βΓβn), which he wants to encrypt in the same way as in japanese crossword. The example of encrypting of a single row of japanese crossword. Help Adaltik find the numbers encrypting the row he drew.InputThe first line of the input contains a single integer n (1ββ€βnββ€β100)Β β the length of the row. The second line of the input contains a single string consisting of n characters 'B' or 'W', ('B' corresponds to black square, 'W'Β β to white square in the row that Adaltik drew).OutputThe first line should contain a single integer kΒ β the number of integers encrypting the row, e.g. the number of groups of black squares in the row.The second line should contain k integers, encrypting the row, e.g. corresponding to sizes of groups of consecutive black squares in the order from left to right.ExamplesInput3BBWOutput12 Input5BWBWBOutput31 1 1 Input4WWWWOutput0Input4BBBBOutput14 Input13WBBBBWWBWBBBWOutput34 1 3 NoteThe last sample case correspond to the picture in the statement. | Input3BBW | Output12 | 1 second | 256 megabytes | ['implementation', '*800'] |
F. Array Coveringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisha has an array of integers of length n. He wants to choose k different continuous subarrays, so that each element of the array belongs to at least one of the chosen subarrays.Misha wants to choose the subarrays in such a way that if he calculated the sum of elements for each subarray, and then add up all these sums, the resulting value was maximum possible.InputThe first line of input contains two integers: n, k (1ββ€βnββ€β100β000, 1ββ€βkββ€βnΒ·(nβ+β1)β/β2)Β β the number of elements in the array and the number of different subarrays that must be chosen.The second line contains n integers ai (β-β50β000ββ€βaiββ€β50β000)Β β the elements of the array.OutputOutput one integerΒ β the maximum possible value Misha can get by choosing k different subarrays.ExampleInput5 46 -4 -10 -4 7Output11 | Input5 46 -4 -10 -4 7 | Output11 | 3 seconds | 256 megabytes | ['data structures', '*3100'] |
E. Ciphertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBorya has recently found a big electronic display. The computer that manages the display stores some integer number. The number has n decimal digits, the display shows the encoded version of the number, where each digit is shown using some lowercase letter of the English alphabet.There is a legend near the display, that describes how the number is encoded. For each digit position i and each digit j the character c is known, that encodes this digit at this position. Different digits can have the same code characters.Each second the number is increased by 1. And one second after a moment when the number reaches the value that is represented as n 9-s in decimal notation, the loud beep sounds. Andrew knows the number that is stored in the computer. Now he wants to know how many seconds must pass until Borya can definitely tell what was the original number encoded by the display. Assume that Borya can precisely measure time, and that the encoded number will first be increased exactly one second after Borya started watching at the display.InputInput data contains multiple test cases. The first line of input contains t (1ββ€βtββ€β100)Β β the number of test cases. Each test case is described as follows. The first line of the description contains n (1ββ€βnββ€β18)Β β the number of digits in the number. The second line contains n decimal digits without spaces (but possibly with leading zeroes)Β β the number initially stored in the display computer. The following n lines contain 10 characters each. The j-th character of the i-th of these lines is the code character for a digit jβ-β1 in position i, most significant digit positions are described first.OutputFor each test case print an integer: the number of seconds until Borya definitely knows what was the initial number stored on the display of the computer. Do not print leading zeroes.ExampleInput3242abcdefghijjihgfedcba242aaaaaaaaaaaaaaaaaaaa12abcdabcdffOutput0582 | Input3242abcdefghijjihgfedcba242aaaaaaaaaaaaaaaaaaaa12abcdabcdff | Output0582 | 2 seconds | 256 megabytes | ['implementation', '*3100'] |
D. Slalomtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle girl Masha likes winter sports, today she's planning to take part in slalom skiing.The track is represented as a grid composed of nβΓβm squares. There are rectangular obstacles at the track, composed of grid squares. Masha must get from the square (1,β1) to the square (n,βm). She can move from a square to adjacent square: either to the right, or upwards. If the square is occupied by an obstacle, it is not allowed to move to that square.One can see that each obstacle can actually be passed in two ways: either it is to the right of Masha's path, or to the left. Masha likes to try all ways to do things, so she would like to know how many ways are there to pass the track. Two ways are considered different if there is an obstacle such that it is to the right of the path in one way, and to the left of the path in the other way.Help Masha to find the number of ways to pass the track. The number of ways can be quite big, so Masha would like to know it modulo 109β+β7.The pictures below show different ways to pass the track in sample tests. InputThe first line of input data contains three positive integers: n, m and k (3ββ€βn,βmββ€β106, 0ββ€βkββ€β105)Β β the size of the track and the number of obstacles.The following k lines contain four positive integers each: x1, y1, x2, y2 (1ββ€βx1ββ€βx2ββ€βn, 1ββ€βy1ββ€βy2ββ€βm)Β β coordinates of bottom left, and top right squares of the obstacle. It is guaranteed that there are no obstacles at squares (1,β1) and (n,βm), and no obstacles overlap (but some of them may touch).OutputOutput one integerΒ β the number of ways to pass the track modulo 109β+β7.ExamplesInput3 3 0Output1Input4 5 12 2 3 4Output2Input5 5 32 2 2 34 2 5 24 4 4 4Output3 | Input3 3 0 | Output1 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'sortings', '*3100'] |
C. Homeworktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Peter has got an additional homework for tomorrow. The teacher has given three integers to him: n, m and k, and asked him to mark one or more squares on a square grid of size nβΓβm. The marked squares must form a connected figure, and there must be exactly k triples of marked squares that form an L-shaped trominoΒ β all three squares are inside a 2βΓβ2 square.The set of squares forms a connected figure if it is possible to get from any square to any other one if you are allowed to move from a square to any adjacent by a common side square.Peter cannot fulfill the task, so he asks you for help. Help him to create such figure.InputInput data contains one or more test cases. The first line contains the number of test cases t (1ββ€βtββ€β100).Each of the following t test cases is described by a line that contains three integers: n, m and k (3ββ€βn,βm, nβΓβmββ€β105, 0ββ€βkββ€β109).The sum of values of nβΓβm for all tests in one input data doesn't exceed 105.OutputFor each test case print the answer.If it is possible to create such figure, print n lines, m characters each, use asterisk '*' to denote the marked square, and dot '.' to denote the unmarked one.If there is no solution, print -1.Print empty line between test cases.ExampleInput33 3 43 3 53 3 3Output.*.***.*.**.**.*...*.****.. | Input33 3 43 3 53 3 3 | Output.*.***.*.**.**.*...*.****.. | 3 seconds | 256 megabytes | ['constructive algorithms', '*3100'] |
B. Cactusophobiatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTree is a connected undirected graph that has no cycles. Edge cactus is a connected undirected graph without loops and parallel edges, such that each edge belongs to at most one cycle.Vasya has an edge cactus, each edge of this graph has some color.Vasya would like to remove the minimal number of edges in such way that his cactus turned to a tree. Vasya wants to make it in such a way that there were edges of as many different colors in the resulting tree, as possible. Help him to find how many different colors can the resulting tree have.InputThe first line contains two integers: n, m (2ββ€βnββ€β10β000)Β β the number of vertices and the number of edges in Vasya's graph, respectively.The following m lines contain three integers each: u, v, c (1ββ€βu,βvββ€βn, uββ βv, 1ββ€βcββ€βm)Β β the numbers of vertices connected by the corresponding edge, and its color. It is guaranteed that the described graph is indeed an edge cactus.OutputOutput one integer: the maximal number of different colors that the resulting tree can have.ExamplesInput4 41 2 42 3 13 4 24 2 3Output3Input7 91 2 12 3 43 1 51 4 54 5 25 1 61 6 46 7 67 1 3Output6 | Input4 41 2 42 3 13 4 24 2 3 | Output3 | 2 seconds | 256 megabytes | ['dfs and similar', 'flows', '*2400'] |
A. Closing ceremonytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe closing ceremony of Squanch Code Cup is held in the big hall with nβΓβm seats, arranged in n rows, m seats in a row. Each seat has two coordinates (x,βy) (1ββ€βxββ€βn, 1ββ€βyββ€βm). There are two queues of people waiting to enter the hall: k people are standing at (0,β0) and nΒ·mβ-βk people are standing at (0,βmβ+β1). Each person should have a ticket for a specific seat. If person p at (x,βy) has ticket for seat (xp,βyp) then he should walk |xβ-βxp|β+β|yβ-βyp| to get to his seat.Each person has a staminaΒ β the maximum distance, that the person agrees to walk. You should find out if this is possible to distribute all nΒ·m tickets in such a way that each person has enough stamina to get to their seat.InputThe first line of input contains two integers n and m (1ββ€βnΒ·mββ€β104)Β β the size of the hall.The second line contains several integers. The first integer k (0ββ€βkββ€βnΒ·m)Β β the number of people at (0,β0). The following k integers indicate stamina of each person there.The third line also contains several integers. The first integer l (lβ=βnΒ·mβ-βk)Β β the number of people at (0,βmβ+β1). The following l integers indicate stamina of each person there.The stamina of the person is a positive integer less that or equal to nβ+βm.OutputIf it is possible to distribute tickets between people in the described manner print "YES", otherwise print "NO".ExamplesInput2 23 3 3 21 3OutputYESInput2 23 2 3 31 2OutputNO | Input2 23 3 3 21 3 | OutputYES | 2 seconds | 256 megabytes | ['greedy', '*2000'] |
B. Anatoly and Cockroachestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.InputThe first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of cockroaches.The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.OutputPrint one integerΒ β the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.ExamplesInput5rbbrrOutput1Input5bbbbbOutput2Input3rbrOutput0NoteIn the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0. | Input5rbbrr | Output1 | 1 second | 256 megabytes | ['greedy', '*1400'] |
A. Vitya in the Countrysidetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units) for each day is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, and then cycle repeats, thus after the second 1 again goes 0.As there is no internet in the countryside, Vitya has been watching the moon for n consecutive days and for each of these days he wrote down the size of the visible part of the moon. Help him find out whether the moon will be up or down next day, or this cannot be determined by the data he has.InputThe first line of the input contains a single integer n (1ββ€βnββ€β92)Β β the number of consecutive days Vitya was watching the size of the visible part of the moon. The second line contains n integers ai (0ββ€βaiββ€β15)Β β Vitya's records.It's guaranteed that the input data is consistent.OutputIf Vitya can be sure that the size of visible part of the moon on day nβ+β1 will be less than the size of the visible part on day n, then print "DOWN" at the only line of the output. If he might be sure that the size of the visible part will increase, then print "UP". If it's impossible to determine what exactly will happen with the moon, print -1.ExamplesInput53 4 5 6 7OutputUPInput712 13 14 15 14 13 12OutputDOWNInput18Output-1NoteIn the first sample, the size of the moon on the next day will be equal to 8, thus the answer is "UP".In the second sample, the size of the moon on the next day will be 11, thus the answer is "DOWN".In the third sample, there is no way to determine whether the size of the moon on the next day will be 7 or 9, thus the answer is -1. | Input53 4 5 6 7 | OutputUP | 1 second | 256 megabytes | ['implementation', '*1100'] |
E. Matvey's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday is Matvey's birthday. He never knows what to ask as a present so friends gave him a string s of length n. This string consists of only first eight English letters: 'a', 'b', ..., 'h'.First question that comes to mind is: who might ever need some string? Matvey is a special boy so he instantly found what to do with this string. He used it to build an undirected graph where vertices correspond to position in the string and there is an edge between distinct positions a and b (1ββ€βa,βbββ€βn) if at least one of the following conditions hold: a and b are neighbouring, i.e. |aβ-βb|β=β1. Positions a and b contain equal characters, i.e. saβ=βsb. Then Matvey decided to find the diameter of this graph. Diameter is a maximum distance (length of the shortest path) among all pairs of vertices. Also, Matvey wants to find the number of pairs of vertices such that the distance between them is equal to the diameter of the graph. As he is very cool and experienced programmer he managed to solve this problem very fast. Will you do the same?InputThe first line of the input contains a single integer n (2ββ€βnββ€β100β000)Β β the length of the string.The second line contains the string s itself. It's guaranteed that s consists of only first eight letters of English alphabet.OutputPrint two integersΒ β the diameter of the graph and the number of pairs of positions with the distance equal to the diameter.ExamplesInput3abcOutput2 1Input7aaabaaaOutput2 4NoteConsider the second sample. The maximum distance is 2. It's obtained for pairs (1,β4), (2,β4), (4,β6) and (4,β7). | Input3abc | Output2 1 | 2 seconds | 256 megabytes | ['bitmasks', 'graphs', '*3300'] |
D. Andrew and Chemistrytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the chemistry lesson Andrew learned that the saturated hydrocarbons (alkanes) enter into radical chlorination reaction. Andrew is a very curious boy, so he wondered how many different products of the reaction may be forms for a given alkane. He managed to solve the task for small molecules, but for large ones he faced some difficulties and asks you to help.Formally, you are given a tree consisting of n vertices, such that the degree of each vertex doesn't exceed 4. You have to count the number of distinct non-isomorphic trees that can be obtained by adding to this tree one new vertex and one new edge, such that the graph is still the tree and the degree of each vertex doesn't exceed 4.Two trees are isomorphic if there exists a bijection f(v) such that vertices u and v are connected by an edge if and only if vertices f(v) and f(u) are connected by an edge.InputThe first line of the input contains an integer n (1ββ€βnββ€β100β000)Β β the number of vertices in the tree.Then follow nβ-β1 lines with edges descriptions. Each edge is given by two integers ui and vi (1ββ€βui,βviββ€βn)Β β indices of vertices connected by an edge. It's guaranteed that the given graph is a tree and the degree of each vertex doesn't exceed 4.OutputPrint one integerΒ β the answer to the question.ExamplesInput41 22 32 4Output2Input51 21 31 41 5Output1Input52 55 34 34 1Output3NoteIn the first sample, one can add new vertex to any existing vertex, but the trees we obtain by adding a new vertex to vertices 1, 3 and 4 are isomorphic, thus the answer is 2.In the second sample, one can't add new vertex to the first vertex, as its degree is already equal to four. Trees, obtained by adding a new vertex to vertices 2, 3, 4 and 5 are isomorphic, thus the answer is 1. | Input41 22 32 4 | Output2 | 2 seconds | 256 megabytes | ['dp', 'hashing', 'trees', '*2900'] |
C. Sasha and Arraytime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha has an array of integers a1,βa2,β...,βan. You have to perform m queries. There might be queries of two types: 1 l r xΒ β increase all integers on the segment from l to r by values x; 2 l rΒ β find , where f(x) is the x-th Fibonacci number. As this number may be large, you only have to find it modulo 109β+β7. In this problem we define Fibonacci numbers as follows: f(1)β=β1, f(2)β=β1, f(x)β=βf(xβ-β1)β+βf(xβ-β2) for all xβ>β2.Sasha is a very talented boy and he managed to perform all queries in five seconds. Will you be able to write the program that performs as well as Sasha?InputThe first line of the input contains two integers n and m (1ββ€βnββ€β100β000, 1ββ€βmββ€β100β000)Β β the number of elements in the array and the number of queries respectively.The next line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109).Then follow m lines with queries descriptions. Each of them contains integers tpi, li, ri and may be xi (1ββ€βtpiββ€β2, 1ββ€βliββ€βriββ€βn, 1ββ€βxiββ€β109). Here tpiβ=β1 corresponds to the queries of the first type and tpi corresponds to the queries of the second type.It's guaranteed that the input will contains at least one query of the second type.OutputFor each query of the second type print the answer modulo 109β+β7.ExamplesInput5 41 1 2 1 12 1 51 2 4 22 2 42 1 5Output579NoteInitially, array a is equal to 1, 1, 2, 1, 1.The answer for the first query of the second type is f(1)β+βf(1)β+βf(2)β+βf(1)β+βf(1)β=β1β+β1β+β1β+β1β+β1β=β5. After the query 1 2 4 2 array a is equal to 1, 3, 4, 3, 1.The answer for the second query of the second type is f(3)β+βf(4)β+βf(3)β=β2β+β3β+β2β=β7.The answer for the third query of the second type is f(1)β+βf(3)β+βf(4)β+βf(3)β+βf(1)β=β1β+β2β+β3β+β2β+β1β=β9. | Input5 41 1 2 1 12 1 51 2 4 22 2 42 1 5 | Output579 | 5 seconds | 256 megabytes | ['data structures', 'math', 'matrices', '*2300'] |
A. Efim and Strange Gradetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEfim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit nβ+β1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the nβ+β1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.InputThe first line of the input contains two integers n and t (1ββ€βnββ€β200β000, 1ββ€βtββ€β109)Β β the length of Efim's grade and the number of seconds till the end of the break respectively.The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.OutputPrint the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.ExamplesInput6 110.245Output10.25Input6 210.245Output10.3Input3 1009.2Output9.2NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all. | Input6 110.245 | Output10.25 | 1 second | 256 megabytes | ['dp', 'implementation', 'math', '*1700'] |
I. Cowboy Beblop at his computertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCowboy Beblop is a funny little boy who likes sitting at his computer. He somehow obtained two elastic hoops in the shape of 2D polygons, which are not necessarily convex. Since there's no gravity on his spaceship, the hoops are standing still in the air. Since the hoops are very elastic, Cowboy Beblop can stretch, rotate, translate or shorten their edges as much as he wants.For both hoops, you are given the number of their vertices, as well as the position of each vertex, defined by the X , Y and Z coordinates. The vertices are given in the order they're connected: the 1stβ―vertex is connected to the 2nd, which is connected to the 3rd, etc., and the last vertex is connected to the first one. Two hoops are connected if it's impossible to pull them to infinity in different directions by manipulating their edges, without having their edges or vertices intersect at any point β just like when two links of a chain are connected. The polygons' edges do not intersect or overlap. To make things easier, we say that two polygons are well-connected, if the edges of one polygon cross the area of the other polygon in two different directions (from the upper and lower sides of the plane defined by that polygon) a different number of times.Cowboy Beblop is fascinated with the hoops he has obtained and he would like to know whether they are well-connected or not. Since heβs busy playing with his dog, Zwei, heβd like you to figure it out for him. He promised you some sweets if you help him! InputThe first line of input contains an integer n (3ββ€βnββ€β100β000), which denotes the number of edges of the first polygon. The next N lines each contain the integers x, y and z (β-β1β000β000ββ€βx,βy,βzββ€β1β000β000)Β β coordinates of the vertices, in the manner mentioned above. The next line contains an integer m (3ββ€βmββ€β100β000) , denoting the number of edges of the second polygon, followed by m lines containing the coordinates of the second polygonβs vertices.It is guaranteed that both polygons are simple (no self-intersections), and in general that the obtained polygonal lines do not intersect each other. Also, you can assume that no 3 consecutive points of a polygon lie on the same line.OutputYour output should contain only one line, with the words "YES" or "NO", depending on whether the two given polygons are well-connected. ExampleInput40 0 02 0 02 2 00 2 041 1 -11 1 11 3 11 3 -1OutputYESNoteOn the picture below, the two polygons are well-connected, as the edges of the vertical polygon cross the area of the horizontal one exactly once in one direction (for example, from above to below), and zero times in the other (in this case, from below to above). Note that the polygons do not have to be parallel to any of the xy-,xz-,yz- planes in general. | Input40 0 02 0 02 2 00 2 041 1 -11 1 11 3 11 3 -1 | OutputYES | 1 second | 256 megabytes | ['geometry', '*2800'] |
H. Pokermon League challengetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWelcome to the world of Pokermon, yellow little mouse-like creatures, who absolutely love playing poker! Yeah, rightβ¦ In the ensuing Pokermon League, there are n registered Pokermon trainers, and t existing trainer teams each of which belongs to one of two conferences. Since there is a lot of jealousy between trainers, there are e pairs of trainers who hate each other. Their hate is mutual, there are no identical pairs among these, and no trainer hates himself (the world of Pokermon is a joyful place!). Each trainer has a wish-list of length li of teams heβd like to join.Your task is to divide players into teams and the teams into two conferences, so that: each trainer belongs to exactly one team; no team is in both conferences; total hate between conferences is at least eβ/β2; every trainer is in a team from his wish-list. Total hate between conferences is calculated as the number of pairs of trainers from teams from different conferences who hate each other. InputThe first line of the input contains two integer n (4ββ€βnββ€β50β000) and e (2ββ€βeββ€β100β000)Β β the total number of Pokermon trainers and the number of pairs of trainers who hate each other.Pokermon trainers are numbered from 1 to n. Next e lines contain two integers a and b (1ββ€βa,βbββ€βn) indicating that Pokermon trainers a and b hate each other. Next 2n lines are in a following format. Starting with Pokermon trainer 1, for each trainer in consecutive order: first number li (16ββ€βliββ€β20)Β β a size of Pokermon trainers wish list, then li positive integers ti,βj (1ββ€βti,βjββ€βT), providing the teams the i-th trainer would like to be on.Each trainers wish list will contain each team no more than once. Teams on the wish lists are numbered in such a way that the set of all teams that appear on at least 1 wish list is set of consecutive positive integers {1,β2,β3,ββ¦,βT}. Here T might be up to 1β000β000.OutputPrint two lines. The first line should contain n numbers, specifying for each trainer the team he is in.The second line should contain T numbers, specifying the conference for each team (1 or 2).ExampleInput4 31 22 34 1161 2 3 4 5 6 7 8 9 10 11 12 13 14 16 15162 3 4 5 6 7 8 9 10 11 12 13 14 15 17 18162 3 4 5 6 7 8 9 10 11 12 13 14 15 18 19161 2 3 4 5 6 7 8 9 10 11 12 13 14 16 19Output16 15 19 14 2 2 2 1 1 1 2 1 1 2 1 1 1 2 2 1 1 1 1 Note | Input4 31 22 34 1161 2 3 4 5 6 7 8 9 10 11 12 13 14 16 15162 3 4 5 6 7 8 9 10 11 12 13 14 15 17 18162 3 4 5 6 7 8 9 10 11 12 13 14 15 18 19161 2 3 4 5 6 7 8 9 10 11 12 13 14 16 19 | Output16 15 19 14 2 2 2 1 1 1 2 1 1 2 1 1 1 2 2 1 1 1 1 | 5 seconds | 256 megabytes | ['math', 'probabilities', '*2400'] |
G. Underfailtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have recently fallen through a hole and, after several hours of unconsciousness, have realized you are in an underground city. On one of your regular, daily walks through the unknown, you have encountered two unusually looking skeletons called Sanz and Pβpairus, who decided to accompany you and give you some puzzles for seemingly unknown reasons.One day, Sanz has created a crossword for you. Not any kind of crossword, but a 1D crossword! You are given m words and a string of length n. You are also given an array p, which designates how much each word is worthΒ β the i-th word is worth pi points. Whenever you find one of the m words in the string, you are given the corresponding number of points. Each position in the crossword can be used at most x times. A certain word can be counted at different places, but you cannot count the same appearance of a word multiple times. If a word is a substring of another word, you can count them both (presuming you havenβt used the positions more than x times).In order to solve the puzzle, you need to tell Sanz whatβs the maximum achievable number of points in the crossword. There is no need to cover all postions, just get the maximal score! Crossword and words contain only lowercase English letters.InputThe first line of the input contains a single integer n (1ββ€βnββ€β500)Β β the length of the crossword. The second line contains the crossword string. The third line contains a single integer m (1ββ€βmββ€β100)Β β the number of given words, and next m lines contain description of words: each line will have a string representing a non-empty word (its length doesn't exceed the length of the crossword) and integer pi (0ββ€βpiββ€β100). Last line of the input will contain x (1ββ€βxββ€β100)Β β maximum number of times a position in crossword can be used.OutputOutput single integerΒ β maximum number of points you can get.ExampleInput6abacba2aba 6ba 33Output12NoteFor example, with the string "abacba", words "aba" (6 points) and "ba" (3 points), and xβ=β3, you can get at most 12 points - the word "aba" appears once ("abacba"), while "ba" appears two times ("abacba"). Note that for xβ=β1, you could get at most 9 points, since you wouldnβt be able to count both "aba" and the first appearance of "ba". | Input6abacba2aba 6ba 33 | Output12 | 1 second | 256 megabytes | ['flows', '*2400'] |
F. Heroes of Making Magic IIItime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIβm strolling on sunshine, yeah-ah! And doesnβt it feel good! Well, it certainly feels good for our Heroes of Making Magic, who are casually walking on a one-directional road, fighting imps. Imps are weak and feeble creatures and they are not good at much. However, Heroes enjoy fighting them. For fun, if nothing else. Our Hero, Ignatius, simply adores imps. He is observing a line of imps, represented as a zero-indexed array of integers a of length n, where ai denotes the number of imps at the i-th position. Sometimes, imps can appear out of nowhere. When heroes fight imps, they select a segment of the line, start at one end of the segment, and finish on the other end, without ever exiting the segment. They can move exactly one cell left or right from their current position and when they do so, they defeat one imp on the cell that they moved to, so, the number of imps on that cell decreases by one. This also applies when heroes appear at one end of the segment, at the beginning of their walk. Their goal is to defeat all imps on the segment, without ever moving to an empty cell in it (without imps), since they would get bored. Since Ignatius loves imps, he doesnβt really want to fight them, so no imps are harmed during the events of this task. However, he would like you to tell him whether it would be possible for him to clear a certain segment of imps in the above mentioned way if he wanted to. You are given q queries, which have two types: 1 a b kΒ β denotes that k imps appear at each cell from the interval [a,βb] 2 a b - asks whether Ignatius could defeat all imps on the interval [a,βb] in the way described above InputThe first line contains a single integer n (1ββ€βnββ€β200β000), the length of the array a. The following line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β5β000), the initial number of imps in each cell. The third line contains a single integer q (1ββ€βqββ€β300β000), the number of queries. The remaining q lines contain one query each. Each query is provided by integers a, b and, possibly, k (0ββ€βaββ€βbβ<βn, 0ββ€βkββ€β5β000).OutputFor each second type of query output 1 if it is possible to clear the segment, and 0 if it is not.ExampleInput32 2 232 0 21 1 1 12 0 2Output01NoteFor the first query, one can easily check that it is indeed impossible to get from the first to the last cell while clearing everything. After we add 1 to the second position, we can clear the segment, for example by moving in the following way: . | Input32 2 232 0 21 1 1 12 0 2 | Output01 | 3 seconds | 256 megabytes | ['data structures', '*2600'] |
E. Paint it really, really dark graytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputI see a pink boar and I want it painted black. Black boars look much more awesome and mighty than the pink ones. Since Jaggy became the ruler of the forest, he has been trying his best to improve the diplomatic relations between the forest region and the nearby ones. Some other rulers, however, have requested too much in return for peace between their two regions, so he realized he has to resort to intimidation. Once a delegate for diplomatic relations of a neighboring region visits Jaggyβs forest, if they see a whole bunch of black boars, they might suddenly change their mind about attacking Jaggy. Black boars are really scary, after all. Jaggyβs forest can be represented as a tree (connected graph without cycles) with n vertices. Each vertex represents a boar and is colored either black or pink. Jaggy has sent a squirrel to travel through the forest and paint all the boars black. The squirrel, however, is quite unusually trained and while it traverses the graph, it changes the color of every vertex it visits, regardless of its initial color: pink vertices become black and black vertices become pink. Since Jaggy is too busy to plan the squirrelβs route, he needs your help. He wants you to construct a walk through the tree starting from vertex 1 such that in the end all vertices are black. A walk is a sequence of vertices, such that every consecutive pair has an edge between them in a tree.InputThe first line of input contains integer n (2ββ€βnββ€β200β000), denoting the number of vertices in the tree. The following n lines contains n integers, which represent the color of the nodes.If the i-th integer is 1, if the i-th vertex is black and β-β1 if the i-th vertex is pink.Each of the next nβ-β1 lines contains two integers, which represent the indexes of the vertices which are connected by the edge. Vertices are numbered starting with 1.OutputOutput path of a squirrel: output a sequence of visited nodes' indexes in order of visiting. In case of all the nodes are initially black, you should print 1. Solution is guaranteed to exist. If there are multiple solutions to the problem you can output any of them provided length of sequence is not longer than 107.ExampleInput511-11-12 54 32 44 1Output1 4 2 5 2 4 3 4 1 4 1NoteAt the beginning squirrel is at node 1 and its color is black. Next steps are as follows: From node 1 we walk to node 4 and change its color to pink. From node 4 we walk to node 2 and change its color to pink. From node 2 we walk to node 5 and change its color to black. From node 5 we return to node 2 and change its color to black. From node 2 we walk to node 4 and change its color to black. We visit node 3 and change its color to black. We visit node 4 and change its color to pink. We visit node 1 and change its color to pink. We visit node 4 and change its color to black. We visit node 1 and change its color to black. | Input511-11-12 54 32 44 1 | Output1 4 2 5 2 4 3 4 1 4 1 | 1 second | 256 megabytes | ['dfs and similar', '*1900'] |
D. Dexterinaβs Labtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDexterina and Womandark have been arch-rivals since theyβve known each other. Since both are super-intelligent teenage girls, theyβve always been trying to solve their disputes in a peaceful and nonviolent way. After god knows how many different challenges theyβve given to one another, their score is equal and theyβre both desperately trying to best the other in various games of wits. This time, Dexterina challenged Womandark to a game of Nim.Nim is a two-player game in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and may remove any number of objects from a single heap. The player who can't make a turn loses. By their agreement, the sizes of piles are selected randomly from the range [0,βx]. Each pile's size is taken independently from the same probability distribution that is known before the start of the game.Womandark is coming up with a brand new and evil idea on how to thwart Dexterinaβs plans, so she hasnβt got much spare time. She, however, offered you some tips on looking fabulous in exchange for helping her win in Nim. Your task is to tell her what is the probability that the first player to play wins, given the rules as above.InputThe first line of the input contains two integers n (1ββ€βnββ€β109) and x (1ββ€βxββ€β100)Β β the number of heaps and the maximum number of objects in a heap, respectively. The second line contains xβ+β1 real numbers, given with up to 6 decimal places each: P(0),βP(1),β... ,βP(X). Here, P(i) is the probability of a heap having exactly i objects in start of a game. It's guaranteed that the sum of all P(i) is equal to 1.OutputOutput a single real number, the probability that the first player wins. The answer will be judged as correct if it differs from the correct answer by at most 10β-β6.ExampleInput2 20.500000 0.250000 0.250000Output0.62500000 | Input2 20.500000 0.250000 0.250000 | Output0.62500000 | 1 second | 256 megabytes | ['games', 'matrices', 'probabilities', '*1900'] |
C. Potions Homeworktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHarry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each studentβs laziness level is equal to their taskβs difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the taskβs difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10β007.InputThe first line of input contains integer n (1ββ€βnββ€β100β000)Β β the number of tasks. The next n lines contain exactly one integer number ai (1ββ€βaiββ€β100β000)Β β both the difficulty of the initial task and the laziness of the i-th students.OutputPrint the minimum total time to finish all tasks modulo 10β007.ExampleInput213Output6NoteIn the first sample, if the students switch their tasks, they will be able to finish them in 3β+β3β=β6 time units. | Input213 | Output6 | 1 second | 256 megabytes | ['implementation', 'sortings', '*1200'] |
B. R3D3βs Summer Adventuretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputR3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met another robot for whom he was sure is the love of his life. Well, his summer, at least. Anyway, R3D3 was too shy to approach his potential soulmate, so he decided to write her a love letter. However, he stumbled upon a problem. Due to a terrorist threat, the Intergalactic Space Police was monitoring all letters sent in the area. Thus, R3D3 decided to invent his own alphabet, for which he was sure his love would be able to decipher.There are n letters in R3D3βs alphabet, and he wants to represent each letter as a sequence of '0' and '1', so that no letterβs sequence is a prefix of another letter's sequence. Since the Intergalactic Space Communications Service has lately introduced a tax for invented alphabets, R3D3 must pay a certain amount of money for each bit in his alphabetβs code (check the sample test for clarifications). He is too lovestruck to think clearly, so he asked you for help.Given the costs c0 and c1 for each '0' and '1' in R3D3βs alphabet, respectively, you should come up with a coding for the alphabet (with properties as above) with minimum total cost.InputThe first line of input contains three integers n (2ββ€βnββ€β108), c0 and c1 (0ββ€βc0,βc1ββ€β108)Β β the number of letters in the alphabet, and costs of '0' and '1', respectively. OutputOutput a single integerΒ β minimum possible total a cost of the whole alphabet.ExampleInput4 1 2Output12NoteThere are 4 letters in the alphabet. The optimal encoding is "00", "01", "10", "11". There are 4 zeroes and 4 ones used, so the total cost is 4Β·1β+β4Β·2β=β12. | Input4 1 2 | Output12 | 1 second | 256 megabytes | ['dp', 'greedy', '*2700'] |
A. Festival Organizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Prodiggers are quite a cool band and for this reason, they have been the surprise guest at the ENTER festival for the past 80 years. At the beginning of their careers, they werenβt so successful, so they had to spend time digging channels to earn money; hence the name. Anyway, they like to tour a lot and have surprising amounts of energy to do extremely long tours. However, they hate spending two consecutive days without having a concert, so they would like to avoid it.A tour is defined by a sequence of concerts and days-off. You need to count in how many ways The Prodiggers can select k different tours of the same length between l and r.For example if kβ=β2, lβ=β1 and rβ=β2, if we define concert day as {1} and day-off as {0}, here are all possible tours: {0}, {1}, {00}, {01}, {10}, {11}. But tour 00 can not be selected because it has 2 days-off in a row. Now, we need to count in how many ways we can select kβ=β2 tours of the same length in range [1;2]. Here they are: {0,1}; {01,10}; {01,11}; {10,11}.Since their schedule is quite busy, they want you to tell them in how many ways can do that, modulo 1β000β000β007 (109β+β7).InputThe first line of the input contains three integers k, l and r (1ββ€βkββ€β200, 1ββ€βlββ€βrββ€β1018).OutputOutput a single number: the number of ways to select k different tours of the same length, modulo 1β000β000β007.ExampleInput1 1 2Output5 | Input1 1 2 | Output5 | 1 second | 256 megabytes | ['combinatorics', 'math', 'number theory', '*2900'] |
B. Complete the Wordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not nice.Now, ZS the Coder tells you a word, where some of its letters are missing as he forgot them. He wants to determine if it is possible to fill in the missing letters so that the resulting word is nice. If it is possible, he needs you to find an example of such a word as well. Can you help him?InputThe first and only line of the input contains a single string s (1ββ€β|s|ββ€β50β000), the word that ZS the Coder remembers. Each character of the string is the uppercase letter of English alphabet ('A'-'Z') or is a question mark ('?'), where the question marks denotes the letters that ZS the Coder can't remember.OutputIf there is no way to replace all the question marks with uppercase letters such that the resulting word is nice, then print β-β1 in the only line.Otherwise, print a string which denotes a possible nice word that ZS the Coder learned. This string should match the string from the input, except for the question marks replaced with uppercase English letters.If there are multiple solutions, you may print any of them.ExamplesInputABC??FGHIJK???OPQR?TUVWXY?OutputABCDEFGHIJKLMNOPQRZTUVWXYSInputWELCOMETOCODEFORCESROUNDTHREEHUNDREDANDSEVENTYTWOOutput-1Input??????????????????????????OutputMNBVCXZLKJHGFDSAQPWOEIRUYTInputAABCDEFGHIJKLMNOPQRSTUVW??MOutput-1NoteIn the first sample case, ABCDEFGHIJKLMNOPQRZTUVWXYS is a valid answer beacuse it contains a substring of length 26 (the whole string in this case) which contains all the letters of the English alphabet exactly once. Note that there are many possible solutions, such as ABCDEFGHIJKLMNOPQRSTUVWXYZ or ABCEDFGHIJKLMNOPQRZTUVWXYS.In the second sample case, there are no missing letters. In addition, the given string does not have a substring of length 26 that contains all the letters of the alphabet, so the answer is β-β1.In the third sample case, any string of length 26 that contains all letters of the English alphabet fits as an answer. | InputABC??FGHIJK???OPQR?TUVWXY? | OutputABCDEFGHIJKLMNOPQRZTUVWXYS | 2 seconds | 256 megabytes | ['greedy', 'two pointers', '*1300'] |
A. Crazy Computertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if bβ-βaββ€βc, just the new word is appended to other words on the screen. If bβ-βaβ>βc, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if cβ=β5 and you typed words at seconds 1,β3,β8,β14,β19,β20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.InputThe first line contains two integers n and c (1ββ€βnββ€β100β000,β1ββ€βcββ€β109)Β β the number of words ZS the Coder typed and the crazy computer delay respectively.The next line contains n integers t1,βt2,β...,βtn (1ββ€βt1β<βt2β<β...β<βtnββ€β109), where ti denotes the second when ZS the Coder typed the i-th word.OutputPrint a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.ExamplesInput6 51 3 8 14 19 20Output3Input6 11 3 5 7 9 10Output2NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3β-β1β>β1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10β-β9ββ€β1. | Input6 51 3 8 14 19 20 | Output3 | 2 seconds | 256 megabytes | ['implementation', '*800'] |
E. Complete the Permutationstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder is given two permutations p and q of {1,β2,β...,βn}, but some of their elements are replaced with 0. The distance between two permutations p and q is defined as the minimum number of moves required to turn p into q. A move consists of swapping exactly 2 elements of p.ZS the Coder wants to determine the number of ways to replace the zeros with positive integers from the set {1,β2,β...,βn} such that p and q are permutations of {1,β2,β...,βn} and the distance between p and q is exactly k.ZS the Coder wants to find the answer for all 0ββ€βkββ€βnβ-β1. Can you help him?InputThe first line of the input contains a single integer n (1ββ€βnββ€β250)Β β the number of elements in the permutations.The second line contains n integers, p1,βp2,β...,βpn (0ββ€βpiββ€βn)Β β the permutation p. It is guaranteed that there is at least one way to replace zeros such that p is a permutation of {1,β2,β...,βn}.The third line contains n integers, q1,βq2,β...,βqn (0ββ€βqiββ€βn)Β β the permutation q. It is guaranteed that there is at least one way to replace zeros such that q is a permutation of {1,β2,β...,βn}.OutputPrint n integers, i-th of them should denote the answer for kβ=βiβ-β1. Since the answer may be quite large, and ZS the Coder loves weird primes, print them modulo 998244353β=β223Β·7Β·17β+β1, which is a prime.ExamplesInput31 0 00 2 0Output1 2 1 Input41 0 0 30 0 0 4Output0 2 6 4 Input61 3 2 5 4 66 4 5 1 0 0Output0 0 0 0 1 1 Input41 2 3 42 3 4 1Output0 0 0 1 NoteIn the first sample case, there is the only way to replace zeros so that it takes 0 swaps to convert p into q, namely pβ=β(1,β2,β3),βqβ=β(1,β2,β3).There are two ways to replace zeros so that it takes 1 swap to turn p into q. One of these ways is pβ=β(1,β2,β3),βqβ=β(3,β2,β1), then swapping 1 and 3 from p transform it into q. The other way is pβ=β(1,β3,β2),βqβ=β(1,β2,β3). Swapping 2 and 3 works in this case.Finally, there is one way to replace zeros so that it takes 2 swaps to turn p into q, namely pβ=β(1,β3,β2),βqβ=β(3,β2,β1). Then, we can transform p into q like following: . | Input31 0 00 2 0 | Output1 2 1 | 5 seconds | 256 megabytes | ['combinatorics', 'fft', 'graphs', 'math', '*3400'] |
D. Create a Mazetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder loves mazes. Your job is to create one so that he can play with it. A maze consists of nβΓβm rooms, and the rooms are arranged in n rows (numbered from the top to the bottom starting from 1) and m columns (numbered from the left to the right starting from 1). The room in the i-th row and j-th column is denoted by (i,βj). A player starts in the room (1,β1) and wants to reach the room (n,βm).Each room has four doors (except for ones at the maze border), one on each of its walls, and two adjacent by the wall rooms shares the same door. Some of the doors are locked, which means it is impossible to pass through the door. For example, if the door connecting (i,βj) and (i,βjβ+β1) is locked, then we can't go from (i,βj) to (i,βjβ+β1). Also, one can only travel between the rooms downwards (from the room (i,βj) to the room (iβ+β1,βj)) or rightwards (from the room (i,βj) to the room (i,βjβ+β1)) provided the corresponding door is not locked. This image represents a maze with some doors locked. The colored arrows denotes all the possible paths while a red cross denotes a locked door. ZS the Coder considers a maze to have difficulty x if there is exactly x ways of travelling from the room (1,β1) to the room (n,βm). Two ways are considered different if they differ by the sequence of rooms visited while travelling.Your task is to create a maze such that its difficulty is exactly equal to T. In addition, ZS the Coder doesn't like large mazes, so the size of the maze and the number of locked doors are limited. Sounds simple enough, right?InputThe first and only line of the input contains a single integer T (1ββ€βTββ€β1018), the difficulty of the required maze.OutputThe first line should contain two integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the maze respectively.The next line should contain a single integer k (0ββ€βkββ€β300)Β β the number of locked doors in the maze.Then, k lines describing locked doors should follow. Each of them should contain four integers, x1,βy1,βx2,βy2. This means that the door connecting room (x1,βy1) and room (x2,βy2) is locked. Note that room (x2,βy2) should be adjacent either to the right or to the bottom of (x1,βy1), i.e. x2β+βy2 should be equal to x1β+βy1β+β1. There should not be a locked door that appears twice in the list.It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them.ExamplesInput3Output3 20Input4Output4 331 2 2 23 2 3 31 3 2 3NoteHere are how the sample input and output looks like. The colored arrows denotes all the possible paths while a red cross denotes a locked door.In the first sample case: In the second sample case: | Input3 | Output3 20 | 2 seconds | 256 megabytes | ['constructive algorithms', '*3100'] |
C. Digit Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder has a large tree. It can be represented as an undirected connected graph of n vertices numbered from 0 to nβ-β1 and nβ-β1 edges between them. There is a single nonzero digit written on each edge.One day, ZS the Coder was bored and decided to investigate some properties of the tree. He chose a positive integer M, which is coprime to 10, i.e. .ZS consider an ordered pair of distinct vertices (u,βv) interesting when if he would follow the shortest path from vertex u to vertex v and write down all the digits he encounters on his path in the same order, he will get a decimal representaion of an integer divisible by M.Formally, ZS consider an ordered pair of distinct vertices (u,βv) interesting if the following states true: Let a1β=βu,βa2,β...,βakβ=βv be the sequence of vertices on the shortest path from u to v in the order of encountering them; Let di (1ββ€βiβ<βk) be the digit written on the edge between vertices ai and aiβ+β1; The integer is divisible by M. Help ZS the Coder find the number of interesting pairs!InputThe first line of the input contains two integers, n and M (2ββ€βnββ€β100β000,β1ββ€βMββ€β109, )Β β the number of vertices and the number ZS has chosen respectively.The next nβ-β1 lines contain three integers each. i-th of them contains ui,βvi and wi, denoting an edge between vertices ui and vi with digit wi written on it (0ββ€βui,βviβ<βn,ββ1ββ€βwiββ€β9).OutputPrint a single integerΒ β the number of interesting (by ZS the Coder's consideration) pairs.ExamplesInput6 70 1 24 2 42 0 13 0 92 5 7Output7Input5 111 2 32 0 33 0 34 3 3Output8NoteIn the first sample case, the interesting pairs are (0,β4),β(1,β2),β(1,β5),β(3,β2),β(2,β5),β(5,β2),β(3,β5). The numbers that are formed by these pairs are 14,β21,β217,β91,β7,β7,β917 respectively, which are all multiples of 7. Note that (2,β5) and (5,β2) are considered different. In the second sample case, the interesting pairs are (4,β0),β(0,β4),β(3,β2),β(2,β3),β(0,β1),β(1,β0),β(4,β1),β(1,β4), and 6 of these pairs give the number 33 while 2 of them give the number 3333, which are all multiples of 11. | Input6 70 1 24 2 42 0 13 0 92 5 7 | Output7 | 3 seconds | 256 megabytes | ['dfs and similar', 'divide and conquer', 'dsu', 'trees', '*2700'] |
B. Complete The Graphtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder has drawn an undirected graph of n vertices numbered from 0 to nβ-β1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him?InputThe first line contains five integers n,βm,βL,βs,βt (2ββ€βnββ€β1000,ββ1ββ€βmββ€β10β000,ββ1ββ€βLββ€β109,ββ0ββ€βs,βtββ€βnβ-β1,ββsββ βt)Β β the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively.Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui,βvi,βwi (0ββ€βui,βviββ€βnβ-β1,ββuiββ βvi,ββ0ββ€βwiββ€β109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased.It is guaranteed that there is at most one edge between any pair of vertices.OutputPrint "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way.Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018. The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L.If there are multiple solutions, print any of them.ExamplesInput5 5 13 0 40 1 52 1 23 2 31 4 04 3 4OutputYES0 1 52 1 23 2 31 4 84 3 4Input2 1 123456789 0 10 1 0OutputYES0 1 123456789Input2 1 999999999 1 00 1 1000000000OutputNONoteHere's how the graph in the first sample case looks like : In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13.In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789.In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO". | Input5 5 13 0 40 1 52 1 23 2 31 4 04 3 4 | OutputYES0 1 52 1 23 2 31 4 84 3 4 | 4 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'graphs', 'shortest paths', '*2300'] |
A. Plus and Square Roottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, 'β+β' (plus) and '' (square root). Initially, the number 2 is displayed on the screen. There are nβ+β1 levels in the game and ZS the Coder start at the level 1.When ZS the Coder is at level k, he can : Press the 'β+β' button. This increases the number on the screen by exactly k. So, if the number on the screen was x, it becomes xβ+βk. Press the '' button. Let the number on the screen be x. After pressing this button, the number becomes . After that, ZS the Coder levels up, so his current level becomes kβ+β1. This button can only be pressed when x is a perfect square, i.e. xβ=βm2 for some positive integer m. Additionally, after each move, if ZS the Coder is at level k, and the number on the screen is m, then m must be a multiple of k. Note that this condition is only checked after performing the press. For example, if ZS the Coder is at level 4 and current number is 100, he presses the '' button and the number turns into 10. Note that at this moment, 10 is not divisible by 4, but this press is still valid, because after it, ZS the Coder is at level 5, and 10 is divisible by 5.ZS the Coder needs your help in beating the gameΒ β he wants to reach level nβ+β1. In other words, he needs to press the '' button n times. Help him determine the number of times he should press the 'β+β' button before pressing the '' button at each level. Please note that ZS the Coder wants to find just any sequence of presses allowing him to reach level nβ+β1, but not necessarily a sequence minimizing the number of presses.InputThe first and only line of the input contains a single integer n (1ββ€βnββ€β100β000), denoting that ZS the Coder wants to reach level nβ+β1.OutputPrint n non-negative integers, one per line. i-th of them should be equal to the number of times that ZS the Coder needs to press the 'β+β' button before pressing the '' button at level i. Each number in the output should not exceed 1018. However, the number on the screen can be greater than 1018.It is guaranteed that at least one solution exists. If there are multiple solutions, print any of them.ExamplesInput3Output141646Input2Output99999999999999999844500000000Input4Output2174697NoteIn the first sample case:On the first level, ZS the Coder pressed the 'β+β' button 14 times (and the number on screen is initially 2), so the number became 2β+β14Β·1β=β16. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the 'β+β' button 16 times, so the number becomes 4β+β16Β·2β=β36. Then, ZS pressed the '' button, levelling up and changing the number into .After that, on the third level, ZS pressed the 'β+β' button 46 times, so the number becomes 6β+β46Β·3β=β144. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 12 is indeed divisible by 4, so ZS the Coder can reach level 4.Also, note that pressing the 'β+β' button 10 times on the third level before levelling up does not work, because the number becomes 6β+β10Β·3β=β36, and when the '' button is pressed, the number becomes and ZS the Coder is at Level 4. However, 6 is not divisible by 4 now, so this is not a valid solution.In the second sample case:On the first level, ZS the Coder pressed the 'β+β' button 999999999999999998 times (and the number on screen is initially 2), so the number became 2β+β999999999999999998Β·1β=β1018. Then, ZS the Coder pressed the '' button, and the number became . After that, on the second level, ZS pressed the 'β+β' button 44500000000 times, so the number becomes 109β+β44500000000Β·2β=β9Β·1010. Then, ZS pressed the '' button, levelling up and changing the number into . Note that 300000 is a multiple of 3, so ZS the Coder can reach level 3. | Input3 | Output141646 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*1600'] |
B. Filya and Homeworktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help.Filya is given an array of non-negative integers a1,βa2,β...,βan. First, he pick an integer x and then he adds x to some elements of the array (no more than once), subtract x from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal.Now he wonders if it's possible to pick such integer x and change some elements of the array using this x in order to make all elements equal.InputThe first line of the input contains an integer n (1ββ€βnββ€β100β000)Β β the number of integers in the Filya's array. The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β109)Β β elements of the array.OutputIf it's impossible to make all elements of the array equal using the process given in the problem statement, then print "NO" (without quotes) in the only line of the output. Otherwise print "YES" (without quotes).ExamplesInput51 3 3 2 1OutputYESInput51 2 3 4 5OutputNONoteIn the first sample Filya should select xβ=β1, then add it to the first and the last elements of the array and subtract from the second and the third elements. | Input51 3 3 2 1 | OutputYES | 1 second | 256 megabytes | ['implementation', 'sortings', '*1200'] |
A. Meeting of Old Friendstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday an outstanding event is going to happen in the forestΒ β hedgehog Filya will come to his old fried Sonya!Sonya is an owl and she sleeps during the day and stay awake from minute l1 to minute r1 inclusive. Also, during the minute k she prinks and is unavailable for Filya.Filya works a lot and he plans to visit Sonya from minute l2 to minute r2 inclusive.Calculate the number of minutes they will be able to spend together.InputThe only line of the input contains integers l1, r1, l2, r2 and k (1ββ€βl1,βr1,βl2,βr2,βkββ€β1018, l1ββ€βr1, l2ββ€βr2), providing the segments of time for Sonya and Filya and the moment of time when Sonya prinks.OutputPrint one integerΒ β the number of minutes Sonya and Filya will be able to spend together.ExamplesInput1 10 9 20 1Output2Input1 100 50 200 75Output50NoteIn the first sample, they will be together during minutes 9 and 10.In the second sample, they will be together from minute 50 to minute 74 and from minute 76 to minute 100. | Input1 10 9 20 1 | Output2 | 1 second | 256 megabytes | ['implementation', 'math', '*1100'] |
E. Sonya Partymakertime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOwl Sonya decided to become a partymaker. To train for this role she gather all her owl friends in the country house. There are m chairs located in a circle and consequently numbered with integers from 1 to m. Thus, chairs i and iβ+β1 are neighbouring for all i from 1 to mβ-β1. Chairs 1 and m are also neighbouring. Some chairs are occupied by her friends. There are n friends in total. No two friends occupy the same chair. Rules are the following: Each participant removes from the game the chair he is currently sitting on. Each of the participants choose a direction that she will follow: clockwise (indices increase, from m goes to 1) and counter-clockwise (indices decrease, from 1 goes to m). This direction may coincide or be different for any pair of owls. Each turn all guests move one step in the chosen directions. If some guest move to the position with a chair there, he removes this chair from the game. Game ends if there are no more chairs left in the game. Owls are very busy and want to get rid of the game as soon as possible. They cooperate to pick the direction. Your goal is to find the minimum number o moves required to finish the game.InputThe first line of the input contains a single integer m (1ββ€βmββ€β109)Β β the length of the circle.The second line contains a single integer n (1ββ€βnββ€β100β000)Β β the number of friends.Last line contains an increasing sequence of n integers ai (1ββ€βaiββ€βm)Β β initial positions of all owls.OutputPrint the minimum number of move required to finish the game. Note, that 0 also may be an answer.ExamplesInput631 3 5Output1Input621 6Output2Input40661 2 3 204 205 206Output100NoteIn the first sample, it's possible if all owls will move clockwise, i.e. in the direction of increasing indices.In the sample, first owl has to move clockwise, while the secondΒ β counterclockwise.In the third sample, the first and the fourth owls should move counterclockwise, while the third and the sixthΒ β clockwise. The second and the firth may move in any direction. | Input631 3 5 | Output1 | 1.5 seconds | 256 megabytes | ['binary search', 'dp', '*3300'] |
D. Animals and Puzzletime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOwl Sonya gave a huge lake puzzle of size nβΓβm to hedgehog Filya as a birthday present. Friends immediately started to assemble the puzzle, but some parts of it turned out to be emptyΒ β there was no picture on them. Parts with picture on it are denoted by 1, while empty parts are denoted by 0. Rows of the puzzle are numbered from top to bottom with integers from 1 to n, while columns are numbered from left to right with integers from 1 to m.Animals decided to complete the picture and play with it, as it might be even more fun! Owl and hedgehog ask each other some queries. Each query is provided by four integers x1, y1, x2, y2 which define the rectangle, where (x1,βy1) stands for the coordinates of the up left cell of the rectangle, while (x2,βy2) stands for the coordinates of the bottom right cell. The answer to the query is the size of the maximum square consisting of picture parts only (only parts denoted by 1) and located fully inside the query rectangle.Help Sonya and Filya answer t queries.InputThe first line of the input contains two integers n and m (1ββ€βn,βmββ€β1000)Β β sizes of the puzzle.Each of the following n lines contains m integers aij. Each of them is equal to 1 if the corresponding cell contains a picture and 0 if it's empty.Next line contains an integer t (1ββ€βtββ€β1β000β000)Β β the number of queries.Then follow t lines with queries' descriptions. Each of them contains four integers x1, y1, x2, y2 (1ββ€βx1ββ€βx2ββ€βn, 1ββ€βy1ββ€βy2ββ€βm)Β β coordinates of the up left and bottom right cells of the query rectangle.OutputPrint t lines. The i-th of them should contain the maximum size of the square consisting of 1-s and lying fully inside the query rectangle.ExampleInput3 41 1 0 10 1 1 00 1 1 051 1 2 32 1 3 23 2 3 41 1 3 41 2 3 4Output11122 | Input3 41 1 0 10 1 1 00 1 1 051 1 2 32 1 3 23 2 3 41 1 3 41 2 3 4 | Output11122 | 5 seconds | 512 megabytes | ['binary search', 'data structures', '*2700'] |
C. Sonya and Problem Wihtout a Legendtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSonya was unable to think of a story for this problem, so here comes the formal description.You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operations. You are allowed to change elements in any way, they can become negative or equal to 0.InputThe first line of the input contains a single integer n (1ββ€βnββ€β3000)Β β the length of the array.Next line contains n integer ai (1ββ€βaiββ€β109).OutputPrint the minimum number of operation required to make the array strictly increasing.ExamplesInput72 1 5 11 5 9 11Output9Input55 4 3 2 1Output12NoteIn the first sample, the array is going to look as follows:2 3 5 6 7 9 11|2β-β2|β+β|1β-β3|β+β|5β-β5|β+β|11β-β6|β+β|5β-β7|β+β|9β-β9|β+β|11β-β11|β=β9And for the second sample:1 2 3 4 5|5β-β1|β+β|4β-β2|β+β|3β-β3|β+β|2β-β4|β+β|1β-β5|β=β12 | Input72 1 5 11 5 9 11 | Output9 | 5 seconds | 256 megabytes | ['dp', 'sortings', '*2300'] |
B. Searching Rectanglestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFilya just learned new geometry objectΒ β rectangle. He is given a field consisting of nβΓβn unit cells. Rows are numbered from bottom to top with integer from 1 to n. Columns are numbered from left to right with integers from 1 to n. Cell, located at the intersection of the row r and column c is denoted as (r,βc). Filya has painted two rectangles, such that their sides are parallel to coordinate axes and each cell lies fully inside or fully outside each of them. Moreover, no cell lies in both rectangles.Later, hedgehog Filya became interested in the location of his rectangles but was unable to find the sheet of paper they were painted on. They were taken by Sonya and now she wants to play a little game with Filya. He tells her a query rectangle and she replies with the number of initial rectangles that lie fully inside the given query rectangle. The query rectangle should match the same conditions as initial rectangles. Rectangle lies fully inside the query if each o its cells lies inside the query.Filya knows Sonya really well, so is sure that if he asks more than 200 questions she will stop to reply.InputThe first line of the input contains an integer n (2ββ€βnββ€β216)Β β size of the field.For each query an integer between 0 and 2 is returnedΒ β the number of initial rectangles that lie fully inside the query rectangle.OutputTo make a query you have to print "? x1 y1 x2 y2" (without quotes) (1ββ€βx1ββ€βx2ββ€βn, 1ββ€βy1ββ€βy2ββ€βn), where (x1,βy1) stands for the position of the bottom left cell of the query and (x2,βy2) stands for the up right cell of the query. You are allowed to ask no more than 200 queries. After each query you should perform "flush" operation and read the answer.In case you suppose you've already determined the location of two rectangles (or run out of queries) you should print "! x11 y11 x12 y12 x21 y21 x22 y22" (without quotes), where first four integers describe the bottom left and up right cells of the first rectangle, and following four describe the corresponding cells of the second rectangle. You can print the rectangles in an arbitrary order. After you have printed the answer, print the end of the line and perform "flush". Your program should terminate immediately after it print the answer.InteractionTo flush you can use (just after printing an integer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. You will get the Wrong Answer verdict if you ask more than 200 queries, or if you print an incorrect coordinates.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).Hacking.The first line should contain an integer n (2ββ€βnββ€β216).The second line should contain four integers x1, y1, x2, y2 (1ββ€βx1ββ€βx2ββ€βn, 1ββ€βy1ββ€βy2ββ€βn)Β β the description of the first rectangle.The third line contains the description of the second rectangle in the similar way.ExampleInput521011101Output? 1 1 5 5? 1 1 3 3? 1 1 3 1? 2 2 2 2? 3 3 5 5? 3 3 3 5? 3 3 3 4? 3 4 3 5! 2 2 2 2 3 4 3 5 | Input521011101 | Output? 1 1 5 5? 1 1 3 3? 1 1 3 1? 2 2 2 2? 3 3 5 5? 3 3 3 5? 3 3 3 4? 3 4 3 5! 2 2 2 2 3 4 3 5 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'interactive', '*2200'] |
A. Sonya and Queriestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type: β+β aiΒ β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occurrences of the same integer. β-β aiΒ β delete a single occurrence of non-negative integer ai from the multiset. It's guaranteed, that there is at least one ai in the multiset. ? sΒ β count the number of integers in the multiset (with repetitions) that match some pattern s consisting of 0 and 1. In the pattern, 0 stands for the even digits, while 1 stands for the odd. Integer x matches the pattern s, if the parity of the i-th from the right digit in decimal notation matches the i-th from the right digit of the pattern. If the pattern is shorter than this integer, it's supplemented with 0-s from the left. Similarly, if the integer is shorter than the pattern its decimal notation is supplemented with the 0-s from the left. For example, if the pattern is sβ=β010, than integers 92, 2212, 50 and 414 match the pattern, while integers 3, 110, 25 and 1030 do not.InputThe first line of the input contains an integer t (1ββ€βtββ€β100β000)Β β the number of operation Sonya has to perform.Next t lines provide the descriptions of the queries in order they appear in the input file. The i-th row starts with a character ciΒ β the type of the corresponding operation. If ci is equal to '+' or '-' then it's followed by a space and an integer ai (0ββ€βaiβ<β1018) given without leading zeroes (unless it's 0). If ci equals '?' then it's followed by a space and a sequence of zeroes and onse, giving the pattern of length no more than 18.It's guaranteed that there will be at least one query of type '?'.It's guaranteed that any time some integer is removed from the multiset, there will be at least one occurrence of this integer in it.OutputFor each query of the third type print the number of integers matching the given pattern. Each integer is counted as many times, as it appears in the multiset at this moment of time.ExamplesInput12+ 1+ 241? 1+ 361- 241? 0101+ 101? 101- 101? 101+ 4000? 0Output21211Input4+ 200+ 200- 200? 0Output1NoteConsider the integers matching the patterns from the queries of the third type. Queries are numbered in the order they appear in the input. 1 and 241. 361. 101 and 361. 361. 4000. | Input12+ 1+ 241? 1+ 361- 241? 0101+ 101? 101- 101? 101+ 4000? 0 | Output21211 | 1 second | 256 megabytes | ['data structures', 'implementation', '*1400'] |
E. Memory and Casinostime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n casinos lined in a row. If Memory plays at casino i, he has probability pi to win and move to the casino on the right (iβ+β1) or exit the row (if iβ=βn), and a probability 1β-βpi to lose and move to the casino on the left (iβ-β1) or also exit the row (if iβ=β1). We say that Memory dominates on the interval i... j if he completes a walk such that, He starts on casino i. He never looses in casino i. He finishes his walk by winning in casino j. Note that Memory can still walk left of the 1-st casino and right of the casino n and that always finishes the process.Now Memory has some requests, in one of the following forms: 1 i a b: Set . 2 l r: Print the probability that Memory will dominate on the interval l... r, i.e. compute the probability that Memory will first leave the segment l... r after winning at casino r, if she starts in casino l. It is guaranteed that at any moment of time p is a non-decreasing sequence, i.e. piββ€βpiβ+β1 for all i from 1 to nβ-β1.Please help Memory by answering all his requests!InputThe first line of the input contains two integers n and q(1ββ€βn,βqββ€β100β000), Β β number of casinos and number of requests respectively.The next n lines each contain integers ai and bi (1ββ€βaiβ<βbiββ€β109) Β β is the probability pi of winning in casino i.The next q lines each contain queries of one of the types specified above (1ββ€βaβ<βbββ€β109, 1ββ€βiββ€βn, 1ββ€βlββ€βrββ€βn).It's guaranteed that there will be at least one query of type 2, i.e. the output will be non-empty. Additionally, it is guaranteed that p forms a non-decreasing sequence at all times.OutputPrint a real number for every request of type 2Β β the probability that boy will "dominate" on that interval. Your answer will be considered correct if its absolute error does not exceed 10β-β4.Namely: let's assume that one of your answers is a, and the corresponding answer of the jury is b. The checker program will consider your answer correct if |aβ-βb|ββ€β10β-β4.ExampleInput3 131 31 22 32 1 12 1 22 1 32 2 22 2 32 3 31 2 2 32 1 12 1 22 1 32 2 22 2 32 3 3Output0.33333333330.20000000000.16666666670.50000000000.40000000000.66666666670.33333333330.25000000000.22222222220.66666666670.57142857140.6666666667 | Input3 131 31 22 32 1 12 1 22 1 32 2 22 2 32 3 31 2 2 32 1 12 1 22 1 32 2 22 2 32 3 3 | Output0.33333333330.20000000000.16666666670.50000000000.40000000000.66666666670.33333333330.25000000000.22222222220.66666666670.57142857140.6666666667 | 4 seconds | 512 megabytes | ['data structures', 'math', 'probabilities', '*2500'] |
D. Memory and Scorestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMemory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score a and Lexa starts with score b. In a single turn, both Memory and Lexa get some integer in the range [β-βk;k] (i.e. one integer among β-βk,ββ-βkβ+β1,ββ-βkβ+β2,β...,ββ-β2,ββ-β1,β0,β1,β2,β...,βkβ-β1,βk) and add them to their current scores. The game has exactly t turns. Memory and Lexa, however, are not good at this game, so they both always get a random integer at their turn.Memory wonders how many possible games exist such that he ends with a strictly higher score than Lexa. Two games are considered to be different if in at least one turn at least one player gets different score. There are (2kβ+β1)2t games in total. Since the answer can be very large, you should print it modulo 109β+β7. Please solve this problem for Memory.InputThe first and only line of input contains the four integers a, b, k, and t (1ββ€βa,βbββ€β100, 1ββ€βkββ€β1000, 1ββ€βtββ€β100)Β β the amount Memory and Lexa start with, the number k, and the number of turns respectively.OutputPrint the number of possible games satisfying the conditions modulo 1β000β000β007 (109β+β7) in one line.ExamplesInput1 2 2 1Output6Input1 1 1 2Output31Input2 12 3 1Output0NoteIn the first sample test, Memory starts with 1 and Lexa starts with 2. If Lexa picks β-β2, Memory can pick 0, 1, or 2 to win. If Lexa picks β-β1, Memory can pick 1 or 2 to win. If Lexa picks 0, Memory can pick 2 to win. If Lexa picks 1 or 2, Memory cannot win. Thus, there are 3β+β2β+β1β=β6 possible games in which Memory wins. | Input1 2 2 1 | Output6 | 2 seconds | 512 megabytes | ['combinatorics', 'dp', 'math', '*2200'] |
C. Memory and De-Evolutiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMemory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.In a single second, he can modify the length of a single side of the current triangle such that it remains a non-degenerate triangle (triangle of positive area). At any moment of time, the length of each side should be integer.What is the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y?InputThe first and only line contains two integers x and y (3ββ€βyβ<βxββ€β100β000)Β β the starting and ending equilateral triangle side lengths respectively.OutputPrint a single integerΒ β the minimum number of seconds required for Memory to obtain the equilateral triangle of side length y if he starts with the equilateral triangle of side length x.ExamplesInput6 3Output4Input8 5Output3Input22 4Output6NoteIn the first sample test, Memory starts with an equilateral triangle of side length 6 and wants one of side length 3. Denote a triangle with sides a, b, and c as (a,βb,βc). Then, Memory can do .In the second sample test, Memory can do .In the third sample test, Memory can do: . | Input6 3 | Output4 | 2 seconds | 256 megabytes | ['greedy', 'math', '*1600'] |
B. Memory and Tridenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMemory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: An 'L' indicates he should move one unit left. An 'R' indicates he should move one unit right. A 'U' indicates he should move one unit up. A 'D' indicates he should move one unit down.But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.InputThe first and only line contains the string s (1ββ€β|s|ββ€β100β000)Β β the instructions Memory is given.OutputIf there is a string satisfying the conditions, output a single integerΒ β the minimum number of edits required. In case it's not possible to change the sequence in such a way that it will bring Memory to to the origin, output -1.ExamplesInputRRUOutput-1InputUDUROutput1InputRUUROutput2NoteIn the first sample test, Memory is told to walk right, then right, then up. It is easy to see that it is impossible to edit these instructions to form a valid walk.In the second sample test, Memory is told to walk up, then down, then up, then right. One possible solution is to change s to "LDUR". This string uses 1 edit, which is the minimum possible. It also ends at the origin. | InputRRU | Output-1 | 2 seconds | 256 megabytes | ['implementation', 'strings', '*1100'] |
A. Memory and Crowtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n integers b1,βb2,β...,βbn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure: The crow sets ai initially 0. The crow then adds bi to ai, subtracts biβ+β1, adds the biβ+β2 number, and so on until the n'th number. Thus, aiβ=βbiβ-βbiβ+β1β+βbiβ+β2β-βbiβ+β3.... Memory gives you the values a1,βa2,β...,βan, and he now wants you to find the initial numbers b1,βb2,β...,βbn written in the row? Can you do it?InputThe first line of the input contains a single integer n (2ββ€βnββ€β100β000)Β β the number of integers written in the row.The next line contains n, the i'th of which is ai (β-β109ββ€βaiββ€β109)Β β the value of the i'th number.OutputPrint n integers corresponding to the sequence b1,βb2,β...,βbn. It's guaranteed that the answer is unique and fits in 32-bit integer type.ExamplesInput56 -4 8 -2 3Output2 4 6 1 3 Input53 -2 -1 5 6Output1 -3 4 11 6 NoteIn the first sample test, the crows report the numbers 6,β-β4, 8,β-β2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6β=β2β-β4β+β6β-β1β+β3, and β-β4β=β4β-β6β+β1β-β3.In the second sample test, the sequence 1, β-β3, 4, 11, 6 satisfies the reports. For example, 5β=β11β-β6 and 6β=β6. | Input56 -4 8 -2 3 | Output2 4 6 1 3 | 2 seconds | 256 megabytes | ['implementation', 'math', '*800'] |
E. ZS and The Birthday Paradoxtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland.In Udayland, there are 2n days in a year. ZS the Coder wants to interview k people from Udayland, each of them has birthday in one of 2n days (each day with equal probability). He is interested in the probability of at least two of them have the birthday at the same day. ZS the Coder knows that the answer can be written as an irreducible fraction . He wants to find the values of A and B (he does not like to deal with floating point numbers). Can you help him?InputThe first and only line of the input contains two integers n and k (1ββ€βnββ€β1018,β2ββ€βkββ€β1018), meaning that there are 2n days in a year and that ZS the Coder wants to interview exactly k people.OutputIf the probability of at least two k people having the same birthday in 2n days long year equals (Aββ₯β0, Bββ₯β1, ), print the A and B in a single line.Since these numbers may be too large, print them modulo 106β+β3. Note that A and B must be coprime before their remainders modulo 106β+β3 are taken.ExamplesInput3 2Output1 8Input1 3Output1 1Input4 3Output23 128NoteIn the first sample case, there are 23β=β8 days in Udayland. The probability that 2 people have the same birthday among 2 people is clearly , so Aβ=β1, Bβ=β8.In the second sample case, there are only 21β=β2 days in Udayland, but there are 3 people, so it is guaranteed that two of them have the same birthday. Thus, the probability is 1 and Aβ=βBβ=β1. | Input3 2 | Output1 8 | 2 seconds | 256 megabytes | ['math', 'number theory', 'probabilities', '*2300'] |
D. Directed Roadstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (aiββ βi). ZS the Coder can flip the direction of any road in Udayland, i.e. if it goes from town A to town B before the flip, it will go from town B to town A after.ZS the Coder considers the roads in the Udayland confusing, if there is a sequence of distinct towns A1,βA2,β...,βAk (kβ>β1) such that for every 1ββ€βiβ<βk there is a road from town Ai to town Aiβ+β1 and another road from town Ak to town A1. In other words, the roads are confusing if some of them form a directed cycle of some towns.Now ZS the Coder wonders how many sets of roads (there are 2n variants) in initial configuration can he choose to flip such that after flipping each road in the set exactly once, the resulting network will not be confusing.Note that it is allowed that after the flipping there are more than one directed road from some town and possibly some towns with no roads leading out of it, or multiple roads between any pair of cities.InputThe first line of the input contains single integer n (2ββ€βnββ€β2Β·105)Β β the number of towns in Udayland.The next line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€βn,βaiββ βi), ai denotes a road going from town i to town ai.OutputPrint a single integerΒ β the number of ways to flip some set of the roads so that the resulting whole set of all roads is not confusing. Since this number may be too large, print the answer modulo 109β+β7.ExamplesInput32 3 1Output6Input42 1 1 1Output8Input52 4 2 5 3Output28NoteConsider the first sample case. There are 3 towns and 3 roads. The towns are numbered from 1 to 3 and the roads are , , initially. Number the roads 1 to 3 in this order. The sets of roads that ZS the Coder can flip (to make them not confusing) are {1},β{2},β{3},β{1,β2},β{1,β3},β{2,β3}. Note that the empty set is invalid because if no roads are flipped, then towns 1,β2,β3 is form a directed cycle, so it is confusing. Similarly, flipping all roads is confusing too. Thus, there are a total of 6 possible sets ZS the Coder can flip.The sample image shows all possible ways of orienting the roads from the first sample such that the network is not confusing. | Input32 3 1 | Output6 | 2 seconds | 256 megabytes | ['combinatorics', 'dfs and similar', 'graphs', 'math', '*1900'] |
C. Coloring Treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0ββ€βciββ€βm, where ciβ=β0 means that tree i is uncolored.ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ciβ=β0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi,βj litres of paint.The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2,β1,β1,β1,β3,β2,β2,β3,β1,β3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2},β{1,β1,β1},β{3},β{2,β2},β{3},β{1},β{3}. ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.Please note that the friends can't color the trees that are already colored.InputThe first line contains three integers, n, m and k (1ββ€βkββ€βnββ€β100, 1ββ€βmββ€β100)Β β the number of trees, number of colors and beauty of the resulting coloring respectively.The second line contains n integers c1,βc2,β...,βcn (0ββ€βciββ€βm), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi,βj (1ββ€βpi,βjββ€β109)Β β the amount of litres the friends need to color i-th tree with color j. pi,βj's are specified even for the initially colored trees, but such trees still can't be colored.OutputPrint a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print β-β1.ExamplesInput3 2 20 0 01 23 45 6Output10Input3 2 22 1 21 32 43 5Output-1Input3 2 22 0 01 32 43 5Output5Input3 2 32 1 21 32 43 5Output0NoteIn the first sample case, coloring the trees with colors 2,β1,β1 minimizes the amount of paint used, which equals to 2β+β3β+β5β=β10. Note that 1,β1,β1 would not be valid because the beauty of such coloring equals to 1 ({1,β1,β1} is a way to group the trees into a single group of the same color).In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is β-β1.In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0. | Input3 2 20 0 01 23 45 6 | Output10 | 2 seconds | 256 megabytes | ['dp', '*1700'] |
B. Chris and Magic Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a nβΓβn magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonalΒ β and the secondary diagonalΒ β ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?InputThe first line of the input contains a single integer n (1ββ€βnββ€β500)Β β the number of rows and columns of the magic grid.n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai,βj (1ββ€βai,βjββ€β109 or ai,βjβ=β0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai,βj will be equal to 0. Otherwise, ai,βj is positive.It is guaranteed that there is exactly one pair of integers i,βj (1ββ€βi,βjββ€βn) such that ai,βjβ=β0.OutputOutput a single integer, the positive integer x (1ββ€βxββ€β1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output β-β1 instead.If there are multiple solutions, you may print any of them.ExamplesInput34 0 23 5 78 1 6Output9Input41 1 1 11 1 0 11 1 1 11 1 1 1Output1Input41 1 1 11 1 0 11 1 2 11 1 1 1Output-1NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4β+β9β+β2β=β3β+β5β+β7β=β8β+β1β+β6β=β15.The sum of numbers in each column is:4β+β3β+β8β=β9β+β5β+β1β=β2β+β7β+β6β=β15.The sum of numbers in the two diagonals is:4β+β5β+β6β=β2β+β5β+β8β=β15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square. | Input34 0 23 5 78 1 6 | Output9 | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', '*1400'] |
A. Bus to Udaylandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?InputThe first line of the input contains a single integer n (1ββ€βnββ€β1000)Β β the number of rows of seats in the bus.Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row. Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details. OutputIf it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output).If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line.If there are multiple solutions, you may print any of them.ExamplesInput6OO|OXXO|XXOX|OOXX|OXOO|OOOO|XXOutputYES++|OXXO|XXOX|OOXX|OXOO|OOOO|XXInput4XO|OXXO|XXOX|OXXX|OXOutputNOInput5XX|XXXX|XXXO|OXXO|OOOX|XOOutputYESXX|XXXX|XXXO|OXXO|++OX|XONoteNote that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.O+|+XXO|XXOX|OOXX|OXOO|OOOO|XX | Input6OO|OXXO|XXOX|OOXX|OXOO|OOOO|XX | OutputYES++|OXXO|XXOX|OOXX|OXOO|OOOO|XX | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*800'] |
F. String Set Queriestime limit per test3 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou should process m queries over a set D of strings. Each query is one of three kinds: Add a string s to the set D. It is guaranteed that the string s was not added before. Delete a string s from the set D. It is guaranteed that the string s is in the set D. For the given string s find the number of occurrences of the strings from the set D. If some string p from D has several occurrences in s you should count all of them. Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query of the third type. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.InputThe first line contains integer m (1ββ€βmββ€β3Β·105) β the number of queries.Each of the next m lines contains integer t (1ββ€βtββ€β3) and nonempty string s β the kind of the query and the string to process. All strings consist of only lowercase English letters.The sum of lengths of all strings in the input will not exceed 3Β·105.OutputFor each query of the third kind print the only integer c β the desired number of occurrences in the string s.ExamplesInput51 abc3 abcabc2 abc1 aba3 abababcOutput22Input101 abc1 bcd1 abcd3 abcd2 abcd3 abcd2 bcd3 abcd2 abc3 abcdOutput3210 | Input51 abc3 abcabc2 abc1 aba3 abababc | Output22 | 3 seconds | 768 megabytes | ['brute force', 'data structures', 'hashing', 'interactive', 'string suffix structures', 'strings', '*2400'] |
E. Generate a Stringtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputzscoder wants to generate an input file for some programming competition problem.His input is a string consisting of n letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor.Initially, the text editor is empty. It takes him x seconds to insert or delete a letter 'a' from the text file and y seconds to copy the contents of the entire text file, and duplicate it.zscoder wants to find the minimum amount of time needed for him to create the input file of exactly n letters 'a'. Help him to determine the amount of time needed to generate the input.InputThe only line contains three integers n, x and y (1ββ€βnββ€β107, 1ββ€βx,βyββ€β109) β the number of letters 'a' in the input file and the parameters from the problem statement.OutputPrint the only integer t β the minimum amount of time needed to generate the input file.ExamplesInput8 1 1Output4Input8 1 10Output8 | Input8 1 1 | Output4 | 2 seconds | 512 megabytes | ['dfs and similar', 'dp', '*2000'] |
D. Two Arithmetic Progressionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arithmetic progressions: a1kβ+βb1 and a2lβ+βb2. Find the number of integers x such that Lββ€βxββ€βR and xβ=βa1k'β+βb1β=βa2l'β+βb2, for some integers k',βl'ββ₯β0.InputThe only line contains six integers a1,βb1,βa2,βb2,βL,βR (0β<βa1,βa2ββ€β2Β·109,ββ-β2Β·109ββ€βb1,βb2,βL,βRββ€β2Β·109,βLββ€βR).OutputPrint the desired number of integers x.ExamplesInput2 0 3 3 5 21Output3Input2 4 3 0 6 17Output2 | Input2 0 3 3 5 21 | Output3 | 1 second | 256 megabytes | ['math', 'number theory', '*2500'] |
C. Magic Odd Squaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFind an nβΓβn matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.InputThe only line contains odd integer n (1ββ€βnββ€β49).OutputPrint n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.ExamplesInput1Output1Input3Output2 1 43 5 76 9 8 | Input1 | Output1 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*1500'] |
B. Optimal Point on a Linetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.InputThe first line contains integer n (1ββ€βnββ€β3Β·105) β the number of points on the line.The second line contains n integers xi (β-β109ββ€βxiββ€β109) β the coordinates of the given n points.OutputPrint the only integer x β the position of the optimal point on the line. If there are several optimal points print the position of the leftmost one. It is guaranteed that the answer is always the integer.ExampleInput41 2 3 4Output2 | Input41 2 3 4 | Output2 | 1 second | 256 megabytes | ['brute force', 'sortings', '*1400'] |
A. King Movestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only king stands on the standard chess board. You are given his position in format "cd", where c is the column from 'a' to 'h' and d is the row from '1' to '8'. Find the number of moves permitted for the king.Check the king's moves here https://en.wikipedia.org/wiki/King_(chess). King moves from the position e4 InputThe only line contains the king's position in the format "cd", where 'c' is the column from 'a' to 'h' and 'd' is the row from '1' to '8'.OutputPrint the only integer x β the number of moves permitted for the king.ExampleInpute4Output8 | Inpute4 | Output8 | 1 second | 256 megabytes | ['implementation', '*800'] |
B. Checkpointstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1,βx2,β...,βxn. Vasya starts at the point with coordinate a. His goal is to visit at least nβ-β1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.InputThe first line of the input contains two integers n and a (1ββ€βnββ€β100β000, β-β1β000β000ββ€βaββ€β1β000β000)Β β the number of checkpoints and Vasya's starting position respectively.The second line contains n integers x1,βx2,β...,βxn (β-β1β000β000ββ€βxiββ€β1β000β000)Β β coordinates of the checkpoints.OutputPrint one integerΒ β the minimum distance Vasya has to travel in order to visit at least nβ-β1 checkpoint.ExamplesInput3 101 7 12Output7Input2 011 -10Output10Input5 00 0 1000 0 0Output0NoteIn the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12β-β10β=β2) and then proceed to the second one (distance is 12β-β7β=β5). The total distance is equal to 2β+β5β=β7.In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point β-β10. | Input3 101 7 12 | Output7 | 1 second | 256 megabytes | ['greedy', 'implementation', 'sortings', '*1500'] |
A. Juicertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKolya is going to make fresh orange juice. He has n oranges of sizes a1,βa2,β...,βan. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than d. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?InputThe first line of the input contains three integers n, b and d (1ββ€βnββ€β100β000, 1ββ€βbββ€βdββ€β1β000β000)Β β the number of oranges, the maximum size of the orange that fits in the juicer and the value d, which determines the condition when the waste section should be emptied.The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β1β000β000)Β β sizes of the oranges listed in the order Kolya is going to try to put them in the juicer.OutputPrint one integerΒ β the number of times Kolya will have to empty the waste section.ExamplesInput2 7 105 6Output1Input1 5 107Output0Input3 10 105 7 7Output1Input1 1 11Output0NoteIn the first sample, Kolya will squeeze the juice from two oranges and empty the waste section afterwards.In the second sample, the orange won't fit in the juicer so Kolya will have no juice at all. | Input2 7 105 6 | Output1 | 1 second | 256 megabytes | ['implementation', '*900'] |
E. Student's Camptime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex studied well and won the trip to student camp Alushta, located on the seashore. Unfortunately, it's the period of the strong winds now and there is a chance the camp will be destroyed! Camp building can be represented as the rectangle of nβ+β2 concrete blocks height and m blocks width.Every day there is a breeze blowing from the sea. Each block, except for the blocks of the upper and lower levers, such that there is no block to the left of it is destroyed with the probability . Similarly, each night the breeze blows in the direction to the sea. Thus, each block (again, except for the blocks of the upper and lower levers) such that there is no block to the right of it is destroyed with the same probability p. Note, that blocks of the upper and lower level are indestructible, so there are only nΒ·m blocks that can be destroyed.The period of the strong winds will last for k days and k nights. If during this period the building will split in at least two connected components, it will collapse and Alex will have to find another place to spend summer.Find the probability that Alex won't have to look for other opportunities and will be able to spend the summer in this camp.InputThe first line of the input contains two integers n and m (1ββ€βn,βmββ€β1500) that define the size of the destructible part of building.The second line of the input contains two integers a and b (1ββ€βaββ€βbββ€β109) that define the probability p. It's guaranteed that integers a and b are coprime. The third line contains a single integer k (0ββ€βkββ€β100β000)Β β the number of days and nights strong wind will blow for.OutputConsider the answer as an irreducible fraction is equal to . Print one integer equal to . It's guaranteed that within the given constraints .ExamplesInput2 21 21Output937500007Input5 13 101Output95964640Input3 31 105Output927188454NoteIn the first sample, each of the four blocks is destroyed with the probability . There are 7 scenarios that result in building not collapsing, and the probability we are looking for is equal to , so you should print | Input2 21 21 | Output937500007 | 3 seconds | 256 megabytes | ['dp', 'math', '*3100'] |
D. Incorrect Flowtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the entrance examination for the magistracy of the MSU Cyber-Mechanics Department Sasha got the question about Ford-Fulkerson algorithm. He knew the topic perfectly as he worked with it many times on programming competition. As the task for the question he was given a network with partially build flow that he had to use in order to demonstrate the workflow of the algorithm. He quickly finished to write the text and took a look at the problem only to understand that the given network is incorrect!Suppose you are given a directed graph G(V,βE) with two special nodes s and t called source and sink. We denote as n the number of nodes in the graph, i.e. nβ=β|V| and m stands for the number of directed edges in the graph, i.e. mβ=β|E|. For the purpose of this problem we always consider node 1 to be the source and node n to be the sink. In addition, for each edge of the graph e we define the capacity function c(e) and flow function f(e). Function f(e) represents the correct flow if the following conditions are satisfied: For each edge the flow is non-negative and does not exceed capacity c(e), i.e. 0ββ€βf(e)ββ€βc(e). For each node , that is not source or sink (vββ βs and vββ βt) the sum of flows of all edges going in v is equal to the sum of the flows among all edges going out from v. In other words, there is no flow stuck in v. It was clear that as the exam was prepared last night and there are plenty of mistakes in the tasks. Sasha asked one of the professors to fix the network or give the correct task, but the reply was that the magistrate student should be able to fix the network himself. As the professor doesn't want the task to become easier, he asks Sasha to fix the network in a such way that the total number of changes is minimum possible. Sasha is not allowed to remove edges, add new ones or reverse the direction of existing edges. The only thing he is able to do is to change capacity function c(e) and flow function f(e). Moreover, all the values should remain non-negative integers. There is no requirement on the flow to be maximum in any sense.Find the minimum possible total change of the functions f(e) and c(e) that Sasha has to make in order to make the flow correct. The total change is defined as the sum of absolute differences, i.e. if new functions are fβ*β(e) and cβ*β(e), then the total change is .InputThe first line of the input contains two integers n and m (2ββ€βnββ€β100, 0ββ€βmββ€β100)Β β the number of nodes and edges in the graph respectively. Each of the following m lines contains the description of the edges, consisting of four integers ui, vi, ci and fi (1ββ€βui,βviββ€βn, uiββ βvi, 0ββ€βci,βfiββ€β1β000β000)Β β index of the node the edges starts from, the index of the node the edge goes to, current capacity and flow value.Node number 1 is the source, and node number n is the sink. It's guaranteed that no edge goes to the source, and no edges starts in the sink.Given graph contains no self-loops but may contain multiple edges.OutputPrint one integerΒ β the minimum total sum of changes that Sasha has to do in order to get the correct flow description.ExamplesInput2 11 2 2 1Output0Input2 11 2 1 2Output1Input3 31 2 1 12 3 2 21 3 3 3Output1Input4 22 3 1 13 2 1 1Output0NoteIn the first sample, the flow is initially correct. Note, that the flow is not maximum, but this is not required.In the second sample, the flow value of the only edge is greater than its capacity. There are two ways to fix this: either increase the capacity up to 2 or reduce the flow down to 1.In the third sample, there is only 1 unit of flow coming to vertex 2, but there are 2 units going out of it. One of the possible solutions is to reduce the value of the flow on the second edge by 1.In the fourth sample, there is isolated circulation of flow, but this description is correct by definition. | Input2 11 2 2 1 | Output0 | 1 second | 256 megabytes | ['flows', '*2900'] |
C. Centroidstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputTree is a connected acyclic graph. Suppose you are given a tree consisting of n vertices. The vertex of this tree is called centroid if the size of each connected component that appears if this vertex is removed from the tree doesn't exceed .You are given a tree of size n and can perform no more than one edge replacement. Edge replacement is the operation of removing one edge from the tree (without deleting incident vertices) and inserting one new edge (without adding new vertices) in such a way that the graph remains a tree. For each vertex you have to determine if it's possible to make it centroid by performing no more than one edge replacement.InputThe first line of the input contains an integer n (2ββ€βnββ€β400β000)Β β the number of vertices in the tree. Each of the next nβ-β1 lines contains a pair of vertex indices ui and vi (1ββ€βui,βviββ€βn)Β β endpoints of the corresponding edge.OutputPrint n integers. The i-th of them should be equal to 1 if the i-th vertex can be made centroid by replacing no more than one edge, and should be equal to 0 otherwise.ExamplesInput31 22 3Output1 1 1 Input51 21 31 41 5Output1 0 0 0 0 NoteIn the first sample each vertex can be made a centroid. For example, in order to turn vertex 1 to centroid one have to replace the edge (2,β3) with the edge (1,β3). | Input31 22 3 | Output1 1 1 | 4 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'dp', 'graphs', 'greedy', 'trees', '*2300'] |
B. Recover the Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor each string s consisting of characters '0' and '1' one can define four integers a00, a01, a10 and a11, where axy is the number of subsequences of length 2 of the string s equal to the sequence {x,βy}. In these problem you are given four integers a00, a01, a10, a11 and have to find any non-empty string s that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1β000β000.InputThe only line of the input contains four non-negative integers a00, a01, a10 and a11. Each of them doesn't exceed 109.OutputIf there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1β000β000.ExamplesInput1 2 3 4OutputImpossibleInput1 2 2 1Output0110 | Input1 2 3 4 | OutputImpossible | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'math', '*1900'] |
A. Letters Cyclic Shifttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' 'y' 'x' 'b' 'a' 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' is replaced with 'z'.What is the lexicographically minimum string that can be obtained from s by performing this shift exactly once?InputThe only line of the input contains the string s (1ββ€β|s|ββ€β100β000) consisting of lowercase English letters.OutputPrint the lexicographically minimum string that can be obtained from s by shifting letters of exactly one non-empty substring.ExamplesInputcodeforcesOutputbncdenqbdrInputabacabaOutputaaacabaNoteString s is lexicographically smaller than some other string t of the same length if there exists some 1ββ€βiββ€β|s|, such that s1β=βt1,βs2β=βt2,β...,βsiβ-β1β=βtiβ-β1, and siβ<βti. | Inputcodeforces | Outputbncdenqbdr | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'strings', '*1200'] |
E. Garlandstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLike all children, Alesha loves New Year celebration. During the celebration he and his whole family dress up the fir-tree. Like all children, Alesha likes to play with garlandsΒ β chains consisting of a lightbulbs.Alesha uses a grid field sized nβΓβm for playing. The rows of the field are numbered from 1 to n from the top to the bottom and columns are numbered from 1 to m from the left to the right.Alesha has k garlands which he places at the field. He does so in the way such that each lightbulb of each garland lies in the center of some cell in the field, and each cell contains at most one lightbulb. Of course lightbulbs, which are neighbours in some garland, appears in cells neighbouring by a side.The example of garland placing.Each garland is turned off or turned on at any moment. If some garland is turned on then each of its lightbulbs is turned on, the same applies for garland turned off. Each lightbulb in the whole garland set is unique, and thus, being turned on, brings Alesha some pleasure, described by an integer value. Turned off lightbulbs don't bring Alesha any pleasure.Alesha can turn garlands on and off and wants to know the sum of pleasure value which the lightbulbs, placed in the centers of the cells in some rectangular part of the field, bring him. Initially all the garlands are turned on.Alesha is still very little and can't add big numbers. He extremely asks you to help him.InputThe first line of the input contains three integers n, m and k (1ββ€βn,βm,βkββ€β2000)Β β the number of field rows, the number of field columns and the number of garlands placed at the field respectively.Next lines contains garlands set description in the following format:The first line of a single garland description contains a single integer len (1ββ€βlenββ€β2000)Β β the number of lightbulbs in the garland.Each of the next len lines contains three integers i, j and w (1ββ€βiββ€βn, 1ββ€βjββ€βm, 1ββ€βwββ€β109)Β β the coordinates of the cell containing a lightbullb and pleasure value Alesha gets from it if it is turned on. The lightbulbs are given in the order they are forming a chain in the garland. It is guaranteed that neighbouring lightbulbs are placed in the cells neighbouring by a side.The next line contains single integer q (1ββ€βqββ€β106)Β β the number of events in Alesha's game. The next q lines describes events in chronological order. The i-th of them describes the i-th event in the one of the following formats: SWITCH iΒ β Alesha turns off i-th garland if it is turned on, or turns it on if it is turned off. It is guaranteed that 1ββ€βiββ€βk. ASK x1 y1 x2 y2Β β Alesha wants to know the sum of pleasure values the lightbulbs, placed in a rectangular part of the field. Top-left cell of a part has coordinates (x1,βy1) and right-bottom cell has coordinates (x2,βy2). It is guaranteed that 1ββ€βx1ββ€βx2ββ€βn and 1ββ€βy1ββ€βy2ββ€βm. There is no more than 2000 events of this type in the input. All the numbers in the input are integers.Please note that the input is quite large, so be careful while using some input ways. In particular, it's not recommended to use cin in codes on C++ and class Scanner in codes on Java.OutputFor each ASK operation print the sum Alesha wants to know in a separate line. Print the answers in chronological order.ExamplesInput4 4 351 1 21 2 32 2 12 1 43 1 741 3 12 3 32 4 31 4 174 1 14 2 93 2 83 3 34 3 44 4 13 4 12ASK 2 2 3 3ASK 1 1 4 4Output1552Input4 4 184 1 13 1 22 1 11 1 71 2 52 2 42 3 11 3 13ASK 1 1 3 2SWITCH 1ASK 1 1 3 2Output190NoteThis image illustrates the first sample case. | Input4 4 351 1 21 2 32 2 12 1 43 1 741 3 12 3 32 4 31 4 174 1 14 2 93 2 83 3 34 3 44 4 13 4 12ASK 2 2 3 3ASK 1 1 4 4 | Output1552 | 3 seconds | 256 megabytes | ['data structures', '*2400'] |
D. Persistent Bookcase time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelvesΒ β from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i jΒ β Place a book at position j at shelf i if there is no book at it. 2 i jΒ β Remove the book from position j at shelf i if there is a book at it. 3 iΒ β Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 kΒ β Return the books in the bookcase in a state they were after applying k-th operation. In particular, kβ=β0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so?InputThe first line of the input contains three integers n, m and q (1ββ€βn,βmββ€β103, 1ββ€βqββ€β105)Β β the bookcase dimensions and the number of operations respectively.The next q lines describes operations in chronological orderΒ β i-th of them describes i-th operation in one of the four formats described in the statement.It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0.OutputFor each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order.ExamplesInput2 3 31 1 13 24 0Output140Input4 2 63 22 2 23 33 22 2 23 2Output213324Input2 2 23 22 2 1Output21NoteThis image illustrates the second sample case. | Input2 3 31 1 13 24 0 | Output140 | 2 seconds | 512 megabytes | ['bitmasks', 'data structures', 'dfs and similar', 'implementation', '*2200'] |
C. Pythagorean Triplestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKatya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3,β4,β5), (5,β12,β13) and (6,β8,β10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?InputThe only line of the input contains single integer n (1ββ€βnββ€β109)Β β the length of some side of a right triangle.OutputPrint two integers m and k (1ββ€βm,βkββ€β1018), such that n, m and k form a Pythagorean triple, in the only line.In case if there is no any Pythagorean triple containing integer n, print β-β1 in the only line. If there are many answers, print any of them.ExamplesInput3Output4 5Input6Output8 10Input1Output-1Input17Output144 145Input67Output2244 2245NoteIllustration for the first sample. | Input3 | Output4 5 | 1 second | 256 megabytes | ['math', 'number theory', '*1500'] |
B. Bakerytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1,βa2,β...,βak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another nβ-βk cities, and, of course, flour delivery should be paidΒ β for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (aiββ βb for every 1ββ€βiββ€βk) and choose a storage in some city s (sβ=βaj for some 1ββ€βjββ€βk) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.InputThe first line of the input contains three integers n, m and k (1ββ€βn,βmββ€β105, 0ββ€βkββ€βn)Β β the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively.Then m lines follow. Each of them contains three integers u, v and l (1ββ€βu,βvββ€βn, 1ββ€βlββ€β109, uββ βv) meaning that there is a road between cities u and v of length of l kilometers .If kβ>β0, then the last line of the input contains k distinct integers a1,βa2,β...,βak (1ββ€βaiββ€βn)Β β the number of cities having flour storage located in. If kβ=β0 then this line is not presented in the input.OutputPrint the minimum possible amount of rubles Masha should pay for flour delivery in the only line.If the bakery can not be opened (while satisfying conditions) in any of the n cities, print β-β1 in the only line.ExamplesInput5 4 21 2 51 2 32 3 41 4 101 5Output3Input3 1 11 2 33Output-1NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened. | Input5 4 21 2 51 2 32 3 41 4 101 5 | Output3 | 2 seconds | 256 megabytes | ['graphs', '*1300'] |
A. Brain's Photostime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmall, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).Brain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, and to sort them, one needs to spend more than one hour!As soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.Photo can be represented as a matrix sized nβΓβm, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors: 'C' (cyan) 'M' (magenta) 'Y' (yellow) 'W' (white) 'G' (grey) 'B' (black) The photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo then it is considered colored.InputThe first line of the input contains two integers n and m (1ββ€βn,βmββ€β100)Β β the number of photo pixel matrix rows and columns respectively.Then n lines describing matrix rows follow. Each of them contains m space-separated characters describing colors of pixels in a row. Each character in the line is one of the 'C', 'M', 'Y', 'W', 'G' or 'B'.OutputPrint the "#Black&White" (without quotes), if the photo is black-and-white and "#Color" (without quotes), if it is colored, in the only line.ExamplesInput2 2C MY YOutput#ColorInput3 2W WW WB BOutput#Black&WhiteInput1 1WOutput#Black&White | Input2 2C MY Y | Output#Color | 2 seconds | 256 megabytes | ['implementation', '*800'] |
E. Working routinetime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasiliy finally got to work, where there is a huge amount of tasks waiting for him. Vasiliy is given a matrix consisting of n rows and m columns and q tasks. Each task is to swap two submatrices of the given matrix.For each task Vasiliy knows six integers ai, bi, ci, di, hi, wi, where ai is the index of the row where the top-left corner of the first rectangle is located, bi is the index of its column, ci is the index of the row of the top-left corner of the second rectangle, di is the index of its column, hi is the height of the rectangle and wi is its width.It's guaranteed that two rectangles in one query do not overlap and do not touch, that is, no cell belongs to both rectangles, and no two cells belonging to different rectangles share a side. However, rectangles are allowed to share an angle.Vasiliy wants to know how the matrix will look like after all tasks are performed.InputThe first line of the input contains three integers n, m and q (2ββ€βn,βmββ€β1000, 1ββ€βqββ€β10β000)Β β the number of rows and columns in matrix, and the number of tasks Vasiliy has to perform.Then follow n lines containing m integers vi,βj (1ββ€βvi,βjββ€β109) eachΒ β initial values of the cells of the matrix.Each of the following q lines contains six integers ai, bi, ci, di, hi, wi (1ββ€βai,βci,βhiββ€βn, 1ββ€βbi,βdi,βwiββ€βm).OutputPrint n lines containing m integers eachΒ β the resulting matrix.ExamplesInput4 4 21 1 2 21 1 2 23 3 4 43 3 4 41 1 3 3 2 23 1 1 3 2 2Output4 4 3 34 4 3 32 2 1 12 2 1 1Input4 2 11 11 12 22 21 1 4 1 1 2Output2 21 12 21 1 | Input4 4 21 1 2 21 1 2 23 3 4 43 3 4 41 1 3 3 2 23 1 1 3 2 2 | Output4 4 3 34 4 3 32 2 1 12 2 1 1 | 2.5 seconds | 256 megabytes | ['data structures', 'implementation', '*2500'] |
D. Vasiliy's Multisettime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAuthor has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries: "+ x"Β β add integer x to multiset A. "- x"Β β erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. "? x"Β β you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed.InputThe first line of the input contains a single integer q (1ββ€βqββ€β200β000)Β β the number of queries Vasiliy has to perform.Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1ββ€βxiββ€β109). It's guaranteed that there is at least one query of the third type.Note, that the integer 0 will always be present in the set A.OutputFor each query of the type '?' print one integerΒ β the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.ExampleInput10+ 8+ 9+ 11+ 6+ 1? 3- 8? 3? 8? 11Output11101413NoteAfter first five operations multiset A contains integers 0, 8, 9, 11, 6 and 1.The answer for the sixth query is integer Β β maximum among integers , , , and . | Input10+ 8+ 9+ 11+ 6+ 1? 3- 8? 3? 8? 11 | Output11101413 | 4 seconds | 256 megabytes | ['binary search', 'bitmasks', 'data structures', 'trees', '*1800'] |
C. Hard problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A|β<β|B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.InputThe first line of the input contains a single integer n (2ββ€βnββ€β100β000)Β β the number of strings.The second line contains n integers ci (0ββ€βciββ€β109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string. Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100β000.OutputIf it is impossible to reverse some of the strings such that they will be located in lexicographical order, print β-β1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.ExamplesInput21 2baacOutput1Input31 3 1aabaacOutput1Input25 5bbbaaaOutput-1Input23 3aaaaaOutput-1NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is β-β1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is β-β1. | Input21 2baac | Output1 | 1 second | 256 megabytes | ['dp', 'strings', '*1600'] |
B. Interesting drinktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".InputThe first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of shops in the city that sell Vasiliy's favourite drink.The second line contains n integers xi (1ββ€βxiββ€β100β000)Β β prices of the bottles of the drink in the i-th shop.The third line contains a single integer q (1ββ€βqββ€β100β000)Β β the number of days Vasiliy plans to buy the drink.Then follow q lines each containing one integer mi (1ββ€βmiββ€β109)Β β the number of coins Vasiliy can spent on the i-th day.OutputPrint q integers. The i-th of them should be equal to the number of shops where Vasiliy will be able to buy a bottle of the drink on the i-th day.ExampleInput53 10 8 6 114110311Output0415NoteOn the first day, Vasiliy won't be able to buy a drink in any of the shops.On the second day, Vasiliy can buy a drink in the shops 1, 2, 3 and 4.On the third day, Vasiliy can buy a drink only in the shop number 1.Finally, on the last day Vasiliy can buy a drink in any shop. | Input53 10 8 6 114110311 | Output0415 | 2 seconds | 256 megabytes | ['binary search', 'dp', 'implementation', '*1100'] |
A. Beru-taxitime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasiliy lives at point (a,βb) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi,βyi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.InputThe first line of the input contains two integers a and b (β-β100ββ€βa,βbββ€β100)Β β coordinates of Vasiliy's home.The second line contains a single integer n (1ββ€βnββ€β1000)Β β the number of available Beru-taxi cars nearby. The i-th of the following n lines contains three integers xi, yi and vi (β-β100ββ€βxi,βyiββ€β100, 1ββ€βviββ€β100)Β β the coordinates of the i-th car and its speed.It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.OutputPrint a single real valueΒ β the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10β-β6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput0 022 0 10 2 2Output1.00000000000000000000Input1 333 3 2-2 3 6-2 7 10Output0.50000000000000000000NoteIn the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.In the second sample, cars 2 and 3 will arrive simultaneously. | Input0 022 0 10 2 2 | Output1.00000000000000000000 | 1 second | 256 megabytes | ['brute force', 'geometry', 'implementation', '*900'] |
B. Spider Mantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and xβ-βp vertices where 1ββ€βpβ<βx is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.InputThe first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of tests Peter is about to make.The second line contains n space separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109), i-th of them stands for the number of vertices in the cycle added before the i-th test.OutputPrint the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.ExamplesInput31 2 3Output211Input51 1 5 1 1Output22222NoteIn the first sample test:In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.In the second sample test:Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3. If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses. If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses. | Input31 2 3 | Output211 | 2 seconds | 256 megabytes | ['games', 'math', '*1100'] |
A. Hulktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if nβ=β1, then his feeling is "I hate it" or if nβ=β2 it's "I hate that I love it", and if nβ=β3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.InputThe only line of the input contains a single integer n (1ββ€βnββ€β100)Β β the number of layers of love and hate.OutputPrint Dr.Banner's feeling in one line.ExamplesInput1OutputI hate itInput2OutputI hate that I love itInput3OutputI hate that I love that I hate it | Input1 | OutputI hate it | 1 second | 256 megabytes | ['implementation', '*800'] |
E. Iron Mantime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTony Stark is playing a game with his suits (they have auto-pilot now). He lives in Malibu. Malibu has n junctions numbered from 1 to n, connected with nβ-β1 roads. One can get from a junction to any other junction using these roads (graph of Malibu forms a tree).Tony has m suits. There's a special plan for each suit. The i-th suit will appear at the moment of time ti in the junction vi, and will move to junction ui using the shortest path between vi and ui with the speed ci roads per second (passing a junctions takes no time), and vanishing immediately when arriving at ui (if it reaches ui in time q, it's available there at moment q, but not in further moments). Also, suits move continuously (for example if viββ βui, at time it's in the middle of a road. Please note that if viβ=βui it means the suit will be at junction number vi only at moment ti and then it vanishes. An explosion happens if at any moment of time two suits share the same exact location (it may be in a junction or somewhere on a road; while appearing, vanishing or moving).Your task is to tell Tony the moment of the the first explosion (if there will be any).InputThe first line of the input contains two integers n and m (1ββ€βn,βmββ€β100β000)Β β the number of junctions and the number of suits respectively.The next nβ-β1 lines contain the roads descriptions. Each line contains two integers ai and biΒ β endpoints of the i-th road (1ββ€βai,βbiββ€βn, aiββ βbi).The next m lines contain the suit descriptions. The i-th of them contains four integers ti, ci, vi and ui (0ββ€βtiββ€β10β000,β1ββ€βciββ€β10β000, 1ββ€βvi,βuiββ€βn), meaning the i-th suit will appear at moment of time ti at the junction vi and will move to the junction ui with a speed ci roads per second.OutputIf there would be no explosions at all, print -1 in the first and only line of output.Otherwise print the moment of the first explosion.Your answer will be considered correct if its relative or absolute error doesn't exceed 10β-β6.ExamplesInput6 42 56 53 64 64 127 6 1 39 5 1 627 4 3 411 29 2 6Output27.3Input6 43 14 56 46 12 616 4 4 513 20 6 23 16 4 528 5 3 5Output-1 | Input6 42 56 53 64 64 127 6 1 39 5 1 627 4 3 411 29 2 6 | Output27.3 | 5 seconds | 256 megabytes | ['data structures', 'geometry', 'trees', '*3300'] |
D. Captain Americatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSteve Rogers is fascinated with new vibranium shields S.H.I.E.L.D gave him. They're all uncolored. There are n shields in total, the i-th shield is located at point (xi,βyi) of the coordinate plane. It's possible that two or more shields share the same location.Steve wants to paint all these shields. He paints each shield in either red or blue. Painting a shield in red costs r dollars while painting it in blue costs b dollars.Additionally, there are m constraints Steve wants to be satisfied. The i-th constraint is provided by three integers ti, li and di: If tiβ=β1, then the absolute difference between the number of red and blue shields on line xβ=βli should not exceed di. If tiβ=β2, then the absolute difference between the number of red and blue shields on line yβ=βli should not exceed di. Steve gave you the task of finding the painting that satisfies all the condition and the total cost is minimum.InputThe first line of the input contains two integers n and m (1ββ€βn,βmββ€β100β000)Β β the number of shields and the number of constraints respectively.The second line contains two integers r and b (1ββ€βr,βbββ€β109).The next n lines contain the shields coordinates. The i-th of these lines contains two integers xi and yi (1ββ€βxi,βyiββ€β109).The next m lines contain the constrains. The j-th of these lines contains three integers tj, lj and dj (1ββ€βtjββ€β2,β1ββ€βljββ€β109,β0ββ€βdjββ€βn).OutputIf satisfying all the constraints is impossible print -1 in first and only line of the output.Otherwise, print the minimum total cost in the first line of output. In the second line print a string of length n consisting of letters 'r' and 'b' only. The i-th character should be 'r' if the i-th shield should be painted red in the optimal answer and 'b' if it should be painted blue. The cost of painting shields in these colors should be equal the minimum cost you printed on the first line.If there exist more than one optimal solution, print any of them.ExamplesInput5 68 32 101 59 109 102 81 9 11 2 12 10 32 10 21 1 12 5 2Output25rbrbbInput4 47 310 39 810 32 82 8 02 8 01 2 01 9 0Output-1 | Input5 68 32 101 59 109 102 81 9 11 2 12 10 32 10 21 1 12 5 2 | Output25rbrbb | 2 seconds | 256 megabytes | ['flows', 'greedy', '*3100'] |
C. Black Widowtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNatalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:Where represents logical OR and represents logical exclusive OR (XOR), and vi,βj are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and vi,βj are called literals.In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables x1,βx2,β...,βxm and their negations. An XNF formula is 2-XNF-2 if: For each 1ββ€βiββ€βn, kiββ€β2, i.e. the size of each clause doesn't exceed two. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of m variables, consisting of n clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set x1,β...,βxm with true and false (out of total of 2m ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109β+β7.Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to false or true gives different ways to set variables).InputThe first line of input contains two integers n and m (1ββ€βn,βmββ€β100β000)Β β the number of clauses and the number of variables respectively.The next n lines contain the formula. The i-th of them starts with an integer kiΒ β the number of literals in the i-th clause. It is followed by ki non-zero integers ai,β1,β...,βai,βki. If ai,βjβ>β0 then vi,βj is xai,βj otherwise it's negation of xβ-βai,βj (1ββ€βkiββ€β2, β-βmββ€βai,βjββ€βm, ai,βjββ β0).OutputPrint the answer modulo 1β000β000β007 (109β+β7) in one line.ExamplesInput6 72 4 -22 6 32 -7 12 -5 12 3 62 -2 -5Output48Input8 101 -52 4 -62 -2 -62 -7 92 10 -12 3 -12 -8 92 5 8Output544Input2 32 1 12 -3 3Output4NoteThe equation in the first sample is:The equation in the second sample is:The equation in the third sample is: | Input6 72 4 -22 6 32 -7 12 -5 12 3 62 -2 -5 | Output48 | 2 seconds | 256 megabytes | ['dp', 'graphs', 'implementation', 'math', '*2900'] |
B. Ant Mantime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputScott Lang is at war with Darren Cross. There are n chairs in a hall where they are, numbered with 1,β2,β...,βn from left to right. The i-th chair is located at coordinate xi. Scott is on chair number s and Cross is on chair number e. Scott can jump to all other chairs (not only neighboring chairs). He wants to start at his position (chair number s), visit each chair exactly once and end up on chair number e with Cross. As we all know, Scott can shrink or grow big (grow big only to his normal size), so at any moment of time he can be either small or large (normal). The thing is, he can only shrink or grow big while being on a chair (not in the air while jumping to another chair). Jumping takes time, but shrinking and growing big takes no time. Jumping from chair number i to chair number j takes |xiβ-βxj| seconds. Also, jumping off a chair and landing on a chair takes extra amount of time. If Scott wants to jump to a chair on his left, he can only be small, and if he wants to jump to a chair on his right he should be large.Jumping off the i-th chair takes: ci extra seconds if he's small. di extra seconds otherwise (he's large). Also, landing on i-th chair takes: bi extra seconds if he's small. ai extra seconds otherwise (he's large). In simpler words, jumping from i-th chair to j-th chair takes exactly: |xiβ-βxj|β+βciβ+βbj seconds if jβ<βi. |xiβ-βxj|β+βdiβ+βaj seconds otherwise (jβ>βi). Given values of x, a, b, c, d find the minimum time Scott can get to Cross, assuming he wants to visit each chair exactly once.InputThe first line of the input contains three integers n,βs and e (2ββ€βnββ€β5000,β1ββ€βs,βeββ€βn,βsββ βe)Β β the total number of chairs, starting and ending positions of Scott.The second line contains n integers x1,βx2,β...,βxn (1ββ€βx1β<βx2β<β...β<βxnββ€β109).The third line contains n integers a1,βa2,β...,βan (1ββ€βa1,βa2,β...,βanββ€β109).The fourth line contains n integers b1,βb2,β...,βbn (1ββ€βb1,βb2,β...,βbnββ€β109).The fifth line contains n integers c1,βc2,β...,βcn (1ββ€βc1,βc2,β...,βcnββ€β109).The sixth line contains n integers d1,βd2,β...,βdn (1ββ€βd1,βd2,β...,βdnββ€β109).OutputPrint the minimum amount of time Scott needs to get to the Cross while visiting each chair exactly once.ExampleInput7 4 38 11 12 16 17 18 2017 16 20 2 20 5 1317 8 8 16 12 15 1312 4 16 4 15 7 68 14 2 11 17 12 8Output139NoteIn the sample testcase, an optimal solution would be . Spent time would be 17β+β24β+β23β+β20β+β33β+β22β=β139. | Input7 4 38 11 12 16 17 18 2017 16 20 2 20 5 1317 8 8 16 12 15 1312 4 16 4 15 7 68 14 2 11 17 12 8 | Output139 | 4 seconds | 256 megabytes | ['dp', 'graphs', 'greedy', '*2500'] |
A. Thortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types: Application x generates a notification (this new notification is unread). Thor reads all notifications generated so far by application x (he may re-read some notifications). Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.InputThe first line of input contains two integers n and q (1ββ€βn,βqββ€β300β000)Β β the number of applications and the number of events to happen.The next q lines contain the events. The i-th of these lines starts with an integer typeiΒ β type of the i-th event. If typeiβ=β1 or typeiβ=β2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1ββ€βtypeiββ€β3,β1ββ€βxiββ€βn,β1ββ€βtiββ€βq).OutputPrint the number of unread notifications after each event.ExamplesInput3 41 31 11 22 3Output1232Input4 61 21 41 23 31 31 3Output123012NoteIn the first sample: Application 3 generates a notification (there is 1 unread notification). Application 1 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test: Application 2 generates a notification (there is 1 unread notification). Application 4 generates a notification (there are 2 unread notifications). Application 2 generates a notification (there are 3 unread notifications). Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left. Application 3 generates a notification (there is 1 unread notification). Application 3 generates a notification (there are 2 unread notifications). | Input3 41 31 11 22 3 | Output1232 | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'implementation', '*1600'] |
E. Mishka and Divisorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter playing with her beautiful array, Mishka decided to learn some math. After learning how to multiply, divide and what is divisibility, she is now interested in solving the following problem.You are given integer k and array a1,βa2,β...,βan of n integers. You are to find non-empty subsequence of array elements such that the product of its elements is divisible by k and it contains minimum possible number of elements.Formally, you are to find a sequence of indices 1ββ€βi1β<βi2β<β...β<βimββ€βn such that is divisible by k while m is minimum possible among all such variants.If there are more than one such subsequences, you should choose one among them, such that sum of its elements is minimum possible.Mishka quickly solved this problem. Will you do so?InputThe first line of the input contains two integers n and k (1ββ€βnββ€β1β000, 1ββ€βkββ€β1012).The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β1012)Β β array elements.OutputPrint single positive integer m in the first lineΒ β the number of elements in desired sequence.In the second line print m distinct integersΒ β the sequence of indices of given array elements, which should be taken into the desired sequence. If there are more than one such subsequence (e.g. subsequence of minimum possible number of elements and with minimum possible sum of elements), you can print any of them.If there are no such subsequences, print β-β1 in the only line.ExampleInput5 602 4 6 5 2Output34 3 1 | Input5 602 4 6 5 2 | Output34 3 1 | 1 second | 256 megabytes | ['dp', 'number theory', '*2600'] |
D. Mishka and Interesting sumtime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1,βa2,β...,βan of n elements!Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.Each query is processed in the following way: Two integers l and r (1ββ€βlββ€βrββ€βn) are specifiedΒ β bounds of query segment. Integers, presented in array segment [l,ββr] (in sequence of integers al,βalβ+β1,β...,βar) even number of times, are written down. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1,βx2,β...,βxk, then Mishka wants to know the value , where Β β operator of exclusive bitwise OR. Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented.InputThe first line of the input contains single integer n (1ββ€βnββ€β1β000β000)Β β the number of elements in the array.The second line of the input contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β array elements.The third line of the input contains single integer m (1ββ€βmββ€β1β000β000)Β β the number of queries.Each of the next m lines describes corresponding query by a pair of integers l and r (1ββ€βlββ€βrββ€βn)Β β the bounds of query segment.OutputPrint m non-negative integersΒ β the answers for the queries in the order they appear in the input.ExamplesInput33 7 811 3Output0Input71 2 1 3 3 2 354 74 51 31 71 5Output03132NoteIn the second sample:There is no integers in the segment of the first query, presented even number of times in the segmentΒ β the answer is 0.In the second query there is only integer 3 is presented even number of timesΒ β the answer is 3.In the third query only integer 1 is written downΒ β the answer is 1.In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is .In the fifth query 1 and 3 are written down. The answer is . | Input33 7 811 3 | Output0 | 3.5 seconds | 256 megabytes | ['data structures', '*2100'] |
C. Chris and Roadtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnd while Mishka is enjoying her trip...Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend.Once walking with his friend, John gave Chris the following problem:At the infinite horizontal road of width w, bounded by lines yβ=β0 and yβ=βw, there is a bus moving, presented as a convex polygon of n vertices. The bus moves continuously with a constant speed of v in a straight Ox line in direction of decreasing x coordinates, thus in time only x coordinates of its points are changing. Formally, after time t each of x coordinates of its points will be decreased by vt.There is a pedestrian in the point (0,β0), who can move only by a vertical pedestrian crossing, presented as a segment connecting points (0,β0) and (0,βw) with any speed not exceeding u. Thus the pedestrian can move only in a straight line Oy in any direction with any speed not exceeding u and not leaving the road borders. The pedestrian can instantly change his speed, thus, for example, he can stop instantly.Please look at the sample note picture for better understanding.We consider the pedestrian is hit by the bus, if at any moment the point he is located in lies strictly inside the bus polygon (this means that if the point lies on the polygon vertex or on its edge, the pedestrian is not hit by the bus).You are given the bus position at the moment 0. Please help Chris determine minimum amount of time the pedestrian needs to cross the road and reach the point (0,βw) and not to be hit by the bus.InputThe first line of the input contains four integers n, w, v, u (3ββ€βnββ€β10β000, 1ββ€βwββ€β109, 1ββ€βv,ββuββ€β1000)Β β the number of the bus polygon vertices, road width, bus speed and pedestrian speed respectively.The next n lines describes polygon vertices in counter-clockwise order. i-th of them contains pair of integers xi and yi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€βw)Β β coordinates of i-th polygon point. It is guaranteed that the polygon is non-degenerate.OutputPrint the single real tΒ β the time the pedestrian needs to croos the road and not to be hit by the bus. The answer is considered correct if its relative or absolute error doesn't exceed 10β-β6.ExampleInput5 5 1 21 23 14 33 41 4Output5.0000000000NoteFollowing image describes initial position in the first sample case: | Input5 5 1 21 23 14 33 41 4 | Output5.0000000000 | 2 seconds | 256 megabytes | ['geometry', 'implementation', '*2100'] |
B. Mishka and triptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXXΒ β beautiful, but little-known northern country.Here are some interesting facts about XXX: XXX consists of n cities, k of whose (just imagine!) are capital cities. All of cities in the country are beautiful, but each is beautiful in its own way. Beauty value of i-th city equals to ci. All the cities are consecutively connected by the roads, including 1-st and n-th city, forming a cyclic route 1βββ2βββ...βββnβββ1. Formally, for every 1ββ€βiβ<βn there is a road between i-th and iβ+β1-th city, and another one between 1-st and n-th city. Each capital city is connected with each other city directly by the roads. Formally, if city x is a capital city, then for every 1ββ€βiββ€βn,ββiββ βx, there is a road between cities x and i. There is at most one road between any two cities. Price of passing a road directly depends on beauty values of cities it connects. Thus if there is a road between cities i and j, price of passing it equals ciΒ·cj.Mishka started to gather her things for a trip, but didn't still decide which route to follow and thus she asked you to help her determine summary price of passing each of the roads in XXX. Formally, for every pair of cities a and b (aβ<βb), such that there is a road between a and b you are to find sum of products caΒ·cb. Will you help her?InputThe first line of the input contains two integers n and k (3ββ€βnββ€β100β000,β1ββ€βkββ€βn)Β β the number of cities in XXX and the number of capital cities among them.The second line of the input contains n integers c1,βc2,β...,βcn (1ββ€βciββ€β10β000)Β β beauty values of the cities.The third line of the input contains k distinct integers id1,βid2,β...,βidk (1ββ€βidiββ€βn)Β β indices of capital cities. Indices are given in ascending order.OutputPrint the only integerΒ β summary price of passing each of the roads in XXX.ExamplesInput4 12 3 1 23Output17Input5 23 5 2 2 41 4Output71NoteThis image describes first sample case:It is easy to see that summary price is equal to 17.This image describes second sample case:It is easy to see that summary price is equal to 71. | Input4 12 3 1 23 | Output17 | 1 second | 256 megabytes | ['implementation', 'math', '*1400'] |
A. Mishka and Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her!InputThe first line of the input contains single integer n n (1ββ€βnββ€β100)Β β the number of game rounds.The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1ββ€βmi,ββciββ€β6)Β β values on dice upper face after Mishka's and Chris' throws in i-th round respectively.OutputIf Mishka is the winner of the game, print "Mishka" (without quotes) in the only line.If Chris is the winner of the game, print "Chris" (without quotes) in the only line.If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line.ExamplesInput33 52 14 2OutputMishkaInput26 11 6OutputFriendship is magic!^^Input31 53 32 2OutputChrisNoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Input33 52 14 2 | OutputMishka | 1 second | 256 megabytes | ['implementation', '*800'] |
F. T-Shirtstime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThe big consignment of t-shirts goes on sale in the shop before the beginning of the spring. In all n types of t-shirts go on sale. The t-shirt of the i-th type has two integer parameters β ci and qi, where ci β is the price of the i-th type t-shirt, qi β is the quality of the i-th type t-shirt. It should be assumed that the unlimited number of t-shirts of each type goes on sale in the shop, but in general the quality is not concerned with the price. As predicted, k customers will come to the shop within the next month, the j-th customer will get ready to spend up to bj on buying t-shirts. All customers have the same strategy. First of all, the customer wants to buy the maximum possible number of the highest quality t-shirts, then to buy the maximum possible number of the highest quality t-shirts from residuary t-shirts and so on. At the same time among several same quality t-shirts the customer will buy one that is cheaper. The customers don't like the same t-shirts, so each customer will not buy more than one t-shirt of one type. Determine the number of t-shirts which each customer will buy, if they use the described strategy. All customers act independently from each other, and the purchase of one does not affect the purchase of another.InputThe first line contains the positive integer n (1ββ€βnββ€β2Β·105) β the number of t-shirt types. Each of the following n lines contains two integers ci and qi (1ββ€βci,βqiββ€β109) β the price and the quality of the i-th type t-shirt.The next line contains the positive integer k (1ββ€βkββ€β2Β·105) β the number of the customers. The next line contains k positive integers b1,βb2,β...,βbk (1ββ€βbjββ€β109), where the j-th number is equal to the sum, which the j-th customer gets ready to spend on t-shirts.OutputThe first line of the input data should contain the sequence of k integers, where the i-th number should be equal to the number of t-shirts, which the i-th customer will buy.ExamplesInput37 53 54 3213 14Output2 3 Input2100 50050 499450 200 150 100Output1 2 2 1 NoteIn the first example the first customer will buy the t-shirt of the second type, then the t-shirt of the first type. He will spend 10 and will not be able to buy the t-shirt of the third type because it costs 4, and the customer will owe only 3. The second customer will buy all three t-shirts (at first, the t-shirt of the second type, then the t-shirt of the first type, and then the t-shirt of the third type). He will spend all money on it. | Input37 53 54 3213 14 | Output2 3 | 4 seconds | 1024 megabytes | ['data structures', '*2800'] |
Subsets and Splits