problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
βŒ€
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
B. Biridian Foresttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.The forestThe Biridian Forest is a two-dimensional grid consisting of r rows and c columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example): MovesBreeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions: Do nothing. Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees. If you are located on the exit cell, you may leave the forest. Only you can perform this move β€” all other mikemon breeders will never leave the forest by using this type of movement. After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).Mikemon battleIf you and t (t > 0) mikemon breeders are located on the same cell, exactly t mikemon battles will ensue that time (since you will be battling each of those t breeders once). After the battle, all of those t breeders will leave the forest to heal their respective mikemons.Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders β€” there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).Your goalYou would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.Goal of other breedersBecause you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.Your taskPrint the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.InputThe first line consists of two integers: r and c (1 ≀ r, c ≀ 1000), denoting the number of rows and the number of columns in Biridian Forest. The next r rows will each depict a row of the map, where each character represents the content of a single cell: 'T': A cell occupied by a tree. 'S': An empty cell, and your starting position. There will be exactly one occurence of this in the map. 'E': An empty cell, and where the exit is located. There will be exactly one occurence of this in the map. A digit (0-9): A cell represented by a digit X means that the cell is empty and is occupied by X breeders (in particular, if X is zero, it means that the cell is not occupied by any breeder). It is guaranteed that it will be possible for you to go from your starting position to the exit cell through a sequence of moves.OutputA single line denoted the minimum possible number of mikemon battles that you have to participate in if you pick a strategy that minimize this number.ExamplesInput5 7000E0T3T0TT0T0010T0T02T0T0T00T0S000Output3Input1 4SE23Output2NoteThe following picture illustrates the first example. The blue line denotes a possible sequence of moves that you should post in your blog: The three breeders on the left side of the map will be able to battle you β€” the lone breeder can simply stay in his place until you come while the other two breeders can move to where the lone breeder is and stay there until you come. The three breeders on the right does not have a way to battle you, so they will stay in their place.For the second example, you should post this sequence in your Blog: Here's what happens. First, you move one cell to the right. Then, the two breeders directly to the right of the exit will simultaneously move to the left. The other three breeder cannot battle you so they will do nothing. You end up in the same cell with 2 breeders, so 2 mikemon battles are conducted. After those battles, all of your opponents leave the forest. Finally, you make another move by leaving the forest.
Input5 7000E0T3T0TT0T0010T0T02T0T0T00T0S000
Output3
2 seconds
256 megabytes
['dfs and similar', 'shortest paths', '*1500']
A. Purificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an n × n grid. The rows are numbered 1 through n from top to bottom, and the columns are numbered 1 through n from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The cleaning of all evil will awaken the door! Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile β€” then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.You would like to purify all n × n cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.InputThe first line will contain a single integer n (1 ≀ n ≀ 100). Then, n lines follows, each contains n characters. The j-th character in the i-th row represents the cell located at row i and column j. It will be the character 'E' if it is a particularly more evil cell, and '.' otherwise.OutputIf there exists no way to purify all the cells, output -1. Otherwise, if your solution casts x "Purification" spells (where x is the minimum possible number of spells), output x lines. Each line should consist of two integers denoting the row and column numbers of the cell on which you should cast the "Purification" spell.ExamplesInput3.E.E.E.E.Output1 12 23 3Input3EEEE..E.EOutput-1Input5EE.EEE.EE.E...E.EE.EEE.EEOutput3 31 32 24 45 3NoteThe first example is illustrated as follows. Purple tiles are evil tiles that have not yet been purified. Red tile is the tile on which "Purification" is cast. Yellow tiles are the tiles being purified as a result of the current "Purification" spell. Green tiles are tiles that have been purified previously. In the second example, it is impossible to purify the cell located at row 1 and column 1.For the third example:
Input3.E.E.E.E.
Output1 12 23 3
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1500']
B. Sheldon and Ice Piecestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDo you remember how Kai constructed the word "eternity" using pieces of ice as components?Little Sheldon plays with pieces of ice, each piece has exactly one digit between 0 and 9. He wants to construct his favourite number t. He realized that digits 6 and 9 are very similar, so he can rotate piece of ice with 6 to use as 9 (and vice versa). Similary, 2 and 5 work the same. There is no other pair of digits with similar effect. He called this effect "Digital Mimicry".Sheldon favourite number is t. He wants to have as many instances of t as possible. How many instances he can construct using the given sequence of ice pieces. He can use any piece at most once. InputThe first line contains integer t (1 ≀ t ≀ 10000). The second line contains the sequence of digits on the pieces. The length of line is equal to the number of pieces and between 1 and 200, inclusive. It contains digits between 0 and 9.OutputPrint the required number of instances.ExamplesInput4223454Output2Input16912118999Output1NoteThis problem contains very weak pretests.
Input4223454
Output2
1 second
256 megabytes
['greedy', '*1500']
A. IQ Testtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.Arithmetic progression is a sequence a1, a1 + d, a1 + 2d, ..., a1 + (n - 1)d, where a1 and d are any numbers.Geometric progression is a sequence b1, b2 = b1q, ..., bn = bn - 1q, where b1 ≠ 0, q ≠ 0, q ≠ 1. Help Petya and write a program to determine if the given sequence is arithmetic or geometric. Also it should found the next number. If the sequence is neither arithmetic nor geometric, print 42 (he thinks it is impossible to find better answer). You should also print 42 if the next element of progression is not integer. So answer is always integer.InputThe first line contains exactly four integer numbers between 1 and 1000, inclusively.OutputPrint the required number. If the given sequence is arithmetic progression, print the next progression element. Similarly, if the given sequence is geometric progression, print the next progression element.Print 42 if the given sequence is not an arithmetic or geometric progression.ExamplesInput836 624 412 200Output-12Input1 334 667 1000Output1333NoteThis problem contains very weak pretests!
Input836 624 412 200
Output-12
1 second
256 megabytes
['implementation', '*1800']
E. Axis Walkingtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIahub wants to meet his girlfriend Iahubina. They both live in Ox axis (the horizontal axis). Iahub lives at point 0 and Iahubina at point d.Iahub has n positive integers a1, a2, ..., an. The sum of those numbers is d. Suppose p1, p2, ..., pn is a permutation of {1, 2, ..., n}. Then, let b1 = ap1, b2 = ap2 and so on. The array b is called a "route". There are n! different routes, one for each permutation p.Iahub's travel schedule is: he walks b1 steps on Ox axis, then he makes a break in point b1. Then, he walks b2 more steps on Ox axis and makes a break in point b1 + b2. Similarly, at j-th (1 ≀ j ≀ n) time he walks bj more steps on Ox axis and makes a break in point b1 + b2 + ... + bj.Iahub is very superstitious and has k integers which give him bad luck. He calls a route "good" if he never makes a break in a point corresponding to one of those k numbers. For his own curiosity, answer how many good routes he can make, modulo 1000000007 (109 + 7). InputThe first line contains an integer n (1 ≀ n ≀ 24). The following line contains n integers: a1, a2, ..., an (1 ≀ ai ≀ 109). The third line contains integer k (0 ≀ k ≀ 2). The fourth line contains k positive integers, representing the numbers that give Iahub bad luck. Each of these numbers does not exceed 109.OutputOutput a single integer β€” the answer of Iahub's dilemma modulo 1000000007 (109 + 7). ExamplesInput32 3 525 7Output1Input32 2 221 3Output6NoteIn the first case consider six possible orderings: [2, 3, 5]. Iahub will stop at position 2, 5 and 10. Among them, 5 is bad luck for him. [2, 5, 3]. Iahub will stop at position 2, 7 and 10. Among them, 7 is bad luck for him. [3, 2, 5]. He will stop at the unlucky 5. [3, 5, 2]. This is a valid ordering. [5, 2, 3]. He got unlucky twice (5 and 7). [5, 3, 2]. Iahub would reject, as it sends him to position 5. In the second case, note that it is possible that two different ways have the identical set of stopping. In fact, all six possible ways have the same stops: [2, 4, 6], so there's no bad luck for Iahub.
Input32 3 525 7
Output1
3 seconds
512 megabytes
['bitmasks', 'combinatorics', 'constructive algorithms', 'dp', 'meet-in-the-middle', '*2300']
D. Block Towertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with n rows and m columns (it contains n × m cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any building. The rest of cells are empty. In some empty cell Iahub can build exactly one tower of two following types: Blue towers. Each has population limit equal to 100. Red towers. Each has population limit equal to 200. However, it can be built in some cell only if in that moment at least one of the neighbouring cells has a Blue Tower. Two cells are neighbours is they share a side. Iahub is also allowed to destroy a building from any cell. He can do this operation as much as he wants. After destroying a building, the other buildings are not influenced, and the destroyed cell becomes empty (so Iahub can build a tower in this cell if needed, see the second example for such a case).Iahub can convince as many population as he wants to come into his city. So he needs to configure his city to allow maximum population possible. Therefore he should find a sequence of operations that builds the city in an optimal way, so that total population limit is as large as possible.He says he's the best at this game, but he doesn't have the optimal solution. Write a program that calculates the optimal one, to show him that he's not as good as he thinks. InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 500). Each of the next n lines contains m characters, describing the grid. The j-th character in the i-th line is '.' if you're allowed to build at the cell with coordinates (i, j) a tower (empty cell) or '#' if there is a big hole there. OutputPrint an integer k in the first line (0 ≀ k ≀ 106) β€” the number of operations Iahub should perform to obtain optimal result.Each of the following k lines must contain a single operation in the following format: Β«B x yΒ» (1 ≀ x ≀ n, 1 ≀ y ≀ m) β€” building a blue tower at the cell (x, y); Β«R x yΒ» (1 ≀ x ≀ n, 1 ≀ y ≀ m) β€” building a red tower at the cell (x, y); Β«D x yΒ» (1 ≀ x ≀ n, 1 ≀ y ≀ m) β€” destroying a tower at the cell (x, y). If there are multiple solutions you can output any of them. Note, that you shouldn't minimize the number of operations.ExamplesInput2 3..#.#.Output4B 1 1R 1 2R 2 1B 2 3Input1 3...Output5B 1 1B 1 2R 1 3D 1 2R 1 2
Input2 3..#.#.
Output4B 1 1R 1 2R 2 1B 2 3
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', '*1900']
C. Magic Fivetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.Now Iahub wants to count the number of ways he can obtain magic number, modulo 1000000007 (109 + 7). Two ways are different, if the set of deleted positions in s differs.Look at the input part of the statement, s is given in a special form.InputIn the first line you're given a string a (1 ≀ |a| ≀ 105), containing digits only. In the second line you're given an integer k (1 ≀ k ≀ 109). The plate s is formed by concatenating k copies of a together. That is n = |a|Β·k.OutputPrint a single integer β€” the required number of ways modulo 1000000007 (109 + 7).ExamplesInput12561Output4Input139902Output528Input5552Output63NoteIn the first case, there are four possible ways to make a number that is divisible by 5: 5, 15, 25 and 125.In the second case, remember to concatenate the copies of a. The actual plate is 1399013990.In the third case, except deleting all digits, any choice will do. Therefore there are 26 - 1 = 63 possible ways to delete digits.
Input12561
Output4
1 second
256 megabytes
['combinatorics', 'math', '*1700']
B. Hungry Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: Its elements are in increasing order. That is an inequality ai < aj holds for any two indices i, j (i < j). For any two indices i and j (i < j), aj must not be divisible by ai. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with n elements.InputThe input contains a single integer: n (1 ≀ n ≀ 105).OutputOutput a line that contains n space-separated integers a1 a2, ..., an (1 ≀ ai ≀ 107), representing a possible Hungry sequence. Note, that each ai must not be greater than 10000000 (107) and less than 1.If there are multiple solutions you can output any one.ExamplesInput3Output2 9 15Input5Output11 14 20 27 31
Input3
Output2 9 15
1 second
256 megabytes
['math', '*1200']
A. Flipping Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≀ i ≀ j ≀ n) and flips all values ak for which their positions are in range [i, j] (that is i ≀ k ≀ j). Flip the value of x means to apply operation x = 1 - x.The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.InputThe first line of the input contains an integer n (1 ≀ n ≀ 100). In the second line of the input there are n integers: a1, a2, ..., an. It is guaranteed that each of those n values is either 0 or 1.OutputPrint an integer β€” the maximal number of 1s that can be obtained after exactly one move. ExamplesInput51 0 0 1 0Output4Input41 0 0 1Output4NoteIn the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1].In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.
Input51 0 0 1 0
Output4
1 second
256 megabytes
['brute force', 'dp', 'implementation', '*1200']
E. The Red Buttontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPiegirl found the red button. You have one last chance to change the inevitable end.The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2Β·i) modulo n or node (2Β·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once. Your task is to find any such order and print it. If there is no such order, print -1.InputInput consists of a single integer n (2 ≀ n ≀ 105).OutputPrint an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.ExamplesInput2Output0 1 0Input3Output-1Input4Output0 1 3 2 0Input16Output0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0
Input2
Output0 1 0
1 second
256 megabytes
['combinatorics', 'dfs and similar', 'dsu', 'graphs', 'greedy', '*2800']
D. Reclamationtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn a far away land, there exists a planet shaped like a cylinder. There are three regions in this planet: top, bottom, and side as shown in the following picture. Both the top and the bottom areas consist of big cities. The side area consists entirely of the sea.One day, a city decides that it has too little space and would like to reclamate some of the side area into land. The side area can be represented by a grid with r rows and c columns β€” each cell represents a rectangular area in the side area. The rows are numbered 1 through r from top to bottom, while the columns are numbered 1 through c from left to right. Two cells are adjacent if they share a side. In addition, two cells located on the same row β€” one in the leftmost column, and the other in the rightmost column β€” are also adjacent.Initially, all of the cells are occupied by the sea. The plan is to turn some of those cells into land one by one in a particular order that will be given to you.However, the sea on the side area is also used as a major trade route. More formally, it is not allowed to reclamate the sea cells into land in such way that there does not exist a sequence of cells with the following property: All cells in the sequence are occupied by the sea (i.e., they are not reclamated). The first cell in the sequence is in the top row. The last cell in the sequence is in the bottom row. Consecutive cells in the sequence are adjacent. Thus, the plan is revised. Each time a cell is going to be turned from sea to land, the city first needs to check whether or not it would violate the above condition by doing that. If it would, then the cell is not turned into land and the plan proceeds into the next cell. Otherwise, the cell is turned into land.Your job is to simulate this and output the number of cells that were successfully turned into land.InputThe first line consists of three integers r, c, and n (1 ≀ r, c ≀ 3000, 1 ≀ n ≀ 3Β·105). Then, n lines follow, describing the cells in the order you will reclamate them. Each line will consists of two integers: ri and ci (1 ≀ ri ≀ r, 1 ≀ ci ≀ c), which represents the cell located at row ri and column ci. All of the lines describing the cells will be distinct.OutputYou should output a single number representing the number of cells that were successfully turned to land.ExamplesInput3 4 92 23 22 33 43 11 32 11 11 4Output6NoteThe pictures below show the sequence of reclamations that are performed in the example input. Blue cells represent the cells occupied by sea, while other colored cells represent land. The latest cell that are reclamated is colored either yellow or red, depending on whether the addition violates the condition in the statement. The dashed red line represents a possible trade route, if it exists.No route exists, so this reclamation is not performed.No route exists, skipped.Remember that the leftmost and rightmost cells in the same row are adjacent.No route exists, skipped.Hence the result is:There are 6 successful reclamation and 3 failed ones.
Input3 4 92 23 22 33 43 11 32 11 11 4
Output6
5 seconds
512 megabytes
['dsu', '*2900']
C. Monsters and Diamondstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPiegirl has found a monster and a book about monsters and pies. When she is reading the book, she found out that there are n types of monsters, each with an ID between 1 and n. If you feed a pie to a monster, the monster will split into some number of monsters (possibly zero), and at least one colorful diamond. Monsters may be able to split in multiple ways.At the begining Piegirl has exactly one monster. She begins by feeding the monster a pie. She continues feeding pies to monsters until no more monsters are left. Then she collects all the diamonds that were created.You will be given a list of split rules describing the way in which the various monsters can split. Every monster can split in at least one way, and if a monster can split in multiple ways then each time when it splits Piegirl can choose the way it splits.For each monster, determine the smallest and the largest number of diamonds Piegirl can possibly collect, if initially she has a single instance of that monster. Piegirl has an unlimited supply of pies.InputThe first line contains two integers: m and n (1 ≀ m, n ≀ 105), the number of possible splits and the number of different monster types. Each of the following m lines contains a split rule. Each split rule starts with an integer (a monster ID) mi (1 ≀ mi ≀ n), and a positive integer li indicating the number of monsters and diamonds the current monster can split into. This is followed by li integers, with positive integers representing a monster ID and -1 representing a diamond.Each monster will have at least one split rule. Each split rule will have at least one diamond. The sum of li across all split rules will be at most 105.OutputFor each monster, in order of their IDs, print a line with two integers: the smallest and the largest number of diamonds that can possibly be collected by starting with that monster. If Piegirl cannot possibly end up in a state without monsters, print -1 for both smallest and the largest value. If she can collect an arbitrarily large number of diamonds, print -2 as the largest number of diamonds. If any number in output exceeds 314000000 (but is finite), print 314000000 instead of that number.ExamplesInput6 41 3 -1 1 -11 2 -1 -12 3 -1 3 -12 3 -1 -1 -13 2 -1 -14 2 4 -1Output2 -23 42 2-1 -1Input3 21 2 1 -12 2 -1 -12 3 2 1 -1Output-1 -12 2
Input6 41 3 -1 1 -11 2 -1 -12 3 -1 3 -12 3 -1 -1 -13 2 -1 -14 2 4 -1
Output2 -23 42 2-1 -1
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'shortest paths', '*2600']
B. Stadium and Gamestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDaniel is organizing a football tournament. He has come up with the following tournament format: In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers.InputThe first line contains a single integer n (1 ≀ n ≀ 1018), the number of games that should be played.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.OutputPrint all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1.ExamplesInput3Output34Input25Output20Input2Output-1
Input3
Output34
1 second
256 megabytes
['binary search', 'math', '*1800']
A. Square and Rectanglestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n rectangles. The corners of rectangles have integer coordinates and their edges are parallel to the Ox and Oy axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle). Your task is to determine if the rectangles form a square. In other words, determine if the set of points inside or on the border of at least one rectangle is precisely equal to the set of points inside or on the border of some square.InputThe first line contains a single integer n (1 ≀ n ≀ 5). Next n lines contain four integers each, describing a single rectangle: x1, y1, x2, y2 (0 ≀ x1 < x2 ≀ 31400, 0 ≀ y1 < y2 ≀ 31400) β€” x1 and x2 are x-coordinates of the left and right edges of the rectangle, and y1 and y2 are y-coordinates of the bottom and top edges of the rectangle. No two rectangles overlap (that is, there are no points that belong to the interior of more than one rectangle).OutputIn a single line print "YES", if the given rectangles form a square, or "NO" otherwise.ExamplesInput50 0 2 30 3 3 52 0 5 23 2 5 52 2 3 3OutputYESInput40 0 2 30 3 3 52 0 5 23 2 5 5OutputNO
Input50 0 2 30 3 3 52 0 5 23 2 5 52 2 3 3
OutputYES
1 second
256 megabytes
['implementation', '*1500']
C. Two permutationstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two permutations p and q, consisting of n elements, and m queries of the form: l1, r1, l2, r2 (l1 ≀ r1;Β l2 ≀ r2). The response for the query is the number of such integers from 1 to n, that their position in the first permutation is in segment [l1, r1] (borders included), and position in the second permutation is in segment [l2, r2] (borders included too).A permutation of n elements is the sequence of n distinct integers, each not less than 1 and not greater than n.Position of number v (1 ≀ v ≀ n) in permutation g1, g2, ..., gn is such number i, that gi = v.InputThe first line contains one integer n (1 ≀ n ≀ 106), the number of elements in both permutations. The following line contains n integers, separated with spaces: p1, p2, ..., pn (1 ≀ pi ≀ n). These are elements of the first permutation. The next line contains the second permutation q1, q2, ..., qn in same format.The following line contains an integer m (1 ≀ m ≀ 2Β·105), that is the number of queries.The following m lines contain descriptions of queries one in a line. The description of the i-th query consists of four integers: a, b, c, d (1 ≀ a, b, c, d ≀ n). Query parameters l1, r1, l2, r2 are obtained from the numbers a, b, c, d using the following algorithm: Introduce variable x. If it is the first query, then the variable equals 0, else it equals the response for the previous query plus one. Introduce function f(z) = ((z - 1 + x) mod n) + 1. Suppose l1 = min(f(a), f(b)), r1 = max(f(a), f(b)), l2 = min(f(c), f(d)), r2 = max(f(c), f(d)). OutputPrint a response for each query in a separate line.ExamplesInput33 1 23 2 111 2 3 3Output1Input44 3 2 12 3 4 131 2 3 41 3 2 11 4 2 3Output112
Input33 1 23 2 111 2 3 3
Output1
6 seconds
512 megabytes
['data structures', '*2400']
B. Tournament-graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you have to build tournament graph, consisting of n vertices, such, that for any oriented pair of vertices (v, u) (v ≠ u) there exists a path from vertex v to vertex u consisting of no more then two edges.A directed graph without self-loops is a tournament, if there is exactly one edge between any two distinct vertices (in one out of two possible directions).InputThe first line contains an integer n (3 ≀ n ≀ 1000), the number of the graph's vertices.OutputPrint -1 if there is no graph, satisfying the described conditions.Otherwise, print n lines with n integers in each. The numbers should be separated with spaces. That is adjacency matrix a of the found tournament. Consider the graph vertices to be numbered with integers from 1 to n. Then av, u = 0, if there is no edge from v to u, and av, u = 1 if there is one. As the output graph has to be a tournament, following equalities must be satisfied: av, u + au, v = 1 for each v, u (1 ≀ v, u ≀ n;Β v ≠ u); av, v = 0 for each v (1 ≀ v ≀ n). ExamplesInput3Output0 1 00 0 11 0 0Input4Output-1
Input3
Output0 1 00 0 11 0 0
1 second
256 megabytes
['constructive algorithms', 'graphs', '*2200']
A. Black-and-White Cubetime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a cube of size k × k × k, which consists of unit cubes. Two unit cubes are considered neighbouring, if they have common face.Your task is to paint each of k3 unit cubes one of two colours (black or white), so that the following conditions must be satisfied: each white cube has exactly 2 neighbouring cubes of white color; each black cube has exactly 2 neighbouring cubes of black color. InputThe first line contains integer k (1 ≀ k ≀ 100), which is size of the cube.OutputPrint -1 if there is no solution. Otherwise, print the required painting of the cube consequently by layers. Print a k × k matrix in the first k lines, showing how the first layer of the cube should be painted. In the following k lines print a k × k matrix β€” the way the second layer should be painted. And so on to the last k-th layer. Note that orientation of the cube in the space does not matter.Mark a white unit cube with symbol "w" and a black one with "b". Use the format of output data, given in the test samples. You may print extra empty lines, they will be ignored.ExamplesInput1Output-1Input2Outputbbwwbbww
Input1
Output-1
0.5 seconds
256 megabytes
['combinatorics', 'constructive algorithms', '*1600']
B. Ciel and Flowerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel has some flowers: r red flowers, g green flowers and b blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets: To make a "red bouquet", it needs 3 red flowers. To make a "green bouquet", it needs 3 green flowers. To make a "blue bouquet", it needs 3 blue flowers. To make a "mixing bouquet", it needs 1 red, 1 green and 1 blue flower. Help Fox Ciel to find the maximal number of bouquets she can make.InputThe first line contains three integers r, g and b (0 ≀ r, g, b ≀ 109) β€” the number of red, green and blue flowers.OutputPrint the maximal number of bouquets Fox Ciel can make.ExamplesInput3 6 9Output6Input4 4 4Output4Input0 0 0Output0NoteIn test case 1, we can make 1 red bouquet, 2 green bouquets and 3 blue bouquets.In test case 2, we can make 1 red, 1 green, 1 blue and 1 mixing bouquet.
Input3 6 9
Output6
1 second
256 megabytes
['combinatorics', 'math', '*1600']
A. Ciel and Dancingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule: either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before); or the girl in the dancing pair must dance for the first time. Help Fox Ciel to make a schedule that they can dance as many songs as possible.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 100) β€” the number of boys and girls in the dancing room.OutputIn the first line print k β€” the number of songs during which they can dance. Then in the following k lines, print the indexes of boys and girls dancing during songs chronologically. You can assume that the boys are indexed from 1 to n, and the girls are indexed from 1 to m.ExamplesInput2 1Output21 12 1Input2 2Output31 11 22 2NoteIn test case 1, there are 2 boys and 1 girl. We can have 2 dances: the 1st boy and 1st girl (during the first song), the 2nd boy and 1st girl (during the second song).And in test case 2, we have 2 boys with 2 girls, the answer is 3.
Input2 1
Output21 12 1
1 second
256 megabytes
['greedy', '*1000']
E. Ciel and Gondolastime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFox Ciel is in the Amusement Park. And now she is in a queue in front of the Ferris wheel. There are n people (or foxes more precisely) in the queue: we use first people to refer one at the head of the queue, and n-th people to refer the last one in the queue.There will be k gondolas, and the way we allocate gondolas looks like this: When the first gondolas come, the q1 people in head of the queue go into the gondolas. Then when the second gondolas come, the q2 people in head of the remain queue go into the gondolas.Β Β Β Β ... The remain qk people go into the last (k-th) gondolas. Note that q1, q2, ..., qk must be positive. You can get from the statement that and qi > 0.You know, people don't want to stay with strangers in the gondolas, so your task is to find an optimal allocation way (that is find an optimal sequence q) to make people happy. For every pair of people i and j, there exists a value uij denotes a level of unfamiliar. You can assume uij = uji for all i, j (1 ≀ i, j ≀ n) and uii = 0 for all i (1 ≀ i ≀ n). Then an unfamiliar value of a gondolas is the sum of the levels of unfamiliar between any pair of people that is into the gondolas.A total unfamiliar value is the sum of unfamiliar values for all gondolas. Help Fox Ciel to find the minimal possible total unfamiliar value for some optimal allocation.InputThe first line contains two integers n and k (1 ≀ n ≀ 4000 and 1 ≀ k ≀ min(n, 800)) β€” the number of people in the queue and the number of gondolas. Each of the following n lines contains n integers β€” matrix u, (0 ≀ uij ≀ 9, uij = uji and uii = 0).Please, use fast input methods (for example, please use BufferedReader instead of Scanner for Java).OutputPrint an integer β€” the minimal possible total unfamiliar value.ExamplesInput5 20 0 1 1 10 0 1 1 11 1 0 0 01 1 0 0 01 1 0 0 0Output0Input8 30 1 1 1 1 1 1 11 0 1 1 1 1 1 11 1 0 1 1 1 1 11 1 1 0 1 1 1 11 1 1 1 0 1 1 11 1 1 1 1 0 1 11 1 1 1 1 1 0 11 1 1 1 1 1 1 0Output7Input3 20 2 02 0 30 3 0Output2NoteIn the first example, we can allocate people like this: {1, 2} goes into a gondolas, {3, 4, 5} goes into another gondolas.In the second example, an optimal solution is : {1, 2, 3} | {4, 5, 6} | {7, 8}.
Input5 20 0 1 1 10 0 1 1 11 1 0 0 01 1 0 0 01 1 0 0 0
Output0
4 seconds
512 megabytes
['data structures', 'divide and conquer', 'dp', '*2600']
D. Ciel and Flipboardtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel has a board with n rows and n columns, there is one integer in each cell.It's known that n is an odd number, so let's introduce . Fox Ciel can do the following operation many times: she choose a sub-board with size x rows and x columns, then all numbers in it will be multiplied by -1.Return the maximal sum of numbers in the board that she can get by these operations.InputThe first line contains an integer n, (1 ≀ n ≀ 33, and n is an odd integer) β€” the size of the board.Each of the next n lines contains n integers β€” the numbers in the board. Each number doesn't exceed 1000 by its absolute value.OutputOutput a single integer: the maximal sum of numbers in the board that can be accomplished.ExamplesInput3-1 -1 1-1 1 -11 -1 -1Output9Input5-2 0 0 0 -20 -2 0 -2 00 0 -2 0 00 -2 0 -2 0-2 0 0 0 -2Output18NoteIn the first test, we can apply this operation twice: first on the top left 2 × 2 sub-board, then on the bottom right 2 × 2 sub-board. Then all numbers will become positive.
Input3-1 -1 1-1 1 -11 -1 -1
Output9
4 seconds
256 megabytes
['dp', 'greedy', 'math', '*2900']
C. Ciel the Commandertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has n cities connected by n - 1 undirected roads, and for any two cities there always exists a path between them.Fox Ciel needs to assign an officer to each city. Each officer has a rank β€” a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost.There are enough officers of each rank. But there is a special rule must obey: if x and y are two distinct cities and their officers have the same rank, then on the simple path between x and y there must be a city z that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer.Help Ciel to make a valid plan, and if it's impossible, output "Impossible!".InputThe first line contains an integer n (2 ≀ n ≀ 105) β€” the number of cities in Tree Land.Each of the following n - 1 lines contains two integers a and b (1 ≀ a, b ≀ n, a ≠ b) β€” they mean that there will be an undirected road between a and b. Consider all the cities are numbered from 1 to n.It guaranteed that the given graph will be a tree.OutputIf there is a valid plane, output n space-separated characters in a line β€” i-th character is the rank of officer in the city with number i. Otherwise output "Impossible!".ExamplesInput41 21 31 4OutputA B B BInput101 22 33 44 55 66 77 88 99 10OutputD C B A D C B D C DNoteIn the first example, for any two officers of rank 'B', an officer with rank 'A' will be on the path between them. So it is a valid solution.
Input41 21 31 4
OutputA B B B
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'divide and conquer', 'greedy', 'trees', '*2100']
B. Ciel and Dueltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel is playing a card game with her friend Jiro.Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.Now is Ciel's battle phase, Ciel can do the following operation many times: Choose one of her cards X. This card mustn't be chosen before. If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then: If Y's position is Attack, then (X's strength)  β‰₯  (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength). If Y's position is Defense, then (X's strength)  >  (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage. Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 100) β€” the number of cards Jiro and Ciel have.Each of the next n lines contains a string position and an integer strength (0 ≀ strength ≀ 8000) β€” the position and strength of Jiro's current card. Position is the string "ATK" for attack, and the string "DEF" for defense.Each of the next m lines contains an integer strength (0 ≀ strength ≀ 8000) β€” the strength of Ciel's current card.OutputOutput an integer: the maximal damage Jiro can get.ExamplesInput2 3ATK 2000DEF 1700250025002500Output3000Input3 4ATK 10ATK 100ATK 10001111011001Output992Input2 4DEF 0ATK 00011Output1NoteIn the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack "ATK 2000" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the "DEF 1700" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000.In the second test case, she should use the "1001" card to attack the "ATK 100" card, then use the "101" card to attack the "ATK 10" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992.In the third test case note that she can destroy the "ATK 0" card by a card with strength equal to 0, but she can't destroy a "DEF 0" card with that card.
Input2 3ATK 2000DEF 1700250025002500
Output3000
2 seconds
256 megabytes
['dp', 'flows', 'greedy', '*1900']
A. Ciel and Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all: 'U': go up, (x, y)  →  (x, y+1); 'D': go down, (x, y)  →  (x, y-1); 'L': go left, (x, y)  →  (x-1, y); 'R': go right, (x, y)  →  (x+1, y). The robot will do the operations in s from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in (a, b).InputThe first line contains two integers a and b, ( - 109 ≀ a, b ≀ 109). The second line contains a string s (1 ≀ |s| ≀ 100, s only contains characters 'U', 'D', 'L', 'R') β€” the command.OutputPrint "Yes" if the robot will be located at (a, b), and "No" otherwise.ExamplesInput2 2RUOutputYesInput1 2RUOutputNoInput-1 1000000000LRRLUOutputYesInput0 0DOutputYesNoteIn the first and second test case, command string is "RU", so the robot will go right, then go up, then right, and then up and so on.The locations of its moves are (0, 0)  →  (1, 0)  →  (1, 1)  →  (2, 1)  →  (2, 2)  →  ...So it can reach (2, 2) but not (1, 2).
Input2 2RU
OutputYes
1 second
256 megabytes
['binary search', 'implementation', 'math', '*1700']
B. Ping-Pong (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2.Your program should handle the queries of the following two types: "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. "2 a b" (a ≠ b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals.InputThe first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value.It's guaranteed that all queries are correct.OutputFor each query of the second type print "YES" or "NO" on a separate line depending on the answer.ExamplesInput51 1 51 5 112 1 21 2 92 1 2OutputNOYES
Input51 1 51 5 112 1 21 2 92 1 2
OutputNOYES
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*1500']
A. Magic Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not.You're given a number. Determine if it is a magic number or not.InputThe first line of input contains an integer n, (1 ≀ n ≀ 109). This number doesn't contain leading zeros.OutputPrint "YES" if n is a magic number or print "NO" if it's not.ExamplesInput114114OutputYESInput1111OutputYESInput441231OutputNO
Input114114
OutputYES
2 seconds
256 megabytes
['brute force', 'greedy', '*900']
E. Ping-Pongtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2.Your program should handle the queries of the following two types: "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. "2 a b" (a ≠ b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals.InputThe first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value.It's guaranteed that all queries are correct.OutputFor each query of the second type print "YES" or "NO" on a separate line depending on the answer.ExamplesInput51 1 51 5 112 1 21 2 92 1 2OutputNOYES
Input51 1 51 5 112 1 21 2 92 1 2
OutputNOYES
2 seconds
256 megabytes
['data structures', '*3000']
D. Have You Ever Heard About the Word?time limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA substring of a string is a contiguous subsequence of that string. So, string bca is substring of string abcabc, but string cc is not.A repeating block is a string formed by concatenating some string with itself. So, string abcabc is a repeating block, but strings abcabd, ababab are not.You've got a sequence of Latin characters (string). At each step you find the shortest substring that is a repeating block, if there exists more than one you must choose the leftmost. As the substring is of form XX (X β€” some string) you replace this substring with X, in other words you delete one of the X substrings in the substring. You repeat this process until there remains no repeating block in the string. How would the final string looks like? Look at the sample explanation to understand the statement more precise.InputIn the first line of input you're given a string of small Latin characters with length between 1 to 50000, inclusive.OutputPrint the final string after applying changes.ExamplesInputabccabcOutputabcInputaaaabaaabOutputabInputbirdbirdbirdisthewordOutputbirdisthewordNoteAt the first sample the string transforms as follows: abccabc  →  abcabc  →  abc.At the second sample the string transforms as follows: aaaabaaab  →  aaabaaab  →  aabaaab  →  abaaab  →  abaab  →  abab  →  ab.
Inputabccabc
Outputabc
6 seconds
256 megabytes
['greedy', 'hashing', 'string suffix structures', 'strings', '*2800']
C. Kalila and Dimna in the Logging Industrytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut n trees with heights a1, a2, ..., an. They bought a chain saw from a shop. Each time they use the chain saw on the tree number i, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is i (the tree that have height ai in the beginning), then the cost of charging the chain saw would be bi. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each i < j, ai < aj and bi > bj and also bn = 0 and a1 = 1. Kalila and Dimna want to cut all the trees completely, with minimum cost. They want you to help them! Will you?InputThe first line of input contains an integer n (1 ≀ n ≀ 105). The second line of input contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The third line of input contains n integers b1, b2, ..., bn (0 ≀ bi ≀ 109).It's guaranteed that a1 = 1, bn = 0, a1 < a2 < ... < an and b1 > b2 > ... > bn.OutputThe only line of output must contain the minimum cost of cutting all the trees completely.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput51 2 3 4 55 4 3 2 0Output25Input61 2 3 10 20 306 5 4 3 2 0Output138
Input51 2 3 4 55 4 3 2 0
Output25
2 seconds
256 megabytes
['dp', 'geometry', '*2100']
B. Psychos in a Linetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.InputThe first line of input contains integer n denoting the number of psychos, (1 ≀ n ≀ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive β€” ids of the psychos in the line from left to right.OutputPrint the number of steps, so that the line remains the same afterward.ExamplesInput1010 9 7 8 6 5 3 4 2 1Output2Input61 2 3 4 5 6Output0NoteIn the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1]  →  [10 8 4]  →  [10]. So, there are two steps.
Input1010 9 7 8 6 5 3 4 2 1
Output2
1 second
256 megabytes
['data structures', 'implementation', '*1900']
A. Malek Dance Clubtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2n members and coincidentally Natalia Fan Club also has 2n members. Each member of MDC is assigned a unique id i from 0 to 2n - 1. The same holds for each member of NFC.One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers (a, b) such that member a from MDC dances with member b from NFC.The complexity of a pairs' assignment is the number of pairs of dancing pairs (a, b) and (c, d) such that a < c and b > d.You are given a binary number of length n named x. We know that member i from MDC dances with member from NFC. Your task is to calculate the complexity of this assignment modulo 1000000007 (109 + 7).Expression denotes applying Β«XORΒ» to numbers x and y. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as Β«^Β», in Pascal β€” Β«xorΒ».InputThe first line of input contains a binary number x of lenght n, (1 ≀ n ≀ 100).This number may contain leading zeros.OutputPrint the complexity of the given dance assignent modulo 1000000007 (109 + 7).ExamplesInput11Output6Input01Output2Input1Output1
Input11
Output6
1 second
256 megabytes
['combinatorics', 'math', '*1600']
B. Strings of Powertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVolodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.For simplicity, let us assume that Volodya's text can be represented as a single string.InputInput contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.OutputPrint exactly one number β€” the number of powerful substrings of the given string.Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInputheavymetalisheavymetalOutput3InputheavymetalismetalOutput2InputtrueheavymetalissotruewellitisalsosoheavythatyoucanalmostfeeltheweightofmetalonyouOutput3NoteIn the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal".
Inputheavymetalisheavymetal
Output3
2 seconds
256 megabytes
['implementation', 'strings', 'two pointers', '*1300']
A. Even Oddstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the following sequence of numbers: firstly all odd integers from 1 to n (in ascending order), then all even integers from 1 to n (also in ascending order). Help our hero to find out which number will stand at the position number k.InputThe only line of input contains integers n and k (1 ≀ k ≀ n ≀ 1012).Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.OutputPrint the number that will stand at the position number k after Volodya's manipulations.ExamplesInput10 3Output5Input7 7Output6NoteIn the first sample Volodya's sequence will look like this: {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}. The third place in the sequence is therefore occupied by the number 5.
Input10 3
Output5
1 second
256 megabytes
['math', '*900']
E. Princess and Her Shadowtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPrincess Vlada enjoys springing in the meadows and walking in the forest. One day β€” wonderful, sunny day β€” during her walk Princess found out with astonishment that her shadow was missing! "Blimey!", β€” she thought and started her search of the shadow in the forest.Normally the Shadow is too lazy and simply sleeps under the Princess. But at this terrifically hot summer day she got bored of such a dull life, so she decided to play with Vlada.The forest, where our characters entertain themselves, may be represented as a set of integer cells in the plane, where the Shadow and the Princess can move only up, down, left and right by 1. Some cells (as it happens in decent forests) are occupied by trees. The Shadow and the Princess are not allowed to enter a cell occupied by a tree. Unfortunately, these are the hard times for the forest, so there are very few trees growing here...At first the Princess was walking within the cell (vx,Β vy), while the Shadow hid from the Princess in the cell (sx,Β sy). The Princess, The Shadow and the trees are located in the different cells.The Shadow is playing with the Princess. As soon as the Princess moves by 1 in some direction, the Shadow simultaneously flies by 1 in the same direction, if it is possible (if the cell to fly to is not occupied by some tree); otherwise, the Shadow doesn't move. The Shadow is very shadowy, so our characters do not interfere with each other.We say that the Shadow is caught by the Princess if after some move both of them are located in the same cell. Vlada managed to catch her Shadow! Can you?InputFirst line of the input contains the coordinates of the characters vx, vy, sx, sy and the number of trees m (0 ≀ m ≀ 400). The following m lines contain the coordinates of the trees.All the coordinates are integers between -100 and 100, inclusive. The Princess, The Shadow and the trees are located in the different cells.OutputIf it is impossible for the Princess to catch the Shadow, print "-1" (without quotes).Otherwise print a sequence of characters "L", "R", "D", "U", corresponding to the Princess's moves, following which she will be able to catch the Shadow at some turn (L β€” move to the left, R β€” to the right, U β€” up, D β€” down; axis x is directed to the right, y β€” up).The number of characters (that is, the number of moves) must not exceed 106. All the Princess's moves should be correct, that is must not lead to the cell where a tree grows. It is allowed for the Princess and the Shadow to occupy the same cell before the last turn.ExamplesInput0 0 1 0 10 1OutputLLURInput5 0 3 0 82 -12 02 13 -14 14 03 14 -1Output-1Input3 2 1 1 30 11 00 0OutputDLLNoteBelow the pictures for the samples are given (Princess, Shadow and the trees are colored in pink, gray and black correspondingly; the blue dot marks the lattice center).In the first case the Princess may make two left steps, one step upwards and one right step: In the following case the Princess cannot catch the Shadow: In the last sample the Princess may make two left steps and one down step (in any order):
Input0 0 1 0 10 1
OutputLLUR
1 second
256 megabytes
['constructive algorithms', 'shortest paths', '*3100']
D. Game with Powerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya and Petya wrote down all integers from 1 to n to play the "powers" game (n can be quite large; however, Vasya and Petya are not confused by this fact).Players choose numbers in turn (Vasya chooses first). If some number x is chosen at the current turn, it is forbidden to choose x or all of its other positive integer powers (that is, x2, x3, ...) at the next turns. For instance, if the number 9 is chosen at the first turn, one cannot choose 9 or 81 later, while it is still allowed to choose 3 or 27. The one who cannot make a move loses.Who wins if both Vasya and Petya play optimally?InputInput contains single integer n (1 ≀ n ≀ 109).OutputPrint the name of the winner β€” "Vasya" or "Petya" (without quotes).ExamplesInput1OutputVasyaInput2OutputPetyaInput8OutputPetyaNoteIn the first sample Vasya will choose 1 and win immediately.In the second sample no matter which number Vasya chooses during his first turn, Petya can choose the remaining number and win.
Input1
OutputVasya
1 second
256 megabytes
['dp', 'games', '*2300']
C. Balancetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA system of n vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals e. Volume of each vessel equals v liters. Of course, the amount of the water in any vessel cannot exceed v liters in the process of transfusions.Given the initial amounts ai of water in the vessels and the desired amounts bi find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed 2Β·n2.InputFirst line of the input contains integers n, v, e (1 ≀ n ≀ 300, 1 ≀ v ≀ 109, 0 ≀ e ≀ 50000).Next two lines contain n integers each: initial ai and the desired amounts bi of water in corresponding vessels (0 ≀ ai, bi ≀ v).Next e lines describe one tube each in the format x y (1 ≀ x, y ≀ n, x ≠ y) for a tube between vessels number x and y. There might be multiple tubes between two vessels. You may assume that vessels are numbered from 1 to n in some way.OutputPrint "NO" (without quotes), if such sequence of transfusions does not exist.Otherwise print any suitable sequence in the following format. On the first line print the total number of transfusions k (k should not exceed 2Β·n2). In the following k lines print transfusions in the format xΒ yΒ d (transfusion of d liters from the vessel number x to the vessel number y, x and y must be distinct). For all transfusions d must be a non-negative integer.ExamplesInput2 10 11 95 51 2Output12 1 4Input2 10 05 24 2OutputNOInput2 10 04 24 2Output0
Input2 10 11 95 51 2
Output12 1 4
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'trees', '*2500']
B. Antstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1) β€” one ant in each direction. No other ant movements will happen. Ants never interfere with each other.Scientists have put a colony of n ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.InputFirst input line contains integers n (0 ≀ n ≀ 30000) and t (1 ≀ t ≀ 50000), where n is the number of ants in the colony and t is the number of queries. Each of the next t lines contains coordinates of a query junction: integers xi, yi ( - 109 ≀ xi, yi ≀ 109). Queries may coincide.It is guaranteed that there will be a certain moment of time when no possible movements can happen (in other words, the process will eventually end).OutputPrint t integers, one per line β€” the number of ants at the corresponding junctions when the movement of the ants stops.ExamplesInput1 30 10 00 -1Output010Input6 50 -20 -10 00 10 2Output01210NoteIn the first sample the colony consists of the one ant, so nothing happens at all.In the second sample the colony consists of 6 ants. At the first minute 4 ants scatter from (0, 0) to the neighbouring junctions. After that the process stops.
Input1 30 10 00 -1
Output010
1 second
256 megabytes
['brute force', 'implementation', '*2000']
A. Perfect Pairtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not.Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, (x + y).What is the minimum number of such operations one has to perform in order to make the given pair of integers m-perfect?InputSingle line of the input contains three integers x, y and m ( - 1018 ≀ x, y, m ≀ 1018).Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preffered to use the cin, cout streams or the %I64d specifier.OutputPrint the minimum number of operations or "-1" (without quotes), if it is impossible to transform the given pair to the m-perfect one.ExamplesInput1 2 5Output2Input-1 4 15Output4Input0 -1 5Output-1NoteIn the first sample the following sequence of operations is suitable: (1, 2) (3, 2) (5, 2).In the second sample: (-1, 4) (3, 4) (7, 4) (11, 4) (15, 4).Finally, in the third sample x, y cannot be made positive, hence there is no proper sequence of operations.
Input1 2 5
Output2
1 second
256 megabytes
['brute force', '*1600']
G3. Good Substringstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t.We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].InputThe first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.The input limits for scoring 30 points are (subproblem G1): 0 ≀ n ≀ 10. The length of string s and the maximum length of string p is  ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): 0 ≀ n ≀ 10. The length of string s and the maximum length of string p is  ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): 0 ≀ n ≀ 10. The length of string s and the maximum length of string p is  ≀ 50000. OutputPrint a single integer β€” the number of good substrings of string s.ExamplesInputaaab2aa 0 0aab 1 1Output3Inputltntlnen3n 0 0ttlneenl 1 4lelllt 1 1Output2Inputa0Output1NoteThere are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ».In the second test only substrings Β«eΒ» and Β«tΒ» are good.
Inputaaab2aa 0 0aab 1 1
Output3
4 seconds
256 megabytes
['string suffix structures', '*2400']
G2. Good Substringstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t.We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].InputThe first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.The input limits for scoring 30 points are (subproblem G1): 0 ≀ n ≀ 10. The length of string s and the maximum length of string p is  ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): 0 ≀ n ≀ 10. The length of string s and the maximum length of string p is  ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): 0 ≀ n ≀ 10. The length of string s and the maximum length of string p is  ≀ 50000. OutputPrint a single integer β€” the number of good substrings of string s.ExamplesInputaaab2aa 0 0aab 1 1Output3Inputltntlnen3n 0 0ttlneenl 1 4lelllt 1 1Output2Inputa0Output1NoteThere are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ».In the second test only substrings Β«eΒ» and Β«tΒ» are good.
Inputaaab2aa 0 0aab 1 1
Output3
4 seconds
256 megabytes
['string suffix structures', '*2200']
G1. Good Substringstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≀ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≀ l ≀ r ≀ |p|) such that p[l... r] = t.We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].InputThe first line contains string s. The second line contains integer n. Next n lines contain the rules, one per line. Each of these lines contains a string and two integers pi, li, ri, separated by single spaces (0 ≀ li ≀ ri ≀ |pi|). It is guaranteed that all the given strings are non-empty and only contain lowercase English letters.The input limits for scoring 30 points are (subproblem G1): 0 ≀ n ≀ 10. The length of string s and the maximum length of string p is  ≀ 200. The input limits for scoring 70 points are (subproblems G1+G2): 0 ≀ n ≀ 10. The length of string s and the maximum length of string p is  ≀ 2000. The input limits for scoring 100 points are (subproblems G1+G2+G3): 0 ≀ n ≀ 10. The length of string s and the maximum length of string p is  ≀ 50000. OutputPrint a single integer β€” the number of good substrings of string s.ExamplesInputaaab2aa 0 0aab 1 1Output3Inputltntlnen3n 0 0ttlneenl 1 4lelllt 1 1Output2Inputa0Output1NoteThere are three good substrings in the first sample test: Β«aabΒ», Β«abΒ» and Β«bΒ».In the second test only substrings Β«eΒ» and Β«tΒ» are good.
Inputaaab2aa 0 0aab 1 1
Output3
4 seconds
256 megabytes
['hashing', 'strings', '*1700']
E3. Summer Homeworktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBy the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): No extra limitations. OutputFor each query print the calculated sum modulo 1000000000 (109).ExamplesInput5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5Output1232850Input5 41 3 1 2 43 1 4 12 2 41 2 102 1 5Output1245
Input5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5
Output1232850
3 seconds
256 megabytes
['data structures', 'math', '*2300']
E2. Summer Homeworktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBy the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): No extra limitations. OutputFor each query print the calculated sum modulo 1000000000 (109).ExamplesInput5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5Output1232850Input5 41 3 1 2 43 1 4 12 2 41 2 102 1 5Output1245
Input5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5
Output1232850
3 seconds
256 megabytes
['data structures', 'math', '*2300']
E1. Summer Homeworktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBy the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type: For given numbers xi and vi assign value vi to element axi. For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i β‰₯ 2: fi = fi - 1 + fi - 2. For a group of three numbers li ri di you should increase value ax by di for all x (li ≀ x ≀ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≀ ti ≀ 3) β€” the operation type: if ti = 1, then next follow two integers xi vi (1 ≀ xi ≀ n, 0 ≀ vi ≀ 105); if ti = 2, then next follow two integers li ri (1 ≀ li ≀ ri ≀ n); if ti = 3, then next follow three integers li ri di (1 ≀ li ≀ ri ≀ n, 0 ≀ di ≀ 105). The input limits for scoring 30 points are (subproblem E1): It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type. The input limits for scoring 70 points are (subproblems E1+E2): It is guaranteed that there will be queries of the 1-st and 2-nd type only. The input limits for scoring 100 points are (subproblems E1+E2+E3): No extra limitations. OutputFor each query print the calculated sum modulo 1000000000 (109).ExamplesInput5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5Output1232850Input5 41 3 1 2 43 1 4 12 2 41 2 102 1 5Output1245
Input5 51 3 1 2 42 1 42 1 52 2 41 3 102 1 5
Output1232850
3 seconds
256 megabytes
['brute force', 'data structures', '*1500']
D3. PE Lessontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for n = 5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.InputThe first line contains a single number n β€” the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in.The input limits for scoring 30 points are (subproblem D1): 1 ≀ n ≀ 10. The input limits for scoring 70 points are (subproblems D1+D2): 1 ≀ n ≀ 500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1 ≀ n ≀ 1000000. OutputThe output should contain a single integer β€” the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109 + 7).ExamplesInput51 2 2 1 2Output120Input81 2 2 1 2 1 1 2Output16800
Input51 2 2 1 2
Output120
3 seconds
256 megabytes
['dp', 'math', '*2400']
D2. PE Lessontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for n = 5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.InputThe first line contains a single number n β€” the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in.The input limits for scoring 30 points are (subproblem D1): 1 ≀ n ≀ 10. The input limits for scoring 70 points are (subproblems D1+D2): 1 ≀ n ≀ 500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1 ≀ n ≀ 1000000. OutputThe output should contain a single integer β€” the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109 + 7).ExamplesInput51 2 2 1 2Output120Input81 2 2 1 2 1 1 2Output16800
Input51 2 2 1 2
Output120
3 seconds
256 megabytes
['dp', '*2300']
D1. PE Lessontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning. The balls are numbered from 1 to n (by the demand of the inventory commission). Figure 1. The initial position for n = 5. After receiving the balls the students perform the warm-up exercise. The exercise takes place in a few throws. For each throw the teacher chooses any two arbitrary different students who will participate in it. The selected students throw their balls to each other. Thus, after each throw the students remain in their positions, and the two balls are swapped. Figure 2. The example of a throw. In this case there was a throw between the students, who were holding the 2-nd and the 4-th balls. Since the warm-up has many exercises, each of them can only continue for little time. Therefore, for each student we know the maximum number of throws he can participate in. For this lessons maximum number of throws will be 1 or 2.Note that after all phases of the considered exercise any ball can end up with any student. Smart Beaver decided to formalize it and introduced the concept of the "ball order". The ball order is a sequence of n numbers that correspond to the order of balls in the line. The first number will match the number of the ball of the first from the left student in the line, the second number will match the ball of the second student, and so on. For example, in figure 2 the order of the balls was (1, 2, 3, 4, 5), and after the throw it was (1, 4, 3, 2, 5). Smart beaver knows the number of students and for each student he knows the maximum number of throws in which he can participate. And now he is wondering: what is the number of distinct ways of ball orders by the end of the exercise.InputThe first line contains a single number n β€” the number of students in the line and the number of balls. The next line contains exactly n space-separated integers. Each number corresponds to a student in the line (the i-th number corresponds to the i-th from the left student in the line) and shows the number of throws he can participate in.The input limits for scoring 30 points are (subproblem D1): 1 ≀ n ≀ 10. The input limits for scoring 70 points are (subproblems D1+D2): 1 ≀ n ≀ 500. The input limits for scoring 100 points are (subproblems D1+D2+D3): 1 ≀ n ≀ 1000000. OutputThe output should contain a single integer β€” the number of variants of ball orders after the warm up exercise is complete. As the number can be rather large, print it modulo 1000000007 (109 + 7).ExamplesInput51 2 2 1 2Output120Input81 2 2 1 2 1 1 2Output16800
Input51 2 2 1 2
Output120
3 seconds
256 megabytes
['brute force', 'dp', '*2300']
C2. Tidying Uptime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmart Beaver is careful about his appearance and pays special attention to shoes so he has a huge number of pairs of shoes from the most famous brands of the forest. He's trying to handle his shoes carefully so that each pair stood side by side. But by the end of the week because of his very active lifestyle in his dressing room becomes a mess.Smart Beaver from ABBYY is not only the brightest beaver in the area, but he also is the most domestically oriented. For example, on Mondays the Smart Beaver cleans everything in his home.It's Monday morning. Smart Beaver does not want to spend the whole day cleaning, besides, there is much in to do and it’s the gym day, so he wants to clean up as soon as possible. Now the floors are washed, the dust is wiped off β€” it’s time to clean up in the dressing room. But as soon as the Smart Beaver entered the dressing room, all plans for the day were suddenly destroyed: chaos reigned there and it seemed impossible to handle, even in a week. Give our hero some hope: tell him what is the minimum number of shoes need to change the position to make the dressing room neat.The dressing room is rectangular and is divided into n × m equal squares, each square contains exactly one shoe. Each pair of shoes has a unique number that is integer from 1 to , more formally, a square with coordinates (i, j) contains an integer number of the pair which is lying on it. The Smart Beaver believes that the dressing room is neat only when each pair of sneakers lies together. We assume that the pair of sneakers in squares (i1, j1) and (i2, j2) lies together if |i1 - i2| + |j1 - j2| = 1.InputThe first line contains two space-separated integers n and m. They correspond to the dressing room size. Next n lines contain m space-separated integers each. Those numbers describe the dressing room. Each number corresponds to a snicker. It is guaranteed that: nΒ·m is even. All numbers, corresponding to the numbers of pairs of shoes in the dressing room, will lie between 1 and . Each number from 1 to will occur exactly twice. The input limits for scoring 30 points are (subproblem C1): 2 ≀ n, m ≀ 8. The input limits for scoring 100 points are (subproblems C1+C2): 2 ≀ n, m ≀ 80. OutputPrint exactly one integer β€” the minimum number of the sneakers that need to change their location.ExamplesInput2 31 1 22 3 3Output2Input3 41 3 2 62 1 5 64 4 5 3Output4Note The second sample.
Input2 31 1 22 3 3
Output2
4 seconds
256 megabytes
['flows', 'graph matchings', '*2300']
C1. Tidying Uptime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmart Beaver is careful about his appearance and pays special attention to shoes so he has a huge number of pairs of shoes from the most famous brands of the forest. He's trying to handle his shoes carefully so that each pair stood side by side. But by the end of the week because of his very active lifestyle in his dressing room becomes a mess.Smart Beaver from ABBYY is not only the brightest beaver in the area, but he also is the most domestically oriented. For example, on Mondays the Smart Beaver cleans everything in his home.It's Monday morning. Smart Beaver does not want to spend the whole day cleaning, besides, there is much in to do and it’s the gym day, so he wants to clean up as soon as possible. Now the floors are washed, the dust is wiped off β€” it’s time to clean up in the dressing room. But as soon as the Smart Beaver entered the dressing room, all plans for the day were suddenly destroyed: chaos reigned there and it seemed impossible to handle, even in a week. Give our hero some hope: tell him what is the minimum number of shoes need to change the position to make the dressing room neat.The dressing room is rectangular and is divided into n × m equal squares, each square contains exactly one shoe. Each pair of shoes has a unique number that is integer from 1 to , more formally, a square with coordinates (i, j) contains an integer number of the pair which is lying on it. The Smart Beaver believes that the dressing room is neat only when each pair of sneakers lies together. We assume that the pair of sneakers in squares (i1, j1) and (i2, j2) lies together if |i1 - i2| + |j1 - j2| = 1.InputThe first line contains two space-separated integers n and m. They correspond to the dressing room size. Next n lines contain m space-separated integers each. Those numbers describe the dressing room. Each number corresponds to a snicker. It is guaranteed that: nΒ·m is even. All numbers, corresponding to the numbers of pairs of shoes in the dressing room, will lie between 1 and . Each number from 1 to will occur exactly twice. The input limits for scoring 30 points are (subproblem C1): 2 ≀ n, m ≀ 8. The input limits for scoring 100 points are (subproblems C1+C2): 2 ≀ n, m ≀ 80. OutputPrint exactly one integer β€” the minimum number of the sneakers that need to change their location.ExamplesInput2 31 1 22 3 3Output2Input3 41 3 2 62 1 5 64 4 5 3Output4Note The second sample.
Input2 31 1 22 3 3
Output2
4 seconds
256 megabytes
['flows', '*2200']
B2. EKGtime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.InputThe first line contains two integers n (1 ≀ n ≀ 103) and x (1 ≀ x ≀ n) β€” the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ n) β€” the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.The input limits for scoring 30 points are (subproblem B1): It is guaranteed that the number of zero elements ai doesn't exceed 20. The input limits for scoring 100 points are (subproblems B1+B2): The number of zero elements ai is arbitrary. OutputPrint all possible positions of the Smart Beaver in the line in the increasing order.ExamplesInput6 12 0 4 0 6 0Output246Input6 22 3 0 5 6 0Output25Input4 10 0 0 0Output1234Input6 20 0 1 0 4 5Output1346Note Picture for the fourth test.
Input6 12 0 4 0 6 0
Output246
0.5 seconds
256 megabytes
['dfs and similar', 'dp', '*1600']
B1. EKGtime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.InputThe first line contains two integers n (1 ≀ n ≀ 103) and x (1 ≀ x ≀ n) β€” the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n.The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ n) β€” the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue.The input limits for scoring 30 points are (subproblem B1): It is guaranteed that the number of zero elements ai doesn't exceed 20. The input limits for scoring 100 points are (subproblems B1+B2): The number of zero elements ai is arbitrary. OutputPrint all possible positions of the Smart Beaver in the line in the increasing order.ExamplesInput6 12 0 4 0 6 0Output246Input6 22 3 0 5 6 0Output25Input4 10 0 0 0Output1234Input6 20 0 1 0 4 5Output1346Note Picture for the fourth test.
Input6 12 0 4 0 6 0
Output246
0.5 seconds
256 megabytes
['brute force', 'dfs and similar', '*1500']
A2. Special Tasktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSpecial Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure: if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively); if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code; if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits. The length of the safe code coincides with the length of the hint. For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...InputThe first line contains string s β€” the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.The input limits for scoring 30 points are (subproblem A1): 1 ≀ |s| ≀ 5. The input limits for scoring 100 points are (subproblems A1+A2): 1 ≀ |s| ≀ 105. Here |s| means the length of string s.OutputPrint the number of codes that match the given hint.ExamplesInputAJOutput81Input1?AAOutput100
InputAJ
Output81
1 second
256 megabytes
['math', '*1400']
A1. Special Tasktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSpecial Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get the latest research by British scientists on the English Language. These developments are encoded and stored in a large safe. The Beaver's teeth are strong enough, so the authorities assured that upon arriving at the place the beaver won't have any problems with opening the safe.And he finishes his aspen sprig and leaves for this important task. Of course, the Beaver arrived at the location without any problems, but alas. He can't open the safe with his strong and big teeth. At this point, the Smart Beaver get a call from the headquarters and learns that opening the safe with the teeth is not necessary, as a reliable source has sent the following information: the safe code consists of digits and has no leading zeroes. There also is a special hint, which can be used to open the safe. The hint is string s with the following structure: if si = "?", then the digit that goes i-th in the safe code can be anything (between 0 to 9, inclusively); if si is a digit (between 0 to 9, inclusively), then it means that there is digit si on position i in code; if the string contains letters from "A" to "J", then all positions with the same letters must contain the same digits and the positions with distinct letters must contain distinct digits. The length of the safe code coincides with the length of the hint. For example, hint "?JGJ9" has such matching safe code variants: "51919", "55959", "12329", "93539" and so on, and has wrong variants such as: "56669", "00111", "03539" and "13666".After receiving such information, the authorities change the plan and ask the special agents to work quietly and gently and not to try to open the safe by mechanical means, and try to find the password using the given hint.At a special agent school the Smart Beaver was the fastest in his platoon finding codes for such safes, but now he is not in that shape: the years take their toll ... Help him to determine the number of possible variants of the code to the safe, matching the given hint. After receiving this information, and knowing his own speed of entering codes, the Smart Beaver will be able to determine whether he will have time for tonight's show "Beavers are on the trail" on his favorite TV channel, or he should work for a sleepless night...InputThe first line contains string s β€” the hint to the safe code. String s consists of the following characters: ?, 0-9, A-J. It is guaranteed that the first character of string s doesn't equal to character 0.The input limits for scoring 30 points are (subproblem A1): 1 ≀ |s| ≀ 5. The input limits for scoring 100 points are (subproblems A1+A2): 1 ≀ |s| ≀ 105. Here |s| means the length of string s.OutputPrint the number of codes that match the given hint.ExamplesInputAJOutput81Input1?AAOutput100
InputAJ
Output81
1 second
256 megabytes
['greedy', '*1100']
B. Sereja and Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms: Make vi-th array element equal to xi. In other words, perform the assignment avi = xi. Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≀ i ≀ n). Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.InputThe first line contains integers n, m (1 ≀ n, m ≀ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the original array.Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≀ ti ≀ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≀ vi ≀ n, 1 ≀ xi ≀ 109). If ti = 2, then it is followed by integer yi (1 ≀ yi ≀ 104). And if ti = 3, then it is followed by integer qi (1 ≀ qi ≀ n).OutputFor each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.ExamplesInput10 111 2 3 4 5 6 7 8 9 103 23 92 103 13 101 1 102 102 103 13 103 9Output291120304039
Input10 111 2 3 4 5 6 7 8 9 103 23 92 103 13 101 1 102 102 103 13 103 9
Output291120304039
1 second
256 megabytes
['implementation', '*1200']
A. Sereja and Bottlestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja and his friends went to a picnic. The guys had n soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles.Sereja knows that the i-th bottle is from brand ai, besides, you can use it to open other bottles of brand bi. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle.Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.InputThe first line contains integer n (1 ≀ n ≀ 100) β€” the number of bottles. The next n lines contain the bottles' description. The i-th line contains two integers ai, bi (1 ≀ ai, bi ≀ 1000) β€” the description of the i-th bottle.OutputIn a single line print a single integer β€” the answer to the problem.ExamplesInput41 12 23 34 4Output4Input41 22 33 44 1Output0
Input41 12 23 34 4
Output4
2 seconds
256 megabytes
['brute force', '*1400']
E. Sereja and Squarestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja painted n points on the plane, point number i (1 ≀ i ≀ n) has coordinates (i, 0). Then Sereja marked each point with a small or large English letter. Sereja don't like letter "x", so he didn't use it to mark points. Sereja thinks that the points are marked beautifully if the following conditions holds: all points can be divided into pairs so that each point will belong to exactly one pair; in each pair the point with the lesser abscissa will be marked with a small English letter and the point with the larger abscissa will be marked with the same large English letter; if we built a square on each pair, the pair's points will be the square's opposite points and the segment between them will be the square's diagonal, then among the resulting squares there won't be any intersecting or touching ones. Little Petya erased some small and all large letters marking the points. Now Sereja wonders how many ways are there to return the removed letters so that the points were marked beautifully.InputThe first line contains integer n the number of points (1 ≀ n ≀ 105). The second line contains a sequence consisting of n small English letters and question marks β€” the sequence of letters, that mark points, in order of increasing x-coordinate of points. Question marks denote the points without letters (Petya erased them). It is guaranteed that the input string doesn't contain letter "x".OutputIn a single line print the answer to the problem modulo 4294967296. If there is no way to return the removed letters, print number 0.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput4a???Output50Input4abc?Output0Input6abc???Output1
Input4a???
Output50
4 seconds
256 megabytes
['dp', '*2900']
D. Sereja and Straight Linestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja placed n points on a plane. Now Sereja wants to place on the plane two straight lines, intersecting at a right angle, so that one of the straight lines intersect the Ox axis at an angle of 45 degrees and the maximum distance from the points to the straight lines were minimum. In this problem we consider the distance between points (x1, y1) and (x2, y2) equal |x1 - x2| + |y1 - y2|. The distance between the point and the straight lines is the minimum distance from the point to some point belonging to one of the lines.Help Sereja, find the maximum distance from the points to the optimally located straight lines.InputThe first line contains integer n (1 ≀ n ≀ 105). Next n lines contain the coordinates of the lines. The i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109).OutputIn a single line print a real number β€” the answer to the problem. Your answer will be considered correct iff its absolute or relative error doesn't exceed 10 - 6.ExamplesInput40 02 00 22 2Output0.000000000000000Input41 00 12 11 2Output1.000000000000000
Input40 02 00 22 2
Output0.000000000000000
2 seconds
256 megabytes
['binary search', 'data structures', 'geometry', 'sortings', 'two pointers', '*2500']
C. Sereja and Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja has a sequence that consists of n positive integers, a1, a2, ..., an. First Sereja took a piece of squared paper and wrote all distinct non-empty non-decreasing subsequences of sequence a. Then for each sequence written on the squared paper, Sereja wrote on a piece of lines paper all sequences that do not exceed it.A sequence of positive integers x = x1, x2, ..., xr doesn't exceed a sequence of positive integers y = y1, y2, ..., yr, if the following inequation holds: x1 ≀ y1, x2 ≀ y2, ..., xr ≀ yr.Now Sereja wonders, how many sequences are written on the lines piece of paper. Help Sereja, find the required quantity modulo 1000000007 (109 + 7). InputThe first line contains integer n (1 ≀ n ≀ 105). The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106).OutputIn the single line print the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput142Output42Input31 2 2Output13Input51 2 3 4 5Output719
Input142
Output42
2 seconds
256 megabytes
['data structures', 'dp', '*2000']
B. Sereja and Periodstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's introduce the designation , where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc.We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, strings ab and aсba can be obtained from string xacbac, and strings bx and aaa cannot be obtained from it.Sereja has two strings, w = [a, b] and q = [c, d]. He wants to find such maximum integer p (p > 0), that [q, p] can be obtained from string w.InputThe first line contains two integers b, d (1 ≀ b, d ≀ 107). The second line contains string a. The third line contains string c. The given strings are not empty and consist of lowercase English letters. Their lengths do not exceed 100.OutputIn a single line print an integer β€” the largest number p. If the required value of p doesn't exist, print 0.ExamplesInput10 3ababbabOutput3
Input10 3ababbab
Output3
1 second
256 megabytes
['binary search', 'dfs and similar', 'strings', '*2000']
A. Sereja and Contesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants. Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula .After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.InputThe first line contains two integers n, k (1 ≀ n ≀ 2Β·105,  - 109 ≀ k ≀ 0). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” ratings of the participants in the initial table.OutputPrint the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.ExamplesInput5 05 3 4 1 2Output234Input10 -105 5 1 7 5 1 2 4 9 2Output245789NoteConsider the first test sample. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered. Thus, you should print 2, 3, 4.
Input5 05 3 4 1 2
Output234
2 seconds
256 megabytes
['implementation', '*1600']
E. Ilya and Two Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya has recently taken up archaeology. He's recently found two numbers, written in the m-based notation. Each of the found numbers consisted of exactly n digits. Ilya immediately started looking for information about those numbers. He learned that the numbers are part of a cyphered code and the one who can decypher it can get the greatest treasure.After considerable research Ilya understood that to decypher the code, he should do the following: Rearrange digits in the first number in some manner. Similarly, rearrange digits in the second number in some manner. As a result of this operation, the numbers can get leading zeroes. Add numbers, digit by digit, modulo m. In other words, we need to get the third number of length n, each digit of the number is the sum of the respective numbers of the found numbers. For example, suppose there are two numbers recorded in the ternary notation, 001210 and 012111, then if you add them to each other digit by digit modulo 3, you will get number 010021. The key to the code is the maximum possible number that can be obtained in the previous step. Help Ilya, find the key to the code.InputThe first line contains two integers n, m (1 ≀ n, m ≀ 105, m > 1). The second line contains the first found number, the third line contains the second found number. The numbers are recorded as a sequence of digits in the m-based notation. Each digit is an integer from 0 to m - 1. The digits in the line are written in the order from the most significant digits to the least significant ones.The given numbers can contain leading zeroes.OutputPrint n m-base digits. The resulting third number written in the m-based notation. Print the digits in the order from the most significant digits to the least significant ones.ExamplesInput4 75 4 3 25 6 5 4Output6 4 2 1 Input5 52 4 4 1 31 0 1 2 4Output4 4 4 3 2
Input4 75 4 3 25 6 5 4
Output6 4 2 1
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'dsu', 'greedy', '*2300']
D. Ilya and Roadstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as n holes in a row. We will consider the holes numbered from 1 to n, from left to right.Ilya is really keep on helping his city. So, he wants to fix at least k holes (perharps he can fix more) on a single ZooVille road. The city has m building companies, the i-th company needs ci money units to fix a road segment containing holes with numbers of at least li and at most ri. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment. Determine the minimum money Ilya will need to fix at least k holes.InputThe first line contains three integers n, m, k (1 ≀ n ≀ 300, 1 ≀ m ≀ 105, 1 ≀ k ≀ n). The next m lines contain the companies' description. The i-th line contains three integers li, ri, ci (1 ≀ li ≀ ri ≀ n, 1 ≀ ci ≀ 109).OutputPrint a single integer β€” the minimum money Ilya needs to fix at least k holes. If it is impossible to fix at least k holes, print -1.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput10 4 67 9 116 9 137 7 73 5 6Output17Input10 7 13 4 158 9 85 6 89 10 61 4 21 4 108 10 13Output2Input10 1 95 10 14Output-1
Input10 4 67 9 116 9 137 7 73 5 6
Output17
3 seconds
256 megabytes
['dp', '*2100']
C. Ilya and Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.He's got a square 2n × 2n-sized matrix and 4n integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that the beauty of the resulting matrix with numbers is maximum.The beauty of a 2n × 2n-sized matrix is an integer, obtained by the following algorithm: Find the maximum element in the matrix. Let's denote it as m. If n = 0, then the beauty of the matrix equals m. Otherwise, a matrix can be split into 4 non-intersecting 2n - 1 × 2n - 1-sized submatrices, then the beauty of the matrix equals the sum of number m and other four beauties of the described submatrices. As you can see, the algorithm is recursive.Help Ilya, solve the problem and print the resulting maximum beauty of the matrix.InputThe first line contains integer 4n (1 ≀ 4n ≀ 2Β·106). The next line contains 4n integers ai (1 ≀ ai ≀ 109) β€” the numbers you need to arrange in the 2n × 2n-sized matrix.OutputOn a single line print the maximum value of the beauty of the described matrix.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput113Output13Input41 2 3 4Output14NoteConsider the second sample. You need to arrange the numbers in the matrix as follows:1 23 4Then the beauty of the matrix will equal: 4 + 1 + 2 + 3 + 4 = 14.
Input113
Output13
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'sortings', '*1400']
B. Ilya and Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li < ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i < ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.InputThe first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#".The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li < ri ≀ n).OutputPrint m integers β€” the answers to the queries in the order in which they are given in the input.ExamplesInput......43 42 31 62 6Output1154Input#..###51 35 61 53 63 4Output11220
Input......43 42 31 62 6
Output1154
2 seconds
256 megabytes
['dp', 'implementation', '*1100']
A. Ilya and Bank Accounttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money.Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance.Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.InputThe single line contains integer n (10 ≀ |n| ≀ 109) β€” the state of Ilya's bank account.OutputIn a single line print an integer β€” the maximum state of the bank account that Ilya can get. ExamplesInput2230Output2230Input-10Output0Input-100003Output-10000NoteIn the first test sample Ilya doesn't profit from using the present.In the second test sample you can delete digit 1 and get the state of the account equal to 0.
Input2230
Output2230
2 seconds
256 megabytes
['implementation', 'number theory', '*900']
B. Archertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.InputA single line contains four integers .OutputPrint a single real number, the probability that SmallR will win the match.The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.ExamplesInput1 2 1 2Output0.666666666667
Input1 2 1 2
Output0.666666666667
2 seconds
256 megabytes
['math', 'probabilities', '*1300']
A. Whose sentence is it?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is. InputThe first line of the input contains an integer n (1 ≀ n ≀ 10), number of sentences in the chat record. Each of the next n lines contains a sentence. A sentence is a string that contains only Latin letters (A-Z, a-z), underline (_), comma (,), point (.) and space ( ). Its length doesn’t exceed 100.OutputFor each sentence, output "Freda's" if the sentence was said by Freda, "Rainbow's" if the sentence was said by Rainbow, or "OMG>.< I don't know!" if liouzhou_101 can’t recognize whose sentence it is. He can’t recognize a sentence if it begins with "miao." and ends with "lala.", or satisfies neither of the conditions. ExamplesInput5I will go to play with you lala.wow, welcome.miao.lala.miao.miao .OutputFreda'sOMG>.< I don't know!OMG>.< I don't know!Rainbow'sOMG>.< I don't know!
Input5I will go to play with you lala.wow, welcome.miao.lala.miao.miao .
OutputFreda'sOMG>.< I don't know!OMG>.< I don't know!Rainbow'sOMG>.< I don't know!
2 seconds
256 megabytes
['implementation', 'strings', '*1100']
E. Biologisttime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSmallR is a biologist. Her latest research finding is how to change the sex of dogs. In other words, she can change female dogs into male dogs and vice versa.She is going to demonstrate this technique. Now SmallR has n dogs, the costs of each dog's change may be different. The dogs are numbered from 1 to n. The cost of change for dog i is vi RMB. By the way, this technique needs a kind of medicine which can be valid for only one day. So the experiment should be taken in one day and each dog can be changed at most once.This experiment has aroused extensive attention from all sectors of society. There are m rich folks which are suspicious of this experiment. They all want to bet with SmallR forcibly. If SmallR succeeds, the i-th rich folk will pay SmallR wi RMB. But it's strange that they have a special method to determine whether SmallR succeeds. For i-th rich folk, in advance, he will appoint certain ki dogs and certain one gender. He will think SmallR succeeds if and only if on some day the ki appointed dogs are all of the appointed gender. Otherwise, he will think SmallR fails.If SmallR can't satisfy some folk that isn't her friend, she need not pay him, but if someone she can't satisfy is her good friend, she must pay g RMB to him as apologies for her fail.Then, SmallR hope to acquire money as much as possible by this experiment. Please figure out the maximum money SmallR can acquire. By the way, it is possible that she can't obtain any money, even will lose money. Then, please give out the minimum money she should lose.InputThe first line contains three integers n, m, g (1 ≀ n ≀ 104, 0 ≀ m ≀ 2000, 0 ≀ g ≀ 104). The second line contains n integers, each is 0 or 1, the sex of each dog, 0 represent the female and 1 represent the male. The third line contains n integers v1, v2, ..., vn (0 ≀ vi ≀ 104).Each of the next m lines describes a rich folk. On the i-th line the first number is the appointed sex of i-th folk (0 or 1), the next two integers are wi and ki (0 ≀ wi ≀ 104, 1 ≀ ki ≀ 10), next ki distinct integers are the indexes of appointed dogs (each index is between 1 and n). The last number of this line represents whether i-th folk is SmallR's good friend (0 β€” no or 1 β€” yes).OutputPrint a single integer, the maximum money SmallR can gain. Note that the integer is negative if SmallR will lose money. ExamplesInput5 5 90 1 1 1 01 8 6 2 30 7 3 3 2 1 11 8 1 5 11 0 3 2 1 4 10 8 3 4 2 1 01 7 2 4 1 1Output2Input5 5 81 0 1 1 16 5 4 2 80 6 3 2 3 4 00 8 3 3 2 4 00 0 3 3 4 1 10 10 3 4 3 1 10 4 3 3 4 1 1Output16
Input5 5 90 1 1 1 01 8 6 2 30 7 3 3 2 1 11 8 1 5 11 0 3 2 1 4 10 8 3 4 2 1 01 7 2 4 1 1
Output2
1.5 seconds
256 megabytes
['flows', '*2300']
D. Interval Cubingtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile learning Computational Geometry, Tiny is simultaneously learning a useful data structure called segment tree or interval tree. He has scarcely grasped it when comes out a strange problem:Given an integer sequence a1, a2, ..., an. You should run q queries of two types: Given two integers l and r (1 ≀ l ≀ r ≀ n), ask the sum of all elements in the sequence al, al + 1, ..., ar. Given two integers l and r (1 ≀ l ≀ r ≀ n), let each element x in the sequence al, al + 1, ..., ar becomes x3. In other words, apply an assignments al = al3, al + 1 = al + 13, ..., ar = ar3. For every query of type 1, output the answer to it.Tiny himself surely cannot work it out, so he asks you for help. In addition, Tiny is a prime lover. He tells you that because the answer may be too huge, you should only output it modulo 95542721 (this number is a prime number).InputThe first line contains an integer n (1 ≀ n ≀ 105), representing the length of the sequence. The second line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109).The third line contains an integer q (1 ≀ q ≀ 105), representing the number of queries. Then follow q lines. Each line contains three integers ti (1 ≀ ti ≀ 2), li, ri (1 ≀ li ≀ ri ≀ n), where ti stands for the type of the query while li and ri is the parameters of the query, correspondingly.OutputFor each 1-type query, print the answer to it per line.You should notice that each printed number should be non-negative and less than 95542721.ExamplesInput81 2 3 4 5 6 7 851 2 52 2 51 2 52 3 61 4 7Output142242215492
Input81 2 3 4 5 6 7 851 2 52 2 51 2 52 3 61 4 7
Output142242215492
6 seconds
256 megabytes
['data structures', 'math', '*2600']
C. Fetch the Treasuretime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRainbow built h cells in a row that are numbered from 1 to h from left to right. There are n cells with treasure. We call each of these n cells "Treasure Cell". The i-th "Treasure Cell" is the ai-th cell and the value of treasure in it is ci dollars.Then, Freda went in the first cell. For now, she can go just k cells forward, or return to the first cell. That means Freda was able to reach the 1st, (k + 1)-th, (2Β·k + 1)-th, (3Β·k + 1)-th cells and so on.Then Rainbow gave Freda m operations. Each operation is one of the following three types: Add another method x: she can also go just x cells forward at any moment. For example, initially she has only one method k. If at some moment she has methods a1, a2, ..., ar then she can reach all the cells with number in form , where vi β€” some non-negative integer. Reduce the value of the treasure in the x-th "Treasure Cell" by y dollars. In other words, to apply assignment cx = cx - y. Ask the value of the most valuable treasure among the cells Freda can reach. If Freda cannot reach any cell with the treasure then consider the value of the most valuable treasure equal to 0, and do nothing. Otherwise take the most valuable treasure away. If several "Treasure Cells" have the most valuable treasure, take the "Treasure Cell" with the minimum number (not necessarily with the minimum number of cell). After that the total number of cells with a treasure is decreased by one. As a programmer, you are asked by Freda to write a program to answer each query.InputThe first line of the input contains four integers: hΒ (1 ≀ h ≀ 1018), n, mΒ (1 ≀ n, m ≀ 105) and kΒ (1 ≀ k ≀ 104).Each of the next n lines contains two integers: aiΒ (1 ≀ ai ≀ h), ciΒ (1 ≀ ci ≀ 109). That means the i-th "Treasure Cell" is the ai-th cell and cost of the treasure in that cell is ci dollars. All the ai are distinct.Each of the next m lines is in one of the three following formats: "1 x" β€” an operation of type 1, 1 ≀ x ≀ h; "2 x y" β€” an operation of type 2, 1 ≀ x ≀ n, 0 ≀ y < cx; "3" β€” an operation of type 3. There are at most 20 operations of type 1. It's guaranteed that at any moment treasure in each cell has positive value. It's guaranteed that all operations is correct (no operation can decrease the value of the taken tresure).Please, do not use the %lld specifier to read 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.OutputFor each operation of type 3, output an integer indicates the value (in dollars) of the most valuable treasure among the "Treasure Cells" Freda can reach. If there is no such treasure, output 0.ExamplesInput10 3 5 25 507 608 1002 2 531 333Output5510050NoteIn the sample, there are 10 cells and 3 "Treasure Cells". The first "Treasure Cell" is cell 5, having 50 dollars tresure in it. The second "Treasure Cell" is cell 7, having 60 dollars tresure in it. The third "Treasure Cell" is cell 8, having 100 dollars tresure in it.At first, Freda can only reach cell 1, 3, 5, 7 and 9. In the first operation, we reduce the value in the second "Treasure Cell" from 60 to 55. Then the most valuable treasure among the "Treasure Cells" she can reach is max(50, 55) = 55. After the third operation, she can also go 3 cells forward each step, being able to reach cell 1, 3, 4, 5, 6, 7, 8, 9, 10. So the most valuable tresure is 100.Noticed that she took the 55 dollars and 100 dollars treasure away, so the last answer is 50.
Input10 3 5 25 507 608 1002 2 531 333
Output5510050
3 seconds
256 megabytes
['brute force', 'data structures', 'graphs', 'shortest paths', '*2500']
B. Cats Transporttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZxr960115 is owner of a large farm. He feeds m cute cats and employs p feeders. There's a straight road across the farm and n hills along the road, numbered from 1 to n from left to right. The distance between hill i and (i - 1) is di meters. The feeders live in hill 1.One day, the cats went out to play. Cat i went on a trip to hill hi, finished its trip at time ti, and then waited at hill hi for a feeder. The feeders must take all the cats. Each feeder goes straightly from hill 1 to n without waiting at a hill and takes all the waiting cats at each hill away. Feeders walk at a speed of 1 meter per unit time and are strong enough to take as many cats as they want.For example, suppose we have two hills (d2 = 1) and one cat that finished its trip at time 3 at hill 2 (h1 = 2). Then if the feeder leaves hill 1 at time 2 or at time 3, he can take this cat, but if he leaves hill 1 at time 1 he can't take it. If the feeder leaves hill 1 at time 2, the cat waits him for 0 time units, if the feeder leaves hill 1 at time 3, the cat waits him for 1 time units.Your task is to schedule the time leaving from hill 1 for each feeder so that the sum of the waiting time of all cats is minimized.InputThe first line of the input contains three integers n, m, p (2 ≀ n ≀ 105, 1 ≀ m ≀ 105, 1 ≀ p ≀ 100).The second line contains n - 1 positive integers d2, d3, ..., dn (1 ≀ di < 104).Each of the next m lines contains two integers hi and ti (1 ≀ hi ≀ n, 0 ≀ ti ≀ 109).OutputOutput an integer, the minimum sum of waiting time of all cats.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput4 6 21 3 51 02 14 91 102 103 12Output3
Input4 6 21 3 51 02 14 91 102 103 12
Output3
2 seconds
256 megabytes
['data structures', 'dp', '*2400']
A. The Closest Pairtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCurrently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.The problem is the follows. Given n points in the plane, find a pair of points between which the distance is minimized. Distance between (x1, y1) and (x2, y2) is .The pseudo code of the unexpected code is as follows:input nfor i from 1 to n input the i-th point's coordinates into p[i]sort array p[] by increasing of x coordinate first and increasing of y coordinate secondd=INF //here INF is a number big enoughtot=0for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x>=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j]))output dHere, tot can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, tot should not be more than k in order not to get Time Limit Exceeded.You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?InputA single line which contains two space-separated integers n and k (2 ≀ n ≀ 2000, 1 ≀ k ≀ 109).OutputIf there doesn't exist such a data which let the given code get TLE, print "no solution" (without quotes); else print n lines, and the i-th line contains two integers xi, yi (|xi|, |yi| ≀ 109) representing the coordinates of the i-th point.The conditions below must be held: All the points must be distinct. |xi|, |yi| ≀ 109. After running the given code, the value of tot should be larger than k. ExamplesInput4 3Output0 00 11 01 1Input2 100Outputno solution
Input4 3
Output0 00 11 01 1
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1300']
E. Sheeptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInformation technologies are developing and are increasingly penetrating into all spheres of human activity. Incredible as it is, the most modern technology are used in farming!A large farm has a meadow with grazing sheep. Overall there are n sheep and each of them contains a unique number from 1 to n β€” because the sheep need to be distinguished and you need to remember information about each one, and they are so much alike! The meadow consists of infinite number of regions numbered from 1 to infinity. It's known that sheep i likes regions from li to ri.There are two shepherds taking care of the sheep: First and Second. First wakes up early in the morning and leads the sheep graze on the lawn. Second comes in the evening and collects all the sheep.One morning, First woke up a little later than usual, and had no time to lead the sheep graze on the lawn. So he tied together every two sheep if there is a region they both like. First thought that it would be better β€” Second would have less work in the evening, because sheep won't scatter too much, being tied to each other!In the evening Second came on the lawn, gathered the sheep and tried to line them up in a row. But try as he might, the sheep wouldn't line up as Second want! Second had neither the strength nor the ability to untie the sheep so he left them as they are, but with one condition: he wanted to line up the sheep so that the maximum distance between two tied sheep was as small as possible. The distance between the sheep is the number of sheep in the ranks that are between these two.Help Second find the right arrangement.InputThe first input line contains one integer n (1 ≀ n ≀ 2000). Each of the following n lines contains two integers li and ri (1 ≀ li, ri ≀ 109;Β li ≀ ri).OutputIn the single output line print n space-separated numbers β€” the sought arrangement of the sheep. The i-th value in the line must represent the number of the sheep that took the i-th place from left in the optimal arrangement line. If there are multiple optimal arrangements, print any of them.ExamplesInput31 35 72 4Output1 3 2Input51 52 43 61 72 6Output2 1 3 5 4Input41 34 65 72 3Output1 4 2 3
Input31 35 72 4
Output1 3 2
1 second
256 megabytes
['binary search', 'greedy', '*2900']
D. Tennis Racketstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessional sport is more than hard work. It also is the equipment, designed by top engineers. As an example, let's take tennis. Not only should you be in great shape, you also need an excellent racket! In this problem your task is to contribute to the development of tennis and to help to design a revolutionary new concept of a racket!The concept is a triangular racket. Ant it should be not just any triangle, but a regular one. As soon as you've chosen the shape, you need to stretch the net. By the time you came the rocket had n holes drilled on each of its sides. The holes divide each side into equal n + 1 parts. At that, the m closest to each apex holes on each side are made for better ventilation only and you cannot stretch the net through them. The next revolutionary idea as to stretch the net as obtuse triangles through the holes, so that for each triangle all apexes lay on different sides. Moreover, you need the net to be stretched along every possible obtuse triangle. That's where we need your help β€” help us to count the number of triangles the net is going to consist of.Two triangles are considered to be different if their pictures on the fixed at some position racket are different.InputThe first and the only input line contains two integers n, m .OutputPrint a single number β€” the answer to the problem.ExamplesInput3 0Output9Input4 0Output24Input10 1Output210Input8 4Output0NoteFor the following picture n = 8, m = 2. White circles are the holes for ventilation, red circles β€” holes for net stretching. One of the possible obtuse triangles is painted red.
Input3 0
Output9
3 seconds
256 megabytes
['brute force', 'geometry', '*2700']
C. Memory for Arraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine.We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly n memory clusters, the i-th cluster consists of ai cells. You need to find memory for m arrays in your program. The j-th array takes 2bj consecutive memory cells. There possibly isn't enough memory for all m arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 106). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ 2bi ≀ 109).OutputPrint a single integer β€” the answer to the problem.ExamplesInput5 38 4 3 2 23 2 2Output2Input10 61 1 1 1 1 1 1 1 1 10 0 0 0 0 0Output6NoteIn the first example you are given memory clusters with sizes 8, 4, 3, 2, 2 and arrays with sizes 8, 4, 4. There are few ways to obtain an answer equals 2: you can locate array with size 8 to the cluster with size 8, and one of the arrays with size 4 to the cluster with size 4. Another way is to locate two arrays with size 4 to the one cluster with size 8.In the second example you are given 10 memory clusters with size 1 and 6 arrays with size 1. You can choose any 6 clusters and locate all given arrays to them.
Input5 38 4 3 2 23 2 2
Output2
2 seconds
256 megabytes
['binary search', 'bitmasks', 'greedy', '*1900']
B. Context Advertisingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdvertising has become part of our routine. And now, in the era of progressive technologies, we need your ideas to make advertising better!In this problem we'll look at a simplified version of context advertising. You've got a text, consisting of exactly n words. A standard advertising banner has exactly r lines, each line can contain at most c characters. The potential customer always likes it when they can see lots of advertising, so you should determine which maximum number of consecutive words from the text can be written on the banner. Single words in one line of the banner should be separated by spaces. You are allowed to insert more than one space at once. Note that you are not allowed to break the words, that is, each word in the text must occupy exactly one line in the banner. Besides, you cannot change the word order, that is, if you read the banner text consecutively, from top to bottom and from left to right, you should get some consecutive part of the advertisement text.More formally, the statement can be written like that. Let's say that all words are indexed from 1 to n in the order in which they occur in the advertisement text. Then you have to choose all words, starting from some i-th one and ending with some j-th one (1 ≀ i ≀ j ≀ n), so that all of them could be written on the banner. There must be as many words as possible. See the samples for clarifications.InputThe first input line contains three integers n, r, c (1 ≀ n, r, c ≀ 106;Β r × c ≀ 106). The next line contains a text, consisting of n words. The words consist only of lowercase English letters and are not empty. The words in the lines are separated by single spaces. The total number of characters in all words doesn't exceed 5Β·106.OutputPrint at most r lines, in each line print at most c characters β€” the optimal advertisement banner. If there are multiple advertisement banners, print any of them. Note that some lines of the banner can be empty. You are allowed not to print such lines.ExamplesInput9 4 12this is a sample text for croc final roundOutputthis is asample textfor crocfinal roundInput9 1 9this is a sample text for croc final roundOutputthis is aInput6 2 3croc a a a croc aOutputa aaInput2 2 5first secondOutputfirst
Input9 4 12this is a sample text for croc final round
Outputthis is asample textfor crocfinal round
2 seconds
256 megabytes
['dp', 'two pointers', '*2100']
A. Morning runtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeople like to be fit. That's why many of them are ready to wake up at dawn, go to the stadium and run. In this problem your task is to help a company design a new stadium. The city of N has a shabby old stadium. Many people like it and every morning thousands of people come out to this stadium to run. The stadium can be represented as a circle, its length is exactly l meters with a marked start line. However, there can't be simultaneous start in the morning, so exactly at 7, each runner goes to his favorite spot on the stadium and starts running from there. Note that not everybody runs in the same manner as everybody else. Some people run in the clockwise direction, some of them run in the counter-clockwise direction. It mostly depends on the runner's mood in the morning, so you can assume that each running direction is equiprobable for each runner in any fixed morning. The stadium is tiny and is in need of major repair, for right now there only is one running track! You can't get too playful on a single track, that's why all runners keep the same running speed β€” exactly 1 meter per a time unit. Nevertheless, the runners that choose different directions bump into each other as they meet. The company wants to design a new stadium, but they first need to know how bad the old one is. For that they need the expectation of the number of bumpings by t time units after the running has begun. Help the company count the required expectation. Note that each runner chooses a direction equiprobably, independently from the others and then all runners start running simultaneously at 7 a.m. Assume that each runner runs for t time units without stopping. Consider the runners to bump at a certain moment if at that moment they found themselves at the same point in the stadium. A pair of runners can bump more than once.InputThe first line of the input contains three integers n, l, t (1 ≀ n ≀ 106, 1 ≀ l ≀ 109, 1 ≀ t ≀ 109). The next line contains n distinct integers a1, a2, ..., an (0 ≀ a1 < a2 < ... < an < l), here ai is the clockwise distance from the start line to the i-th runner's starting position.OutputPrint a single real number β€” the answer to the problem with absolute or relative error of at most 10 - 6.ExamplesInput2 5 10 2Output0.2500000000Input3 7 30 1 6Output1.5000000000NoteThere are two runners in the first example. If the first runner run clockwise direction, then in 1 time unit he will be 1m away from the start line. If the second runner run counter-clockwise direction then in 1 time unit he will be also 1m away from the start line. And it is the only possible way to meet. We assume that each running direction is equiprobable, so the answer for the example is equal to 0.5Β·0.5 = 0.25.
Input2 5 10 2
Output0.2500000000
2 seconds
256 megabytes
['binary search', 'math', 'two pointers', '*2000']
D. Polygontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus loves convex polygons, especially if all their angles are the same and all their sides are different. Draw for him any such polygon with the given number of vertexes.InputThe input contains a single integer n (3 ≀ n ≀ 100) β€” the number of the polygon vertexes.OutputPrint n lines, containing the coordinates of the vertexes of the n-gon "xi yi" in the counter clockwise order. The coordinates of the vertexes shouldn't exceed 106 in their absolute value. The side lengths should fit within limits [1, 1000] (not necessarily integer). Mutual comparing sides and angles of your polygon during the test will go with precision of 10 - 3.If there is no solution, print "No solution" (without the quotes).ExamplesInput8Output1.000 0.0007.000 0.0009.000 2.0009.000 3.0005.000 7.0003.000 7.0000.000 4.0000.000 1.000
Input8
Output1.000 0.0007.000 0.0009.000 2.0009.000 3.0005.000 7.0003.000 7.0000.000 4.0000.000 1.000
1 second
256 megabytes
['constructive algorithms', 'geometry', '*2300']
C. White, Black and White Againtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus is sure that his life fits the description: "first there is a white stripe, then a black one, then a white one again". So, Polycarpus is sure that this rule is going to fulfill during the next n days. Polycarpus knows that he is in for w good events and b not-so-good events. At least one event is going to take place during each day. As each day is unequivocally characterizes as a part of a white or a black stripe, then each day is going to have events of the same type only (ether good or not-so-good).What is the number of distinct ways this scenario can develop over the next n days if Polycarpus is in for a white stripe (a stripe that has good events only, the stripe's length is at least 1 day), the a black stripe (a stripe that has not-so-good events only, the stripe's length is at least 1 day) and a white stripe again (a stripe that has good events only, the stripe's length is at least 1 day). Each of n days will belong to one of the three stripes only.Note that even the events of the same type are distinct from each other. Even if some events occur on the same day, they go in some order (there are no simultaneous events).Write a code that prints the number of possible configurations to sort the events into days. See the samples for clarifications on which scenarios should be considered distinct. Print the answer modulo 1000000009 (109 + 9).InputThe single line of the input contains integers n, w and b (3 ≀ n ≀ 4000, 2 ≀ w ≀ 4000, 1 ≀ b ≀ 4000) β€” the number of days, the number of good events and the number of not-so-good events. It is guaranteed that w + b β‰₯ n.OutputPrint the required number of ways modulo 1000000009 (109 + 9).ExamplesInput3 2 1Output2Input4 2 2Output4Input3 2 2Output4NoteWe'll represent the good events by numbers starting from 1 and the not-so-good events β€” by letters starting from 'a'. Vertical lines separate days.In the first sample the possible ways are: "1|a|2" and "2|a|1". In the second sample the possible ways are: "1|a|b|2", "2|a|b|1", "1|b|a|2" and "2|b|a|1". In the third sample the possible ways are: "1|ab|2", "2|ab|1", "1|ba|2" and "2|ba|1".
Input3 2 1
Output2
3 seconds
256 megabytes
['combinatorics', 'number theory', '*2100']
B. Optimizertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA process RAM is a sequence of bytes that are indexed from 1 to n. Polycarpus's program contains such instructions as "memset", that is, the operations of filling memory cells on a segment with some value. The details are: the code only contains m instructions that look like "set13 a_i l_i". Instruction i fills a continuous memory segment of length li, starting from cell number ai, (that it cells with numbers ai, ai + 1, ..., ai + li - 1) with values 13.In Polycarpus's code, the optimizer's task is to remove the maximum number of instructions from his code in such a way that the remaining instructions set value 13 in all the memory bytes that got this value from the code before the optimization. Also, the value 13 should be set only in the memory bytes that got this value from the code before the optimization. Your task is to implement the optimizer for such program.InputThe first line contains integers n and m (1 ≀ n ≀ 2Β·106, 1 ≀ m ≀ 2Β·105) β€” the number of bytes (memory cells) and the number of instructions in Polycarpus's code. Then m lines follow, each line contains a pair of integers ai, li (1 ≀ ai ≀ n, 1 ≀ li ≀ n - ai + 1).OutputPrint in the first line the sought maximum number of instructions that can be removed from the code. In the second line print the numbers of the instructions. The instructions are numbered from 1 to m in the order they appeared in the input. If there are multiple solutions, print any of them.ExamplesInput10 43 33 14 19 2Output22 3 Input1 11 1Output0
Input10 43 33 14 19 2
Output22 3
3 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*2100']
A. Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has got n candies and m friends (n β‰₯ m). He wants to make a New Year present with candies to each friend. Polycarpus is planning to present all candies and he wants to do this in the fairest (that is, most equal) manner. He wants to choose such ai, where ai is the number of candies in the i-th friend's present, that the maximum ai differs from the least ai as little as possible.For example, if n is divisible by m, then he is going to present the same number of candies to all his friends, that is, the maximum ai won't differ from the minimum one.InputThe single line of the input contains a pair of space-separated positive integers n, m (1 ≀ n, m ≀ 100;n β‰₯ m) β€” the number of candies and the number of Polycarpus's friends.OutputPrint the required sequence a1, a2, ..., am, where ai is the number of candies in the i-th friend's present. All numbers ai must be positive integers, total up to n, the maximum one should differ from the minimum one by the smallest possible value.ExamplesInput12 3Output4 4 4 Input15 4Output3 4 4 4 Input18 7Output2 2 2 3 3 3 3 NotePrint ai in any order, separate the numbers by spaces.
Input12 3
Output4 4 4
1 second
256 megabytes
['implementation', '*800']
E. Playing with Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell. An example of the initial situation at s = "abacaba" A player's move is the sequence of actions: The player chooses one of the available pieces of paper with some string written on it. Let's denote it is t. Note that initially, only one piece of paper is available. The player chooses in the string t = t1t2... t|t| character in position i (1 ≀ i ≀ |t|) such that for some positive integer l (0 < i - l;Β i + l ≀ |t|) the following equations hold: ti - 1 = ti + 1, ti - 2 = ti + 2, ..., ti - l = ti + l. Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string t1t2... ti - 1, the second one will contain a string consisting of a single character ti, the third one contains string ti + 1ti + 2... t|t|. An example of making action (i = 4) with string s = Β«abacabaΒ» Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.InputThe first line contains string s (1 ≀ |s| ≀ 5000). It is guaranteed that string s only contains lowercase English letters.OutputIf the second player wins, print in the single line "Second" (without the quotes). Otherwise, print in the first line "First" (without the quotes), and in the second line print the minimal possible winning move β€” integer i (1 ≀ i ≀ |s|).ExamplesInputabacabaOutputFirst2InputabcdeOutputSecondNoteIn the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2. In the second sample the first player has no available moves.
Inputabacaba
OutputFirst2
2 seconds
256 megabytes
['games', '*2300']
D. Olya and Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOlya has got a directed non-weighted graph, consisting of n vertexes and m edges. We will consider that the graph vertexes are indexed from 1 to n in some manner. Then for any graph edge that goes from vertex v to vertex u the following inequation holds: v < u.Now Olya wonders, how many ways there are to add an arbitrary (possibly zero) number of edges to the graph so as the following conditions were met: You can reach vertexes number i + 1, i + 2, ..., n from any vertex number i (i < n). For any graph edge going from vertex v to vertex u the following inequation fulfills: v < u. There is at most one edge between any two vertexes. The shortest distance between the pair of vertexes i, j (i < j), for which j - i ≀ k holds, equals j - i edges. The shortest distance between the pair of vertexes i, j (i < j), for which j - i > k holds, equals either j - i or j - i - k edges. We will consider two ways distinct, if there is the pair of vertexes i, j (i < j), such that first resulting graph has an edge from i to j and the second one doesn't have it.Help Olya. As the required number of ways can be rather large, print it modulo 1000000007 (109 + 7).InputThe first line contains three space-separated integers n, m, k (2 ≀ n ≀ 106, 0 ≀ m ≀ 105, 1 ≀ k ≀ 106).The next m lines contain the description of the edges of the initial graph. The i-th line contains a pair of space-separated integers ui, vi (1 ≀ ui < vi ≀ n) β€” the numbers of vertexes that have a directed edge from ui to vi between them. It is guaranteed that any pair of vertexes ui, vi has at most one edge between them. It also is guaranteed that the graph edges are given in the order of non-decreasing ui. If there are multiple edges going from vertex ui, then it is guaranteed that these edges are given in the order of increasing vi.OutputPrint a single integer β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput7 8 21 22 33 43 64 54 75 66 7Output2Input7 0 2Output12Input7 2 11 33 5Output0NoteIn the first sample there are two ways: the first way is not to add anything, the second way is to add a single edge from vertex 2 to vertex 5.
Input7 8 21 22 33 43 64 54 75 66 7
Output2
2 seconds
256 megabytes
['combinatorics', 'math', '*2200']
C. Ivan and Powers of Twotime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan has got an array of n non-negative integers a1, a2, ..., an. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers 2a1, 2a2, ..., 2an on a piece of paper. Now he wonders, what minimum number of integers of form 2b (b β‰₯ 0) need to be added to the piece of paper so that the sum of all integers written on the paper equalled 2v - 1 for some integer v (v β‰₯ 0). Help Ivan, find the required quantity of numbers.InputThe first line contains integer n (1 ≀ n ≀ 105). The second input line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 2Β·109). It is guaranteed that a1 ≀ a2 ≀ ... ≀ an.OutputPrint a single integer β€” the answer to the problem.ExamplesInput40 1 1 1Output0Input13Output3NoteIn the first sample you do not need to add anything, the sum of numbers already equals 23 - 1 = 7.In the second sample you need to add numbers 20, 21, 22.
Input40 1 1 1
Output0
0.5 seconds
256 megabytes
['greedy', 'implementation', '*1600']
B. Continued Fractionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA continued fraction of height n is a fraction of form . You are given two rational numbers, one is represented as and the other one is represented as a finite fraction of height n. Check if they are equal.InputThe first line contains two space-separated integers p, q (1 ≀ q ≀ p ≀ 1018) β€” the numerator and the denominator of the first fraction.The second line contains integer n (1 ≀ n ≀ 90) β€” the height of the second fraction. The third line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 1018) β€” the continued fraction.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.OutputPrint "YES" if these fractions are equal and "NO" otherwise.ExamplesInput9 422 4OutputYESInput9 432 3 1OutputYESInput9 431 2 4OutputNONoteIn the first sample .In the second sample .In the third sample .
Input9 422 4
OutputYES
2 seconds
256 megabytes
['brute force', 'implementation', 'math', '*1700']
A. Strange Additiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUnfortunately, Vasya can only sum pairs of integers (a, b), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4.Vasya has a set of k distinct non-negative integers d1, d2, ..., dk.Vasya wants to choose some integers from this set so that he could sum any two chosen numbers. What maximal number of integers can he choose in the required manner?InputThe first input line contains integer k (1 ≀ k ≀ 100) β€” the number of integers.The second line contains k distinct space-separated integers d1, d2, ..., dk (0 ≀ di ≀ 100).OutputIn the first line print a single integer n the maximum number of the chosen integers. In the second line print n distinct non-negative integers β€” the required integers.If there are multiple solutions, print any of them. You can print the numbers in any order.ExamplesInput4100 10 1 0Output40 1 10 100 Input32 70 3Output22 70
Input4100 10 1 0
Output40 1 10 100
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'implementation', '*1600']
B. Calendartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCalendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year. In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February.Look at the sample to understand what borders are included in the aswer.InputThe first two lines contain two dates, each date is in the format yyyy:mm:dd (1900 ≀ yyyy ≀ 2038 and yyyy:mm:dd is a legal date).OutputPrint a single integer β€” the answer to the problem.ExamplesInput1900:01:012038:12:31Output50768Input1996:03:091991:11:12Output1579
Input1900:01:012038:12:31
Output50768
2 seconds
256 megabytes
['brute force', 'implementation', '*1300']
A. Pythagorean Theorem IItime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn mathematics, the Pythagorean theorem β€” is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states: In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle). The theorem can be written as an equation relating the lengths of the sides a, b and c, often called the Pythagorean equation:a2 + b2 = c2where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Given n, your task is to count how many right-angled triangles with side-lengths a, b and c that satisfied an inequality 1 ≀ a ≀ b ≀ c ≀ n.InputThe only line contains one integer nΒ (1 ≀ n ≀ 104) as we mentioned above.OutputPrint a single integer β€” the answer to the problem.ExamplesInput5Output1Input74Output35
Input5
Output1
3 seconds
256 megabytes
['brute force', 'math', '*1200']
E. Random Rankingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImagine a real contest or exam of n participants. Every participant will get a particular score. We can predict the standings board more or less, if we do some statistics on their previous performance. Let's say the score of the participants will be uniformly distributed in interval [li, ri] (the score can be a real number). Can you predict the standings board according to these data? In other words you should say for each participant the probability that he gets some fixed place in the scoreboard. The participants are sorted by increasing of their scores in the scoreboard. So, the participant with the largest score gets the last place.InputThe first line contains integer n (1  ≀ n  ≀ 80), showing how many participants we have. Each of the next n lines contains our predictions, the i-th line contains a pair of integers li, ri (0 ≀ li < ri ≀ 109) as the distributed interval for participant i.Consider the participants numbered from 1 to n in some way.OutputOutput a distributed matrix a of order n. The element aij of the matrix is the probability that participant i has rank j.Your answer will considered correct if it has at most 10 - 6 absolute or relative error.ExamplesInput21 64 9Output0.9200000000 0.080 0.080 0.9200000000 Input80 21 32 43 54 65 76 87 9Output0.875 0.125 0 0 0 0 0 0 0.125 0.750 0.125 0 0 0 0 0 0 0.125 0.750 0.125 0 0 0 0 0 0 0.125 0.750 0.125 0 0 0 0 0 0 0.125 0.750 0.125 0 0 0 0 0 0 0.125 0.750 0.125 0 0 0 0 0 0 0.125 0.750 0.125 0 0 0 0 0 0 0.125 0.875 NoteThe score probability distribution is continuous, which means, there is no possibility for a draw.
Input21 64 9
Output0.9200000000 0.080 0.080 0.9200000000
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*3000']
D. Rotatable Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBike is a smart boy who loves math very much. He invented a number called "Rotatable Number" inspired by 142857. As you can see, 142857 is a magic number because any of its rotatings can be got by multiplying that number by 1, 2, ..., 6 (numbers from one to number's length). Rotating a number means putting its last several digit into first. For example, by rotating number 12345 you can obtain any numbers: 12345, 51234, 45123, 34512, 23451. It's worth mentioning that leading-zeroes are allowed. So both 4500123 and 0123450 can be obtained by rotating 0012345. You can see why 142857 satisfies the condition. All of the 6 equations are under base 10. 142857Β·1 = 142857; 142857Β·2 = 285714; 142857Β·3 = 428571; 142857Β·4 = 571428; 142857Β·5 = 714285; 142857Β·6 = 857142. Now, Bike has a problem. He extends "Rotatable Number" under any base b. As is mentioned above, 142857 is a "Rotatable Number" under base 10. Another example is 0011 under base 2. All of the 4 equations are under base 2. 0011Β·1 = 0011; 0011Β·10 = 0110; 0011Β·11 = 1001; 0011Β·100 = 1100. So, he wants to find the largest b (1 < b < x) so that there is a positive "Rotatable Number" (leading-zeroes allowed) of length n under base b.Note that any time you multiply a rotatable number by numbers from 1 to its length you should get a rotating of that number.InputThe only line contains two space-separated integers n, x (1 ≀ n ≀ 5Β·106, 2 ≀ x ≀ 109). OutputPrint a single integer β€” the largest b you found. If no such b exists, print -1 instead. ExamplesInput6 11Output10Input5 8Output-1
Input6 11
Output10
2 seconds
256 megabytes
['math', 'number theory', '*2600']
C. Minimum Modulartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have been given n distinct integers a1, a2, ..., an. You can remove at most k of them. Find the minimum modular m (m > 0), so that for every pair of the remaining integers (ai, aj), the following unequality holds: .InputThe first line contains two integers n and k (1  ≀ n  ≀ 5000, 0 ≀ k ≀ 4), which we have mentioned above. The second line contains n distinct integers a1, a2, ..., an (0 ≀ ai ≀ 106).OutputPrint a single positive integer β€” the minimum m.ExamplesInput7 00 2 3 6 7 12 18Output13Input7 10 2 3 6 7 12 18Output7
Input7 00 2 3 6 7 12 18
Output13
2 seconds
256 megabytes
['brute force', 'graphs', 'math', 'number theory', '*2400']
B. Rectangle Puzzle IItime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangle grid. That grid's size is n × m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates β€” a pair of integers (x, y) (0 ≀ x ≀ n, 0 ≀ y ≀ m).Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (x, y), and its length-width ratio is exactly (a, b). In other words the following conditions must hold: 0 ≀ x1 ≀ x ≀ x2 ≀ n, 0 ≀ y1 ≀ y ≀ y2 ≀ m, .The sides of this sub-rectangle should be parallel to the axes. And values x1, y1, x2, y2 should be integers. If there are multiple solutions, find the rectangle which is closest to (x, y). Here "closest" means the Euclid distance between (x, y) and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers (x1, y1, x2, y2), so we can choose the lexicographically minimum one.InputThe first line contains six integers n, m, x, y, a, b (1 ≀ n, m ≀ 109, 0 ≀ x ≀ n, 0 ≀ y ≀ m, 1 ≀ a ≀ n, 1 ≀ b ≀ m).OutputPrint four integers x1, y1, x2, y2, which represent the founded sub-rectangle whose left-bottom point is (x1, y1) and right-up point is (x2, y2).ExamplesInput9 9 5 5 2 1Output1 3 9 7Input100 100 52 50 46 56Output17 8 86 92
Input9 9 5 5 2 1
Output1 3 9 7
2 seconds
256 megabytes
['implementation', 'math', '*1700']
A. Lucky Permutation Tripletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBike is interested in permutations. A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] is not.A permutation triple of permutations of length n (a, b, c) is called a Lucky Permutation Triple if and only if . The sign ai denotes the i-th element of permutation a. The modular equality described above denotes that the remainders after dividing ai + bi by n and dividing ci by n are equal.Now, he has an integer n and wants to find a Lucky Permutation Triple. Could you please help him?InputThe first line contains a single integer n (1 ≀ n ≀ 105).OutputIf no Lucky Permutation Triple of length n exists print -1.Otherwise, you need to print three lines. Each line contains n space-seperated integers. The first line must contain permutation a, the second line β€” permutation b, the third β€” permutation c.If there are multiple solutions, print any of them.ExamplesInput5Output1 4 3 2 01 0 2 4 32 4 0 1 3Input2Output-1NoteIn Sample 1, the permutation triple ([1, 4, 3, 2, 0], [1, 0, 2, 4, 3], [2, 4, 0, 1, 3]) is Lucky Permutation Triple, as following holds: ; ; ; ; . In Sample 2, you can easily notice that no lucky permutation triple exists.
Input5
Output1 4 3 2 01 0 2 4 32 4 0 1 3
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'math', '*1300']
B. Eugeny and Play Listtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.InputThe first line contains two integers n, m (1 ≀ n, m ≀ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≀ ci, ti ≀ 109) β€” the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 .The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m).The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.OutputPrint m integers β€” the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.ExamplesInput1 22 81 16Output11Input4 91 22 11 12 21 2 3 4 5 6 7 8 9Output112234444
Input1 22 81 16
Output11
2 seconds
256 megabytes
['binary search', 'implementation', 'two pointers', '*1200']
A. Eugeny and Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries: Query number i is given as a pair of integers li, ri (1 ≀ li ≀ ri ≀ n). The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries.InputThe first line contains integers n and m (1 ≀ n, m ≀ 2Β·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≀ li ≀ ri ≀ n).OutputPrint m integers β€” the responses to Eugene's queries in the order they occur in the input.ExamplesInput2 31 -11 11 22 2Output010Input5 5-1 1 1 1 -11 12 33 52 51 5Output01010
Input2 31 -11 11 22 2
Output010
1 second
256 megabytes
['implementation', '*800']
E. Yaroslav and Arrangementstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav calls an array of r integers a1, a2, ..., ar good, if it meets the following conditions: |a1 - a2| = 1, |a2 - a3| = 1, ..., |ar - 1 - ar| = 1, |ar - a1| = 1, at that . An array of integers b1, b2, ..., br is called great, if it meets the following conditions: The elements in it do not decrease (bi ≀ bi + 1). If the inequalities 1 ≀ r ≀ n and 1 ≀ bi ≀ m hold. If we can rearrange its elements and get at least one and at most k distinct good arrays. Yaroslav has three integers n, m, k. He needs to count the number of distinct great arrays. Help Yaroslav! As the answer may be rather large, print the remainder after dividing it by 1000000007 (109 + 7).Two arrays are considered distinct if there is a position in which they have distinct numbers.InputThe single line contains three integers n, m, k (1 ≀ n, m, k ≀ 100).OutputIn a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7).ExamplesInput1 1 1Output0Input3 3 3Output2
Input1 1 1
Output0
3 seconds
256 megabytes
['dp', '*2800']
D. Yaroslav and Divisorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav has an array p = p1, p2, ..., pn (1 ≀ pi ≀ n), consisting of n distinct integers. Also, he has m queries: Query number i is represented as a pair of integers li, ri (1 ≀ li ≀ ri ≀ n). The answer to the query li, ri is the number of pairs of integers q, w (li ≀ q, w ≀ ri) such that pq is the divisor of pw. Help Yaroslav, answer all his queries.InputThe first line contains the integers n and m (1 ≀ n, m ≀ 2Β·105). The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n). The following m lines contain Yaroslav's queries. The i-th line contains integers li, ri (1 ≀ li ≀ ri ≀ n).OutputPrint m integers β€” the answers to Yaroslav's queries in the order they appear in the input.Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput1 111 1Output1Input10 91 2 3 4 5 6 7 8 9 101 102 93 84 75 62 29 105 104 10Output27148421279
Input1 111 1
Output1
2 seconds
256 megabytes
['data structures', '*2200']
C. Yaroslav and Algorithmtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav likes algorithms. We'll describe one of his favorite algorithms. The algorithm receives a string as the input. We denote this input string as a. The algorithm consists of some number of command. Π‘ommand number i looks either as si >> wi, or as si <> wi, where si and wi are some possibly empty strings of length at most 7, consisting of digits and characters "?". At each iteration, the algorithm looks for a command with the minimum index i, such that si occurs in a as a substring. If this command is not found the algorithm terminates. Let's denote the number of the found command as k. In string a the first occurrence of the string sk is replaced by string wk. If the found command at that had form sk >> wk, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates. The value of string a after algorithm termination is considered to be the output of the algorithm. Yaroslav has a set of n positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one.Help Yaroslav.InputThe first line contains integer n (1 ≀ n ≀ 100) β€” the number of elements in the set. The next n lines contains one positive integer each. All the given numbers are less than 1025.OutputPrint the algorithm which can individually increase each number of the set. In the i-th line print the command number i without spaces.Your algorithm will be launched for each of these numbers. The answer will be considered correct if: Β  Each line will a correct algorithm command (see the description in the problem statement). The number of commands should not exceed 50. The algorithm will increase each of the given numbers by one. To get a respond, the algorithm will perform no more than 200 iterations for each number. ExamplesInput21079Output10<>1179<>80
Input21079
Output10<>1179<>80
2 seconds
256 megabytes
['constructive algorithms', '*2500']
B. Yaroslav and Timetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (xi, yi) of the plane. As the player visits station number i, he increases the current time on his timer by ai. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow.A player spends dΒ·dist time units to move between stations, where dist is the distance the player has covered and d is some constant. The distance between stations i and j is determined as |xi - xj| + |yi - yj|.Initially, the player is at station number 1, and the player has strictly more than zero and strictly less than one units of time. At station number 1 one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units).Now Yaroslav is wondering, how much money he needs to get to station n. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small.InputThe first line contains integers n and d (3 ≀ n ≀ 100, 103 ≀ d ≀ 105) β€” the number of stations and the constant from the statement.The second line contains n - 2 integers: a2, a3, ..., an - 1 (1 ≀ ai ≀ 103). The next n lines contain the coordinates of the stations. The i-th of them contains two integers xi, yi (-100 ≀ xi, yi ≀ 100).It is guaranteed that no two stations are located at the same point.OutputIn a single line print an integer β€” the answer to the problem.ExamplesInput3 100010000 00 10 3Output2000Input3 100010001 01 11 2Output1000
Input3 100010000 00 10 3
Output2000
2 seconds
256 megabytes
['binary search', 'graphs', 'shortest paths', '*2100']
A. Yaroslav and Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav has an array, consisting of (2Β·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?Help Yaroslav.InputThe first line contains an integer n (2 ≀ n ≀ 100). The second line contains (2Β·n - 1) integers β€” the array elements. The array elements do not exceed 1000 in their absolute value.OutputIn a single line print the answer to the problem β€” the maximum sum that Yaroslav can get.ExamplesInput250 50 50Output150Input2-1 -100 -1Output100NoteIn the first sample you do not need to change anything. The sum of elements equals 150.In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.
Input250 50 50
Output150
2 seconds
256 megabytes
['constructive algorithms', '*1800']