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
|
---|---|---|---|---|---|
A1. Death Stars (easy)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct. Two rebel spies have provided her with the maps of the solar system. Each map is an N × N grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information.Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out.InputThe first line of the input contains one number N (1 ≤ N ≤ 10) – the dimension of each map. Next N lines each contain N characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next N lines each contain N characters, depicting the second map in the same format.OutputThe only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations.ExamplesInput4XOOOXXOOOOOOXXXXXOOOXOOOXOXOXOXXOutputYesInput2XXOOXOOXOutputNoNoteIn the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. | Input4XOOOXXOOOOOOXXXXXOOOXOOOXOXOXOXX | OutputYes | 1 second | 256 megabytes | ['implementation', '*1400'] |
A. Tritonic Iridescencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOverlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into n consecutive segments, each segment needs to be painted in one of the colours.Arkady has already painted some (possibly none or all) segments and passes the paintbrush to you. You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour. Two ways are considered different if and only if a segment is painted in different colours in them.InputThe first line contains a single positive integer n (1 ≤ n ≤ 100) — the length of the canvas.The second line contains a string s of n characters, the i-th of which is either 'C' (denoting a segment painted in cyan), 'M' (denoting one painted in magenta), 'Y' (one painted in yellow), or '?' (an unpainted one).OutputIf there are at least two different ways of painting, output "Yes"; otherwise output "No" (both without quotes).You can print each character in any case (upper or lower).ExamplesInput5CY??YOutputYesInput5C?C?YOutputYesInput5?CYC?OutputYesInput5C??MMOutputNoInput3MMYOutputNoNoteFor the first example, there are exactly two different ways of colouring: CYCMY and CYMCY.For the second example, there are also exactly two different ways of colouring: CMCMY and CYCMY.For the third example, there are four ways of colouring: MCYCM, MCYCY, YCYCM, and YCYCY.For the fourth example, no matter how the unpainted segments are coloured, the existing magenta segments will prevent the painting from satisfying the requirements. The similar is true for the fifth example. | Input5CY??Y | OutputYes | 1 second | 256 megabytes | ['implementation', '*1300'] |
F. Heapstime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou're given a tree with n vertices rooted at 1.We say that there's a k-ary heap of depth m located at u if the following holds: For m = 1 u itself is a k-ary heap of depth 1. For m > 1 vertex u is a k-ary heap of depth m if at least k of its children are k-ary heaps of depth at least m - 1. Denote dpk(u) as maximum depth of k-ary heap in the subtree of u (including u). Your goal is to compute .InputThe first line contains an integer n denoting the size of the tree (2 ≤ n ≤ 3·105). The next n - 1 lines contain two integers u, v each, describing vertices connected by i-th edge.It's guaranteed that the given configuration forms a tree.OutputOutput the answer to the task.ExamplesInput41 32 34 3Output21Input41 22 33 4Output22NoteConsider sample case one.For k ≥ 3 all dpk will be equal to 1.For k = 2 dpk is 2 if and 1 otherwise.For k = 1 dpk values are (3, 1, 2, 1) respectively.To sum up, 4·1 + 4·1 + 2·2 + 2·1 + 3 + 1 + 2 + 1 = 21. | Input41 32 34 3 | Output21 | 2.5 seconds | 512 megabytes | ['dp', 'trees', '*2600'] |
E. Iciclestime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrew's favourite Krakozyabra has recenly fled away and now he's eager to bring it back!At the moment the refugee is inside an icy cave with n icicles dangling from the ceiling located in integer coordinates numbered from 1 to n. The distance between floor and the i-th icicle is equal to ai.Andrew is free to choose an arbitrary integer point T in range from 1 to n inclusive and at time instant 0 launch a sound wave spreading into both sides (left and right) at the speed of one point per second. Any icicle touched by the wave starts falling at the same speed (that means that in a second the distance from floor to icicle decreases by one but cannot become less that zero). While distance from icicle to floor is more than zero, it is considered passable; as soon as it becomes zero, the icicle blocks the path and prohibits passing.Krakozyabra is initially (i.e. at time instant 0) is located at point and starts running in the right direction at the speed of one point per second. You can assume that events in a single second happen in the following order: first Krakozyabra changes its position, and only then the sound spreads and icicles fall; in particular, that means that if Krakozyabra is currently at point and the falling (i.e. already touched by the sound wave) icicle at point i is 1 point from the floor, then Krakozyabra will pass it and find itself at and only after that the icicle will finally fall and block the path.Krakozyabra is considered entrapped if there are fallen (i.e. with ai = 0) icicles both to the left and to the right of its current position. Help Andrew find the minimum possible time it takes to entrap Krakozyabra by choosing the optimal value of T or report that this mission is impossible.InputThe first line contains the number of icicles n (2 ≤ n ≤ 105).The next line contains n space-separated numbers ai (1 ≤ ai ≤ 105) — the distances from floor to icicles.OutputPrint an only integer — the minimum time it takes to entrap Krakozyabra between two fallen icicles. If it is impossible, print - 1.ExamplesInput51 4 3 5 1Output3Input41 2 1 1Output2Input22 1Output3Input21 2Output-1NoteIn sample case one it's optimal to launch the sound wave from point 3. Then in two seconds icicles 1 and 5 will start falling, and in one more seconds they will block the paths. Krakozyabra will be located at at that time. Note that icicle number 3 will also be fallen, so there will actually be two icicles blocking the path to the left.In sample case two it is optimal to launch the wave from point 2 and entrap Krakozyabra in 2 seconds.In sample case four the answer is impossible. | Input51 4 3 5 1 | Output3 | 2.5 seconds | 256 megabytes | ['*2900'] |
D. Scissorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJenya has recently acquired quite a useful tool — k-scissors for cutting strings. They are generally used for cutting out two non-intersecting substrings of length k from an arbitrary string s (its length should be at least 2·k in order to perform this operation) and concatenating them afterwards (preserving the initial order). For example, with the help of 2-scissors you can cut ab and de out of abcde and concatenate them into abde, but not ab and bc since they're intersecting.It's a nice idea to test this tool before using it in practice. After looking through the papers, Jenya came up with two strings s and t. His question is whether it is possible to apply his scissors to string s such that the resulting concatenation contains t as a substring?InputThe first line contains three integers n, m, k (2 ≤ m ≤ 2·k ≤ n ≤ 5·105) — length of s, length of t and the aforementioned scissors' parameter correspondingly.The next two lines feature s and t consisting of lowercase latin letters.OutputIf there is no answer, print «No». Otherwise print «Yes» and two integers L and R denoting the indexes where cutted substrings start (1-indexed). If there are several possible answers, output any.ExamplesInput7 4 3baabaabaaaaOutputYes1 5Input6 3 2cbcbcbbccOutputYes2 5Input7 5 3aabbaaaaaaaaOutputNoNoteIn the first sample case you can cut out two substrings starting at 1 and 5. The resulting string baaaab contains aaaa as a substring.In the second sample case the resulting string is bccb. | Input7 4 3baabaabaaaa | OutputYes1 5 | 1 second | 256 megabytes | ['brute force', 'strings', '*2600'] |
C. Sad powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given Q queries of the form (L, R). For each query you have to find the number of such x that L ≤ x ≤ R and there exist integer numbers a > 0, p > 1 such that x = ap.InputThe first line contains the number of queries Q (1 ≤ Q ≤ 105).The next Q lines contains two integers L, R each (1 ≤ L ≤ R ≤ 1018).OutputOutput Q lines — the answers to the queries.ExampleInput61 49 95 712 29137 5911 1000000Output2103171111NoteIn query one the suitable numbers are 1 and 4. | Input61 49 95 712 29137 5911 1000000 | Output2103171111 | 2 seconds | 256 megabytes | ['binary search', 'math', 'number theory', '*2100'] |
B. Not simply beatiful stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others — a group of b-s), but cccc is not since in each possible consequent partition letters in these two groups coincide.You're given a string s. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string.InputThe only line contains s (1 ≤ |s| ≤ 105) consisting of lowercase latin letters.OutputPrint «Yes» if the string can be split according to the criteria above or «No» otherwise.Each letter can be printed in arbitrary case.ExamplesInputababaOutputYesInputzzcxxOutputYesInputyeeeOutputNoNoteIn sample case two zzcxx can be split into subsequences zc and zxx each of which is adorable.There's no suitable partition in sample case three. | Inputababa | OutputYes | 1 second | 256 megabytes | ['implementation', '*1400'] |
A. Feed the cattime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.InputThe first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening.The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102).OutputOutput the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4.Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .ExamplesInput19 00255 1 100 1Output25200.0000Input17 411000 6 15 11Output1365.0000NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles. | Input19 00255 1 100 1 | Output25200.0000 | 1 second | 256 megabytes | ['greedy', 'math', '*1100'] |
I. Yet Another String Matching Problemtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you have two strings s and t, and their length is equal. You may perform the following operation any number of times: choose two different characters c1 and c2, and replace every occurence of c1 in both strings with c2. Let's denote the distance between strings s and t as the minimum number of operations required to make these strings equal. For example, if s is abcd and t is ddcb, the distance between them is 2 — we may replace every occurence of a with b, so s becomes bbcd, and then we may replace every occurence of b with d, so both strings become ddcd.You are given two strings S and T. For every substring of S consisting of |T| characters you have to determine the distance between this substring and T.InputThe first line contains the string S, and the second — the string T (1 ≤ |T| ≤ |S| ≤ 125000). Both strings consist of lowercase Latin letters from a to f.OutputPrint |S| - |T| + 1 integers. The i-th of these integers must be equal to the distance between the substring of S beginning at i-th index with length |T| and the string T.ExampleInputabcdefaddcbOutput2 3 3 3 | Inputabcdefaddcb | Output2 3 3 3 | 4 seconds | 256 megabytes | ['fft', 'math', '*2200'] |
H. Path Countingtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree. Let's denote d(x) as depth of node x: depth of the root is 1, depth of any other node x is d(y) + 1, where y is a parent of x.The tree has the following property: every node x with d(x) = i has exactly ai children. Maximum possible depth of a node is n, and an = 0.We define fk as the number of unordered pairs of vertices in the tree such that the number of edges on the simple path between them is equal to k.Calculate fk modulo 109 + 7 for every 1 ≤ k ≤ 2n - 2.InputThe first line of input contains an integer n (2 ≤ n ≤ 5 000) — the maximum depth of a node.The second line of input contains n - 1 integers a1, a2, ..., an - 1 (2 ≤ ai ≤ 109), where ai is the number of children of every node x such that d(x) = i. Since an = 0, it is not given in the input.OutputPrint 2n - 2 numbers. The k-th of these numbers must be equal to fk modulo 109 + 7.ExamplesInput42 2 2Output14 19 20 20 16 16 Input32 3Output8 13 6 9 NoteThis the tree from the first sample: | Input42 2 2 | Output14 19 20 20 16 16 | 5 seconds | 256 megabytes | ['combinatorics', 'dp', '*2500'] |
G. Castle Defensetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday you are going to lead a group of elven archers to defend the castle that is attacked by an army of angry orcs. Three sides of the castle are protected by impassable mountains and the remaining side is occupied by a long wall that is split into n sections. At this moment there are exactly ai archers located at the i-th section of this wall. You know that archer who stands at section i can shoot orcs that attack section located at distance not exceeding r, that is all such sections j that |i - j| ≤ r. In particular, r = 0 means that archers are only capable of shooting at orcs who attack section i.Denote as defense level of section i the total number of archers who can shoot at the orcs attacking this section. Reliability of the defense plan is the minimum value of defense level of individual wall section.There is a little time left till the attack so you can't redistribute archers that are already located at the wall. However, there is a reserve of k archers that you can distribute among wall sections in arbitrary way. You would like to achieve maximum possible reliability of the defence plan.InputThe first line of the input contains three integers n, r and k (1 ≤ n ≤ 500 000, 0 ≤ r ≤ n, 0 ≤ k ≤ 1018) — the number of sections of the wall, the maximum distance to other section archers can still shoot and the number of archers yet to be distributed along the wall. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the current number of archers at each section.OutputPrint one integer — the maximum possible value of defense plan reliability, i.e. the maximum possible value of minimum defense level if we distribute k additional archers optimally.ExamplesInput5 0 65 4 3 4 9Output5Input4 2 01 2 3 4Output6Input5 1 12 1 2 1 2Output3 | Input5 0 65 4 3 4 9 | Output5 | 1.5 seconds | 256 megabytes | ['binary search', 'data structures', 'greedy', 'two pointers', '*2000'] |
F. Runner's Problemtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are running through a rectangular field. This field can be represented as a matrix with 3 rows and m columns. (i, j) denotes a cell belonging to i-th row and j-th column.You start in (2, 1) and have to end your path in (2, m). From the cell (i, j) you may advance to: (i - 1, j + 1) — only if i > 1, (i, j + 1), or (i + 1, j + 1) — only if i < 3. However, there are n obstacles blocking your path. k-th obstacle is denoted by three integers ak, lk and rk, and it forbids entering any cell (ak, j) such that lk ≤ j ≤ rk.You have to calculate the number of different paths from (2, 1) to (2, m), and print it modulo 109 + 7.InputThe first line contains two integers n and m (1 ≤ n ≤ 104, 3 ≤ m ≤ 1018) — the number of obstacles and the number of columns in the matrix, respectively.Then n lines follow, each containing three integers ak, lk and rk (1 ≤ ak ≤ 3, 2 ≤ lk ≤ rk ≤ m - 1) denoting an obstacle blocking every cell (ak, j) such that lk ≤ j ≤ rk. Some cells may be blocked by multiple obstacles.OutputPrint the number of different paths from (2, 1) to (2, m), taken modulo 109 + 7. If it is impossible to get from (2, 1) to (2, m), then the number of paths is 0.ExampleInput2 51 3 42 2 3Output2 | Input2 51 3 42 2 3 | Output2 | 4 seconds | 256 megabytes | ['dp', 'matrices', 'sortings', '*2100'] |
E. Water Tapstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a system of n water taps all pouring water into the same container. The i-th water tap can be set to deliver any amount of water from 0 to ai ml per second (this amount may be a real number). The water delivered by i-th tap has temperature ti.If for every you set i-th tap to deliver exactly xi ml of water per second, then the resulting temperature of water will be (if , then to avoid division by zero we state that the resulting water temperature is 0).You have to set all the water taps in such a way that the resulting temperature is exactly T. What is the maximum amount of water you may get per second if its temperature has to be T?InputThe first line contains two integers n and T (1 ≤ n ≤ 200000, 1 ≤ T ≤ 106) — the number of water taps and the desired temperature of water, respectively.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) where ai is the maximum amount of water i-th tap can deliver per second.The third line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 106) — the temperature of water each tap delivers.OutputPrint the maximum possible amount of water with temperature exactly T you can get per second (if it is impossible to obtain water with such temperature, then the answer is considered to be 0).Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6.ExamplesInput2 1003 1050 150Output6.000000000000000Input3 95 5 306 6 10Output40.000000000000000Input2 121 310 15Output1.666666666666667 | Input2 1003 1050 150 | Output6.000000000000000 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'sortings', '*2000'] |
D. Fight Against Traffictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease. You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.InputThe firt line of the input contains integers n, m, s and t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 1000, 1 ≤ s, t ≤ n, s ≠ t) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.OutputPrint one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.ExamplesInput5 4 1 51 22 33 44 5Output0Input5 4 3 51 22 33 44 5Output5Input5 6 1 51 21 31 44 53 52 5Output3 | Input5 4 1 51 22 33 44 5 | Output0 | 1 second | 256 megabytes | ['dfs and similar', 'graphs', 'shortest paths', '*1600'] |
C. Matrix Walktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a matrix A of size x × y filled with integers. For every , Ai, j = y(i - 1) + j. Obviously, every integer from [1..xy] occurs exactly once in this matrix. You have traversed some path in this matrix. Your path can be described as a sequence of visited cells a1, a2, ..., an denoting that you started in the cell containing the number a1, then moved to the cell with the number a2, and so on.From the cell located in i-th line and j-th column (we denote this cell as (i, j)) you can move into one of the following cells: (i + 1, j) — only if i < x; (i, j + 1) — only if j < y; (i - 1, j) — only if i > 1; (i, j - 1) — only if j > 1.Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know x and y exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer a1, then move to the cell containing a2 (in one step), then move to the cell containing a3 (also in one step) and so on. Can you choose x and y so that they don't contradict with your sequence of moves?InputThe first line contains one integer number n (1 ≤ n ≤ 200000) — the number of cells you visited on your path (if some cell is visited twice, then it's listed twice).The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers in the cells on your path.OutputIf all possible values of x and y such that 1 ≤ x, y ≤ 109 contradict with the information about your path, print NO.Otherwise, print YES in the first line, and in the second line print the values x and y such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.ExamplesInput81 2 3 6 9 8 5 2OutputYES3 3Input61 2 1 2 5 3OutputNOInput21 10OutputYES4 9NoteThe matrix and the path on it in the first test looks like this: Also there exist multiple correct answers for both the first and the third examples. | Input81 2 3 6 9 8 5 2 | OutputYES3 3 | 1 second | 256 megabytes | ['implementation', '*1700'] |
B. String Typingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard.Initially, you have an empty string. Until you type the whole string, you may perform the following operation: add a character to the end of the string. Besides, at most once you may perform one additional operation: copy the string and append it to itself.For example, if you have to type string abcabca, you can type it in 7 operations if you type all the characters one by one. However, you can type it in 5 operations if you type the string abc first and then copy it and type the last character.If you have to type string aaaaaaaaa, the best option is to type 4 characters one by one, then copy the string, and then type the remaining character.Print the minimum number of operations you need to type the given string.InputThe first line of the input containing only one integer number n (1 ≤ n ≤ 100) — the length of the string you have to type. The second line containing the string s consisting of n lowercase Latin letters.OutputPrint one integer number — the minimum number of operations you need to type the given string.ExamplesInput7abcabcaOutput5Input8abcdefghOutput8NoteThe first test described in the problem statement.In the second test you can only type all the characters one by one. | Input7abcabca | Output5 | 1 second | 256 megabytes | ['implementation', 'strings', '*1400'] |
A. Diagonal Walkingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.Your problem is to print the minimum possible length of the sequence of moves after the replacements.InputThe first line of the input contains one integer n (1 ≤ n ≤ 100) — the length of the sequence. The second line contains the sequence consisting of n characters U and R.OutputPrint the minimum possible length of the sequence of moves after all replacements are done.ExamplesInput5RUURUOutput3Input17UUURRRRRUUURURUUUOutput13NoteIn the first test the shortened sequence of moves may be DUD (its length is 3).In the second test the shortened sequence of moves can be UUDRRRDUDDUUU (its length is 13). | Input5RUURU | Output3 | 1 second | 256 megabytes | ['implementation', '*800'] |
G. Puzzling Languagetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you will write a simple code generator for a 2D programming language derived from Brainfuck.The code in this language is a rectangular grid of characters '.' and 'X'. The code is converted to a Brainfuck program as follows: the characters are read in the usual order (top to bottom, left to right), and each 'X' character is converted a Brainfuck instruction to be executed. The instruction is defined by the left, top and right neighbors of the 'X' character using the following conversion table: You are given a string. Output a program in the described language which prints this string.You can download the language interpreter used for judging here: https://assets.codeforces.com/rounds/952/puzzling-interpreter.cpp (use C++11 to compile the code). Note several implementation details: The first step of the language interpretation is conversion to a Brainfuck program, which is then executed. The code must be rectangular, with all lines of the same length. It can have at most 10,000 lines and 10,000 columns, and can have at most 500,000 'X' characters. The code has toroidal topology, i.e. the 'X' on the first line will have top neighbor in the last line. Brainfuck interpreter has 30000 memory cells which store integers from 0 to 255 with increment/decrement done modulo 256. Console input (, command) is allowed in Brainfuck code but has no effect when executed.InputThe input consists of a single string of characters with ASCII codes between 33 ('!') and 122 ('z'), inclusive. The length of the string is between 1 and 10 characters, inclusive.OutputOutput a program in the described language which, when executed, will print the given message.ExampleInputOutput.......X.............XXX...........XXXXX.........XXXXXXX.......XXXXXXXXX.....XXXXXXXXXXX...XXXXXXXXXXXXX................X.............XX..............X..............X..............NoteThe example corresponds to the following Brainfuck program: - >+< >+++< >+++++< >+++++++< >+++++++++< >+++++++++++<< >...The triangular block decrements the first memory cell and sets the value of the second memory cell to 36 - the ASCII code of '$' character. The next line after the triangular block moves the memory pointer to the second memory cell, and the next three lines print the '$' character three times. | Input$$$ | Output.......X.............XXX...........XXXXX.........XXXXXXX.......XXXXXXXXX.....XXXXXXXXXXX...XXXXXXXXXXXXX................X.............XX..............X..............X.............. | 1 second | 256 megabytes | ['constructive algorithms', '*2200'] |
F. 2 + 2 != 4time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne very experienced problem writer decided to prepare a problem for April Fools Day contest. The task was very simple - given an arithmetic expression, return the result of evaluating this expression. However, looks like there is a bug in the reference solution...InputThe only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive.OutputReproduce the output of the reference solution, including the bug.ExamplesInput8-7+6-5+4-3+2-1-0Output4Input2+2Output-46Input112-37Output375 | Input8-7+6-5+4-3+2-1-0 | Output4 | 1 second | 256 megabytes | ['*2400'] |
E. Cheese Boardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNot to be confused with chessboard. InputThe first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have.The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct.OutputOutput a single number.ExamplesInput9brie softcamembert softfeta softgoat softmuenster softasiago hardcheddar hardgouda hardswiss hardOutput3Input6parmesan hardemmental hardedam hardcolby hardgruyere hardasiago hardOutput4 | Input9brie softcamembert softfeta softgoat softmuenster softasiago hardcheddar hardgouda hardswiss hard | Output3 | 1 second | 256 megabytes | ['*2000'] |
C. Ravioli Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody knows of spaghetti sort. You decided to implement an analog sorting algorithm yourself, but as you survey your pantry you realize you're out of spaghetti! The only type of pasta you have is ravioli, but you are not going to let this stop you...You come up with the following algorithm. For each number in the array ai, build a stack of ai ravioli. The image shows the stack for ai = 4. Arrange the stacks in one row in the order in which the corresponding numbers appear in the input array. Find the tallest one (if there are several stacks of maximal height, use the leftmost one). Remove it and add its height to the end of the output array. Shift the stacks in the row so that there is no gap between them. Repeat the procedure until all stacks have been removed.At first you are very happy with your algorithm, but as you try it on more inputs you realize that it doesn't always produce the right sorted array. Turns out when two stacks of ravioli are next to each other (at any step of the process) and differ in height by two or more, the top ravioli of the taller stack slides down on top of the lower stack.Given an input array, figure out whether the described algorithm will sort it correctly.InputThe first line of input contains a single number n (1 ≤ n ≤ 10) — the size of the array.The second line of input contains n space-separated integers ai (1 ≤ ai ≤ 100) — the elements of the array.OutputOutput "YES" if the array can be sorted using the described procedure and "NO" if it can not.ExamplesInput31 2 3OutputYESInput33 1 2OutputNONoteIn the second example the array will change even before the tallest stack is chosen for the first time: ravioli from stack of height 3 will slide on the stack of height 1, and the algorithm will output an array {2, 2, 2}. | Input31 2 3 | OutputYES | 1 second | 256 megabytes | ['implementation', '*1600'] |
A. Quirky Quantifierstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputInputThe input contains a single integer a (10 ≤ a ≤ 999).OutputOutput 0 or 1.ExamplesInput13Output1Input927Output1Input48Output0 | Input13 | Output1 | 2 seconds | 64 megabytes | ['math', '*800'] |
B. Intercepted Messagetime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputHacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information.Zhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred through the network: if an archive consists of k files of sizes l1, l2, ..., lk bytes, then the i-th file is split to one or more blocks bi, 1, bi, 2, ..., bi, mi (here the total length of the blocks bi, 1 + bi, 2 + ... + bi, mi is equal to the length of the file li), and after that all blocks are transferred through the network, maintaining the order of files in the archive.Zhorik thinks that the two messages contain the same archive, because their total lengths are equal. However, each file can be split in blocks in different ways in the two messages.You are given the lengths of blocks in each of the two messages. Help Zhorik to determine what is the maximum number of files could be in the archive, if the Zhorik's assumption is correct.InputThe first line contains two integers n, m (1 ≤ n, m ≤ 105) — the number of blocks in the first and in the second messages.The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 106) — the length of the blocks that form the first message.The third line contains m integers y1, y2, ..., ym (1 ≤ yi ≤ 106) — the length of the blocks that form the second message.It is guaranteed that x1 + ... + xn = y1 + ... + ym. Also, it is guaranteed that x1 + ... + xn ≤ 106.OutputPrint the maximum number of files the intercepted array could consist of.ExamplesInput7 62 5 3 1 11 4 47 8 2 4 1 8Output3Input3 31 10 1001 100 10Output2Input1 441 1 1 1Output1NoteIn the first example the maximum number of files in the archive is 3. For example, it is possible that in the archive are three files of sizes 2 + 5 = 7, 15 = 3 + 1 + 11 = 8 + 2 + 4 + 1 and 4 + 4 = 8.In the second example it is possible that the archive contains two files of sizes 1 and 110 = 10 + 100 = 100 + 10. Note that the order of files is kept while transferring archives through the network, so we can't say that there are three files of sizes 1, 10 and 100.In the third example the only possibility is that the archive contains a single file of size 4. | Input7 62 5 3 1 11 4 47 8 2 4 1 8 | Output3 | 1 second | 512 megabytes | ['greedy', 'implementation', '*1100'] |
A. Left-handers, Right-handers and Ambidexterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand.The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactly half of the players should play with their left hand. One player should use only on of his hands.Ambidexters play as well with their right hand as with their left hand. In the team, an ambidexter can play with their left hand, or with their right hand.Please find the maximum possible size of the team, where equal number of players use their left and right hands, respectively.InputThe only line contains three integers l, r and a (0 ≤ l, r, a ≤ 100) — the number of left-handers, the number of right-handers and the number of ambidexters at the training. OutputPrint a single even integer — the maximum number of players in the team. It is possible that the team can only have zero number of players.ExamplesInput1 4 2Output6Input5 5 5Output14Input0 2 0Output0NoteIn the first example you can form a team of 6 players. You should take the only left-hander and two ambidexters to play with left hand, and three right-handers to play with right hand. The only person left can't be taken into the team.In the second example you can form a team of 14 people. You have to take all five left-handers, all five right-handers, two ambidexters to play with left hand and two ambidexters to play with right hand. | Input1 4 2 | Output6 | 1 second | 256 megabytes | ['implementation', 'math', '*800'] |
E. Binary Cardstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt is never too late to play the fancy "Binary Cards" game!There is an infinite amount of cards of positive and negative ranks that are used in the game. The absolute value of any card rank is a power of two, i.e. each card has a rank of either 2k or - 2k for some integer k ≥ 0. There is an infinite amount of cards of any valid rank.At the beginning of the game player forms his deck that is some multiset (possibly empty) of cards. It is allowed to pick any number of cards of any rank but the small deck is considered to be a skill indicator. Game consists of n rounds. In the i-th round jury tells the player an integer ai. After that the player is obligated to draw such a subset of his deck that the sum of ranks of the chosen cards is equal to ai (it is allowed to not draw any cards, in which case the sum is considered to be equal to zero). If player fails to do so, he loses and the game is over. Otherwise, player takes back all of his cards into his deck and the game proceeds to the next round. Player is considered a winner if he is able to draw the suitable set of cards in each of the rounds.Somebody told you which numbers ai the jury is going to tell you in each round. Now you want to pick a deck consisting of the minimum number of cards that allows you to win the "Binary Cards" game.InputThe first line of input contains an integer n (1 ≤ n ≤ 100 000), the number of rounds in the game.The second line of input contains n integers a1, a2, ..., an ( - 100 000 ≤ ai ≤ 100 000), the numbers that jury is going to tell in each round.OutputIn the first line print the integer k (0 ≤ k ≤ 100 000), the minimum number of cards you have to pick in your deck in ordered to win the "Binary Cards".In the second line print k integers b1, b2, ..., bk ( - 220 ≤ bi ≤ 220, |bi| is a power of two), the ranks of the cards in your deck. You may output ranks in any order. If there are several optimum decks, you are allowed to print any of them.It is guaranteed that there exists a deck of minimum size satisfying all the requirements above.ExamplesInput19Output21 8Input5-1 3 0 4 7Output34 -1 4Input42 -2 14 18Output3-2 2 16NoteIn the first sample there is the only round in the game, in which you may simply draw both your cards. Note that this sample test is the only one satisfying the first test group constraints.In the second sample you may draw the only card - 1 in the first round, cards 4 and - 1 in the second round, nothing in the third round, the only card 4 in the fourth round and the whole deck in the fifth round. | Input19 | Output21 8 | 1 second | 512 megabytes | ['brute force', '*2700'] |
D. Curfewtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputInstructors of Some Informatics School make students go to bed.The house contains n rooms, in each room exactly b students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to n. Initially, in i-th room there are ai students. All students are currently somewhere in the house, therefore a1 + a2 + ... + an = nb. Also 2 instructors live in this house.The process of curfew enforcement is the following. One instructor starts near room 1 and moves toward room n, while the second instructor starts near room n and moves toward room 1. After processing current room, each instructor moves on to the next one. Both instructors enter rooms and move simultaneously, if n is odd, then only the first instructor processes the middle room. When all rooms are processed, the process ends.When an instructor processes a room, she counts the number of students in the room, then turns off the light, and locks the room. Also, if the number of students inside the processed room is not equal to b, the instructor writes down the number of this room into her notebook (and turns off the light, and locks the room). Instructors are in a hurry (to prepare the study plan for the next day), so they don't care about who is in the room, but only about the number of students.While instructors are inside the rooms, students can run between rooms that are not locked and not being processed. A student can run by at most d rooms, that is she can move to a room with number that differs my at most d. Also, after (or instead of) running each student can hide under a bed in a room she is in. In this case the instructor will not count her during the processing. In each room any number of students can hide simultaneously.Formally, here is what's happening: A curfew is announced, at this point in room i there are ai students. Each student can run to another room but not further than d rooms away from her initial room, or stay in place. After that each student can optionally hide under a bed. Instructors enter room 1 and room n, they count students there and lock the room (after it no one can enter or leave this room). Each student from rooms with numbers from 2 to n - 1 can run to another room but not further than d rooms away from her current room, or stay in place. Each student can optionally hide under a bed. Instructors move from room 1 to room 2 and from room n to room n - 1. This process continues until all rooms are processed. Let x1 denote the number of rooms in which the first instructor counted the number of non-hidden students different from b, and x2 be the same number for the second instructor. Students know that the principal will only listen to one complaint, therefore they want to minimize the maximum of numbers xi. Help them find this value if they use the optimal strategy.InputThe first line contains three integers n, d and b (2 ≤ n ≤ 100 000, 1 ≤ d ≤ n - 1, 1 ≤ b ≤ 10 000), number of rooms in the house, running distance of a student, official number of students in a room.The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109), i-th of which stands for the number of students in the i-th room before curfew announcement.It is guaranteed that a1 + a2 + ... + an = nb.OutputOutput one integer, the minimal possible value of the maximum of xi.ExamplesInput5 1 11 0 0 0 4Output1Input6 1 23 8 0 1 0 0Output2NoteIn the first sample the first three rooms are processed by the first instructor, and the last two are processed by the second instructor. One of the optimal strategies is the following: firstly three students run from room 5 to room 4, on the next stage two of them run to room 3, and one of those two hides under a bed. This way, the first instructor writes down room 2, and the second writes down nothing.In the second sample one of the optimal strategies is the following: firstly all students in room 1 hide, all students from room 2 run to room 3. On the next stage one student runs from room 3 to room 4, and 5 students hide. This way, the first instructor writes down rooms 1 and 2, the second instructor writes down rooms 5 and 6. | Input5 1 11 0 0 0 4 | Output1 | 2 seconds | 512 megabytes | ['binary search', 'brute force', 'greedy', 'sortings', '*2300'] |
C. Data Center Maintenancetime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputBigData Inc. is a corporation that has n data centers indexed from 1 to n that are located all over the world. These data centers provide storage for client data (you can figure out that client data is really big!).Main feature of services offered by BigData Inc. is the access availability guarantee even under the circumstances of any data center having an outage. Such a guarantee is ensured by using the two-way replication. Two-way replication is such an approach for data storage that any piece of data is represented by two identical copies that are stored in two different data centers.For each of m company clients, let us denote indices of two different data centers storing this client data as ci, 1 and ci, 2.In order to keep data centers operational and safe, the software running on data center computers is being updated regularly. Release cycle of BigData Inc. is one day meaning that the new version of software is being deployed to the data center computers each day.Data center software update is a non-trivial long process, that is why there is a special hour-long time frame that is dedicated for data center maintenance. During the maintenance period, data center computers are installing software updates, and thus they may be unavailable. Consider the day to be exactly h hours long. For each data center there is an integer uj (0 ≤ uj ≤ h - 1) defining the index of an hour of day, such that during this hour data center j is unavailable due to maintenance.Summing up everything above, the condition uci, 1 ≠ uci, 2 should hold for each client, or otherwise his data may be unaccessible while data centers that store it are under maintenance.Due to occasional timezone change in different cities all over the world, the maintenance time in some of the data centers may change by one hour sometimes. Company should be prepared for such situation, that is why they decided to conduct an experiment, choosing some non-empty subset of data centers, and shifting the maintenance time for them by an hour later (i.e. if uj = h - 1, then the new maintenance hour would become 0, otherwise it would become uj + 1). Nonetheless, such an experiment should not break the accessibility guarantees, meaning that data of any client should be still available during any hour of a day after the data center maintenance times are changed.Such an experiment would provide useful insights, but changing update time is quite an expensive procedure, that is why the company asked you to find out the minimum number of data centers that have to be included in an experiment in order to keep the data accessibility guarantees.InputThe first line of input contains three integers n, m and h (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000, 2 ≤ h ≤ 100 000), the number of company data centers, number of clients and the day length of day measured in hours. The second line of input contains n integers u1, u2, ..., un (0 ≤ uj < h), j-th of these numbers is an index of a maintenance hour for data center j. Each of the next m lines contains two integers ci, 1 and ci, 2 (1 ≤ ci, 1, ci, 2 ≤ n, ci, 1 ≠ ci, 2), defining the data center indices containing the data of client i.It is guaranteed that the given maintenance schedule allows each client to access at least one copy of his data at any moment of day.OutputIn the first line print the minimum possible number of data centers k (1 ≤ k ≤ n) that have to be included in an experiment in order to keep the data available for any client.In the second line print k distinct integers x1, x2, ..., xk (1 ≤ xi ≤ n), the indices of data centers whose maintenance time will be shifted by one hour later. Data center indices may be printed in any order.If there are several possible answers, it is allowed to print any of them. It is guaranteed that at there is at least one valid choice of data centers.ExamplesInput3 3 54 4 01 33 23 1Output13 Input4 5 42 1 0 34 33 21 21 41 3Output41 2 3 4 NoteConsider the first sample test. The given answer is the only way to conduct an experiment involving the only data center. In such a scenario the third data center has a maintenance during the hour 1, and no two data centers storing the information of the same client have maintenance at the same hour.On the other hand, for example, if we shift the maintenance time on hour later for the first data center, then the data of clients 1 and 3 will be unavailable during the hour 0. | Input3 3 54 4 01 33 23 1 | Output13 | 1 second | 512 megabytes | ['dfs and similar', 'graphs', '*1900'] |
B. A Leapfrog in the Arraytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows: You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes.InputThe first line contains two integers n and q (1 ≤ n ≤ 1018, 1 ≤ q ≤ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer.Next q lines contain integers xi (1 ≤ xi ≤ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes.OutputFor each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes.ExamplesInput4 3234Output324Input13 410548Output13389NoteThe first example is shown in the picture.In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7]. | Input4 3234 | Output324 | 2 seconds | 512 megabytes | ['constructive algorithms', 'math', '*1700'] |
A. Zebrastime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputOleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days. InputIn the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200 000 characters.OutputIf there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1 ≤ k ≤ |s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1 ≤ li ≤ |s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1.Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.ExamplesInput0010100Output33 1 3 43 2 5 61 7Input111Output-1 | Input0010100 | Output33 1 3 43 2 5 61 7 | 1 second | 512 megabytes | ['greedy', '*1600'] |
A. Protect Sheeptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number. InputFirst line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively.Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.OutputIf it is impossible to protect all sheep, output a single line with the word "No".Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf.If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.ExamplesInput6 6..S.....S.W..S......W......W........OutputYes..SD....SDW..SD....DW...DD.W........Input1 2SWOutputNoInput5 5.S......S.S.......S..S...OutputYes.S......S.S.D.....S..S...NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him. | Input6 6..S.....S.W..S......W......W........ | OutputYes..SD....SDW..SD....DW...DD.W........ | 1 second | 256 megabytes | ['brute force', 'dfs and similar', 'graphs', 'implementation', '*900'] |
G. Almost Increasing Arraytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe call an array almost increasing if we can erase not more than one element from it so that the array becomes strictly increasing (that is, every element is striclty greater than every element before it).You are given an array a consisting of n elements. You are allowed to replace any element with any integer number (and you may do so any number of times you need). What is the minimum number of replacements you have to perform in order to make the array almost increasing?InputThe first line contains one integer n (2 ≤ n ≤ 200000) — the number of elements in a.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the array a.OutputPrint the minimum number of replaces you have to perform so that a is almost increasing.ExamplesInput55 4 3 2 1Output3Input51 2 8 9 5Output0 | Input55 4 3 2 1 | Output3 | 3 seconds | 512 megabytes | ['data structures', 'dp', '*2500'] |
F. Fibonacci String Subsequencestime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s (each character of this string is either 0 or 1).Let's denote the cost of string t as the number of occurences of s in t. For example, if s is 11 and t is 111011, then the cost of t is 3.Let's also denote the Fibonacci strings sequence as follows: F(0) is 0; F(1) is 1; F(i) = F(i - 1) + F(i - 2) if i > 1, where + means the concatenation of two strings.Your task is to calculate the sum of costs of all subsequences of the string F(x). Since answer may be large, calculate it modulo 109 + 7.InputThe first line contains two integers n and x (1 ≤ n ≤ 100, 0 ≤ x ≤ 100) — the length of s and the index of a Fibonacci string you are interested in, respectively.The second line contains s — a string consisting of n characters. Each of these characters is either 0 or 1.OutputPrint the only integer — the sum of costs of all subsequences of the string F(x), taken modulo 109 + 7. ExamplesInput2 411Output14Input10 1001010101010Output553403224 | Input2 411 | Output14 | 3.5 seconds | 256 megabytes | ['combinatorics', 'dp', 'matrices', '*2400'] |
E. Largest Beautiful Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYes, that's another problem with definition of "beautiful" numbers.Let's call a positive integer x beautiful if its decimal representation without leading zeroes contains even number of digits, and there exists a permutation of this representation which is palindromic. For example, 4242 is a beautiful number, since it contains 4 digits, and there exists a palindromic permutation 2442.Given a positive integer s, find the largest beautiful number which is less than s.InputThe first line contains one integer t (1 ≤ t ≤ 105) — the number of testcases you have to solve.Then t lines follow, each representing one testcase and containing one string which is the decimal representation of number s. It is guaranteed that this string has even length, contains no leading zeroes, and there exists at least one beautiful number less than s.The sum of lengths of s over all testcases doesn't exceed 2·105.OutputFor each testcase print one line containing the largest beautiful number which is less than s (it is guaranteed that the answer exists).ExampleInput48988100028923845Output88779928923839 | Input48988100028923845 | Output88779928923839 | 1 second | 256 megabytes | ['greedy', 'implementation', '*2200'] |
D. Timetabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th hour, and last lesson is during j-th hour, then he spends j - i + 1 hours in the university during this day. If there are no lessons during some day, then Ivan stays at home and therefore spends 0 hours in the university.Ivan doesn't like to spend a lot of time in the university, so he has decided to skip some lessons. He cannot skip more than k lessons during the week. After deciding which lessons he should skip and which he should attend, every day Ivan will enter the university right before the start of the first lesson he does not skip, and leave it after the end of the last lesson he decides to attend. If Ivan skips all lessons during some day, he doesn't go to the university that day at all.Given n, m, k and Ivan's timetable, can you determine the minimum number of hours he has to spend in the university during one week, if he cannot skip more than k lessons?InputThe first line contains three integers n, m and k (1 ≤ n, m ≤ 500, 0 ≤ k ≤ 500) — the number of days in the Berland week, the number of working hours during each day, and the number of lessons Ivan can skip, respectively.Then n lines follow, i-th line containing a binary string of m characters. If j-th character in i-th line is 1, then Ivan has a lesson on i-th day during j-th hour (if it is 0, there is no such lesson).OutputPrint the minimum number of hours Ivan has to spend in the university during the week if he skips not more than k lessons.ExamplesInput2 5 10100110110Output5Input2 5 00100110110Output8NoteIn the first example Ivan can skip any of two lessons during the first day, so he spends 1 hour during the first day and 4 hours during the second day.In the second example Ivan can't skip any lessons, so he spends 4 hours every day. | Input2 5 10100110110 | Output5 | 2 seconds | 256 megabytes | ['dp', '*1800'] |
C. String Transformationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of |s| small english letters.In one move you can replace any character of this string to the next character in alphabetical order (a will be replaced with b, s will be replaced with t, etc.). You cannot replace letter z with any other letter.Your target is to make some number of moves (not necessary minimal) to get string abcdefghijklmnopqrstuvwxyz (english alphabet) as a subsequence. Subsequence of the string is the string that is obtained by deleting characters at some positions. You need to print the string that will be obtained from the given string and will be contain english alphabet as a subsequence or say that it is impossible.InputThe only one line of the input consisting of the string s consisting of |s| (1 ≤ |s| ≤ 105) small english letters.OutputIf you can get a string that can be obtained from the given string and will contain english alphabet as a subsequence, print it. Otherwise print «-1» (without quotes).ExamplesInputaacceeggiikkmmooqqssuuwwyyOutputabcdefghijklmnopqrstuvwxyzInputthereisnoanswerOutput-1 | Inputaacceeggiikkmmooqqssuuwwyy | Outputabcdefghijklmnopqrstuvwxyz | 1 second | 256 megabytes | ['greedy', 'strings', '*1300'] |
B. Weird Subtraction Processtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have two variables a and b. Consider the following sequence of actions performed with these variables: If a = 0 or b = 0, end the process. Otherwise, go to step 2; If a ≥ 2·b, then set the value of a to a - 2·b, and repeat step 1. Otherwise, go to step 3; If b ≥ 2·a, then set the value of b to b - 2·a, and repeat step 1. Otherwise, end the process.Initially the values of a and b are positive integers, and so the process will be finite.You have to determine the values of a and b after the process ends.InputThe only line of the input contains two integers n and m (1 ≤ n, m ≤ 1018). n is the initial value of variable a, and m is the initial value of variable b.OutputPrint two integers — the values of a and b after the end of the process.ExamplesInput12 5Output0 1Input31 12Output7 12NoteExplanations to the samples: a = 12, b = 5 a = 2, b = 5 a = 2, b = 1 a = 0, b = 1; a = 31, b = 12 a = 7, b = 12. | Input12 5 | Output0 1 | 1 second | 256 megabytes | ['math', 'number theory', '*1100'] |
A. Partitiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of B - C?InputThe first line contains one integer n (1 ≤ n ≤ 100) — the number of elements in a.The second line contains n integers a1, a2, ..., an ( - 100 ≤ ai ≤ 100) — the elements of sequence a.OutputPrint the maximum possible value of B - C, where B is the sum of elements of sequence b, and C is the sum of elements of sequence c.ExamplesInput31 -2 0Output3Input616 23 16 15 42 8Output120NoteIn the first example we may choose b = {1, 0}, c = { - 2}. Then B = 1, C = - 2, B - C = 3.In the second example we choose b = {16, 23, 16, 15, 42, 8}, c = {} (an empty sequence). Then B = 120, C = 0, B - C = 120. | Input31 -2 0 | Output3 | 1 second | 256 megabytes | ['greedy', '*800'] |
F. Machine Learningtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou come home and fell some unpleasant smell. Where is it coming from?You are given an array a. You have to answer the following queries: You are given two integers l and r. Let ci be the number of occurrences of i in al: r, where al: r is the subarray of a from l-th element to r-th inclusive. Find the Mex of {c0, c1, ..., c109} You are given two integers p to x. Change ap to x. The Mex of a multiset of numbers is the smallest non-negative integer not in the set.Note that in this problem all elements of a are positive, which means that c0 = 0 and 0 is never the answer for the query of the second type.InputThe first line of input contains two integers n and q (1 ≤ n, q ≤ 100 000) — the length of the array and the number of queries respectively.The second line of input contains n integers — a1, a2, ..., an (1 ≤ ai ≤ 109).Each of the next q lines describes a single query.The first type of query is described by three integers ti = 1, li, ri, where 1 ≤ li ≤ ri ≤ n — the bounds of the subarray.The second type of query is described by three integers ti = 2, pi, xi, where 1 ≤ pi ≤ n is the index of the element, which must be changed and 1 ≤ xi ≤ 109 is the new value.OutputFor each query of the first type output a single integer — the Mex of {c0, c1, ..., c109}.ExampleInput10 41 2 3 1 1 2 2 2 9 91 1 11 2 82 7 11 2 8Output232NoteThe subarray of the first query consists of the single element — 1. The subarray of the second query consists of four 2s, one 3 and two 1s.The subarray of the fourth query consists of three 1s, three 2s and one 3. | Input10 41 2 3 1 1 2 2 2 9 91 1 11 2 82 7 11 2 8 | Output232 | 4 seconds | 512 megabytes | ['brute force', 'data structures', '*2600'] |
E. Cashbacktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSince you are the best Wraith King, Nizhniy Magazin «Mir» at the centre of Vinnytsia is offering you a discount.You are given an array a of length n and an integer c. The value of some array b of length k is the sum of its elements except for the smallest. For example, the value of the array [3, 1, 6, 5, 2] with c = 2 is 3 + 6 + 5 = 14.Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.InputThe first line contains integers n and c (1 ≤ n, c ≤ 100 000).The second line contains n integers ai (1 ≤ ai ≤ 109) — elements of a.OutputOutput a single integer — the smallest possible sum of values of these subarrays of some partition of a.ExamplesInput3 51 2 3Output6Input12 101 1 10 10 10 10 10 10 9 10 10 10Output92Input7 22 3 6 4 5 7 1Output17Input8 41 3 4 5 5 3 4 1Output23NoteIn the first example any partition yields 6 as the sum.In the second example one of the optimal partitions is [1, 1], [10, 10, 10, 10, 10, 10, 9, 10, 10, 10] with the values 2 and 90 respectively.In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively.In the fourth example one of the optimal partitions is [1], [3, 4, 5, 5, 3, 4], [1] with the values 1, 21 and 1 respectively. | Input3 51 2 3 | Output6 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', 'math', '*2000'] |
D. Alena And The Heatertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme.""Little Alena got an array as a birthday present..."The array b of length n is obtained from the array a of length n and two integers l and r (l ≤ r) using the following procedure:b1 = b2 = b3 = b4 = 0.For all 5 ≤ i ≤ n: bi = 0 if ai, ai - 1, ai - 2, ai - 3, ai - 4 > r and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 1 bi = 1 if ai, ai - 1, ai - 2, ai - 3, ai - 4 < l and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 0 bi = bi - 1 otherwise You are given arrays a and b' of the same length. Find two integers l and r (l ≤ r), such that applying the algorithm described above will yield an array b equal to b'.It's guaranteed that the answer exists.InputThe first line of input contains a single integer n (5 ≤ n ≤ 105) — the length of a and b'.The second line of input contains n space separated integers a1, ..., an ( - 109 ≤ ai ≤ 109) — the elements of a.The third line of input contains a string of n characters, consisting of 0 and 1 — the elements of b'. Note that they are not separated by spaces.OutputOutput two integers l and r ( - 109 ≤ l ≤ r ≤ 109), conforming to the requirements described above.If there are multiple solutions, output any of them.It's guaranteed that the answer exists.ExamplesInput51 2 3 4 500001Output6 15Input10-10 -9 -8 -7 -6 6 7 8 9 100000111110Output-5 5NoteIn the first test case any pair of l and r pair is valid, if 6 ≤ l ≤ r ≤ 109, in that case b5 = 1, because a1, ..., a5 < l. | Input51 2 3 4 500001 | Output6 15 | 2 seconds | 256 megabytes | ['binary search', 'implementation', '*1600'] |
C. Phone Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnd where the are the phone numbers?You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.It's guaranteed that the answer exists.Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a, b, d}.String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that pi < qi and for all j < i it is satisfied that pj = qj. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.InputThe first line of input contains two space separated integers n and k (1 ≤ n, k ≤ 100 000) — the length of s and the required length of t.The second line of input contains the string s consisting of n lowercase English letters.OutputOutput the string t conforming to the requirements above.It's guaranteed that the answer exists.ExamplesInput3 3abcOutputacaInput3 2abcOutputacInput3 3ayyOutputyaaInput2 3baOutputbaaNoteIn the first example the list of strings t of length 3, such that the set of letters of t is a subset of letters of s is as follows: aaa, aab, aac, aba, abb, abc, aca, acb, .... Among them, those are lexicographically greater than abc: aca, acb, .... Out of those the lexicographically smallest is aca. | Input3 3abc | Outputaca | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', 'strings', '*1500'] |
B. Our Tanya is Crying Out Loudtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRight now she actually isn't. But she will be, if you don't solve this problem.You are given integers n, k, A and B. There is a number x, which is initially equal to n. You are allowed to perform two types of operations: Subtract 1 from x. This operation costs you A coins. Divide x by k. Can be performed only if x is divisible by k. This operation costs you B coins. What is the minimum amount of coins you have to pay to make x equal to 1?InputThe first line contains a single integer n (1 ≤ n ≤ 2·109).The second line contains a single integer k (1 ≤ k ≤ 2·109).The third line contains a single integer A (1 ≤ A ≤ 2·109).The fourth line contains a single integer B (1 ≤ B ≤ 2·109).OutputOutput a single integer — the minimum amount of coins you have to pay to make x equal to 1.ExamplesInput9231Output6Input55220Output8Input19342Output12NoteIn the first testcase, the optimal strategy is as follows: Subtract 1 from x (9 → 8) paying 3 coins. Divide x by 2 (8 → 4) paying 1 coin. Divide x by 2 (4 → 2) paying 1 coin. Divide x by 2 (2 → 1) paying 1 coin. The total cost is 6 coins.In the second test case the optimal strategy is to subtract 1 from x 4 times paying 8 coins in total. | Input9231 | Output6 | 1 second | 256 megabytes | ['dp', 'greedy', '*1400'] |
A. Points on the linetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round. The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1, 3, 2, 1} is 2.Diameter of multiset consisting of one point is 0.You are given n points on the line. What is the minimum number of points you have to remove, so that the diameter of the multiset of the remaining points will not exceed d?InputThe first line contains two integers n and d (1 ≤ n ≤ 100, 0 ≤ d ≤ 100) — the amount of points and the maximum allowed diameter respectively.The second line contains n space separated integers (1 ≤ xi ≤ 100) — the coordinates of the points.OutputOutput a single integer — the minimum number of points you have to remove.ExamplesInput3 12 1 4Output1Input3 07 7 7Output0Input6 31 3 4 6 9 10Output3NoteIn the first test case the optimal strategy is to remove the point with coordinate 4. The remaining points will have coordinates 1 and 2, so the diameter will be equal to 2 - 1 = 1.In the second test case the diameter is equal to 0, so its is unnecessary to remove any points. In the third test case the optimal strategy is to remove points with coordinates 1, 9 and 10. The remaining points will have coordinates 3, 4 and 6, so the diameter will be equal to 6 - 3 = 3. | Input3 12 1 4 | Output1 | 1 second | 256 megabytes | ['brute force', 'greedy', 'sortings', '*1200'] |
F. Cutlettime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady wants to have a dinner. He has just returned from a shop where he has bought a semifinished cutlet. He only needs to fry it. The cutlet should be fried for 2n seconds, in particular, it should be fried for n seconds on one side and n seconds on the other side. Arkady has already got a frying pan and turn on fire, but understood that maybe he won't be able to flip the cutlet exactly after n seconds after the beginning of cooking.Arkady is too busy with sorting sticker packs in his favorite messenger and can flip the cutlet only in some periods of time. Namely, there are k periods of time in which he can do it, the i-th of them is an interval of time from li seconds after he starts cooking till ri seconds, inclusive. Arkady decided that it's not required to flip the cutlet exactly in the middle of cooking, instead, he will flip it several times in such a way that the cutlet will be fried exactly n seconds on one side and n seconds on the other side in total.Help Arkady and find out if it's possible for him to cook the cutlet, if he is able to flip the cutlet only in given periods of time; and if yes, find the minimum number of flips he needs to cook the cutlet.InputThe first line contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 100) — the number of seconds the cutlet should be cooked on each side and number of periods of time in which Arkady can flip it.The next k lines contain descriptions of these intervals. Each line contains two integers li and ri (0 ≤ li ≤ ri ≤ 2·n), meaning that Arkady can flip the cutlet in any moment starting from li seconds after the beginning of cooking and finishing at ri seconds after beginning of cooking. In particular, if li = ri then Arkady can flip the cutlet only in the moment li = ri. It's guaranteed that li > ri - 1 for all 2 ≤ i ≤ k.OutputOutput "Hungry" if Arkady won't be able to fry the cutlet for exactly n seconds on one side and exactly n seconds on the other side.Otherwise, output "Full" in the first line, and the minimum number of times he should flip the cutlet in the second line.ExamplesInput10 23 511 13OutputFull2Input10 33 59 1011 13OutputFull1Input20 13 19OutputHungryNoteIn the first example Arkady should flip the cutlet in time moment 3 seconds after he starts cooking and in time moment 13 seconds after he starts cooking.In the second example, Arkady can flip the cutlet at 10 seconds after he starts cooking. | Input10 23 511 13 | OutputFull2 | 4 seconds | 256 megabytes | ['data structures', 'dp', '*2400'] |
E. Maximize!time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a multiset S consisting of positive integers (initially empty). There are two kind of queries: Add a positive integer to S, the newly added integer is not less than any number in it. Find a subset s of the set S such that the value is maximum possible. Here max(s) means maximum value of elements in s, — the average value of numbers in s. Output this maximum possible value of . InputThe first line contains a single integer Q (1 ≤ Q ≤ 5·105) — the number of queries.Each of the next Q lines contains a description of query. For queries of type 1 two integers 1 and x are given, where x (1 ≤ x ≤ 109) is a number that you should add to S. It's guaranteed that x is not less than any number in S. For queries of type 2, a single integer 2 is given.It's guaranteed that the first query has type 1, i. e. S is not empty when a query of type 2 comes.OutputOutput the answer for each query of the second type in the order these queries are given in input. Each number should be printed in separate line.Your answer is considered correct, if each of your answers has absolute or relative error not greater than 10 - 6.Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .ExamplesInput61 321 421 82Output0.00000000000.50000000003.0000000000Input41 11 41 52Output2.0000000000 | Input61 321 421 82 | Output0.00000000000.50000000003.0000000000 | 3 seconds | 256 megabytes | ['binary search', 'greedy', 'ternary search', 'two pointers', '*1800'] |
D. Love Rescuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValya and Tolya are an ideal pair, but they quarrel sometimes. Recently, Valya took offense at her boyfriend because he came to her in t-shirt with lettering that differs from lettering on her pullover. Now she doesn't want to see him and Tolya is seating at his room and crying at her photos all day long.This story could be very sad but fairy godmother (Tolya's grandmother) decided to help them and restore their relationship. She secretly took Tolya's t-shirt and Valya's pullover and wants to make the letterings on them same. In order to do this, for one unit of mana she can buy a spell that can change some letters on the clothes. Your task is calculate the minimum amount of mana that Tolya's grandmother should spend to rescue love of Tolya and Valya.More formally, letterings on Tolya's t-shirt and Valya's pullover are two strings with same length n consisting only of lowercase English letters. Using one unit of mana, grandmother can buy a spell of form (c1, c2) (where c1 and c2 are some lowercase English letters), which can arbitrary number of times transform a single letter c1 to c2 and vise-versa on both Tolya's t-shirt and Valya's pullover. You should find the minimum amount of mana that grandmother should spend to buy a set of spells that can make the letterings equal. In addition you should output the required set of spells. InputThe first line contains a single integer n (1 ≤ n ≤ 105) — the length of the letterings.The second line contains a string with length n, consisting of lowercase English letters — the lettering on Valya's pullover.The third line contains the lettering on Tolya's t-shirt in the same format.OutputIn the first line output a single integer — the minimum amount of mana t required for rescuing love of Valya and Tolya.In the next t lines output pairs of space-separated lowercase English letters — spells that Tolya's grandmother should buy. Spells and letters in spells can be printed in any order.If there are many optimal answers, output any.ExamplesInput3abbdadOutput2a db aInput8drpeppercocacolaOutput7l ee dd cc pp oo rr aNoteIn first example it's enough to buy two spells: ('a','d') and ('b','a'). Then first letters will coincide when we will replace letter 'a' with 'd'. Second letters will coincide when we will replace 'b' with 'a'. Third letters will coincide when we will at first replace 'b' with 'a' and then 'a' with 'd'. | Input3abbdad | Output2a db a | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', 'greedy', 'strings', '*1600'] |
C. Convenient For Everybodytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, local time in the i-th timezone is i hours.Some online programming contests platform wants to conduct a contest that lasts for an hour in such a way that its beginning coincides with beginning of some hour (in all time zones). The platform knows, that there are ai people from i-th timezone who want to participate in the contest. Each person will participate if and only if the contest starts no earlier than s hours 00 minutes local time and ends not later than f hours 00 minutes local time. Values s and f are equal for all time zones. If the contest starts at f hours 00 minutes local time, the person won't participate in it.Help platform select such an hour, that the number of people who will participate in the contest is maximum. InputThe first line contains a single integer n (2 ≤ n ≤ 100 000) — the number of hours in day.The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 10 000), where ai is the number of people in the i-th timezone who want to participate in the contest.The third line contains two space-separated integers s and f (1 ≤ s < f ≤ n).OutputOutput a single integer — the time of the beginning of the contest (in the first timezone local time), such that the number of participants will be maximum possible. If there are many answers, output the smallest among them.ExamplesInput31 2 31 3Output3Input51 2 3 4 11 3Output4NoteIn the first example, it's optimal to start competition at 3 hours (in first timezone). In this case, it will be 1 hour in the second timezone and 2 hours in the third timezone. Only one person from the first timezone won't participate.In second example only people from the third and the fourth timezones will participate. | Input31 2 31 3 | Output3 | 2 seconds | 256 megabytes | ['binary search', 'two pointers', '*1600'] |
B. Hamster Farmtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.InputThe first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces.The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.OutputOutput two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input.If there are many correct answers, output any of them.ExamplesInput19 35 4 10Output2 4Input28 35 6 30Output1 5 | Input19 35 4 10 | Output2 4 | 2 seconds | 256 megabytes | ['implementation', '*1000'] |
A. Love Triangletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 ≤ fi ≤ n and fi ≠ i.We call a love triangle a situation in which plane A likes plane B, plane B likes plane C and plane C likes plane A. Find out if there is any love triangle on Earth.InputThe first line contains a single integer n (2 ≤ n ≤ 5000) — the number of planes.The second line contains n integers f1, f2, ..., fn (1 ≤ fi ≤ n, fi ≠ i), meaning that the i-th plane likes the fi-th.OutputOutput «YES» if there is a love triangle consisting of planes on Earth. Otherwise, output «NO».You can output any letter in lower case or in upper case.ExamplesInput52 4 5 1 3OutputYESInput55 5 5 5 1OutputNONoteIn first example plane 2 likes plane 4, plane 4 likes plane 1, plane 1 likes plane 2 and that is a love triangle.In second example there are no love triangles. | Input52 4 5 1 3 | OutputYES | 1 second | 256 megabytes | ['graphs', '*800'] |
G. Shortest Path Queriestime limit per test3.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an undirected connected graph with weighted edges. The length of some path between two vertices is the bitwise xor of weights of all edges belonging to this path (if some edge is traversed more than once, then it is included in bitwise xor the same number of times). There are three types of queries you have to process: 1 x y d — add an edge connecting vertex x to vertex y with weight d. It is guaranteed that there is no edge connecting x to y before this query; 2 x y — remove an edge connecting vertex x to vertex y. It is guaranteed that there was such edge in the graph, and the graph stays connected after this query; 3 x y — calculate the length of the shortest path (possibly non-simple) from vertex x to vertex y. Print the answers for all queries of type 3.InputThe first line contains two numbers n and m (1 ≤ n, m ≤ 200000) — the number of vertices and the number of edges in the graph, respectively.Then m lines follow denoting the edges of the graph. Each line contains three integers x, y and d (1 ≤ x < y ≤ n, 0 ≤ d ≤ 230 - 1). Each pair (x, y) is listed at most once. The initial graph is connected.Then one line follows, containing an integer q (1 ≤ q ≤ 200000) — the number of queries you have to process.Then q lines follow, denoting queries in the following form: 1 x y d (1 ≤ x < y ≤ n, 0 ≤ d ≤ 230 - 1) — add an edge connecting vertex x to vertex y with weight d. It is guaranteed that there is no edge connecting x to y before this query; 2 x y (1 ≤ x < y ≤ n) — remove an edge connecting vertex x to vertex y. It is guaranteed that there was such edge in the graph, and the graph stays connected after this query; 3 x y (1 ≤ x < y ≤ n) — calculate the length of the shortest path (possibly non-simple) from vertex x to vertex y. It is guaranteed that at least one query has type 3.OutputPrint the answers for all queries of type 3 in the order they appear in input.ExampleInput5 51 2 32 3 43 4 54 5 61 5 153 1 51 1 3 13 1 52 1 53 1 5Output112 | Input5 51 2 32 3 43 4 54 5 61 5 153 1 51 1 3 13 1 52 1 53 1 5 | Output112 | 3.5 seconds | 512 megabytes | ['bitmasks', 'data structures', 'dsu', 'graphs', '*2900'] |
F. Erasing Substringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, initially consisting of n lowercase Latin letters. After that, you perform k operations with it, where . During i-th operation you must erase some substring of length exactly 2i - 1 from s.Print the lexicographically minimal string you may obtain after performing k such operations.InputThe only line contains one string s consisting of n lowercase Latin letters (1 ≤ n ≤ 5000).OutputPrint the lexicographically minimal string you may obtain after performing k operations.ExamplesInputadcbcaOutputabaInputabacabadabacabaOutputaabacabaNotePossible operations in examples: adcbca adcba aba; abacabadabacaba abcabadabacaba aabadabacaba aabacaba. | Inputadcbca | Outputaba | 1 second | 256 megabytes | ['bitmasks', 'dp', 'greedy', '*2700'] |
E. Max Historytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n. We define fa the following way: Initially fa = 0, M = 1; for every 2 ≤ i ≤ n if aM < ai then we set fa = fa + aM and then set M = i. Calculate the sum of fa over all n! permutations of the array a modulo 109 + 7.Note: two elements are considered different if their indices differ, so for every array a there are exactly n! permutations.InputThe first line contains integer n (1 ≤ n ≤ 1 000 000) — the size of array a.Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109).OutputPrint the only integer, the sum of fa over all n! permutations of the array a modulo 109 + 7.ExamplesInput21 3Output1Input31 1 2Output4NoteFor the second example all the permutations are: p = [1, 2, 3] : fa is equal to 1; p = [1, 3, 2] : fa is equal to 1; p = [2, 1, 3] : fa is equal to 1; p = [2, 3, 1] : fa is equal to 1; p = [3, 1, 2] : fa is equal to 0; p = [3, 2, 1] : fa is equal to 0. Where p is the array of the indices of initial array a. The sum of fa is equal to 4. | Input21 3 | Output1 | 3 seconds | 256 megabytes | ['combinatorics', 'math', '*2300'] |
D. Buy a Tickettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMusicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.InputThe first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105).Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input.The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.OutputPrint n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).ExamplesInput4 21 2 42 3 76 20 1 25Output6 14 1 25 Input3 31 2 12 3 11 3 130 10 20Output12 10 12 | Input4 21 2 42 3 76 20 1 25 | Output6 14 1 25 | 2 seconds | 256 megabytes | ['data structures', 'graphs', 'shortest paths', '*2000'] |
C. Constructing Teststime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote a m-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size m × m of this matrix contains at least one zero. Consider the following problem:You are given two integers n and m. You have to construct an m-free square matrix of size n × n such that the number of 1's in this matrix is maximum possible. Print the maximum possible number of 1's in such matrix.You don't have to solve this problem. Instead, you have to construct a few tests for it.You will be given t numbers x1, x2, ..., xt. For every , find two integers ni and mi (ni ≥ mi) such that the answer for the aforementioned problem is exactly xi if we set n = ni and m = mi.InputThe first line contains one integer t (1 ≤ t ≤ 100) — the number of tests you have to construct.Then t lines follow, i-th line containing one integer xi (0 ≤ xi ≤ 109).Note that in hacks you have to set t = 1.OutputFor each test you have to construct, output two positive numbers ni and mi (1 ≤ mi ≤ ni ≤ 109) such that the maximum number of 1's in a mi-free ni × ni matrix is exactly xi. If there are multiple solutions, you may output any of them; and if this is impossible to construct a test, output a single integer - 1. ExampleInput32101Output5 21 1-1 | Input32101 | Output5 21 1-1 | 1 second | 256 megabytes | ['binary search', 'brute force', 'constructive algorithms', '*1700'] |
B. Run For Your Prizetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your friend are participating in a TV show "Run For Your Prize".At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.What is the minimum number of seconds it will take to pick up all the prizes?InputThe first line contains one integer n (1 ≤ n ≤ 105) — the number of prizes.The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 106 - 1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.OutputPrint one integer — the minimum number of seconds it will take to collect all prizes.ExamplesInput32 3 9Output8Input22 999995Output5NoteIn the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5. | Input32 3 9 | Output8 | 1 second | 256 megabytes | ['brute force', 'greedy', '*1100'] |
A. Word Correctiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVictor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange.Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consecutive vowels in the word, it deletes the first vowel in a word such that there is another vowel right before it. If there are no two consecutive vowels in the word, it is considered to be correct.You are given a word s. Can you predict what will it become after correction?In this problem letters a, e, i, o, u and y are considered to be vowels.InputThe first line contains one integer n (1 ≤ n ≤ 100) — the number of letters in word s before the correction.The second line contains a string s consisting of exactly n lowercase Latin letters — the word before the correction.OutputOutput the word s after the correction.ExamplesInput5weirdOutputwerdInput4wordOutputwordInput5aaeaaOutputaNoteExplanations of the examples: There is only one replace: weird werd; No replace needed since there are no two consecutive vowels; aaeaa aeaa aaa aa a. | Input5weird | Outputwerd | 1 second | 256 megabytes | ['implementation', '*800'] |
B. Vile Grasshopperstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches .Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible.InputThe only line contains two integers p and y (2 ≤ p ≤ y ≤ 109).OutputOutput the number of the highest suitable branch. If there are none, print -1 instead.ExamplesInput3 6Output5Input3 4Output-1NoteIn the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5.It immediately follows that there are no valid branches in second sample case. | Input3 6 | Output5 | 1 second | 256 megabytes | ['brute force', 'math', 'number theory', '*1400'] |
A. Olympiadtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria: At least one participant should get a diploma. None of those with score equal to zero should get awarded. When someone is awarded, all participants with score not less than his score should also be awarded. Determine the number of ways to choose a subset of participants that will receive the diplomas.InputThe first line contains a single integer n (1 ≤ n ≤ 100) — the number of participants.The next line contains a sequence of n integers a1, a2, ..., an (0 ≤ ai ≤ 600) — participants' scores.It's guaranteed that at least one participant has non-zero score.OutputPrint a single integer — the desired number of ways.ExamplesInput41 3 3 2Output3Input31 1 1Output1Input442 0 0 42Output1NoteThere are three ways to choose a subset in sample case one. Only participants with 3 points will get diplomas. Participants with 2 or 3 points will get diplomas. Everyone will get a diploma! The only option in sample case two is to award everyone.Note that in sample case three participants with zero scores cannot get anything. | Input41 3 3 2 | Output3 | 1 second | 256 megabytes | ['implementation', 'sortings', '*800'] |
D. World of Tanktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitya loves programming and problem solving, but sometimes, to distract himself a little, he plays computer games. Once he found a new interesting game about tanks, and he liked it so much that he went through almost all levels in one day. Remained only the last level, which was too tricky. Then Vitya remembered that he is a programmer, and wrote a program that helped him to pass this difficult level. Try do the same.The game is organized as follows. There is a long road, two cells wide and n cells long. Some cells have obstacles. You control a tank that occupies one cell. Initially, the tank is located before the start of the road, in a cell with coordinates (0, 1). Your task is to move the tank to the end of the road, to the cell (n + 1, 1) or (n + 1, 2). Every second the tank moves one cell to the right: the coordinate x is increased by one. When you press the up or down arrow keys, the tank instantly changes the lane, that is, the y coordinate. When you press the spacebar, the tank shoots, and the nearest obstacle along the lane in which the tank rides is instantly destroyed. In order to load a gun, the tank needs t seconds. Initially, the gun is not loaded, that means, the first shot can be made only after t seconds after the tank starts to move.If at some point the tank is in the same cell with an obstacle not yet destroyed, it burns out. If you press the arrow exactly at the moment when the tank moves forward, the tank will first move forward, and then change the lane, so it will not be possible to move diagonally.Your task is to find out whether it is possible to pass the level, and if possible, to find the order of actions the player need to make.InputThe first line contains four integers n, m1, m2 and t, the length of the field, the number of obstacles in the first lane, the number of obstacles in the second lane and the number of tank steps before reloading, respectively (1 ≤ n ≤ 109; 0 ≤ m1, m2 ≤ n; 0 ≤ m1 + m2 ≤ 106; 1 ≤ t ≤ n).The next two lines contain a description of the obstacles. The first of these lines contains m1 numbers xi — the obstacle coordinates in the first lane (1 ≤ xi ≤ n; xi < xi + 1). The y coordinate for all these obstacles will be 1.The second line contains m2 numbers describing the obstacles of the second lane in the same format. The y coordinate of all these obstacles will be 2.OutputIn the first line print «Yes», if it is possible to pass the level, or «No», otherwise.If it is possible, then in the second line print the number of times the tank moves from one lane to another, and in the next line print the coordinates of the transitions, one number per transition: the coordinate x (0 ≤ x ≤ n + 1). All transition coordinates coordinates must be distinct and should be output in strictly increasing order.The number of transitions should not exceed 2·106. If the tank can pass the level, then it can do it using no more than 2·106 transitions.In the fourth line print the number of shots that the tank makes during the movement, in the following lines print two numbers, x and y coordinates of the point (1 ≤ x ≤ n, 1 ≤ y ≤ 2), from which the tank fired a shot, the number of shots must not exceed m1 + m2. Shots must be output in the order in which they are fired.If there are several solutions, output any one.ExamplesInput6 2 3 22 63 5 6OutputYes20 3 22 24 1Input1 1 1 111OutputNoInput9 5 2 51 2 7 8 94 6OutputYes40 3 5 10 15 2NotePicture for the first sample test. | Input6 2 3 22 63 5 6 | OutputYes20 3 22 24 1 | 2 seconds | 256 megabytes | ['dp', 'greedy', '*3000'] |
C. Lock Puzzletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWelcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer x from 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift 4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.InputThe first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).After that, there are two strings s and t, consisting of n lowercase Latin letters each.OutputIf it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.ExamplesInput6abacbbbabcbaOutput46 3 2 3Input3ababbaOutput-1In the first example, after applying the operations, the string on the screen will change as follows: abacbb bbcaba bbcaba ababbc ababbc cbabab cbabab babcba | Input6abacbbbabcba | Output46 3 2 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', 'strings', '*2300'] |
B. Sleepy Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and Vasya arranged a game. The game runs by the following rules. Players have a directed graph consisting of n vertices and m edges. One of the vertices contains a chip. Initially the chip is located at vertex s. Players take turns moving the chip along some edge of the graph. Petya goes first. Player who can't move the chip loses. If the game lasts for 106 turns the draw is announced.Vasya was performing big laboratory work in "Spelling and parts of speech" at night before the game, so he fell asleep at the very beginning of the game. Petya decided to take the advantage of this situation and make both Petya's and Vasya's moves.Your task is to help Petya find out if he can win the game or at least draw a tie.InputThe first line of input contain two integers n and m — the number of vertices and the number of edges in the graph (2 ≤ n ≤ 105, 0 ≤ m ≤ 2·105).The next n lines contain the information about edges of the graph. i-th line (1 ≤ i ≤ n) contains nonnegative integer ci — number of vertices such that there is an edge from i to these vertices and ci distinct integers ai, j — indices of these vertices (1 ≤ ai, j ≤ n, ai, j ≠ i).It is guaranteed that the total sum of ci equals to m.The next line contains index of vertex s — the initial position of the chip (1 ≤ s ≤ n).OutputIf Petya can win print «Win» in the first line. In the next line print numbers v1, v2, ..., vk (1 ≤ k ≤ 106) — the sequence of vertices Petya should visit for the winning. Vertex v1 should coincide with s. For i = 1... k - 1 there should be an edge from vi to vi + 1 in the graph. There must be no possible move from vertex vk. The sequence should be such that Petya wins the game.If Petya can't win but can draw a tie, print «Draw» in the only line. Otherwise print «Lose».ExamplesInput5 62 2 32 4 51 41 501OutputWin1 2 4 5 Input3 21 31 102OutputLoseInput2 21 21 11OutputDrawNoteIn the first example the graph is the following: Initially the chip is located at vertex 1. In the first move Petya moves the chip to vertex 2, after that he moves it to vertex 4 for Vasya. After that he moves to vertex 5. Now it is Vasya's turn and there is no possible move, so Petya wins.In the second example the graph is the following: Initially the chip is located at vertex 2. The only possible Petya's move is to go to vertex 1. After that he has to go to 3 for Vasya. Now it's Petya's turn but he has no possible move, so Petya loses.In the third example the graph is the following: Petya can't win, but he can move along the cycle, so the players will draw a tie. | Input5 62 2 32 4 51 41 501 | OutputWin1 2 4 5 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'games', 'graphs', '*2100'] |
A. Save Energy!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJulia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.InputThe single line contains three integers k, d and t (1 ≤ k, d, t ≤ 1018).OutputPrint a single number, the total time of cooking in minutes. The relative or absolute error must not exceed 10 - 9.Namely, let's assume that your answer is x and the answer of the jury is y. The checker program will consider your answer correct if .ExamplesInput3 2 6Output6.5Input4 2 20Output20.0NoteIn the first example, the chicken will be cooked for 3 minutes on the turned on stove, after this it will be cooked for . Then the chicken will be cooked for one minute on a turned off stove, it will be cooked for . Thus, after four minutes the chicken will be cooked for . Before the fifth minute Julia will turn on the stove and after 2.5 minutes the chicken will be ready .In the second example, when the stove is turned off, Julia will immediately turn it on, so the stove will always be turned on and the chicken will be cooked in 20 minutes. | Input3 2 6 | Output6.5 | 1 second | 256 megabytes | ['binary search', 'implementation', 'math', '*1700'] |
F. Fafa and Arraytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFafa has an array A of n positive integers, the function f(A) is defined as . He wants to do q queries of two types: 1 l r x — find the maximum possible value of f(A), if x is to be added to one element in the range [l, r]. You can choose to which element to add x. 2 l r x — increase all the elements in the range [l, r] by value x. Note that queries of type 1 don't affect the array elements.InputThe first line contains one integer n (3 ≤ n ≤ 105) — the length of the array.The second line contains n positive integers a1, a2, ..., an (0 < ai ≤ 109) — the array elements.The third line contains an integer q (1 ≤ q ≤ 105) — the number of queries. Then q lines follow, line i describes the i-th query and contains four integers ti li ri xi . It is guaranteed that at least one of the queries is of type 1.OutputFor each query of type 1, print the answer to the query.ExamplesInput51 1 1 1 151 2 4 12 2 3 12 4 4 22 3 4 11 3 3 2Output28Input51 2 3 4 541 2 4 22 2 4 12 3 4 11 2 4 2Output610 | Input51 1 1 1 151 2 4 12 2 3 12 4 4 22 3 4 11 3 3 2 | Output28 | 3 seconds | 256 megabytes | ['data structures', 'greedy', '*2600'] |
E. Fafa and Ancient Mathematicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAncient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression.An Ahmes arithmetic expression can be defined as: "d" is an Ahmes arithmetic expression, where d is a one-digit positive integer; "(E1 op E2)" is an Ahmes arithmetic expression, where E1 and E2 are valid Ahmes arithmetic expressions (without spaces) and op is either plus ( + ) or minus ( - ). For example 5, (1-1) and ((1+(2-3))-5) are valid Ahmes arithmetic expressions.On his trip to Egypt, Fafa found a piece of papyrus paper having one of these Ahmes arithmetic expressions written on it. Being very ancient, the papyrus piece was very worn out. As a result, all the operators were erased, keeping only the numbers and the brackets. Since Fafa loves mathematics, he decided to challenge himself with the following task:Given the number of plus and minus operators in the original expression, find out the maximum possible value for the expression on the papyrus paper after putting the plus and minus operators in the place of the original erased operators.InputThe first line contains a string E (1 ≤ |E| ≤ 104) — a valid Ahmes arithmetic expression. All operators are erased and replaced with '?'.The second line contains two space-separated integers P and M (0 ≤ min(P, M) ≤ 100) — the number of plus and minus operators, respectively. It is guaranteed that P + M = the number of erased operators.OutputPrint one line containing the answer to the problem.ExamplesInput(1?1)1 0Output2Input(2?(1?2))1 1Output1Input((1?(5?7))?((6?2)?7))3 2Output18Input((1?(5?7))?((6?2)?7))2 3Output16Note The first sample will be (1 + 1) = 2. The second sample will be (2 + (1 - 2)) = 1. The third sample will be ((1 - (5 - 7)) + ((6 + 2) + 7)) = 18. The fourth sample will be ((1 + (5 + 7)) - ((6 - 2) - 7)) = 16. | Input(1?1)1 0 | Output2 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'trees', '*2300'] |
D. Fafa and Ancient Alphabettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAncient Egyptians are known to have used a large set of symbols to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words S1 and S2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the words were erased. The symbols in the set have equal probability for being in the position of any erased symbol.Fifa challenged Fafa to calculate the probability that S1 is lexicographically greater than S2. Can you help Fafa with this task?You know that , i. e. there were m distinct characters in Egyptians' alphabet, in this problem these characters are denoted by integers from 1 to m in alphabet order. A word x is lexicographically greater than a word y of the same length, if the words are same up to some position, and then the word x has a larger character, than the word y.We can prove that the probability equals to some fraction , where P and Q are coprime integers, and . Print as the answer the value , i. e. such a non-negative integer less than 109 + 7, such that , where means that a and b give the same remainders when divided by m.InputThe first line contains two integers n and m (1 ≤ n, m ≤ 105) — the length of each of the two words and the size of the alphabet , respectively.The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ m) — the symbols of S1. If ai = 0, then the symbol at position i was erased.The third line contains n integers representing S2 with the same format as S1.OutputPrint the value , where P and Q are coprime and is the answer to the problem.ExamplesInput1 201Output500000004Input1 210Output0Input7 260 15 12 9 13 0 1411 1 0 13 15 12 0Output230769233NoteIn the first sample, the first word can be converted into (1) or (2). The second option is the only one that will make it lexicographically larger than the second word. So, the answer to the problem will be , that is 500000004, because .In the second example, there is no replacement for the zero in the second word that will make the first one lexicographically larger. So, the answer to the problem is , that is 0. | Input1 201 | Output500000004 | 2 seconds | 256 megabytes | ['math', 'probabilities', '*1900'] |
C. Fifa and Fafatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by Fifa) from its position. Fifa must put the access point inside the flat which has a circular shape of radius R. Fifa wants to minimize the area that is not covered by the access point inside the flat without letting Fafa or anyone outside the flat to get access to the internet.The world is represented as an infinite 2D plane. The flat is centered at (x1, y1) and has radius R and Fafa's laptop is located at (x2, y2), not necessarily inside the flat. Find the position and the radius chosen by Fifa for his access point which minimizes the uncovered area.InputThe single line of the input contains 5 space-separated integers R, x1, y1, x2, y2 (1 ≤ R ≤ 105, |x1|, |y1|, |x2|, |y2| ≤ 105).OutputPrint three space-separated numbers xap, yap, r where (xap, yap) is the position which Fifa chose for the access point and r is the radius of its range. Your answer will be considered correct if the radius does not differ from optimal more than 10 - 6 absolutely or relatively, and also the radius you printed can be changed by no more than 10 - 6 (absolutely or relatively) in such a way that all points outside the flat and Fafa's laptop position are outside circle of the access point range.ExamplesInput5 3 3 1 1Output3.7677669529663684 3.7677669529663684 3.914213562373095Input10 5 5 5 15Output5.0 5.0 10.0 | Input5 3 3 1 1 | Output3.7677669529663684 3.7677669529663684 3.914213562373095 | 1 second | 256 megabytes | ['geometry', '*1600'] |
B. Fafa and the Gatestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.The world can be represented by the first quadrant of a plane and the wall is built along the identity line (i.e. the line with the equation x = y). Any point below the wall belongs to the first kingdom while any point above the wall belongs to the second kingdom. There is a gate at any integer point on the line (i.e. at points (0, 0), (1, 1), (2, 2), ...). The wall and the gates do not belong to any of the kingdoms. Fafa is at the gate at position (0, 0) and he wants to walk around in the two kingdoms. He knows the sequence S of moves he will do. This sequence is a string where each character represents a move. The two possible moves Fafa will do are 'U' (move one step up, from (x, y) to (x, y + 1)) and 'R' (move one step right, from (x, y) to (x + 1, y)). Fafa wants to know the number of silver coins he needs to pay to walk around the two kingdoms following the sequence S. Note that if Fafa visits a gate without moving from one kingdom to another, he pays no silver coins. Also assume that he doesn't pay at the gate at point (0, 0), i. e. he is initially on the side he needs. InputThe first line of the input contains single integer n (1 ≤ n ≤ 105) — the number of moves in the walking sequence.The second line contains a string S of length n consisting of the characters 'U' and 'R' describing the required moves. Fafa will follow the sequence S in order from left to right.OutputOn a single line, print one integer representing the number of silver coins Fafa needs to pay at the gates to follow the sequence S.ExamplesInput1UOutput0Input6RURUUROutput1Input7URRRUUUOutput2NoteThe figure below describes the third sample. The red arrows represent the sequence of moves Fafa will follow. The green gates represent the gates at which Fafa have to pay silver coins. | Input1U | Output0 | 2 seconds | 256 megabytes | ['implementation', '*900'] |
A. Fafa and his Companytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.InputThe input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.OutputPrint a single integer representing the answer to the problem.ExamplesInput2Output1Input10Output3NoteIn the second sample Fafa has 3 ways: choose only 1 employee as a team leader with 9 employees under his responsibility. choose 2 employees as team leaders with 4 employees under the responsibility of each of them. choose 5 employees as team leaders with 1 employee under the responsibility of each of them. | Input2 | Output1 | 1 second | 256 megabytes | ['brute force', 'implementation', '*800'] |
B. A Prosperous Lottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputApart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside.Big Banban is hesitating over the amount of money to give out. He considers loops to be lucky since it symbolizes unity and harmony.He would like to find a positive integer n not greater than 1018, such that there are exactly k loops in the decimal representation of n, or determine that such n does not exist.A loop is a planar area enclosed by lines in the digits' decimal representation written in Arabic numerals. For example, there is one loop in digit 4, two loops in 8 and no loops in 5. Refer to the figure below for all exact forms. InputThe first and only line contains an integer k (1 ≤ k ≤ 106) — the desired number of loops.OutputOutput an integer — if no such n exists, output -1; otherwise output any such n. In the latter case, your output should be a positive decimal integer not exceeding 1018.ExamplesInput2Output462Input6Output8080 | Input2 | Output462 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1200'] |
A. A Compatible Pairtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a1, a2, ..., an, and Banban's have brightness b1, b2, ..., bm respectively.Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.You are asked to find the brightness of the chosen pair if both of them choose optimally.InputThe first line contains two space-separated integers n and m (2 ≤ n, m ≤ 50).The second line contains n space-separated integers a1, a2, ..., an.The third line contains m space-separated integers b1, b2, ..., bm.All the integers range from - 109 to 109.OutputPrint a single integer — the brightness of the chosen pair.ExamplesInput2 220 182 14Output252Input5 3-1 0 1 2 3-1 0 1Output2NoteIn the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself. | Input2 220 182 14 | Output252 | 1 second | 256 megabytes | ['brute force', 'games', '*1400'] |
E. A Preponderant Reuniontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEast or west, home is best. That's why family reunion, the indispensable necessity of Lunar New Year celebration, is put in such a position.After the reunion dinner, Little Tommy plays a game with the family. Here is a concise introduction to this game: There is a sequence of n non-negative integers p1, p2, ..., pn in the beginning. It is ruled that each integer in this sequence should be non-negative at any time. You can select two consecutive positive integers in this sequence, pi and pi + 1 (1 ≤ i < n), and then decrease them by their minimum (i. e. min(pi, pi + 1)), the cost of this operation is equal to min(pi, pi + 1). We call such operation as a descension. The game immediately ends when there are no two consecutive positive integers. Your task is to end the game so that the total cost of your operations is as small as possible. Obviously, every game ends after at most n - 1 descensions. Please share your solution of this game with the lowest cost.InputThe first line contains one integer n (1 ≤ n ≤ 3·105).The second line contains n space-separated integers p1, p2, ..., pn (0 ≤ pi ≤ 109, i = 1, 2, ..., n).OutputIn the first line print one integer as the number of descensions m (0 ≤ m ≤ n - 1).In the next m lines print the descensions chronologically. More precisely, in each line of the next m lines print one integer i (1 ≤ i < n) representing a descension would operate on pi and pi + 1 such that all the descensions could be utilized from top to bottom.If there are many possible solutions to reach the minimal cost, print any of them.ExamplesInput42 1 3 1Output213Input52 2 1 3 1Output3214NoteIn the first sample, one possible best solution is , of which the cost is 1 + 1 = 2.In the second sample, one possible best solution is , of which the cost is 1 + 1 + 1 = 3. | Input42 1 3 1 | Output213 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dp', '*3200'] |
D. A Creative Cutouttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverything red frightens Nian the monster. So do red paper and... you, red on Codeforces, potential or real.Big Banban has got a piece of paper with endless lattice points, where lattice points form squares with the same area. His most favorite closed shape is the circle because of its beauty and simplicity. Once he had obtained this piece of paper, he prepares it for paper-cutting. He drew n concentric circles on it and numbered these circles from 1 to n such that the center of each circle is the same lattice point and the radius of the k-th circle is times the length of a lattice edge.Define the degree of beauty of a lattice point as the summation of the indices of circles such that this lattice point is inside them, or on their bounds. Banban wanted to ask you the total degree of beauty of all the lattice points, but changed his mind.Defining the total degree of beauty of all the lattice points on a piece of paper with n circles as f(n), you are asked to figure out .InputThe first line contains one integer m (1 ≤ m ≤ 1012).OutputIn the first line print one integer representing .ExamplesInput5Output387Input233Output788243189NoteA piece of paper with 5 circles is shown in the following. There are 5 types of lattice points where the degree of beauty of each red point is 1 + 2 + 3 + 4 + 5 = 15, the degree of beauty of each orange point is 2 + 3 + 4 + 5 = 14, the degree of beauty of each green point is 4 + 5 = 9, the degree of beauty of each blue point is 5 and the degree of beauty of each gray point is 0. Therefore, f(5) = 5·15 + 4·14 + 4·9 + 8·5 = 207.Similarly, f(1) = 5, f(2) = 23, f(3) = 50, f(4) = 102 and consequently . | Input5 | Output387 | 2 seconds | 256 megabytes | ['brute force', 'combinatorics', 'math', '*2900'] |
C. A Colourful Prospecttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFirecrackers scare Nian the monster, but they're wayyyyy too noisy! Maybe fireworks make a nice complement.Little Tommy is watching a firework show. As circular shapes spread across the sky, a splendid view unfolds on the night of Lunar New Year's eve.A wonder strikes Tommy. How many regions are formed by the circles on the sky? We consider the sky as a flat plane. A region is a connected part of the plane with positive area, whose bound consists of parts of bounds of the circles and is a curve or several curves without self-intersections, and that does not contain any curve other than its boundaries. Note that exactly one of the regions extends infinitely.InputThe first line of input contains one integer n (1 ≤ n ≤ 3), denoting the number of circles.The following n lines each contains three space-separated integers x, y and r ( - 10 ≤ x, y ≤ 10, 1 ≤ r ≤ 10), describing a circle whose center is (x, y) and the radius is r. No two circles have the same x, y and r at the same time.OutputPrint a single integer — the number of regions on the plane.ExamplesInput30 0 12 0 14 0 1Output4Input30 0 23 0 26 0 2Output6Input30 0 22 0 21 1 2Output8NoteFor the first example, For the second example, For the third example, | Input30 0 12 0 14 0 1 | Output4 | 1 second | 256 megabytes | ['geometry', 'graphs', '*2700'] |
B. A Determined Cleanuptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients).InputThe only line of input contains two space-separated integers p and k (1 ≤ p ≤ 1018, 2 ≤ k ≤ 2 000).OutputIf the polynomial does not exist, print a single integer -1, or output two lines otherwise.In the first line print a non-negative integer d — the number of coefficients in the polynomial.In the second line print d space-separated integers a0, a1, ..., ad - 1, describing a polynomial fulfilling the given requirements. Your output should satisfy 0 ≤ ai < k for all 0 ≤ i ≤ d - 1, and ad - 1 ≠ 0.If there are many possible solutions, print any of them.ExamplesInput46 2Output70 1 0 0 1 1 1Input2018 214Output392 205 1NoteIn the first example, f(x) = x6 + x5 + x4 + x = (x5 - x4 + 3x3 - 6x2 + 12x - 23)·(x + 2) + 46.In the second example, f(x) = x2 + 205x + 92 = (x - 9)·(x + 214) + 2018. | Input46 2 | Output70 1 0 0 1 1 1 | 1 second | 256 megabytes | ['math', '*2000'] |
A. A Twisty Movementtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.InputThe first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence.The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).OutputPrint a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.ExamplesInput41 2 1 2Output4Input101 1 2 2 2 1 1 2 2 1Output9NoteIn the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9. | Input41 2 1 2 | Output4 | 1 second | 256 megabytes | ['dp', '*1800'] |
G. Palindrome Partitiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a string s, find the number of ways to split s to substrings such that if there are k substrings (p1, p2, p3, ..., pk) in partition, then pi = pk - i + 1 for all i (1 ≤ i ≤ k) and k is even.Since the number of ways can be large, print it modulo 109 + 7.InputThe only line of input contains a string s (2 ≤ |s| ≤ 106) of even length consisting of lowercase Latin letters. OutputPrint one integer, the number of ways of partitioning the string modulo 109 + 7.ExamplesInputabcdcdabOutput1InputabbababababbabOutput3NoteIn the first case, the only way to partition the string is ab|cd|cd|ab.In the second case, the string can be partitioned as ab|b|ab|ab|ab|ab|b|ab or ab|b|abab|abab|b|ab or abbab|ab|ab|abbab. | Inputabcdcdab | Output1 | 3 seconds | 256 megabytes | ['dp', 'string suffix structures', 'strings', '*2900'] |
F. Escape Through Leaftime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n nodes (numbered from 1 to n) rooted at node 1. Also, each node has two values associated with it. The values for i-th node are ai and bi.You can jump from a node to any node in its subtree. The cost of one jump from node x to node y is the product of ax and by. The total cost of a path formed by one or more jumps is sum of costs of individual jumps. For every node, calculate the minimum total cost to reach any leaf from that node. Pay attention, that root can never be leaf, even if it has degree 1.Note that you cannot jump from a node to itself.InputThe first line of input contains an integer n (2 ≤ n ≤ 105) — the number of nodes in the tree.The second line contains n space-separated integers a1, a2, ..., an( - 105 ≤ ai ≤ 105).The third line contains n space-separated integers b1, b2, ..., bn( - 105 ≤ bi ≤ 105).Next n - 1 lines contains two space-separated integers ui and vi (1 ≤ ui, vi ≤ n) describing edge between nodes ui and vi in the tree.OutputOutput n space-separated integers, i-th of which denotes the minimum cost of a path from node i to reach any leaf.ExamplesInput32 10 -17 -7 52 32 1Output10 50 0 Input45 -10 5 7-8 -80 -3 -102 12 41 3Output-300 100 0 0 NoteIn the first example, node 3 is already a leaf, so the cost is 0. For node 2, jump to node 3 with cost a2 × b3 = 50. For node 1, jump directly to node 3 with cost a1 × b3 = 10.In the second example, node 3 and node 4 are leaves, so the cost is 0. For node 2, jump to node 4 with cost a2 × b4 = 100. For node 1, jump to node 2 with cost a1 × b2 = - 400 followed by a jump from 2 to 4 with cost a2 × b4 = 100. | Input32 10 -17 -7 52 32 1 | Output10 50 0 | 3 seconds | 256 megabytes | ['data structures', 'dp', 'geometry', '*2700'] |
E. Team Worktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a team of N people. For a particular task, you can pick any non-empty subset of people. The cost of having x people for the task is xk. Output the sum of costs over all non-empty subsets of people.InputOnly line of input contains two integers N (1 ≤ N ≤ 109) representing total number of people and k (1 ≤ k ≤ 5000).OutputOutput the sum of costs for all non empty subsets modulo 109 + 7.ExamplesInput1 1Output1Input3 2Output24NoteIn the first example, there is only one non-empty subset {1} with cost 11 = 1.In the second example, there are seven non-empty subsets.- {1} with cost 12 = 1- {2} with cost 12 = 1- {1, 2} with cost 22 = 4- {3} with cost 12 = 1- {1, 3} with cost 22 = 4- {2, 3} with cost 22 = 4- {1, 2, 3} with cost 32 = 9The total cost is 1 + 1 + 4 + 1 + 4 + 4 + 9 = 24. | Input1 1 | Output1 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', '*2400'] |
D. Treetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a node of the tree with index 1 and with weight 0. Let cnt be the number of nodes in the tree at any instant (initially, cnt is set to 1). Support Q queries of following two types: Add a new node (index cnt + 1) with weight W and add edge between node R and this node. Output the maximum length of sequence of nodes which starts with R. Every node in the sequence is an ancestor of its predecessor. Sum of weight of nodes in sequence does not exceed X. For some nodes i, j that are consecutive in the sequence if i is an ancestor of j then w[i] ≥ w[j] and there should not exist a node k on simple path from i to j such that w[k] ≥ w[j] The tree is rooted at node 1 at any instant.Note that the queries are given in a modified way.InputFirst line containing the number of queries Q (1 ≤ Q ≤ 400000).Let last be the answer for previous query of type 2 (initially last equals 0).Each of the next Q lines contains a query of following form: 1 p q (1 ≤ p, q ≤ 1018): This is query of first type where and . It is guaranteed that 1 ≤ R ≤ cnt and 0 ≤ W ≤ 109. 2 p q (1 ≤ p, q ≤ 1018): This is query of second type where and . It is guaranteed that 1 ≤ R ≤ cnt and 0 ≤ X ≤ 1015. denotes bitwise XOR of a and b.It is guaranteed that at least one query of type 2 exists.OutputOutput the answer to each query of second type in separate line.ExamplesInput61 1 12 2 02 2 11 3 02 2 02 2 2Output0112Input61 1 02 2 02 0 31 0 22 1 32 1 6Output2232Input71 1 21 2 32 3 31 0 01 5 12 5 02 4 0Output112Input71 1 31 2 32 3 41 2 01 5 32 5 52 7 22Output123NoteIn the first example, last = 0- Query 1: 1 1 1, Node 2 with weight 1 is added to node 1.- Query 2: 2 2 0, No sequence of nodes starting at 2 has weight less than or equal to 0. last = 0 - Query 3: 2 2 1, Answer is 1 as sequence will be {2}. last = 1- Query 4: 1 2 1, Node 3 with weight 1 is added to node 2. - Query 5: 2 3 1, Answer is 1 as sequence will be {3}. Node 2 cannot be added as sum of weights cannot be greater than 1. last = 1- Query 6: 2 3 3, Answer is 2 as sequence will be {3, 2}. last = 2 | Input61 1 12 2 02 2 11 3 02 2 02 2 2 | Output0112 | 2 seconds | 512 megabytes | ['binary search', 'dp', 'trees', '*2200'] |
C. Permutation Cycletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a permutation P[1... N] of integers from 1 to N, function f is defined as follows: Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.InputThe only line contains three integers N, A, B (1 ≤ N ≤ 106, 1 ≤ A, B ≤ N).OutputIf no such permutation exists, output -1. Otherwise, output a permutation of integers from 1 to N.ExamplesInput9 2 5Output6 5 8 3 4 1 9 2 7Input3 2 1Output1 2 3 NoteIn the first example, g(1) = g(6) = g(7) = g(9) = 2 and g(2) = g(3) = g(4) = g(5) = g(8) = 5 In the second example, g(1) = g(2) = g(3) = 1 | Input9 2 5 | Output6 5 8 3 4 1 9 2 7 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', '*1600'] |
B. Recursive Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet us define two functions f and g on positive integer numbers. You need to process Q queries. In each query, you will be given three integers l, r and k. You need to print the number of integers x between l and r inclusive, such that g(x) = k. InputThe first line of the input contains an integer Q (1 ≤ Q ≤ 2 × 105) representing the number of queries. Q lines follow, each of which contains 3 integers l, r and k (1 ≤ l ≤ r ≤ 106, 1 ≤ k ≤ 9).OutputFor each query, print a single line containing the answer for that query.ExamplesInput422 73 945 64 647 55 72 62 4Output1408Input482 94 656 67 428 59 939 74 4Output3115NoteIn the first example: g(33) = 9 as g(33) = g(3 × 3) = g(9) = 9 g(47) = g(48) = g(60) = g(61) = 6 There are no such integers between 47 and 55. g(4) = g(14) = g(22) = g(27) = g(39) = g(40) = g(41) = g(58) = 4 | Input422 73 945 64 647 55 72 62 4 | Output1408 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', '*1300'] |
A. Palindromic Supersequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest".A palindrome is a string that reads the same forward or backward.The length of string B should be at most 104. It is guaranteed that there always exists such string.You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104.InputFirst line contains a string A (1 ≤ |A| ≤ 103) consisting of lowercase Latin letters, where |A| is a length of A.OutputOutput single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them.ExamplesInputabaOutputabaInputabOutputaabaaNoteIn the first example, "aba" is a subsequence of "aba" which is a palindrome.In the second example, "ab" is a subsequence of "aabaa" which is a palindrome. | Inputaba | Outputaba | 2 seconds | 256 megabytes | ['constructive algorithms', '*800'] |
C. Laboratory Worktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnya and Kirill are doing a physics laboratory work. In one of the tasks they have to measure some value n times, and then compute the average value to lower the error.Kirill has already made his measurements, and has got the following integer values: x1, x2, ..., xn. It is important that the values are close to each other, namely, the difference between the maximum value and the minimum value is at most 2.Anya does not want to make the measurements, however, she can't just copy the values from Kirill's work, because the error of each measurement is a random value, and this coincidence will be noted by the teacher. Anya wants to write such integer values y1, y2, ..., yn in her work, that the following conditions are met: the average value of x1, x2, ..., xn is equal to the average value of y1, y2, ..., yn; all Anya's measurements are in the same bounds as all Kirill's measurements, that is, the maximum value among Anya's values is not greater than the maximum value among Kirill's values, and the minimum value among Anya's values is not less than the minimum value among Kirill's values; the number of equal measurements in Anya's work and Kirill's work is as small as possible among options with the previous conditions met. Formally, the teacher goes through all Anya's values one by one, if there is equal value in Kirill's work and it is not strike off yet, he strikes off this Anya's value and one of equal values in Kirill's work. The number of equal measurements is then the total number of strike off values in Anya's work. Help Anya to write such a set of measurements that the conditions above are met.InputThe first line contains a single integer n (1 ≤ n ≤ 100 000) — the numeber of measurements made by Kirill.The second line contains a sequence of integers x1, x2, ..., xn ( - 100 000 ≤ xi ≤ 100 000) — the measurements made by Kirill. It is guaranteed that the difference between the maximum and minimum values among values x1, x2, ..., xn does not exceed 2.OutputIn the first line print the minimum possible number of equal measurements.In the second line print n integers y1, y2, ..., yn — the values Anya should write. You can print the integers in arbitrary order. Keep in mind that the minimum value among Anya's values should be not less that the minimum among Kirill's values, and the maximum among Anya's values should be not greater than the maximum among Kirill's values.If there are multiple answers, print any of them. ExamplesInput6-1 1 1 0 0 -1Output20 0 0 0 0 0 Input3100 100 101Output3101 100 100 Input7-10 -9 -10 -8 -10 -9 -9Output5-10 -10 -9 -9 -9 -9 -9 NoteIn the first example Anya can write zeros as here measurements results. The average value is then equal to the average value of Kirill's values, and there are only two equal measurements.In the second example Anya should write two values 100 and one value 101 (in any order), because it is the only possibility to make the average be the equal to the average of Kirill's values. Thus, all three measurements are equal.In the third example the number of equal measurements is 5. | Input6-1 1 1 0 0 -1 | Output20 0 0 0 0 0 | 1 second | 256 megabytes | ['implementation', 'math', '*1700'] |
B. World Cuptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe last stage of Football World Cup is played using the play-off system.There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the fourth, the fifth — with the sixth, and so on. It is guaranteed that in each round there is even number of teams. The winner of each game advances to the next round, the loser is eliminated from the tournament, there are no draws. In the last round there is the only game with two remaining teams: the round is called the Final, the winner is called the champion, and the tournament is over.Arkady wants his two favorite teams to play in the Final. Unfortunately, the team ids are already determined, and it may happen that it is impossible for teams to meet in the Final, because they are to meet in some earlier stage, if they are strong enough. Determine, in which round the teams with ids a and b can meet.InputThe only line contains three integers n, a and b (2 ≤ n ≤ 256, 1 ≤ a, b ≤ n) — the total number of teams, and the ids of the teams that Arkady is interested in. It is guaranteed that n is such that in each round an even number of team advance, and that a and b are not equal.OutputIn the only line print "Final!" (without quotes), if teams a and b can meet in the Final.Otherwise, print a single integer — the number of the round in which teams a and b can meet. The round are enumerated from 1.ExamplesInput4 1 2Output1Input8 2 6OutputFinal!Input8 7 5Output2NoteIn the first example teams 1 and 2 meet in the first round.In the second example teams 2 and 6 can only meet in the third round, which is the Final, if they win all their opponents in earlier rounds.In the third example the teams with ids 7 and 5 can meet in the second round, if they win their opponents in the first round. | Input4 1 2 | Output1 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1200'] |
A. Friends Meetingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x1 = a, another one is in the point x2 = b. Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the following rules: the first move increases the tiredness by 1, the second move increases the tiredness by 2, the third — by 3 and so on. For example, if a friend moves first to the left, then to the right (returning to the same point), and then again to the left his tiredness becomes equal to 1 + 2 + 3 = 6.The friends want to meet in a integer point. Determine the minimum total tiredness they should gain, if they meet in the same point.InputThe first line contains a single integer a (1 ≤ a ≤ 1000) — the initial position of the first friend. The second line contains a single integer b (1 ≤ b ≤ 1000) — the initial position of the second friend.It is guaranteed that a ≠ b.OutputPrint the minimum possible total tiredness if the friends meet in the same point.ExamplesInput34Output1Input10199Output2Input510Output9NoteIn the first example the first friend should move by one to the right (then the meeting happens at point 4), or the second friend should move by one to the left (then the meeting happens at point 3). In both cases, the total tiredness becomes 1.In the second example the first friend should move by one to the left, and the second friend should move by one to the right. Then they meet in the point 100, and the total tiredness becomes 1 + 1 = 2.In the third example one of the optimal ways is the following. The first friend should move three times to the right, and the second friend — two times to the left. Thus the friends meet in the point 8, and the total tiredness becomes 1 + 2 + 3 + 1 + 2 = 9. | Input34 | Output1 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', 'math', '*800'] |
E. Coins Exhibitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady and Kirill visited an exhibition of rare coins. The coins were located in a row and enumerated from left to right from 1 to k, each coin either was laid with its obverse (front) side up, or with its reverse (back) side up.Arkady and Kirill made some photos of the coins, each photo contained a segment of neighboring coins. Akrady is interested in obverses, so on each photo made by him there is at least one coin with obverse side up. On the contrary, Kirill is interested in reverses, so on each photo made by him there is at least one coin with its reverse side up.The photos are lost now, but Arkady and Kirill still remember the bounds of the segments of coins each photo contained. Given this information, compute the remainder of division by 109 + 7 of the number of ways to choose the upper side of each coin in such a way, that on each Arkady's photo there is at least one coin with obverse side up, and on each Kirill's photo there is at least one coin with reverse side up.InputThe first line contains three integers k, n and m (1 ≤ k ≤ 109, 0 ≤ n, m ≤ 105) — the total number of coins, the number of photos made by Arkady, and the number of photos made by Kirill, respectively.The next n lines contain the descriptions of Arkady's photos, one per line. Each of these lines contains two integers l and r (1 ≤ l ≤ r ≤ k), meaning that among coins from the l-th to the r-th there should be at least one with obverse side up.The next m lines contain the descriptions of Kirill's photos, one per line. Each of these lines contains two integers l and r (1 ≤ l ≤ r ≤ k), meaning that among coins from the l-th to the r-th there should be at least one with reverse side up.OutputPrint the only line — the number of ways to choose the side for each coin modulo 109 + 7 = 1000000007.ExamplesInput5 2 21 33 52 24 5Output8Input5 3 21 32 23 52 24 5Output0Input60 5 71 350 601 6030 4520 404 56 375 1850 5522 2725 3144 45Output732658600NoteIn the first example the following ways are possible ('O' — obverse, 'R' — reverse side): OROOR, ORORO, ORORR, RROOR, RRORO, RRORR, ORROR, ORRRO. In the second example the information is contradictory: the second coin should have obverse and reverse sides up at the same time, that is impossible. So, the answer is 0. | Input5 2 21 33 52 24 5 | Output8 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'math', '*2900'] |
D. Game with Tokenstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the following game for two players. There is one white token and some number of black tokens. Each token is placed on a plane in a point with integer coordinates x and y.The players take turn making moves, white starts. On each turn, a player moves all tokens of their color by 1 to up, down, left or right. Black player can choose directions for each token independently.After a turn of the white player the white token can not be in a point where a black token is located. There are no other constraints on locations of the tokens: positions of black tokens can coincide, after a turn of the black player and initially the white token can be in the same point with some black point. If at some moment the white player can't make a move, he loses. If the white player makes 10100500 moves, he wins.You are to solve the following problem. You are given initial positions of all black tokens. It is guaranteed that initially all these positions are distinct. In how many places can the white token be located initially so that if both players play optimally, the black player wins?InputThe first line contains a single integer n (1 ≤ n ≤ 105) — the number of black points.The (i + 1)-th line contains two integers xi, yi ( - 105 ≤ xi, yi, ≤ 105) — the coordinates of the point where the i-th black token is initially located.It is guaranteed that initial positions of black tokens are distinct.OutputPrint the number of points where the white token can be located initially, such that if both players play optimally, the black player wins.ExamplesInput4-2 -10 10 -32 -1Output4Input4-2 0-1 10 -21 -1Output2Input162 11 2-1 10 10 01 12 -12 01 0-1 -11 -12 20 -1-1 00 2-1 2Output4NoteIn the first and second examples initial positions of black tokens are shown with black points, possible positions of the white token (such that the black player wins) are shown with white points.The first example: The second example: In the third example the white tokens should be located in the inner square 2 × 2, to make the black player win. | Input4-2 -10 10 -32 -1 | Output4 | 2 seconds | 256 megabytes | ['data structures', 'games', 'implementation', '*2500'] |
C. Teodor is not a liar!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYoung Teodor enjoys drawing. His favourite hobby is drawing segments with integer borders inside his huge [1;m] segment. One day Teodor noticed that picture he just drawn has one interesting feature: there doesn't exist an integer point, that belongs each of segments in the picture. Having discovered this fact, Teodor decided to share it with Sasha.Sasha knows that Teodor likes to show off so he never trusts him. Teodor wants to prove that he can be trusted sometimes, so he decided to convince Sasha that there is no such integer point in his picture, which belongs to each segment. However Teodor is lazy person and neither wills to tell Sasha all coordinates of segments' ends nor wills to tell him their amount, so he suggested Sasha to ask him series of questions 'Given the integer point xi, how many segments in Fedya's picture contain that point?', promising to tell correct answers for this questions.Both boys are very busy studying and don't have much time, so they ask you to find out how many questions can Sasha ask Teodor, that having only answers on his questions, Sasha can't be sure that Teodor isn't lying to him. Note that Sasha doesn't know amount of segments in Teodor's picture. Sure, Sasha is smart person and never asks about same point twice.InputFirst line of input contains two integer numbers: n and m (1 ≤ n, m ≤ 100 000) — amount of segments of Teodor's picture and maximal coordinate of point that Sasha can ask about.ith of next n lines contains two integer numbers li and ri (1 ≤ li ≤ ri ≤ m) — left and right ends of ith segment in the picture. Note that that left and right ends of segment can be the same point.It is guaranteed that there is no integer point, that belongs to all segments.OutputSingle line of output should contain one integer number k – size of largest set (xi, cnt(xi)) where all xi are different, 1 ≤ xi ≤ m, and cnt(xi) is amount of segments, containing point with coordinate xi, such that one can't be sure that there doesn't exist point, belonging to all of segments in initial picture, if he knows only this set(and doesn't know n).ExamplesInput2 41 23 4Output4Input4 61 32 34 65 6Output5NoteFirst example shows situation where Sasha can never be sure that Teodor isn't lying to him, because even if one knows cnt(xi) for each point in segment [1;4], he can't distinguish this case from situation Teodor has drawn whole [1;4] segment.In second example Sasha can ask about 5 points e.g. 1, 2, 3, 5, 6, still not being sure if Teodor haven't lied to him. But once he knows information about all points in [1;6] segment, Sasha can be sure that Teodor haven't lied to him. | Input2 41 23 4 | Output4 | 1 second | 256 megabytes | ['data structures', 'dp', '*1900'] |
B. Game with Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string t = sk + 1sk + 2... sns1s2... sk. Vasya does not know the integer k nor the string t, but he wants to guess the integer k. To do this, he asks Kolya to tell him the first letter of the new string, and then, after he sees it, open one more letter on some position, which Vasya can choose.Vasya understands, that he can't guarantee that he will win, but he wants to know the probability of winning, if he plays optimally. He wants you to compute this probability. Note that Vasya wants to know the value of k uniquely, it means, that if there are at least two cyclic shifts of s that fit the information Vasya knowns, Vasya loses. Of course, at any moment of the game Vasya wants to maximize the probability of his win.InputThe only string contains the string s of length l (3 ≤ l ≤ 5000), consisting of small English letters only.OutputPrint the only number — the answer for the problem. You answer is considered correct, if its absolute or relative error does not exceed 10 - 6.Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if ExamplesInputtechnocupOutput1.000000000000000InputtictictactacOutput0.333333333333333InputbbaabaabbbOutput0.100000000000000NoteIn the first example Vasya can always open the second letter after opening the first letter, and the cyclic shift is always determined uniquely.In the second example if the first opened letter of t is "t" or "c", then Vasya can't guess the shift by opening only one other letter. On the other hand, if the first letter is "i" or "a", then he can open the fourth letter and determine the shift uniquely. | Inputtechnocup | Output1.000000000000000 | 2 seconds | 256 megabytes | ['implementation', 'probabilities', 'strings', '*1600'] |
A. Peculiar apple-treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.InputFirst line of input contains single integer number n (2 ≤ n ≤ 100 000) — number of inflorescences.Second line of input contains sequence of n - 1 integer numbers p2, p3, ..., pn (1 ≤ pi < i), where pi is number of inflorescence into which the apple from i-th inflorescence rolls down.OutputSingle line of output should contain one integer number: amount of apples that Arcady will be able to collect from first inflorescence during one harvest.ExamplesInput31 1Output1Input51 2 2 2Output3Input181 1 1 4 4 3 2 2 2 10 8 9 9 9 10 10 4Output4NoteIn first example Arcady will be able to collect only one apple, initially situated in 1st inflorescence. In next second apples from 2nd and 3rd inflorescences will roll down and annihilate, and Arcady won't be able to collect them.In the second example Arcady will be able to collect 3 apples. First one is one initially situated in first inflorescence. In a second apple from 2nd inflorescence will roll down to 1st (Arcady will collect it) and apples from 3rd, 4th, 5th inflorescences will roll down to 2nd. Two of them will annihilate and one not annihilated will roll down from 2-nd inflorescence to 1st one in the next second and Arcady will collect it. | Input31 1 | Output1 | 1 second | 256 megabytes | ['dfs and similar', 'graphs', 'trees', '*1500'] |
D. Пограничные вратаограничение по времени на тест1 секундаограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводГерой Аркадий находится на узкой полоске земли, разделенной на n зон, пронумерованных от 1 до n. Из i-й зоны можно пройти лишь в (i - 1)-ю зону и в (i + 1)-ю зону, если они существуют. При этом между каждой парой соседних зон находятся пограничные врата, которые могут быть разных цветов, цвет врат между i-й и (i + 1)-й зоной равен gi.Аркадий может пройти пограничные врата некоторого цвета, только если он перед этим побывал в одном из шатров хранителей ключей этого цвета и взял ключ. В каждой зоне находится ровно один шатер хранителя ключей некоторого цвета, цвет шатра в i-й зоне равен ki. После посещения шатра определенного цвета Аркадий может неограниченное число раз проходить через любые врата этого цвета.На проход через одни врата Аркадий тратит один ход, на посещение шатра и другие перемещения ходы не требуются. За какое минимальное число ходов Аркадий может попасть из зоны a в зону b, если изначально у него нет никаких ключей?Входные данныеПервая строка содержит три целых числа n, a, b (2 ≤ n ≤ 100 000, 1 ≤ a, b ≤ n, a ≠ b) — число зон, номер начальной зоны и номер конечной зоны, соответственно.Вторая строка содержит n - 1 целое число g1, g2, ..., gn - 1 (1 ≤ gi ≤ 100 000), где gi означает цвет пограничных врат между зонами i и i + 1.Третья строка содержит n целых чисел k1, k2, ..., kn (1 ≤ ki ≤ 100 000), где ki означает цвет шатра хранителя ключей в i-й зоне.Выходные данныеЕсли Аркадий не может попасть из зоны a в зону b, не имея изначально ключей, выведите -1.Иначе выведите минимальное количество ходов, которое потребуется Аркадию.ПримерыВходные данные5 4 13 1 1 27 1 2 1 3Выходные данные7Входные данные5 1 54 3 2 14 3 2 5 5Выходные данные-1ПримечаниеВ первом примере, чтобы попасть из зоны 4 в зону 1, Аркадию нужно сначала взять ключ цвета 1, пройти в зону 3, там взять ключ цвета 2 и пройти обратно в зону 4 и затем в зону 5, взять там ключ цвета 3 и дойти до зоны 1 за четыре хода.Во втором примере Аркадий может дойти лишь до четвертой зоны, так как шатров хранителей ключей цвета 1 нет совсем. | Входные данные5 4 13 1 1 27 1 2 1 3 | Выходные данные7 | ограничение по времени на тест1 секунда | ограничение по памяти на тест256 мегабайт | ['*2400'] |
C. Красивая командаограничение по времени на тест1 секундаограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводЗавтра у хоккейной команды, которой руководит Евгений, важный матч. Евгению нужно выбрать шесть игроков, которые выйдут на лед в стартовом составе: один вратарь, два защитника и три нападающих.Так как это стартовый состав, Евгения больше волнует, насколько красива будет команда на льду, чем способности игроков. А именно, Евгений хочет выбрать такой стартовый состав, чтобы номера любых двух игроков из стартового состава отличались не более, чем в два раза. Например, игроки с номерами 13, 14, 10, 18, 15 и 20 устроят Евгения, а если, например, на лед выйдут игроки с номерами 8 и 17, то это не устроит Евгения.Про каждого из игроков вам известно, на какой позиции он играет (вратарь, защитник или нападающий), а также его номер. В хоккее номера игроков не обязательно идут подряд. Посчитайте число различных стартовых составов из одного вратаря, двух защитников и трех нападающих, которые может выбрать Евгений, чтобы выполнялось его условие красоты.Входные данныеПервая строка содержит три целых числа g, d и f (1 ≤ g ≤ 1 000, 1 ≤ d ≤ 1 000, 1 ≤ f ≤ 1 000) — число вратарей, защитников и нападающих в команде Евгения. Вторая строка содержит g целых чисел, каждое в пределах от 1 до 100 000 — номера вратарей.Третья строка содержит d целых чисел, каждое в пределах от 1 до 100 000 — номера защитников.Четвертая строка содержит f целых чисел, каждое в пределах от 1 до 100 000 — номера нападающих.Гарантируется, что общее количество игроков не превосходит 1 000, т. е. g + d + f ≤ 1 000. Все g + d + f номеров игроков различны.Выходные данныеВыведите одно целое число — количество возможных стартовых составов.ПримерыВходные данные1 2 31510 1920 11 13Выходные данные1Входные данные2 3 416 4020 12 1913 21 11 10Выходные данные6ПримечаниеВ первом примере всего один вариант для выбора состава, который удовлетворяет описанным условиям, поэтому ответ 1.Во втором примере подходят следующие игровые сочетания (в порядке вратарь-защитник-защитник-нападающий-нападающий-нападающий): 16 20 12 13 21 11 16 20 12 13 11 10 16 20 19 13 21 11 16 20 19 13 11 10 16 12 19 13 21 11 16 12 19 13 11 10 Таким образом, ответ на этот пример — 6. | Входные данные1 2 31510 1920 11 13 | Выходные данные1 | ограничение по времени на тест1 секунда | ограничение по памяти на тест256 мегабайт | ['*special problem', 'combinatorics', 'math', '*1700'] |
B. Места в самолётеограничение по времени на тест1 секундаограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводВ самолёте есть n рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа.Известно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, которые часто летают) и обычные. Перед вами стоит задача рассадить ещё k обычных пассажиров так, чтобы суммарное число соседей у статусных пассажиров было минимально возможным. Два пассажира считаются соседями, если они сидят в одном ряду и между ними нет других мест и прохода между рядами. Если пассажир является соседним пассажиром для двух статусных пассажиров, то его следует учитывать в сумме соседей дважды.Входные данныеВ первой строке следуют два целых числа n и k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10·n) — количество рядов мест в самолёте и количество пассажиров, которых нужно рассадить.Далее следует описание рядов мест самолёта по одному ряду в строке. Если очередной символ равен '-', то это проход между рядами. Если очередной символ равен '.', то это свободное место. Если очередной символ равен 'S', то на текущем месте будет сидеть статусный пассажир. Если очередной символ равен 'P', то на текущем месте будет сидеть обычный пассажир. Гарантируется, что количество свободных мест не меньше k. Гарантируется, что все ряды удовлетворяют описанному в условии формату.Выходные данныеВ первую строку выведите минимальное суммарное число соседей у статусных пассажиров.Далее выведите план рассадки пассажиров, который минимизирует суммарное количество соседей у статусных пассажиров, в том же формате, что и во входных данных. Если в свободное место нужно посадить одного из k пассажиров, выведите строчную букву 'x' вместо символа '.'. ПримерыВходные данные1 2SP.-SS.S-S.SВыходные данные5SPx-SSxS-S.SВходные данные4 9PP.-PPPS-S.SPSP-PPSP-.S..S.-S..P-SS.P.S-P.PP-PSPВыходные данные15PPx-PPPS-S.SPSP-PPSP-xSxxSx-SxxP-SSxP.S-PxPP-PSPПримечаниеВ первом примере нужно посадить ещё двух обычных пассажиров. Для минимизации соседей у статусных пассажиров, нужно посадить первого из них на третье слева место, а второго на любое из оставшихся двух мест, так как независимо от выбора места он станет соседом двух статусных пассажиров. Изначально, у статусного пассажира, который сидит на самом левом месте уже есть сосед. Также на четвёртом и пятом местах слева сидят статусные пассажиры, являющиеся соседями друг для друга (что добавляет к сумме 2).Таким образом, после посадки ещё двух обычных пассажиров, итоговое суммарное количество соседей у статусных пассажиров станет равно пяти. | Входные данные1 2SP.-SS.S-S.S | Выходные данные5SPx-SSxS-S.S | ограничение по времени на тест1 секунда | ограничение по памяти на тест256 мегабайт | ['*special problem', 'implementation', '*1300'] |
A. Прокат велосипедовограничение по времени на тест1 секундаограничение по памяти на тест256 мегабайтвводстандартный вводвыводстандартный выводКак известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x1 километров вдоль улицы, второй — в точке x2 и так далее, n-й велопрокат находится в точке xn. Школа Аркадия находится в точке x1 (то есть там же, где и первый велопрокат), а дом — в точке xn (то есть там же, где и n-й велопрокат). Известно, что xi < xi + 1 для всех 1 ≤ i < n.Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.Входные данныеВ первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде.В следующей строке следует последовательность целых чисел x1, x2, ..., xn (0 ≤ x1 < x2 < ... < xn ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.Выходные данныеЕсли Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.ПримерыВходные данные4 43 6 8 10Выходные данные2Входные данные2 910 20Выходные данные-1Входные данные12 34 6 7 9 10 11 13 15 17 18 20 21Выходные данные6ПримечаниеВ первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах. | Входные данные4 43 6 8 10 | Выходные данные2 | ограничение по времени на тест1 секунда | ограничение по памяти на тест256 мегабайт | ['*special problem', 'greedy', 'implementation', '*1400'] |
D. Autocompletiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArcady is a copywriter. His today's task is to type up an already well-designed story using his favorite text editor.Arcady types words, punctuation signs and spaces one after another. Each letter and each sign (including line feed) requires one keyboard click in order to be printed. Moreover, when Arcady has a non-empty prefix of some word on the screen, the editor proposes a possible autocompletion for this word, more precisely one of the already printed words such that its prefix matches the currently printed prefix if this word is unique. For example, if Arcady has already printed «codeforces», «coding» and «codeforces» once again, then there will be no autocompletion attempt for «cod», but if he proceeds with «code», the editor will propose «codeforces».With a single click Arcady can follow the editor's proposal, i.e. to transform the current prefix to it. Note that no additional symbols are printed after the autocompletion (no spaces, line feeds, etc). What is the minimum number of keyboard clicks Arcady has to perform to print the entire text, if he is not allowed to move the cursor or erase the already printed symbols?A word here is a contiguous sequence of latin letters bordered by spaces, punctuation signs and line/text beginnings/ends. Arcady uses only lowercase letters. For example, there are 20 words in «it's well-known that tic-tac-toe is a paper-and-pencil game for two players, x and o.».InputThe only line contains Arcady's text, consisting only of lowercase latin letters, spaces, line feeds and the following punctuation signs: «.», «,», «?», «!», «'» and «-». The total amount of symbols doesn't exceed 3·105. It's guaranteed that all lines are non-empty.OutputPrint a single integer — the minimum number of clicks.ExamplesInputsnow affects sports such as skiing, snowboarding, and snowmachine travel.snowboarding is a recreational activity and olympic and paralympic sport.Output141Input'co-co-co, codeforces?!'Output25Inputthun-thun-thunder, thunder, thunderthunder, thun-, thunderthun-thun-thunder, thunderthunder, feel the thunderlightning then the thunderthunder, feel the thunderlightning then the thunderthunder, thunderOutput183NoteIn sample case one it's optimal to use autocompletion for the first instance of «snowboarding» after typing up «sn» and for the second instance of «snowboarding» after typing up «snowb». This will save 7 clicks.In sample case two it doesn't matter whether to use autocompletion or not. | Inputsnow affects sports such as skiing, snowboarding, and snowmachine travel.snowboarding is a recreational activity and olympic and paralympic sport. | Output141 | 1 second | 256 megabytes | ['*special problem', 'strings', 'trees', '*1900'] |
C. Dependency managementtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is currently developing a project in Vaja language and using a popular dependency management system called Vamen. From Vamen's point of view both Vaja project and libraries are treated projects for simplicity.A project in Vaja has its own uniqie non-empty name consisting of lowercase latin letters with length not exceeding 10 and version — positive integer from 1 to 106. Each project (keep in mind that it is determined by both its name and version) might depend on other projects. For sure, there are no cyclic dependencies.You're given a list of project descriptions. The first of the given projects is the one being developed by Polycarp at this moment. Help Polycarp determine all projects that his project depends on (directly or via a certain chain). It's possible that Polycarp's project depends on two different versions of some project. In this case collision resolving is applied, i.e. for each such project the system chooses the version that minimizes the distance from it to Polycarp's project. If there are several options, the newer (with the maximum version) is preferred. This version is considered actual; other versions and their dependencies are ignored.More formal, choose such a set of projects of minimum possible size that the following conditions hold: Polycarp's project is chosen; Polycarp's project depends (directly or indirectly) on all other projects in the set; no two projects share the name; for each project x that some other project in the set depends on we have either x or some y with other version and shorter chain to Polycarp's project chosen. In case of ties the newer one is chosen. Output all Polycarp's project's dependencies (Polycarp's project itself should't be printed) in lexicographical order.InputThe first line contains an only integer n (1 ≤ n ≤ 1 000) — the number of projects in Vaja.The following lines contain the project descriptions. Each project is described by a line consisting of its name and version separated by space. The next line gives the number of direct dependencies (from 0 to n - 1) and the dependencies themselves (one in a line) in arbitrary order. Each dependency is specified by its name and version. The projects are also given in arbitrary order, but the first of them is always Polycarp's. Project descriptions are separated by one empty line. Refer to samples for better understanding.It's guaranteed that there are no cyclic dependencies. OutputOutput all Polycarp's project's dependencies in lexicographical order.ExamplesInput4a 32b 1c 1 b 20 b 11b 2 c 11b 2Output2b 1c 1Input9codehorses 53webfrmk 6mashadb 1mashadb 2 commons 20 mashadb 30 webfrmk 62mashadb 3commons 2 extra 41extra 3 extra 30 extra 10 mashadb 11extra 3 mashadb 21extra 1Output4commons 2extra 1mashadb 2webfrmk 6Input3abc 12abc 3cba 2abc 30cba 20Output1cba 2NoteThe first sample is given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «a» (version 3) depends on are painted black. The second sample is again given in the pic below. Arrow from A to B means that B directly depends on A. Projects that Polycarp's project «codehorses» (version 5) depends on are paint it black. Note that «extra 1» is chosen instead of «extra 3» since «mashadb 1» and all of its dependencies are ignored due to «mashadb 2». | Input4a 32b 1c 1 b 20 b 11b 2 c 11b 2 | Output2b 1c 1 | 4 seconds | 256 megabytes | ['*special problem', 'graphs', 'implementation', '*1900'] |
B. Chattime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to n where n is the total number of messages in the chat.Each message might contain a link to an earlier message which it is a reply to. When opening a message x or getting a link to it, the dialogue is shown in such a way that k previous messages, message x and k next messages are visible (with respect to message x). In case there are less than k messages somewhere, they are yet all shown.Digging deep into your message history, you always read all visible messages and then go by the link in the current message x (if there is one) and continue reading in the same manner.Determine the number of messages you'll read if your start from message number t for all t from 1 to n. Calculate these numbers independently. If you start with message x, the initial configuration is x itself, k previous and k next messages. Messages read multiple times are considered as one.InputThe first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ n) — the total amount of messages and the number of previous and next messages visible.The second line features a sequence of integers a1, a2, ..., an (0 ≤ ai < i), where ai denotes the i-th message link destination or zero, if there's no link from i. All messages are listed in chronological order. It's guaranteed that the link from message x goes to message with number strictly less than x.OutputPrint n integers with i-th denoting the number of distinct messages you can read starting from message i and traversing the links while possible.ExamplesInput6 00 1 1 2 3 2Output1 2 2 3 3 3 Input10 10 1 0 3 4 5 2 3 7 0Output2 3 3 4 5 6 6 6 8 2 Input2 20 1Output2 2 NoteConsider i = 6 in sample case one. You will read message 6, then 2, then 1 and then there will be no link to go.In the second sample case i = 6 gives you messages 5, 6, 7 since k = 1, then 4, 5, 6, then 2, 3, 4 and then the link sequence breaks. The number of distinct messages here is equal to 6. | Input6 00 1 1 2 3 2 | Output1 2 2 3 3 3 | 1 second | 256 megabytes | ['*special problem', 'dp', '*1400'] |
A. Login Verificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins s and t are considered similar if we can transform s to t via a sequence of operations of the following types: transform lowercase letters to uppercase and vice versa; change letter «O» (uppercase latin letter) to digit «0» and vice versa; change digit «1» (one) to any letter among «l» (lowercase latin «L»), «I» (uppercase latin «i») and vice versa, or change one of these letters to other. For example, logins «Codeforces» and «codef0rces» as well as «OO0OOO00O0OOO0O00OOO0OO_lol» and «OO0OOO0O00OOO0O00OO0OOO_1oI» are considered similar whereas «Codeforces» and «Code_forces» are not.You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.InputThe first line contains a non-empty string s consisting of lower and uppercase latin letters, digits and underline symbols («_») with length not exceeding 50 — the login itself.The second line contains a single integer n (1 ≤ n ≤ 1 000) — the number of existing logins.The next n lines describe the existing logins, following the same constraints as the user login (refer to the first line of the input). It's guaranteed that no two existing logins are similar.OutputPrint «Yes» (without quotes), if user can register via this login, i.e. none of the existing logins is similar with it.Otherwise print «No» (without quotes).ExamplesInput1_wat22_watwat_1OutputYesInput000300ooAoOoOutputNoInput_i_3__i__1_IOutputNoInputLa032a0La11a0OutputNoInputabc1aBcOutputNoInput0Lil2LIL00RilOutputYesNoteIn the second sample case the user wants to create a login consisting of three zeros. It's impossible due to collision with the third among the existing.In the third sample case the new login is similar with the second one. | Input1_wat22_watwat_1 | OutputYes | 1 second | 256 megabytes | ['*special problem', 'strings', '*1200'] |
J. Segmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a straight line colored in white. n black segments are added on it one by one.After each segment is added, determine the number of connected components of black segments (i. e. the number of black segments in the union of the black segments). In particular, if one segment ends in a point x, and another segment starts in the point x, these two segments belong to the same connected component.InputThe first line contains a single integer n (1 ≤ n ≤ 200 000) — the number of segments.The i-th of the next n lines contains two integers li and ri (1 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. The segments are listed in the order they are added on the white line.OutputPrint n integers — the number of connected components of black segments after each segment is added. ExamplesInput31 34 52 4Output1 2 1 Input910 2050 6030 4070 8090 10060 7010 4040 5080 90Output1 2 3 4 5 4 3 2 1 NoteIn the first example there are two components after the addition of the first two segments, because these segments do not intersect. The third added segment intersects the left segment and touches the right segment at the point 4 (these segments belong to the same component, according to the statements). Thus the number of connected components of black segments is equal to 1 after that. | Input31 34 52 4 | Output1 2 1 | 1 second | 256 megabytes | ['data structures', '*2100'] |
I. A Vital Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a strict daily schedule. He has n alarms set for each day, and the i-th alarm rings each day at the same time during exactly one minute.Determine the longest time segment when Polycarp can sleep, i. e. no alarm rings in that period. It is possible that Polycarp begins to sleep in one day, and wakes up in another.InputThe first line contains a single integer n (1 ≤ n ≤ 100) — the number of alarms.Each of the next n lines contains a description of one alarm. Each description has a format "hh:mm", where hh is the hour when the alarm rings, and mm is the minute of that hour when the alarm rings. The number of hours is between 0 and 23, and the number of minutes is between 0 and 59. All alarm times are distinct. The order of the alarms is arbitrary.Each alarm starts ringing in the beginning of the corresponding minute and rings for exactly one minute (i. e. stops ringing in the beginning of the next minute). Polycarp can start sleeping instantly when no alarm is ringing, and he wakes up at the moment when some alarm starts ringing.OutputPrint a line in format "hh:mm", denoting the maximum time Polycarp can sleep continuously. hh denotes the number of hours, and mm denotes the number of minutes. The number of minutes should be between 0 and 59. Look through examples to understand the format better.ExamplesInput105:43Output23:59Input422:0003:2116:0309:59Output06:37NoteIn the first example there is only one alarm which rings during one minute of a day, and then rings again on the next day, 23 hours and 59 minutes later. Polycarp can sleep all this time. | Input105:43 | Output23:59 | 1 second | 256 megabytes | ['*1700'] |
Subsets and Splits