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
E. Empire Strikes Backtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn a far away galaxy there is war again. The treacherous Republic made k precision strikes of power ai on the Empire possessions. To cope with the republican threat, the Supreme Council decided to deal a decisive blow to the enemy forces. To successfully complete the conflict, the confrontation balance after the blow should be a positive integer. The balance of confrontation is a number that looks like , where p = n! (n is the power of the Imperial strike), . After many years of war the Empire's resources are low. So to reduce the costs, n should be a minimum positive integer that is approved by the commanders.Help the Empire, find the minimum positive integer n, where the described fraction is a positive integer.InputThe first line contains integer k (1 ≀ k ≀ 106). The second line contains k integers a1, a2, ..., ak (1 ≀ ai ≀ 107).OutputPrint the minimum positive integer n, needed for the Empire to win.Please, do not use the %lld to read or write 64-but integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInput21000 1000Output2000Input12Output2
Input21000 1000
Output2000
5 seconds
512 megabytes
['binary search', 'math', 'number theory', '*2300']
D. Painting Squaretime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasily the bear has got a large square white table of n rows and n columns. The table has got a black border around this table. The example of the initial table at n = 5. Vasily the bear wants to paint his square table in exactly k moves. Each move is sequence of actions: The bear chooses some square inside his table. At that the square must have a black border painted around it. Also, the square shouldn't contain a black cell. The number of cells in the square shouldn't be less than 2. The bear chooses some row and some column inside the chosen square. Then he paints each cell of this row and this column inside the chosen square. After that the rectangles, formed by the square's border and the newly painted cells, must be squares of a non-zero area. An example of correct painting at n = 7 ΠΈ k = 2. The bear already knows numbers n and k. Help him β€” find the number of ways to paint the square in exactly k moves. Two ways to paint are called distinct if the resulting tables will differ in at least one cell. As the answer can be rather large, print the remainder after dividing it by 7340033.InputThe first line contains integer q (1 ≀ q ≀ 105) β€” the number of test data.Each of the following q lines contains two integers n and k (1 ≀ n ≀ 109, 0 ≀ k ≀ 1000) β€” the size of the initial table and the number of moves for the corresponding test.OutputFor each test from the input print the answer to the problem modulo 7340033. Print the answers to the tests in the order in which the tests are given in the input.ExamplesInput81 01 13 03 12 02 13 27 2Output10111004NoteAll possible painting ways for the test n = 7 and k = 2 are:
Input81 01 13 03 12 02 13 27 2
Output10111004
3 seconds
256 megabytes
['dp', 'fft', '*2300']
C. Beautiful Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitaly is a very weird man. He's got two favorite digits a and b. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits a and b. Vitaly calls a good number excellent, if the sum of its digits is a good number.For example, let's say that Vitaly's favourite digits are 1 and 3, then number 12 isn't good and numbers 13 or 311 are. Also, number 111 is excellent and number 11 isn't. Now Vitaly is wondering, how many excellent numbers of length exactly n are there. As this number can be rather large, he asks you to count the remainder after dividing it by 1000000007 (109 + 7).A number's length is the number of digits in its decimal representation without leading zeroes.InputThe first line contains three integers: a, b, n (1 ≀ a < b ≀ 9, 1 ≀ n ≀ 106).OutputPrint a single integer β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput1 3 3Output1Input2 3 10Output165
Input1 3 3
Output1
2 seconds
256 megabytes
['brute force', 'combinatorics', '*1800']
B. Coachtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.InputThe first line of the input contains integers n and m (3 ≀ n ≀ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≀ ai < bi ≀ n) β€” the pair ai, bi means that students with numbers ai and bi want to be on the same team.It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.OutputIf the required division into teams doesn't exist, print number -1. Otherwise, print lines. In each line print three integers xi, yi, zi (1 ≀ xi, yi, zi ≀ n) β€” the i-th team. If there are multiple answers, you are allowed to print any of them.ExamplesInput3 0Output3 2 1 Input6 41 22 33 45 6Output-1Input3 31 22 31 3Output3 2 1
Input3 0
Output3 2 1
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'graphs', '*1500']
A. Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero ( < 0). The product of all numbers in the second set is greater than zero ( > 0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.InputThe first line of the input contains integer n (3 ≀ n ≀ 100). The second line contains n space-separated distinct integers a1, a2, ..., an (|ai| ≀ 103) β€” the array elements.OutputIn the first line print integer n1 (n1 > 0) β€” the number of elements in the first set. Then print n1 numbers β€” the elements that got to the first set.In the next line print integer n2 (n2 > 0) β€” the number of elements in the second set. Then print n2 numbers β€” the elements that got to the second set.In the next line print integer n3 (n3 > 0) β€” the number of elements in the third set. Then print n3 numbers β€” the elements that got to the third set.The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them.ExamplesInput3-1 2 0Output1 -11 21 0Input4-1 -2 -3 0Output1 -12 -3 -21 0
Input3-1 2 0
Output1 -11 21 0
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'implementation', '*1100']
B. Ksusha the Squirreltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKsusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i + 1, i + 2, ..., i + k. Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?InputThe first line contains two integers n and k (2 ≀ n ≀ 3Β·105, 1 ≀ k ≀ 3Β·105). The next line contains n characters β€” the description of the road: the i-th character equals ".", if the i-th sector contains no rocks. Otherwise, it equals "#".It is guaranteed that the first and the last characters equal ".".OutputPrint "YES" (without the quotes) if Ksusha can reach the end of the road, otherwise print "NO" (without the quotes).ExamplesInput2 1..OutputYESInput5 2.#.#.OutputYESInput7 3.#.###.OutputNO
Input2 1..
OutputYES
1 second
256 megabytes
['brute force', 'implementation', '*900']
A. Ksusha and Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKsusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!InputThe first line contains integer n (1 ≀ n ≀ 105), showing how many numbers the array has. The next line contains integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the array elements.OutputPrint a single integer β€” the number from the array, such that all array elements are divisible by it. If such number doesn't exist, print -1.If there are multiple answers, you are allowed to print any of them.ExamplesInput32 2 4Output2Input52 1 3 1 6Output1Input32 3 5Output-1
Input32 2 4
Output2
2 seconds
256 megabytes
['brute force', 'number theory', 'sortings', '*1000']
B. Sailtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y). If the wind blows to the east, the boat will move to (x + 1, y). If the wind blows to the south, the boat will move to (x, y - 1). If the wind blows to the west, the boat will move to (x - 1, y). If the wind blows to the north, the boat will move to (x, y + 1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?InputThe first line contains five integers t, sx, sy, ex, ey (1 ≀ t ≀ 105,  - 109 ≀ sx, sy, ex, ey ≀ 109). The starting location and the ending location will be different.The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).OutputIf they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).ExamplesInput5 0 0 1 1SESNWOutput4Input10 5 3 3 6NENSWESNEEOutput-1NoteIn the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.In the second sample, they cannot sail to the destination.
Input5 0 0 1 1SESNW
Output4
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*1200']
A. Snow Footprintstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one. At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.InputThe first line of the input contains integer n (3 ≀ n ≀ 1000).The second line contains the description of the road β€” the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint).It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists.OutputPrint two space-separated integers β€” the values of s and t. If there are several possible solutions you can print any of them.ExamplesInput9..RRLL...Output3 4Input11.RRRLLLLL..Output7 5NoteThe first test sample is the one in the picture.
Input9..RRLL...
Output3 4
1 second
256 megabytes
['greedy', 'implementation', '*1300']
E. Mystic Carvingstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe polar bears have discovered a gigantic circular piece of floating ice with some mystic carvings on it. There are n lines carved on the ice. Each line connects two points on the boundary of the ice (we call these points endpoints). The endpoints are numbered 1, 2, ..., 2n counter-clockwise along the circumference. No two lines share an endpoint.Now a group of 6 polar bears (Alice, Bob, Carol, Dave, Eve, Frank) are going to build caves on the endpoints. Each polar bear would build a cave and live in it. No two polar bears can build a cave on the same endpoints. Alice and Bob is a pair of superstitious lovers. They believe the lines are carved by aliens (or humans, which are pretty much the same thing to polar bears), and have certain spiritual power. Therefore they want to build their caves on two endpoints which are connected by a line. The same for Carol and Dave, Eve and Frank.The distance between two caves X and Y is defined as one plus minimum number of other caves one need to pass through in order to travel from X to Y along the boundary of the ice (endpoints without caves are not counted).To ensure fairness, the distances between the three pairs of lovers have to be the same (that is, the distance between Alice and Bob, the distance between Carol and Dave, and the distance between Eve and Frank are the same).The figures below show two different configurations, where the dots on the circle are the endpoints. The configuration on the left is not valid. Although each pair of lovers (A and B, C and D, E and F) is connected a line, the distance requirement is not satisfied. The distance between A and B is 2 (one can go from A to B in the clockwise direction passing through F). The distance between E and F is also 2. However, the distance between C and D is 1 (one can go from C to D in the counter-clockwise direction without passing through any other caves). The configuration on the right is valid. All three pairs have the same distance 1. Count the number of ways to build the caves under the requirements. Two configurations are considered the same if the same set of 6 endpoints are used.InputThe first line contains integer n(3 ≀ n ≀ 105) β€” the number of lines.Each of the following n lines contains two integers ai, bi (1 ≀ ai, bi ≀ 2n), which means that there is a line carved on the ice connecting the ai–th and bi–th endpoint. It's guaranteed that each endpoints touches exactly one line.OutputPrint the number of ways to build the caves.Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput45 41 26 78 3Output2Input81 72 43 95 116 810 1613 1514 12Output6NoteThe second sample corresponds to the figure in the problem statement.
Input45 41 26 78 3
Output2
3 seconds
256 megabytes
['data structures', '*3000']
D. Color the Carpettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEven polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height h and width w. Then the grid is divided into h × w squares. Alice is going to assign one of k different colors to each square. The colors are numbered from 1 to k. She may choose not to use all of the colors.However, there are some restrictions. For every two adjacent squares (squares that shares an edge) x and y, there is a color constraint in one of the forms: color(x) = color(y), or color(x) ≠ color(y). Example of the color constraints: Ideally, Alice wants to satisfy all color constraints. But again, life in the Arctic is hard. It is not always possible to satisfy all color constraints. Fortunately, she will still be happy if at least of the color constraints are satisfied. If she has 4 colors she can color the carpet in the following way: And she is happy because of the color constraints are satisfied, and . Your task is to help her color the carpet.InputThe first line contains three integers h, w, k (2 ≀ h, w ≀ 1000, 1 ≀ k ≀ wΒ·h).The next 2h - 1 lines describe the color constraints from top to bottom, left to right. They contain w - 1, w, w - 1, w, ..., w - 1 characters respectively. Each color constraint is represented by a character "E" or "N", where "E" means " = " and "N" means " ≠ ".The color constraints listed in the order they are depicted on the picture.OutputIf there is a coloring that satisfies at least of the color constraints, print "YES" (without quotes) in the first line. In each of the next h lines, print w integers describing the coloring.Otherwise, print "NO" (without quotes).ExamplesInput3 4 4ENENNEENEEENENENNOutputYES1 1 2 23 4 1 13 3 2 4
Input3 4 4ENENNEENEEENENENN
OutputYES1 1 2 23 4 1 13 3 2 4
1 second
256 megabytes
['constructive algorithms', '*2500']
C. Splitting the Uniquenesstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolar bears like unique arrays β€” that is, arrays without repeated elements. You have got a unique array s with length n containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays a and b that are also of length n, with the following conditions for all i (1 ≀ i ≀ n): ai, bi are non-negative integers; si = ai + bi . Ideally, a and b should also be unique arrays. However, life in the Arctic is hard and this is not always possible. Fortunately, Alice and Bob are still happy if their arrays are almost unique. We define an array of length n to be almost unique, if and only if it can be turned into a unique array by removing no more than entries.For example, the array [1, 2, 1, 3, 2] is almost unique because after removing the first two entries, it becomes [1, 3, 2]. The array [1, 2, 1, 3, 1, 2] is not almost unique because we need to remove at least 3 entries to turn it into a unique array.So, your task is to split the given unique array s into two almost unique arrays a and b.InputThe first line of the input contains integer n (1 ≀ n ≀ 105).The second line contains n distinct integers s1, s2, ... sn (0 ≀ si ≀ 109).OutputIf it is possible to make Alice and Bob happy (if you can split the given array), print "YES" (without quotes) in the first line. In the second line, print the array a. In the third line, print the array b. There may be more than one solution. Any of them will be accepted.If it is impossible to split s into almost unique arrays a and b, print "NO" (without quotes) in the first line.ExamplesInput612 5 8 3 11 9OutputYES6 2 6 0 2 46 3 2 3 9 5NoteIn the sample, we can remove the first two entries from a and the second entry from b to make them both unique.
Input612 5 8 3 11 9
OutputYES6 2 6 0 2 46 3 2 3 9 5
1 second
256 megabytes
['constructive algorithms', '*2400']
B. Fish Weighttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≀ w2 ≀ ... ≀ wk holds.Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a strictly larger total weight than Bob's. In other words, does there exist a sequence of weights wi (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?InputThe first line contains three integers n, m, k (1 ≀ n, m ≀ 105, 1 ≀ k ≀ 109) β€” the number of fish caught by Alice and Bob respectively, and the number of fish species.The second line contains n integers each from 1 to k, the list of fish type caught by Alice. The third line contains m integers each from 1 to k, the list of fish type caught by Bob.Note that one may have caught more than one fish for a same species.OutputOutput "YES" (without quotes) if it is possible, and "NO" (without quotes) otherwise.ExamplesInput3 3 32 2 21 1 3OutputYESInput4 7 95 2 7 33 5 2 7 3 8 7OutputNONoteIn the first sample, if w1 = 1, w2 = 2, w3 = 2.5, then Alice has a total of 2 + 2 + 2 = 6 weight units, while Bob only has 1 + 1 + 2.5 = 4.5.In the second sample, the fish that Alice caught is a subset of Bob's. Therefore, the total weight of Bob’s fish is always not less than the total weight of Alice’s fish.
Input3 3 32 2 21 1 3
OutputYES
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1600']
A. Parity Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations: Write parity(a) to the end of a. For example, . Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.InputThe first line contains the string a and the second line contains the string b (1 ≀ |a|, |b| ≀ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.OutputPrint "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.ExamplesInput010110110OutputYESInput00111110OutputNONoteIn the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110
Input010110110
OutputYES
1 second
256 megabytes
['constructive algorithms', '*1700']
B. Yaroslav and Two Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w.A string's template is a string that consists of digits and question marks ("?").Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers.Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7).InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format.OutputIn a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7).ExamplesInput29009Output1Input21155Output0Input5??????????Output993531194NoteThe first test contains no question marks and both strings are incomparable, so the answer is 1.The second test has no question marks, but the given strings are comparable, so the answer is 0.
Input29009
Output1
2 seconds
256 megabytes
['combinatorics', 'dp', '*2000']
A. Yaroslav and Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.Help Yaroslav.InputThe first line contains integer n (1 ≀ n ≀ 100) β€” the number of elements in the array. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 1000) β€” the array elements.OutputIn the single line print "YES" (without the quotes) if Yaroslav can obtain the array he needs, and "NO" (without the quotes) otherwise.ExamplesInput11OutputYESInput31 1 2OutputYESInput47 7 7 7OutputNONoteIn the first sample the initial array fits well.In the second sample Yaroslav can get array: 1, 2, 1. He can swap the last and the second last elements to obtain it.In the third sample Yarosav can't get the array he needs.
Input11
OutputYES
2 seconds
256 megabytes
['greedy', 'math', '*1100']
E. Yaroslav and Pointstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav has n points that lie on the Ox axis. The coordinate of the first point is x1, the coordinate of the second point is x2, ..., the coordinate of the n-th point is β€” xn. Now Yaroslav wants to execute m queries, each of them is of one of the two following types: Move the pj-th point from position xpj to position xpj + dj. At that, it is guaranteed that after executing such query all coordinates of the points will be distinct. Count the sum of distances between all pairs of points that lie on the segment [lj, rj] (lj ≀ rj). In other words, you should count the sum of: . Help Yaroslav.InputThe first line contains integer n β€” the number of points (1 ≀ n ≀ 105). The second line contains distinct integers x1, x2, ..., xn β€” the coordinates of points (|xi| ≀ 109).The third line contains integer m β€” the number of queries (1 ≀ m ≀ 105). The next m lines contain the queries. The j-th line first contains integer tj (1 ≀ tj ≀ 2) β€” the query type. If tj = 1, then it is followed by two integers pj and dj (1 ≀ pj ≀ n, |dj| ≀ 1000). If tj = 2, then it is followed by two integers lj and rj ( - 109 ≀ lj ≀ rj ≀ 109).It is guaranteed that at any moment all the points have distinct coordinates.OutputFor each type 2 query print the answer on a single line. Print the answers in the order, in which the queries follow 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 of the %I64d specifier.ExamplesInput836 50 28 -75 40 -60 -95 -48202 -61 291 5 -531 1 4291 5 1302 -101 -712 -69 531 1 4041 5 5182 -101 532 50 8721 1 -2072 -99 -401 7 -3891 6 -1711 2 4641 7 -7071 1 -7301 1 5602 635 6441 7 -677Output17620406104616381560
Input836 50 28 -75 40 -60 -95 -48202 -61 291 5 -531 1 4291 5 1302 -101 -712 -69 531 1 4041 5 5182 -101 532 50 8721 1 -2072 -99 -401 7 -3891 6 -1711 2 4641 7 -7071 1 -7301 1 5602 635 6441 7 -677
Output17620406104616381560
5 seconds
256 megabytes
['data structures', '*2500']
D. Greg and Cavestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGreg has a pad. The pad's screen is an n × m rectangle, each cell can be either black or white. We'll consider the pad rows to be numbered with integers from 1 to n from top to bottom. Similarly, the pad's columns are numbered with integers from 1 to m from left to right.Greg thinks that the pad's screen displays a cave if the following conditions hold: There is a segment [l, r] (1 ≀ l ≀ r ≀ n), such that each of the rows l, l + 1, ..., r has exactly two black cells and all other rows have only white cells. There is a row number t (l ≀ t ≀ r), such that for all pairs of rows with numbers i and j (l ≀ i ≀ j ≀ t) the set of columns between the black cells in row i (with the columns where is these black cells) is the subset of the set of columns between the black cells in row j (with the columns where is these black cells). Similarly, for all pairs of rows with numbers i and j (t ≀ i ≀ j ≀ r) the set of columns between the black cells in row j (with the columns where is these black cells) is the subset of the set of columns between the black cells in row i (with the columns where is these black cells). Greg wondered, how many ways there are to paint a cave on his pad. Two ways can be considered distinct if there is a cell that has distinct colors on the two pictures.Help Greg.InputThe first line contains two integers n, m β€” the pad's screen size (1 ≀ n, m ≀ 2000).OutputIn the single line print the remainder after dividing the answer to the problem by 1000000007 (109 + 7).ExamplesInput1 1Output0Input4 4Output485Input3 5Output451
Input1 1
Output0
2 seconds
256 megabytes
['combinatorics', 'dp', '*2400']
C. Greg and Friendstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold people with the total weight of at most k kilograms.Greg immediately took a piece of paper and listed there the weights of all people in his group (including himself). It turned out that each person weights either 50 or 100 kilograms. Now Greg wants to know what minimum number of times the boat needs to cross the river to transport the whole group to the other bank. The boat needs at least one person to navigate it from one bank to the other. As the boat crosses the river, it can have any non-zero number of passengers as long as their total weight doesn't exceed k.Also Greg is wondering, how many ways there are to transport everybody to the other side in the minimum number of boat rides. Two ways are considered distinct if during some ride they have distinct sets of people on the boat.Help Greg with this problem. InputThe first line contains two integers n, k (1 ≀ n ≀ 50, 1 ≀ k ≀ 5000) β€” the number of people, including Greg, and the boat's weight limit. The next line contains n integers β€” the people's weights. A person's weight is either 50 kilos or 100 kilos.You can consider Greg and his friends indexed in some way.OutputIn the first line print an integer β€” the minimum number of rides. If transporting everyone to the other bank is impossible, print an integer -1.In the second line print the remainder after dividing the number of ways to transport the people in the minimum number of rides by number 1000000007 (109 + 7). If transporting everyone to the other bank is impossible, print integer 0.ExamplesInput1 5050Output11Input3 10050 50 100Output52Input2 5050 50Output-10NoteIn the first test Greg walks alone and consequently, he needs only one ride across the river.In the second test you should follow the plan: transport two 50 kg. people; transport one 50 kg. person back; transport one 100 kg. person; transport one 50 kg. person back; transport two 50 kg. people. That totals to 5 rides. Depending on which person to choose at step 2, we can get two distinct ways.
Input1 5050
Output11
2 seconds
256 megabytes
['combinatorics', 'dp', 'graphs', 'shortest paths', '*2100']
B. Greg and Graphtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGreg has a weighed directed graph, consisting of n vertices. In this graph any pair of distinct vertices has an edge between them in both directions. Greg loves playing with the graph and now he has invented a new game: The game consists of n steps. On the i-th step Greg removes vertex number xi from the graph. As Greg removes a vertex, he also removes all the edges that go in and out of this vertex. Before executing each step, Greg wants to know the sum of lengths of the shortest paths between all pairs of the remaining vertices. The shortest path can go through any remaining vertex. In other words, if we assume that d(i, v, u) is the shortest path between vertices v and u in the graph that formed before deleting vertex xi, then Greg wants to know the value of the following sum: . Help Greg, print the value of the required sum before each step.InputThe first line contains integer n (1 ≀ n ≀ 500) β€” the number of vertices in the graph.Next n lines contain n integers each β€” the graph adjacency matrix: the j-th number in the i-th line aij (1 ≀ aij ≀ 105, aii = 0) represents the weight of the edge that goes from vertex i to vertex j.The next line contains n distinct integers: x1, x2, ..., xn (1 ≀ xi ≀ n) β€” the vertices that Greg deletes.OutputPrint n integers β€” the i-th number equals the required sum before the i-th step.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 of the %I64d specifier.ExamplesInput101Output0 Input20 54 01 2Output9 0 Input40 3 1 16 0 400 12 4 0 11 1 1 04 1 2 3Output17 23 404 0
Input101
Output0
3 seconds
256 megabytes
['dp', 'graphs', 'shortest paths', '*1700']
A. Greg and Arraytime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGreg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≀ li ≀ ri ≀ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di.Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, (1 ≀ xi ≀ yi ≀ m). That means that one should apply operations with numbers xi, xi + 1, ..., yi to the array.Now Greg is wondering, what the array a will be after all the queries are executed. Help Greg.InputThe first line contains integers n, m, k (1 ≀ n, m, k ≀ 105). The second line contains n integers: a1, a2, ..., an (0 ≀ ai ≀ 105) β€” the initial array.Next m lines contain operations, the operation number i is written as three integers: li, ri, di, (1 ≀ li ≀ ri ≀ n), (0 ≀ di ≀ 105).Next k lines contain the queries, the query number i is written as two integers: xi, yi, (1 ≀ xi ≀ yi ≀ m).The numbers in the lines are separated by single spaces.OutputOn a single line print n integers a1, a2, ..., an β€” the array after executing all the queries. Separate the printed numbers by spaces.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 of the %I64d specifier.ExamplesInput3 3 31 2 31 2 11 3 22 3 41 21 32 3Output9 18 17Input1 1 111 1 11 1Output2Input4 3 61 2 3 41 2 12 3 23 4 41 21 32 31 21 32 3Output5 18 31 20
Input3 3 31 2 31 2 11 3 22 3 41 21 32 3
Output9 18 17
1.5 seconds
256 megabytes
['data structures', 'implementation', '*1400']
E. Shaass the Greattime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe great Shaass is the new king of the Drakht empire. The empire has n cities which are connected by n - 1 bidirectional roads. Each road has an specific length and connects a pair of cities. There's a unique simple path connecting each pair of cities.His majesty the great Shaass has decided to tear down one of the roads and build another road with the same length between some pair of cities. He should build such road that it's still possible to travel from each city to any other city. He might build the same road again.You as his advisor should help him to find a way to make the described action. You should find the way that minimize the total sum of pairwise distances between cities after the action. So calculate the minimum sum.InputThe first line of the input contains an integer n denoting the number of cities in the empire, (2 ≀ n ≀ 5000). The next n - 1 lines each contains three integers ai, bi and wi showing that two cities ai and bi are connected using a road of length wi, (1 ≀ ai, bi ≀ n, ai ≠ bi, 1 ≀ wi ≀ 106).OutputOn the only line of the output print the minimum pairwise sum of distances between the cities.Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInput31 2 21 3 4Output12Input61 2 12 3 13 4 14 5 15 6 1Output29Input61 3 12 3 13 4 1004 5 24 6 1Output825
Input31 2 21 3 4
Output12
3.5 seconds
256 megabytes
['dp', 'trees', '*2300']
D. Shaass and Painter Robottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputShaass thinks a kitchen with all white floor tiles is so boring. His kitchen floor is made of nΒ·m square tiles forming a n × m rectangle. Therefore he's decided to color some of the tiles in black so that the floor looks like a checkerboard, which is no two side-adjacent tiles should have the same color.Shaass wants to use a painter robot to color the tiles. In the beginning the robot is standing in a border tile (xs, ys) facing a diagonal direction (i.e. upper-left, upper-right, down-left or down-right). As the robot walks in the kitchen he paints every tile he passes even if it's painted before. Painting each tile consumes one unit of black paint. If at any moment the robot hits a wall of the kitchen he changes his direction according the reflection rules. Note that a tile gets painted when the robot enters the tile from another tile, in other words changing direction in the same tile doesn't lead to any painting. The first tile the robot is standing on, is also painted.The robot stops painting the first moment the floor is checkered. Given the dimensions of the kitchen and the position of the robot, find out the amount of paint the robot consumes before it stops painting the floor.Let's consider an examples depicted below. If the robot starts at tile number 1 (the tile (1, 1)) of the left grid heading to down-right it'll pass tiles 1354236 and consumes 7 units of black paint on his way until he stops at tile number 6. But if it starts at tile number 1 in the right grid heading to down-right it will get stuck in a loop painting tiles 1, 2, and 3.InputThe first line of the input contains two integers n and m, (2 ≀ n, m ≀ 105). The second line contains two integers xs and ys (1 ≀ xs ≀ n, 1 ≀ ys ≀ m) and the direction robot is facing initially. Direction is one of the strings: "UL" (upper-left direction), "UR" (upper-right), "DL" (down-left) or "DR" (down-right).Note, that record (xs, ys) denotes the tile that is located at the xs-th row from the top and at the ys-th column from the left of the kitchen.It's guaranteed that the starting position will be a border tile (a tile with less than four side-adjacent tiles).OutputPrint the amount of paint the robot consumes to obtain a checkered kitchen floor. Or print -1 if it never happens.Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInput3 41 1 DROutput7Input3 43 3 DROutput11Input3 31 1 DROutput-1Input3 31 2 DLOutput4
Input3 41 1 DR
Output7
2 seconds
256 megabytes
['brute force', 'implementation', 'number theory', '*2500']
C. Shaass and Lightstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007Β (109 + 7).InputThe first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≀ n ≀ 1000, 1 ≀ m ≀ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on.OutputIn the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007Β (109 + 7).ExamplesInput3 11Output1Input4 21 4Output2Input11 24 8Output6720
Input3 11
Output1
1 second
256 megabytes
['combinatorics', 'number theory', '*1900']
B. Shaass and Bookshelftime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputShaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is ti and its pages' width is equal to wi. The thickness of each book is either 1 or 2. All books have the same page heights. Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure. Help Shaass to find the minimum total thickness of the vertical books that we can achieve.InputThe first line of the input contains an integer n, (1 ≀ n ≀ 100). Each of the next n lines contains two integers ti and wi denoting the thickness and width of the i-th book correspondingly, (1 ≀ ti ≀ 2, 1 ≀ wi ≀ 100).OutputOn the only line of the output print the minimum total thickness of the vertical books that we can achieve.ExamplesInput51 121 32 152 52 1Output5Input31 102 12 4Output3
Input51 121 32 152 52 1
Output5
1 second
256 megabytes
['dp', 'greedy', '*1700']
A. Shaass and Oskolstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputShaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols sitting on the i-th wire. Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the i-th wire). Consequently all the birds on the i-th wire to the left of the dead bird get scared and jump up on the wire number i - 1, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number i + 1, if there exists no such wire they fly away. Shaass has shot m birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.InputThe first line of the input contains an integer n, (1 ≀ n ≀ 100). The next line contains a list of space-separated integers a1, a2, ..., an, (0 ≀ ai ≀ 100). The third line contains an integer m, (0 ≀ m ≀ 100). Each of the next m lines contains two integers xi and yi. The integers mean that for the i-th time Shaass shoot the yi-th (from left) bird on the xi-th wire, (1 ≀ xi ≀ n, 1 ≀ yi). It's guaranteed there will be at least yi birds on the xi-th wire at that moment.OutputOn the i-th line of the output print the number of birds on the i-th wire.ExamplesInput510 10 10 10 1052 53 132 121 134 6Output0125016Input32 4 112 2Output303
Input510 10 10 10 1052 53 132 121 134 6
Output0125016
2 seconds
256 megabytes
['implementation', 'math', '*800']
E. Close Verticestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a weighted tree, consisting of n vertices. Each edge has a non-negative weight. The length of the path between any two vertices of the tree is the number of edges in the path. The weight of the path is the total weight of all edges it contains. Two vertices are close if there exists a path of length at most l between them and a path of weight at most w between them. Count the number of pairs of vertices v, u (v < u), such that vertices v and u are close.InputThe first line contains three integers n, l and w (1 ≀ n ≀ 105, 1 ≀ l ≀ n, 0 ≀ w ≀ 109). The next n - 1 lines contain the descriptions of the tree edges. The i-th line contains two integers pi, wi (1 ≀ pi < (i + 1), 0 ≀ wi ≀ 104), that mean that the i-th edge connects vertex (i + 1) and pi and has weight wi.Consider the tree vertices indexed from 1 to n in some way.OutputPrint a single integer β€” the number of close pairs.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.ExamplesInput4 4 61 31 41 3Output4Input6 2 171 32 52 131 65 9Output9
Input4 4 61 31 41 3
Output4
5 seconds
256 megabytes
['data structures', 'divide and conquer', 'trees', '*2700']
D. Ksusha and Squaretime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKsusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles. Today Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the polygon and then draws a square with two opposite vertices lying in the chosen points, what will the expectation of this square's area be?A pair of distinct points is chosen uniformly among all pairs of distinct points, located inside or on the border of the polygon. Pairs of points p, q (p ≠ q) and q, p are considered the same.Help Ksusha! Count the required expectation.InputThe first line contains integer n (3 ≀ n ≀ 105) β€” the number of vertices of Ksusha's convex polygon. Next n lines contain the coordinates of the polygon vertices in clockwise or counterclockwise order. The i-th line contains integers xi, yi (|xi|, |yi| ≀ 106) β€” the coordinates of the vertex that goes i-th in that order.OutputPrint a single real number β€” the required expected area. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6.ExamplesInput30 05 55 0Output4.6666666667Input4-1 34 56 23 -5Output8.1583333333Input317 136859 93716 641Output66811.3704155169
Input30 05 55 0
Output4.6666666667
4 seconds
256 megabytes
['geometry', 'math', 'probabilities', 'two pointers', '*2700']
C. Cube Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav, Andrey and Roman love playing cubes. Sometimes they get together and play cubes for hours and hours! Today they got together again and they are playing cubes. Yaroslav took unit cubes and composed them into an a × a × a cube, Andrey made a b × b × b cube and Roman made a c × c × c cube. After that the game was finished and the guys left. But later, Vitaly entered the room. He saw the cubes and wanted to make a cube as well. But what size should the cube be? Of course it should be a large cube with the side of length a + b + c. Besides, Vitaly decided to decompose the cubes built by Yaroslav, Andrey and Roman and compose his own large cube out of them. However, it turned out that the unit cubes he got from destroying the three cubes just weren't enough to make a large cube. We know that Vitaly was short of exactly n cubes. Vitaly got upset, demolished everything and left. As he was leaving, he met Petya and told him that there had been three cubes in the room and that he needed another n unit cubes to make his own large cube.Petya entered the room and saw the messily scattered cubes. He wanted to make it neat and orderly again. But he only knows that there had been three cubes, made of small unit cubes and that Vitaly needed n more unit cubes to make a large one! Help Petya understand, how many ways of sizes a, b, c are there to restore Yaroslav's, Andrey's and Roman's cubes.InputThe single line of the input contains integer n (1 ≀ n ≀ 1014). We know that all numbers a, b, c are positive integers.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.OutputIn the single line print the required number of ways. If it turns out that there isn't a single way of suitable sizes of a, b, c, print 0. ExamplesInput24Output1Input648Output7Input5Output0Input93163582512000Output39090
Input24
Output1
2 seconds
256 megabytes
['brute force', 'math', 'number theory', '*2400']
B. Distinct Pathstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a rectangular n × m-cell board. Some cells are already painted some of k colors. You need to paint each uncolored cell one of the k colors so that any path from the upper left square to the lower right one doesn't contain any two cells of the same color. The path can go only along side-adjacent cells and can only go down or right.Print the number of possible paintings modulo 1000000007 (109 + 7).InputThe first line contains three integers n, m, k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 10). The next n lines contain m integers each β€” the board. The first of them contains m uppermost cells of the board from the left to the right and the second one contains m cells from the second uppermost row and so on. If a number in a line equals 0, then the corresponding cell isn't painted. Otherwise, this number represents the initial color of the board cell β€” an integer from 1 to k.Consider all colors numbered from 1 to k in some manner.OutputPrint the number of possible paintings modulo 1000000007 (109 + 7).ExamplesInput2 2 40 00 0Output48Input2 2 41 22 1Output0Input5 6 100 0 0 0 0 00 0 0 0 0 00 0 0 0 0 00 0 0 0 0 00 0 0 0 0 0Output3628800Input2 6 101 2 3 4 5 60 0 0 0 0 0Output4096
Input2 2 40 00 0
Output48
2 seconds
256 megabytes
['brute force', 'combinatorics', '*2700']
A. Weird Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2Β·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to 2Β·n, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string. Let's represent Yaroslav's word as s = s1s2... s2n. Similarly, let's represent Andrey's word as t = t1t2... t2n. Then, if Yaroslav choose number k during his move, then he is going to write out character sk on the piece of paper. Similarly, if Andrey choose number r during his move, then he is going to write out character tr on the piece of paper.The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw.You are given two strings s and t. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.InputThe first line contains integer n (1 ≀ n ≀ 106). The second line contains string s β€” Yaroslav's word. The third line contains string t β€” Andrey's word.It is guaranteed that both words consist of 2Β·n characters "0" and "1".OutputPrint "First", if both players play optimally well and Yaroslav wins. If Andrey wins, print "Second" and if the game ends with a draw, print "Draw". Print the words without the quotes.ExamplesInput201110001OutputFirstInput3110110001001OutputFirstInput3111000000111OutputDrawInput40101011000101101OutputFirstInput40110000010010011OutputSecond
Input201110001
OutputFirst
2 seconds
256 megabytes
['games', 'greedy', '*1500']
E. Copying Datatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe often have to copy large volumes of information. Such operation can take up many computer resources. Therefore, in this problem you are advised to come up with a way to copy some part of a number array into another one, quickly.More formally, you've got two arrays of integers a1, a2, ..., an and b1, b2, ..., bn of length n. Also, you've got m queries of two types: Copy the subsegment of array a of length k, starting from position x, into array b, starting from position y, that is, execute by + q = ax + q for all integer q (0 ≀ q < k). The given operation is correct β€” both subsegments do not touch unexistent elements. Determine the value in position x of array b, that is, find value bx. For each query of the second type print the result β€” the value of the corresponding element of array b.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of elements in the arrays and the number of queries, correspondingly. The second line contains an array of integers a1, a2, ..., an (|ai| ≀ 109). The third line contains an array of integers b1, b2, ..., bn (|bi| ≀ 109).Next m lines contain the descriptions of the queries. The i-th line first contains integer ti β€” the type of the i-th query (1 ≀ ti ≀ 2). If ti = 1, then the i-th query means the copying operation. If ti = 2, then the i-th query means taking the value in array b. If ti = 1, then the query type is followed by three integers xi, yi, ki (1 ≀ xi, yi, ki ≀ n) β€” the parameters of the copying query. If ti = 2, then the query type is followed by integer xi (1 ≀ xi ≀ n) β€” the position in array b.All numbers in the lines are separated with single spaces. It is guaranteed that all the queries are correct, that is, the copying borders fit into the borders of arrays a and b.OutputFor each second type query print the result on a single line.ExamplesInput5 101 2 0 -1 33 1 5 -2 02 51 3 3 32 52 42 11 2 1 42 12 41 4 2 12 2Output03-1323-1
Input5 101 2 0 -1 33 1 5 -2 02 51 3 3 32 52 42 11 2 1 42 12 41 4 2 12 2
Output03-1323-1
2 seconds
256 megabytes
['data structures', '*1900']
D. Connected Componentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe already know of the large corporation where Polycarpus works as a system administrator. The computer network there consists of n computers and m cables that connect some pairs of computers. In other words, the computer network can be represented as some non-directed graph with n nodes and m edges. Let's index the computers with integers from 1 to n, let's index the cables with integers from 1 to m.Polycarpus was given an important task β€” check the reliability of his company's network. For that Polycarpus decided to carry out a series of k experiments on the computer network, where the i-th experiment goes as follows: Temporarily disconnect the cables with indexes from li to ri, inclusive (the other cables remain connected). Count the number of connected components in the graph that is defining the computer network at that moment. Re-connect the disconnected cables with indexes from li to ri (that is, restore the initial network). Help Polycarpus carry out all experiments and for each print the number of connected components in the graph that defines the computer network through the given experiment. Isolated vertex should be counted as single component.InputThe first line contains two space-separated integers n, m (2 ≀ n ≀ 500;Β 1 ≀ m ≀ 104) β€” the number of computers and the number of cables, correspondingly.The following m lines contain the cables' description. The i-th line contains space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n;Β xi ≠ yi) β€” the numbers of the computers that are connected by the i-th cable. Note that a pair of computers can be connected by multiple cables.The next line contains integer k (1 ≀ k ≀ 2Β·104) β€” the number of experiments. Next k lines contain the experiments' descriptions. The i-th line contains space-separated integers li, ri (1 ≀ li ≀ ri ≀ m) β€” the numbers of the cables that Polycarpus disconnects during the i-th experiment. OutputPrint k numbers, the i-th number represents the number of connected components of the graph that defines the computer network during the i-th experiment. ExamplesInput6 51 25 42 33 13 661 32 51 55 52 43 3Output456342
Input6 51 25 42 33 13 661 32 51 55 52 43 3
Output456342
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'dp', 'dsu', '*1900']
C. Beautiful IP Addressestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe problem uses a simplified TCP/IP address model, please read the statement carefully.An IP address is a 32-bit integer, represented as a group of four decimal 8-bit integers (without leading zeroes), separated by commas. For example, record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In the given problem an arbitrary group of four 8-bit integers is a correct IP address.Our hero Polycarpus still works as a system administrator in some large corporation. He likes beautiful IP addresses. To check if some IP address is beautiful, he should do the following: write out in a line four 8-bit numbers of the IP address, without the commas; check if the resulting string is a palindrome. Let us remind you that a palindrome is a string that reads the same from right to left and from left to right.For example, IP addresses 12.102.20.121 and 0.3.14.130 are beautiful (as strings "1210220121" and "0314130" are palindromes), and IP addresses 1.20.20.1 and 100.4.4.1 are not.Polycarpus wants to find all beautiful IP addresses that have the given set of digits. Each digit from the set must occur in the IP address at least once. IP address must not contain any other digits. Help him to cope with this difficult task.InputThe first line contains a single integer n (1 ≀ n ≀ 10) β€” the number of digits in the set. The second line contains the set of integers a1, a2, ..., an (0 ≀ ai ≀ 9). It is guaranteed that all digits in the set are distinct.OutputIn the first line print a single integer k β€” the number of beautiful IP addresses that contain the given set of digits. In the following k lines print the IP addresses, one per line in the arbitrary order.ExamplesInput60 1 2 9 8 7Output678.190.209.18779.180.208.19787.190.209.17889.170.207.19897.180.208.17998.170.207.189Input14Output164.4.4.44.4.4.444.4.44.44.4.44.444.44.4.44.44.4.444.44.44.44.44.44.4444.4.4.444.4.4.4444.4.44.444.4.44.4444.44.4.444.44.4.4444.44.44.444.44.44.44
Input60 1 2 9 8 7
Output678.190.209.18779.180.208.19787.190.209.17889.170.207.19897.180.208.17998.170.207.189
2 seconds
256 megabytes
['brute force', '*2000']
B. Network Topologytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computersPolycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture. (1) β€” bus, (2) β€” ring, (3) β€” star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown. InputThe first line contains two space-separated integers n and m (4 ≀ n ≀ 105;Β 3 ≀ m ≀ 105) β€” the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≀ xi, yi ≀ n) β€” the numbers of nodes that are connected by the i-the edge.It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself.OutputIn a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes).ExamplesInput4 31 22 33 4Outputbus topologyInput4 41 22 33 44 1Outputring topologyInput4 31 21 31 4Outputstar topologyInput4 41 22 33 11 4Outputunknown topology
Input4 31 22 33 4
Outputbus topology
2 seconds
256 megabytes
['graphs', 'implementation', '*1200']
A. SMSCtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC. For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci β€” the receiving time (the second) and the number of the text messages, correspondingly.Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows: If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x. If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue. Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.InputThe first line contains a single integer n (1 ≀ n ≀ 103) β€” the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≀ ti, ci ≀ 106) β€” the time (the second) when the i-th task was received and the number of messages to send, correspondingly.It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≀ i < n).OutputIn a single line print two space-separated integers β€” the time when the last text message was sent and the maximum queue size at a certain moment of time.ExamplesInput21 12 1Output3 1Input11000000 10Output1000010 10Input33 34 35 3Output12 7NoteIn the first test sample: second 1: the first message has appeared in the queue, the queue's size is 1; second 2: the first message is sent, the second message has been received, the queue's size is 1; second 3: the second message is sent, the queue's size is 0, Thus, the maximum size of the queue is 1, the last message was sent at the second 3.
Input21 12 1
Output3 1
2 seconds
256 megabytes
['implementation', '*1100']
E. Tree-String Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA rooted tree is a non-directed connected graph without any cycles with a distinguished vertex, which is called the tree root. Consider the vertices of a rooted tree, that consists of n vertices, numbered from 1 to n. In this problem the tree root is the vertex number 1.Let's represent the length of the shortest by the number of edges path in the tree between vertices v and u as d(v, u).A parent of vertex v in the rooted tree with the root in vertex r (v ≠ r) is vertex pv, such that d(r, pv) + 1 = d(r, v) and d(pv, v) = 1. For example, on the picture the parent of vertex v = 5 is vertex p5 = 2.One day Polycarpus came across a rooted tree, consisting of n vertices. The tree wasn't exactly ordinary: it had strings written on its edges. Polycarpus positioned the tree on the plane so as to make all edges lead from top to bottom if you go from the vertex parent to the vertex (see the picture). For any edge that lead from vertex pv to vertex v (1 < v ≀ n), he knows string sv that is written on it. All strings are written on the edges from top to bottom. For example, on the picture s7="ba". The characters in the strings are numbered starting from 0. An example of Polycarpus's tree (corresponds to the example from the statement) Polycarpus defines the position in this tree as a specific letter on a specific string. The position is written as a pair of integers (v, x) that means that the position is the x-th letter of the string sv (1 < v ≀ n, 0 ≀ x < |sv|), where |sv| is the length of string sv. For example, the highlighted letters are positions (2, 1) and (3, 1).Let's consider the pair of positions (v, x) and (u, y) in Polycarpus' tree, such that the way from the first position to the second goes down on each step. We will consider that the pair of such positions defines string z. String z consists of all letters on the way from (v, x) to (u, y), written in the order of this path. For example, in the picture the highlighted positions define string "bacaba".Polycarpus has a string t, he wants to know the number of pairs of positions that define string t. Note that the way from the first position to the second in the pair must go down everywhere. Help him with this challenging tree-string problem!InputThe first line contains integer n (2 ≀ n ≀ 105) β€” the number of vertices of Polycarpus's tree. Next n - 1 lines contain the tree edges. The i-th of them contains number pi + 1 and string si + 1 (1 ≀ pi + 1 ≀ n;Β pi + 1 ≠ (i + 1)). String si + 1 is non-empty and consists of lowercase English letters. The last line contains string t. String t consists of lowercase English letters, its length is at least 2.It is guaranteed that the input contains at most 3Β·105 English letters.OutputPrint a single integer β€” the required number.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.ExamplesInput71 ab5 bacaba1 abacaba2 aca5 ba2 baabaOutput6Input71 ab5 bacaba1 abacaba2 aca5 ba2 babacabaOutput4NoteIn the first test case string "aba" is determined by the pairs of positions: (2, 0) and (5, 0); (5, 2) and (6, 1); (5, 2) and (3, 1); (4, 0) and (4, 2); (4, 4) and (4, 6); (3, 3) and (3, 5).Note that the string is not defined by the pair of positions (7, 1) and (5, 0), as the way between them doesn't always go down.
Input71 ab5 bacaba1 abacaba2 aca5 ba2 baaba
Output6
1 second
256 megabytes
['*special problem', 'dfs and similar', 'hashing', 'strings', '*2000']
D. Parallel Programmingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has a computer with n processors. Also, his computer has n memory cells. We'll consider the processors numbered by integers from 1 to n and that the memory cells are consecutively numbered by integers from 1 to n.Polycarpus needs to come up with a parallel program model. For each memory cell number i this program must record the value n - i to this cell. In other words, for each cell you've got to find the distance to cell n.Let's denote the value that is written in the i-th cell as ai. Initially, ai = 1 (1 ≀ i < n) and an = 0. We will consider that only processor i can write values in the memory cell number i. All processors can read an information from some cell (several processors can read an information from some cell simultaneously).The parallel program is executed in several steps. During each step we execute the parallel version of the increment operation. Executing the parallel version of the increment operation goes as follows: Each processor independently of the other ones chooses some memory cell. Let's say that processor i has chosen a cell with number ci (1 ≀ ci ≀ n). All processors simultaneously execute operation ai = ai + aci. Help Polycarpus come up with the parallel program model that is executed in exactly k steps. Calculate the operations that need to be executed. Note that after k steps for all i's value ai must be equal n - i.InputThe first line contains two space-separated integers n and k (1 ≀ n ≀ 104, 1 ≀ k ≀ 20).It is guaranteed that at the given n and k the required sequence of operations exists.OutputPrint exactly nΒ·k integers in k lines. In the first line print numbers c1, c2, ..., cn (1 ≀ ci ≀ n) for the first increment operation. In the second line print the numbers for the second increment operation. In the k-th line print the numbers for the k-th increment operation.As a result of the printed operations for any i value ai must equal n - i.ExamplesInput1 1Output1Input3 2Output2 3 33 3 3
Input1 1
Output1
2 seconds
256 megabytes
['*special problem', 'greedy', '*1600']
C. Network Masktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively.Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address.Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess.The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as "11...11000..000". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000.To get the network address of the IP address, you need to perform the operation of the bitwise "and" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise "and" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one.Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so.InputThe first line contains two integers, n and k (1 ≀ k ≀ n ≀ 105) β€” the number of IP addresses and networks. The next n lines contain the IP addresses. It is guaranteed that all IP addresses are distinct.OutputIn a single line print the IP address of the subnet mask in the format that is described in the statement, if the required subnet mask exists. Otherwise, print -1.ExamplesInput5 30.0.0.10.1.1.20.0.2.10.1.1.00.0.2.3Output255.255.254.0Input5 20.0.0.10.1.1.20.0.2.10.1.1.00.0.2.3Output255.255.0.0Input2 1255.0.0.10.0.0.2Output-1
Input5 30.0.0.10.1.1.20.0.2.10.1.1.00.0.2.3
Output255.255.254.0
2 seconds
256 megabytes
['*special problem', 'bitmasks', 'brute force', 'implementation', '*1600']
B. Command Line Argumentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings are the lexemes of the command line β€” the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited β€” that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space).It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters.InputThe single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the ".,?!"" signs, or a space.It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme.OutputIn the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the "<" (less) character to the left of your lexemes and the ">" (more) character to the right. Print the lexemes in the order in which they occur in the command.Please, follow the given output format strictly. For more clarifications on the output format see the test samples.ExamplesInput"RUn.exe O" "" " 2ne, " two! . " "Output<RUn.exe O><>< 2ne, ><two!><.>< >Input firstarg second "" Output<firstarg><second><>
Input"RUn.exe O" "" " 2ne, " two! . " "
Output<RUn.exe O><>< 2ne, ><two!><.>< >
1 second
256 megabytes
['*special problem', 'implementation', 'strings', '*1300']
A. Spyke Talkstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted β€” that is, one call connects exactly two people.InputThe first line contains integer n (1 ≀ n ≀ 103) β€” the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≀ idi ≀ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise.Consider the secretaries indexed from 1 to n in some way.OutputPrint a single integer β€” the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.ExamplesInput60 1 7 1 7 10Output2Input31 1 1Output-1Input10Output0NoteIn the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.In the second test sample the described situation is impossible as conferences aren't allowed.
Input60 1 7 1 7 10
Output2
2 seconds
256 megabytes
['*special problem', 'implementation', 'sortings', '*800']
F. Greedy Petyatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya is an unexperienced programming contestant. Recently he has come across the following problem:You are given a non-directed graph which consists of n nodes and m edges. Your task is to determine whether the graph contains a Hamiltonian path.Petya wrote a quick bug-free code which he believes solves this problem. After that Petya decided to give this problem for April Fools Day contest. Unfortunately, Petya might have made a mistake, and it's quite possible that his algorithm is wrong. But this isn't a good excuse to leave the contest without submitting this problem, is it?InputThe first line contains two integers n, m (1 ≀ n ≀ 20;Β 0 ≀ m ≀ 400). Next m lines contain pairs of integers vi, ui (1 ≀ vi, ui ≀ n).OutputFollow the format of Petya's code output.ExamplesInput2 31 22 11 1OutputYesInput3 0OutputNoInput10 203 104 64 97 58 83 109 75 29 210 610 41 17 28 47 21 85 410 28 55 2OutputNo
Input2 31 22 11 1
OutputYes
2 seconds
256 megabytes
['*special problem', 'dfs and similar', 'graphs', 'greedy', '*2800']
E. HQtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset β€” a language called HQ...InputThe only line of the input is a string between 1 and 106 characters long.OutputOutput "Yes" or "No".ExamplesInputHHHHOutputYesInputHQHQHOutputNoInputHHQHHQHOutputNoInputHHQQHHQQHHOutputYesNoteThe rest of the problem statement was destroyed by a stray raccoon. We are terribly sorry for the inconvenience.
InputHHHH
OutputYes
2 seconds
256 megabytes
['*special problem', 'constructive algorithms', '*2500']
D. Orangetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output InputThe first line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be a letter of English alphabet, lowercase or uppercase.The second line of the input is an integer between 0 and 26, inclusive.OutputOutput the required string.ExamplesInputAprilFool14OutputAprILFooL
InputAprilFool14
OutputAprILFooL
2 seconds
256 megabytes
['*special problem', 'implementation', '*1400']
C. WTF?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHAII HAS A TUXGIMMEH TUXI HAS A FOO ITS 0I HAS A BAR ITS 0I HAS A BAZ ITS 0I HAS A QUZ ITS 1TUX IS NOW A NUMBRIM IN YR LOOP NERFIN YR TUX TIL BOTH SAEM TUX AN 0I HAS A PURGIMMEH PURPUR IS NOW A NUMBRFOO R SUM OF FOO AN PURBAR R SUM OF BAR AN 1BOTH SAEM BIGGR OF PRODUKT OF FOO AN QUZ AN PRODUKT OF BAR BAZ AN PRODUKT OF FOO AN QUZO RLY?YA RLYBAZ R FOOQUZ R BAROICIM OUTTA YR LOOPBAZ IS NOW A NUMBARVISIBLE SMOOSH QUOSHUNT OF BAZ QUZKTHXBYEInputThe input contains between 1 and 10 lines, i-th line contains an integer number xi (0 ≀ xi ≀ 9).OutputOutput a single real number. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 4.ExamplesInput3011Output0.666667
Input3011
Output0.666667
2 seconds
256 megabytes
['*special problem', 'graph matchings', 'implementation', 'trees', '*1700']
B. QR codetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output InputThe input contains two integers a1, a2 (0 ≀ ai ≀ 32), separated by a single space.OutputOutput a single integer.ExamplesInput1 1Output0Input3 7Output0Input13 10Output1
Input1 1
Output0
2 seconds
256 megabytes
['*special problem', 'implementation', '*1500']
A. Mysterious stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe input contains a single integer a (1 ≀ a ≀ 40).OutputOutput a single string.ExamplesInput2OutputAdamsInput8OutputVan BurenInput29OutputHarding
Input2
OutputAdams
2 seconds
256 megabytes
['*special problem', 'implementation', '*1400']
B. Polo the Penguin and Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.InputThe first line contains three integers n, m and d (1 ≀ n, m ≀ 100, 1 ≀ d ≀ 104) β€” the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 ≀ aij ≀ 104).OutputIn a single line print a single integer β€” the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).ExamplesInput2 2 22 46 8Output4Input1 2 76 7Output-1
Input2 2 22 46 8
Output4
2 seconds
256 megabytes
['brute force', 'dp', 'implementation', 'sortings', 'ternary search', '*1400']
A. Polo the Penguin and Segments time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle penguin Polo adores integer segments, that is, pairs of integers [l;Β r] (l ≀ r). He has a set that consists of n integer segments: [l1;Β r1], [l2;Β r2], ..., [ln;Β rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l;Β r] to either segment [l - 1;Β r], or to segment [l;Β r + 1].The value of a set of segments that consists of n segments [l1;Β r1], [l2;Β r2], ..., [ln;Β rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≀ x ≀ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.InputThe first line contains two integers n and k (1 ≀ n, k ≀ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≀ li ≀ ri ≀ 105), separated by a space.It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≀ i < j ≀ n) the following inequality holds, min(ri, rj) < max(li, lj).OutputIn a single line print a single integer β€” the answer to the problem.ExamplesInput2 31 23 4Output2Input3 71 23 34 7Output0
Input2 31 23 4
Output2
2 seconds
256 megabytes
['brute force', 'implementation', '*1100']
E. Polo the Penguin and Lucky Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Polo the Penguin have two positive integers l and r (l < r), both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other.Let's assume that n is the number of distinct lucky numbers, each of them cannot be greater than r or less than l, and ai is the i-th (in increasing order) number of them. Find a1Β·a2 + a2Β·a3 + ... + an - 1Β·an. As the answer can be rather large, print the remainder after dividing it by 1000000007 (109 + 7).InputThe first line contains a positive integer l, and the second line contains a positive integer r (1 ≀ l < r ≀ 10100000). The numbers are given without any leading zeroes.It is guaranteed that the lengths of the given numbers are equal to each other and that both of them are lucky numbers.OutputIn the single line print a single integer β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput47Output28Input474777Output2316330
Input47
Output28
2 seconds
256 megabytes
['dp', 'implementation', 'math', '*2800']
D. Polo the Penguin and Trees time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle penguin Polo has got a tree β€” a non-directed connected acyclic graph, containing n nodes and n - 1 edges. We will consider the tree nodes numbered by integers from 1 to n.Today Polo wonders, how to find the number of pairs of paths that don't have common nodes. More formally, he should find the number of groups of four integers a, b, c and d such that: 1 ≀ a < b ≀ n; 1 ≀ c < d ≀ n; there's no such node that lies on both the shortest path from node a to node b and from node c to node d. The shortest path betweem two nodes is the path that is shortest in the number of edges.Help Polo solve this problem.InputThe first line contains integer n (1 ≀ n ≀ 80000) β€” the number of tree nodes. Each of the following n - 1 lines contains a pair of integers ui and vi (1 ≀ ui, vi ≀ n;Β ui ≠ vi) β€” the i-th edge of the tree.It is guaranteed that the given graph is a tree.OutputIn a single line print a single integer β€” the answer to the problem.Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specificator.ExamplesInput41 22 33 4Output2
Input41 22 33 4
Output2
2 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'trees', '*2400']
C. Polo the Penguin and XOR operationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.For permutation p = p0, p1, ..., pn, Polo has defined its beauty β€” number .Expression means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal β€” as "xor".Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.InputThe single line contains a positive integer n (1 ≀ n ≀ 106).OutputIn the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m.If there are several suitable permutations, you are allowed to print any of them.ExamplesInput4Output200 2 1 4 3
Input4
Output200 2 1 4 3
2 seconds
256 megabytes
['implementation', 'math', '*1700']
B. Polo the Penguin and Houses time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≀ pi ≀ n).Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.We know that: When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house. You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).InputThe single line contains two space-separated integers n and k (1 ≀ n ≀ 1000, 1 ≀ k ≀ min(8, n)) β€” the number of the houses and the number k from the statement.OutputIn a single line print a single integer β€” the answer to the problem modulo 1000000007 (109 + 7).ExamplesInput5 2Output54Input7 4Output1728
Input5 2
Output54
2 seconds
256 megabytes
['combinatorics', '*1500']
A. Polo the Penguin and Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions: The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≀ i < n). Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.InputA single line contains two positive integers n and k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26) β€” the string's length and the number of distinct letters.OutputIn a single line print the required string. If there isn't such string, print "-1" (without the quotes).ExamplesInput7 4OutputababacdInput4 7Output-1
Input7 4
Outputababacd
2 seconds
256 megabytes
['greedy', '*1300']
B. Pipelinetime limit per test0.4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only one pipe with flowing water. Besides, Vova has several splitters.A splitter is a construction that consists of one input (it can be connected to a water pipe) and x output pipes. When a splitter is connected to a water pipe, water flows from each output pipe. You can assume that the output pipes are ordinary pipes. For example, you can connect water supply to such pipe if there's water flowing out from it. At most one splitter can be connected to any water pipe. The figure shows a 4-output splitter Vova has one splitter of each kind: with 2, 3, 4, ..., k outputs. Help Vova use the minimum number of splitters to build the required pipeline or otherwise state that it's impossible.Vova needs the pipeline to have exactly n pipes with flowing out water. Note that some of those pipes can be the output pipes of the splitters.InputThe first line contains two space-separated integers n and k (1 ≀ n ≀ 1018, 2 ≀ k ≀ 109).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 β€” the minimum number of splitters needed to build the pipeline. If it is impossible to build a pipeline with the given splitters, print -1.ExamplesInput4 3Output2Input5 5Output1Input8 4Output-1
Input4 3
Output2
0.4 seconds
256 megabytes
['binary search', 'math', '*1700']
A. IQ Testtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the city of Ultima Thule job applicants are often offered an IQ test. The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2 × 2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed. Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2 × 2 square, consisting of cells of the same color.InputFour lines contain four characters each: the j-th character of the i-th line equals "." if the cell in the i-th row and the j-th column of the square is painted white, and "#", if the cell is black.OutputPrint "YES" (without the quotes), if the test can be passed and "NO" (without the quotes) otherwise.ExamplesInput####.#..####....OutputYESInput####....####....OutputNONoteIn the first test sample it is enough to repaint the first cell in the second row. After such repainting the required 2 × 2 square is on the intersection of the 1-st and 2-nd row with the 1-st and 2-nd column.
Input####.#..####....
OutputYES
2 seconds
256 megabytes
['brute force', 'implementation', '*1100']
E. Ladies' Shoptime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA ladies' shop has recently opened in the city of Ultima Thule. To get ready for the opening, the shop bought n bags. Each bag is characterised by the total weight ai of the items you can put there. The weird thing is, you cannot use these bags to put a set of items with the total weight strictly less than ai. However the weights of the items that will be sold in the shop haven't yet been defined. That's what you should determine right now.Your task is to find the set of the items' weights p1, p2, ..., pk (1 ≀ p1 < p2 < ... < pk), such that: Any bag will be used. That is, for any i (1 ≀ i ≀ n) there will be such set of items that their total weight will equal ai. We assume that there is the infinite number of items of any weight. You can put multiple items of the same weight in one bag. For any set of items that have total weight less than or equal to m, there is a bag into which you can put this set. Similarly, a set of items can contain multiple items of the same weight. Of all sets of the items' weights that satisfy points 1 and 2, find the set with the minimum number of weights. In other words, value k should be as small as possible. Find and print the required set.InputThe first line contains space-separated integers n and m (1 ≀ n, m ≀ 106). The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ a1 < a2 < ... < an ≀ m) β€” the bags' weight limits.OutputIn the first line print "NO" (without the quotes) if there isn't set pi, that would meet the conditions.Otherwise, in the first line print "YES" (without the quotes), in the second line print an integer k (showing how many numbers are in the suitable set with the minimum number of weights), in the third line print k space-separated integers p1, p2, ..., pk (1 ≀ p1 < p2 < ... < pk). If there are multiple solutions, print any of them.ExamplesInput6 105 6 7 8 9 10OutputYES55 6 7 8 9 Input1 101OutputNOInput1 106OutputYES16
Input6 105 6 7 8 9 10
OutputYES55 6 7 8 9
8 seconds
256 megabytes
['constructive algorithms', 'fft', 'math', '*2800']
D. Touriststime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA double tourist path, located at a park in Ultima Thule, is working by the following principle: We introduce the Cartesian coordinate system. At some points of time there are two tourists going (for a walk) from points ( - 1, 0) and (1, 0) simultaneously. The first one is walking from ( - 1, 0), the second one is walking from (1, 0). Both tourists in a pair move at the same speed 1 (distance unit per second), the first one moves along line x =  - 1, the second one moves along line x = 1, both of them are moving in the positive direction of the Oy axis. At some points of time walls appear. Wall (li, ri) is a segment between points (0, li) and (0, ri). Each wall appears immediately. The Ultima Thule government wants to learn this for each pair of tourists that walk simultaneously: for how long (in seconds) will they not see each other? Two tourists don't see each other if the segment that connects their positions on the plane intersects at least one wall. Two segments intersect if they share at least one point. We assume that the segments' ends belong to the segments.Help the government count the required time. Note that the walls can intersect (in any way) or coincide.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of pairs of tourists and the number of built walls. The next m lines contain three space-separated integers li, ri and ti each (0 ≀ li < ri ≀ 109, 0 ≀ ti ≀ 109) β€” the wall ends and the time it appeared. The last line contains n distinct space-separated strictly increasing integers q1, q2, ..., qn (0 ≀ qi ≀ 109) β€” the points of time when pairs of tourists walk.All points of time are given in seconds.OutputFor each pair of tourists print on a single line a single integer β€” the time in seconds when the two tourists from the corresponding pair won't see each other. Print the numbers in the order in which the they go in the input.ExamplesInput2 21 4 33 6 50 1Output24Input3 30 3 40 1 22 4 01 3 4Output244
Input2 21 4 33 6 50 1
Output24
1 second
256 megabytes
['data structures', 'sortings', '*2600']
C. Main Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you know, Vova has recently become a new shaman in the city of Ultima Thule. So, he has received the shaman knowledge about the correct bracket sequences. The shamans of Ultima Thule have been using lots of different types of brackets since prehistoric times. A bracket type is a positive integer. The shamans define a correct bracket sequence as follows: An empty sequence is a correct bracket sequence. If {a1, a2, ..., al} and {b1, b2, ..., bk} are correct bracket sequences, then sequence {a1, a2, ..., al, b1, b2, ..., bk} (their concatenation) also is a correct bracket sequence. If {a1, a2, ..., al} β€” is a correct bracket sequence, then sequence also is a correct bracket sequence, where v (v > 0) is an integer. For example, sequences {1, 1,  - 1, 2,  - 2,  - 1} and {3,  - 3} are correct bracket sequences, and {2,  - 3} is not.Moreover, after Vova became a shaman, he learned the most important correct bracket sequence {x1, x2, ..., xn}, consisting of n integers. As sequence x is the most important, Vova decided to encrypt it just in case.Encrypting consists of two sequences. The first sequence {p1, p2, ..., pn} contains types of brackets, that is, pi = |xi| (1 ≀ i ≀ n). The second sequence {q1, q2, ..., qt} contains t integers β€” some positions (possibly, not all of them), which had negative numbers in sequence {x1, x2, ..., xn}.Unfortunately, Vova forgot the main sequence. But he was lucky enough to keep the encryption: sequences {p1, p2, ..., pn} and {q1, q2, ..., qt}. Help Vova restore sequence x by the encryption. If there are multiple sequences that correspond to the encryption, restore any of them. If there are no such sequences, you should tell so.InputThe first line of the input contains integer n (1 ≀ n ≀ 106). The second line contains n integers: p1, p2, ..., pn (1 ≀ pi ≀ 109).The third line contains integer t (0 ≀ t ≀ n), followed by t distinct integers q1, q2, ..., qt (1 ≀ qi ≀ n).The numbers in each line are separated by spaces.OutputPrint a single string "NO" (without the quotes) if Vova is mistaken and a suitable sequence {x1, x2, ..., xn} doesn't exist.Otherwise, in the first line print "YES" (without the quotes) and in the second line print n integers x1, x2, ..., xn (|xi| = pi;Β xqj < 0). If there are multiple sequences that correspond to the encrypting, you are allowed to print any of them.ExamplesInput21 10OutputYES1 -1Input41 1 1 11 3OutputYES1 1 -1 -1Input31 1 10OutputNOInput41 2 2 12 3 4OutputYES1 2 -2 -1
Input21 10
OutputYES1 -1
2 seconds
256 megabytes
['greedy', 'implementation', '*2100']
B. Shiftingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Doe has found the beautiful permutation formula.Let's take permutation p = p1, p2, ..., pn. Let's define transformation f of this permutation: where k (k > 1) is an integer, the transformation parameter, r is such maximum integer that rk ≀ n. If rk = n, then elements prk + 1, prk + 2 and so on are omitted. In other words, the described transformation of permutation p cyclically shifts to the left each consecutive block of length k and the last block with the length equal to the remainder after dividing n by k. John Doe thinks that permutation f(f(Β ...Β f(p = [1, 2, ..., n], 2)Β ...Β , n - 1), n) is beautiful. Unfortunately, he cannot quickly find the beautiful permutation he's interested in. That's why he asked you to help him.Your task is to find a beautiful permutation for the given n. For clarifications, see the notes to the third sample.InputA single line contains integer n (2 ≀ n ≀ 106).OutputPrint n distinct space-separated integers from 1 to n β€” a beautiful permutation of size n.ExamplesInput2Output2 1 Input3Output1 3 2 Input4Output4 2 3 1 NoteA note to the third test sample: f([1, 2, 3, 4], 2) = [2, 1, 4, 3] f([2, 1, 4, 3], 3) = [1, 4, 2, 3] f([1, 4, 2, 3], 4) = [4, 2, 3, 1]
Input2
Output2 1
2 seconds
256 megabytes
['implementation', '*2200']
A. Lucky Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≀ pi ≀ n).A lucky permutation is such permutation p, that any integer i (1 ≀ i ≀ n) meets this condition ppi = n - i + 1.You have integer n. Find some lucky permutation p of size n.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the required permutation size.OutputPrint "-1" (without the quotes) if the lucky permutation p of size n doesn't exist.Otherwise, print n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) after a space β€” the required permutation.If there are multiple answers, you can print any of them.ExamplesInput1Output1 Input2Output-1Input4Output2 4 1 3 Input5Output2 5 3 1 4
Input1
Output1
2 seconds
256 megabytes
['constructive algorithms', 'math', '*1400']
E. Positions in Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPermutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.We'll call position i (1 ≀ i ≀ n) in permutation p1, p2, ..., pn good, if |p[i] - i| = 1. Count the number of permutations of size n with exactly k good positions. Print the answer modulo 1000000007 (109 + 7).InputThe single line contains two space-separated integers n and k (1 ≀ n ≀ 1000, 0 ≀ k ≀ n).OutputPrint the number of permutations of length n with exactly k good positions modulo 1000000007 (109 + 7).ExamplesInput1 0Output1Input2 1Output0Input3 2Output4Input4 1Output6Input7 4Output328NoteThe only permutation of size 1 has 0 good positions.Permutation (1, 2) has 0 good positions, and permutation (2, 1) has 2 positions.Permutations of size 3: (1, 2, 3) β€” 0 positions β€” 2 positions β€” 2 positions β€” 2 positions β€” 2 positions (3, 2, 1) β€” 0 positions
Input1 0
Output1
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*2600']
D. Permutation Sumtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPermutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.Petya decided to introduce the sum operation on the set of permutations of length n. Let's assume that we are given two permutations of length n: a1, a2, ..., an and b1, b2, ..., bn. Petya calls the sum of permutations a and b such permutation c of length n, where ci = ((ai - 1 + bi - 1) mod n) + 1 (1 ≀ i ≀ n).Operation means taking the remainder after dividing number x by number y.Obviously, not for all permutations a and b exists permutation c that is sum of a and b. That's why Petya got sad and asked you to do the following: given n, count the number of such pairs of permutations a and b of length n, that exists permutation c that is sum of a and b. The pair of permutations x, y (x ≠ y) and the pair of permutations y, x are considered distinct pairs.As the answer can be rather large, print the remainder after dividing it by 1000000007 (109 + 7).InputThe single line contains integer n (1 ≀ n ≀ 16).OutputIn the single line print a single non-negative integer β€” the number of such pairs of permutations a and b, that exists permutation c that is sum of a and b, modulo 1000000007 (109 + 7).ExamplesInput3Output18Input5Output1800
Input3
Output18
3 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'implementation', 'meet-in-the-middle', '*1900']
C. Building Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPermutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.InputThe first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).OutputPrint a single number β€” the minimum number of moves.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.ExamplesInput23 0Output2Input3-1 -1 2Output6NoteIn the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1).In the second sample you need 6 moves to build permutation (1, 3, 2).
Input23 0
Output2
1 second
256 megabytes
['greedy', 'implementation', 'sortings', '*1200']
B. Find Marbletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not.First Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position p1, the glass from the second position to position p2 and so on. That is, a glass goes from position i to position pi. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.After all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.InputThe first line contains three integers: n, s, t (1 ≀ n ≀ 105;Β 1 ≀ s, t ≀ n) β€” the number of glasses, the ball's initial and final position. The second line contains n space-separated integers: p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the shuffling operation parameters. It is guaranteed that all pi's are distinct.Note that s can equal t.OutputIf the marble can move from position s to position t, then print on a single line a non-negative integer β€” the minimum number of shuffling operations, needed to get the marble to position t. If it is impossible, print number -1.ExamplesInput4 2 12 3 4 1Output3Input4 3 34 1 3 2Output0Input4 3 41 2 3 4Output-1Input3 1 32 1 3Output-1
Input4 2 12 3 4 1
Output3
2 seconds
256 megabytes
['implementation', '*1200']
A. Slightly Decreasing Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPermutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.The decreasing coefficient of permutation p1, p2, ..., pn is the number of such i (1 ≀ i < n), that pi > pi + 1.You have numbers n and k. Your task is to print the permutation of length n with decreasing coefficient k.InputThe single line contains two space-separated integers: n, k (1 ≀ n ≀ 105, 0 ≀ k < n) β€” the permutation length and the decreasing coefficient.OutputIn a single line print n space-separated integers: p1, p2, ..., pn β€” the permutation of length n with decreasing coefficient k. If there are several permutations that meet this condition, print any of them. It is guaranteed that the permutation with the sought parameters exists.ExamplesInput5 2Output1 5 2 4 3Input3 0Output1 2 3Input3 2Output3 2 1
Input5 2
Output1 5 2 4 3
2 seconds
256 megabytes
['greedy', 'implementation', '*1100']
B. Cows and Poker Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN".Find the number of cows that can currently show their hands without affecting any betting decisions.InputThe first line contains a single integer, n (2 ≀ n ≀ 2Β·105). The second line contains n characters, each either "A", "I", or "F". The i-th character is "A" if the i-th player's status is "ALLIN", "I" if the i-th player's status is "IN", or "F" if the i-th player's status is "FOLDED".OutputThe first line should contain a single integer denoting the number of players that can currently show their hands.ExamplesInput6AFFAAAOutput4Input3AFIOutput1NoteIn the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand.
Input6AFFAAA
Output4
2 seconds
256 megabytes
['brute force', 'implementation', '*1000']
A. Cows and Primitive Rootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe cows have just learned what a primitive root is! Given a prime p, a primitive root is an integer x (1 ≀ x < p) such that none of integers x - 1, x2 - 1, ..., xp - 2 - 1 are divisible by p, but xp - 1 - 1 is. Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime p, help the cows find the number of primitive roots .InputThe input contains a single line containing an integer p (2 ≀ p < 2000). It is guaranteed that p is a prime.OutputOutput on a single line the number of primitive roots .ExamplesInput3Output1Input5Output2NoteThe only primitive root is 2.The primitive roots are 2 and 3.
Input3
Output1
2 seconds
256 megabytes
['implementation', 'math', 'number theory', '*1400']
E. Cow Tennis Tournamenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John is hosting a tennis tournament with his n cows. Each cow has a skill level si, and no two cows having the same skill level. Every cow plays every other cow exactly once in the tournament, and each cow beats every cow with skill level lower than its own.However, Farmer John thinks the tournament will be demoralizing for the weakest cows who lose most or all of their matches, so he wants to flip some of the results. In particular, at k different instances, he will take two integers ai, bi (ai < bi) and flip all the results between cows with skill level between ai and bi inclusive. That is, for any pair x, y he will change the result of the match on the final scoreboard (so if x won the match, the scoreboard will now display that y won the match, and vice versa). It is possible that Farmer John will change the result of a match multiple times. It is not guaranteed that ai and bi are equal to some cow's skill level.Farmer John wants to determine how balanced he made the tournament results look. In particular, he wants to count the number of triples of cows (p, q, r) for which the final leaderboard shows that cow p beats cow q, cow q beats cow r, and cow r beats cow p. Help him determine this number.Note that two triples are considered different if they do not contain the same set of cows (i.e. if there is a cow in one triple that is not in the other).InputOn the first line are two space-separated integers, n and k (3 ≀ n ≀ 105;Β 0 ≀ k ≀ 105). On the next line are n space-separated distinct integers, s1, s2, ..., sn (1 ≀ si ≀ 109), denoting the skill levels of the cows. On the next k lines are two space separated integers, ai and bi (1 ≀ ai < bi ≀ 109) representing the changes Farmer John made to the scoreboard in the order he makes it.OutputA single integer, containing the number of triples of cows (p, q, r) for which the final leaderboard shows that cow p beats cow q, cow q beats cow r, and cow r beats cow p.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 21 2 31 22 3Output1Input5 35 9 4 1 71 72 83 9Output3NoteIn the first sample, cow 3 > cow 1, cow 3 > cow 2, and cow 2 > cow 1. However, the results between cows 1 and 2 and cows 2 and 3 are flipped, so now FJ's results show that cow 1 > cow 2, cow 2 > cow 3, and cow 3 > cow 1, so cows 1, 2, and 3 form a balanced triple.
Input3 21 2 31 22 3
Output1
2 seconds
256 megabytes
['combinatorics', 'data structures', 'math', '*2800']
D. Cows and Cool Sequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie and the cows have recently been playing with "cool" sequences and are trying to construct some. Unfortunately they are bad at arithmetic, so they need your help!A pair (x, y) of positive integers is "cool" if x can be expressed as the sum of y consecutive integers (not necessarily positive). A sequence (a1, a2, ..., an) is "cool" if the pairs (a1, a2), (a2, a3), ..., (an - 1, an) are all cool. The cows have a sequence of n positive integers, a1, a2, ..., an. In one move, they may replace some ai with any other positive integer (there are no other limits on the new value of ai). Determine the smallest number of moves needed to make the resulting sequence cool.InputThe first line contains a single integer, n (2 ≀ n ≀ 5000). The next line contains n space-separated integers, a1, a2, ..., an (1 ≀ ai ≀ 1015).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.OutputA single integer, the minimum number of ai that must be changed to make the sequence cool.ExamplesInput36 4 1Output0Input420 6 3 4Output2NoteIn the first sample, the sequence is already cool, so we don't need to change any elements. In the second sample, we can change a2 to 5 and a3 to 10 to make (20, 5, 10, 4) which is cool. This changes 2 elements.
Input36 4 1
Output0
2 seconds
256 megabytes
['dp', 'math', 'number theory', '*2400']
C. Coin Troublestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the Isle of Guernsey there are n different types of coins. For each i (1 ≀ i ≀ n), coin of type i is worth ai cents. It is possible that ai = aj for some i and j (i ≠ j). Bessie has some set of these coins totaling t cents. She tells Jessie q pairs of integers. For each i (1 ≀ i ≀ q), the pair bi, ci tells Jessie that Bessie has a strictly greater number of coins of type bi than coins of type ci. It is known that all bi are distinct and all ci are distinct. Help Jessie find the number of possible combinations of coins Bessie could have. Two combinations are considered different if there is some i (1 ≀ i ≀ n), such that the number of coins Bessie has of type i is different in the two combinations. Since the answer can be very large, output it modulo 1000000007 (109 + 7). If there are no possible combinations of coins totaling t cents that satisfy Bessie's conditions, output 0.InputThe first line contains three space-separated integers, n, q and t (1 ≀ n ≀ 300;Β 0 ≀ q ≀ n;Β 1 ≀ t ≀ 105). The second line contains n space separated integers, a1, a2, ..., an (1 ≀ ai ≀ 105). The next q lines each contain two distinct space-separated integers, bi and ci (1 ≀ bi, ci ≀ n;Β bi ≠ ci).It's guaranteed that all bi are distinct and all ci are distinct.OutputA single integer, the number of valid coin combinations that Bessie could have, modulo 1000000007 (109 + 7).ExamplesInput4 2 173 1 2 54 23 4Output3Input3 2 63 1 11 22 3Output0Input3 2 101 2 31 22 1Output0NoteFor the first sample, the following 3 combinations give a total of 17 cents and satisfy the given conditions: {0Β ofΒ typeΒ 1, 1Β ofΒ typeΒ 2, 3Β ofΒ typeΒ 3, 2Β ofΒ typeΒ 4}, {0, 0, 6, 1}, {2, 0, 3, 1}.No other combinations exist. Note that even though 4 occurs in both bi and ci,  the problem conditions are still satisfied because all bi are distinct and all ci are distinct.
Input4 2 173 1 2 54 23 4
Output3
2 seconds
256 megabytes
['dp', '*2100']
B. Cow Programtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFarmer John has just given the cows a program to play with! The program contains two integer variables, x and y, and performs the following operations on a sequence a1, a2, ..., an of positive integers: Initially, x = 1 and y = 0. If, after any step, x ≀ 0 or x > n, the program immediately terminates. The program increases both x and y by a value equal to ax simultaneously. The program now increases y by ax while decreasing x by ax. The program executes steps 2 and 3 (first step 2, then step 3) repeatedly until it terminates (it may never terminate). So, the sequence of executed steps may start with: step 2, step 3, step 2, step 3, step 2 and so on. The cows are not very good at arithmetic though, and they want to see how the program works. Please help them!You are given the sequence a2, a3, ..., an. Suppose for each i (1 ≀ i ≀ n - 1) we run the program on the sequence i, a2, a3, ..., an. For each such run output the final value of y if the program terminates or -1 if it does not terminate.InputThe first line contains a single integer, n (2 ≀ n ≀ 2Β·105). The next line contains n - 1 space separated integers, a2, a3, ..., an (1 ≀ ai ≀ 109).OutputOutput n - 1 lines. On the i-th line, print the requested value when the program is run on the sequence i, a2, a3, ...an.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.ExamplesInput42 4 1Output368Input31 2Output-1-1NoteIn the first sample For i = 1,  x becomes and y becomes 1 + 2 = 3. For i = 2,  x becomes and y becomes 2 + 4 = 6. For i = 3,  x becomes and y becomes 3 + 1 + 4 = 8.
Input42 4 1
Output368
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', '*1700']
A. Cows and Sequencetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following: Add the integer xi to the first ai elements of the sequence. Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1) Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!InputThe first line contains a single integer nΒ (1 ≀ n ≀ 2Β·105) β€” the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1 ≀ ti ≀ 3), denoting the type of the operation (see above). If ti = 1, it will be followed by two integers ai, xi (|xi| ≀ 103;Β 1 ≀ ai). If ti = 2, it will be followed by a single integer ki (|ki| ≀ 103). If ti = 3, it will not be followed by anything.It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence.OutputOutput n lines each containing the average of the numbers in the sequence after the corresponding operation.The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.ExamplesInput52 132 32 13Output0.5000000.0000001.5000001.3333331.500000Input62 11 2 202 21 2 -333Output0.50000020.50000014.33333312.33333317.50000017.000000NoteIn the second sample, the sequence becomes
Input52 132 32 13
Output0.5000000.0000001.5000001.3333331.500000
1.5 seconds
256 megabytes
['constructive algorithms', 'data structures', 'implementation', '*1600']
E. Sausage Maximizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.InputThe first line contains an integer n (1 ≀ n ≀ 105).The next line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 1012) β€” Mr. Bitkoch's sausage.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 β€” the maximum pleasure BitHaval and BitAryo can get from the dinner.ExamplesInput21 2Output3Input31 2 3Output3Input21000 1000Output1000
Input21 2
Output3
2 seconds
256 megabytes
['bitmasks', 'data structures', 'trees', '*2200']
D. Yet Another Number Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSince most contestants do not read this part, I have to repeat that Bitlandians are quite weird. They have their own jobs, their own working method, their own lives, their own sausages and their own games!Since you are so curious about Bitland, I'll give you the chance of peeking at one of these games.BitLGM and BitAryo are playing yet another of their crazy-looking genius-needed Bitlandish games. They've got a sequence of n non-negative integers a1, a2, ..., an. The players make moves in turns. BitLGM moves first. Each player can and must do one of the two following actions in his turn: Take one of the integers (we'll denote it as ai). Choose integer x (1 ≀ x ≀ ai). And then decrease ai by x, that is, apply assignment: ai = ai - x. Choose integer x . And then decrease all ai by x, that is, apply assignment: ai = ai - x, for all i. The player who cannot make a move loses.You're given the initial sequence a1, a2, ..., an. Determine who wins, if both players plays optimally well and if BitLGM and BitAryo start playing the described game in this sequence.InputThe first line contains an integer n (1 ≀ n ≀ 3).The next line contains n integers a1, a2, ..., an (0 ≀ ai < 300).OutputWrite the name of the winner (provided that both players play optimally well). Either "BitLGM" or "BitAryo" (without the quotes).ExamplesInput21 1OutputBitLGMInput21 2OutputBitAryoInput31 2 1OutputBitLGM
Input21 1
OutputBitLGM
2 seconds
256 megabytes
['dp', 'games', '*2100']
C. XOR and ORtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.A Bitlandish string is a string made only of characters "0" and "1".BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = xΒ xorΒ y, q = xΒ orΒ y. Then he replaces one of the two taken characters by p and the other one by q.The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.InputThe first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths.It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106.OutputPrint "YES" if a can be transformed into b, otherwise print "NO". Please do not print the quotes.ExamplesInput1110OutputYESInput101OutputNOInput000101OutputNO
Input1110
OutputYES
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'math', '*1500']
B. Painting Eggstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Bitlandians are quite weird people. They have very peculiar customs.As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work.The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. has got n eggs. G. named his price for painting each egg. Similarly, A. named his price for painting each egg. It turns out that for each egg the sum of the money both A. and G. want for the painting equals 1000.Uncle J. wants to distribute the eggs between the children so as to give each egg to exactly one child. Also, Uncle J. wants the total money paid to A. to be different from the total money paid to G. by no more than 500.Help Uncle J. Find the required distribution of eggs or otherwise say that distributing the eggs in the required manner is impossible.InputThe first line contains integer n (1 ≀ n ≀ 106) β€” the number of eggs.Next n lines contain two integers ai and gi each (0 ≀ ai, gi ≀ 1000;Β ai + gi = 1000): ai is the price said by A. for the i-th egg and gi is the price said by G. for the i-th egg.OutputIf it is impossible to assign the painting, print "-1" (without quotes).Otherwise print a string, consisting of n letters "G" and "A". The i-th letter of this string should represent the child who will get the i-th egg in the required distribution. Letter "A" represents A. and letter "G" represents G. If we denote the money Uncle J. must pay A. for the painting as Sa, and the money Uncle J. must pay G. for the painting as Sg, then this inequality must hold: |Sa  -  Sg|  ≀  500. If there are several solutions, you are allowed to print any of them.ExamplesInput21 999999 1OutputAGInput3400 600400 600400 600OutputAGA
Input21 999999 1
OutputAG
5 seconds
256 megabytes
['greedy', 'math', '*1500']
A. Bit++time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe classic programming language of Bitland is Bit++. This language is so peculiar and complicated.The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: Operation ++ increases the value of variable x by 1. Operation -- decreases the value of variable x by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).InputThe first line contains a single integer n (1 ≀ n ≀ 150) β€” the number of statements in the programme.Next n lines contain a statement each. Each statement contains exactly one operation (++ or --) and exactly one variable x (denoted as letter Β«XΒ»). Thus, there are no empty statements. The operation and the variable can be written in any order.OutputPrint a single integer β€” the final value of x.ExamplesInput1++XOutput1Input2X++--XOutput0
Input1++X
Output1
1 second
256 megabytes
['implementation', '*800']
B. Nearest Fractiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction whose denominator is no more than n. Formally, you should find such pair of integers a, b (1 ≀ b ≀ n;Β 0 ≀ a) that the value is as minimal as possible.If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator.InputA single line contains three integers x, y, n (1 ≀ x, y, n ≀ 105).OutputPrint the required fraction in the format "a/b" (without quotes).ExamplesInput3 7 6Output2/5Input7 2 4Output7/2
Input3 7 6
Output2/5
2 seconds
256 megabytes
['brute force', 'implementation', 'two pointers', '*1700']
A. Word Capitalizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCapitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.Note, that during capitalization all the letters except the first one remains unchanged.InputA single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 103.OutputOutput the given word after capitalization.ExamplesInputApPLeOutputApPLeInputkonjacOutputKonjac
InputApPLe
OutputApPLe
2 seconds
256 megabytes
['implementation', 'strings', '*800']
E. Sequence Transformationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a non-decreasing sequence x1, x2, ..., xn (1 ≀ x1 ≀ x2 ≀ ... ≀ xn ≀ q). You've also got two integers a and b (a ≀ b;Β aΒ·(n - 1) < q).Your task is to transform sequence x1, x2, ..., xn into some sequence y1, y2, ..., yn (1 ≀ yi ≀ q;Β a ≀ yi + 1 - yi ≀ b). The transformation price is the following sum: . Your task is to choose such sequence y that minimizes the described transformation price.InputThe first line contains four integers n, q, a, b (2 ≀ n ≀ 6000;Β 1 ≀ q, a, b ≀ 109;Β aΒ·(n - 1) < q;Β a ≀ b).The second line contains a non-decreasing integer sequence x1, x2, ..., xn (1 ≀ x1 ≀ x2 ≀ ... ≀ xn ≀ q).OutputIn the first line print n real numbers β€” the sought sequence y1, y2, ..., yn (1 ≀ yi ≀ q;Β a ≀ yi + 1 - yi ≀ b). In the second line print the minimum transformation price, that is, .If there are multiple optimal answers you can print any of them.The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.ExamplesInput3 6 2 21 4 6Output1.666667 3.666667 5.666667 0.666667Input10 100000 8714 93443378 14705 17588 22672 32405 34309 37446 51327 81228 94982Output1.000000 8715.000000 17429.000000 26143.000000 34857.000000 43571.000000 52285.000000 61629.000000 70973.000000 80317.000000 797708674.000000
Input3 6 2 21 4 6
Output1.666667 3.666667 5.666667 0.666667
3 seconds
256 megabytes
['brute force', 'data structures', 'dp', 'implementation', 'math', '*3000']
D. k-Maximum Subsequence Sumtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider integer sequence a1, a2, ..., an. You should run queries of two types: The query format is "0 i val". In reply to this query you should make the following assignment: ai = val. The query format is "1 l r k". In reply to this query you should print the maximum sum of at most k non-intersecting subsegments of sequence al, al + 1, ..., ar. Formally, you should choose at most k pairs of integers (x1, y1), (x2, y2), ..., (xt, yt) (l ≀ x1 ≀ y1 < x2 ≀ y2 < ... < xt ≀ yt ≀ r;Β t ≀ k) such that the sum ax1 + ax1 + 1 + ... + ay1 + ax2 + ax2 + 1 + ... + ay2 + ... + axt + axt + 1 + ... + ayt is as large as possible. Note that you should choose at most k subsegments. Particularly, you can choose 0 subsegments. In this case the described sum considered equal to zero. InputThe first line contains integer n (1 ≀ n ≀ 105), showing how many numbers the sequence has. The next line contains n integers a1, a2, ..., an (|ai| ≀ 500). The third line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. The next m lines contain the queries in the format, given in the statement.All changing queries fit into limits: 1 ≀ i ≀ n, |val| ≀ 500.All queries to count the maximum sum of at most k non-intersecting subsegments fit into limits: 1 ≀ l ≀ r ≀ n, 1 ≀ k ≀ 20. It is guaranteed that the number of the queries to count the maximum sum of at most k non-intersecting subsegments doesn't exceed 10000.OutputFor each query to count the maximum sum of at most k non-intersecting subsegments print the reply β€” the maximum sum. Print the answers to the queries in the order, in which the queries follow in the input.ExamplesInput99 -8 9 -1 -1 -1 9 -8 931 1 9 11 1 9 21 4 6 3Output17250Input15-4 8 -3 -10 10 4 -7 -7 0 -6 3 8 -10 7 2151 3 9 21 6 12 10 6 50 10 -71 4 9 11 7 9 10 10 -31 4 10 21 3 13 21 4 11 20 15 -90 13 -90 11 -101 5 14 21 6 12 1Output1411150152618238NoteIn the first query of the first example you can select a single pair (1, 9). So the described sum will be 17.Look at the second query of the first example. How to choose two subsegments? (1, 3) and (7, 9)? Definitely not, the sum we could get from (1, 3) and (7, 9) is 20, against the optimal configuration (1, 7) and (9, 9) with 25.The answer to the third query is 0, we prefer select nothing if all of the numbers in the given interval are negative.
Input99 -8 9 -1 -1 -1 9 -8 931 1 9 11 1 9 21 4 6 3
Output17250
4 seconds
256 megabytes
['data structures', 'flows', 'graphs', 'implementation', '*2800']
C. Game on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMomiji has got a rooted tree, consisting of n nodes. The tree nodes are numbered by integers from 1 to n. The root has number 1. Momiji decided to play a game on this tree.The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let's denote it by v) and removes all the subtree nodes with the root in node v from the tree. Node v gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number 1.Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of nodes in the tree. The next n - 1 lines contain the tree edges. The i-th line contains integers ai, bi (1 ≀ ai, bi ≀ n;Β ai ≠ bi) β€” the numbers of the nodes that are connected by the i-th edge.It is guaranteed that the given graph is a tree.OutputPrint a single real number β€” the expectation of the number of steps in the described game.The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.ExamplesInput21 2Output1.50000000000000000000Input31 21 3Output2.00000000000000000000NoteIn the first sample, there are two cases. One is directly remove the root and another is remove the root after one step. Thus the expected steps are: 1 × (1 / 2) + 2 × (1 / 2) = 1.5In the second sample, things get more complex. There are two cases that reduce to the first sample, and one case cleaned at once. Thus the expected steps are: 1 × (1 / 3) + (1 + 1.5) × (2 / 3) = (1 / 3) + (5 / 3) = 2
Input21 2
Output1.50000000000000000000
1 second
256 megabytes
['implementation', 'math', 'probabilities', 'trees', '*2200']
B. Maximum Xor Secondarytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≀ l < r ≀ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence.InputThe first line contains integer n (1 < n ≀ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≀ si ≀ 109).OutputPrint a single integer β€” the maximum lucky number among all lucky numbers of sequences s[l..r].ExamplesInput55 2 1 4 3Output7Input59 8 3 5 7Output15NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4Β xorΒ 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}.
Input55 2 1 4 3
Output7
1 second
256 megabytes
['data structures', 'implementation', 'two pointers', '*1800']
A. Rectangle Puzzletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle Ξ±. Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.InputThe first line contains three integers w, h, α (1 ≀ w, h ≀ 106;Β 0 ≀ α ≀ 180). Angle Ξ± is given in degrees.OutputIn a single line print a real number β€” the area of the region which belongs to both given rectangles.The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.ExamplesInput1 1 45Output0.828427125Input6 4 30Output19.668384925NoteThe second sample has been drawn on the picture above.
Input1 1 45
Output0.828427125
2 seconds
256 megabytes
['geometry', '*2000']
E. Beautiful Decompositiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera considers a number beautiful, if it equals 2k or -2k for some integer k (k β‰₯ 0). Recently, the math teacher asked Valera to represent number n as the sum of beautiful numbers. As Valera is really greedy, he wants to complete the task using as few beautiful numbers as possible. Help Valera and find, how many numbers he is going to need. In other words, if you look at all decompositions of the number n into beautiful summands, you need to find the size of the decomposition which has the fewest summands.InputThe first line contains string s (1 ≀ |s| ≀ 106), that is the binary representation of number n without leading zeroes (n > 0).OutputPrint a single integer β€” the minimum amount of beautiful numbers that give a total of n.ExamplesInput10Output1Input111Output2Input1101101Output4NoteIn the first sample n = 2 is a beautiful number.In the second sample n = 7 and Valera can decompose it into sum 23 + ( - 20).In the third sample n = 109 can be decomposed into the sum of four summands as follows: 27 + ( - 24) + ( - 22) + 20.
Input10
Output1
2 seconds
256 megabytes
['dp', 'games', 'greedy', 'number theory', '*1900']
D. The Minimum Number of Variablestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a positive integer sequence a1, a2, ..., an. All numbers in the sequence are distinct. Let's fix the set of variables b1, b2, ..., bm. Initially each variable bi (1 ≀ i ≀ m) contains the value of zero. Consider the following sequence, consisting of n operations.The first operation is assigning the value of a1 to some variable bx (1 ≀ x ≀ m). Each of the following n - 1 operations is assigning to some variable by the value that is equal to the sum of values that are stored in the variables bi and bj (1 ≀ i, j, y ≀ m). At that, the value that is assigned on the t-th operation, must equal at. For each operation numbers y, i, j are chosen anew.Your task is to find the minimum number of variables m, such that those variables can help you perform the described sequence of operations.InputThe first line contains integer n (1 ≀ n ≀ 23). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ak ≀ 109).It is guaranteed that all numbers in the sequence are distinct.OutputIn a single line print a single number β€” the minimum number of variables m, such that those variables can help you perform the described sequence of operations.If you cannot perform the sequence of operations at any m, print -1.ExamplesInput51 2 3 6 8Output2Input33 6 5Output-1Input62 4 8 6 10 18Output3NoteIn the first sample, you can use two variables b1 and b2 to perform the following sequence of operations. b1 := 1; b2 := b1 + b1; b1 := b1 + b2; b1 := b1 + b1; b1 := b1 + b2.
Input51 2 3 6 8
Output2
1 second
256 megabytes
['bitmasks', 'dp', '*2200']
C. Laddertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got an array, consisting of n integers a1, a2, ..., an. Also, you've got m queries, the i-th query is described by two integers li, ri. Numbers li, ri define a subsegment of the original array, that is, the sequence of numbers ali, ali + 1, ali + 2, ..., ari. For each query you should check whether the corresponding segment is a ladder. A ladder is a sequence of integers b1, b2, ..., bk, such that it first doesn't decrease, then doesn't increase. In other words, there is such integer x (1 ≀ x ≀ k), that the following inequation fulfills: b1 ≀ b2 ≀ ... ≀ bx β‰₯ bx + 1 β‰₯ bx + 2... β‰₯ bk. Note that the non-decreasing and the non-increasing sequences are also considered ladders.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 105) β€” the number of array elements and the number of queries. The second line contains the sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 109), where number ai stands for the i-th array element.The following m lines contain the description of the queries. The i-th line contains the description of the i-th query, consisting of two integers li, ri (1 ≀ li ≀ ri ≀ n) β€” the boundaries of the subsegment of the initial array.The numbers in the lines are separated by single spaces.OutputPrint m lines, in the i-th line print word "Yes" (without the quotes), if the subsegment that corresponds to the i-th query is the ladder, or word "No" (without the quotes) otherwise. ExamplesInput8 61 2 1 3 3 5 2 11 32 32 48 81 45 8OutputYesYesNoYesNoYes
Input8 61 2 1 3 3 5 2 11 32 32 48 81 45 8
OutputYesYesNoYesNoYes
2 seconds
256 megabytes
['dp', 'implementation', 'two pointers', '*1700']
B. Bookstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the i-th book.Valera decided to choose an arbitrary book with number i and read the books one by one, starting from this book. In other words, he will first read book number i, then book number i + 1, then book number i + 2 and so on. He continues the process until he either runs out of the free time or finishes reading the n-th book. Valera reads each book up to the end, that is, he doesn't start reading the book if he doesn't have enough free time to finish reading it. Print the maximum number of books Valera can read.InputThe first line contains two integers n and t (1 ≀ n ≀ 105;Β 1 ≀ t ≀ 109) β€” the number of books and the number of free minutes Valera's got. The second line contains a sequence of n integers a1, a2, ..., an (1 ≀ ai ≀ 104), where number ai shows the number of minutes that the boy needs to read the i-th book.OutputPrint a single integer β€” the maximum number of books Valera can read.ExamplesInput4 53 1 2 1Output3Input3 32 2 3Output1
Input4 53 1 2 1
Output3
2 seconds
256 megabytes
['binary search', 'brute force', 'implementation', 'two pointers', '*1400']
A. Point on Spiraltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1,  - 1)], [( - 1,  - 1), (2,  - 1)], [(2,  - 1), (2, 2)] and so on. Thus, this infinite spiral passes through each integer point of the plane.Valera the horse lives on the plane at coordinates (0, 0). He wants to walk along the spiral to point (x, y). Valera the horse has four legs, so he finds turning very difficult. Count how many times he will have to turn if he goes along a spiral from point (0, 0) to point (x, y).InputThe first line contains two space-separated integers x and y (|x|, |y| ≀ 100).OutputPrint a single integer, showing how many times Valera has to turn.ExamplesInput0 0Output0Input1 0Output0Input0 1Output2Input-1 -1Output3
Input0 0
Output0
2 seconds
256 megabytes
['brute force', 'geometry', 'implementation', '*1400']
B. New Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputComing up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems β€” the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is string slsl + 1... sr.String x = x1x2... xp is lexicographically smaller than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there exists such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The string characters are compared by their ASCII codes.InputThe first line contains integer n (1 ≀ n ≀ 30) β€” the number of titles you've got to consider. Then follow n problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive.OutputPrint a string, consisting of lowercase English letters β€” the lexicographically minimum shortest original title.ExamplesInput5threehorsesgoodsubstringssecretprimematrixbeautifulyearOutputjInput4aabdefghijklmnopqrstuvwxyzcOutputabNoteIn the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j.In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title.
Input5threehorsesgoodsubstringssecretprimematrixbeautifulyear
Outputj
2 seconds
256 megabytes
['brute force', 'strings', '*1500']
A. Circle Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dn - 1 is the distance between the n - 1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.InputThe first line contains integer n (3 ≀ n ≀ 100) β€” the number of stations on the circle line. The second line contains n integers d1, d2, ..., dn (1 ≀ di ≀ 100) β€” the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≀ s, t ≀ n) β€” the numbers of stations, between which you need to find the shortest distance. These numbers can be the same.The numbers in the lines are separated by single spaces.OutputPrint a single number β€” the length of the shortest path between stations number s and t.ExamplesInput42 3 4 91 3Output5Input45 8 2 1004 1Output15Input31 1 13 1Output1Input331 41 591 1Output0NoteIn the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.
Input42 3 4 91 3
Output5
2 seconds
256 megabytes
['implementation', '*800']
E. Binary Tree on Planetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA root tree is a directed acyclic graph that contains one node (root), from which there is exactly one path to any other node.A root tree is binary if each node has at most two outgoing arcs.When a binary tree is painted on the plane, all arcs should be directed from top to bottom. That is, each arc going from u to v must meet the condition yu > yv.You've been given the coordinates of all tree nodes. Your task is to connect these nodes by arcs so as to get the binary root tree and make the total length of the arcs minimum. All arcs of the built tree must be directed from top to bottom.InputThe first line contains a single integer n (2 ≀ n ≀ 400) β€” the number of nodes in the tree. Then follow n lines, two integers per line: xi, yi (|xi|, |yi| ≀ 103) β€” coordinates of the nodes. It is guaranteed that all points are distinct.OutputIf it is impossible to build a binary root tree on the given points, print "-1". Otherwise, print a single real number β€” the total length of the arcs in the minimum binary tree. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6. ExamplesInput30 01 02 1Output3.650281539872885Input40 01 02 12 0Output-1
Input30 01 02 1
Output3.650281539872885
3 seconds
256 megabytes
['flows', 'trees', '*2400']
D. Google Code Jamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMany of you must be familiar with the Google Code Jam round rules. Let us remind you of some key moments that are crucial to solving this problem. During the round, the participants are suggested to solve several problems, each divided into two subproblems: an easy one with small limits (Small input), and a hard one with large limits (Large input). You can submit a solution for Large input only after you've solved the Small input for this problem. There are no other restrictions on the order of solving inputs. In particular, the participant can first solve the Small input, then switch to another problem, and then return to the Large input. Solving each input gives the participant some number of points (usually different for each problem). This takes into account only complete solutions that work correctly on all tests of the input. The participant gets the test result of a Small input right after he submits it, but the test result of a Large input are out only after the round's over. In the final results table the participants are sorted by non-increasing of received points. If the points are equal, the participants are sorted by ascending of time penalty. By the Google Code Jam rules the time penalty is the time when the last correct solution was submitted.Vasya decided to check out a new tactics on another round. As soon as the round begins, the boy quickly read all the problems and accurately evaluated the time it takes to solve them. Specifically, for each one of the n problems Vasya knows five values: Solving the Small input of the i-th problem gives to the participant scoreSmalli points, and solving the Large input gives scoreLargei more points. That is, the maximum number of points you can get for the i-th problem equals scoreSmalli + scoreLargei. Writing the solution for the Small input of the i-th problem takes exactly timeSmalli minutes for Vasya. Improving this code and turning it into the solution of the Large input takes another timeLargei minutes. Vasya's had much practice, so he solves all Small inputs from the first attempt. But it's not so easy with the Large input: there is the probFaili probability that the solution to the Large input will turn out to be wrong at the end of the round. Please keep in mind that these solutions do not affect the participants' points and the time penalty.A round lasts for t minutes. The time for reading problems and submitting solutions can be considered to equal zero. Vasya is allowed to submit a solution exactly at the moment when the round ends.Vasya wants to choose a set of inputs and the order of their solution so as to make the expectation of the total received points maximum possible. If there are multiple ways to do this, he needs to minimize the expectation of the time penalty. Help Vasya to cope with this problem.InputThe first line contains two integers n and t (1 ≀ n ≀ 1000, 1 ≀ t ≀ 1560). Then follow n lines, each containing 5 numbers: scoreSmalli, scoreLargei, timeSmalli, timeLargei, probFaili (1 ≀ scoreSmalli, scoreLargei ≀ 109, 1 ≀ timeSmalli, timeLargei ≀ 1560, 0 ≀ probFaili ≀ 1).probFaili are real numbers, given with at most 6 digits after the decimal point. All other numbers in the input are integers.OutputPrint two real numbers β€” the maximum expectation of the total points and the corresponding minimum possible time penalty expectation. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 9.ExamplesInput3 4010 20 15 4 0.54 100 21 1 0.991 4 1 1 0.25Output24.0 18.875Input1 1100000000 200000000 1 1 0Output100000000 1NoteIn the first sample one of the optimal orders of solving problems is: The Small input of the third problem. The Small input of the first problem. The Large input of the third problem. The Large input of the first problem.Note that if you solve the Small input of the second problem instead of two inputs of the third one, then total score expectation will be the same but the time penalty expectation will be worse (38).
Input3 4010 20 15 4 0.54 100 21 1 0.991 4 1 1 0.25
Output24.0 18.875
2 seconds
256 megabytes
['dp', 'probabilities', '*2800']
C. Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo players play the following game. Initially, the players have a knife and a rectangular sheet of paper, divided into equal square grid cells of unit size. The players make moves in turn, the player who can't make a move loses. In one move, a player can take the knife and cut the paper along any segment of the grid line (not necessarily from border to border). The part of the paper, that touches the knife at least once, is considered cut. There is one limit not to turn the game into an infinite cycle: each move has to cut the paper, that is the knife has to touch the part of the paper that is not cut before.Obviously, the game ends when the entire sheet is cut into 1 × 1 blocks. During the game, the pieces of the sheet are not allowed to move. It is also prohibited to cut along the border. The coordinates of the ends of each cut must be integers.You are given an n × m piece of paper, somebody has already made k cuts there. Your task is to determine who will win if the players start to play on this sheet. You can consider that both players play optimally well. If the first player wins, you also need to find the winning first move.InputThe first line contains three integers n, m, k (1 ≀ n, m ≀ 109, 0 ≀ k ≀ 105) β€” the sizes of the piece of paper and the number of cuts. Then follow k lines, each containing 4 integers xbi, ybi, xei, yei (0 ≀ xbi, xei ≀ n, 0 ≀ ybi, yei ≀ m) β€” the coordinates of the ends of the existing cuts. It is guaranteed that each cut has a non-zero length, is either vertical or horizontal and doesn't go along the sheet border.The cuts may intersect, overlap and even be the same. That is, it is not guaranteed that the cuts were obtained during any correct game.OutputIf the second player wins, print "SECOND". Otherwise, in the first line print "FIRST", and in the second line print any winning move of the first player (the coordinates of the cut ends, follow input format to print them).ExamplesInput2 1 0OutputFIRST1 0 1 1Input2 2 40 1 2 10 1 2 11 2 1 01 1 1 2OutputSECOND
Input2 1 0
OutputFIRST1 0 1 1
2 seconds
256 megabytes
['games', 'implementation', '*2400']
B. Set of Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConvexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line.InputThe single line contains two integers n and m (3 ≀ m ≀ 100, m ≀ n ≀ 2m).OutputIf there is no solution, print "-1". Otherwise, print n pairs of integers β€” the coordinates of points of any set with the convexity of m. The coordinates shouldn't exceed 108 in their absolute value.ExamplesInput4 3Output0 03 00 31 1Input6 3Output-1Input6 6Output10 0-10 010 19 19 -10 -2Input7 4Output176166 6377709276 539564654734 174109910147 434207790497 366519606663 21061859328 886001
Input4 3
Output0 03 00 31 1
2 seconds
256 megabytes
['constructive algorithms', 'geometry', '*2300']
A. Learning Languagestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).InputThe first line contains two integers n and m (2 ≀ n, m ≀ 100) β€” the number of employees and the number of languages.Then n lines follow β€” each employee's language list. At the beginning of the i-th line is integer ki (0 ≀ ki ≀ m) β€” the number of languages the i-th employee knows. Next, the i-th line contains ki integers β€” aij (1 ≀ aij ≀ m) β€” the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.The numbers in the lines are separated by single spaces.OutputPrint a single integer β€” the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).ExamplesInput5 51 22 2 32 3 42 4 51 5Output0Input8 703 1 2 31 12 5 42 6 71 32 7 41 1Output2Input2 21 20Output1NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.
Input5 51 22 2 32 3 42 4 51 5
Output0
2 seconds
256 megabytes
['dfs and similar', 'dsu', '*1400']
E. Little Girl and Problem on Treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA little girl loves problems on trees very much. Here's one of them.A tree is an undirected connected graph, not containing cycles. The degree of node x in the tree is the number of nodes y of the tree, such that each of them is connected with node x by some edge of the tree. Let's consider a tree that consists of n nodes. We'll consider the tree's nodes indexed from 1 to n. The cosidered tree has the following property: each node except for node number 1 has the degree of at most 2.Initially, each node of the tree contains number 0. Your task is to quickly process the requests of two types: Request of form: 0 v x d. In reply to the request you should add x to all numbers that are written in the nodes that are located at the distance of at most d from node v. The distance between two nodes is the number of edges on the shortest path between them. Request of form: 1 v. In reply to the request you should print the current number that is written in node v. InputThe first line contains integers n (2 ≀ n ≀ 105) and q (1 ≀ q ≀ 105) β€” the number of tree nodes and the number of requests, correspondingly.Each of the next n  -  1 lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi), that show that there is an edge between nodes ui and vi. Each edge's description occurs in the input exactly once. It is guaranteed that the given graph is a tree that has the property that is described in the statement.Next q lines describe the requests. The request to add has the following format: 0 v x d (1 ≀ v ≀ n, 1 ≀ x ≀ 104, 1 ≀ d < n). The request to print the node value has the following format: 1 v (1 ≀ v ≀ n). The numbers in the lines are separated by single spaces.OutputFor each request to print the node value print an integer β€” the reply to the request.ExamplesInput3 61 21 30 3 1 20 2 3 10 1 5 21 11 21 3Output996Input6 111 22 55 41 61 30 3 1 30 3 4 50 2 1 40 1 5 50 4 6 21 11 21 31 41 51 6Output111711161711
Input3 61 21 30 3 1 20 2 3 10 1 5 21 11 21 3
Output996
2 seconds
256 megabytes
['data structures', 'graphs', 'trees', '*2100']
D. Little Girl and Maximum XORtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA little girl loves problems on bitwise operations very much. Here's one of them.You are given two integers l and r. Let's consider the values of for all pairs of integers a and b (l ≀ a ≀ b ≀ r). Your task is to find the maximum value among all considered ones.Expression means applying bitwise excluding or operation to integers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is represented as "^", in Pascal β€” as "xor".InputThe single line contains space-separated integers l and r (1 ≀ l ≀ r ≀ 1018).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.OutputIn a single line print a single integer β€” the maximum value of for all pairs of integers a, b (l ≀ a ≀ b ≀ r).ExamplesInput1 2Output3Input8 16Output31Input1 1Output0
Input1 2
Output3
1 second
256 megabytes
['bitmasks', 'dp', 'greedy', 'implementation', 'math', '*1700']
C. Little Girl and Maximum Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); also, there are q queries, each one is defined by a pair of integers l_i, r_i (1 \le l_i \le r_i \le n). You need to find for each query the sum of elements of the array with indexes from l_i to r_i, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.InputThe first line contains two space-separated integers n (1 \le n \le 2\cdot10^5) and q (1 \le q \le 2\cdot10^5) β€” the number of elements in the array and the number of queries, correspondingly.The next line contains n space-separated integers a_i (1 \le a_i \le 2\cdot10^5) β€” the array elements.Each of the following q lines contains two space-separated integers l_i and r_i (1 \le l_i \le r_i \le n) β€” the i-th query.OutputIn a single line print, a single integer β€” the maximum sum of query replies after the array elements are reordered.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.ExamplesInput3 35 3 21 22 31 3Output25Input5 35 2 4 1 31 52 32 3Output33
Input3 35 3 21 22 31 3
Output25
1 second
256 megabytes
['data structures', 'greedy', 'implementation', 'sortings', '*1500']