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. The tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHarry Potter has a difficult homework. Given a rectangular table, consisting of nβΓβm cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second β in the selected column. Harry's task is to make non-negative the sum of the numbers in each row and each column using these spells.Alone, the boy can not cope. Help the young magician!InputThe first line contains two integers n and m (1ββ€βn,βΒ mββ€β100) β the number of rows and the number of columns. Next n lines follow, each contains m integers: j-th integer in the i-th line is ai,βj (|ai,βj|ββ€β100), the number in the i-th row and j-th column of the table.The rows of the table numbered from 1 to n. The columns of the table numbered from 1 to m.OutputIn the first line print the number a β the number of required applications of the first spell. Next print a space-separated integers β the row numbers, you want to apply a spell. These row numbers must be distinct!In the second line print the number b β the number of required applications of the second spell. Next print b space-separated integers β the column numbers, you want to apply a spell. These column numbers must be distinct!If there are several solutions are allowed to print any of them.ExamplesInput4 1-1-1-1-1Output4 1 2 3 4 0 Input2 4-1 -1 -1 21 1 1 1Output1 1 1 4 | Input4 1-1-1-1-1 | Output4 1 2 3 4 0 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*2100'] |
C. Anniversarytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of numbers l, lβ+β1, lβ+β2, ..., r; let's consider all its k-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one.Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where F1β=β1, F2β=β1, Fnβ=βFnβ-β1β+βFnβ-β2 for nββ₯β3.Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by m.InputThe first line contains four space-separated integers m, l, r and k (1ββ€βmββ€β109;Β 1ββ€βlβ<βrββ€β1012;Β 2ββ€βkββ€βrβ-βlβ+β1).Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.OutputPrint a single integer β the residue from dividing the sought greatest common divisor by m.ExamplesInput10 1 8 2Output3Input10 1 8 3Output1 | Input10 1 8 2 | Output3 | 2 seconds | 256 megabytes | ['data structures', 'implementation', 'math', 'matrices', 'number theory', '*2400'] |
B. Naughty Stone Pilestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n piles of stones of sizes a1,βa2,β...,βan lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.InputThe first line contains integer n (1ββ€βnββ€β105) β the number of stone piles. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β109) β the initial sizes of the stone piles. The third line contains integer q (1ββ€βqββ€β105) β the number of queries. The last line contains q space-separated integers k1,βk2,β...,βkq (1ββ€βkiββ€β105) β the values of number k for distinct queries. Note that numbers ki can repeat.OutputPrint q whitespace-separated integers β the answers to the queries in the order, in which the queries are given in the input.Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput52 3 4 1 122 3Output9 8 NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2). | Input52 3 4 1 122 3 | Output9 8 | 2 seconds | 256 megabytes | ['greedy', '*1900'] |
A. Flying Saucer Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the 2-nd one, the 2-nd one β to the 1-st and the 3-rd ones, the 3-rd one β only to the 2-nd one. The transitions are possible only between the adjacent sections.The spacecraft team consists of n aliens. Each of them is given a rank β an integer from 1 to n. The ranks of all astronauts are distinct. The rules established on the Saucer, state that an alien may move from section a to section b only if it is senior in rank to all aliens who are in the segments a and b (besides, the segments a and b are of course required to be adjacent). Any alien requires exactly 1 minute to make a move. Besides, safety regulations require that no more than one alien moved at the same minute along the ship.Alien A is senior in rank to alien B, if the number indicating rank A, is more than the corresponding number for B.At the moment the whole saucer team is in the 3-rd segment. They all need to move to the 1-st segment. One member of the crew, the alien with the identification number CFR-140, decided to calculate the minimum time (in minutes) they will need to perform this task.Help CFR-140, figure out the minimum time (in minutes) that all the astronauts will need to move from the 3-rd segment to the 1-st one. Since this number can be rather large, count it modulo m.InputThe first line contains two space-separated integers: n and m (1ββ€βn,βmββ€β109) β the number of aliens on the saucer and the number, modulo which you should print the answer, correspondingly.OutputPrint a single number β the answer to the problem modulo m.ExamplesInput1 10Output2Input3 8Output2NoteIn the first sample the only crew member moves from segment 3 to segment 2, and then from segment 2 to segment 1 without any problems. Thus, the whole moving will take two minutes.To briefly describe the movements in the second sample we will use value , which would correspond to an alien with rank i moving from the segment in which it is at the moment, to the segment number j. Using these values, we will describe the movements between the segments in the second sample: , , , , , , , , , , , , , , , , , , , , , , , , , ; In total: the aliens need 26 moves. The remainder after dividing 26 by 8 equals 2, so the answer to this test is 2. | Input1 10 | Output2 | 2 seconds | 256 megabytes | ['math', '*1400'] |
E. Unsolvabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the following equation: where sign [a] represents the integer part of number a.Let's find all integer z (zβ>β0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers x and y (x,βyβ>β0), for which the given above equation holds.Let's write out all such z in the increasing order: z1,βz2,βz3, and so on (ziβ<βziβ+β1). Your task is: given the number n, find the number zn.InputThe first line contains a single integer n (1ββ€βnββ€β40).OutputPrint a single integer β the number zn modulo 1000000007 (109β+β7). It is guaranteed that the answer exists.ExamplesInput1Output1Input2Output3Input3Output15 | Input1 | Output1 | 2 seconds | 256 megabytes | ['math', 'number theory', '*2100'] |
D. Snaketime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet us remind you the rules of a very popular game called "Snake" (or sometimes "Boa", "Python" or "Worm").The game field is represented by an nβΓβm rectangular table. Some squares of the field are considered impassable (walls), all other squares of the fields are passable.You control a snake, the snake consists of segments. Each segment takes up exactly one passable square of the field, but any passable square contains at most one segment. All segments are indexed by integers from 1 to k, where k is the snake's length. The 1-th segment is the head and the k-th segment is the tail. For any i (1ββ€βiβ<βk), segments with indexes i and iβ+β1 are located in the adjacent squares of the field, that is, these squares share a common side.One of the passable field squares contains an apple. The snake's aim is to reach the apple and eat it (that is, to position its head in the square with the apple).The snake moves throughout the game. During one move the snake can move its head to an adjacent field square. All other segments follow the head. That is, each segment number i (1β<βiββ€βk) moves to the square that has just had segment number iβ-β1. Consider that all segments including the head move simultaneously (see the second test sample). If the snake's head moves to an unpassable square or to the square, occupied by its other segment, the snake dies. That's why we will consider such moves unvalid.Your task is to determine the minimum number of valid moves that the snake needs to reach the apple.InputThe first line contains two space-separated integers n and m (1ββ€βn,βmββ€β15) β the number of rows and columns of the game field.Next n lines describe the game field. Each of these lines contains m characters. Character "#" represents a wall, "." is a passable square, "@" is an apple. The snake's first segment is represented by character "1", the second one segment β by character "2" and so on.The game field description doesn't contain any characters besides "#', ".", "@" and digits (except 0). It is guaranteed that the described field is correct. It is guaranteed that the described field contains exactly one apple and exactly one snake, the snake's length is at least 3 and at most 9.OutputPrint a single integer to the output β the minimum number of moves needed to reach the apple. If the snake can't reach the apple, print -1.ExamplesInput4 5##.....1#@432#....#.Output4Input4 4#78#[email protected] 23@2#1#Output-1 | Input4 5##.....1#@432#....#. | Output4 | 4 seconds | 256 megabytes | ['bitmasks', 'dfs and similar', 'graphs', 'implementation', '*2200'] |
C. Barcodetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got an nβΓβm pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. InputThe first line contains four space-separated integers n, m, x and y (1ββ€βn,βm,βx,βyββ€β1000;Β xββ€βy).Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#".OutputIn the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. ExamplesInput6 5 1 2##.#..###.###..#...#.##.####..Output11Input2 5 1 1#####.....Output5NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Input6 5 1 2##.#..###.###..#...#.##.####.. | Output11 | 2 seconds | 256 megabytes | ['dp', 'matrices', '*1700'] |
B. Well-known Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNumbers k-bonacci (k is integer, kβ>β1) are a generalization of Fibonacci numbers and are determined as follows: F(k,βn)β=β0, for integer n, 1ββ€βnβ<βk; F(k,βk)β=β1; F(k,βn)β=βF(k,βnβ-β1)β+βF(k,βnβ-β2)β+β...β+βF(k,βnβ-βk), for integer n, nβ>βk. Note that we determine the k-bonacci numbers, F(k,βn), only for integer values of n and k.You've got a number s, represent it as a sum of several (at least two) distinct k-bonacci numbers. InputThe first line contains two integers s and k (1ββ€βs,βkββ€β109;Β kβ>β1).OutputIn the first line print an integer m (mββ₯β2) that shows how many numbers are in the found representation. In the second line print m distinct integers a1,βa2,β...,βam. Each printed integer should be a k-bonacci number. The sum of printed integers must equal s.It is guaranteed that the answer exists. If there are several possible answers, print any of them.ExamplesInput5 2Output30 2 3Input21 5Output34 1 16 | Input5 2 | Output30 2 3 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'number theory', '*1600'] |
A. Dice Towertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.InputThe first line contains a single integer n (1ββ€βnββ€β100) β the number of dice in the tower.The second line contains an integer x (1ββ€βxββ€β6) β the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai,βbi (1ββ€βai,βbiββ€β6;Β aiββ βbi) β the numbers Bob sees on the two sidelong faces of the i-th dice in the tower.Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.OutputPrint "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes).ExamplesInput363 25 42 4OutputYESInput332 64 15 3OutputNO | Input363 25 42 4 | OutputYES | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*1100'] |
B. Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got an array a, consisting of n integers: a1,βa2,β...,βan. Your task is to find a minimal by inclusion segment [l,βr] (1ββ€βlββ€βrββ€βn) such, that among numbers al,βΒ alβ+β1,βΒ ...,βΒ ar there are exactly k distinct numbers.Segment [l,βr] (1ββ€βlββ€βrββ€βn; l,βr are integers) of length mβ=βrβ-βlβ+β1, satisfying the given property, is called minimal by inclusion, if there is no segment [x,βy] satisfying the property and less then m in length, such that 1ββ€βlββ€βxββ€βyββ€βrββ€βn. Note that the segment [l,βr] doesn't have to be minimal in length among all segments, satisfying the given property.InputThe first line contains two space-separated integers: n and k (1ββ€βn,βkββ€β105). The second line contains n space-separated integers a1,βa2,β...,βanΒ β elements of the array a (1ββ€βaiββ€β105).OutputPrint a space-separated pair of integers l and r (1ββ€βlββ€βrββ€βn) such, that the segment [l,βr] is the answer to the problem. If the sought segment does not exist, print "-1 -1" without the quotes. If there are multiple correct answers, print any of them.ExamplesInput4 21 2 2 3Output1 2Input8 31 1 2 2 3 3 4 5Output2 5Input7 44 7 7 4 7 4 7Output-1 -1NoteIn the first sample among numbers a1 and a2 there are exactly two distinct numbers.In the second sample segment [2,β5] is a minimal by inclusion segment with three distinct numbers, but it is not minimal in length among such segments.In the third sample there is no segment with four distinct numbers. | Input4 21 2 2 3 | Output1 2 | 2 seconds | 256 megabytes | ['bitmasks', 'implementation', 'two pointers', '*1500'] |
A. Parallelepipedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.InputThe first and the single line contains three space-separated integers β the areas of the parallelepiped's faces. The area's values are positive (β>β0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement.OutputPrint a single number β the sum of all edges of the parallelepiped.ExamplesInput1 1 1Output12Input4 6 6Output28NoteIn the first sample the parallelepiped has sizes 1βΓβ1βΓβ1, in the second oneΒ β 2βΓβ2βΓβ3. | Input1 1 1 | Output12 | 2 seconds | 256 megabytes | ['brute force', 'geometry', 'math', '*1100'] |
E. Planar Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA graph is called planar, if it can be drawn in such a way that its edges intersect only at their vertexes.An articulation point is such a vertex of an undirected graph, that when removed increases the number of connected components of the graph.A bridge is such an edge of an undirected graph, that when removed increases the number of connected components of the graph.You've got a connected undirected planar graph consisting of n vertexes, numbered from 1 to n, drawn on the plane. The graph has no bridges, articulation points, loops and multiple edges. You are also given q queries. Each query is a cycle in the graph. The query response is the number of graph vertexes, which (if you draw a graph and the cycle on the plane) are located either inside the cycle, or on it. Write a program that, given the graph and the queries, will answer each query.InputThe first line contains two space-separated integers n and m (3ββ€βn,βmββ€β105) β the number of vertexes and edges of the graph. Next m lines contain the edges of the graph: the i-th line contains two space-separated integers ui and vi (1ββ€βui,βviββ€βn) β the numbers of vertexes, connecting the i-th edge. The next n lines contain the positions of the planar graph vertexes on the plane: the i-th line contains a pair of space-separated integers xi and yi (|xi|,β|yi|ββ€β109) β the coordinates of the i-th vertex of the graph on the plane. The next line contains integer q (1ββ€βqββ€β105)Β β the number of queries. Then follow q lines that describe the queries: the i-th line contains the sequence of space-separated integers ki, a1, a2, ..., aki (1ββ€βajββ€βn;Β kiβ>β2), where ki is the cycle length in the i-th query, aj are numbers of the vertexes that form a cycle. The numbers of vertexes in the cycle are given in the clockwise or counterclockwise order. The given cycles are simple, that is they cannot go through a graph vertex more than once. The total length of all cycles in all queries does not exceed 105.It is guaranteed that the given graph contains no bridges, articulation points, loops and multiple edges. It is guaranteed that the edge segments can have common points only at the graph's vertexes.OutputFor each query print a single integer β the number of vertexes inside the cycle or on it. Print the answers in the order, in which the queries follow in the input. Separate the numbers by spaces.ExamplesInput3 31 22 33 10 01 00 113 1 2 3Output3Input5 81 22 33 44 11 52 53 54 50 02 02 20 21 114 1 2 3 4Output5Input4 51 22 33 44 12 40 01 01 10 133 1 2 43 4 2 34 1 2 3 4Output334 | Input3 31 22 33 10 01 00 113 1 2 3 | Output3 | 1 second | 256 megabytes | ['flows', 'geometry', 'graphs', '*3000'] |
D. Spidertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA plane contains a not necessarily convex polygon without self-intersections, consisting of n vertexes, numbered from 1 to n. There is a spider sitting on the border of the polygon, the spider can move like that: Transfer. The spider moves from the point p1 with coordinates (x1,βy1), lying on the polygon border, to the point p2 with coordinates (x2,βy2), also lying on the border. The spider can't go beyond the polygon border as it transfers, that is, the spider's path from point p1 to point p2 goes along the polygon border. It's up to the spider to choose the direction of walking round the polygon border (clockwise or counterclockwise). Descend. The spider moves from point p1 with coordinates (x1,βy1) to point p2 with coordinates (x2,βy2), at that points p1 and p2 must lie on one vertical straight line (x1β=βx2), point p1 must be not lower than point p2 (y1ββ₯βy2) and segment p1p2 mustn't have points, located strictly outside the polygon (specifically, the segment can have common points with the border). Initially the spider is located at the polygon vertex with number s. Find the length of the shortest path to the vertex number t, consisting of transfers and descends. The distance is determined by the usual Euclidean metric .InputThe first line contains integer n (3ββ€βnββ€β105) β the number of vertexes of the given polygon. Next n lines contain two space-separated integers each β the coordinates of the polygon vertexes. The vertexes are listed in the counter-clockwise order. The coordinates of the polygon vertexes do not exceed 104 in their absolute value. The last line contains two space-separated integers s and t (1ββ€βs,βtββ€βn) β the start and the end vertexes of the sought shortest way. Consider the polygon vertexes numbered in the order they are given in the input, that is, the coordinates of the first vertex are located on the second line of the input and the coordinates of the n-th vertex are on the (nβ+β1)-th line. It is guaranteed that the given polygon is simple, that is, it contains no self-intersections or self-tangencies.OutputIn the output print a single real number β the length of the shortest way from vertex s to vertex t. The answer is considered correct, if its absolute or relative error does not exceed 10β-β6.ExamplesInput40 01 01 10 11 4Output1.000000000000000000e+000Input40 01 10 2-1 13 3Output0.000000000000000000e+000Input50 05 01 40 22 13 1Output5.650281539872884700e+000NoteIn the first sample the spider transfers along the side that connects vertexes 1 and 4.In the second sample the spider doesn't have to transfer anywhere, so the distance equals zero.In the third sample the best strategy for the spider is to transfer from vertex 3 to point (2,3), descend to point (2,1), and then transfer to vertex 1. | Input40 01 01 10 11 4 | Output1.000000000000000000e+000 | 3 seconds | 256 megabytes | ['geometry', 'graphs', '*3000'] |
C. Partial Sumstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that: First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1ββ€βiββ€βn) of array s equals . The operation xΒ modΒ y means that we take the remainder of the division of number x by number y. Then we write the contents of the array s to the array a. Element number i (1ββ€βiββ€βn) of the array s becomes the i-th element of the array a (aiβ=βsi). You task is to find array a after exactly k described operations are applied.InputThe first line contains two space-separated integers n and k (1ββ€βnββ€β2000, 0ββ€βkββ€β109). The next line contains n space-separated integers a1,βa2,β...,βanΒ β elements of the array a (0ββ€βaiββ€β109).OutputPrint n integers Β β elements of the array a after the operations are applied to it. Print the elements in the order of increasing of their indexes in the array a. Separate the printed numbers by spaces.ExamplesInput3 11 2 3Output1 3 6Input5 03 14 15 92 6Output3 14 15 92 6 | Input3 11 2 3 | Output1 3 6 | 4 seconds | 256 megabytes | ['combinatorics', 'math', 'number theory', '*1900'] |
B. Two Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA subsequence of length |x| of string sβ=βs1s2... s|s| (where |s| is the length of string s) is a string xβ=βsk1sk2... sk|x| (1ββ€βk1β<βk2β<β...β<βk|x|ββ€β|s|).You've got two stringsΒ β s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1ββ€βiββ€β|s|), there is such subsequence xβ=βsk1sk2... sk|x| of string s, that xβ=βt and for some j (1ββ€βjββ€β|x|) kjβ=βi.InputThe first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2Β·105.OutputPrint "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise.ExamplesInputabababOutputYesInputabacabaabaOutputNoInputabcbaOutputNoNoteIn the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once.In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t.In the third sample there is no occurrence of string t in string s. | Inputababab | OutputYes | 2 seconds | 256 megabytes | ['data structures', 'dp', 'strings', '*1900'] |
A. Bracket Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA bracket sequence is a string, containing only characters "(", ")", "[" and "]".A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition.A substring s[l... r] (1ββ€βlββ€βrββ€β|s|) of string sβ=βs1s2... s|s| (where |s| is the length of string s) is the string slslβ+β1... sr. The empty string is a substring of any string by definition.You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets Β«[Β» as possible.InputThe first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters.OutputIn the first line print a single integer β the number of brackets Β«[Β» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them.ExamplesInput([])Output1([])Input(((Output0 | Input([]) | Output1([]) | 2 seconds | 256 megabytes | ['data structures', 'expression parsing', 'implementation', '*1700'] |
E. Decoding Genometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently a top secret mission to Mars has taken place. As a result, scientists managed to obtain some information about the Martian DNA. Now we know that any Martian DNA contains at most m different nucleotides, numbered from 1 to m. Special characteristics of the Martian DNA prevent some nucleotide pairs from following consecutively in this chain. For example, if the nucleotide 1 and nucleotide 2 can not follow consecutively in the Martian DNA, then the chain of nucleotides [1, 2] is not a valid chain of Martian DNA, but the chain of nucleotides [2, 1] can be a valid chain (if there is no corresponding restriction). The number of nucleotide pairs that can't follow in the DNA chain consecutively, is k. The needs of gene research required information about the quantity of correct n-long chains of the Martian DNA. Your task is to write a program that will calculate this value.InputThe first line contains three space-separated integers n,βm,βk (1ββ€βnββ€β1015, 1ββ€βmββ€β52, 0ββ€βkββ€βm2).Next k lines contain two characters each, without a space between them, representing a forbidden nucleotide pair. The first character represents the first nucleotide in the forbidden pair, the second character represents the second nucleotide.The nucleotides with assigned numbers from 1 to 26 are represented by English alphabet letters from "a" to "z" (1 is an "a", 2 is a "b", ..., 26 is a "z"). Nucleotides with assigned numbers from 27 to 52 are represented by English alphabet letters from "A" to "Z" (27 is an "A", 28 is a "B", ..., 52 is a "Z").It is guaranteed that each forbidden pair occurs at most once in the input. It is guaranteed that nucleotide's numbers in all forbidden pairs cannot be more than m. Note that order is important in nucleotide pairs.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.OutputPrint a single integer β the sought number modulo 1000000007 (109β+β7).ExamplesInput3 3 2abbaOutput17Input3 3 0Output27Input2 1 1aaOutput0NoteIn the second test case all possible three-nucleotide DNAs are permitted. Each nucleotide can take one of three values, thus in total there are 27 distinct three nucleotide DNAs.In the third test sample we cannot make any DNA of two nucleotides β the only possible nucleotide "a" cannot occur two times consecutively. | Input3 3 2abba | Output17 | 2 seconds | 256 megabytes | ['dp', 'matrices', '*1900'] |
D. Olympiadtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA boy named Vasya has taken part in an Olympiad. His teacher knows that in total Vasya got at least x points for both tours of the Olympiad. The teacher has the results of the first and the second tour of the Olympiad but the problem is, the results have only points, no names. The teacher has to know Vasya's chances.Help Vasya's teacher, find two numbers β the best and the worst place Vasya could have won. Note that the total results' table sorts the participants by the sum of points for both tours (the first place has the participant who has got the most points). If two or more participants have got the same number of points, it's up to the jury to assign places to them according to their choice. It is guaranteed that each participant of the Olympiad participated in both tours of the Olympiad.InputThe first line contains two space-separated integers n,βx (1ββ€βnββ€β105;Β 0ββ€βxββ€β2Β·105) β the number of Olympiad participants and the minimum number of points Vasya earned.The second line contains n space-separated integers: a1,βa2,β...,βan (0ββ€βaiββ€β105) β the participants' points in the first tour.The third line contains n space-separated integers: b1,βb2,β...,βbn (0ββ€βbiββ€β105) β the participants' points in the second tour.The participants' points are given in the arbitrary order. It is guaranteed that Vasya was present in the Olympiad β there are two integers i,βj (1ββ€βi,βjββ€βn) such, that aiβ+βbjββ₯βx.OutputPrint two space-separated integers β the best and the worst place Vasya could have got on the Olympiad.ExamplesInput5 21 1 1 1 11 1 1 1 1Output1 5Input6 74 3 5 6 4 48 6 0 4 3 4Output1 5NoteIn the first text sample all 5 participants earn 2 points each in any case. Depending on the jury's decision, Vasya can get the first (the best) as well as the last (the worst) fifth place.In the second test sample in the best case scenario Vasya wins again: he can win 12 points and become the absolute winner if the total results' table looks like that β {4:8, 6:4, 3:6, 4:4, 4:3, 5:0}.In this table all participants are sorted by decreasing points and we can see how much a participant earned in the first and in the second tour.In the worst case scenario Vasya can get the fifth place if the table looks like that β {4:8, 4:6, 6:4, 5:4, 4:3, 3:0}, and he earned 4 and 3 points in the first and second tours, correspondingly. | Input5 21 1 1 1 11 1 1 1 1 | Output1 5 | 1 second | 256 megabytes | ['binary search', 'greedy', 'sortings', 'two pointers', '*1900'] |
C. Reducing Fractionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you.InputThe first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly.The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator.The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator.OutputPrint the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them.ExamplesInput3 2100 5 250 10Output2 32 11 1 1Input4 32 5 10 20100 1 3Output1 1203NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Input3 2100 5 250 10 | Output2 32 11 1 1 | 2 seconds | 256 megabytes | ['implementation', 'math', 'number theory', 'sortings', '*1800'] |
B. Cosmic Tablestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an nβΓβm table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.InputThe first line contains three space-separated integers n, m and k (1ββ€βn,βmββ€β1000, 1ββ€βkββ€β500000) β the number of table columns and rows and the number of queries, correspondingly.Next n lines contain m space-separated numbers each β the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0ββ€βpββ€β106.Next k lines contain queries in the format "si xi yi", where si is one of the characters "Ρ", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1ββ€βx,βyββ€βm,βxββ βy); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1ββ€βx,βyββ€βn,βxββ βy); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1ββ€βxββ€βn,β1ββ€βyββ€βm). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β from left to right from 1 to m.OutputFor each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.ExamplesInput3 3 51 2 34 5 67 8 9g 3 2r 3 2c 2 3g 2 2g 3 2Output896Input2 3 31 2 43 1 5c 2 1r 1 2g 1 3Output5NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5. | Input3 3 51 2 34 5 67 8 9g 3 2r 3 2c 2 3g 2 2g 3 2 | Output896 | 3 seconds | 256 megabytes | ['data structures', 'implementation', '*1300'] |
A. Shooshuns and Sequence time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.InputThe first line contains two space-separated integers n and k (1ββ€βkββ€βnββ€β105).The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β105) β the sequence that the shooshuns found.OutputPrint the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.ExamplesInput3 23 1 1Output1Input3 13 1 1Output-1NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1. | Input3 23 1 1 | Output1 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1200'] |
B. Little Elephant and Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant loves numbers. He has a positive integer x. The Little Elephant wants to find the number of positive integers d, such that d is the divisor of x, and x and d have at least one common (the same) digit in their decimal representations. Help the Little Elephant to find the described number.InputA single line contains a single integer x (1ββ€βxββ€β109).OutputIn a single line print an integer β the answer to the problem.ExamplesInput1Output1Input10Output2 | Input1 | Output1 | 2 seconds | 256 megabytes | ['implementation', '*1300'] |
A. Little Elephant and Functiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows: If xβ=β1, exit the function. Otherwise, call f(xβ-β1), and then make swap(axβ-β1,βax) (swap the x-th and (xβ-β1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.InputA single line contains integer n (1ββ€βnββ€β1000) β the size of permutation.OutputIn a single line print n distinct integers from 1 to n β the required permutation. Numbers in a line should be separated by spaces.It is guaranteed that the answer exists.ExamplesInput1Output1 Input2Output2 1 | Input1 | Output1 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1000'] |
E. Little Elephant and Inversionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1ββ€βlβ<βrββ€βn and sequence bβ=βa1a2... alararβ+β1... an has no more than k inversions. An inversion in sequence b is a pair of elements of the sequence b, that change their relative order after a stable sorting of the sequence. In other words, an inversion is a pair of integers i and j, such that 1ββ€βiβ<βjββ€β|b| and biβ>βbj, where |b| is the length of sequence b, and bj is its j-th element.Help the Little Elephant and count the number of the described pairs.InputThe first line contains two integers n and k (2ββ€βnββ€β105,β0ββ€βkββ€β1018) β the size of array a and the maximum allowed number of inversions respectively. The next line contains n positive integers, separated by single spaces, a1,βa2,β...,βan (1ββ€βaiββ€β109) β elements of array a.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.OutputIn a single line print a single number β the answer to the problem.ExamplesInput3 11 3 2Output3Input5 21 3 2 1 7Output6 | Input3 11 3 2 | Output3 | 2 seconds | 256 megabytes | ['data structures', 'two pointers', '*2400'] |
D. Little Elephant and Triangletime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant is playing with the Cartesian coordinates' system. Most of all he likes playing with integer points. The Little Elephant defines an integer point as a pair of integers (x;Β y), such that 0ββ€βxββ€βw and 0ββ€βyββ€βh. Thus, the Little Elephant knows only (wβ+β1)Β·(hβ+β1) distinct integer points.The Little Elephant wants to paint a triangle with vertexes at integer points, the triangle's area must be a positive integer. For that, he needs to find the number of groups of three points that form such triangle. At that, the order of points in a group matters, that is, the group of three points (0;0), (0;2), (2;2) isn't equal to the group (0;2), (0;0), (2;2).Help the Little Elephant to find the number of groups of three integer points that form a nondegenerate triangle with integer area.InputA single line contains two integers w and h (1ββ€βw,βhββ€β4000).OutputIn a single output line print an integer β the remainder of dividing the answer to the problem by 1000000007 (109β+β7).ExamplesInput2 1Output36Input2 2Output240 | Input2 1 | Output36 | 3 seconds | 256 megabytes | ['geometry', 'math', '*2500'] |
C. Little Elephant and Shiftstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1ββ€βiββ€βn) element of the permutation a as ai, the j-th (1ββ€βjββ€βn) element of the permutation b β as bj.The distance between permutations a and b is the minimum absolute value of the difference between the positions of the occurrences of some number in a and in b. More formally, it's such minimum |iβ-βj|, that aiβ=βbj.A cyclic shift number i (1ββ€βiββ€βn) of permutation b consisting from n elements is a permutation bibiβ+β1... bnb1b2... biβ-β1. Overall a permutation has n cyclic shifts.The Little Elephant wonders, for all cyclic shifts of permutation b, what is the distance between the cyclic shift and permutation a?InputThe first line contains a single integer n (1ββ€βnββ€β105) β the size of the permutations. The second line contains permutation a as n distinct numbers from 1 to n, inclusive. The numbers are separated with single spaces. The third line contains permutation b in the same format.OutputIn n lines print n integers β the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation b, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on.ExamplesInput21 22 1Output10Input42 1 3 43 4 2 1Output2101 | Input21 22 1 | Output10 | 2 seconds | 256 megabytes | ['data structures', '*2100'] |
B. Little Elephant and Arraytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant loves playing with arrays. He has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai. Additionally the Little Elephant has m queries to the array, each query is characterised by a pair of integers lj and rj (1ββ€βljββ€βrjββ€βn). For each query lj,βrj the Little Elephant has to count, how many numbers x exist, such that number x occurs exactly x times among numbers alj,βaljβ+β1,β...,βarj.Help the Little Elephant to count the answers to all queries.InputThe first line contains two space-separated integers n and m (1ββ€βn,βmββ€β105) β the size of array a and the number of queries to it. The next line contains n space-separated positive integers a1, a2, ..., an (1ββ€βaiββ€β109). Next m lines contain descriptions of queries, one per line. The j-th of these lines contains the description of the j-th query as two space-separated integers lj and rj (1ββ€βljββ€βrjββ€βn).OutputIn m lines print m integers β the answers to the queries. The j-th line should contain the answer to the j-th query.ExamplesInput7 23 1 2 2 3 3 71 73 4Output31 | Input7 23 1 2 2 3 3 71 73 4 | Output31 | 4 seconds | 256 megabytes | ['constructive algorithms', 'data structures', '*1800'] |
A. Little Elephant and Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant has got a problem β somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.InputThe first line contains a single integer n (2ββ€βnββ€β105) β the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, β array a.Note that the elements of the array are not necessarily distinct numbers.OutputIn a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise.ExamplesInput21 2OutputYESInput33 2 1OutputYESInput44 3 2 1OutputNONoteIn the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES".In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES".In the third sample we can't sort the array in more than one swap operation, so the answer is "NO". | Input21 2 | OutputYES | 2 seconds | 256 megabytes | ['implementation', 'sortings', '*1300'] |
E. Parking Lottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA parking lot in the City consists of n parking spaces, standing in a line. The parking spaces are numbered from 1 to n from left to right. When a car arrives at the lot, the operator determines an empty parking space for it. For the safety's sake the chosen place should be located as far from the already occupied places as possible. That is, the closest occupied parking space must be as far away as possible. If there are several such places, then the operator chooses the place with the minimum index from them. If all parking lot places are empty, then the car gets place number 1.We consider the distance between the i-th and the j-th parking spaces equal to 4Β·|iβ-βj| meters.You are given the parking lot records of arriving and departing cars in the chronological order. For each record of an arriving car print the number of the parking lot that was given to this car.InputThe first line contains two space-separated integers n and m (1ββ€βn,βmββ€β2Β·105) β the number of parking places and the number of records correspondingly. Next m lines contain the descriptions of the records, one per line. The i-th line contains numbers ti, idi (1ββ€βtiββ€β2;Β 1ββ€βidiββ€β106). If ti equals 1, then the corresponding record says that the car number idi arrived at the parking lot. If ti equals 2, then the corresponding record says that the car number idi departed from the parking lot. Records about arriving to the parking lot and departing from the parking lot are given chronologically. All events occurred consecutively, no two events occurred simultaneously.It is guaranteed that all entries are correct: each car arrived at the parking lot at most once and departed from the parking lot at most once, there is no record of a departing car if it didn't arrive at the parking lot earlier, there are no more than n cars on the parking lot at any moment. You can consider the cars arbitrarily numbered from 1 to 106, all numbers are distinct. Initially all places in the parking lot are empty.OutputFor each entry of an arriving car print the number of its parking space. Print the numbers of the spaces in the order, in which the cars arrive to the parking lot.ExamplesInput7 111 151 1231231 31 52 1231232 151 212 31 61 71 8Output17427413 | Input7 111 151 1231231 31 52 1231232 151 212 31 61 71 8 | Output17427413 | 2 seconds | 256 megabytes | ['data structures', '*2200'] |
D. Choosing Capital for Treelandtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are nβ-β1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.InputThe first input line contains integer n (2ββ€βnββ€β2Β·105) β the number of cities in Treeland. Next nβ-β1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si,βti (1ββ€βsi,βtiββ€βn;Β siββ βti) β the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.OutputIn the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital β a sequence of indexes of cities in the increasing order.ExamplesInput32 12 3Output02 Input41 42 43 4Output21 2 3 | Input32 12 3 | Output02 | 3 seconds | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'trees', '*1700'] |
C. Color Stripetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.InputThe first input line contains two integers n and k (1ββ€βnββ€β5Β·105;Β 2ββ€βkββ€β26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.OutputPrint a single integer β the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.ExamplesInput6 3ABBACCOutput2ABCACAInput3 2BBBOutput1BAB | Input6 3ABBACC | Output2ABCACA | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', '*1600'] |
B. Special Offer! Super Price 999 Bourles!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors.Polycaprus calculated that the optimal celling price for such scissors would be p bourles. However, he read somewhere that customers are attracted by prices that say something like "Special Offer! Super price 999 bourles!". So Polycarpus decided to lower the price a little if it leads to the desired effect.Polycarpus agrees to lower the price by no more than d bourles so that the number of nines at the end of the resulting price is maximum. If there are several ways to do it, he chooses the maximum possible price.Note, Polycarpus counts only the trailing nines in a price.InputThe first line contains two integers p and d (1ββ€βpββ€β1018; 0ββ€βdβ<βp) β the initial price of scissors and the maximum possible price reduction.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.OutputPrint the required price β the maximum price that ends with the largest number of nines and that is less than p by no more than d.The required number shouldn't have leading zeroes.ExamplesInput1029 102Output999Input27191 17Output27189 | Input1029 102 | Output999 | 1 second | 256 megabytes | ['implementation', '*1400'] |
A. k-Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.InputThe first input line contains integer k (1ββ€βkββ€β1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1ββ€β|s|ββ€β1000, where |s| is the length of string s.OutputRearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them.If the solution doesn't exist, print "-1" (without quotes).ExamplesInput2aazzOutputazazInput3abcabcabzOutput-1 | Input2aazz | Outputazaz | 2 seconds | 256 megabytes | ['implementation', 'strings', '*1000'] |
B. Airporttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows: it is up to a passenger to choose a plane to fly on; if the chosen plane has x (xβ>β0) empty seats at the given moment, then the ticket for such a plane costs x zlotys (units of Polish currency). The only ticket office of the airport already has a queue of n passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all n passengers buy tickets according to the conditions of this offer?The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to n-th person.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β1000) β the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains m integers a1,βa2,β...,βam (1ββ€βaiββ€β1000) β ai stands for the number of empty seats in the i-th plane before the ticket office starts selling tickets.The numbers in the lines are separated by a space. It is guaranteed that there are at least n empty seats in total.OutputPrint two integers β the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.ExamplesInput4 32 1 1Output5 5Input4 32 2 2Output7 6NoteIn the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person β to the 2-nd plane, the 3-rd person β to the 3-rd plane, the 4-th person β to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person β to the 1-st plane, the 3-rd person β to the 2-nd plane, the 4-th person β to the 2-nd plane. | Input4 32 1 1 | Output5 5 | 2 seconds | 256 megabytes | ['implementation', '*1100'] |
A. Mountain Scenerytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2nβ+β1 points with coordinates (1,βy1), (2,βy2), ..., (2nβ+β1,βy2nβ+β1), with the i-th segment connecting the point (i,βyi) and the point (iβ+β1,βyiβ+β1). For any even i (2ββ€βiββ€β2n) the following condition holds: yiβ-β1β<βyi and yiβ>βyiβ+β1. We shall call a vertex of a polyline with an even x coordinate a mountain peak. The figure to the left shows the initial picture, the figure to the right shows what the picture looks like after Bolek's actions. The affected peaks are marked red, k = 2. Bolek fancied a little mischief. He chose exactly k mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the y coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1,βr1), (2,βr2), ..., (2nβ+β1,βr2nβ+β1).Given Bolek's final picture, restore the initial one.InputThe first line contains two space-separated integers n and k (1ββ€βkββ€βnββ€β100). The next line contains 2nβ+β1 space-separated integers r1,βr2,β...,βr2nβ+β1 (0ββ€βriββ€β100) β the y coordinates of the polyline vertices on Bolek's picture.It is guaranteed that we can obtain the given picture after performing the described actions on some picture of mountain peaks.OutputPrint 2nβ+β1 integers y1,βy2,β...,βy2nβ+β1 β the y coordinates of the vertices of the polyline on the initial picture. If there are multiple answers, output any one of them.ExamplesInput3 20 5 3 5 1 5 2Output0 5 3 4 1 4 2 Input1 10 2 0Output0 1 0 | Input3 20 5 3 5 1 5 2 | Output0 5 3 4 1 4 2 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', '*1100'] |
E. Alien DNAtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations β each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The mangled copy of the activated continuous subsequence is formed by first joining all the elements at the even positions in that subsequence, and then joining all the elements at the odd ones at the end. That is, if the activated subsequence consists of 11 elements and represented as s1s2... s11, its mangled copy is s2s4s6s8s10s1s3s5s7s9s11.For example, if the original sequence was "ACTGG" and the mutation happened on the segment [2,β4] (that is the activated subsequence is "CTG"), the mutated DNA is: "ACTGTCGG". The mangled copy of the activated subsequence is marked with bold font.Professor Bajtocy has written down the original DNA sequence and the mutations that sequentially happened to it, and he now asks you to recover the first k elements of the DNA sequence after all the mutations.InputThe first line of input contains the original DNA sequence, consisting only of letters "A", "C", "T" and "G" and not exceeding 3Β·106 in length. The second line contains a single integer k (1ββ€βkββ€β3Β·106).The third line contains a single integer n (0ββ€βnββ€β5000) β the number of mutations. The next n lines describe the mutations in chronological order β each mutation is described by two numbers li and ri (1ββ€βliββ€βriββ€β109), meaning that the continuous subsequence [li,βri] has become active and cloned itself, joining itself with the mangled copy. It is guaranteed that the input data is correct, that is, no mutation acts on non-existing elements of the DNA sequence, and the resulting DNA sequence has at least k elements.Assume that the DNA elements are indexed starting from 1 and that the notation [l,βr] meaning the continuous subsequence of DNA sequence that consists of rβ-βlβ+β1 elements starting at the l-th DNA sequence element and ending at the r-th DNA sequence element.OutputOutput a single line, containing the first k letters of the mutated DNA sequence.ExamplesInputGAGA40OutputGAGAInputACGTACGT1621 22 8OutputACCAGTACCGACATCGNoteIn the second example, after the first mutation the sequence is "ACCAGTACGT". After the second mutation it's "ACCAGTACCGACATCGT". | InputGAGA40 | OutputGAGA | 2 seconds | 256 megabytes | ['data structures', 'dsu', 'trees', '*2800'] |
D. Bitonix' Patroltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputByteland is trying to send a space mission onto the Bit-X planet. Their task is complicated by the fact that the orbit of the planet is regularly patrolled by Captain Bitonix, the leader of the space forces of Bit-X.There are n stations around Bit-X numbered clockwise from 1 to n. The stations are evenly placed on a circular orbit, so the stations number i and iβ+β1 (1ββ€βiβ<βn), and the stations number 1 and n, are neighboring. The distance between every pair of adjacent stations is equal to m space miles. To go on a patrol, Captain Bitonix jumps in his rocket at one of the stations and flies in a circle, covering a distance of at least one space mile, before finishing in some (perhaps the starting) station.Bitonix' rocket moves by burning fuel tanks. After Bitonix attaches an x-liter fuel tank and chooses the direction (clockwise or counter-clockwise), the rocket flies exactly x space miles along a circular orbit in the chosen direction. Note that the rocket has no brakes; it is not possible for the rocket to stop before depleting a fuel tank.For example, assume that nβ=β3 and mβ=β60 and Bitonix has fuel tanks with volumes of 10, 60, 90 and 100 liters. If Bitonix starts from station 1, uses the 100-liter fuel tank to go clockwise, then uses the 90-liter fuel tank to go clockwise, and then uses the 10-liter fuel tank to go counterclockwise, he will finish back at station 1. This constitutes a valid patrol. Note that Bitonix does not have to use all available fuel tanks. Another valid option for Bitonix in this example would be to simply use the 60-liter fuel tank to fly to either station 2 or 3.However, if n was equal to 3, m was equal to 60 and the only fuel tanks available to Bitonix were one 10-liter tank and one 100-liter tank, he would have no way of completing a valid patrol (he wouldn't be able to finish any patrol exactly at the station).The Byteland space agency wants to destroy some of Captain Bitonix' fuel tanks so that he cannot to complete any valid patrol. Find how many different subsets of the tanks the agency can destroy to prevent Captain Bitonix from completing a patrol and output the answer modulo 1000000007 (109β+β7).InputThe first line of the input contains three integers n (2ββ€βnββ€β1000) β the number of stations, m (1ββ€βmββ€β120) β the distance between adjacent stations, and t (1ββ€βtββ€β10000) β the number of fuel tanks owned by Captain Bitonix.The second line of the input contains t space-separated integers between 1 and 109, inclusive β the volumes of Bitonix' fuel tanks.OutputOutput a single number β the number of distinct subsets of tanks that the Bytelandian space agency can destroy in order to prevent Captain Bitonix from completing a patrol, modulo 109β+β7.ExamplesInput7 6 55 4 12 6 5Output6Input3 60 210 100Output4NoteAll the fuel tanks are distinct, even if some of them have the same capacity. | Input7 6 55 4 12 6 5 | Output6 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'combinatorics', 'dfs and similar', 'math', '*2900'] |
C. Formurosatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Bytelandian Institute for Biological Research (BIBR) is investigating the properties of two species of bacteria, named simply 0 and 1. Even under a microscope, bacteria of those two species are very difficult to distinguish. In fact, the only thing the scientists possess that is able to differentiate between them is a plant called Formurosa.If the scientists place a sample of colonies of bacteria on each on Formurosa's leaves, it will activate a complicated nutrition process. During that process color of Formurosa changes to reflect the result of a β possibly very complicated β logical formula on the species of bacteria, involving constants and the operators | (OR), & (AND) and ^ (XOR). If it is 0, the plant will turn red, otherwise β it will turn blue.For example, if the nutrition process of Formurosa is described by the formula: (((?^?)|?)&(1^?)); then Formurosa has four leaves (the "?" signs denote the leaves). If we place 0,β1,β0,β0 on the respective leaves, the result of the nutrition process will be (((0^1)|0)&(1^0))β=β1, therefore the plant will turn blue.The scientists have n colonies of bacteria. They do not know their types; the only thing they know for sure is that not all colonies are of the same type. They want to attempt to determine the bacteria's species by repeated evaluations with Formurosa. During each evaluation they must place exactly one sample on every leaf of the plant. However, they may use multiple samples of one colony during a single evaluation; they can even cover the whole plant with bacteria from one colony!Is it possible for them to always determine the species of each colony, no matter what they are (assuming they are not all the same)?InputThe first line of input contains a single integer n (2ββ€βnββ€β106) β the number of colonies of bacteria.The second line contains the formula describing the nutrition process of Formurosa. This line contains only characters Β«0Β», Β«1Β», Β«?Β», Β«|Β», Β«&Β», Β«^Β», Β«(Β», Β«)Β» and complies with the following grammar:sβββ0|1|?|(s|s)|(s&s)|(s^s)The formula consists of no more than 106 characters.OutputIf it is always possible to determine the species of each colony, output "YES" (without quotes). Otherwise, output "NO" (without quotes).ExamplesInput2(?^?)OutputNOInput10?OutputYESInput2((?^?)&?)OutputYES | Input2(?^?) | OutputNO | 1 second | 256 megabytes | ['divide and conquer', 'dp', 'expression parsing', '*2600'] |
B. Blackboard Fibonaccitime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFibonacci numbers are the sequence of integers: f0β=β0, f1β=β1, f2β=β1, f3β=β2, f4β=β3, f5β=β5, ..., fnβ=βfnβ-β2β+βfnβ-β1. So every next number is the sum of the previous two.Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he performs the following two operations: operation "T": replace the top number with the sum of both numbers; operation "B": replace the bottom number with the sum of both numbers. If he performs n operations, starting with "T" and then choosing operations alternately (so that the sequence of operations looks like "TBTBTBTB..."), the last number written will be equal to fnβ+β1.Unfortunately, Bajtek sometimes makes mistakes and repeats an operation two or more times in a row. For example, if Bajtek wanted to compute f7, then he would want to do nβ=β6 operations: "TBTBTB". If he instead performs the sequence of operations "TTTBBT", then he will have made 3 mistakes, and he will incorrectly compute that the seventh Fibonacci number is 10. The number of mistakes in the sequence of operations is the number of neighbouring equal operations (Β«TTΒ» or Β«BBΒ»).You are given the number n of operations that Bajtek has made in an attempt to compute fnβ+β1 and the number r that is the result of his computations (that is last written number). Find the minimum possible number of mistakes that Bajtek must have made and any possible sequence of n operations resulting in r with that number of mistakes.Assume that Bajtek always correctly starts with operation "T".InputThe first line contains the integers n and r (1ββ€βn,βrββ€β106).OutputThe first line of the output should contain one number β the minimum possible number of mistakes made by Bajtek. The second line should contain n characters, starting with "T", describing one possible sequence of operations with that number of mistakes. Each character must be either "T" or "B".If the required sequence doesn't exist, output "IMPOSSIBLE" (without quotes).ExamplesInput6 10Output2TBBTTBInput4 5Output0TBTBInput2 1OutputIMPOSSIBLE | Input6 10 | Output2TBBTTB | 1 second | 256 megabytes | ['brute force', 'math', '*2100'] |
A. Ice Skatingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.InputThe first line of input contains a single integer n (1ββ€βnββ€β100) β the number of snow drifts. Each of the following n lines contains two integers xi and yi (1ββ€βxi,βyiββ€β1000) β the coordinates of the i-th snow drift.Note that the north direction coinΡides with the direction of Oy axis, so the east direction coinΡides with the direction of the Ox axis. All snow drift's locations are distinct.OutputOutput the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.ExamplesInput22 11 2Output1Input22 14 1Output0 | Input22 11 2 | Output1 | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'dsu', 'graphs', '*1200'] |
E. Martian Lucktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou know that the Martians use a number system with base k. Digit b (0ββ€βbβ<βk) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year b (by Martian chronology).A digital root d(x) of number x is a number that consists of a single digit, resulting after cascading summing of all digits of number x. Word "cascading" means that if the first summing gives us a number that consists of several digits, then we sum up all digits again, and again, until we get a one digit number.For example, d(35047)β=βd((3β+β5β+β0β+β4)7)β=βd(157)β=βd((1β+β5)7)β=βd(67)β=β67. In this sample the calculations are performed in the 7-base notation.If a number's digital root equals b, the Martians also call this number lucky.You have string s, which consists of n digits in the k-base notation system. Your task is to find, how many distinct substrings of the given string are lucky numbers. Leading zeroes are permitted in the numbers.Note that substring s[i... j] of the string sβ=βa1a2... an (1ββ€βiββ€βjββ€βn) is the string aiaiβ+β1... aj. Two substrings s[i1... j1] and s[i2... j2] of the string s are different if either i1ββ βi2 or j1ββ βj2.InputThe first line contains three integers k, b and n (2ββ€βkββ€β109, 0ββ€βbβ<βk, 1ββ€βnββ€β105).The second line contains string s as a sequence of n integers, representing digits in the k-base notation: the i-th integer equals ai (0ββ€βaiβ<βk) β the i-th digit of string s. The numbers in the lines are space-separated.OutputPrint a single integer β the number of substrings that are lucky numbers.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput10 5 63 2 0 5 6 1Output5Input7 6 43 5 0 4Output1Input257 0 30 0 256Output3NoteIn the first sample the following substrings have the sought digital root: s[1... 2] = "3 2", s[1... 3] = "3 2 0", s[3... 4] = "0 5", s[4... 4] = "5" and s[2... 6] = "2 0 5 6 1". | Input10 5 63 2 0 5 6 1 | Output5 | 2 seconds | 256 megabytes | ['math', 'number theory', '*2000'] |
D. Spider's Webtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPaw the Spider is making a web. Web-making is a real art, Paw has been learning to do it his whole life. Let's consider the structure of the web. There are n main threads going from the center of the web. All main threads are located in one plane and divide it into n equal infinite sectors. The sectors are indexed from 1 to n in the clockwise direction. Sectors i and iβ+β1 are adjacent for every i, 1ββ€βiβ<βn. In addition, sectors 1 and n are also adjacent.Some sectors have bridge threads. Each bridge connects the two main threads that make up this sector. The points at which the bridge is attached to the main threads will be called attachment points. Both attachment points of a bridge are at the same distance from the center of the web. At each attachment point exactly one bridge is attached. The bridges are adjacent if they are in the same sector, and there are no other bridges between them.A cell of the web is a trapezoid, which is located in one of the sectors and is bounded by two main threads and two adjacent bridges. You can see that the sides of the cell may have the attachment points of bridges from adjacent sectors. If the number of attachment points on one side of the cell is not equal to the number of attachment points on the other side, it creates an imbalance of pulling forces on this cell and this may eventually destroy the entire web. We'll call such a cell unstable. The perfect web does not contain unstable cells.Unstable cells are marked red in the figure. Stable cells are marked green.Paw the Spider isn't a skillful webmaker yet, he is only learning to make perfect webs. Help Paw to determine the number of unstable cells in the web he has just spun.InputThe first line contains integer n (3ββ€βnββ€β1000) β the number of main threads.The i-th of following n lines describe the bridges located in the i-th sector: first it contains integer ki (1ββ€βkiββ€β105) equal to the number of bridges in the given sector. Then follow ki different integers pij (1ββ€βpijββ€β105;Β 1ββ€βjββ€βki). Number pij equals the distance from the attachment points of the j-th bridge of the i-th sector to the center of the web.It is guaranteed that any two bridges between adjacent sectors are attached at a different distance from the center of the web. It is guaranteed that the total number of the bridges doesn't exceed 105.OutputPrint a single integer β the number of unstable cells in Paw the Spider's web.ExamplesInput73 1 6 74 3 5 2 92 8 14 3 7 6 43 2 5 93 6 3 83 4 2 9Output6 | Input73 1 6 74 3 5 2 92 8 14 3 7 6 43 2 5 93 6 3 83 4 2 9 | Output6 | 2 seconds | 256 megabytes | ['binary search', 'sortings', 'two pointers', '*1700'] |
C. Hiring Stafftime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA new Berland businessman Vitaly is going to open a household appliances' store. All he's got to do now is to hire the staff.The store will work seven days a week, but not around the clock. Every day at least k people must work in the store.Berland has a law that determines the order of working days and non-working days. Namely, each employee must work for exactly n consecutive days, then rest for exactly m days, then work for n more days and rest for m more, and so on. Vitaly doesn't want to break the law. Fortunately, there is a loophole: the law comes into force on the day when the employee is hired. For example, if an employee is hired on day x, then he should work on days [x,βxβ+β1,β...,βxβ+βnβ-β1], [xβ+βmβ+βn,βxβ+βmβ+βnβ+β1,β...,βxβ+βmβ+β2nβ-β1], and so on. Day x can be chosen arbitrarily by Vitaly.There is one more thing: the key to the store. Berland law prohibits making copies of keys, so there is only one key. Vitaly is planning to entrust the key to the store employees. At the same time on each day the key must be with an employee who works that day β otherwise on this day no one can get inside the store. During the day the key holder can give the key to another employee, if he also works that day. The key will handed to the first hired employee at his first working day.Each employee has to be paid salary. Therefore, Vitaly wants to hire as few employees as possible provided that the store can operate normally on each day from 1 to infinity. In other words, on each day with index from 1 to infinity, the store must have at least k working employees, and one of the working employees should have the key to the store.Help Vitaly and determine the minimum required number of employees, as well as days on which they should be hired.InputThe first line contains three integers n, m and k (1ββ€βmββ€βnββ€β1000, nββ β1, 1ββ€βkββ€β1000).OutputIn the first line print a single integer z β the minimum required number of employees.In the second line print z positive integers, separated by spaces: the i-th integer ai (1ββ€βaiββ€β104) should represent the number of the day, on which Vitaly should hire the i-th employee.If there are multiple answers, print any of them.ExamplesInput4 3 2Output41 1 4 5Input3 3 1Output31 3 5 | Input4 3 2 | Output41 1 4 5 | 2 seconds | 256 megabytes | ['greedy', '*1800'] |
B. Forming Teamstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B is an archenemy to student A.The students want to split so as no two archenemies were in one team. If splitting in the required manner is impossible, some students will have to sit on the bench.Determine the minimum number of students you will have to send to the bench in order to form the two teams in the described manner and begin the game at last.InputThe first line contains two integers n and m (2ββ€βnββ€β100, 1ββ€βmββ€β100) β the number of students and the number of pairs of archenemies correspondingly.Next m lines describe enmity between students. Each enmity is described as two numbers ai and bi (1ββ€βai,βbiββ€βn, aiββ βbi) β the indexes of the students who are enemies to each other. Each enmity occurs in the list exactly once. It is guaranteed that each student has no more than two archenemies.You can consider the students indexed in some manner with distinct integers from 1 to n.OutputPrint a single integer β the minimum number of students you will have to send to the bench in order to start the game.ExamplesInput5 41 22 45 31 4Output1Input6 21 43 4Output0Input6 61 22 33 14 55 66 4Output2 | Input5 41 22 45 31 4 | Output1 | 2 seconds | 256 megabytes | ['dfs and similar', 'implementation', '*1700'] |
A. Tiling with Hexagonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSeveral ages ago Berland was a kingdom. The King of Berland adored math. That's why, when he first visited one of his many palaces, he first of all paid attention to the floor in one hall. The floor was tiled with hexagonal tiles.The hall also turned out hexagonal in its shape. The King walked along the perimeter of the hall and concluded that each of the six sides has a, b, c, a, b and c adjacent tiles, correspondingly.To better visualize the situation, look at the picture showing a similar hexagon for aβ=β2, bβ=β3 and cβ=β4. According to the legend, as the King of Berland obtained the values a, b and c, he almost immediately calculated the total number of tiles on the hall floor. Can you do the same?InputThe first line contains three integers: a, b and c (2ββ€βa,βb,βcββ€β1000).OutputPrint a single number β the total number of tiles on the hall floor.ExamplesInput2 3 4Output18 | Input2 3 4 | Output18 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1200'] |
E. Periodical Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA non-empty string s is called binary, if it consists only of characters "0" and "1". Let's number the characters of binary string s from 1 to the string's length and let's denote the i-th character in string s as si.Binary string s with length n is periodical, if there is an integer 1ββ€βkβ<βn such that: k is a divisor of number n for all 1ββ€βiββ€βnβ-βk, the following condition fulfills: siβ=βsiβ+βk For example, binary strings "101010" and "11" are periodical and "10" and "10010" are not.A positive integer x is periodical, if its binary representation (without leading zeroes) is a periodic string.Your task is to calculate, how many periodic numbers are in the interval from l to r (both ends are included).InputThe single input line contains two integers l and r (1ββ€βlββ€βrββ€β1018). The numbers are separated by a space.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.OutputPrint a single integer, showing how many periodic numbers are in the interval from l to r (both ends are included).ExamplesInput1 10Output3Input25 38Output2NoteIn the first sample periodic numbers are 3, 7 and 10.In the second sample periodic numbers are 31 and 36. | Input1 10 | Output3 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'number theory', '*2100'] |
D. Hot Daystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1ββ€βiββ€βn) region has a stable temperature of ti degrees in summer.This summer a group of m schoolchildren wants to get from the official capital to the cultural capital to visit museums and sights. The trip organizers transport the children between the cities in buses, but sometimes it is very hot. Specifically, if the bus is driving through the i-th region and has k schoolchildren, then the temperature inside the bus is tiβ+βk degrees.Of course, nobody likes it when the bus is hot. So, when the bus drives through the i-th region, if it has more than Ti degrees inside, each of the schoolchild in the bus demands compensation for the uncomfortable conditions. The compensation is as large as xi rubles and it is charged in each region where the temperature in the bus exceeds the limit.To save money, the organizers of the trip may arbitrarily add or remove extra buses in the beginning of the trip, and between regions (of course, they need at least one bus to pass any region). The organizers can also arbitrarily sort the children into buses, however, each of buses in the i-th region will cost the organizers costi rubles. Please note that sorting children into buses takes no money.Your task is to find the minimum number of rubles, which the organizers will have to spend to transport all schoolchildren.InputThe first input line contains two integers n and m (1ββ€βnββ€β105;Β 1ββ€βmββ€β106) β the number of regions on the way and the number of schoolchildren in the group, correspondingly. Next n lines contain four integers each: the i-th line contains ti, Ti, xi and costi (1ββ€βti,βTi,βxi,βcostiββ€β106). The numbers in the lines are separated by single spaces.OutputPrint the only integer β the minimum number of roubles the organizers will have to spend to transport all schoolchildren.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.ExamplesInput2 1030 35 1 10020 35 10 10Output120Input3 10010 30 1000 15 10 1000 310 40 1000 100000Output200065NoteIn the first sample the organizers will use only one bus to travel through the first region. However, the temperature in the bus will equal 30β+β10β=β40 degrees and each of 10 schoolchildren will ask for compensation. Only one bus will transport the group through the second region too, but the temperature inside won't exceed the limit. Overall, the organizers will spend 100β+β10β+β10β=β120 rubles. | Input2 1030 35 1 10020 35 10 10 | Output120 | 2 seconds | 256 megabytes | ['greedy', '*1900'] |
C. Crossestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a board with a grid consisting of n rows and m columns, the rows are numbered from 1 from top to bottom and the columns are numbered from 1 from left to right. In this grid we will denote the cell that lies on row number i and column number j as (i,βj).A group of six numbers (a,βb,βc,βd,βx0,βy0), where 0ββ€βa,βb,βc,βd, is a cross, and there is a set of cells that are assigned to it. Cell (x,βy) belongs to this set if at least one of two conditions are fulfilled: |x0β-βx|ββ€βa and |y0β-βy|ββ€βb |x0β-βx|ββ€βc and |y0β-βy|ββ€βd The picture shows the cross (0,β1,β1,β0,β2,β3) on the grid 3βΓβ4. Your task is to find the number of different groups of six numbers, (a,βb,βc,βd,βx0,βy0) that determine the crosses of an area equal to s, which are placed entirely on the grid. The cross is placed entirely on the grid, if any of its cells is in the range of the grid (that is for each cell (x,βy) of the cross 1ββ€βxββ€βn;Β 1ββ€βyββ€βm holds). The area of the cross is the number of cells it has.Note that two crosses are considered distinct if the ordered groups of six numbers that denote them are distinct, even if these crosses coincide as sets of points.InputThe input consists of a single line containing three integers n, m and s (1ββ€βn,βmββ€β500, 1ββ€βsββ€βnΒ·m). The integers are separated by a space.OutputPrint a single integer β the number of distinct groups of six integers that denote crosses with area s and that are fully placed on the nβΓβm grid.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.ExamplesInput2 2 1Output4Input3 4 5Output4NoteIn the first sample the sought groups of six numbers are: (0,β0,β0,β0,β1,β1), (0,β0,β0,β0,β1,β2), (0,β0,β0,β0,β2,β1), (0,β0,β0,β0,β2,β2).In the second sample the sought groups of six numbers are: (0,β1,β1,β0,β2,β2), (0,β1,β1,β0,β2,β3), (1,β0,β0,β1,β2,β2), (1,β0,β0,β1,β2,β3). | Input2 2 1 | Output4 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*2100'] |
B. Olympic Medaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0β<βr2β<βr1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested inside the ring.The Olympic jury decided that r1 will take one of possible values of x1,βx2,β...,βxn. It is up to jury to decide which particular value r1 will take. Similarly, the Olympic jury decided that p1 will take one of possible value of y1,βy2,β...,βym, and p2 will take a value from list z1,βz2,β...,βzk.According to most ancient traditions the ratio between the outer ring mass mout and the inner disk mass min must equal , where A,βB are constants taken from ancient books. Now, to start making medals, the jury needs to take values for r1, p1, p2 and calculate the suitable value of r2.The jury wants to choose the value that would maximize radius r2. Help the jury find the sought value of r2. Value r2 doesn't have to be an integer.Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.InputThe first input line contains an integer n and a sequence of integers x1,βx2,β...,βxn. The second input line contains an integer m and a sequence of integers y1,βy2,β...,βym. The third input line contains an integer k and a sequence of integers z1,βz2,β...,βzk. The last line contains two integers A and B.All numbers given in the input are positive and do not exceed 5000. Each of the three sequences contains distinct numbers. The numbers in the lines are separated by spaces.OutputPrint a single real number β the sought value r2 with absolute or relative error of at most 10β-β6. It is guaranteed that the solution that meets the problem requirements exists.ExamplesInput3 1 2 31 23 3 2 11 2Output2.683281573000Input4 2 3 6 42 1 23 10 6 82 1Output2.267786838055NoteIn the first sample the jury should choose the following values: r1β=β3, p1β=β2, p2β=β1. | Input3 1 2 31 23 3 2 11 2 | Output2.683281573000 | 2 seconds | 256 megabytes | ['greedy', 'math', '*1300'] |
A. Bicycle Chaintime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0β<βa1β<βa2β<β...β<βan) teeth, and the j-th star on the rear wheel axle has bj (0β<βb1β<βb2β<β...β<βbm) teeth. Any pair (i,βj) (1ββ€βiββ€βn;Β 1ββ€βjββ€βm) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i,βj) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i,βj), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i,βj) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction denotes division in real numbers, that is, no rounding is performed.InputThe first input line contains integer n (1ββ€βnββ€β50) β the number of stars on the bicycle's pedal axle. The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β104) in the order of strict increasing.The third input line contains integer m (1ββ€βmββ€β50) β the number of stars on the rear wheel axle. The fourth line contains m integers b1,βb2,β...,βbm (1ββ€βbiββ€β104) in the order of strict increasing.It is guaranteed that there exists at least one gear (i,βj), that its gear ratio is an integer. The numbers on the lines are separated by spaces.OutputPrint the number of "integer" gears with the maximum ratio among all "integer" gears.ExamplesInput24 5312 13 15Output2Input41 2 3 4510 11 12 13 14Output1NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1β=β4,βb1β=β12, and for the other a2β=β5,βb3β=β15. | Input24 5312 13 15 | Output2 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*900'] |
B. Hometasktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFurik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.InputA single line contains a single integer n (1ββ€βnββ€β100000) β the number of digits in the set. The second line contains n digits, the digits are separated by a single space. OutputOn a single line print the answer to the problem. If such number does not exist, then you should print -1.ExamplesInput10Output0Input113 4 5 4 5 3 5 3 4 4 0Output5554443330Input83 2 5 1 5 2 2 3Output-1NoteIn the first sample there is only one number you can make β 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Input10 | Output0 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'math', '*1600'] |
A. System of Equationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFurik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a system of equations: You should count, how many there are pairs of integers (a,βb) (0ββ€βa,βb) which satisfy the system.InputA single line contains two integers n,βm (1ββ€βn,βmββ€β1000) β the parameters of the system. The numbers on the line are separated by a space.OutputOn a single line print the answer to the problem.ExamplesInput9 3Output1Input14 28Output1Input4 20Output0NoteIn the first sample the suitable pair is integers (3,β0). In the second sample the suitable pair is integers (3,β5). In the third sample there is no suitable pair. | Input9 3 | Output1 | 2 seconds | 256 megabytes | ['brute force', '*800'] |
E. Two Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRubik is very keen on number permutations. A permutation a with length n is a sequence, consisting of n different numbers from 1 to n. Element number i (1ββ€βiββ€βn) of this permutation will be denoted as ai.Furik decided to make a present to Rubik and came up with a new problem on permutations. Furik tells Rubik two number permutations: permutation a with length n and permutation b with length m. Rubik must give an answer to the problem: how many distinct integers d exist, such that sequence c (c1β=βa1β+βd,βc2β=βa2β+βd,β...,βcnβ=βanβ+βd) of length n is a subsequence of b.Sequence a is a subsequence of sequence b, if there are such indices i1,βi2,β...,βin (1ββ€βi1β<βi2β<β...β<βinββ€βm), that a1β=βbi1, a2β=βbi2, ..., anβ=βbin, where n is the length of sequence a, and m is the length of sequence b. You are given permutations a and b, help Rubik solve the given problem.InputThe first line contains two integers n and m (1ββ€βnββ€βmββ€β200000) β the sizes of the given permutations. The second line contains n distinct integers β permutation a, the third line contains m distinct integers β permutation b. Numbers on the lines are separated by spaces.OutputOn a single line print the answer to the problem. ExamplesInput1 111Output1Input1 212 1Output2Input3 32 3 11 2 3Output0 | Input1 111 | Output1 | 2 seconds | 256 megabytes | ['data structures', 'hashing', 'strings', '*2700'] |
D. Starstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFurik loves painting stars. A star is a shape that results if we take a regular pentagon and paint all diagonals in it. Recently he decided to teach Rubik to paint stars. After many years of training Rubik could paint stars easily. But now Furik decided to test Rubik and complicated the task. Rubik must paint n stars, observing the following rules: all stars must be painted in a single move (i.e. it is forbidden to take the pen away from the paper); it is forbidden to paint the same segment of non-zero length more than once; the stars can intersect only in their vertexes; the length of a side of the regular pentagon, in which Rubik paints each star, must equal 10. Help Rubik to cope with this hard task.InputA single line contains an integer (1ββ€βnββ€β100) β the number of stars to paint.OutputOn the first line print an integer m (1ββ€βmββ€β5Β·n). On the next m lines print coordinates of m distinct points with accuracy of at least 9 and at most 100 digits after decimal point. All coordinates should not exceed 5000 in their absolute value. On each of the next n lines print 5 integers β the indexes of the points that form the given star in the clockwise or counterclockwise order. On the next line print 5Β·nβ+β1 integers β the numbers of points in the order, in which Rubik paints stars. That is, if number with index i is ai, and number with index iβ+β1 is aiβ+β1, then points with indexes ai and aiβ+β1 will have a segment painted between them. You can consider all m printed points indexed from 1 to m in the order, in which they occur in the output. Separate the numbers on the lines with whitespaces.Note that the answer has an imprecise validation. Try to obtain as accurate a solution as possible. The validator performs all calculations considering that the absolute error of a participant's answer is not more than 10β-β8.ExamplesInput1Output53.830127018922193 3.366025403784439-3.601321235851749 10.0573314673730210.466045194906253 19.19278604379903010.411264148588986 18.14750141112249512.490381056766580 8.3660254037844391 2 3 4 51 3 5 2 4 1NoteThe initial position of points in the sample is: The order in which Rubik can paint segments is: | Input1 | Output53.830127018922193 3.366025403784439-3.601321235851749 10.0573314673730210.466045194906253 19.19278604379903010.411264148588986 18.14750141112249512.490381056766580 8.3660254037844391 2 3 4 51 3 5 2 4 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'geometry', '*2300'] |
C. Relay Racetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFurik and Rubik take part in a relay race. The race will be set up on a large square with the side of n meters. The given square is split into nβΓβn cells (represented as unit squares), each cell has some number.At the beginning of the race Furik stands in a cell with coordinates (1,β1), and Rubik stands in a cell with coordinates (n,βn). Right after the start Furik runs towards Rubik, besides, if Furik stands at a cell with coordinates (i,βj), then he can move to cell (iβ+β1,βj) or (i,βjβ+β1). After Furik reaches Rubik, Rubik starts running from cell with coordinates (n,βn) to cell with coordinates (1,β1). If Rubik stands in cell (i,βj), then he can move to cell (iβ-β1,βj) or (i,βjβ-β1). Neither Furik, nor Rubik are allowed to go beyond the boundaries of the field; if a player goes beyond the boundaries, he will be disqualified. To win the race, Furik and Rubik must earn as many points as possible. The number of points is the sum of numbers from the cells Furik and Rubik visited. Each cell counts only once in the sum.Print the maximum number of points Furik and Rubik can earn on the relay race.InputThe first line contains a single integer (1ββ€βnββ€β300). The next n lines contain n integers each: the j-th number on the i-th line ai,βj (β-β1000ββ€βai,βjββ€β1000) is the number written in the cell with coordinates (i,βj).OutputOn a single line print a single number β the answer to the problem. ExamplesInput15Output5Input211 1416 12Output53Input325 16 2512 18 1911 13 8Output136NoteComments to the second sample: The profitable path for Furik is: (1,β1), (1,β2), (2,β2), and for Rubik: (2,β2), (2,β1), (1,β1). Comments to the third sample: The optimal path for Furik is: (1,β1), (1,β2), (1,β3), (2,β3), (3,β3), and for Rubik: (3,β3), (3,β2), (2,β2), (2,β1), (1,β1). The figure to the sample: Furik's path is marked with yellow, and Rubik's path is marked with pink. | Input15 | Output5 | 4 seconds | 256 megabytes | ['dp', '*2000'] |
B. Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFurik loves writing all sorts of problems, especially such that he can't solve himself. You've got one of his problems, the one Furik gave to Rubik. And Rubik asks you to solve it.There is integer n and array a, consisting of ten integers, indexed by numbers from 0 to 9. Your task is to count the number of positive integers with the following properties: the number's length does not exceed n; the number doesn't have leading zeroes; digit i (0ββ€βiββ€β9) occurs in the number at least a[i] times. InputThe first line contains integer n (1ββ€βnββ€β100). The next line contains 10 integers a[0], a[1], ..., a[9] (0ββ€βa[i]ββ€β100) β elements of array a. The numbers are separated by spaces.OutputOn a single line print the remainder of dividing the answer to the problem by 1000000007 (109β+β7).ExamplesInput10 0 0 0 0 0 0 0 0 1Output1Input21 1 0 0 0 0 0 0 0 0Output1Input31 1 0 0 0 0 0 0 0 0Output36NoteIn the first sample number 9 meets the requirements.In the second sample number 10 meets the requirements.In the third sample numbers 10, 110, 210, 120, 103 meet the requirements. There are other suitable numbers, 36 in total. | Input10 0 0 0 0 0 0 0 0 1 | Output1 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', '*1900'] |
A. Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFurik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies. Rubik has 3 computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from 1 to 3. Rubik can perform the following actions: Complete some part of the game on some computer. Rubik spends exactly 1 hour on completing any part on any computer. Move from the 1-st computer to the 2-nd one. Rubik spends exactly 1 hour on that. Move from the 1-st computer to the 3-rd one. Rubik spends exactly 2 hours on that. Move from the 2-nd computer to the 1-st one. Rubik spends exactly 2 hours on that. Move from the 2-nd computer to the 3-rd one. Rubik spends exactly 1 hour on that. Move from the 3-rd computer to the 1-st one. Rubik spends exactly 1 hour on that. Move from the 3-rd computer to the 2-nd one. Rubik spends exactly 2 hours on that. Help Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary. InputThe first line contains integer n (1ββ€βnββ€β200) β the number of game parts. The next line contains n integers, the i-th integer β ci (1ββ€βciββ€β3) represents the number of the computer, on which you can complete the game part number i. Next n lines contain descriptions of game parts. The i-th line first contains integer ki (0ββ€βkiββ€βnβ-β1), then ki distinct integers ai,βj (1ββ€βai,βjββ€βn;Β ai,βjββ βi) β the numbers of parts to complete before part i.Numbers on all lines are separated by single spaces. You can assume that the parts of the game are numbered from 1 to n in some way. It is guaranteed that there are no cyclic dependencies between the parts of the game.OutputOn a single line print the answer to the problem.ExamplesInput110Output1Input52 2 1 1 31 52 5 12 5 41 50Output7NoteNote to the second sample: before the beginning of the game the best strategy is to stand by the third computer. First we complete part 5. Then we go to the 1-st computer and complete parts 3 and 4. Then we go to the 2-nd computer and complete parts 1 and 2. In total we get 1+1+2+1+2, which equals 7 hours. | Input110 | Output1 | 1 second | 256 megabytes | ['dfs and similar', 'greedy', '*1700'] |
E. IT Restaurantstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputΠ‘ity N. has a huge problem with roads, food and IT-infrastructure. In total the city has n junctions, some pairs of them are connected by bidirectional roads. The road network consists of nβ-β1 roads, you can get from any junction to any other one by these roads. Yes, you're right β the road network forms an undirected tree.Recently, the Mayor came up with a way that eliminates the problems with the food and the IT-infrastructure at the same time! He decided to put at the city junctions restaurants of two well-known cafe networks for IT professionals: "iMac D0naldz" and "Burger Bing". Since the network owners are not friends, it is strictly prohibited to place two restaurants of different networks on neighboring junctions. There are other requirements. Here's the full list: each junction must have at most one restaurant; each restaurant belongs either to "iMac D0naldz", or to "Burger Bing"; each network should build at least one restaurant; there is no pair of junctions that are connected by a road and contains restaurants of different networks. The Mayor is going to take a large tax from each restaurant, so he is interested in making the total number of the restaurants as large as possible.Help the Mayor to analyze the situation. Find all such pairs of (a,βb) that a restaurants can belong to "iMac D0naldz", b restaurants can belong to "Burger Bing", and the sum of aβ+βb is as large as possible.InputThe first input line contains integer n (3ββ€βnββ€β5000) β the number of junctions in the city. Next nβ-β1 lines list all roads one per line. Each road is given as a pair of integers xi,βyi (1ββ€βxi,βyiββ€βn) β the indexes of connected junctions. Consider the junctions indexed from 1 to n.It is guaranteed that the given road network is represented by an undirected tree with n vertexes.OutputPrint on the first line integer z β the number of sought pairs. Then print all sought pairs (a,βb) in the order of increasing of the first component a.ExamplesInput51 22 33 44 5Output31 32 23 1Input101 22 33 45 66 77 48 99 1010 4Output61 82 73 66 37 28 1NoteThe figure below shows the answers to the first test case. The junctions with "iMac D0naldz" restaurants are marked red and "Burger Bing" restaurants are marked blue. | Input51 22 33 44 5 | Output31 32 23 1 | 1.5 seconds | 256 megabytes | ['dfs and similar', 'dp', 'trees', '*1500'] |
D. Cutting a Fencetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya the carpenter has an estate that is separated from the wood by a fence. The fence consists of n planks put in a line. The fence is not closed in a circle. The planks are numbered from left to right from 1 to n, the i-th plank is of height ai. All planks have the same width, the lower edge of each plank is located at the ground level.Recently a local newspaper "Malevich and Life" wrote that the most fashionable way to decorate a fence in the summer is to draw a fuchsia-colored rectangle on it, the lower side of the rectangle must be located at the lower edge of the fence.Vasya is delighted with this idea! He immediately bought some fuchsia-colored paint and began to decide what kind of the rectangle he should paint. Vasya is sure that the rectangle should cover k consecutive planks. In other words, he will paint planks number x, xβ+β1, ..., xβ+βkβ-β1 for some x (1ββ€βxββ€βnβ-βkβ+β1). He wants to paint the rectangle of maximal area, so the rectangle height equals min ai for xββ€βiββ€βxβ+βkβ-β1, x is the number of the first colored plank.Vasya has already made up his mind that the rectangle width can be equal to one of numbers of the sequence k1,βk2,β...,βkm. For each ki he wants to know the expected height of the painted rectangle, provided that he selects x for such fence uniformly among all nβ-βkiβ+β1 possible values. Help him to find the expected heights.InputThe first line contains a single integer n (1ββ€βnββ€β106) β the number of planks in the fence. The second line contains a sequence of integers a1,βa2,β...,βan (1ββ€βaiββ€β109) where ai is the height of the i-th plank of the fence.The third line contains an integer m (1ββ€βmββ€β106) and the next line contains m space-separated integers k1,βk2,β...,βkm (1ββ€βkiββ€βn) where ki is the width of the desired fuchsia-colored rectangle in planks.OutputPrint m whitespace-separated real numbers, the i-th number equals the expected value of the rectangle height, if its width in planks equals ki. The value will be considered correct if its absolute or relative error doesn't exceed 10β-β9.ExamplesInput33 2 131 2 3Output2.0000000000000001.5000000000000001.000000000000000Input21 131 2 1Output1.0000000000000001.0000000000000001.000000000000000NoteLet's consider the first sample test. There are three possible positions of the fence for k1β=β1. For the first position (xβ=β1) the height is 3, for the second one (xβ=β2) the height is 2, for the third one (xβ=β3) the height is 1. As the fence position is chosen uniformly, the expected height of the fence equals ; There are two possible positions of the fence for k2β=β2. For the first position (xβ=β1) the height is 2, for the second one (xβ=β2) the height is 1. The expected height of the fence equals ; There is the only possible position of the fence for k3β=β3. The expected height of the fence equals 1. | Input33 2 131 2 3 | Output2.0000000000000001.5000000000000001.000000000000000 | 5 seconds | 256 megabytes | ['binary search', 'data structures', 'dsu', '*2500'] |
C. Cowboystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA very tense moment: n cowboys stand in a circle and each one points his colt at a neighbor. Each cowboy can point the colt to the person who follows or precedes him in clockwise direction. Human life is worthless, just like in any real western.The picture changes each second! Every second the cowboys analyse the situation and, if a pair of cowboys realize that they aim at each other, they turn around. In a second all such pairs of neighboring cowboys aiming at each other turn around. All actions happen instantaneously and simultaneously in a second.We'll use character "A" to denote a cowboy who aims at his neighbour in the clockwise direction, and character "B" for a cowboy who aims at his neighbour in the counter clockwise direction. Then a string of letters "A" and "B" will denote the circle of cowboys, the record is made from the first of them in a clockwise direction.For example, a circle that looks like "ABBBABBBA" after a second transforms into "BABBBABBA" and a circle that looks like "BABBA" transforms into "ABABB". This picture illustrates how the circle "BABBA" transforms into "ABABB" A second passed and now the cowboys' position is described by string s. Your task is to determine the number of possible states that lead to s in a second. Two states are considered distinct if there is a cowboy who aims at his clockwise neighbor in one state and at his counter clockwise neighbor in the other state.InputThe input data consists of a single string s. Its length is from 3 to 100 characters, inclusive. Line s consists of letters "A" and "B".OutputPrint the sought number of states.ExamplesInputBABBBABBAOutput2InputABABBOutput2InputABABABOutput4NoteIn the first sample the possible initial states are "ABBBABBAB" and "ABBBABBBA".In the second sample the possible initial states are "AABBB" and "BABBA". | InputBABBBABBA | Output2 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', '*2100'] |
B. Polycarpus is Looking for Good Substringstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe'll call string s[a,βb]β=βsasaβ+β1... sb (1ββ€βaββ€βbββ€β|s|) a substring of string sβ=βs1s2... s|s|, where |s| is the length of string s.The trace of a non-empty string t is a set of characters that the string consists of. For example, the trace of string "aab" equals {'a', 'b'}.Let's consider an arbitrary string s and the set of its substrings with trace equal to C. We will denote the number of substrings from this set that are maximal by inclusion by r(C,βs). Substring s[a,βb] of length nβ=βbβ-βaβ+β1 belonging to some set is called maximal by inclusion, if there is no substring s[x,βy] in this set with length greater than n, such that 1ββ€βxββ€βaββ€βbββ€βyββ€β|s|. Two substrings of string s are considered different even if they are equal but they are located at different positions of s.Polycarpus got a challenging practical task on a stringology exam. He must do the following: given string s and non-empty sets of characters C1, C2, ..., Cm, find r(Ci,βs) for each set Ci. Help Polycarpus to solve the problem as he really doesn't want to be expelled from the university and go to the army!InputThe first line contains a non-empty string s (1ββ€β|s|ββ€β106).The second line contains a single integer m (1ββ€βmββ€β104). Next m lines contain descriptions of sets Ci. The i-th line contains string ci such that its trace equals Ci. It is guaranteed that all characters of each string ci are different.Note that Ci are not necessarily different. All given strings consist of lowercase English letters.OutputPrint m integers β the i-th integer must equal r(Ci,βs).ExamplesInputaaaaa2aaOutput11Inputabacaba3acbaaOutput124 | Inputaaaaa2aa | Output11 | 4 seconds | 256 megabytes | ['bitmasks', 'hashing', 'implementation', '*2300'] |
A. Privatizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a developed network of flights between Berland and Beerland. All of them belong to the Berland state company BerAvia. Each flight connects some Berland city with some Beerland city. For each flight airplanes fly in both directions.Changes are coming to Berland β the state decided to privatize BerAvia, namely, to sell out all flights to t private companies. Each of these companies wants to get the maximal number of flights, so if the Berland flights are sold unevenly, Berland can be accused of partiality. Berland Government decided to sell the flights as evenly as possible between the t companies.The unevenness of the distribution of flights between companies is calculated as follows. For each city i (both Berland and Beerland) we'll calculate the value of where aij is the number of flights from city i, which belong to company j. The sum of wi for all cities in both countries is called the unevenness of the distribution. The distribution with the minimal unevenness is the most even one.Help the Berland government come up with the most even distribution plan of selling flights.InputThe first input line contains four integers n,βm,βk and t (1ββ€βn,βm,βtββ€β200;1ββ€βkββ€β5000), where n,βm are the numbers of cities in Berland and Beerland, correspondingly, k is the number of flights between them, and t is the number of private companies. Next k lines describe the flights, one per line, as pairs of positive integers xi,βyi (1ββ€βxiββ€βn;1ββ€βyiββ€βm), where xi and yi are the indexes of cities in Berland and Beerland, correspondingly, connected by the i-th flight. There is at most one flight between any pair of cities, each flight connects cities of different countries. The cities in Berland are indexed from 1 to n, and in Beerland β from 1 to m.OutputPrint the unevenness of the sought plan on the first line. On the second line print a sequence of k integers c1,βc2,β...,βck (1ββ€βciββ€βt), where ci is the index of the company that should buy the i-th flight. Assume that the flights are indexed from 1 to k in the order they appear in the input. If there are multiple solutions, print any of them.ExamplesInput3 5 8 21 41 33 31 21 12 11 52 2Output42 1 2 1 2 1 2 2 | Input3 5 8 21 41 33 31 21 12 11 52 2 | Output42 1 2 1 2 1 2 2 | 2 seconds | 256 megabytes | ['flows', 'graphs', '*3000'] |
C. Trails and Gladestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya went for a walk in the park. The park has n glades, numbered from 1 to n. There are m trails between the glades. The trails are numbered from 1 to m, where the i-th trail connects glades xi and yi. The numbers of the connected glades may be the same (xiβ=βyi), which means that a trail connects a glade to itself. Also, two glades may have several non-intersecting trails between them.Vasya is on glade 1, he wants to walk on all trails of the park exactly once, so that he can eventually return to glade 1. Unfortunately, Vasya does not know whether this walk is possible or not. Help Vasya, determine whether the walk is possible or not. If such walk is impossible, find the minimum number of trails the authorities need to add to the park in order to make the described walk possible.Vasya can shift from one trail to another one only on glades. He can move on the trails in both directions. If Vasya started going on the trail that connects glades a and b, from glade a, then he must finish this trail on glade b.InputThe first line contains two integers n and m (1ββ€βnββ€β106;Β 0ββ€βmββ€β106) β the number of glades in the park and the number of trails in the park, respectively. Next m lines specify the trails. The i-th line specifies the i-th trail as two space-separated numbers, xi, yi (1ββ€βxi,βyiββ€βn) β the numbers of the glades connected by this trail.OutputPrint the single integer β the answer to the problem. If Vasya's walk is possible without adding extra trails, print 0, otherwise print the minimum number of trails the authorities need to add to the park in order to make Vasya's walk possible. ExamplesInput3 31 22 33 1Output0Input2 51 11 21 22 21 2Output1NoteIn the first test case the described walk is possible without building extra trails. For example, let's first go on the first trail, then on the second one, and finally on the third one.In the second test case the described walk is impossible without adding extra trails. To make the walk possible, it is enough to add one trail, for example, between glades number one and two. | Input3 31 22 33 1 | Output0 | 4 seconds | 256 megabytes | ['constructive algorithms', 'dsu', 'graphs', 'greedy', '*2400'] |
B. Pixelstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFlatland is inhabited by pixels of three colors: red, green and blue. We know that if two pixels of different colors meet in a violent fight, only one of them survives the fight (that is, the total number of pixels decreases by one). Besides, if pixels of colors x and y (xββ βy) meet in a violent fight, then the pixel that survives the fight immediately changes its color to z (zββ βx;Β zββ βy). Pixels of the same color are friends, so they don't fight.The King of Flatland knows that his land will be peaceful and prosperous when the pixels are of the same color. For each of the three colors you know the number of pixels of this color that inhabit Flatland. Help the king and determine whether fights can bring peace and prosperity to the country and if it is possible, find the minimum number of fights needed to make the land peaceful and prosperous. InputThe first line contains three space-separated integers a, b and c (0ββ€βa,βb,βcββ€β231;Β aβ+βbβ+βcβ>β0) β the number of red, green and blue pixels, correspondingly.OutputPrint a single number β the minimum number of pixel fights before the country becomes peaceful and prosperous. If making the country peaceful and prosperous is impossible, print -1.ExamplesInput1 1 1Output1Input3 1 0Output3NoteIn the first test sample the country needs only one fight to achieve peace and prosperity. Besides, it can be any fight whatsoever. For example, let's assume that the green and the blue pixels fight, then the surviving pixel will be red. As a result, after the fight there are two red pixels. There won't be other pixels.In the second sample the following sequence of fights is possible: red and blue, green and red, red and blue. As a result, after all fights there is one green pixel left. | Input1 1 1 | Output1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*2100'] |
A. Multicolored Marblestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus plays with red and blue marbles. He put n marbles from the left to the right in a row. As it turned out, the marbles form a zebroid.A non-empty sequence of red and blue marbles is a zebroid, if the colors of the marbles in this sequence alternate. For example, sequences (red; blue; red) and (blue) are zebroids and sequence (red; red) is not a zebroid.Now Polycarpus wonders, how many ways there are to pick a zebroid subsequence from this sequence. Help him solve the problem, find the number of ways modulo 1000000007 (109β+β7).InputThe first line contains a single integer n (1ββ€βnββ€β106) β the number of marbles in Polycarpus's sequence.OutputPrint a single number β the answer to the problem modulo 1000000007 (109β+β7).ExamplesInput3Output6Input4Output11NoteLet's consider the first test sample. Let's assume that Polycarpus initially had sequence (red; blue; red), so there are six ways to pick a zebroid: pick the first marble; pick the second marble; pick the third marble; pick the first and second marbles; pick the second and third marbles; pick the first, second and third marbles. It can be proven that if Polycarpus picks (blue; red; blue) as the initial sequence, the number of ways won't change. | Input3 | Output6 | 2 seconds | 256 megabytes | ['dp', 'math', '*1600'] |
E. Blood Cousinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus got hold of a family relationship tree. The tree describes family relationships of n people, numbered 1 through n. Each person in the tree has no more than one parent.Let's call person a a 1-ancestor of person b, if a is the parent of b.Let's call person a a k-ancestor (kβ>β1) of person b, if person b has a 1-ancestor, and a is a (kβ-β1)-ancestor of b's 1-ancestor. Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an x-ancestor for himself, for some x, xβ>β0).Let's call two people x and y (xββ βy) p-th cousins (pβ>β0), if there is person z, who is a p-ancestor of x and a p-ancestor of y.Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote m pairs of integers vi, pi. Help him to calculate the number of pi-th cousins that person vi has, for each pair vi, pi.InputThe first input line contains a single integer n (1ββ€βnββ€β105) β the number of people in the tree. The next line contains n space-separated integers r1,βr2,β...,βrn, where ri (1ββ€βriββ€βn) is the number of person i's parent or 0, if person i has no parent. It is guaranteed that family relationships don't form cycles.The third line contains a single number m (1ββ€βmββ€β105) β the number of family relationship queries Polycarus has. Next m lines contain pairs of space-separated integers. The i-th line contains numbers vi, pi (1ββ€βvi,βpiββ€βn).OutputPrint m space-separated integers β the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.ExamplesInput60 1 1 0 4 471 11 22 12 24 15 16 1Output0 0 1 0 0 1 1 | Input60 1 1 0 4 471 11 22 12 24 15 16 1 | Output0 0 1 0 0 1 1 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', 'trees', '*2100'] |
D. Prizes, Prizes, more Prizestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it β the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy β as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost): a mug (costs a points), a towel (costs b points), a bag (costs c points), a bicycle (costs d points), a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1,βp2,β...,βpn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.InputThe first line contains a single integer n (1ββ€βnββ€β50) β the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1,βp2,β...,βpn (1ββ€βpiββ€β109). The third line contains 5 integers a, b, c, d, e (1ββ€βaβ<βbβ<βcβ<βdβ<βeββ€β109) β the prizes' costs.OutputPrint on the first line 5 integers, separated by a space β the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer β the number of points Vasya will have left after all operations of exchange are completed.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.ExamplesInput33 10 42 4 10 15 20Output1 1 1 0 0 1Input410 4 39 23 5 10 11 12Output3 0 1 0 3 0NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3β-β2β+β10β-β10β+β4β-β4β=β1 points remains. | Input33 10 42 4 10 15 20 | Output1 1 1 0 0 1 | 2 seconds | 256 megabytes | ['implementation', '*1200'] |
C. Police Stationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Berland road network consists of n cities and of m bidirectional roads. The cities are numbered from 1 to n, where the main capital city has number n, and the culture capital β number 1. The road network is set up so that it is possible to reach any city from any other one by the roads. Moving on each road in any direction takes the same time.All residents of Berland are very lazy people, and so when they want to get from city v to city u, they always choose one of the shortest paths (no matter which one).The Berland government wants to make this country's road network safer. For that, it is going to put a police station in one city. The police station has a rather strange property: when a citizen of Berland is driving along the road with a police station at one end of it, the citizen drives more carefully, so all such roads are considered safe. The roads, both ends of which differ from the city with the police station, are dangerous.Now the government wonders where to put the police station so that the average number of safe roads for all the shortest paths from the cultural capital to the main capital would take the maximum value.InputThe first input line contains two integers n and m (2ββ€βnββ€β100, ) β the number of cities and the number of roads in Berland, correspondingly. Next m lines contain pairs of integers vi, ui (1ββ€βvi,βuiββ€βn, viββ βui) β the numbers of cities that are connected by the i-th road. The numbers on a line are separated by a space. It is guaranteed that each pair of cities is connected with no more than one road and that it is possible to get from any city to any other one along Berland roads.OutputPrint the maximum possible value of the average number of safe roads among all shortest paths from the culture capital to the main one. The answer will be considered valid if its absolute or relative inaccuracy does not exceed 10β-β6.ExamplesInput4 41 22 41 33 4Output1.000000000000Input11 141 21 32 43 44 54 65 116 111 88 99 711 71 1010 4Output1.714285714286NoteIn the first sample you can put a police station in one of the capitals, then each path will have exactly one safe road. If we place the station not in the capital, then the average number of safe roads will also make .In the second sample we can obtain the maximum sought value if we put the station in city 4, then 6 paths will have 2 safe roads each, and one path will have 0 safe roads, so the answer will equal . | Input4 41 22 41 33 4 | Output1.000000000000 | 2 seconds | 256 megabytes | ['dp', 'graphs', 'shortest paths', '*1900'] |
B. Solitairetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA boy named Vasya wants to play an old Russian solitaire called "Accordion". In this solitaire, the player must observe the following rules: A deck of n cards is carefully shuffled, then all n cards are put on the table in a line from left to right; Before each move the table has several piles of cards lying in a line (initially there are n piles, each pile has one card). Let's number the piles from left to right, from 1 to x. During one move, a player can take the whole pile with the maximum number x (that is the rightmost of remaining) and put it on the top of pile xβ-β1 (if it exists) or on the top of pile xβ-β3 (if it exists). The player can put one pile on top of another one only if the piles' top cards have the same suits or values. Please note that if pile x goes on top of pile y, then the top card of pile x becomes the top card of the resulting pile. Also note that each move decreases the total number of piles by 1; The solitaire is considered completed if all cards are in the same pile. Vasya has already shuffled the cards and put them on the table, help him understand whether completing this solitaire is possible or not. InputThe first input line contains a single integer n (1ββ€βnββ€β52) β the number of cards in Vasya's deck. The next line contains n space-separated strings c1,βc2,β...,βcn, where string ci describes the i-th card on the table. Each string ci consists of exactly two characters, the first one represents the card's value, the second one represents its suit. Cards on the table are numbered from left to right. A card's value is specified by one of these characters: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A". A card's suit is specified by one of these characters: "S", "D", "H", "C".It is not guaranteed that the deck has all possible cards. Also, the cards in Vasya's deck can repeat.OutputOn a single line print the answer to the problem: string "YES" (without the quotes) if completing the solitaire is possible, string "NO" (without the quotes) otherwise.ExamplesInput42S 2S 2C 2COutputYESInput23S 2COutputNONoteIn the first sample you can act like that: put the 4-th pile on the 1-st one; put the 3-rd pile on the 2-nd one; put the 2-nd pile on the 1-st one. In the second sample there is no way to complete the solitaire. | Input42S 2S 2C 2C | OutputYES | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', '*1900'] |
A. Dubsteptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.InputThe input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters. It is guaranteed that before Vasya remixed the song, no word contained substring "WUB" in it; Vasya didn't change the word order. It is also guaranteed that initially the song had at least one word.OutputPrint the words of the initial song that Vasya used to make a dubsteb remix. Separate the words with a space.ExamplesInputWUBWUBABCWUBOutputABC InputWUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUBOutputWE ARE THE CHAMPIONS MY FRIEND NoteIn the first sample: "WUBWUBABCWUB" = "WUB" + "WUB" + "ABC" + "WUB". That means that the song originally consisted of a single word "ABC", and all words "WUB" were added by Vasya.In the second sample Vasya added a single word "WUB" between all neighbouring words, in the beginning and in the end, except for words "ARE" and "THE" β between them Vasya added two "WUB". | InputWUBWUBABCWUB | OutputABC | 2 seconds | 256 megabytes | ['strings', '*900'] |
C3. Game with Two Treestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has come up with a new developing game for children. The Beaver thinks that this game will help children to understand programming better.The main object of the game is finite rooted trees, each of their edges contains some lowercase English letter. Vertices on any tree are always numbered sequentially from 1 to m, where m is the number of vertices in the tree. Before describing the actual game, let's introduce some definitions.We'll assume that the sequence of vertices with numbers v1, v2, ..., vk (kββ₯β1) is a forward path, if for any integer i from 1 to kβ-β1 vertex vi is a direct ancestor of vertex viβ+β1. If we sequentially write out all letters from the the edges of the given path from v1 to vk, we get some string (kβ=β1 gives us an empty string). We'll say that such string corresponds to forward path v1, v2, ..., vk.We'll assume that the sequence of tree vertices with numbers v1, v2, ..., vk (kββ₯β1) is a backward path if for any integer i from 1 to kβ-β1 vertex vi is the direct descendant of vertex viβ+β1. If we sequentially write out all the letters from the edges of the given path from v1 to vk, we get some string (kβ=β1 gives us an empty string). We'll say that such string corresponds to backward path v1, v2, ..., vk.Now let's describe the game that the Smart Beaver from ABBYY has come up with. The game uses two rooted trees, each of which initially consists of one vertex with number 1. The player is given some sequence of operations. Each operation is characterized by three values (t, v, c) where: t is the number of the tree on which the operation is executed (1 or 2); v is the vertex index in this tree (it is guaranteed that the tree contains a vertex with this index); c is a lowercase English letter. The actual operation is as follows: vertex v of tree t gets a new descendant with number mβ+β1 (where m is the current number of vertices in tree t), and there should be letter c put on the new edge from vertex v to vertex mβ+β1.We'll say that an ordered group of three integers (i, j, q) is a good combination if: 1ββ€βiββ€βm1, where m1 is the number of vertices in the first tree; 1ββ€βj,βqββ€βm2, where m2 is the number of vertices in the second tree; there exists a forward path v1, v2, ..., vk such that v1β=βj and vkβ=βq in the second tree; the string that corresponds to the forward path in the second tree from vertex j to vertex q equals the string that corresponds to the backward path in the first tree from vertex i to vertex 1 (note that both paths are determined uniquely). Your task is to calculate the number of existing good combinations after each operation on the trees.InputThe first line contains integer n β the number of operations on the trees. Next n lines specify the operations in the order of their execution. Each line has form "t v c", where t is the number of the tree, v is the vertex index in this tree, and c is a lowercase English letter.To get the full points for the first group of tests it is sufficient to solve the problem with 1ββ€βnββ€β700.To get the full points for the second group of tests it is sufficient to solve the problem with 1ββ€βnββ€β7000.To get the full points for the third group of tests it is sufficient to solve the problem with 1ββ€βnββ€β100000.OutputPrint exactly n lines, each containing one integer β the number of existing good combinations after the corresponding operation from the input.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.ExamplesInput51 1 a2 1 a1 2 b2 1 b2 3 aOutput13347NoteAfter the first operation the only good combination was (1,β1,β1). After the second operation new good combinations appeared, (2,β1,β2) and (1,β2,β2). The third operation didn't bring any good combinations. The fourth operation added good combination (1,β3,β3). Finally, the fifth operation resulted in as much as three new good combinations β (1,β4,β4), (2,β3,β4) and (3,β1,β4). | Input51 1 a2 1 a1 2 b2 1 b2 3 a | Output13347 | 1 second | 256 megabytes | ['data structures', '*2700'] |
C2. Game with Two Treestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has come up with a new developing game for children. The Beaver thinks that this game will help children to understand programming better.The main object of the game is finite rooted trees, each of their edges contains some lowercase English letter. Vertices on any tree are always numbered sequentially from 1 to m, where m is the number of vertices in the tree. Before describing the actual game, let's introduce some definitions.We'll assume that the sequence of vertices with numbers v1, v2, ..., vk (kββ₯β1) is a forward path, if for any integer i from 1 to kβ-β1 vertex vi is a direct ancestor of vertex viβ+β1. If we sequentially write out all letters from the the edges of the given path from v1 to vk, we get some string (kβ=β1 gives us an empty string). We'll say that such string corresponds to forward path v1, v2, ..., vk.We'll assume that the sequence of tree vertices with numbers v1, v2, ..., vk (kββ₯β1) is a backward path if for any integer i from 1 to kβ-β1 vertex vi is the direct descendant of vertex viβ+β1. If we sequentially write out all the letters from the edges of the given path from v1 to vk, we get some string (kβ=β1 gives us an empty string). We'll say that such string corresponds to backward path v1, v2, ..., vk.Now let's describe the game that the Smart Beaver from ABBYY has come up with. The game uses two rooted trees, each of which initially consists of one vertex with number 1. The player is given some sequence of operations. Each operation is characterized by three values (t, v, c) where: t is the number of the tree on which the operation is executed (1 or 2); v is the vertex index in this tree (it is guaranteed that the tree contains a vertex with this index); c is a lowercase English letter. The actual operation is as follows: vertex v of tree t gets a new descendant with number mβ+β1 (where m is the current number of vertices in tree t), and there should be letter c put on the new edge from vertex v to vertex mβ+β1.We'll say that an ordered group of three integers (i, j, q) is a good combination if: 1ββ€βiββ€βm1, where m1 is the number of vertices in the first tree; 1ββ€βj,βqββ€βm2, where m2 is the number of vertices in the second tree; there exists a forward path v1, v2, ..., vk such that v1β=βj and vkβ=βq in the second tree; the string that corresponds to the forward path in the second tree from vertex j to vertex q equals the string that corresponds to the backward path in the first tree from vertex i to vertex 1 (note that both paths are determined uniquely). Your task is to calculate the number of existing good combinations after each operation on the trees.InputThe first line contains integer n β the number of operations on the trees. Next n lines specify the operations in the order of their execution. Each line has form "t v c", where t is the number of the tree, v is the vertex index in this tree, and c is a lowercase English letter.To get the full points for the first group of tests it is sufficient to solve the problem with 1ββ€βnββ€β700.To get the full points for the second group of tests it is sufficient to solve the problem with 1ββ€βnββ€β7000.To get the full points for the third group of tests it is sufficient to solve the problem with 1ββ€βnββ€β100000.OutputPrint exactly n lines, each containing one integer β the number of existing good combinations after the corresponding operation from the input.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.ExamplesInput51 1 a2 1 a1 2 b2 1 b2 3 aOutput13347NoteAfter the first operation the only good combination was (1,β1,β1). After the second operation new good combinations appeared, (2,β1,β2) and (1,β2,β2). The third operation didn't bring any good combinations. The fourth operation added good combination (1,β3,β3). Finally, the fifth operation resulted in as much as three new good combinations β (1,β4,β4), (2,β3,β4) and (3,β1,β4). | Input51 1 a2 1 a1 2 b2 1 b2 3 a | Output13347 | 1 second | 256 megabytes | ['*2200'] |
C1. Game with Two Treestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has come up with a new developing game for children. The Beaver thinks that this game will help children to understand programming better.The main object of the game is finite rooted trees, each of their edges contains some lowercase English letter. Vertices on any tree are always numbered sequentially from 1 to m, where m is the number of vertices in the tree. Before describing the actual game, let's introduce some definitions.We'll assume that the sequence of vertices with numbers v1, v2, ..., vk (kββ₯β1) is a forward path, if for any integer i from 1 to kβ-β1 vertex vi is a direct ancestor of vertex viβ+β1. If we sequentially write out all letters from the the edges of the given path from v1 to vk, we get some string (kβ=β1 gives us an empty string). We'll say that such string corresponds to forward path v1, v2, ..., vk.We'll assume that the sequence of tree vertices with numbers v1, v2, ..., vk (kββ₯β1) is a backward path if for any integer i from 1 to kβ-β1 vertex vi is the direct descendant of vertex viβ+β1. If we sequentially write out all the letters from the edges of the given path from v1 to vk, we get some string (kβ=β1 gives us an empty string). We'll say that such string corresponds to backward path v1, v2, ..., vk.Now let's describe the game that the Smart Beaver from ABBYY has come up with. The game uses two rooted trees, each of which initially consists of one vertex with number 1. The player is given some sequence of operations. Each operation is characterized by three values (t, v, c) where: t is the number of the tree on which the operation is executed (1 or 2); v is the vertex index in this tree (it is guaranteed that the tree contains a vertex with this index); c is a lowercase English letter. The actual operation is as follows: vertex v of tree t gets a new descendant with number mβ+β1 (where m is the current number of vertices in tree t), and there should be letter c put on the new edge from vertex v to vertex mβ+β1.We'll say that an ordered group of three integers (i, j, q) is a good combination if: 1ββ€βiββ€βm1, where m1 is the number of vertices in the first tree; 1ββ€βj,βqββ€βm2, where m2 is the number of vertices in the second tree; there exists a forward path v1, v2, ..., vk such that v1β=βj and vkβ=βq in the second tree; the string that corresponds to the forward path in the second tree from vertex j to vertex q equals the string that corresponds to the backward path in the first tree from vertex i to vertex 1 (note that both paths are determined uniquely). Your task is to calculate the number of existing good combinations after each operation on the trees.InputThe first line contains integer n β the number of operations on the trees. Next n lines specify the operations in the order of their execution. Each line has form "t v c", where t is the number of the tree, v is the vertex index in this tree, and c is a lowercase English letter.To get the full points for the first group of tests it is sufficient to solve the problem with 1ββ€βnββ€β700.To get the full points for the second group of tests it is sufficient to solve the problem with 1ββ€βnββ€β7000.To get the full points for the third group of tests it is sufficient to solve the problem with 1ββ€βnββ€β100000.OutputPrint exactly n lines, each containing one integer β the number of existing good combinations after the corresponding operation from the input.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.ExamplesInput51 1 a2 1 a1 2 b2 1 b2 3 aOutput13347NoteAfter the first operation the only good combination was (1,β1,β1). After the second operation new good combinations appeared, (2,β1,β2) and (1,β2,β2). The third operation didn't bring any good combinations. The fourth operation added good combination (1,β3,β3). Finally, the fifth operation resulted in as much as three new good combinations β (1,β4,β4), (2,β3,β4) and (3,β1,β4). | Input51 1 a2 1 a1 2 b2 1 b2 3 a | Output13347 | 1 second | 256 megabytes | ['*2100'] |
B3. Military Trainingstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows.Initially, the column consists of n tanks sequentially numbered from 1 to n in the order of position in the column from its beginning to its end. During the whole exercise, exactly n messages must be transferred from the beginning of the column to its end.Transferring one message is as follows. The tank that goes first in the column transmits the message to some tank in the column. The tank which received the message sends it further down the column. The process is continued until the last tank receives the message. It is possible that not all tanks in the column will receive the message β it is important that the last tank in the column should receive the message.After the last tank (tank number n) receives the message, it moves to the beginning of the column and sends another message to the end of the column in the same manner. When the message reaches the last tank (tank number nβ-β1), that tank moves to the beginning of the column and sends the next message to the end of the column, and so on. Thus, the exercise is completed when the tanks in the column return to their original order, that is, immediately after tank number 1 moves to the beginning of the column.If the tanks were initially placed in the column in the order 1,β2,β...,βn, then after the first message their order changes to n,β1,β...,βnβ-β1, after the second message it changes to nβ-β1,βn,β1,β...,βnβ-β2, and so on.The tanks are constructed in a very peculiar way. The tank with number i is characterized by one integer ai, which is called the message receiving radius of this tank.Transferring a message between two tanks takes one second, however, not always one tank can transmit a message to another one. Let's consider two tanks in the column such that the first of them is the i-th in the column counting from the beginning, and the second one is the j-th in the column, and suppose the second tank has number x. Then the first tank can transmit a message to the second tank if iβ<βj and iββ₯βjβ-βax.The Ministry of Defense (and soon the Smart Beaver) faced the question of how to organize the training efficiently. The exercise should be finished as quickly as possible. We'll neglect the time that the tanks spend on moving along the column, since improving the tanks' speed is not a priority for this training.You are given the number of tanks, as well as the message receiving radii of all tanks. You must help the Smart Beaver and organize the transferring of messages in a way that makes the total transmission time of all messages as small as possible.InputThe first line contains integer n β the number of tanks in the column. Each of the next n lines contains one integer ai (1ββ€βaiββ€β250000, 1ββ€βiββ€βn) β the message receiving radii of the tanks in the order from tank 1 to tank n (let us remind you that initially the tanks are located in the column in ascending order of their numbers).To get the full points for the first group of tests it is sufficient to solve the problem with 2ββ€βnββ€β300.To get the full points for the second group of tests it is sufficient to solve the problem with 2ββ€βnββ€β10000.To get the full points for the third group of tests it is sufficient to solve the problem with 2ββ€βnββ€β250000.OutputPrint a single integer β the minimum possible total time of transmitting the messages.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.ExamplesInput3211Output5Input522222Output10NoteIn the first sample the original order of tanks is 1,β2,β3. The first tank sends a message to the second one, then the second tank sends it to the third one β it takes two seconds. The third tank moves to the beginning of the column and the order of tanks now is 3,β1,β2. The third tank sends a message to the first one, then the first one sends it to the second one β it takes two more seconds. The second tank moves to the beginning and the order of the tanks is now 2,β3,β1. With this arrangement, the second tank can immediately send a message to the first one, since the message receiving radius of the first tank is large enough β it takes one second. Finally, the tanks return to their original order 1,β2,β3. In total, the exercise takes 5 seconds.In the second sample, all five tanks are the same and sending a single message takes two seconds, so in total the exercise takes 10 seconds. | Input3211 | Output5 | 3 seconds | 256 megabytes | ['*1700'] |
B2. Military Trainingstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows.Initially, the column consists of n tanks sequentially numbered from 1 to n in the order of position in the column from its beginning to its end. During the whole exercise, exactly n messages must be transferred from the beginning of the column to its end.Transferring one message is as follows. The tank that goes first in the column transmits the message to some tank in the column. The tank which received the message sends it further down the column. The process is continued until the last tank receives the message. It is possible that not all tanks in the column will receive the message β it is important that the last tank in the column should receive the message.After the last tank (tank number n) receives the message, it moves to the beginning of the column and sends another message to the end of the column in the same manner. When the message reaches the last tank (tank number nβ-β1), that tank moves to the beginning of the column and sends the next message to the end of the column, and so on. Thus, the exercise is completed when the tanks in the column return to their original order, that is, immediately after tank number 1 moves to the beginning of the column.If the tanks were initially placed in the column in the order 1,β2,β...,βn, then after the first message their order changes to n,β1,β...,βnβ-β1, after the second message it changes to nβ-β1,βn,β1,β...,βnβ-β2, and so on.The tanks are constructed in a very peculiar way. The tank with number i is characterized by one integer ai, which is called the message receiving radius of this tank.Transferring a message between two tanks takes one second, however, not always one tank can transmit a message to another one. Let's consider two tanks in the column such that the first of them is the i-th in the column counting from the beginning, and the second one is the j-th in the column, and suppose the second tank has number x. Then the first tank can transmit a message to the second tank if iβ<βj and iββ₯βjβ-βax.The Ministry of Defense (and soon the Smart Beaver) faced the question of how to organize the training efficiently. The exercise should be finished as quickly as possible. We'll neglect the time that the tanks spend on moving along the column, since improving the tanks' speed is not a priority for this training.You are given the number of tanks, as well as the message receiving radii of all tanks. You must help the Smart Beaver and organize the transferring of messages in a way that makes the total transmission time of all messages as small as possible.InputThe first line contains integer n β the number of tanks in the column. Each of the next n lines contains one integer ai (1ββ€βaiββ€β250000, 1ββ€βiββ€βn) β the message receiving radii of the tanks in the order from tank 1 to tank n (let us remind you that initially the tanks are located in the column in ascending order of their numbers).To get the full points for the first group of tests it is sufficient to solve the problem with 2ββ€βnββ€β300.To get the full points for the second group of tests it is sufficient to solve the problem with 2ββ€βnββ€β10000.To get the full points for the third group of tests it is sufficient to solve the problem with 2ββ€βnββ€β250000.OutputPrint a single integer β the minimum possible total time of transmitting the messages.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.ExamplesInput3211Output5Input522222Output10NoteIn the first sample the original order of tanks is 1,β2,β3. The first tank sends a message to the second one, then the second tank sends it to the third one β it takes two seconds. The third tank moves to the beginning of the column and the order of tanks now is 3,β1,β2. The third tank sends a message to the first one, then the first one sends it to the second one β it takes two more seconds. The second tank moves to the beginning and the order of the tanks is now 2,β3,β1. With this arrangement, the second tank can immediately send a message to the first one, since the message receiving radius of the first tank is large enough β it takes one second. Finally, the tanks return to their original order 1,β2,β3. In total, the exercise takes 5 seconds.In the second sample, all five tanks are the same and sending a single message takes two seconds, so in total the exercise takes 10 seconds. | Input3211 | Output5 | 3 seconds | 256 megabytes | ['*1900'] |
B1. Military Trainingstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows.Initially, the column consists of n tanks sequentially numbered from 1 to n in the order of position in the column from its beginning to its end. During the whole exercise, exactly n messages must be transferred from the beginning of the column to its end.Transferring one message is as follows. The tank that goes first in the column transmits the message to some tank in the column. The tank which received the message sends it further down the column. The process is continued until the last tank receives the message. It is possible that not all tanks in the column will receive the message β it is important that the last tank in the column should receive the message.After the last tank (tank number n) receives the message, it moves to the beginning of the column and sends another message to the end of the column in the same manner. When the message reaches the last tank (tank number nβ-β1), that tank moves to the beginning of the column and sends the next message to the end of the column, and so on. Thus, the exercise is completed when the tanks in the column return to their original order, that is, immediately after tank number 1 moves to the beginning of the column.If the tanks were initially placed in the column in the order 1,β2,β...,βn, then after the first message their order changes to n,β1,β...,βnβ-β1, after the second message it changes to nβ-β1,βn,β1,β...,βnβ-β2, and so on.The tanks are constructed in a very peculiar way. The tank with number i is characterized by one integer ai, which is called the message receiving radius of this tank.Transferring a message between two tanks takes one second, however, not always one tank can transmit a message to another one. Let's consider two tanks in the column such that the first of them is the i-th in the column counting from the beginning, and the second one is the j-th in the column, and suppose the second tank has number x. Then the first tank can transmit a message to the second tank if iβ<βj and iββ₯βjβ-βax.The Ministry of Defense (and soon the Smart Beaver) faced the question of how to organize the training efficiently. The exercise should be finished as quickly as possible. We'll neglect the time that the tanks spend on moving along the column, since improving the tanks' speed is not a priority for this training.You are given the number of tanks, as well as the message receiving radii of all tanks. You must help the Smart Beaver and organize the transferring of messages in a way that makes the total transmission time of all messages as small as possible.InputThe first line contains integer n β the number of tanks in the column. Each of the next n lines contains one integer ai (1ββ€βaiββ€β250000, 1ββ€βiββ€βn) β the message receiving radii of the tanks in the order from tank 1 to tank n (let us remind you that initially the tanks are located in the column in ascending order of their numbers).To get the full points for the first group of tests it is sufficient to solve the problem with 2ββ€βnββ€β300.To get the full points for the second group of tests it is sufficient to solve the problem with 2ββ€βnββ€β10000.To get the full points for the third group of tests it is sufficient to solve the problem with 2ββ€βnββ€β250000.OutputPrint a single integer β the minimum possible total time of transmitting the messages.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.ExamplesInput3211Output5Input522222Output10NoteIn the first sample the original order of tanks is 1,β2,β3. The first tank sends a message to the second one, then the second tank sends it to the third one β it takes two seconds. The third tank moves to the beginning of the column and the order of tanks now is 3,β1,β2. The third tank sends a message to the first one, then the first one sends it to the second one β it takes two more seconds. The second tank moves to the beginning and the order of the tanks is now 2,β3,β1. With this arrangement, the second tank can immediately send a message to the first one, since the message receiving radius of the first tank is large enough β it takes one second. Finally, the tanks return to their original order 1,β2,β3. In total, the exercise takes 5 seconds.In the second sample, all five tanks are the same and sending a single message takes two seconds, so in total the exercise takes 10 seconds. | Input3211 | Output5 | 3 seconds | 256 megabytes | ['*1600'] |
A3. Beaver's Calculator 1.0time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scientist brought ki calculating problems for the device developed by the Smart Beaver from ABBYY. The problems of the i-th scientist are numbered from 1 to ki, and they must be calculated sequentially in the described order, since calculating each problem heavily depends on the results of calculating of the previous ones.Each problem of each of the n scientists is described by one integer ai,βj, where i (1ββ€βiββ€βn) is the number of the scientist, j (1ββ€βjββ€βki) is the number of the problem, and ai,βj is the number of resource units the calculating device needs to solve this problem.The calculating device that is developed by the Smart Beaver is pretty unusual. It solves problems sequentially, one after another. After some problem is solved and before the next one is considered, the calculating device allocates or frees resources.The most expensive operation for the calculating device is freeing resources, which works much slower than allocating them. It is therefore desirable that each next problem for the calculating device requires no less resources than the previous one.You are given the information about the problems the scientists offered for the testing. You need to arrange these problems in such an order that the number of adjacent "bad" pairs of problems in this list is minimum possible. We will call two consecutive problems in this list a "bad pair" if the problem that is performed first requires more resources than the one that goes after it. Do not forget that the problems of the same scientist must be solved in a fixed order.InputThe first line contains integer n β the number of scientists. To lessen the size of the input, each of the next n lines contains five integers ki, ai,β1, xi, yi, mi (0ββ€βai,β1β<βmiββ€β109, 1ββ€βxi,βyiββ€β109) β the number of problems of the i-th scientist, the resources the first problem requires and three parameters that generate the subsequent values of ai,βj. For all j from 2 to ki, inclusive, you should calculate value ai,βj by formula ai,βjβ=β(ai,βjβ-β1β*βxiβ+βyi) mod mi, where a mod b is the operation of taking the remainder of division of number a by number b.To get the full points for the first group of tests it is sufficient to solve the problem with nβ=β2, 1ββ€βkiββ€β2000.To get the full points for the second group of tests it is sufficient to solve the problem with nβ=β2, 1ββ€βkiββ€β200000.To get the full points for the third group of tests it is sufficient to solve the problem with 1ββ€βnββ€β5000, 1ββ€βkiββ€β5000.OutputOn the first line print a single number β the number of "bad" pairs in the optimal order.If the total number of problems does not exceed 200000, also print lines β the optimal order of the problems. On each of these lines print two integers separated by a single space β the required number of resources for the problem and the number of the scientist who offered this problem, respectively. The scientists are numbered from 1 to n in the order of input.ExamplesInput22 1 1 1 102 3 1 1 10Output01 12 13 24 2Input23 10 2 3 10003 100 1 999 1000Output210 123 149 1100 299 298 2NoteIn the first sample nβ=β2, k1β=β2, a1,β1β=β1, a1,β2β=β2, k2β=β2, a2,β1β=β3, a2,β2β=β4. We've got two scientists, each of them has two calculating problems. The problems of the first scientist require 1 and 2 resource units, the problems of the second one require 3 and 4 resource units. Let's list all possible variants of the calculating order (each problem is characterized only by the number of resource units it requires): (1,β2,β3,β4), (1,β3,β2,β4), (3,β1,β2,β4), (1,β3,β4,β2), (3,β4,β1,β2), (3,β1,β4,β2).Sequence of problems (1,β3,β2,β4) has one "bad" pair (3 and 2), (3,β1,β4,β2) has two "bad" pairs (3 and 1, 4 and 2), and (1,β2,β3,β4) has no "bad" pairs. | Input22 1 1 1 102 3 1 1 10 | Output01 12 13 24 2 | 3 seconds | 256 megabytes | ['greedy', '*2000'] |
A2. Beaver's Calculator 1.0time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scientist brought ki calculating problems for the device developed by the Smart Beaver from ABBYY. The problems of the i-th scientist are numbered from 1 to ki, and they must be calculated sequentially in the described order, since calculating each problem heavily depends on the results of calculating of the previous ones.Each problem of each of the n scientists is described by one integer ai,βj, where i (1ββ€βiββ€βn) is the number of the scientist, j (1ββ€βjββ€βki) is the number of the problem, and ai,βj is the number of resource units the calculating device needs to solve this problem.The calculating device that is developed by the Smart Beaver is pretty unusual. It solves problems sequentially, one after another. After some problem is solved and before the next one is considered, the calculating device allocates or frees resources.The most expensive operation for the calculating device is freeing resources, which works much slower than allocating them. It is therefore desirable that each next problem for the calculating device requires no less resources than the previous one.You are given the information about the problems the scientists offered for the testing. You need to arrange these problems in such an order that the number of adjacent "bad" pairs of problems in this list is minimum possible. We will call two consecutive problems in this list a "bad pair" if the problem that is performed first requires more resources than the one that goes after it. Do not forget that the problems of the same scientist must be solved in a fixed order.InputThe first line contains integer n β the number of scientists. To lessen the size of the input, each of the next n lines contains five integers ki, ai,β1, xi, yi, mi (0ββ€βai,β1β<βmiββ€β109, 1ββ€βxi,βyiββ€β109) β the number of problems of the i-th scientist, the resources the first problem requires and three parameters that generate the subsequent values of ai,βj. For all j from 2 to ki, inclusive, you should calculate value ai,βj by formula ai,βjβ=β(ai,βjβ-β1β*βxiβ+βyi) mod mi, where a mod b is the operation of taking the remainder of division of number a by number b.To get the full points for the first group of tests it is sufficient to solve the problem with nβ=β2, 1ββ€βkiββ€β2000.To get the full points for the second group of tests it is sufficient to solve the problem with nβ=β2, 1ββ€βkiββ€β200000.To get the full points for the third group of tests it is sufficient to solve the problem with 1ββ€βnββ€β5000, 1ββ€βkiββ€β5000.OutputOn the first line print a single number β the number of "bad" pairs in the optimal order.If the total number of problems does not exceed 200000, also print lines β the optimal order of the problems. On each of these lines print two integers separated by a single space β the required number of resources for the problem and the number of the scientist who offered this problem, respectively. The scientists are numbered from 1 to n in the order of input.ExamplesInput22 1 1 1 102 3 1 1 10Output01 12 13 24 2Input23 10 2 3 10003 100 1 999 1000Output210 123 149 1100 299 298 2NoteIn the first sample nβ=β2, k1β=β2, a1,β1β=β1, a1,β2β=β2, k2β=β2, a2,β1β=β3, a2,β2β=β4. We've got two scientists, each of them has two calculating problems. The problems of the first scientist require 1 and 2 resource units, the problems of the second one require 3 and 4 resource units. Let's list all possible variants of the calculating order (each problem is characterized only by the number of resource units it requires): (1,β2,β3,β4), (1,β3,β2,β4), (3,β1,β2,β4), (1,β3,β4,β2), (3,β4,β1,β2), (3,β1,β4,β2).Sequence of problems (1,β3,β2,β4) has one "bad" pair (3 and 2), (3,β1,β4,β2) has two "bad" pairs (3 and 1, 4 and 2), and (1,β2,β3,β4) has no "bad" pairs. | Input22 1 1 1 102 3 1 1 10 | Output01 12 13 24 2 | 3 seconds | 256 megabytes | ['greedy', '*1800'] |
A1. Beaver's Calculator 1.0time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has once again surprised us! He has developed a new calculating device, which he called the "Beaver's Calculator 1.0". It is very peculiar and it is planned to be used in a variety of scientific problems.To test it, the Smart Beaver invited n scientists, numbered from 1 to n. The i-th scientist brought ki calculating problems for the device developed by the Smart Beaver from ABBYY. The problems of the i-th scientist are numbered from 1 to ki, and they must be calculated sequentially in the described order, since calculating each problem heavily depends on the results of calculating of the previous ones.Each problem of each of the n scientists is described by one integer ai,βj, where i (1ββ€βiββ€βn) is the number of the scientist, j (1ββ€βjββ€βki) is the number of the problem, and ai,βj is the number of resource units the calculating device needs to solve this problem.The calculating device that is developed by the Smart Beaver is pretty unusual. It solves problems sequentially, one after another. After some problem is solved and before the next one is considered, the calculating device allocates or frees resources.The most expensive operation for the calculating device is freeing resources, which works much slower than allocating them. It is therefore desirable that each next problem for the calculating device requires no less resources than the previous one.You are given the information about the problems the scientists offered for the testing. You need to arrange these problems in such an order that the number of adjacent "bad" pairs of problems in this list is minimum possible. We will call two consecutive problems in this list a "bad pair" if the problem that is performed first requires more resources than the one that goes after it. Do not forget that the problems of the same scientist must be solved in a fixed order.InputThe first line contains integer n β the number of scientists. To lessen the size of the input, each of the next n lines contains five integers ki, ai,β1, xi, yi, mi (0ββ€βai,β1β<βmiββ€β109, 1ββ€βxi,βyiββ€β109) β the number of problems of the i-th scientist, the resources the first problem requires and three parameters that generate the subsequent values of ai,βj. For all j from 2 to ki, inclusive, you should calculate value ai,βj by formula ai,βjβ=β(ai,βjβ-β1β*βxiβ+βyi) mod mi, where a mod b is the operation of taking the remainder of division of number a by number b.To get the full points for the first group of tests it is sufficient to solve the problem with nβ=β2, 1ββ€βkiββ€β2000.To get the full points for the second group of tests it is sufficient to solve the problem with nβ=β2, 1ββ€βkiββ€β200000.To get the full points for the third group of tests it is sufficient to solve the problem with 1ββ€βnββ€β5000, 1ββ€βkiββ€β5000.OutputOn the first line print a single number β the number of "bad" pairs in the optimal order.If the total number of problems does not exceed 200000, also print lines β the optimal order of the problems. On each of these lines print two integers separated by a single space β the required number of resources for the problem and the number of the scientist who offered this problem, respectively. The scientists are numbered from 1 to n in the order of input.ExamplesInput22 1 1 1 102 3 1 1 10Output01 12 13 24 2Input23 10 2 3 10003 100 1 999 1000Output210 123 149 1100 299 298 2NoteIn the first sample nβ=β2, k1β=β2, a1,β1β=β1, a1,β2β=β2, k2β=β2, a2,β1β=β3, a2,β2β=β4. We've got two scientists, each of them has two calculating problems. The problems of the first scientist require 1 and 2 resource units, the problems of the second one require 3 and 4 resource units. Let's list all possible variants of the calculating order (each problem is characterized only by the number of resource units it requires): (1,β2,β3,β4), (1,β3,β2,β4), (3,β1,β2,β4), (1,β3,β4,β2), (3,β4,β1,β2), (3,β1,β4,β2).Sequence of problems (1,β3,β2,β4) has one "bad" pair (3 and 2), (3,β1,β4,β2) has two "bad" pairs (3 and 1, 4 and 2), and (1,β2,β3,β4) has no "bad" pairs. | Input22 1 1 1 102 3 1 1 10 | Output01 12 13 24 2 | 3 seconds | 256 megabytes | ['greedy', '*1600'] |
B. Little Elephant and Sortingtime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant loves sortings.He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1ββ€βlββ€βrββ€βn) and increase ai by 1 for all i such that lββ€βiββ€βr.Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1ββ€βiβ<βn) aiββ€βaiβ+β1 holds.InputThe first line contains a single integer n (1ββ€βnββ€β105) β the size of array a. The next line contains n integers, separated by single spaces β array a (1ββ€βaiββ€β109). The array elements are listed in the line in the order of their index's increasing.OutputIn a single line print a single integer β the answer to the problem.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.ExamplesInput31 2 3Output0Input33 2 1Output2Input47 4 1 47Output6NoteIn the first sample the array is already sorted in the non-decreasing order, so the answer is 0.In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]).In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47]. | Input31 2 3 | Output0 | 0.5 seconds | 256 megabytes | ['brute force', 'greedy', '*1400'] |
A. Little Elephant and Rozdiltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil").However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere.For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil.InputThe first line contains a single integer n (1ββ€βnββ€β105) β the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109.You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities.OutputPrint the answer on a single line β the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes).ExamplesInput27 4Output2Input77 4 47 100 4 9 12OutputStill RozdilNoteIn the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one β 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2.In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil". | Input27 4 | Output2 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*900'] |
E. Little Elephant and Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant loves strings very much. He has an array a from n strings, consisting of lowercase English letters. Let's number the elements of the array from 1 to n, then let's denote the element number i as ai. For each string ai (1ββ€βiββ€βn) the Little Elephant wants to find the number of pairs of integers l and r (1ββ€βlββ€βrββ€β|ai|) such that substring ai[l... r] is a substring to at least k strings from array a (including the i-th string).Help the Little Elephant solve this problem.If you are not familiar with the basic notation in string problems, you can find the corresponding definitions in the notes.InputThe first line contains two space-separated integers β n and k (1ββ€βn,βkββ€β105). Next n lines contain array a. The i-th line contains a non-empty string ai, consisting of lowercase English letter. The total length of all strings ai does not exceed 105.OutputOn a single line print n space-separated integers β the i-th number is the answer for string ai.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.ExamplesInput3 1abcaabOutput6 1 3 Input7 4rubikfurikababbabaaaabbbababaabababababazeroOutput1 0 9 9 21 30 0 NoteLet's assume that you are given string aβ=βa1a2... a|a|, then let's denote the string's length as |a| and the string's i-th character as ai.A substring a[l... r] (1ββ€βlββ€βrββ€β|a|) of string a is string alalβ+β1... ar.String a is a substring of string b, if there exists such pair of integers l and r (1ββ€βlββ€βrββ€β|b|), that b[l... r]β=βa. | Input3 1abcaab | Output6 1 3 | 3 seconds | 256 megabytes | ['data structures', 'implementation', 'string suffix structures', 'two pointers', '*2800'] |
D. Little Elephant and Retro Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant has found a ragged old black-and-white string s on the attic.The characters of string s are numbered from the left to the right from 1 to |s|, where |s| is the length of the string. Let's denote the i-th character of string s as si. As the string is black-and-white, each character of the string is either letter "B", or letter "W". Unfortunately, the string is very old and some characters are damaged. The damaged positions are denoted as "X".The Little Elephant in determined to restore the string and hang it on the wall. For that he needs to replace each character "X" by a "B" or a "W". The string must look good on the wall, so it must be beautiful. The Little Elephant considers a string beautiful if it has two non-intersecting substrings of a given length k, such that the left one fully consists of characters "B", and the right one fully consists of characters "W". More formally, there are four integers a,βb,βc,βd (1ββ€βaββ€βbβ<βcββ€βdββ€β|s|;Β bβ-βaβ+β1β=βdβ-βcβ+β1β=βk) such that si = "B" (aββ€βiββ€βb) and sj = "W" (cββ€βjββ€βd). Help the Little Elephant find the number of different beautiful strings he can obtain from string s. Two strings are considered different if there is such position, where the character in the first string differs from the corresponding character in the second string. If this string doesn't contain characters Β«XΒ» and it is already beautiful β the answer is 1.As the answer can be rather large, print it modulo 1000000007 (109β+β7).InputThe first line contains two space-separated integers n and k (1ββ€βkββ€βnββ€β106). The second line contains string s. String s has length n and only consists of characters "W", "B" and "X".OutputOn a single line print an integer β the answer to the problem modulo 1000000007 (109β+β7).ExamplesInput3 2XXXOutput0Input4 2XXXXOutput1Input10 2XXBXXWXXXXOutput166 | Input3 2XXX | Output0 | 2 seconds | 256 megabytes | ['dp', '*2400'] |
C. Little Elephant and Furik and Rubiktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Elephant loves Furik and Rubik, who he met in a small city Kremenchug.The Little Elephant has two strings of equal length a and b, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length β the first one from string a, the second one from string b. The choice is equiprobable among all possible pairs. Let's denote the substring of a as x, and the substring of b β as y. The Little Elephant gives string x to Furik and string y β to Rubik.Let's assume that f(x,βy) is the number of such positions of i (1ββ€βiββ€β|x|), that xiβ=βyi (where |x| is the length of lines x and y, and xi, yi are the i-th characters of strings x and y, correspondingly). Help Furik and Rubik find the expected value of f(x,βy).InputThe first line contains a single integer n (1ββ€βnββ€β2Β·105) β the length of strings a and b. The second line contains string a, the third line contains string b. The strings consist of uppercase English letters only. The length of both strings equals n.OutputOn a single line print a real number β the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10β-β6.ExamplesInput2ABBAOutput0.400000000Input3AABCAAOutput0.642857143NoteLet's assume that we are given string aβ=βa1a2... a|a|, then let's denote the string's length as |a|, and its i-th character β as ai.A substring a[l... r] (1ββ€βlββ€βrββ€β|a|) of string a is string alalβ+β1... ar.String a is a substring of string b, if there exists such pair of integers l and r (1ββ€βlββ€βrββ€β|b|), that b[l... r]β=βa.Let's consider the first test sample. The first sample has 5 possible substring pairs: ("A", "B"), ("A", "A"), ("B", "B"), ("B", "A"), ("AB", "BA"). For the second and third pair value f(x,βy) equals 1, for the rest it equals 0. The probability of choosing each pair equals , that's why the answer is Β· 0 β+β Β· 1 β+β Β· 1 β+β Β· 0 β+β Β· 0 β=β β=β 0.4. | Input2ABBA | Output0.400000000 | 2 seconds | 256 megabytes | ['math', 'probabilities', '*2000'] |
B. Little Elephant and Cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant loves to play with color cards.He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.InputThe first line contains a single integer n (1ββ€βnββ€β105) β the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 β colors of both sides. The first number in a line is the color of the front of the card, the second one β of the back. The color of the front of the card may coincide with the color of the back of the card.The numbers in the lines are separated by single spaces.OutputOn a single line print a single integer β the sought minimum number of moves. If it is impossible to make the set funny, print -1.ExamplesInput34 74 77 4Output0Input54 77 42 119 71 1Output2NoteIn the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7. | Input34 74 77 4 | Output0 | 2 seconds | 256 megabytes | ['binary search', 'data structures', '*1500'] |
A. Little Elephant and Intervaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Little Elephant very much loves sums on intervals.This time he has a pair of integers l and r (lββ€βr). The Little Elephant has to find the number of such integers x (lββ€βxββ€βr), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be included in the answer and 47, 253 or 1020 will not.Help him and count the number of described numbers x for a given pair l and r.InputThe single line contains a pair of integers l and r (1ββ€βlββ€βrββ€β1018) β the boundaries of the interval.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.OutputOn a single line print a single integer β the answer to the problem.ExamplesInput2 47Output12Input47 1024Output98NoteIn the first sample the answer includes integers 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44. | Input2 47 | Output12 | 2 seconds | 256 megabytes | ['binary search', 'combinatorics', 'dp', '*1500'] |
E. Transportationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera came to Japan and bought many robots for his research. He's already at the airport, the plane will fly very soon and Valera urgently needs to bring all robots to the luggage compartment.The robots are self-propelled (they can potentially move on their own), some of them even have compartments to carry other robots. More precisely, for the i-th robot we know value ci β the number of robots it can carry. In this case, each of ci transported robots can additionally carry other robots.However, the robots need to be filled with fuel to go, so Valera spent all his last money and bought S liters of fuel. He learned that each robot has a restriction on travel distances. Thus, in addition to features ci, the i-th robot has two features fi and li β the amount of fuel (in liters) needed to move the i-th robot, and the maximum distance that the robot can go.Due to the limited amount of time and fuel, Valera wants to move the maximum number of robots to the luggage compartment. He operates as follows. First Valera selects some robots that will travel to the luggage compartment on their own. In this case the total amount of fuel required to move all these robots must not exceed S. Then Valera seats the robots into the compartments, so as to transport as many robots as possible. Note that if a robot doesn't move by itself, you can put it in another not moving robot that is moved directly or indirectly by a moving robot. After that all selected and seated robots along with Valera go to the luggage compartment and the rest robots will be lost. There are d meters to the luggage compartment. Therefore, the robots that will carry the rest, must have feature li of not less than d. During the moving Valera cannot stop or change the location of the robots in any way.Help Valera calculate the maximum number of robots that he will be able to take home, and the minimum amount of fuel he will have to spend, because the remaining fuel will come in handy in Valera's research.InputThe first line contains three space-separated integers n,βd,βS (1ββ€βnββ€β105,β1ββ€βd,βSββ€β109). The first number represents the number of robots, the second one β the distance to the luggage compartment and the third one β the amount of available fuel.Next n lines specify the robots. The i-th line contains three space-separated integers ci,βfi,βli (0ββ€βci,βfi,βliββ€β109) β the i-th robot's features. The first number is the number of robots the i-th robot can carry, the second number is the amount of fuel needed for the i-th robot to move and the third one shows the maximum distance the i-th robot can go.OutputPrint two space-separated integers β the maximum number of robots Valera can transport to the luggage compartment and the minimum amount of fuel he will need for that. If Valera won't manage to get any robots to the luggage compartment, print two zeroes.ExamplesInput3 10 100 12 101 6 100 1 1Output2 6Input2 7 103 12 105 16 8Output0 0Input4 8 100 12 31 1 00 3 111 6 9Output4 9 | Input3 10 100 12 101 6 100 1 1 | Output2 6 | 2 seconds | 256 megabytes | ['greedy', 'sortings', 'two pointers', '*2300'] |
D. Hit Balltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Valera was playing football on a stadium, it suddenly began to rain. Valera hid in the corridor under the grandstand not to get wet. However, the desire to play was so great that he decided to train his hitting the ball right in this corridor. Valera went back far enough, put the ball and hit it. The ball bounced off the walls, the ceiling and the floor corridor and finally hit the exit door. As the ball was wet, it left a spot on the door. Now Valera wants to know the coordinates for this spot.Let's describe the event more formally. The ball will be considered a point in space. The door of the corridor will be considered a rectangle located on plane xOz, such that the lower left corner of the door is located at point (0,β0,β0), and the upper right corner is located at point (a,β0,βb) . The corridor will be considered as a rectangular parallelepiped, infinite in the direction of increasing coordinates of y. In this corridor the floor will be considered as plane xOy, and the ceiling as plane, parallel to xOy and passing through point (a,β0,βb). We will also assume that one of the walls is plane yOz, and the other wall is plane, parallel to yOz and passing through point (a,β0,βb).We'll say that the ball hit the door when its coordinate y was equal to 0. Thus the coordinates of the spot are point (x0,β0,βz0), where 0ββ€βx0ββ€βa,β0ββ€βz0ββ€βb. To hit the ball, Valera steps away from the door at distance m and puts the ball in the center of the corridor at point . After the hit the ball flies at speed (vx,βvy,βvz). This means that if the ball has coordinates (x,βy,βz), then after one second it will have coordinates (xβ+βvx,βyβ+βvy,βzβ+βvz).See image in notes for clarification.When the ball collides with the ceiling, the floor or a wall of the corridor, it bounces off in accordance with the laws of reflection (the angle of incidence equals the angle of reflection). In the problem we consider the ideal physical model, so we can assume that there is no air resistance, friction force, or any loss of energy.InputThe first line contains three space-separated integers a,βb,βm (1ββ€βa,βb,βmββ€β100). The first two integers specify point (a,β0,βb), through which the ceiling and one of the corridor walls pass. The third integer is the distance at which Valera went away from the door.The second line has three space-separated integers vx,βvy,βvz (|vx|,β|vy|,β|vz|ββ€β100,βvyβ<β0,βvzββ₯β0) β the speed of the ball after the hit.It is guaranteed that the ball hits the door.OutputPrint two real numbers x0,βz0 β the x and z coordinates of point (x0,β0,βz0), at which the ball hits the exit door. The answer will be considered correct, if its absolute or relative error does not exceed 10ββ-β6.ExamplesInput7 2 113 -11 2Output6.5000000000 2.0000000000Input7 2 114 -3 3Output4.1666666667 1.0000000000Note | Input7 2 113 -11 2 | Output6.5000000000 2.0000000000 | 2 seconds | 256 megabytes | ['geometry', 'implementation', 'math', '*1700'] |
C. Photographertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera's lifelong ambition was to be a photographer, so he bought a new camera. Every day he got more and more clients asking for photos, and one day Valera needed a program that would determine the maximum number of people he can serve.The camera's memory is d megabytes. Valera's camera can take photos of high and low quality. One low quality photo takes a megabytes of memory, one high quality photo take b megabytes of memory. For unknown reasons, each client asks him to make several low quality photos and several high quality photos. More formally, the i-th client asks to make xi low quality photos and yi high quality photos.Valera wants to serve as many clients per day as possible, provided that they will be pleased with his work. To please the i-th client, Valera needs to give him everything he wants, that is, to make xi low quality photos and yi high quality photos. To make one low quality photo, the camera must have at least a megabytes of free memory space. Similarly, to make one high quality photo, the camera must have at least b megabytes of free memory space. Initially the camera's memory is empty. Valera also does not delete photos from the camera so that the camera's memory gradually fills up.Calculate the maximum number of clients Valera can successfully serve and print the numbers of these clients.InputThe first line contains two integers n and d (1ββ€βnββ€β105,β1ββ€βdββ€β109) β the number of clients and the camera memory size, correspondingly. The second line contains two integers a and b (1ββ€βaββ€βbββ€β104) β the size of one low quality photo and of one high quality photo, correspondingly. Next n lines describe the clients. The i-th line contains two integers xi and yi (0ββ€βxi,βyiββ€β105) β the number of low quality photos and high quality photos the i-th client wants, correspondingly. All numbers on all lines are separated by single spaces. OutputOn the first line print the answer to the problem β the maximum number of clients that Valera can successfully serve. Print on the second line the numbers of the client in any order. All numbers must be distinct. If there are multiple answers, print any of them. The clients are numbered starting with 1 in the order in which they are defined in the input data.ExamplesInput3 102 31 42 11 0Output23 2 Input3 66 61 11 01 0Output12 | Input3 102 31 42 11 0 | Output23 2 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1400'] |
B. Game on Papertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne not particularly beautiful evening Valera got very bored. To amuse himself a little bit, he found the following game.He took a checkered white square piece of paper, consisting of nβΓβn cells. After that, he started to paint the white cells black one after the other. In total he painted m different cells on the piece of paper. Since Valera was keen on everything square, he wondered, how many moves (i.e. times the boy paints a square black) he should make till a black square with side 3 can be found on the piece of paper. But Valera does not know the answer to this question, so he asks you to help him.Your task is to find the minimum number of moves, till the checkered piece of paper has at least one black square with side of 3. Otherwise determine that such move does not exist.InputThe first line contains two integers n and m (1ββ€βnββ€β1000, 1ββ€βmββ€βmin(nΒ·n,β105)) β the size of the squared piece of paper and the number of moves, correspondingly. Then, m lines contain the description of the moves. The i-th line contains two integers xi, yi (1ββ€βxi,βyiββ€βn) β the number of row and column of the square that gets painted on the i-th move. All numbers on the lines are separated by single spaces. It is guaranteed that all moves are different. The moves are numbered starting from 1 in the order, in which they are given in the input. The columns of the squared piece of paper are numbered starting from 1, from the left to the right. The rows of the squared piece of paper are numbered starting from 1, from top to bottom.OutputOn a single line print the answer to the problem β the minimum number of the move after which the piece of paper has a black square with side 3. If no such move exists, print -1.ExamplesInput4 111 11 21 32 22 31 42 43 43 23 34 1Output10Input4 121 11 21 32 22 31 42 43 43 24 24 13 1Output-1 | Input4 111 11 21 32 22 31 42 43 43 23 34 1 | Output10 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1300'] |
A. Two Problemstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA boy Valera registered on site Codeforces as Valera, and wrote his first Codeforces Round #300. He boasted to a friend Arkady about winning as much as x points for his first contest. But Arkady did not believe his friend's words and decided to check whether Valera could have shown such a result.He knows that the contest number 300 was unusual because there were only two problems. The contest lasted for t minutes, the minutes are numbered starting from zero. The first problem had the initial cost of a points, and every minute its cost reduced by da points. The second problem had the initial cost of b points, and every minute this cost reduced by db points. Thus, as soon as the zero minute of the contest is over, the first problem will cost aβ-βda points, and the second problem will cost bβ-βdb points. It is guaranteed that at any moment of the contest each problem has a non-negative cost.Arkady asks you to find out whether Valera could have got exactly x points for this contest. You should assume that Valera could have solved any number of the offered problems. You should also assume that for each problem Valera made no more than one attempt, besides, he could have submitted both problems at the same minute of the contest, starting with minute 0 and ending with minute number tβ-β1. Please note that Valera can't submit a solution exactly t minutes after the start of the contest or later.InputThe single line of the input contains six integers x,βt,βa,βb,βda,βdb (0ββ€βxββ€β600;Β 1ββ€βt,βa,βb,βda,βdbββ€β300) β Valera's result, the contest's duration, the initial cost of the first problem, the initial cost of the second problem, the number of points that the first and the second problem lose per minute, correspondingly.It is guaranteed that at each minute of the contest each problem has a non-negative cost, that is, aβ-βiΒ·daββ₯β0 and bβ-βiΒ·dbββ₯β0 for all 0ββ€βiββ€βtβ-β1.OutputIf Valera could have earned exactly x points at a contest, print "YES", otherwise print "NO" (without the quotes).ExamplesInput30 5 20 20 3 5OutputYESInput10 4 100 5 5 1OutputNONoteIn the first sample Valera could have acted like this: he could have submitted the first problem at minute 0 and the second problem β at minute 2. Then the first problem brings him 20 points and the second problem brings him 10 points, that in total gives the required 30 points. | Input30 5 20 20 3 5 | OutputYES | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1200'] |
B. Brand New Easy Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem β a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as , where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.InputThe first line contains a single integer n (1ββ€βnββ€β4) β the number of words in Lesha's problem. The second line contains n space-separated words β the short description of the problem.The third line contains a single integer m (1ββ€βmββ€β10) β the number of problems in the Torcoder.com archive. Next m lines contain the descriptions of the problems as "k s1 s2 ... sk", where k (1ββ€βkββ€β20) is the number of words in the problem and si is a word of the problem description.All words from all problem descriptions contain no more than 10 lowercase English letters. OutputIf Lesha's problem is brand new, print string "Brand new problem!" (without quotes). Otherwise, on the first line print the index of the archive problem which resembles Lesha's problem most. If there are multiple such problems, print the one with the smallest index. On the second line print a string consisting of characters [:, character | repeated p times, and characters :], where p is the "similarity" between this problem and Lesha's one. The archive problems are numbered starting from one in the order in which they are given in the input.ExamplesInput4find the next palindrome110 find the previous palindrome or print better luck next timeOutput1[:||||||:]Input3add two numbers31 add2 two two3 numbers numbers numbersOutputBrand new problem!Input4these papers are formulas36 what are these formulas and papers5 papers are driving me crazy4 crazy into the nightOutput1[:||||:]Input3add two decimals54 please two decimals add5 decimals want to be added4 two add decimals add4 add one two three7 one plus two plus three equals sixOutput3[:|||:]NoteLet us remind you that the number of inversions is the number of pairs of words that follow in the permutation not in their original order. Thus, for example, if the original problem is "add two numbers", then permutation "numbers add two" contains two inversions β pairs of words "numbers" and "add", "numbers" and "two". Sequence b1,ββb2,ββ...,ββbk is a subsequence of sequence a1,βa2,ββ...,ββan if there exists such a set of indices 1ββ€βi1β<ββi2β<β... ββ<βikββ€βn that aijββ=ββbj (in other words, if sequence b can be obtained from a by deleting some of its elements).In the first test case the first problem contains the "find the palindrome next" permutation as a subsequence, in which the number of inversions equals 1 (words "palindrome" and "next").In the second test case there is no problem that contains a permutation of words from Lesha's problem as a subsequence. | Input4find the next palindrome110 find the previous palindrome or print better luck next time | Output1[:||||||:] | 2 seconds | 256 megabytes | ['brute force', '*1700'] |
A. LLPStime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 ββ€β p1β<βp2β<β...β<βpk ββ€β |s|) a subsequence of string s = s1s2... s|s|, where |s| is the length of string s. For example, strings "abcb", "b" and "abacaba" are subsequences of string "abacaba".String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y| if either |x| > |y| and x1β=βy1, x2β=βy2, ...,βx|y|β=βy|y|, or there exists such number r (rβ<β|x|, rβ<β|y|) that x1β=βy1, x2β=βy2, ..., xrβ=βyr and xrββ+ββ1β>βyrββ+ββ1. Characters in the strings are compared according to their ASCII codes. For example, string "ranger" is lexicographically larger than string "racecar" and string "poster" is lexicographically larger than string "post".String s = s1s2... s|s| is a palindrome if it matches string rev(s) = s|s|s|s|β-β1... s1. In other words, a string is a palindrome if it reads the same way from left to right and from right to left. For example, palindromic strings are "racecar", "refer" and "z".InputThe only input line contains a non-empty string s consisting of lowercase English letters only. Its length does not exceed 10.OutputPrint the lexicographically largest palindromic subsequence of string s.ExamplesInputradarOutputrrInputbowwowwowOutputwwwwwInputcodeforcesOutputsInputmississippOutputssssNoteAmong all distinct subsequences of string "radar" the following ones are palindromes: "a", "d", "r", "aa", "rr", "ada", "rar", "rdr", "raar" and "radar". The lexicographically largest of them is "rr". | Inputradar | Outputrr | 2 seconds | 256 megabytes | ['binary search', 'bitmasks', 'brute force', 'greedy', 'implementation', 'strings', '*800'] |
E. Thoroughly Bureaucratic Organizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce n people simultaneously signed in to the reception at the recently opened, but already thoroughly bureaucratic organization (abbreviated TBO). As the organization is thoroughly bureaucratic, it can accept and cater for exactly one person per day. As a consequence, each of n people made an appointment on one of the next n days, and no two persons have an appointment on the same day.However, the organization workers are very irresponsible about their job, so none of the signed in people was told the exact date of the appointment. The only way to know when people should come is to write some requests to TBO.The request form consists of m empty lines. Into each of these lines the name of a signed in person can be written (it can be left blank as well). Writing a person's name in the same form twice is forbidden, such requests are ignored. TBO responds very quickly to written requests, but the reply format is of very poor quality β that is, the response contains the correct appointment dates for all people from the request form, but the dates are in completely random order. Responds to all requests arrive simultaneously at the end of the day (each response specifies the request that it answers).Fortunately, you aren't among these n lucky guys. As an observer, you have the following task β given n and m, determine the minimum number of requests to submit to TBO to clearly determine the appointment date for each person.InputThe first line contains a single integer t (1ββ€βtββ€β1000) β the number of test cases. Each of the following t lines contains two integers n and m (1ββ€βn,βmββ€β109) β the number of people who have got an appointment at TBO and the number of empty lines in the request form, correspondingly.OutputPrint t lines, each containing an answer for the corresponding test case (in the order they are given in the input) β the minimum number of requests to submit to TBO.ExamplesInput54 14 27 31 142 7Output323011NoteIn the first sample, you need to submit three requests to TBO with three different names. When you learn the appointment dates of three people out of four, you can find out the fourth person's date by elimination, so you do not need a fourth request.In the second sample you need only two requests. Let's number the persons from 1 to 4 and mention persons 1 and 2 in the first request and persons 1 and 3 in the second request. It is easy to see that after that we can clearly determine each person's appointment date regardless of the answers obtained from TBO.In the fourth sample only one person signed up for an appointment. He doesn't need to submit any requests β his appointment date is tomorrow. | Input54 14 27 31 142 7 | Output323011 | 2 seconds | 256 megabytes | ['binary search', 'combinatorics', '*2600'] |
D. Brand New Problemtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA widely known among some people Belarusian sport programmer Lesha decided to make some money to buy a one square meter larger flat. To do this, he wants to make and carry out a Super Rated Match (SRM) on the site Torcoder.com. But there's a problem β a severe torcoder coordinator Ivan does not accept any Lesha's problem, calling each of them an offensive word "duped" (that is, duplicated). And one day they nearely quarrelled over yet another problem Ivan wouldn't accept.You are invited to act as a fair judge and determine whether the problem is indeed brand new, or Ivan is right and the problem bears some resemblance to those used in the previous SRMs.You are given the descriptions of Lesha's problem and each of Torcoder.com archive problems. The description of each problem is a sequence of words. Besides, it is guaranteed that Lesha's problem has no repeated words, while the description of an archive problem may contain any number of repeated words.The "similarity" between Lesha's problem and some archive problem can be found as follows. Among all permutations of words in Lesha's problem we choose the one that occurs in the archive problem as a subsequence. If there are multiple such permutations, we choose the one with the smallest number of inversions. Then the "similarity" of a problem can be written as , where n is the number of words in Lesha's problem and x is the number of inversions in the chosen permutation. Note that the "similarity" p is always a positive integer.The problem is called brand new if there is not a single problem in Ivan's archive which contains a permutation of words from Lesha's problem as a subsequence.Help the boys and determine whether the proposed problem is new, or specify the problem from the archive which resembles Lesha's problem the most, otherwise.InputThe first line contains a single integer n (1ββ€βnββ€β15) β the number of words in Lesha's problem. The second line contains n space-separated words β the short description of the problem.The third line contains a single integer m (1ββ€βmββ€β10) β the number of problems in the Torcoder.com archive. Next m lines contain the descriptions of the problems as "k s1 s2 ... sk", where k (1ββ€βkββ€β500000) is the number of words in the problem and si is a word of the problem description.All words from all problem descriptions contain no more than 10 lowercase English letters. It is guaranteed that the total length of words in all problem descriptions does not exceed 500015.OutputIf Lesha's problem is brand new, print string "Brand new problem!" (without quotes). Otherwise, on the first line print the index of the archive problem which resembles Lesha's problem most. If there are multiple such problems, print the one with the smallest index. On the second line print a string consisting of characters [:, character | repeated p times, and characters :], where p is the "similarity" between this problem and Lesha's one. The archive problems are numbered starting from one in the order in which they are given in the input.ExamplesInput4find the next palindrome110 find the previous palindrome or print better luck next timeOutput1[:||||||:]Input3add two numbers31 add2 two two3 numbers numbers numbersOutputBrand new problem!Input4these papers are formulas36 what are these formulas and papers5 papers are driving me crazy4 crazy into the nightOutput1[:||||:]Input3add two decimals54 please two decimals add5 decimals want to be added4 two add decimals add4 add one two three7 one plus two plus three equals sixOutput3[:|||:]NoteLet us remind you that the number of inversions is the number of pairs of words that follow in the permutation not in their original order. Thus, for example, if the original problem is "add two numbers", then permutation "numbers add two" contains two inversions β pairs of words "numbers" and "add", "numbers" and "two". Sequence b1,ββb2,ββ...,ββbk is a subsequence of sequence a1,βa2,ββ...,ββan if there exists such a set of indices 1ββ€βi1β<ββi2β<β... ββ<βikββ€βn that aijββ=ββbj (in other words, if sequence b can be obtained from a by deleting some of its elements).In the first test case the first problem contains the "find the palindrome next" permutation as a subsequence, in which the number of inversions equals 1 (words "palindrome" and "next").In the second test case there is no problem that contains a permutation of words from Lesha's problem as a subsequence. | Input4find the next palindrome110 find the previous palindrome or print better luck next time | Output1[:||||||:] | 5 seconds | 256 megabytes | ['bitmasks', 'brute force', 'dp', '*2600'] |
C. Fragile Bridgestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a video game and you have just reached the bonus level, where the only possible goal is to score as many points as possible. Being a perfectionist, you've decided that you won't leave this level until you've gained the maximum possible number of points there.The bonus level consists of n small platforms placed in a line and numbered from 1 to n from left to right and (nβ-β1) bridges connecting adjacent platforms. The bridges between the platforms are very fragile, and for each bridge the number of times one can pass this bridge from one of its ends to the other before it collapses forever is known in advance.The player's actions are as follows. First, he selects one of the platforms to be the starting position for his hero. After that the player can freely move the hero across the platforms moving by the undestroyed bridges. As soon as the hero finds himself on a platform with no undestroyed bridge attached to it, the level is automatically ended. The number of points scored by the player at the end of the level is calculated as the number of transitions made by the hero between the platforms. Note that if the hero started moving by a certain bridge, he has to continue moving in the same direction until he is on a platform.Find how many points you need to score to be sure that nobody will beat your record, and move to the next level with a quiet heart.InputThe first line contains a single integer n (2ββ€βnββ€β105) β the number of platforms on the bonus level. The second line contains (nβ-β1) integers ai (1ββ€βaiββ€β109, 1ββ€βiβ<βn) β the number of transitions from one end to the other that the bridge between platforms i and iβ+β1 can bear.OutputPrint a single integer β the maximum number of points a player can get on the bonus level.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.ExamplesInput52 1 2 1Output5NoteOne possibility of getting 5 points in the sample is starting from platform 3 and consequently moving to platforms 4, 3, 2, 1 and 2. After that the only undestroyed bridge is the bridge between platforms 4 and 5, but this bridge is too far from platform 2 where the hero is located now. | Input52 1 2 1 | Output5 | 2 seconds | 256 megabytes | ['dp', '*2000'] |
B. Guess That Car!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".The game show takes place on a giant parking lot, which is 4n meters long from north to south and 4m meters wide from west to east. The lot has nβ+β1 dividing lines drawn from west to east and mβ+β1 dividing lines drawn from north to south, which divide the parking lot into nΒ·m 4 by 4 meter squares. There is a car parked strictly inside each square. The dividing lines are numbered from 0 to n from north to south and from 0 to m from west to east. Each square has coordinates (i,βj) so that the square in the north-west corner has coordinates (1,β1) and the square in the south-east corner has coordinates (n,βm). See the picture in the notes for clarifications.Before the game show the organizers offer Yura to occupy any of the (nβ+β1)Β·(mβ+β1) intersection points of the dividing lines. After that he can start guessing the cars. After Yura chooses a point, he will be prohibited to move along the parking lot before the end of the game show. As Yura is a car expert, he will always guess all cars he is offered, it's just a matter of time. Yura knows that to guess each car he needs to spend time equal to the square of the euclidean distance between his point and the center of the square with this car, multiplied by some coefficient characterizing the machine's "rarity" (the rarer the car is, the harder it is to guess it). More formally, guessing a car with "rarity" c placed in a square whose center is at distance d from Yura takes cΒ·d2 seconds. The time Yura spends on turning his head can be neglected.It just so happened that Yura knows the "rarity" of each car on the parking lot in advance. Help him choose his point so that the total time of guessing all cars is the smallest possible.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β1000) β the sizes of the parking lot. Each of the next n lines contains m integers: the j-th number in the i-th line describes the "rarity" cij (0ββ€βcijββ€β100000) of the car that is located in the square with coordinates (i,βj).OutputIn the first line print the minimum total time Yura needs to guess all offered cars. In the second line print two numbers li and lj (0ββ€βliββ€βn,β0ββ€βljββ€βm) β the numbers of dividing lines that form a junction that Yura should choose to stand on at the beginning of the game show. If there are multiple optimal starting points, print the point with smaller li. If there are still multiple such points, print the point with smaller lj.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.ExamplesInput2 33 4 53 9 1Output3921 1Input3 41 0 0 00 0 3 00 0 5 5Output2402 3NoteIn the first test case the total time of guessing all cars is equal to 3Β·8β+β3Β·8β+β4Β·8β+β9Β·8β+β5Β·40β+β1Β·40β=β392.The coordinate system of the field: | Input2 33 4 53 9 1 | Output3921 1 | 2 seconds | 256 megabytes | ['math', 'ternary search', '*1800'] |
A. Clear Symmetrytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai,βj.Let's call matrix A clear if no two cells containing ones have a common side.Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i,βj) (1ββ€βi,βjββ€βn) both of the following conditions must be met: Ai,βjβ=βAnβ-βiβ+β1,βj and Ai,βjβ=βAi,βnβ-βjβ+β1.Let's define the sharpness of matrix A as the number of ones in it.Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x.InputThe only line contains a single integer x (1ββ€βxββ€β100) β the required sharpness of the matrix.OutputPrint a single number β the sought value of n.ExamplesInput4Output3Input9Output5NoteThe figure below shows the matrices that correspond to the samples: | Input4 | Output3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dp', 'math', '*1700'] |
E. Tractor Collegetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile most students still sit their exams, the tractor college has completed the summer exam session. In fact, students study only one subject at this college β the Art of Operating a Tractor. Therefore, at the end of a term a student gets only one mark, a three (satisfactory), a four (good) or a five (excellent). Those who score lower marks are unfortunately expelled.The college has n students, and oddly enough, each of them can be on scholarship. The size of the scholarships varies each term. Since the end-of-the-term exam has just ended, it's time to determine the size of the scholarship to the end of next term.The monthly budget for the scholarships of the Tractor college is s rubles. To distribute the budget optimally, you must follow these rules: The students who received the same mark for the exam, should receive the same scholarship; Let us denote the size of the scholarship (in roubles) for students who have received marks 3, 4 and 5 for the exam, as k3, k4 and k5, respectively. The values k3, k4 and k5 must be integers and satisfy the inequalities 0ββ€βk3ββ€βk4ββ€βk5; Let's assume that c3, c4, c5 show how many students received marks 3, 4 and 5 for the exam, respectively. The budget of the scholarship should be fully spent on them, that is, c3Β·k3β+βc4Β·k4β+βc5Β·k5β=βs; Let's introduce function β the value that shows how well the scholarships are distributed between students. In the optimal distribution function f(k3,βk4,βk5) takes the minimum possible value. Given the results of the exam, and the budget size s, you have to find the optimal distribution of the scholarship.InputThe first line has two integers n, s (3ββ€βnββ€β300,β1ββ€βsββ€β3Β·105) β the number of students and the budget size for the scholarship, respectively. The second line contains n integers, where the i-th number represents the mark that the i-th student got for the exam. It is guaranteed that at each mark was given to at least one student.OutputOn a single line print three integers k3, k4 and k5 β the sought values that represent the optimal distribution of the scholarships. If there are multiple optimal answers, print any of them. If there is no answer, print -1.ExamplesInput5 113 4 3 5 5Output1 3 3Input6 155 3 3 4 4 5Output-1 | Input5 113 4 3 5 5 | Output1 3 3 | 4 seconds | 256 megabytes | ['implementation', 'math', 'number theory', 'ternary search', '*2400'] |
D. Programming Languagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Valery have come across an entirely new programming language. Most of all the language attracted him with template functions and procedures. Let us remind you that templates are tools of a language, designed to encode generic algorithms, without reference to some parameters (e.g., data types, buffer sizes, default values).Valery decided to examine template procedures in this language in more detail. The description of a template procedure consists of the procedure name and the list of its parameter types. The generic type T parameters can be used as parameters of template procedures.A procedure call consists of a procedure name and a list of variable parameters. Let's call a procedure suitable for this call if the following conditions are fulfilled: its name equals to the name of the called procedure; the number of its parameters equals to the number of parameters of the procedure call; the types of variables in the procedure call match the corresponding types of its parameters. The variable type matches the type of a parameter if the parameter has a generic type T or the type of the variable and the parameter are the same. You are given a description of some set of template procedures. You are also given a list of variables used in the program, as well as direct procedure calls that use the described variables. For each call you need to count the number of procedures that are suitable for this call.InputThe first line contains a single integer n (1ββ€βnββ€β1000) β the number of template procedures. The next n lines contain the description of the procedures specified in the following format:"void procedureName (type_1, type_2, ..., type_t)" (1ββ€βtββ€β5), where void is the keyword, procedureName is the procedure name, type_i is the type of the next parameter. Types of language parameters can be "int", "string", "double", and the keyword "T", which denotes the generic type.The next line contains a single integer m (1ββ€βmββ€β1000) β the number of used variables. Next m lines specify the description of the variables in the following format:"type variableName", where type is the type of variable that can take values "int", "string", "double", variableName β the name of the variable.The next line contains a single integer k (1ββ€βkββ€β1000) β the number of procedure calls. Next k lines specify the procedure calls in the following format:"procedureName (var_1, var_2, ..., var_t)" (1ββ€βtββ€β5), where procedureName is the name of the procedure, var_i is the name of a variable.The lines describing the variables, template procedures and their calls may contain spaces at the beginning of the line and at the end of the line, before and after the brackets and commas. Spaces may be before and after keyword void. The length of each input line does not exceed 100 characters. The names of variables and procedures are non-empty strings of lowercase English letters and numbers with lengths of not more than 10 characters. Note that this is the only condition at the names. Only the specified variables are used in procedure calls. The names of the variables are distinct. No two procedures are the same. Two procedures are the same, if they have identical names and identical ordered sets of types of their parameters.OutputOn each of k lines print a single number, where the i-th number stands for the number of suitable template procedures for the i-th call.ExamplesInput4void f(int,T)void f(T, T) void foo123 ( int, double, string,string ) void p(T,double)3int a string sdouble x123 5f(a, a) f(s,a )foo (a,s,s) f ( s ,x123)proc(a)Output21010Input6void f(string,double,int)void f(int) void f ( T )void procedure(int,double)void f (T, double,int) void f(string, T,T)4 int a int xstring tdouble val 5f(t, a, a)f(t,val,a)f(val,a, val) solve300(val, val)f (x)Output13002 | Input4void f(int,T)void f(T, T) void foo123 ( int, double, string,string ) void p(T,double)3int a string sdouble x123 5f(a, a) f(s,a )foo (a,s,s) f ( s ,x123)proc(a) | Output21010 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'expression parsing', 'implementation', '*1800'] |