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
D. Tree and Queriestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a rooted tree consisting of n vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to n. Then we represent the color of vertex v as cv. The tree root is a vertex with number 1.In this problem you need to answer to m queries. Each query is described by two integers vj, kj. The answer to query vj, kj is the number of such colors of vertices x, that the subtree of vertex vj contains at least kj vertices of color x.You can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory).InputThe first line contains two integers n and m (2 ≀ n ≀ 105;Β 1 ≀ m ≀ 105). The next line contains a sequence of integers c1, c2, ..., cn (1 ≀ ci ≀ 105). The next n - 1 lines contain the edges of the tree. The i-th line contains the numbers ai, bi (1 ≀ ai, bi ≀ n;Β ai ≠ bi) β€” the vertices connected by an edge of the tree.Next m lines contain the queries. The j-th line contains two integers vj, kj (1 ≀ vj ≀ n;Β 1 ≀ kj ≀ 105).OutputPrint m integers β€” the answers to the queries in the order the queries appear in the input.ExamplesInput8 51 2 2 3 3 2 3 31 21 52 32 45 65 75 81 21 31 42 35 3Output22101Input4 11 2 3 41 22 33 41 1Output4NoteA subtree of vertex v in a rooted tree with root r is a set of vertices {uΒ : dist(r, v) + dist(v, u) = dist(r, u)}. Where dist(x, y) is the length (in edges) of the shortest path between vertices x and y.
Input8 51 2 2 3 3 2 3 31 21 52 32 45 65 75 81 21 31 42 35 3
Output22101
1 second
256 megabytes
['data structures', 'dfs and similar', 'trees', '*2400']
C. Circling Round Treasurestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a map as a rectangle table. Each cell of the table is either an obstacle, or a treasure with a certain price, or a bomb, or an empty cell. Your initial position is also given to you.You can go from one cell of the map to a side-adjacent one. At that, you are not allowed to go beyond the borders of the map, enter the cells with treasures, obstacles and bombs. To pick the treasures, you need to build a closed path (starting and ending in the starting cell). The closed path mustn't contain any cells with bombs inside. Let's assume that the sum of the treasures' values that are located inside the closed path equals v, and besides, you've made k single moves (from one cell to another) while you were going through the path, then such path brings you the profit of v - k rubles.Your task is to build a closed path that doesn't contain any bombs and brings maximum profit.Note that the path can have self-intersections. In order to determine if a cell lies inside a path or not, use the following algorithm: Assume that the table cells are points on the plane (the table cell on the intersection of the i-th column and the j-th row is point (i, j)). And the given path is a closed polyline that goes through these points. You need to find out if the point p of the table that is not crossed by the polyline lies inside the polyline. Let's draw a ray that starts from point p and does not intersect other points of the table (such ray must exist). Let's count the number of segments of the polyline that intersect the painted ray. If this number is odd, we assume that point p (and consequently, the table cell) lie inside the polyline (path). Otherwise, we assume that it lies outside. InputThe first line contains two integers n and m (1 ≀ n, m ≀ 20) β€” the sizes of the table. Next n lines each contains m characters β€” the description of the table. The description means the following: character "B" is a cell with a bomb; character "S" is the starting cell, you can assume that it's empty; digit c (1-8) is treasure with index c; character "." is an empty cell; character "#" is an obstacle. Assume that the map has t treasures. Next t lines contain the prices of the treasures. The i-th line contains the price of the treasure with index i, vi ( - 200 ≀ vi ≀ 200). It is guaranteed that the treasures are numbered from 1 to t. It is guaranteed that the map has not more than 8 objects in total. Objects are bombs and treasures. It is guaranteed that the map has exactly one character "S".OutputPrint a single integer β€” the maximum possible profit you can get.ExamplesInput4 4.....S1.........10Output2Input7 7........1###2..#...#..#.B.#..3...4...##.........S100100100100Output364Input7 8....................1B...S..........2...3...............100-100100Output0Input1 1SOutput0NoteIn the first example the answer will look as follows. In the second example the answer will look as follows. In the third example you cannot get profit.In the fourth example you cannot get profit as you cannot construct a closed path with more than one cell.
Input4 4.....S1.........10
Output2
1 second
256 megabytes
['bitmasks', 'shortest paths', '*2600']
B. Maximum Submatrix 2time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a matrix consisting of digits zero and one, its size is n × m. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations?Let's assume that the rows of matrix a are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. A matrix cell on the intersection of the i-th row and the j-th column can be represented as (i, j). Formally, a submatrix of matrix a is a group of four integers d, u, l, r (1 ≀ d ≀ u ≀ n;Β 1 ≀ l ≀ r ≀ m). We will assume that the submatrix contains cells (i, j) (d ≀ i ≀ u;Β l ≀ j ≀ r). The area of the submatrix is the number of cells it contains.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 5000). Next n lines contain m characters each β€” matrix a. Matrix a only contains characters: "0" and "1". Note that the elements of the matrix follow without any spaces in the lines.OutputPrint a single integer β€” the area of the maximum obtained submatrix. If we cannot obtain a matrix of numbers one, print 0.ExamplesInput1 11Output1Input2 21011Output2Input4 3100011000101Output2
Input1 11
Output1
2 seconds
512 megabytes
['data structures', 'dp', 'implementation', 'sortings', '*1600']
A. Divisible by Seventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.InputThe first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.OutputPrint a number in the decimal notation without leading zeroes β€” the result of the permutation.If it is impossible to rearrange the digits of the number a in the required manner, print 0.ExamplesInput1689Output1869Input18906Output18690
Input1689
Output1869
1 second
256 megabytes
['math', 'number theory', '*1600']
E. Inna and Babiestime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInna, Dima and Sereja are in one room together. It's cold outside, so Sereja suggested to play a board game called "Babies". The babies playing board is an infinite plane containing n blue babies and m red ones. Each baby is a segment that grows in time. At time moment t the blue baby (x, y) is a blue segment with ends at points (x - t, y + t), (x + t, y - t). Similarly, at time t the red baby (x, y) is a red segment with ends at points (x + t, y + t), (x - t, y - t) of the plane. Initially, at time t = 0 all babies are points on the plane.The goal of the game is to find the first integer moment of time when the plane contains a rectangle of a non-zero area which sides are fully covered by some babies. A side may be covered by multiple babies. More formally, each point of each side of the rectangle should be covered by at least one baby of any color. At that, you must assume that the babies are closed segments, that is, they contain their endpoints.You are given the positions of all babies β€” help Inna and Dima to find the required moment of time.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 2000).Next n lines contain the coordinates of the blue babies. The i-th line contains integers xi, yi β€” a baby's coordinates. Next m lines contain the coordinates of m red babies in the similar form.All coordinates of the input don't exceed 106 in their absolute value. Note that all babies stand in distinct points.OutputIn the single line print a single integer β€” the answer to the problem.If the rectangle never appears on the plane, print "Poor Sereja!" without the quotes.ExamplesInput2 22 25 53 75 1Output3Input3 22 23 26 24 25 2Output1
Input2 22 25 53 75 1
Output3
6 seconds
256 megabytes
['binary search', 'data structures', 'dsu', 'geometry', 'implementation', '*2600']
D. Inna and Sequence time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima's spent much time thinking what present to give to Inna and gave her an empty sequence w. Now they want to fill sequence w with numbers zero and one. For that, they decided to play an amusing game. Before the game begins, Dima chooses m integers a1, a2, ..., am (1 ≀ a1 < a2 < ... < am). Then Inna and Dima start playing, that is, adding numbers to sequence w. Each new number they choose is added to the end of the sequence. At some moments of time Dima feels that the game is going to end too soon (and he wants to play with Inna as long as possible), so he hits a table hard with his fist. At that the a1-th, a2-th, a3-th, ..., ak-th numbers from the beginning simultaneously fall out of the sequence (the sequence gets k numbers less). Here k is such maximum number that value ak doesn't exceed the current length of the sequence. If number a1 is larger than the current length of w, then nothing falls out of the sequence.You are given the chronological sequence of events in the game. Each event is either adding a number to the end of sequence w or Dima's hit on the table. Calculate the sequence w after all these events happen.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 106) showing how many events took place and how many numbers Dima chose.The next line contains m distinct integers ai (1 ≀ ai ≀ 106) sorted in the increasing order. Next n lines describe the events in the chronological order. Each line contains a single integer: -1, 0 or 1. Number -1 means that Dima hits the table. Number 0 means that Inna and Dima add number 0 to the end of the sequence. Number 1 means that Inna and Dima add number 1 to the end of the sequence.OutputIn a single line print a sequence of numbers 0 and 1 β€” the elements of the sequence after all events happen. Print the elements of the sequence in the order from the beginning to the end of the sequence.If after all events the sequence ends up empty, print "Poor stack!".ExamplesInput10 31 3 6-11100-101-11Output011Input2 111-1OutputPoor stack!
Input10 31 3 6-11100-101-11
Output011
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'trees', '*2000']
C. Inna and Dimatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInna and Dima bought a table of size n × m in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A".Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows: initially, Inna chooses some cell of the table where letter "D" is written; then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name; Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D". Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.InputThe first line of the input contains two integers n and m (1 ≀ n, m ≀ 103). Then follow n lines that describe Inna and Dima's table. Each line contains m characters. Each character is one of the following four characters: "D", "I", "M", "A". Note that it is not guaranteed that the table contains at least one letter "D".OutputIf Inna cannot go through name DIMA once, print on a single line "Poor Dima!" without the quotes. If there is the infinite number of names DIMA Inna can go through, print "Poor Inna!" without the quotes. Otherwise print a single integer β€” the maximum number of times Inna can go through name DIMA.ExamplesInput1 2DIOutputPoor Dima!Input2 2MAIDOutputPoor Inna!Input5 5DIMADDIMAIDIMAMDDMAAAAMIDOutput4NoteNotes to the samples:In the first test sample, Inna cannot go through name DIMA a single time.In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner.In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times.
Input1 2DI
OutputPoor Dima!
1 second
256 megabytes
['dfs and similar', 'dp', 'graphs', 'implementation', '*1900']
B. Inna and Ninetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9.For instance, Inna can alter number 14545181 like this: 14545181 → 1945181 → 194519 → 19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine.Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.InputThe first line of the input contains integer a (1 ≀ a ≀ 10100000). Number a doesn't have any zeroes.OutputIn a single line print a single integer β€” the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 263 - 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.ExamplesInput369727Output2Input123456789987654321Output1Input1Output1NoteNotes to the samplesIn the first sample Inna can get the following numbers: 369727 → 99727 → 9997, 369727 → 99727 → 9979.In the second sample, Inna can act like this: 123456789987654321 → 12396789987654321 → 1239678998769321.
Input369727
Output2
1 second
256 megabytes
['combinatorics', 'greedy', '*1500']
A. Inna and Pink Ponytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n × m chessboard, a very tasty candy and two numbers a and b.Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types: move the candy from position (x, y) on the board to position (x - a, y - b); move the candy from position (x, y) on the board to position (x + a, y - b); move the candy from position (x, y) on the board to position (x - a, y + b); move the candy from position (x, y) on the board to position (x + a, y + b). Naturally, Dima doesn't allow to move the candy beyond the chessboard borders.Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (i, j) to one of the chessboard corners. Help them cope with the task! InputThe first line of the input contains six integers n, m, i, j, a, b (1 ≀ n, m ≀ 106;Β 1 ≀ i ≀ n;Β 1 ≀ j ≀ m;Β 1 ≀ a, b ≀ 106).You can assume that the chessboard rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. Position (i, j) in the statement is a chessboard cell on the intersection of the i-th row and the j-th column. You can consider that the corners are: (1, m), (n, 1), (n, m), (1, 1).OutputIn a single line print a single integer β€” the minimum number of moves needed to get the candy.If Inna and the pony cannot get the candy playing by Dima's rules, print on a single line "Poor Inna and pony!" without the quotes.ExamplesInput5 7 1 3 2 2Output2Input5 5 2 3 1 1OutputPoor Inna and pony!NoteNote to sample 1:Inna and the pony can move the candy to position (1 + 2, 3 + 2) = (3, 5), from there they can move it to positions (3 - 2, 5 + 2) = (1, 7) and (3 + 2, 5 + 2) = (5, 7). These positions correspond to the corner squares of the chess board. Thus, the answer to the test sample equals two.
Input5 7 1 3 2 2
Output2
1 second
256 megabytes
['greedy', 'implementation', '*2000']
B. Making Sequences is Funtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe'll define S(n) for positive integer n as follows: the number of the n's digits in the decimal base. For example, S(893) = 3, S(114514) = 6.You want to make a consecutive integer sequence starting from number m (m, m + 1, ...). But you need to pay S(n)Β·k to add the number n to the sequence.You can spend a cost up to w, and you want to make the sequence as long as possible. Write a program that tells sequence's maximum length.InputThe first line contains three integers w (1 ≀ w ≀ 1016), m (1 ≀ m ≀ 1016), k (1 ≀ k ≀ 109).Please, do not write 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.OutputThe first line should contain a single integer β€” the answer to the problem.ExamplesInput9 1 1Output9Input77 7 7Output7Input114 5 14Output6Input1 1 2Output0
Input9 1 1
Output9
2 seconds
256 megabytes
['binary search', 'implementation', 'math', '*1600']
A. Collecting Beats is Funtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCucumber boy is fan of Kyubeat, a famous music game.Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel.Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail.You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.InputThe first line contains a single integer k (1 ≀ k ≀ 5) β€” the number of panels Cucumber boy can press with his one hand.Next 4 lines contain 4 characters each (digits from 1 to 9, or period) β€” table of panels. If a digit i was written on the panel, it means the boy has to press that panel in time i. If period was written on the panel, he doesn't have to press that panel.OutputOutput "YES" (without quotes), if he is able to press all the panels in perfect timing. If not, output "NO" (without quotes).ExamplesInput1.135124734685789OutputYESInput5..1.1111..1...1.OutputYESInput1....12.1.2...2..OutputNONoteIn the third sample boy cannot press all panels in perfect timing. He can press all the panels in timing in time 1, but he cannot press the panels in time 2 in timing with his two hands.
Input1.135124734685789
OutputYES
1 second
256 megabytes
['implementation', '*900']
E. Drawing Circles is Funtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are a set of points S on the plane. This set doesn't contain the origin O(0, 0), and for each two distinct points in the set A and B, the triangle OAB has strictly positive area.Consider a set of pairs of points (P1, P2), (P3, P4), ..., (P2k - 1, P2k). We'll call the set good if and only if: k β‰₯ 2. All Pi are distinct, and each Pi is an element of S. For any two pairs (P2i - 1, P2i) and (P2j - 1, P2j), the circumcircles of triangles OP2i - 1P2j - 1 and OP2iP2j have a single common point, and the circumcircle of triangles OP2i - 1P2j and OP2iP2j - 1 have a single common point. Calculate the number of good sets of pairs modulo 1000000007 (109 + 7).InputThe first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of points in S. Each of the next n lines contains four integers ai, bi, ci, di (0 ≀ |ai|, |ci| ≀ 50;Β 1 ≀ bi, di ≀ 50;Β (ai, ci) ≠ (0, 0)). These integers represent a point .No two points coincide.OutputPrint a single integer β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput10-46 46 0 360 20 -24 48-50 50 -49 49-20 50 8 40-15 30 14 284 10 -4 56 15 8 10-20 50 -3 154 34 -16 3416 34 2 17Output2Input1030 30 -26 260 15 -36 36-28 28 -34 3410 10 0 4-8 20 40 509 45 12 306 15 7 3536 45 -8 20-16 34 -4 344 34 8 17Output4Input100 20 38 38-30 30 -13 13-11 11 16 1630 30 0 376 30 -4 106 15 12 15-4 5 -10 25-16 20 4 108 17 -2 1716 34 2 17Output10
Input10-46 46 0 360 20 -24 48-50 50 -49 49-20 50 8 40-15 30 14 284 10 -4 56 15 8 10-20 50 -3 154 34 -16 3416 34 2 17
Output2
3 seconds
256 megabytes
['combinatorics', 'geometry', '*3000']
D. Choosing Subtree is Funtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a tree consisting of n vertices. The vertices are numbered from 1 to n.Let's define the length of an interval [l, r] as the value r - l + 1. The score of a subtree of this tree is the maximum length of such an interval [l, r] that, the vertices with numbers l, l + 1, ..., r belong to the subtree.Considering all subtrees of the tree whose size is at most k, return the maximum score of the subtree. Note, that in this problem tree is not rooted, so a subtree β€” is an arbitrary connected subgraph of the tree.InputThere are two integers in the first line, n and k (1 ≀ k ≀ n ≀ 105). Each of the next n - 1 lines contains integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi). That means ai and bi are connected by a tree edge.It is guaranteed that the input represents a tree.OutputOutput should contain a single integer β€” the maximum possible score.ExamplesInput10 64 1010 62 99 68 57 14 77 31 8Output3Input16 713 1112 112 148 69 1516 115 146 154 311 1515 1410 13 1414 71 7Output6NoteFor the first case, there is some subtree whose size is at most 6, including 3 consecutive numbers of vertices. For example, the subtree that consists of {1, 3, 4, 5, 7, 8} or of {1, 4, 6, 7, 8, 10} includes 3 consecutive numbers of vertices. But there is no subtree whose size is at most 6, which includes 4 or more consecutive numbers of vertices.
Input10 64 1010 62 99 68 57 14 77 31 8
Output3
5 seconds
256 megabytes
['binary search', 'data structures', 'dfs and similar', 'trees', 'two pointers', '*2600']
C. Watching Fireworks is Funtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA festival will be held in a town's main street. There are n sections in the main street. The sections are numbered 1 through n from left to right. The distance between each adjacent sections is 1.In the festival m fireworks will be launched. The i-th (1 ≀ i ≀ m) launching is on time ti at section ai. If you are at section x (1 ≀ x ≀ n) at the time of i-th launching, you'll gain happiness value bi - |ai - x| (note that the happiness value might be a negative value).You can move up to d length units in a unit time interval, but it's prohibited to go out of the main street. Also you can be in an arbitrary section at initial time moment (time equals to 1), and want to maximize the sum of happiness that can be gained from watching fireworks. Find the maximum total happiness.Note that two or more fireworks can be launched at the same time.InputThe first line contains three integers n, m, d (1 ≀ n ≀ 150000;Β 1 ≀ m ≀ 300;Β 1 ≀ d ≀ n).Each of the next m lines contains integers ai, bi, ti (1 ≀ ai ≀ n;Β 1 ≀ bi ≀ 109;Β 1 ≀ ti ≀ 109). The i-th line contains description of the i-th launching.It is guaranteed that the condition ti ≀ ti + 1 (1 ≀ i < m) will be satisfied.OutputPrint a single integer β€” the maximum sum of happiness that you can gain from watching all the fireworks.Please, do not write 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.ExamplesInput50 3 149 1 126 1 46 1 10Output-31Input10 2 11 1000 49 1000 4Output1992
Input50 3 149 1 126 1 46 1 10
Output-31
4 seconds
256 megabytes
['data structures', 'dp', 'math', '*2100']
B. Counting Rectangles is Funtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an n × m rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the i-th row and the j-th column as (i, j).Let's define a "rectangle" as four integers a, b, c, d (1 ≀ a ≀ c ≀ n;Β 1 ≀ b ≀ d ≀ m). Rectangle denotes a set of cells of the grid {(x, y)Β :  a ≀ x ≀ c, b ≀ y ≀ d}. Let's define a "good rectangle" as a rectangle that includes only the cells with zeros.You should answer the following q queries: calculate the number of good rectangles all of which cells are in the given rectangle.InputThere are three integers in the first line: n, m and q (1 ≀ n, m ≀ 40, 1 ≀ q ≀ 3Β·105). Each of the next n lines contains m characters β€” the grid. Consider grid rows are numbered from top to bottom, and grid columns are numbered from left to right. Both columns and rows are numbered starting from 1. Each of the next q lines contains a query β€” four integers that describe the current rectangle, a, b, c, d (1 ≀ a ≀ c ≀ n;Β 1 ≀ b ≀ d ≀ m).OutputFor each query output an answer β€” a single integer in a separate line.ExamplesInput5 5 500101000000000101000000011 2 2 44 5 4 51 2 5 22 2 4 54 2 5 3Output1017345Input4 7 500001000000010001100000000001 7 2 73 1 3 12 3 4 51 2 2 72 2 4 7Output31162752NoteFor the first example, there is a 5 × 5 rectangular grid, and the first, the second, and the third queries are represented in the following image. For the first query, there are 10 good rectangles, five 1 × 1, two 2 × 1, two 1 × 2, and one 1 × 3. For the second query, there is only one 1 × 1 good rectangle. For the third query, there are 7 good rectangles, four 1 × 1, two 2 × 1, and one 3 × 1.
Input5 5 500101000000000101000000011 2 2 44 5 4 51 2 5 22 2 4 54 2 5 3
Output1017345
4 seconds
256 megabytes
['brute force', 'divide and conquer', 'dp', '*1900']
A. Counting Kangaroos is Funtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held.Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos.The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.InputThe first line contains a single integer β€” n (1 ≀ n ≀ 5Β·105). Each of the next n lines contains an integer si β€” the size of the i-th kangaroo (1 ≀ si ≀ 105).OutputOutput a single integer β€” the optimal number of visible kangaroos.ExamplesInput825769842Output5Input891626583Output5
Input825769842
Output5
1 second
256 megabytes
['binary search', 'greedy', 'sortings', 'two pointers', '*1600']
E. Subway Innovationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland is going through tough times β€” the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!The President of Berland was forced to leave only k of the currently existing n subway stations.The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train.Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.InputThe first line of the input contains integer n (3 ≀ n ≀ 3Β·105) β€” the number of the stations before the innovation. The second line contains the coordinates of the stations x1, x2, ..., xn ( - 108 ≀ xi ≀ 108). The third line contains integer k (2 ≀ k ≀ n - 1) β€” the number of stations after the innovation.The station coordinates are distinct and not necessarily sorted.OutputPrint a sequence of k distinct integers t1, t2, ..., tk (1 ≀ tj ≀ n) β€” the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them.ExamplesInput31 100 1012Output2 3 NoteIn the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way.
Input31 100 1012
Output2 3
2 seconds
256 megabytes
['greedy', 'math', 'two pointers', '*2000']
D. Vesselstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a system of n vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to n, in the order from the highest to the lowest, the volume of the i-th vessel is ai liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the i-th vessel goes to the (i + 1)-th one. The liquid that overflows from the n-th vessel spills on the floor.Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: Add xi liters of water to the pi-th vessel; Print the number of liters of water in the ki-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.InputThe first line contains integer n β€” the number of vessels (1 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ..., an β€” the vessels' capacities (1 ≀ ai ≀ 109). The vessels' capacities do not necessarily increase from the top vessels to the bottom ones (see the second sample). The third line contains integer m β€” the number of queries (1 ≀ m ≀ 2Β·105). Each of the next m lines contains the description of one query. The query of the first type is represented as "1Β piΒ xi", the query of the second type is represented as "2Β ki" (1 ≀ pi ≀ n, 1 ≀ xi ≀ 109, 1 ≀ ki ≀ n).OutputFor each query, print on a single line the number of liters of water in the corresponding vessel.ExamplesInput25 1061 1 42 11 2 51 1 42 12 2Output458Input35 10 861 1 122 21 1 61 3 22 22 3Output7105
Input25 1061 1 42 11 2 51 1 42 12 2
Output458
2 seconds
256 megabytes
['data structures', 'dsu', 'implementation', 'trees', '*1800']
C. Hamburgerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (bread), 'S' (sausage) ΠΈ 'C' (cheese). The ingredients in the recipe go from bottom to top, for example, recipe "Π’SCBS" represents the hamburger where the ingredients go from bottom to top as bread, sausage, cheese, bread and sausage again.Polycarpus has nb pieces of bread, ns pieces of sausage and nc pieces of cheese in the kitchen. Besides, the shop nearby has all three ingredients, the prices are pb rubles for a piece of bread, ps for a piece of sausage and pc for a piece of cheese.Polycarpus has r rubles and he is ready to shop on them. What maximum number of hamburgers can he cook? You can assume that Polycarpus cannot break or slice any of the pieces of bread, sausage or cheese. Besides, the shop has an unlimited number of pieces of each ingredient.InputThe first line of the input contains a non-empty string that describes the recipe of "Le Hamburger de Polycarpus". The length of the string doesn't exceed 100, the string contains only letters 'B' (uppercase English B), 'S' (uppercase English S) and 'C' (uppercase English C).The second line contains three integers nb, ns, nc (1 ≀ nb, ns, nc ≀ 100) β€” the number of the pieces of bread, sausage and cheese on Polycarpus' kitchen. The third line contains three integers pb, ps, pc (1 ≀ pb, ps, pc ≀ 100) β€” the price of one piece of bread, sausage and cheese in the shop. Finally, the fourth line contains integer r (1 ≀ r ≀ 1012) β€” the number of rubles Polycarpus has.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.OutputPrint the maximum number of hamburgers Polycarpus can make. If he can't make any hamburger, print 0.ExamplesInputBBBSSC6 4 11 2 34Output2InputBBC1 10 11 10 121Output7InputBSC1 1 11 1 31000000000000Output200000000001
InputBBBSSC6 4 11 2 34
Output2
1 second
256 megabytes
['binary search', 'brute force', '*1600']
B. Fox Dividing Cheesetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox, how are you going to do that?", the curious bears asked. "It's easy", said the fox. "If the mass of a certain piece is divisible by two, then I can eat exactly a half of the piece. If the mass of a certain piece is divisible by three, then I can eat exactly two-thirds, and if the mass is divisible by five, then I can eat four-fifths. I'll eat a little here and there and make the pieces equal". The little bears realize that the fox's proposal contains a catch. But at the same time they realize that they can not make the two pieces equal themselves. So they agreed to her proposal, but on one condition: the fox should make the pieces equal as quickly as possible. Find the minimum number of operations the fox needs to make pieces equal.InputThe first line contains two space-separated integers a and b (1 ≀ a, b ≀ 109). OutputIf the fox is lying to the little bears and it is impossible to make the pieces equal, print -1. Otherwise, print the required minimum number of operations. If the pieces of the cheese are initially equal, the required number is 0.ExamplesInput15 20Output3Input14 8Output-1Input6 6Output0
Input15 20
Output3
1 second
256 megabytes
['math', 'number theory', '*1300']
A. K-Periodic Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2.Array a is k-period if its length is divisible by k and there is such array b of length k, that a is represented by array b written exactly times consecutively. In other words, array a is k-periodic, if it has period of length k.For example, any array is n-periodic, where n is the array length. Array [2, 1, 2, 1, 2, 1] is at the same time 2-periodic and 6-periodic and array [1, 2, 1, 1, 2, 1, 1, 2, 1] is at the same time 3-periodic and 9-periodic.For the given array a, consisting only of numbers one and two, find the minimum number of elements to change to make the array k-periodic. If the array already is k-periodic, then the required value equals 0.InputThe first line of the input contains a pair of integers n, k (1 ≀ k ≀ n ≀ 100), where n is the length of the array and the value n is divisible by k. The second line contains the sequence of elements of the given array a1, a2, ..., an (1 ≀ ai ≀ 2), ai is the i-th element of the array.OutputPrint the minimum number of array elements we need to change to make the array k-periodic. If the array already is k-periodic, then print 0.ExamplesInput6 22 1 2 2 2 1Output1Input8 41 1 2 1 1 1 2 1Output0Input9 32 1 1 1 2 1 1 1 2Output3NoteIn the first sample it is enough to change the fourth element from 2 to 1, then the array changes to [2, 1, 2, 1, 2, 1].In the second sample, the given array already is 4-periodic.In the third sample it is enough to replace each occurrence of number two by number one. In this case the array will look as [1, 1, 1, 1, 1, 1, 1, 1, 1] β€” this array is simultaneously 1-, 3- and 9-periodic.
Input6 22 1 2 2 2 1
Output1
1 second
256 megabytes
['greedy', 'implementation', 'math', '*1000']
E. Summer Readingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt school Vasya got an impressive list of summer reading books. Unlike other modern schoolchildren, Vasya loves reading, so he read some book each day of the summer.As Vasya was reading books, he was making notes in the Reader's Diary. Each day he wrote the orderal number of the book he was reading. The books in the list are numbered starting from 1 and Vasya was reading them in the order they go in the list. Vasya never reads a new book until he finishes reading the previous one. Unfortunately, Vasya wasn't accurate and some days he forgot to note the number of the book and the notes for those days remained empty.As Vasya knows that the literature teacher will want to check the Reader's Diary, so he needs to restore the lost records. Help him do it and fill all the blanks. Vasya is sure that he spends at least two and at most five days for each book. Vasya finished reading all the books he had started. Assume that the reading list contained many books. So many, in fact, that it is impossible to read all of them in a summer. If there are multiple valid ways to restore the diary records, Vasya prefers the one that shows the maximum number of read books.InputThe first line contains integer n β€” the number of summer days (2 ≀ n ≀ 2Β·105). The second line contains n integers a1, a2, ... an β€” the records in the diary in the order they were written (0 ≀ ai ≀ 105). If Vasya forgot to write the number of the book on the i-th day, then ai equals 0. OutputIf it is impossible to correctly fill the blanks in the diary (the diary may contain mistakes initially), print "-1". Otherwise, print in the first line the maximum number of books Vasya could have read in the summer if we stick to the diary. In the second line print n integers β€” the diary with correctly inserted records. If there are multiple optimal solutions, you can print any of them.ExamplesInput70 1 0 0 0 3 0Output31 1 2 2 3 3 3 Input80 0 0 0 0 0 0 0Output41 1 2 2 3 3 4 4 Input40 0 1 0Output11 1 1 1 Input40 0 0 3Output-1
Input70 1 0 0 0 3 0
Output31 1 2 2 3 3 3
1 second
256 megabytes
['dp', 'greedy', '*2500']
D. Broken Monitortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInnocentius has a problem β€” his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus.Innocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as "the game is good for the imagination and attention".Help Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that: the frame's width is 1 pixel, the frame doesn't go beyond the borders of the screen, all white pixels of the monitor are located on the frame, of all frames that satisfy the previous three conditions, the required frame must have the smallest size. Formally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is d = 3, then it consists of 8 pixels, if its size is d = 2, then it contains 4 pixels and if d = 1, then the frame is reduced to a single pixel.InputThe first line contains the resolution of the monitor as a pair of integers n, m (1 ≀ n, m ≀ 2000). The next n lines contain exactly m characters each β€” the state of the monitor pixels at the moment of the game. Character "." (period, ASCII code 46) corresponds to the black pixel, and character "w" (lowercase English letter w) corresponds to the white pixel. It is guaranteed that at least one pixel of the monitor is white.OutputPrint the monitor screen. Represent the sought frame by characters "+" (the "plus" character). The pixels that has become white during the game mustn't be changed. Print them as "w". If there are multiple possible ways to position the frame of the minimum size, print any of them.If the required frame doesn't exist, then print a single line containing number -1.ExamplesInput4 8..w..w....................w..w..Output..w++w....+..+....+..+....w++w..Input5 6.......w............w.........Output......+w+...+.+...++w.........Input2 4.....w..Output.....w..Input2 6w..w.w...w..Output-1NoteIn the first sample the required size of the optimal frame equals 4. In the second sample the size of the optimal frame equals 3. In the third sample, the size of the optimal frame is 1. In the fourth sample, the required frame doesn't exist.
Input4 8..w..w....................w..w..
Output..w++w....+..+....+..+....w++w..
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'implementation', '*2100']
C. Mittenstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA Christmas party in city S. had n children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to m, and the children are numbered from 1 to n. Then the i-th child has both mittens of color ci.The Party had Santa Claus ('Father Frost' in Russian), his granddaughter Snow Girl, the children danced around the richly decorated Christmas tree. In fact, everything was so bright and diverse that the children wanted to wear mittens of distinct colors. The children decided to swap the mittens so that each of them got one left and one right mitten in the end, and these two mittens were of distinct colors. All mittens are of the same size and fit all the children.The children started exchanging the mittens haphazardly, but they couldn't reach the situation when each child has a pair of mittens of distinct colors. Vasily Petrov, the dad of one of the children, noted that in the general case the children's idea may turn out impossible. Besides, he is a mathematician and he came up with such scheme of distributing mittens that the number of children that have distinct-colored mittens was maximum. You task is to repeat his discovery. Note that the left and right mittens are different: each child must end up with one left and one right mitten.InputThe first line contains two integers n and m β€” the number of the children and the number of possible mitten colors (1 ≀ n ≀ 5000, 1 ≀ m ≀ 100). The second line contains n integers c1, c2, ... cn, where ci is the color of the mittens of the i-th child (1 ≀ ci ≀ m).OutputIn the first line, print the maximum number of children who can end up with a distinct-colored pair of mittens. In the next n lines print the way the mittens can be distributed in this case. On the i-th of these lines print two space-separated integers: the color of the left and the color of the right mitten the i-th child will get. If there are multiple solutions, you can print any of them.ExamplesInput6 31 3 2 2 1 1Output62 11 22 11 31 23 1Input4 21 2 1 1Output21 21 12 11 1
Input6 31 3 2 2 1 1
Output62 11 22 11 31 23 1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*1800']
B. Berland Bingotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLately, a national version of a bingo game has become very popular in Berland. There are n players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the i-th player contains mi numbers.During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct.You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.InputThe first line of the input contains integer n (1 ≀ n ≀ 100) β€” the number of the players. Then follow n lines, each line describes a player's card. The line that describes a card starts from integer mi (1 ≀ mi ≀ 100) that shows how many numbers the i-th player's card has. Then follows a sequence of integers ai, 1, ai, 2, ..., ai, mi (1 ≀ ai, k ≀ 100) β€” the numbers on the i-th player's card. The numbers in the lines are separated by single spaces.It is guaranteed that all the numbers on each card are distinct.OutputPrint n lines, the i-th line must contain word "YES" (without the quotes), if the i-th player can win, and "NO" (without the quotes) otherwise.ExamplesInput31 13 2 4 12 10 11OutputYESNOYESInput21 11 1OutputNONO
Input31 13 2 4 12 10 11
OutputYESNOYES
1 second
256 megabytes
['implementation', '*1300']
A. Rook, Bishop and Kingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8 × 8 table. A field is represented by a pair of integers (r, c) β€” the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules: A rook moves any number of fields horizontally or vertically. A bishop moves any number of fields diagonally. A king moves one field in any direction β€” horizontally, vertically or diagonally. The pieces move like that Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field (r1, c1) to field (r2, c2)? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.InputThe input contains four integers r1, c1, r2, c2 (1 ≀ r1, c1, r2, c2 ≀ 8) β€” the coordinates of the starting and the final field. The starting field doesn't coincide with the final one.You can assume that the chessboard rows are numbered from top to bottom 1 through 8, and the columns are numbered from left to right 1 through 8.OutputPrint three space-separated integers: the minimum number of moves the rook, the bishop and the king (in this order) is needed to move from field (r1, c1) to field (r2, c2). If a piece cannot make such a move, print a 0 instead of the corresponding number.ExamplesInput4 3 1 6Output2 1 3Input5 5 5 6Output1 0 1
Input4 3 1 6
Output2 1 3
1 second
256 megabytes
['graphs', 'math', 'shortest paths', '*1100']
E. Valera and Queriestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputValera loves segments. He has recently come up with one interesting problem.The Ox axis of coordinates has n segments, the i-th segment starts in position li and ends in position ri (we will mark it as [li, ri]). Your task is to process m queries, each consists of number cnti and a set of cnti coordinates of points located on the Ox axis. The answer to the query is the number of segments, such that each of them contains at least one point from the query. Segment [l, r] contains point q, if l ≀ q ≀ r.Valera found the solution of this problem too difficult. So he asked you to help him. Help Valera. InputThe first line contains two integers n, m (1 ≀ n, m ≀ 3Β·105) β€” the number of segments on the axis of coordinates and the number of queries. Next n lines contain the descriptions of the segments. The i-th line contains two positive integers li, ri (1 ≀ li ≀ ri ≀ 106) β€” the borders of the i-th segment.Next m lines contain the description of the queries, one per line. Each line starts from integer cnti (1 ≀ cnti ≀ 3Β·105) β€” the number of points in the i-th query. Then the line contains cnti distinct positive integers p1, p2, ..., pcnti (1 ≀ p1 < p2 < ... < pcnti ≀ 106) β€” the coordinates of points in the i-th query.It is guaranteed that the total number of points in all queries doesn't exceed 3Β·105. OutputPrint m non-negative integers, where the i-th number is the response to the i-th query.ExamplesInput3 31 34 56 73 1 4 72 4 51 8Output310
Input3 31 34 56 73 1 4 72 4 51 8
Output310
2 seconds
512 megabytes
['binary search', 'data structures', '*2200']
D. Valera and Foolstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne fine morning, n fools lined up in a row. After that, they numbered each other with numbers from 1 to n, inclusive. Each fool got a unique number. The fools decided not to change their numbers before the end of the fun.Every fool has exactly k bullets and a pistol. In addition, the fool number i has probability of pi (in percent) that he kills the fool he shoots at.The fools decided to have several rounds of the fun. Each round of the fun looks like this: each currently living fool shoots at another living fool with the smallest number (a fool is not stupid enough to shoot at himself). All shots of the round are perfomed at one time (simultaneously). If there is exactly one living fool, he does not shoot.Let's define a situation as the set of numbers of all the living fools at the some time. We say that a situation is possible if for some integer number j (0 ≀ j ≀ k) there is a nonzero probability that after j rounds of the fun this situation will occur.Valera knows numbers p1, p2, ..., pn and k. Help Valera determine the number of distinct possible situations.InputThe first line contains two integers n, k (1 ≀ n, k ≀ 3000) β€” the initial number of fools and the number of bullets for each fool.The second line contains n integers p1, p2, ..., pn (0 ≀ pi ≀ 100) β€” the given probabilities (in percent).OutputPrint a single number β€” the answer to the problem.ExamplesInput3 350 50 50Output7Input1 1100Output1Input2 1100 100Output2Input3 30 0 0Output1NoteIn the first sample, any situation is possible, except for situation {1, 2}.In the second sample there is exactly one fool, so he does not make shots.In the third sample the possible situations are {1, 2} (after zero rounds) and the "empty" situation {} (after one round).In the fourth sample, the only possible situation is {1, 2, 3}.
Input3 350 50 50
Output7
1 second
256 megabytes
['dfs and similar', 'dp', 'graphs', 'shortest paths', '*2200']
C. Valera and Electionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe city Valera lives in is going to hold elections to the city Parliament.The city has n districts and n - 1 bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from 1 to n, inclusive. Furthermore, for each road the residents decided if it is the problem road or not. A problem road is a road that needs to be repaired.There are n candidates running the elections. Let's enumerate all candidates in some way by integers from 1 to n, inclusive. If the candidate number i will be elected in the city Parliament, he will perform exactly one promise β€” to repair all problem roads on the way from the i-th district to the district 1, where the city Parliament is located.Help Valera and determine the subset of candidates such that if all candidates from the subset will be elected to the city Parliament, all problem roads in the city will be repaired. If there are several such subsets, you should choose the subset consisting of the minimum number of candidates.InputThe first line contains a single integer n (2 ≀ n ≀ 105) β€” the number of districts in the city.Then n - 1 lines follow. Each line contains the description of a city road as three positive integers xi, yi, ti (1 ≀ xi, yi ≀ n, 1 ≀ ti ≀ 2) β€” the districts connected by the i-th bidirectional road and the road type. If ti equals to one, then the i-th road isn't the problem road; if ti equals to two, then the i-th road is the problem road.It's guaranteed that the graph structure of the city is a tree.OutputIn the first line print a single non-negative number k β€” the minimum size of the required subset of candidates. Then on the second line print k space-separated integers a1, a2, ... ak β€” the numbers of the candidates that form the required subset. If there are multiple solutions, you are allowed to print any of them.ExamplesInput51 2 22 3 23 4 24 5 2Output15 Input51 2 12 3 22 4 14 5 1Output13 Input51 2 21 3 21 4 21 5 2Output45 4 3 2
Input51 2 22 3 23 4 24 5 2
Output15
1 second
256 megabytes
['dfs and similar', 'graphs', 'trees', '*1600']
B. Valera and Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.After the contest was over, Valera was interested in results. He found out that: each student in the team scored at least l points and at most r points; in total, all members of the team scored exactly sall points; the total score of the k members of the team who scored the most points is equal to exactly sk; more formally, if a1, a2, ..., an is the sequence of points earned by the team of students in the non-increasing order (a1 β‰₯ a2 β‰₯ ... β‰₯ an), then sk = a1 + a2 + ... + ak. However, Valera did not find out exactly how many points each of n students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.InputThe first line of the input contains exactly six integers n, k, l, r, sall, sk (1 ≀ n, k, l, r ≀ 1000; l ≀ r; k ≀ n; 1 ≀ sk ≀ sall ≀ 106).It's guaranteed that the input is such that the answer exists.OutputPrint exactly n integers a1, a2, ..., an β€” the number of points each student scored. If there are multiple solutions, you can print any of them. You can print the distribution of points in any order. ExamplesInput5 3 1 3 13 9Output2 3 2 3 3 Input5 3 1 3 15 9Output3 3 3 3 3
Input5 3 1 3 13 9
Output2 3 2 3 3
1 second
256 megabytes
['constructive algorithms', 'implementation', 'math', '*1400']
A. Valera and Platestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.InputThe first line of the input contains three integers n, m, k (1 ≀ n, m, k ≀ 1000)Β β€” the number of the planned days, the number of clean bowls and the number of clean plates.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish. OutputPrint a single integer β€” the minimum number of times Valera will need to wash a plate/bowl.ExamplesInput3 1 11 2 1Output1Input4 3 11 1 1 1Output1Input3 1 22 2 2Output0Input8 2 21 2 1 2 1 2 1 2Output4NoteIn the first sample Valera will wash a bowl only on the third day, so the answer is one.In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.
Input3 1 11 2 1
Output1
1 second
256 megabytes
['greedy', 'implementation', '*900']
B. Sereja and Suffixestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≀ li ≀ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ..., n. Formally, he want to find the number of distinct numbers among ali, ali + 1, ..., an.?Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each li.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 105). The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” the array elements.Next m lines contain integers l1, l2, ..., lm. The i-th line contains integer li (1 ≀ li ≀ n).OutputPrint m lines β€” on the i-th line print the answer to the number li.ExamplesInput10 101 2 3 4 1 2 3 4 100000 9999912345678910Output6666654321
Input10 101 2 3 4 1 2 3 4 100000 9999912345678910
Output6666654321
1 second
256 megabytes
['data structures', 'dp', '*1100']
A. Sereja and Coat Racktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja owns a restaurant for n people. The restaurant hall has a coat rack with n hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the i-th hook costs ai rubles. Only one person can hang clothes on one hook.Tonight Sereja expects m guests in the restaurant. Naturally, each guest wants to hang his clothes on an available hook with minimum price (if there are multiple such hooks, he chooses any of them). However if the moment a guest arrives the rack has no available hooks, Sereja must pay a d ruble fine to the guest. Help Sereja find out the profit in rubles (possibly negative) that he will get tonight. You can assume that before the guests arrive, all hooks on the rack are available, all guests come at different time, nobody besides the m guests is visiting Sereja's restaurant tonight.InputThe first line contains two integers n and d (1 ≀ n, d ≀ 100). The next line contains integers a1, a2, ..., an (1 ≀ ai ≀ 100). The third line contains integer m (1 ≀ m ≀ 100).OutputIn a single line print a single integer β€” the answer to the problem.ExamplesInput2 12 12Output3Input2 12 110Output-5NoteIn the first test both hooks will be used, so Sereja gets 1 + 2 = 3 rubles.In the second test both hooks will be used but Sereja pays a fine 8 times, so the answer is 3 - 8 =  - 5.
Input2 12 12
Output3
1 second
256 megabytes
['implementation', '*1000']
E. Sereja and Intervalstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja is interested in intervals of numbers, so he has prepared a problem about intervals for you. An interval of numbers is a pair of integers [l, r] (1 ≀ l ≀ r ≀ m). Interval [l1, r1] belongs to interval [l2, r2] if the following condition is met: l2 ≀ l1 ≀ r1 ≀ r2.Sereja wants to write out a sequence of n intervals [l1, r1], [l2, r2], ..., [ln, rn] on a piece of paper. At that, no interval in the sequence can belong to some other interval of the sequence. Also, Sereja loves number x very much and he wants some (at least one) interval in the sequence to have li = x. Sereja wonders, how many distinct ways to write such intervals are there?Help Sereja and find the required number of ways modulo 1000000007 (109 + 7).Two ways are considered distinct if there is such j (1 ≀ j ≀ n), that the j-th intervals in two corresponding sequences are not equal.InputThe first line contains integers n, m, x (1 ≀ nΒ·m ≀ 100000, 1 ≀ x ≀ m) β€” the number of segments in the sequence, the constraints on the numbers in segments and Sereja's favourite number.OutputIn a single line print the answer modulo 1000000007 (109 + 7).ExamplesInput1 1 1Output1Input3 5 1Output240Input2 3 3Output6NoteIn third example next sequences will be correct: {[1, 1], [3, 3]}, {[1, 2], [3, 3]}, {[2, 2], [3, 3]}, {[3, 3], [1, 1]}, {[3, 3], [2, 2]}, {[3, 3], [1, 2]}.
Input1 1 1
Output1
1 second
256 megabytes
['combinatorics', 'dp', '*2700']
D. Sereja and Setstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja has m non-empty sets of integers A1, A2, ..., Am. What a lucky coincidence! The given sets are a partition of the set of all integers from 1 to n. In other words, for any integer v (1 ≀ v ≀ n) there is exactly one set At such that . Also Sereja has integer d.Sereja decided to choose some sets from the sets he has. Let's suppose that i1, i2, ..., ik (1 ≀ i1 < i2 < ... < ik ≀ m) are indexes of the chosen sets. Then let's define an array of integers b, sorted in ascending order, as a union of the chosen sets, that is, . We'll represent the element with number j in this array (in ascending order) as bj. Sereja considers his choice of sets correct, if the following conditions are met:b1 ≀ d;Β bi + 1 - bi ≀ dΒ (1 ≀ i < |b|);Β n - d + 1 ≀ b|b|.Sereja wants to know what is the minimum number of sets (k) that he can choose so that his choice will be correct. Help him with that.InputThe first line contains integers n, m, d (1 ≀ d ≀ n ≀ 105, 1 ≀ m ≀ 20). The next m lines contain sets. The first number in the i-th line is si (1 ≀ si ≀ n). This number denotes the size of the i-th set. Then the line contains si distinct integers from 1 to n β€” set Ai.It is guaranteed that the sets form partition of all integers from 1 to n.OutputIn a single line print the answer to the problem β€” the minimum value k at the right choice.ExamplesInput3 2 21 22 1 3Output1Input5 1 15 4 5 3 2 1Output1Input7 3 14 1 3 5 72 2 61 4Output3
Input3 2 21 22 1 3
Output1
1 second
256 megabytes
['bitmasks', 'dfs and similar', '*2400']
C. Sereja and the Arrangement of Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an array consisting of n integer numbers a1, a2, ..., an, beautiful if it has the following property: consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a; for each pair x, y must exist some position j (1 ≀ j < n), such that at least one of the two conditions are met, either aj = x, aj + 1 = y, or aj = y, aj + 1 = x. Sereja wants to build a beautiful array a, consisting of n integers. But not everything is so easy, Sereja's friend Dima has m coupons, each contains two integers qi, wi. Coupon i costs wi and allows you to use as many numbers qi as you want when constructing the array a. Values qi are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array a of n elements. After that he takes wi rubles from Sereja for each qi, which occurs in the array a. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay.Help Sereja, find the maximum amount of money he can pay to Dima.InputThe first line contains two integers n and m (1 ≀ n ≀ 2Β·106, 1 ≀ m ≀ 105). Next m lines contain pairs of integers. The i-th line contains numbers qi, wi (1 ≀ qi, wi ≀ 105).It is guaranteed that all qi are distinct.OutputIn a single line print maximum amount of money (in rubles) Sereja can pay.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.ExamplesInput5 21 22 3Output5Input100 31 22 13 1Output4Input1 21 12 100Output100NoteIn the first sample Sereja can pay 5 rubles, for example, if Dima constructs the following array: [1, 2, 1, 2, 2]. There are another optimal arrays for this test.In the third sample Sereja can pay 100 rubles, if Dima constructs the following array: [2].
Input5 21 22 3
Output5
1 second
256 megabytes
['graphs', 'greedy', 'sortings', '*2000']
B. Sereja ans Anagramstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n;Β q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.Sereja needs to rush to the gym, so he asked to find all the described positions of q.InputThe first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109).OutputIn the first line print the number of valid qs. In the second line, print the valid values in the increasing order.ExamplesInput5 3 11 2 3 2 11 2 3Output21 3Input6 3 21 3 2 2 3 11 2 3Output21 2
Input5 3 11 2 3 2 11 2 3
Output21 3
1 second
256 megabytes
['binary search', 'data structures', '*1900']
A. Sereja and Algorithm time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≀ li ≀ ri ≀ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not.InputThe first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'.The second line contains integer m (1 ≀ m ≀ 105) β€” the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≀ li ≀ ri ≀ n).OutputFor each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise.ExamplesInputzyxxxxxxyyz55 51 31 111 43 6OutputYESYESNOYESNONoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly.
Inputzyxxxxxxyyz55 51 31 111 43 6
OutputYESYESNOYESNO
1 second
256 megabytes
['data structures', 'implementation', '*1500']
E. Dima and Magic Guitartime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with n strings and m frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the i-th string holding it on the j-th fret the guitar produces a note, let's denote it as aij. We know that Dima's guitar can produce k distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that aij = apq at (i, j) ≠ (p, q).Dima has already written a song β€” a sequence of s notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein).We'll represent a way to play a song as a sequence of pairs (xi, yi) (1 ≀ i ≀ s), such that the xi-th string on the yi-th fret produces the i-th note from the song. The complexity of moving between pairs (x1, y1) and (x2, y2) equals + . The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs.Help Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!InputThe first line of the input contains four integers n, m, k and s (1 ≀ n, m ≀ 2000, 1 ≀ k ≀ 9, 2 ≀ s ≀ 105). Then follow n lines, each containing m integers aij (1 ≀ aij ≀ k). The number in the i-th row and the j-th column (aij) means a note that the guitar produces on the i-th string and the j-th fret.The last line of the input contains s integers qi (1 ≀ qi ≀ k) β€” the sequence of notes of the song.OutputIn a single line print a single number β€” the maximum possible complexity of the song.ExamplesInput4 6 5 73 1 2 2 3 13 2 2 2 5 54 2 2 2 5 33 2 2 1 4 32 3 1 4 1 5 1Output8Input4 4 9 54 7 9 51 2 1 78 3 4 95 7 7 27 1 9 2 5Output4
Input4 6 5 73 1 2 2 3 13 2 2 2 5 54 2 2 2 5 33 2 2 1 4 32 3 1 4 1 5 1
Output8
3 seconds
256 megabytes
['brute force', 'implementation', 'math', '*2200']
D. Dima and Trap Graphtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal...Dima constructed a trap graph. He shouted: "Hey Seryozha, have a look at my cool graph!" to get his roommate interested and kicked him into the first node.A trap graph is an undirected graph consisting of n nodes and m edges. For edge number k, Dima denoted a range of integers from lk to rk (lk ≀ rk). In order to get out of the trap graph, Seryozha initially (before starting his movements) should pick some integer (let's call it x), then Seryozha must go some way from the starting node with number 1 to the final node with number n. At that, Seryozha can go along edge k only if lk ≀ x ≀ rk.Seryozha is a mathematician. He defined the loyalty of some path from the 1-st node to the n-th one as the number of integers x, such that if he initially chooses one of them, he passes the whole path. Help Seryozha find the path of maximum loyalty and return to his room as quickly as possible!InputThe first line of the input contains two integers n and m (2 ≀ n ≀ 103, 0 ≀ m ≀ 3Β·103). Then follow m lines describing the edges. Each line contains four integers ak, bk, lk and rk (1 ≀ ak, bk ≀ n, 1 ≀ lk ≀ rk ≀ 106). The numbers mean that in the trap graph the k-th edge connects nodes ak and bk, this edge corresponds to the range of integers from lk to rk.Note that the given graph can have loops and multiple edges.OutputIn a single line of the output print an integer β€” the maximum loyalty among all paths from the first node to the n-th one. If such paths do not exist or the maximum loyalty equals 0, print in a single line "Nice work, Dima!" without the quotes.ExamplesInput4 41 2 1 102 4 3 51 3 1 52 4 2 7Output6Input5 61 2 1 102 5 11 201 4 2 51 3 10 113 4 12 100004 5 6 6OutputNice work, Dima!NoteExplanation of the first example.Overall, we have 2 ways to get from node 1 to node 4: first you must go along the edge 1-2 with range [1-10], then along one of the two edges 2-4. One of them contains range [3-5], that is, we can pass through with numbers 3, 4, 5. So the loyalty of such path is 3.If we go along edge 2-4 with range [2-7], then we can pass through with numbers 2, 3, 4, 5, 6, 7. The loyalty is 6. That is the answer.The edge 1-2 have no influence on the answer because its range includes both ranges of the following edges.
Input4 41 2 1 102 4 3 51 3 1 52 4 2 7
Output6
3 seconds
256 megabytes
['binary search', 'data structures', 'dfs and similar', 'dsu', 'shortest paths', 'two pointers', '*2000']
C. Dima and Saladtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something. Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal k. In other words, , where aj is the taste of the j-th chosen fruit and bj is its calories.Inna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem β€” now the happiness of a young couple is in your hands!Inna loves Dima very much so she wants to make the salad from at least one fruit.InputThe first line of the input contains two integers n, k (1 ≀ n ≀ 100, 1 ≀ k ≀ 10). The second line of the input contains n integers a1, a2, ..., an (1 ≀ ai ≀ 100) β€” the fruits' tastes. The third line of the input contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 100) β€” the fruits' calories. Fruit number i has taste ai and calories bi.OutputIf there is no way Inna can choose the fruits for the salad, print in the single line number -1. Otherwise, print a single integer β€” the maximum possible sum of the taste values of the chosen fruits.ExamplesInput3 210 8 12 7 1Output18Input5 34 4 4 4 42 2 2 2 2Output-1NoteIn the first test sample we can get the total taste of the fruits equal to 18 if we choose fruit number 1 and fruit number 2, then the total calories will equal 9. The condition fulfills, that's exactly what Inna wants.In the second test sample we cannot choose the fruits so as to follow Inna's principle.
Input3 210 8 12 7 1
Output18
1 second
256 megabytes
['dp', '*1900']
B. Dima and To-do Listtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.InputThe first line of the input contains two integers n, kΒ (1 ≀ k ≀ n ≀ 105). The second line contains n integers a1, a2, ..., anΒ (1 ≀ ai ≀ 103), where ai is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task.It is guaranteed that n is divisible by k.OutputIn a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.ExamplesInput6 23 2 1 6 5 4Output1Input10 51 3 5 7 9 9 4 1 8 5Output3NoteExplanation of the first example.If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12. Explanation of the second example.In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3.
Input6 23 2 1 6 5 4
Output1
1 second
256 megabytes
['brute force', 'implementation', '*1200']
A. Dima and Guardstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards...There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can bribe a guard by a chocolate bar or a box of juice. For each guard you know the minimum price of the chocolate bar she can accept as a gift and the minimum price of the box of juice she can accept as a gift. If a chocolate bar for some guard costs less than the minimum chocolate bar price for this guard is, or if a box of juice for some guard costs less than the minimum box of juice price for this guard is, then the guard doesn't accept such a gift.In order to pass through a guardpost, one needs to bribe both guards.The shop has an unlimited amount of juice and chocolate of any price starting with 1. Dima wants to choose some guardpost, buy one gift for each guard from the guardpost and spend exactly n rubles on it.Help him choose a post through which he can safely sneak Inna or otherwise say that this is impossible. Mind you, Inna would be very sorry to hear that!InputThe first line of the input contains integer nΒ (1 ≀ n ≀ 105) β€” the money Dima wants to spend. Then follow four lines describing the guardposts. Each line contains four integers a, b, c, dΒ (1 ≀ a, b, c, d ≀ 105) β€” the minimum price of the chocolate and the minimum price of the juice for the first guard and the minimum price of the chocolate and the minimum price of the juice for the second guard, correspondingly.OutputIn a single line of the output print three space-separated integers: the number of the guardpost, the cost of the first present and the cost of the second present. If there is no guardpost Dima can sneak Inna through at such conditions, print -1 in a single line. The guardposts are numbered from 1 to 4 according to the order given in the input.If there are multiple solutions, you can print any of them.ExamplesInput105 6 5 66 6 7 75 8 6 69 9 9 9Output1 5 5Input106 6 6 67 7 7 74 4 4 48 8 8 8Output3 4 6Input53 3 3 33 3 3 33 3 3 33 3 3 3Output-1NoteExplanation of the first example.The only way to spend 10 rubles to buy the gifts that won't be less than the minimum prices is to buy two 5 ruble chocolates to both guards from the first guardpost.Explanation of the second example.Dima needs 12 rubles for the first guardpost, 14 for the second one, 16 for the fourth one. So the only guardpost we can sneak through is the third one. So, Dima can buy 4 ruble chocolate for the first guard and 6 ruble juice of the second guard.
Input105 6 5 66 6 7 75 8 6 69 9 9 9
Output1 5 5
1 second
256 megabytes
['implementation', '*1100']
B. The Fibonacci Segmenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have array a1, a2, ..., an. Segment [l, r] (1 ≀ l ≀ r ≀ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 ≀ i ≀ r).Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]).Your task is to find a good segment of the maximum length in array a. Note that a segment of length 1 or 2 is always good.InputThe first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of elements in the array. The second line contains integers: a1, a2, ..., an (0 ≀ ai ≀ 109).OutputPrint the length of the longest good segment in array a.ExamplesInput101 2 3 5 8 13 21 34 55 89Output10Input51 1 1 1 1Output2
Input101 2 3 5 8 13 21 34 55 89
Output10
1 second
256 megabytes
['implementation', '*1100']
A. Good Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).InputThe first line contains integers n and k (1 ≀ n ≀ 100, 0 ≀ k ≀ 9). The i-th of the following n lines contains integer ai without leading zeroes (1 ≀ ai ≀ 109).OutputPrint a single integer β€” the number of k-good numbers in a.ExamplesInput10 61234560123456012345601234560123456012345601234560123456012345601234560Output10Input2 1110Output1
Input10 61234560123456012345601234560123456012345601234560123456012345601234560
Output10
1 second
256 megabytes
['implementation', '*1100']
E. Empty Rectanglestime limit per test12 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou've got an n × m table (n rows and m columns), each cell of the table contains a "0" or a "1".Your task is to calculate the number of rectangles with the sides that are parallel to the sides of the table and go along the cell borders, such that the number one occurs exactly k times in the rectangle. InputThe first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 2500, 0 ≀ k ≀ 6) β€” the sizes of the table and the required number of numbers one.Next n lines each contains m characters "0" or "1". The i-th character of the j-th line corresponds to the character that is in the j-th row and the i-th column of the table.OutputPrint a single number β€” the number of rectangles that contain exactly k numbers one.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.ExamplesInput3 3 2101000101Output8Input5 5 10000000000001000000000000Output81Input5 5 60101010101010101010101010Output12Input3 3 0001010000Output15Input4 4 00000010100000000Output52
Input3 3 2101000101
Output8
12 seconds
512 megabytes
['divide and conquer', 'two pointers', '*3000']
D. Ghdtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Doe offered his sister Jane Doe find the gcd of some set of numbers a.Gcd is a positive integer g, such that all number from the set are evenly divisible by g and there isn't such g' (g' > g), that all numbers of the set are evenly divisible by g'.Unfortunately Jane couldn't cope with the task and John offered her to find the ghd of the same subset of numbers.Ghd is a positive integer g, such that at least half of numbers from the set are evenly divisible by g and there isn't such g' (g' > g) that at least half of the numbers from the set are evenly divisible by g'.Jane coped with the task for two hours. Please try it, too.InputThe first line contains an integer n (1 ≀ n ≀ 106) showing how many numbers are in set a. The second line contains space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 1012). Please note, that given set can contain equal numbers.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the %I64d specifier.OutputPrint a single integer g β€” the Ghd of set a.ExamplesInput66 2 3 4 5 6Output3Input55 5 6 10 15Output5
Input66 2 3 4 5 6
Output3
4 seconds
256 megabytes
['brute force', 'math', 'probabilities', '*2900']
C. Beautiful Settime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe'll call a set of positive integers a beautiful if the following condition fulfills: for any prime p, if , then . In other words, if one number from the set is divisible by prime p, then at least half of numbers from the set is divisible by p.Your task is to find any beautiful set, where the number of elements is equal to k and each element doesn't exceed 2k2.InputThe first line contains integer k (10 ≀ k ≀ 5000) that shows how many numbers the required beautiful set should have.OutputIn the first line print k space-separated integers that are a beautiful set. If there are multiple such sets, you are allowed to print any of them.ExamplesInput10Output16 18 24 27 36 48 54 72 108 144
Input10
Output16 18 24 27 36 48 54 72 108 144
1 second
256 megabytes
['brute force', 'number theory', '*2300']
B. Free Markettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Doe has recently found a "Free Market" in his city β€” that is the place where you can exchange some of your possessions for other things for free. John knows that his city has n items in total (each item is unique). You can bring any number of items to the market and exchange them for any other one. Note that each item is one of a kind and that means that you cannot exchange set {a, b} for set {v, a}. However, you can always exchange set x for any set y, unless there is item p, such that p occurs in x and p occurs in y.For each item, John knows its value ci. John's sense of justice doesn't let him exchange a set of items x for a set of items y, if s(x) + d < s(y) (s(x) is the total price of items in the set x). During one day John can exchange only one set of items for something else. Initially, he has no items. John wants to get a set of items with the maximum total price. Find the cost of such set and the minimum number of days John can get it in. InputThe first line contains two space-separated integers n, d (1 ≀ n ≀ 50, 1 ≀ d ≀ 104) β€” the number of items on the market and John's sense of justice value, correspondingly. The second line contains n space-separated integers ci (1 ≀ ci ≀ 104).OutputPrint two space-separated integers: the maximum possible price in the set of items John can get and the minimum number of days needed to get such set.ExamplesInput3 21 3 10Output4 3Input3 51 2 3Output6 2Input10 1000010000 9999 1 10000 10000 10000 1 2 3 4Output50010 6NoteIn the first sample John can act like this: Take the first item (1 - 0 ≀ 2). Exchange the first item for the second one (3 - 1 ≀ 2). Take the first item (1 - 0 ≀ 2).
Input3 21 3 10
Output4 3
1 second
256 megabytes
['dp', 'greedy', '*2200']
A. Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string of decimal digits s. Let's define bij = siΒ·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≀ y, z ≀ t). The elements of the rectangle are all cells (i, j) such that x ≀ i ≀ y, z ≀ j ≀ t.InputThe first line contains integer a (0 ≀ a ≀ 109), the second line contains a string of decimal integers s (1 ≀ |s| ≀ 4000).OutputPrint a single integer β€” the answer to a problem.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.ExamplesInput1012345Output6Input16439873893693495623498263984765Output40
Input1012345
Output6
1 second
256 megabytes
['combinatorics', 'data structures', 'implementation', '*1600']
E. Two Circlestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's assume that we are given an n × m table filled by integers. We'll mark a cell in the i-th row and j-th column as (i, j). Thus, (1, 1) is the upper left cell of the table and (n, m) is the lower right cell. We'll assume that a circle of radius r with the center in cell (i0, j0) is a set of such cells (i, j) that . We'll consider only the circles that do not go beyond the limits of the table, that is, for which r + 1 ≀ i0 ≀ n - r and r + 1 ≀ j0 ≀ m - r. A circle of radius 3 with the center at (4, 5). Find two such non-intersecting circles of the given radius r that the sum of numbers in the cells that belong to these circles is maximum. Two circles intersect if there is a cell that belongs to both circles. As there can be more than one way to choose a pair of circles with the maximum sum, we will also be interested in the number of such pairs. Calculate the number of unordered pairs of circles, for instance, a pair of circles of radius 2 with centers at (3, 4) and (7, 7) is the same pair as the pair of circles of radius 2 with centers at (7, 7) and (3, 4). InputThe first line contains three integers n, m and r (2 ≀ n, m ≀ 500, r β‰₯ 0). Each of the following n lines contains m integers from 1 to 1000 each β€” the elements of the table. The rows of the table are listed from top to bottom at the elements in the rows are listed from left to right. It is guaranteed that there is at least one circle of radius r, not going beyond the table limits. OutputPrint two integers β€” the maximum sum of numbers in the cells that are located into two non-intersecting circles and the number of pairs of non-intersecting circles with the maximum sum. If there isn't a single pair of non-intersecting circles, print 0 0.ExamplesInput2 2 01 22 4Output6 2Input5 6 14 2 1 3 2 62 3 2 4 7 25 2 2 1 1 31 4 3 3 6 45 1 4 2 3 2Output34 3Input3 3 11 2 34 5 67 8 9Output0 0
Input2 2 01 22 4
Output6 2
4 seconds
256 megabytes
['brute force', 'data structures', 'implementation', '*2500']
D. Renting Bikestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA group of n schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them.The renting site offered them m bikes. The renting price is different for different bikes, renting the j-th bike costs pj rubles.In total, the boys' shared budget is a rubles. Besides, each of them has his own personal money, the i-th boy has bi personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike.Each boy can rent at most one bike, one cannot give his bike to somebody else.What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?InputThe first line of the input contains three integers n, m and a (1 ≀ n, m ≀ 105; 0 ≀ a ≀ 109). The second line contains the sequence of integers b1, b2, ..., bn (1 ≀ bi ≀ 104), where bi is the amount of the i-th boy's personal money. The third line contains the sequence of integers p1, p2, ..., pm (1 ≀ pj ≀ 109), where pj is the price for renting the j-th bike.OutputPrint two integers r and s, where r is the maximum number of schoolboys that can rent a bike and s is the minimum total personal money needed to rent r bikes. If the schoolchildren cannot rent any bikes, then r = s = 0.ExamplesInput2 2 105 57 6Output2 3Input4 5 28 1 1 26 3 7 5 2Output3 8NoteIn the first sample both schoolchildren can rent a bike. For instance, they can split the shared budget in half (5 rubles each). In this case one of them will have to pay 1 ruble from the personal money and the other one will have to pay 2 rubles from the personal money. In total, they spend 3 rubles of their personal money. This way of distribution of money minimizes the amount of spent personal money.
Input2 2 105 57 6
Output2 3
1 second
256 megabytes
['binary search', 'greedy', '*1800']
C. Fixing Typostime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMany modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.InputThe single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.OutputPrint such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters.If there are multiple solutions, print any of them.ExamplesInputhellooOutputhelloInputwoooooowOutputwoowNoteThe second valid answer to the test from the statement is "heloo".
Inputhelloo
Outputhello
1 second
256 megabytes
['greedy', 'implementation', '*1400']
B. Fencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights. Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1] Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly k consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such k consecutive planks that the sum of their heights is minimal possible.Write the program that finds the indexes of k consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).InputThe first line of the input contains integers n and k (1 ≀ n ≀ 1.5Β·105, 1 ≀ k ≀ n) β€” the number of planks in the fence and the width of the hole for the piano. The second line contains the sequence of integers h1, h2, ..., hn (1 ≀ hi ≀ 100), where hi is the height of the i-th plank of the fence.OutputPrint such integer j that the sum of the heights of planks j, j + 1, ..., j + k - 1 is the minimum possible. If there are multiple such j's, print any of them.ExamplesInput7 31 2 6 1 1 7 1Output3NoteIn the sample, your task is to find three consecutive planks with the minimum sum of heights. In the given case three planks with indexes 3, 4 and 5 have the required attribute, their total height is 8.
Input7 31 2 6 1 1 7 1
Output3
1 second
256 megabytes
['brute force', 'dp', '*1100']
A. Sorobantime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban β€” an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about them. Let's have a look at the Soroban's construction. Soroban consists of some number of rods, each rod contains five beads. We will assume that the rods are horizontal lines. One bead on each rod (the leftmost one) is divided from the others by a bar (the reckoning bar). This single bead is called go-dama and four others are ichi-damas. Each rod is responsible for representing a single digit from 0 to 9. We can obtain the value of a digit by following simple algorithm: Set the value of a digit equal to 0. If the go-dama is shifted to the right, add 5. Add the number of ichi-damas shifted to the left. Thus, the upper rod on the picture shows digit 0, the middle one shows digit 2 and the lower one shows 7. We will consider the top rod to represent the last decimal digit of a number, so the picture shows number 720.Write the program that prints the way Soroban shows the given number n.InputThe first line contains a single integer n (0 ≀ n < 109).OutputPrint the description of the decimal digits of number n from the last one to the first one (as mentioned on the picture in the statement), one per line. Print the beads as large English letters 'O', rod pieces as character '-' and the reckoning bar as '|'. Print as many rods, as many digits are in the decimal representation of number n without leading zeroes. We can assume that number 0 has no leading zeroes.ExamplesInput2OutputO-|OO-OOInput13OutputO-|OOO-OO-|O-OOOInput720OutputO-|-OOOOO-|OO-OO-O|OO-OO
Input2
OutputO-|OO-OO
1 second
256 megabytes
['implementation', '*800']
E. Petya and Pipestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA little boy Petya dreams of growing up and becoming the Head Berland Plumber. He is thinking of the problems he will have to solve in the future. Unfortunately, Petya is too inexperienced, so you are about to solve one of such problems for Petya, the one he's the most interested in.The Berland capital has n water tanks numbered from 1 to n. These tanks are connected by unidirectional pipes in some manner. Any pair of water tanks is connected by at most one pipe in each direction. Each pipe has a strictly positive integer width. Width determines the number of liters of water per a unit of time this pipe can transport. The water goes to the city from the main water tank (its number is 1). The water must go through some pipe path and get to the sewer tank with cleaning system (its number is n). Petya wants to increase the width of some subset of pipes by at most k units in total so that the width of each pipe remains integer. Help him determine the maximum amount of water that can be transmitted per a unit of time from the main tank to the sewer tank after such operation is completed.InputThe first line contains two space-separated integers n and k (2 ≀ n ≀ 50, 0 ≀ k ≀ 1000). Then follow n lines, each line contains n integers separated by single spaces. The i + 1-th row and j-th column contain number cij β€” the width of the pipe that goes from tank i to tank j (0 ≀ cij ≀ 106, cii = 0). If cij = 0, then there is no pipe from tank i to tank j.OutputPrint a single integer β€” the maximum amount of water that can be transmitted from the main tank to the sewer tank per a unit of time.ExamplesInput5 70 1 0 2 00 0 4 10 00 0 0 0 50 0 0 0 100 0 0 0 0Output10Input5 100 1 0 0 00 0 2 0 00 0 0 3 00 0 0 0 4100 0 0 0 0Output5NoteIn the first test Petya can increase width of the pipe that goes from the 1st to the 2nd water tank by 7 units.In the second test Petya can increase width of the pipe that goes from the 1st to the 2nd water tank by 4 units, from the 2nd to the 3rd water tank by 3 units, from the 3rd to the 4th water tank by 2 units and from the 4th to 5th water tank by 1 unit.
Input5 70 1 0 2 00 0 4 10 00 0 0 0 50 0 0 0 100 0 0 0 0
Output10
1 second
256 megabytes
['flows', 'graphs', 'shortest paths', '*2300']
D. Fools and Foolproof Roadstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou must have heard all about the Foolland on your Geography lessons. Specifically, you must know that federal structure of this country has been the same for many centuries. The country consists of n cities, some pairs of cities are connected by bidirectional roads, each road is described by its length li.The fools lived in their land joyfully, but a recent revolution changed the king. Now the king is Vasily the Bear. Vasily divided the country cities into regions, so that any two cities of the same region have a path along the roads between them and any two cities of different regions don't have such path. Then Vasily decided to upgrade the road network and construct exactly p new roads in the country. Constructing a road goes like this: We choose a pair of distinct cities u, v that will be connected by a new road (at that, it is possible that there already is a road between these cities). We define the length of the new road: if cities u, v belong to distinct regions, then the length is calculated as min(109, S + 1) (S β€” the total length of all roads that exist in the linked regions), otherwise we assume that the length equals 1000. We build a road of the specified length between the chosen cities. If the new road connects two distinct regions, after construction of the road these regions are combined into one new region. Vasily wants the road constructing process to result in the country that consists exactly of q regions. Your task is to come up with such road constructing plan for Vasily that it meets the requirement and minimizes the total length of the built roads.InputThe first line contains four integers n (1 ≀ n ≀ 105), m (0 ≀ m ≀ 105), p (0 ≀ p ≀ 105), q (1 ≀ q ≀ n) β€” the number of cities in the Foolland, the number of existing roads, the number of roads that are planned to construct and the required number of regions.Next m lines describe the roads that exist by the moment upgrading of the roads begun. Each of these lines contains three integers xi, yi, li: xi, yi β€” the numbers of the cities connected by this road (1 ≀ xi, yi ≀ n, xi ≠ yi), li β€” length of the road (1 ≀ li ≀ 109). Note that one pair of cities can be connected with multiple roads.OutputIf constructing the roads in the required way is impossible, print a single string "NO" (without the quotes). Otherwise, in the first line print word "YES" (without the quotes), and in the next p lines print the road construction plan. Each line of the plan must consist of two distinct integers, giving the numbers of the cities connected by a road. The road must occur in the plan in the order they need to be constructed. If there are multiple optimal solutions, you can print any of them.ExamplesInput9 6 2 21 2 23 2 14 6 201 3 87 8 35 7 2OutputYES9 51 9Input2 0 1 2OutputNOInput2 0 0 2OutputYESNoteConsider the first sample. Before the reform the Foolland consists of four regions. The first region includes cities 1, 2, 3, the second region has cities 4 and 6, the third region has cities 5, 7, 8, the fourth region has city 9. The total length of the roads in these cities is 11, 20, 5 and 0, correspondingly. According to the plan, we first build the road of length 6 between cities 5 and 9, then the road of length 23 between cities 1 and 9. Thus, the total length of the built roads equals 29.
Input9 6 2 21 2 23 2 14 6 201 3 87 8 35 7 2
OutputYES9 51 9
1 second
256 megabytes
['data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', '*2100']
C. Insertion Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decreasing order. for (int i = 1; i < n; i = i + 1){ int j = i; while (j > 0 && a[j] < a[j - 1]) { swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1] j = j - 1; }}Petya uses this algorithm only for sorting of arrays that are permutations of numbers from 0 to n - 1. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement.It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.InputThe first line contains a single integer n (2 ≀ n ≀ 5000) β€” the length of the permutation. The second line contains n different integers from 0 to n - 1, inclusive β€” the actual permutation.OutputPrint two integers: the minimum number of times the swap function is executed and the number of such pairs (i, j) that swapping the elements of the input permutation with indexes i and j leads to the minimum number of the executions.ExamplesInput54 0 3 1 2Output3 2Input51 2 3 4 0Output3 4NoteIn the first sample the appropriate pairs are (0, 3) and (0, 4). In the second sample the appropriate pairs are (0, 4), (1, 4), (2, 4) and (3, 4).
Input54 0 3 1 2
Output3 2
2 seconds
256 megabytes
['data structures', 'dp', 'implementation', 'math', '*1900']
B. Petya and Staircasestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle boy Petya loves stairs very much. But he is bored from simple going up and down them β€” he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.Now Petya is on the first stair of the staircase, consisting of n stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number n without touching a dirty stair once.One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.InputThe first line contains two integers n and m (1 ≀ n ≀ 109, 0 ≀ m ≀ 3000) β€” the number of stairs in the staircase and the number of dirty stairs, correspondingly. The second line contains m different space-separated integers d1, d2, ..., dm (1 ≀ di ≀ n) β€” the numbers of the dirty stairs (in an arbitrary order).OutputPrint "YES" if Petya can reach stair number n, stepping only on the clean stairs. Otherwise print "NO".ExamplesInput10 52 4 8 3 6OutputNOInput10 52 4 5 7 9OutputYES
Input10 52 4 8 3 6
OutputNO
1 second
256 megabytes
['implementation', 'sortings', '*1100']
A. Two Semiknights Meettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.InputThe first line contains number t (1 ≀ t ≀ 50) β€” the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.OutputFor each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.ExamplesInput2......................#.K..##..#.......#...##..#......#.K.........................#.......#..#....####.....##...............K#K#OutputYESNONoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.
Input2......................#.K..##..#.......#...##..#......#.K.........................#.......#..#....####.....##...............K#K#
OutputYESNO
1 second
256 megabytes
['greedy', 'math', '*1500']
B. Levko and Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLevko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n.Let’s assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1, p2, ... , pn is good if gcd(i, pi) > 1. Levko considers a permutation beautiful, if it has exactly k good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them.InputThe single line contains two integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ n).OutputIn a single line print either any beautiful permutation or -1, if such permutation doesn’t exist.If there are multiple suitable permutations, you are allowed to print any of them.ExamplesInput4 2Output2 4 3 1Input1 1Output-1NoteIn the first sample elements 4 and 3 are good because gcd(2, 4) = 2 > 1 and gcd(3, 3) = 3 > 1. Elements 2 and 1 are not good because gcd(1, 2) = 1 and gcd(4, 1) = 1. As there are exactly 2 good elements, the permutation is beautiful.The second sample has no beautiful permutations.
Input4 2
Output2 4 3 1
1 second
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1200']
A. Levko and Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLevko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them. InputThe single line contains two integers, n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1000).OutputPrint any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value.If there are multiple suitable tables, you are allowed to print any of them.ExamplesInput2 4Output1 33 1Input4 7Output2 1 0 44 0 2 11 3 3 00 3 2 2NoteIn the first sample the sum in the first row is 1 + 3 = 4, in the second row β€” 3 + 1 = 4, in the first column β€” 1 + 3 = 4 and in the second column β€” 3 + 1 = 4. There are other beautiful tables for this sample.In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.
Input2 4
Output1 33 1
1 second
256 megabytes
['constructive algorithms', 'implementation', '*800']
E. Levko and Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLevko loves sports pathfinding competitions in his city very much. In order to boost his performance, Levko spends his spare time practicing. The practice is a game.The city consists of n intersections connected by m + k directed roads. Two or more roads can connect the same pair of intersections. Besides, there can be roads leading from an intersection to itself. Levko and Zenyk are playing a game. First Levko stands on intersection s1, and Zenyk stands on intersection s2. They both want to get to intersection f. The person who does it quicker wins. If they get there at the same time, the game ends with a draw. By agreement both players start simultaneously and move with the same speed.Levko wants to win very much. He knows the lengths of all the roads in the city. Also he knows that he can change the lengths of some roads (there are k such roads at all) if he pays the government. So, the government can change the length of the i-th road to any integer value in the segment [li, ri] (both borders inclusive). Levko wondered if he can reconstruct the roads so as to win the game and whether he can hope for the draw if he cannot win.You should consider that both players play optimally well. It is guaranteed that we can get from intersections s1 and s2 to intersection f. InputThe first line contains three integers n, m and k (1 ≀ n, m ≀ 104, 1 ≀ k ≀ 100). The second line contains three integers s1, s2 and f (1 ≀ s1, s2, f ≀ n).The next m lines contains the descriptions of the roads that cannot be changed by Levko. Each line contains three integers ai, bi and ci (1 ≀ ai, bi ≀ n, 1 ≀ ci ≀ 109), representing a road from intersection ai to intersection bi of length ci.The next k lines contains the descriptions of the roads that can be changed by Levko. Each line contains four integers ai, bi, li and ri (1 ≀ ai, bi ≀ n, 1 ≀ li ≀ ri ≀ 109), representing a road from intersection ai to intersection bi, Levko can set the road's length within limits [li, ri].Consider all intersections numbered from 1 to n. It is guaranteed that you can get from intersections s1 and s2 to intersection f.OutputIn the first line print string "WIN" (without the quotes) if Levko can win this game, string "DRAW" (without the quotes) if Levko can end the game with a draw and "LOSE" (without the quotes) if he loses for sure.If the answer is "WIN" or "DRAW", then print on the second line k space-separated integers β€” the length of the roads Levko sets in the order they occur in the input.ExamplesInput4 1 31 3 43 2 21 2 1 32 4 1 33 4 1 3OutputWIN1 1 3 Input4 1 31 3 43 2 21 2 1 32 4 1 33 4 1 2OutputDRAW1 1 2 Input5 4 21 2 51 3 31 4 42 3 22 4 33 5 1 54 5 4 7OutputLOSE
Input4 1 31 3 43 2 21 2 1 32 4 1 33 4 1 3
OutputWIN1 1 3
2 seconds
256 megabytes
['graphs', 'greedy', 'shortest paths', '*2800']
D. Levko and Setstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLevko loves all sorts of sets very much.Levko has two arrays of integers a1, a2, ... , an and b1, b2, ... , bm and a prime number p. Today he generates n sets. Let's describe the generation process for the i-th set: First it has a single number 1. Let's take any element c from this set. For all j (1 ≀ j ≀ m) if number (cΒ·aibj)Β modΒ p doesn't occur in the set, then add it to the set. Repeat step 2 as long as we can add at least one element to our set. Levko wonders, how many numbers belong to at least one set. That is, he wants to know what size is the union of n generated sets.InputThe first line contains three integers n, m and p (1 ≀ n ≀ 104, 1 ≀ m ≀ 105, 2 ≀ p ≀ 109), p is prime. The second line contains space-separated integers a1, a2, ... , an (1 ≀ ai < p). The third line contains space-separated integers b1, b2, ... , bm (1 ≀ bi ≀ 109).OutputThe single number β€” the size of the union of the sets.ExamplesInput1 1 725Output3Input1 2 722 4Output3Input2 1 71 62Output1Input2 1 71 65Output2
Input1 1 725
Output3
3 seconds
256 megabytes
['number theory', '*2600']
C. Levko and Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLevko loves strings of length n, consisting of lowercase English letters, very much. He has one such string s. For each string t of length n, Levko defines its beauty relative to s as the number of pairs of indexes i, j (1 ≀ i ≀ j ≀ n), such that substring t[i..j] is lexicographically larger than substring s[i..j].The boy wondered how many strings t are there, such that their beauty relative to s equals exactly k. Help him, find the remainder after division this number by 1000000007 (109 + 7).A substring s[i..j] of string s = s1s2... sn is string sisi  +  1... sj.String x  =  x1x2... xp is lexicographically larger than string y  =  y1y2... yp, if there is such number r (r < p), that x1  =  y1,  x2  =  y2,  ... ,  xr  =  yr and xr  +  1 > yr  +  1. The string characters are compared by their ASCII codes.InputThe first line contains two integers n and k (1 ≀ n ≀ 2000, 0 ≀ k ≀ 2000).The second line contains a non-empty string s of length n. String s consists only of lowercase English letters. OutputPrint a single number β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput2 2yzOutput26Input2 3yxOutput2Input4 7abcdOutput21962
Input2 2yz
Output26
1 second
256 megabytes
['combinatorics', 'dp', '*2500']
B. Levko and Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLevko has an array that consists of integers: a1, a2, ... , an. But he doesn’t like this array at all.Levko thinks that the beauty of the array a directly depends on value c(a), which can be calculated by the formula: The less value c(a) is, the more beautiful the array is.It’s time to change the world and Levko is going to change his array for the better. To be exact, Levko wants to change the values of at most k array elements (it is allowed to replace the values by any integers). Of course, the changes should make the array as beautiful as possible.Help Levko and calculate what minimum number c(a) he can reach.InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 2000). The second line contains space-separated integers a1, a2, ... , an ( - 109 ≀ ai ≀ 109).OutputA single number β€” the minimum value of c(a) Levko can get.ExamplesInput5 24 7 4 7 4Output0Input3 1-100 0 100Output100Input6 31 2 3 7 8 9Output1NoteIn the first sample Levko can change the second and fourth elements and get array: 4, 4, 4, 4, 4.In the third sample he can get array: 1, 2, 3, 4, 5, 6.
Input5 24 7 4 7 4
Output0
2 seconds
256 megabytes
['binary search', 'dp', '*2000']
A. Levko and Array Recoverytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLevko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types: Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j that meet the inequation li ≀ j ≀ ri. Find the maximum of elements from li to ri. That is, calculate the value . Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array a. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed 109 in their absolute value, so he asks you to find such an array.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 5000) β€” the size of the array and the number of operations in Levko's records, correspondingly.Next m lines describe the operations, the i-th line describes the i-th operation. The first integer in the i-th line is integer ti (1 ≀ ti ≀ 2) that describes the operation type. If ti = 1, then it is followed by three integers li, ri and di (1 ≀ li ≀ ri ≀ n,  - 104 ≀ di ≀ 104) β€” the description of the operation of the first type. If ti = 2, then it is followed by three integers li, ri and mi (1 ≀ li ≀ ri ≀ n,  - 5Β·107 ≀ mi ≀ 5Β·107) β€” the description of the operation of the second type.The operations are given in the order Levko performed them on his array.OutputIn the first line print "YES" (without the quotes), if the solution exists and "NO" (without the quotes) otherwise.If the solution exists, then on the second line print n integers a1, a2, ... , an (|ai| ≀ 109) β€” the recovered array.ExamplesInput4 51 2 3 12 1 2 82 3 4 71 1 3 32 3 4 8OutputYES4 7 4 7Input4 51 2 3 12 1 2 82 3 4 71 1 3 32 3 4 13OutputNO
Input4 51 2 3 12 1 2 82 3 4 71 1 3 32 3 4 8
OutputYES4 7 4 7
1 second
256 megabytes
['greedy', 'implementation', '*1700']
E. Neatnesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSimon loves neatness. So before he goes to bed, Simon wants to complete all chores in the house.Simon's house looks like a rectangular table consisting of n rows and n columns from above. All rows of the table are numbered from 1 to n from top to bottom. All columns of the table are numbered from 1 to n from left to right. Each cell of the table is a room. Pair (x, y) denotes the room, located at the intersection of the x-th row and the y-th column. For each room we know if the light is on or not there.Initially Simon is in room (x0, y0). He wants to turn off the lights in all the rooms in the house, and then return to room (x0, y0). Suppose that at the current moment Simon is in the room (x, y). To reach the desired result, he can perform the following steps: The format of the action is "1". The action is to turn on the light in room (x, y). Simon cannot do it if the room already has light on. The format of the action is "2". The action is to turn off the light in room (x, y). Simon cannot do it if the room already has light off. The format of the action is "dir" (dir is a character). The action is to move to a side-adjacent room in direction dir. The direction can be left, right, up or down (the corresponding dir is L, R, U or D). Additionally, Simon can move only if he see a light in the direction dir. More formally, if we represent the room, Simon wants to go, as (nx, ny), there shold be an integer k (k > 0), that room (x + (nx - x)k, y + (ny - y)k) has a light. Of course, Simon cannot move out of his house. Help Simon, find the sequence of actions that lets him achieve the desired result.InputThe first line contains three positive integers n, x0, y0 (2 ≀ n ≀ 500, 1 ≀ x0, y0 ≀ n).Next n lines contain the description of rooms in the house. The i-th line contains n space-separated integers ai1, ai2, ..., ain. If number aij equals zero, then room (i, j) has light off, and if number aij equals one, then room (i, j) has light on. It is guaranteed that at least one room has light on.OutputIf there is no desired sequence of actions, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes) and the description of the required sequence of actions as a string. Note that you do not have to minimize the length of the sequence of actions but you shouldn't use more than 3Β·106 actions.ExamplesInput3 1 11 0 00 1 01 0 0OutputYESD1R2L2D2UU2Input3 1 11 0 00 1 00 0 1OutputNO
Input3 1 11 0 00 1 01 0 0
OutputYESD1R2L2D2UU2
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', '*2400']
D. Pair of Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSimon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≀ l ≀ r ≀ n), such that the following conditions hold: there is integer j (l ≀ j ≀ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them.InputThe first line contains integer n (1 ≀ n ≀ 3Β·105).The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 106).OutputPrint two integers in the first line β€” the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order.ExamplesInput54 6 9 3 6Output1 32 Input51 3 5 7 9Output1 41 Input52 3 5 7 11Output5 01 2 3 4 5 NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5).
Input54 6 9 3 6
Output1 32
2 seconds
256 megabytes
['binary search', 'brute force', 'data structures', 'math', 'two pointers', '*2000']
C. Prime Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSimon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7).InputThe first line contains two positive integers n and x (1 ≀ n ≀ 105, 2 ≀ x ≀ 109) β€” the size of the array and the prime number.The second line contains n space-separated integers a1, a2, ..., an (0 ≀ a1 ≀ a2 ≀ ... ≀ an ≀ 109). OutputPrint a single number β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput2 22 2Output8Input3 31 2 3Output27Input2 229 29Output73741817Input4 50 0 0 0Output1NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13Β·27, 729 = 27Β·27.In the third sample the answer to the problem is 1073741824Β modΒ 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1.
Input2 22 2
Output8
1 second
256 megabytes
['math', 'number theory', '*1900']
B. Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation p is an ordered group of numbers p1,   p2,   ...,   pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1,   p2,   ...,   pn.Simon has a positive integer n and a non-negative integer k, such that 2k ≀ n. Help him find permutation a of length 2n, such that it meets this equation: .InputThe first line contains two integers n and k (1 ≀ n ≀ 50000, 0 ≀ 2k ≀ n).OutputPrint 2n integers a1, a2, ..., a2n β€” the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them.ExamplesInput1 0Output1 2Input2 1Output3 2 1 4Input4 0Output2 7 4 6 1 3 5 8NoteRecord |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0.In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2.In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
Input1 0
Output1 2
1 second
256 megabytes
['constructive algorithms', 'dp', 'math', '*1400']
A. Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSimon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns β€” from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≀ p ≀ max(x1, x2), min(y1, y2) ≀ q ≀ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.InputThe first line contains exactly two integers n, m (3 ≀ n, m ≀ 50).Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.OutputPrint a single number β€” the minimum number of operations Simon needs to carry out his idea.ExamplesInput3 30 0 00 1 00 0 0Output4Input4 30 0 00 0 11 0 00 0 0Output2NoteIn the first sample, the sequence of operations can be like this: For the first time you need to choose cell (2, 2) and corner (1, 1). For the second time you need to choose cell (2, 2) and corner (3, 3). For the third time you need to choose cell (2, 2) and corner (3, 1). For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this: For the first time you need to choose cell (3, 1) and corner (4, 3). For the second time you need to choose cell (2, 3) and corner (1, 1).
Input3 30 0 00 1 00 0 0
Output4
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1000']
E. Dima and Kickstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima is a good person. In fact, he's great. But all good things come to an end...Seryozha is going to kick Dima just few times.. For this reason he divides the room into unit squares. Now the room is a rectangle n × m consisting of unit squares.For the beginning, Seryozha put Dima in a center of some square. Then he started to kick Dima (it is known, that he kicks Dima at least once). Each time when Dima is kicked he flyes up and moves into one of four directions (up, left, right, down). On each move Dima passes k (k > 1) unit of the length in the corresponding direction. Seryozha is really kind, so he kicks Dima in such way that Dima never meets the walls (in other words, Dima never leave the room's space). Seryozha is also dynamic character so Dima never flies above the same segment, connecting a pair of adjacent squares, twice.Seryozha kicks Dima for a long time, but Dima is not vindictive β€” Dima writes. Dima marked all squares in which he was staying or above which he was flying. Thanks to kicks, Dima does not remember the k value, so he asks you to find all possible values which matches to the Dima's records.InputThe first line contains n and m (1 ≀ n, m ≀ 103) β€” size of the room.Next n lines goes, each contains m numbers aij β€” Dima's notes: aij = 1, if Dima was staying in the square (i, j) or was flying above it. Otherwise aij = 0.At least one aij equals 1.OutputIn a single line in accending order print all k (k > 1), which matches the Dima's notes. If there are no such k and Dima invented this story with kicks, print -1.ExamplesInput5 51 1 1 1 11 0 0 0 11 0 0 0 11 0 0 0 11 1 1 1 1Output2 4Input7 70 0 1 1 1 0 00 0 1 0 1 0 01 1 1 1 1 1 11 0 1 0 1 0 11 1 1 1 1 1 10 0 1 0 1 0 00 0 1 1 1 0 0Output2Input3 31 1 11 1 11 1 1Output-1Input4 41 1 1 10 0 0 00 0 0 00 0 0 0Output3Input5 50 0 1 0 00 0 1 0 01 1 1 1 10 0 1 0 00 0 1 0 0Output-1
Input5 51 1 1 1 11 0 0 0 11 0 0 0 11 0 0 0 11 1 1 1 1
Output2 4
2 seconds
256 megabytes
['brute force', 'dsu', 'graphs', 'implementation', '*2300']
D. Dima and Harestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)InputThe first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105.Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.OutputIn a single line, print the maximum possible total joy of the hares Inna can get by feeding them.ExamplesInput41 2 3 44 3 2 10 1 1 0Output13Input78 5 7 6 1 8 92 7 9 5 4 3 12 3 3 4 1 1 3Output44Input31 1 11 2 11 1 1Output4
Input41 2 3 44 3 2 10 1 1 0
Output13
2 seconds
256 megabytes
['dp', 'greedy', '*1800']
C. Dima and Containerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands: Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end. Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of Inna's commands. Then n lines follow, describing Inna's commands. Each line consists an integer: Integer a (1 ≀ a ≀ 105) means that Inna gives Dima a command to add number a into one of containers. Integer 0 shows that Inna asks Dima to make at most three extractions from different containers. OutputEach command of the input must correspond to one line of the output β€” Dima's action.For the command of the first type (adding) print one word that corresponds to Dima's choice: pushStack β€” add to the end of the stack; pushQueue β€” add to the end of the queue; pushFront β€” add to the beginning of the deck; pushBack β€” add to the end of the deck. For a command of the second type first print an integer k (0 ≀ k ≀ 3), that shows the number of extract operations, then print k words separated by space. The words can be: popStack β€” extract from the end of the stack; popQueue β€” extract from the beginning of the line; popFront β€” extract from the beginning from the deck; popBack β€” extract from the end of the deck. The printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers.The printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.ExamplesInput100101201230Output0pushStack1 popStackpushStackpushQueue2 popStack popQueuepushStackpushQueuepushFront3 popStack popQueue popFrontInput41230OutputpushStackpushQueuepushFront3 popStack popQueue popFront
Input100101201230
Output0pushStack1 popStackpushStackpushQueue2 popStack popQueuepushStackpushQueuepushFront3 popStack popQueue popFront
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*2000']
B. Dima and Text Messagestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSeryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105. The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.OutputIn a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.ExamplesInput3iloveyou<3i<3love<23you<3OutputyesInput7iamnotmaininthefamily<3i<>3am<3the<3<main<3in<3the<3><3family<3OutputnoNotePlease note that Dima got a good old kick in the pants for the second sample from the statement.
Input3iloveyou<3i<3love<23you<3
Outputyes
2 seconds
256 megabytes
['brute force', 'strings', '*1500']
A. Dima and Continuous Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them by semi-circus in a certain order: first connect the first point with the second one, then connect the second point with the third one, then the third one with the fourth one and so on to the n-th point. Two points with coordinates (x1, 0) and (x2, 0) should be connected by a semi-circle that passes above the abscissa axis with the diameter that coincides with the segment between points. Seryozha needs to find out if the line on the picture intersects itself. For clarifications, see the picture Seryozha showed to Dima (the left picture has self-intersections, the right picture doesn't have any). Seryozha is not a small boy, so the coordinates of the points can be rather large. Help Dima cope with the problem.InputThe first line contains a single integer n (1 ≀ n ≀ 103). The second line contains n distinct integers x1, x2, ..., xn ( - 106 ≀ xi ≀ 106) β€” the i-th point has coordinates (xi, 0). The points are not necessarily sorted by their x coordinate.OutputIn the single line print "yes" (without the quotes), if the line has self-intersections. Otherwise, print "no" (without the quotes).ExamplesInput40 10 5 15OutputyesInput40 15 5 10OutputnoNoteThe first test from the statement is on the picture to the left, the second test is on the picture to the right.
Input40 10 5 15
Outputyes
2 seconds
256 megabytes
['brute force', 'implementation', '*1400']
B. Flag Daytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland, there is the national holiday coming β€” the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.InputThe first line contains two space-separated integers n (3 ≀ n ≀ 105) and m (1 ≀ m ≀ 105) β€” the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers β€” the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.OutputPrint n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.ExamplesInput7 31 2 31 4 54 6 7Output1 2 3 3 2 2 1 Input9 33 6 92 5 81 4 7Output1 1 1 2 2 2 3 3 3 Input5 24 1 53 1 2Output2 3 1 1 3
Input7 31 2 31 4 54 6 7
Output1 2 3 3 2 2 1
1 second
256 megabytes
['constructive algorithms', 'implementation', '*1400']
A. Group of Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to m points. We know that c1 schoolchildren got 1 point, c2 children got 2 points, ..., cm children got m points. Now you need to set the passing rate k (integer from 1 to m): all schoolchildren who got less than k points go to the beginner group and those who get at strictly least k points go to the intermediate group. We know that if the size of a group is more than y, then the university won't find a room for them. We also know that if a group has less than x schoolchildren, then it is too small and there's no point in having classes with it. So, you need to split all schoolchildren into two groups so that the size of each group was from x to y, inclusive. Help the university pick the passing rate in a way that meets these requirements.InputThe first line contains integer m (2 ≀ m ≀ 100). The second line contains m integers c1, c2, ..., cm, separated by single spaces (0 ≀ ci ≀ 100). The third line contains two space-separated integers x and y (1 ≀ x ≀ y ≀ 10000). At least one ci is greater than 0.OutputIf it is impossible to pick a passing rate in a way that makes the size of each resulting groups at least x and at most y, print 0. Otherwise, print an integer from 1 to m β€” the passing rate you'd like to suggest. If there are multiple possible answers, print any of them.ExamplesInput53 4 3 2 16 8Output3Input50 3 3 4 23 10Output4Input22 53 6Output0NoteIn the first sample the beginner group has 7 students, the intermediate group has 6 of them. In the second sample another correct answer is 3.
Input53 4 3 2 16 8
Output3
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*1000']
E. Xenia and String Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia the coder went to The Olympiad of Informatics and got a string problem. Unfortunately, Xenia isn't fabulous in string algorithms. Help her solve the problem.String s is a sequence of characters s1s2... s|s|, where record |s| shows the length of the string. Substring s[i... j] of string s is string sisi + 1... sj.String s is a Gray string, if it meets the conditions: the length of string |s| is odd; character occurs exactly once in the string; either |s| = 1, or substrings and are the same and are Gray strings. For example, strings "abacaba", "xzx", "g" are Gray strings and strings "aaa", "xz", "abaxcbc" are not.The beauty of string p is the sum of the squares of the lengths of all substrings of string p that are Gray strings. In other words, consider all pairs of values i, j (1 ≀ i ≀ j ≀ |p|). If substring p[i... j] is a Gray string, you should add (j - i + 1)2 to the beauty.Xenia has got string t consisting of lowercase English letters. She is allowed to replace at most one letter of the string by any other English letter. The task is to get a string of maximum beauty.InputThe first line contains a non-empty string t (1 ≀ |t| ≀ 105). String t only consists of lowercase English letters.OutputPrint the sought maximum beauty value Xenia can get.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.ExamplesInputzzzOutput12InputabaOutput12InputabacabaOutput83InputaaaaaaOutput15NoteIn the first test sample the given string can be transformed into string p = "zbz". Such string contains Gray strings as substrings p[1... 1], p[2... 2], p[3... 3] ΠΈ p[1... 3]. In total, the beauty of string p gets equal to 12 + 12 + 12 + 32 = 12. You can't obtain a more beautiful string.In the second test case it is not necessary to perform any operation. The initial string has the maximum possible beauty.
Inputzzz
Output12
1 second
256 megabytes
['dp', 'hashing', 'implementation', 'string suffix structures', 'strings', '*3000']
D. Bags and Coinstime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen you were a child you must have been told a puzzle of bags and coins. Anyway, here's one of its versions: A horse has three bags. The first bag has one coin, the second bag has one coin and the third bag has three coins. In total, the horse has three coins in the bags. How is that possible? The answer is quite simple. The third bag contains a coin and two other bags. This problem is a generalization of the childhood puzzle. You have n bags. You know that the first bag contains a1 coins, the second bag contains a2 coins, ..., the n-th bag contains an coins. In total, there are s coins. Find the way to arrange the bags and coins so that they match the described scenario or else state that it is impossible to do.InputThe first line contains two integers n and s (1 ≀ n, s ≀ 70000) β€” the number of bags and the total number of coins. The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 70000), where ai shows the number of coins in the i-th bag.OutputIf the answer doesn't exist, print -1. Otherwise, print n lines, on the i-th line print the contents of the i-th bag. The first number in the line, ci (0 ≀ ci ≀ ai), must represent the number of coins lying directly in the i-th bag (the coins in the bags that are in the i-th bag are not taken into consideration). The second number in the line, ki (0 ≀ ki < n) must represent the number of bags that lie directly in the i-th bag (the bags that are inside the bags lying in the i-th bag are not taken into consideration). Next, the line must contain ki integers β€” the numbers of the bags that are lying directly in the i-th bag.The total number of coins in the solution must equal s. If we count the total number of coins the i-th bag in the solution has, we should get ai. No bag can directly lie in more than one bag. The bags can be nested in more than one level (see the second test case). If there are multiple correct answers, you can print any of them.ExamplesInput3 31 3 1Output1 01 2 3 11 0Input3 31 3 1Output1 02 1 30 1 1Input1 21Output-1Input8 102 7 3 4 1 3 1 2Output2 01 2 1 40 2 7 80 2 5 61 03 01 02 0NoteThe pictures below show two possible ways to solve one test case from the statement. The left picture corresponds to the first test case, the right picture corresponds to the second one.
Input3 31 3 1
Output1 01 2 3 11 0
2.5 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'greedy', '*2700']
C. Compartmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number. After all the swaps each compartment should either have no student left, or have a company of three or four students. InputThe first line contains integer n (1 ≀ n ≀ 106) β€” the number of compartments in the carriage. The second line contains n integers a1, a2, ..., an showing how many students ride in each compartment (0 ≀ ai ≀ 4). It is guaranteed that at least one student is riding in the train.OutputIf no sequence of swapping seats with other people leads to the desired result, print number "-1" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.ExamplesInput51 2 2 4 3Output2Input34 1 1Output2Input40 3 0 4Output0
Input51 2 2 4 3
Output2
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'greedy', 'implementation', '*2100']
B. Xenia and Hammingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia is an amateur programmer. Today on the IT lesson she learned about the Hamming distance.The Hamming distance between two strings s = s1s2... sn and t = t1t2... tn of equal length n is value . Record [si ≠ ti] is the Iverson notation and represents the following: if si ≠ ti, it is one, otherwise β€” zero.Now Xenia wants to calculate the Hamming distance between two long strings a and b. The first string a is the concatenation of n copies of string x, that is, . The second string b is the concatenation of m copies of string y. Help Xenia, calculate the required Hamming distance, given n, x, m, y.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 1012). The second line contains a non-empty string x. The third line contains a non-empty string y. Both strings consist of at most 106 lowercase English letters.It is guaranteed that strings a and b that you obtain from the input have the same length.OutputPrint a single integer β€” the required Hamming distance.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.ExamplesInput100 10aaaaaaaaaaaOutput0Input1 1abacabaabzczzzOutput4Input2 3rzrazOutput5NoteIn the first test case string a is the same as string b and equals 100 letters a. As both strings are equal, the Hamming distance between them is zero.In the second test case strings a and b differ in their 3-rd, 5-th, 6-th and 7-th characters. Thus, the Hamming distance equals 4.In the third test case string a is rzrrzr and string b is azazaz. The strings differ in all characters apart for the second one, the Hamming distance between them equals 5.
Input100 10aaaaaaaaaaa
Output0
1 second
256 megabytes
['implementation', 'math', '*1900']
A. Knight Tournamenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows: There are n knights participating in the tournament. Each knight was assigned his unique number β€” an integer from 1 to n. The tournament consisted of m fights, in the i-th fight the knights that were still in the game with numbers at least li and at most ri have fought for the right to continue taking part in the tournament. After the i-th fight among all participants of the fight only one knight won β€” the knight number xi, he continued participating in the tournament. Other knights left the tournament. The winner of the last (the m-th) fight (the knight number xm) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number b was conquered by the knight number a, if there was a fight with both of these knights present and the winner was the knight number a.Write the code that calculates for each knight, the name of the knight that beat him.InputThe first line contains two integers n, m (2 ≀ n ≀ 3Β·105;Β 1 ≀ m ≀ 3Β·105) β€” the number of knights and the number of fights. Each of the following m lines contains three integers li, ri, xi (1 ≀ li < ri ≀ n;Β li ≀ xi ≀ ri) β€” the description of the i-th fight.It is guaranteed that the input is correct and matches the problem statement. It is guaranteed that at least two knights took part in each battle.OutputPrint n integers. If the i-th knight lost, then the i-th number should equal the number of the knight that beat the knight number i. If the i-th knight is the winner, then the i-th number must equal 0.ExamplesInput4 31 2 11 3 31 4 4Output3 1 4 0 Input8 43 5 43 7 62 8 81 8 1Output0 8 4 6 4 8 6 1 NoteConsider the first test case. Knights 1 and 2 fought the first fight and knight 1 won. Knights 1 and 3 fought the second fight and knight 3 won. The last fight was between knights 3 and 4, knight 4 won.
Input4 31 2 11 3 31 4 4
Output3 1 4 0
3 seconds
256 megabytes
['data structures', 'dsu', '*1500']
B. Vasya and Public Transporttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.Public transport is not free. There are 4 types of tickets: A ticket for one ride on some bus or trolley. It costs c1 burles; A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles; A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles; A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.InputThe first line contains four integers c1, c2, c3, c4 (1 ≀ c1, c2, c3, c4 ≀ 1000) β€” the costs of the tickets.The second line contains two integers n and m (1 ≀ n, m ≀ 1000) β€” the number of buses and trolleys Vasya is going to use.The third line contains n integers ai (0 ≀ ai ≀ 1000) β€” the number of times Vasya is going to use the bus number i.The fourth line contains m integers bi (0 ≀ bi ≀ 1000) β€” the number of times Vasya is going to use the trolley number i.OutputPrint a single number β€” the minimum sum of burles Vasya will have to spend on the tickets.ExamplesInput1 3 7 192 32 54 4 4Output12Input4 3 2 11 37981 2 3Output1Input100 100 8 1003 57 94 12100 1 47 0 42Output16NoteIn the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2Β·1) + 3 + 7 = 12 burles.In the second sample the profitable strategy is to buy one ticket of the fourth type.In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.
Input1 3 7 192 32 54 4 4
Output12
1 second
256 megabytes
['greedy', 'implementation', '*1100']
A. Vasya and Digital Roottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to: dr(n) = S(n), if S(n) < 10; dr(n) = dr( S(n) ), if S(n) β‰₯ 10. For example, dr(4098)  =  dr(21)  =  3.Vasya is afraid of large numbers, so the numbers he works with are at most 101000. For all such numbers, he has proved that dr(n)  =  S( S( S( S(n) ) ) ) (n ≀ 101000).Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers k and d, find the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.InputThe first line contains two integers k and d (1 ≀ k ≀ 1000; 0 ≀ d ≀ 9).OutputIn a single line print either any number that meets the requirements (without the leading zeroes) or "No solution" (without the quotes), if the corresponding number does not exist.The chosen number must consist of exactly k digits. We assume that number 0 doesn't contain any leading zeroes.ExamplesInput4 4Output5881Input5 1Output36172Input1 0Output0NoteFor the first test sample dr(5881)  =  dr(22)  =  4.For the second test sample dr(36172)  =  dr(19)  =  dr(10)  =  1.
Input4 4
Output5881
1 second
256 megabytes
['constructive algorithms', 'implementation', '*1100']
E. Lucky Number Representationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe know that lucky digits are digits 4 and 7, however Vasya's got another favorite digit 0 and he assumes it also is lucky! Lucky numbers are such non-negative integers whose decimal record only contains lucky digits. For example, numbers 0, 47, 7074 are lucky, but 1, 7377, 895,  -7 are not.Vasya has t important positive integers he needs to remember. Vasya is quite superstitious and he wants to remember lucky numbers only, so he is asking you for each important number to represent it as a sum of exactly six lucky numbers (Vasya just can't remember more numbers). Then Vasya can just remember these six numbers and calculate the important number at any moment.For each of t important integers represent it as the sum of six lucky numbers or state that this is impossible.InputThe first line contains a single integer t (1 ≀ t ≀ 5000).Next t lines contain a single positive integer ni (1 ≀ ni ≀ 1018) β€” the list of important numbers.Please, do not use the %lld to read or write 64-bit integers Π‘++. It is preferred to read the cin, cout streams or the %I64d specifier.OutputPrint t lines. The i-th line must contain the answer for the i-th important number: if the solution exists, the line must contain exactly six lucky numbers the sum of which equals ni, if the solution doesn't exist the string must contain a single integer -1.If there are multiple answers print any of them.ExamplesInput54217444751Output7 7 7 7 7 7-1400 0 40 0 4 07 0 0 0 0 047 4 0 0 0 0
Input54217444751
Output7 7 7 7 7 7-1400 0 40 0 4 07 0 0 0 0 047 4 0 0 0 0
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'dp', '*2200']
D. Transferring Pyramidtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya and Petya are using an interesting data storing structure: a pyramid.The pyramid consists of n rows, the i-th row contains i cells. Each row is shifted half a cell to the left relative to the previous row. The cells are numbered by integers from 1 to as shown on the picture below.An example of a pyramid at n = 5 is: This data structure can perform operations of two types: Change the value of a specific cell. It is described by three integers: "t i v", where t = 1 (the type of operation), i β€” the number of the cell to change and v the value to assign to the cell. Change the value of some subpyramid. The picture shows a highlighted subpyramid with the top in cell 5. It is described by s + 2 numbers: "t i v1 v2 ... vs", where t = 2, i β€” the number of the top cell of the pyramid, s β€” the size of the subpyramid (the number of cells it has), vj β€” the value you should assign to the j-th cell of the subpyramid. Formally: a subpyramid with top at the i-th cell of the k-th row (the 5-th cell is the second cell of the third row) will contain cells from rows from k to n, the (k + p)-th row contains cells from the i-th to the (i + p)-th (0 ≀ p ≀ n - k).Vasya and Petya had two identical pyramids. Vasya changed some cells in his pyramid and he now wants to send his changes to Petya. For that, he wants to find a sequence of operations at which Petya can repeat all Vasya's changes. Among all possible sequences, Vasya has to pick the minimum one (the one that contains the fewest numbers).You have a pyramid of n rows with k changed cells. Find the sequence of operations which result in each of the k changed cells being changed by at least one operation. Among all the possible sequences pick the one that contains the fewest numbers.InputThe first line contains two integers n and k (1 ≀ n, k ≀ 105).The next k lines contain the coordinates of the modified cells ri and ci (1 ≀ ci ≀ ri ≀ n) β€” the row and the cell's number in the row. All cells are distinct.OutputPrint a single number showing how many numbers the final sequence has.ExamplesInput4 53 13 34 14 34 4Output10Input7 112 23 14 35 15 25 56 47 27 37 47 5Output26NoteOne of the possible solutions of the first sample consists of two operations:2 4 v4 v7 v82 6 v6 v9 v10The picture shows the changed cells color-highlighted. The subpyramid used by the first operation is highlighted blue and the subpyramid used by the first operation is highlighted yellow:
Input4 53 13 34 14 34 4
Output10
3 seconds
256 megabytes
['dp', '*2900']
C. Vasya and Beautiful Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n.Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array a left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by k for each number).The seller can obtain array b from array a if the following conditions hold: bi > 0; 0 ≀ ai - bi ≀ k for all 1 ≀ i ≀ n.Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).InputThe first line contains two integers n and k (1 ≀ n ≀ 3Β·105; 1 ≀ k ≀ 106). The second line contains n integers ai (1 ≀ ai ≀ 106) β€” array a.OutputIn the single line print a single number β€” the maximum possible beauty of the resulting array.ExamplesInput6 13 6 10 12 13 16Output3Input5 38 21 52 15 77Output7NoteIn the first sample we can obtain the array:3 6 9 12 12 15In the second sample we can obtain the next array:7 21 49 14 77
Input6 13 6 10 12 13 16
Output3
1 second
256 megabytes
['brute force', 'dp', 'number theory', '*2100']
B. Game with Stringstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputGiven an n × n table T consisting of lowercase English letters. We'll consider some string s good if the table contains a correct path corresponding to the given string. In other words, good strings are all strings we can obtain by moving from the left upper cell of the table only to the right and down. Here's the formal definition of correct paths:Consider rows of the table are numbered from 1 to n from top to bottom, and columns of the table are numbered from 1 to n from left to the right. Cell (r, c) is a cell of table T on the r-th row and in the c-th column. This cell corresponds to letter Tr, c.A path of length k is a sequence of table cells [(r1, c1), (r2, c2), ..., (rk, ck)]. The following paths are correct: There is only one correct path of length 1, that is, consisting of a single cell: [(1, 1)]; Let's assume that [(r1, c1), ..., (rm, cm)] is a correct path of length m, then paths [(r1, c1), ..., (rm, cm), (rm + 1, cm)] and [(r1, c1), ..., (rm, cm), (rm, cm + 1)] are correct paths of length m + 1. We should assume that a path [(r1, c1), (r2, c2), ..., (rk, ck)] corresponds to a string of length k: Tr1, c1 + Tr2, c2 + ... + Trk, ck.Two players play the following game: initially they have an empty string. Then the players take turns to add a letter to the end of the string. After each move (adding a new letter) the resulting string must be good. The game ends after 2n - 1 turns. A player wins by the following scenario: If the resulting string has strictly more letters "a" than letters "b", then the first player wins; If the resulting string has strictly more letters "b" than letters "a", then the second player wins; If the resulting string has the same number of letters "a" and "b", then the players end the game with a draw. Your task is to determine the result of the game provided that both players played optimally well.InputThe first line contains a single number n (1 ≀ n ≀ 20).Next n lines contain n lowercase English letters each β€” table T.OutputIn a single line print string "FIRST", if the first player wins, "SECOND", if the second player wins and "DRAW", if the game ends with a draw.ExamplesInput2abcdOutputDRAWInput2xaayOutputFIRSTInput3aabbcbbacOutputDRAWNoteConsider the first sample:Good strings are strings: a, ab, ac, abd, acd.The first player moves first and adds letter a to the string, as there is only one good string of length 1. Then the second player can add b or c and the game will end with strings abd or acd, correspondingly. In the first case it will be a draw (the string has one a and one b), in the second case the first player wins. Naturally, in this case the second player prefers to choose letter b and end the game with a draw.Consider the second sample:Good strings are: x, xa, xay.We can see that the game will end with string xay and the first player wins.
Input2abcd
OutputDRAW
1 second
512 megabytes
['bitmasks', 'dp', 'games', '*2400']
A. Vasya and Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms β€” the left one and the right one. The robot can consecutively perform the following actions: Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units; Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.InputThe first line contains five integers n, l, r, Ql, Qr (1 ≀ n ≀ 105; 1 ≀ l, r ≀ 100; 1 ≀ Ql, Qr ≀ 104).The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 100).OutputIn the single line print a single number β€” the answer to the problem.ExamplesInput3 4 4 19 142 3 99Output576Input4 7 2 3 91 2 3 4Output34NoteConsider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4Β·42 + 4Β·99 + 4Β·3 = 576 energy units.The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2Β·4) + (7Β·1) + (2Β·3) + (2Β·2 + 9) = 34 energy units.
Input3 4 4 19 142 3 99
Output576
1 second
256 megabytes
['brute force', 'greedy', 'math', '*1500']
E. Antichaintime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a directed acyclic graph G, consisting of n vertexes, numbered from 0 to n - 1. The graph contains n edges numbered from 0 to n - 1. An edge with number i connects vertexes i and (i + 1)Β modΒ n, and it can be directed in either direction (from i to (i + 1)Β modΒ n, or vise versa).Operation xΒ modΒ y means taking the remainder after dividing number x by number y.Let's call two vertexes u and v in graph G comparable if the graph contains a path either from u to v or from v to u. We'll assume that an antichain is a set of vertexes of graph G, where any two distinct vertexes are not comparable. The size of an antichain is the number of vertexes in the corresponding set. An antichain is maximum if the graph doesn't have antichains of a larger size.Your task is to find the size of the maximum antichain in graph G.InputThe first line contains the sequence of characters s0s1... sn - 1 (2 ≀ n ≀ 106), consisting of numbers zero and one. The length of the line (number n) corresponds to the number of vertexes and edges in graph G. If character si (i β‰₯ 0) equals 0, then the edge between vertexes i and (i + 1)Β modΒ n is directed from the i-th vertex to the (i + 1)Β modΒ n-th one, otherwise β€” to the opposite point.It is guaranteed that the given graph is acyclic.OutputPrint a single integer β€” the size of the maximum antichain of graph G.ExamplesInput001Output1Input110010Output3NoteConsider the first test sample. The graph's G edges are: 0 → 1, 1 → 2, 0 → 2. We can choose the set of vertexes [0] as the maximum antichain. We cannot choose an antichain of larger size.
Input001
Output1
1 second
256 megabytes
['dp', 'graph matchings', 'greedy', '*2200']
D. Queuetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.InputThe first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.OutputPrint a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.ExamplesInputMFMOutput1InputMMFFOutput3InputFFMMMOutput0NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
InputMFM
Output1
1 second
256 megabytes
['constructive algorithms', 'dp', '*2000']
C. Find Maximumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula , where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≀ x ≀ m.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of array elements. The next line contains n space-separated integers a0, a1, ..., an - 1 (0 ≀ ai ≀ 104) β€” elements of array a.The third line contains a sequence of digits zero and one without spaces s0s1... sn - 1 β€” the binary representation of number m. Number m equals .OutputPrint a single integer β€” the maximum value of function f(x) for all .ExamplesInput23 810Output3Input517 0 10 2 111010Output27NoteIn the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
Input23 810
Output3
1 second
256 megabytes
['implementation', 'math', 'number theory', '*1600']
B. Two Heapstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera has 2Β·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer β€” the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?InputThe first line contains integer n (1 ≀ n ≀ 100). The second line contains 2Β·n space-separated integers ai (10 ≀ ai ≀ 99), denoting the numbers on the cubes.OutputIn the first line print a single number β€” the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2Β·n numbers bi (1 ≀ bi ≀ 2). The numbers mean: the i-th cube belongs to the bi-th heap in your division.If there are multiple optimal ways to split the cubes into the heaps, print any of them.ExamplesInput110 99Output12 1 Input213 24 13 45Output41 2 2 1 NoteIn the first test case Valera can put the first cube in the first heap, and second cube β€” in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.In the second test case Valera can obtain numbers 1313, 1345, 2413, 2445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345.
Input110 99
Output12 1
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'greedy', 'implementation', 'math', 'sortings', '*1900']
A. Dominotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera has got n domino pieces in a row. Each piece consists of two halves β€” the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.InputThe first line contains integer n (1 ≀ n ≀ 100), denoting the number of dominoes Valera has. Next n lines contain two space-separated integers xi, yi (1 ≀ xi, yi ≀ 6). Number xi is initially written on the upper half of the i-th domino, yi is initially written on the lower half.OutputPrint a single number β€” the minimum required number of seconds. If Valera can't do the task in any time, print  - 1.ExamplesInput24 26 4Output0Input12 3Output-1Input31 42 34 4Output1NoteIn the first test case the sum of the numbers on the upper halves equals 10 and the sum of the numbers on the lower halves equals 6. Both numbers are even, so Valera doesn't required to do anything.In the second sample Valera has only one piece of domino. It is written 3 on the one of its halves, therefore one of the sums will always be odd.In the third case Valera can rotate the first piece, and after that the sum on the upper halves will be equal to 10, and the sum on the lower halves will be equal to 8.
Input24 26 4
Output0
1 second
256 megabytes
['implementation', 'math', '*1200']
B. Jeff and Periodstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Jeff got hold of an integer sequence a1, a2, ..., an of length n. The boy immediately decided to analyze the sequence. For that, he needs to find all values of x, for which these conditions hold: x occurs in sequence a. Consider all positions of numbers x in the sequence a (such i, that ai = x). These numbers, sorted in the increasing order, must form an arithmetic progression. Help Jeff, find all x that meet the problem conditions.InputThe first line contains integer n (1 ≀ n ≀ 105). The next line contains integers a1, a2, ..., an (1 ≀ ai ≀ 105). The numbers are separated by spaces.OutputIn the first line print integer t β€” the number of valid x. On each of the next t lines print two integers x and px, where x is current suitable value, px is the common difference between numbers in the progression (if x occurs exactly once in the sequence, px must equal 0). Print the pairs in the order of increasing x.ExamplesInput12Output12 0Input81 2 1 3 1 2 1 5Output41 22 43 05 0NoteIn the first test 2 occurs exactly once in the sequence, ergo p2 = 0.
Input12
Output12 0
1 second
256 megabytes
['implementation', 'sortings', '*1300']
A. Jeff and Digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.InputThe first line contains integer n (1 ≀ n ≀ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card.OutputIn a single line print the answer to the problem β€” the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.ExamplesInput45 0 5 0Output0Input115 5 5 5 5 5 5 5 0 5 5Output5555555550NoteIn the first test you can make only one number that is a multiple of 90 β€” 0.In the second test you can make number 5555555550, it is a multiple of 90.
Input45 0 5 0
Output0
1 second
256 megabytes
['brute force', 'implementation', 'math', '*1000']
E. Jeff and Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday.Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 ≀ i < j ≀ n), such that an inequality ai > aj holds.Jeff can multiply some numbers of the sequence p by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.InputThe first line contains integer n (1 ≀ n ≀ 2000). The next line contains n integers β€” sequence p1, p2, ..., pn (|pi| ≀ 105). The numbers are separated by spaces.OutputIn a single line print the answer to the problem β€” the minimum number of inversions Jeff can get.ExamplesInput22 1Output0Input9-2 0 -1 0 -1 2 1 0 -1Output6
Input22 1
Output0
2 seconds
256 megabytes
['greedy', '*2200']
D. Jeff and Removing Periodstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCosider a sequence, consisting of n integers: a1, a2, ..., an. Jeff can perform the following operation on sequence a: take three integers v, t, k (1 ≀ v, t ≀ n;Β 0 ≀ k;Β v + tk ≀ n), such that av = av + t, av + t = av + 2t, ..., av + t(k - 1) = av + tk; remove elements av, av + t, ..., av + tΒ·k from the sequence a, the remaining elements should be reindexed a1, a2, ..., an - k - 1. permute in some order the remaining elements of sequence a. A beauty of a sequence a is the minimum number of operations that is needed to delete all elements from sequence a.Jeff's written down a sequence of m integers b1, b2, ..., bm. Now he wants to ask q questions. Each question can be described with two integers li, ri. The answer to the question is the beauty of sequence bli, bli + 1, ..., bri. You are given the sequence b and all questions. Help Jeff, answer all his questions.InputThe first line contains integer m (1 ≀ m ≀ 105). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 105). The third line contains integer q (1 ≀ q ≀ 105) β€” the number of questions. The next q lines contain pairs of integers, i-th of them contains a pair of integers li, ri (1 ≀ li ≀ ri ≀ m) β€” the description of i-th question.OutputIn q lines print the answers to Jeff's queries. Print the answers according to the order of questions in input.ExamplesInput52 2 1 1 251 51 12 21 32 3Output21122Input102 1 3 3 3 3 1 3 1 1104 82 101 104 41 32 46 71 92 51 1Output2331322321
Input52 2 1 1 251 51 12 21 32 3
Output21122
3 seconds
256 megabytes
['data structures', '*2700']