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
A. Points on Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.InputThe first line contains two integers: n and d (1 ≀ n ≀ 105;Β 1 ≀ d ≀ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 β€” the x-coordinates of the points that Petya has got.It is guaranteed that the coordinates of the points in the input strictly increase.OutputPrint a single integer β€” the number of groups of three points, where the distance between two farthest points doesn't exceed d.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 31 2 3 4Output4Input4 2-3 -2 -1 0Output2Input5 191 10 20 30 50Output1NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.
Input4 31 2 3 4
Output4
2 seconds
256 megabytes
['binary search', 'combinatorics', 'two pointers', '*1300']
E. Mad Joetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJoe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each floor is surrounded by a concrete wall on the left and on the right.Now Joe is on the n-th floor and in the first cell, counting from left to right. At each moment of time, Joe has the direction of his gaze, to the right or to the left (always one direction of the two). Initially, Joe looks to the right.Joe moves by a particular algorithm. Every second he makes one of the following actions: If the cell directly under Joe is empty, then Joe falls down. That is, he moves to this cell, the gaze direction is preserved. Otherwise consider the next cell in the current direction of the gaze. If the cell is empty, then Joe moves into it, the gaze direction is preserved. If this cell has bricks, then Joe breaks them with his forehead (the cell becomes empty), and changes the direction of his gaze to the opposite. If this cell has a concrete wall, then Joe just changes the direction of his gaze to the opposite (concrete can withstand any number of forehead hits). Joe calms down as soon as he reaches any cell of the first floor.The figure below shows an example Joe's movements around the house. Determine how many seconds Joe will need to calm down.InputThe first line contains two integers n and m (2 ≀ n ≀ 100, 1 ≀ m ≀ 104).Next n lines contain the description of Joe's house. The i-th of these lines contains the description of the (n - i + 1)-th floor of the house β€” a line that consists of m characters: "." means an empty cell, "+" means bricks and "#" means a concrete wall.It is guaranteed that the first cell of the n-th floor is empty.OutputPrint a single number β€” the number of seconds Joe needs to reach the first floor; or else, print word "Never" (without the quotes), if it can never happen.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 5..+.##+..++.#+.Output14Input4 10...+.##+.++#++..+++#++.#++++...+##.++#.+Output42Input2 2..++OutputNever
Input3 5..+.##+..++.#+.
Output14
1 second
256 megabytes
['brute force', '*2000']
D. Building Bridgetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages.The river banks can be assumed to be vertical straight lines x = a and x = b (0 < a < b).The west village lies in a steppe at point O = (0, 0). There are n pathways leading from the village to the river, they end at points Ai = (a, yi). The villagers there are plain and simple, so their pathways are straight segments as well.The east village has reserved and cunning people. Their village is in the forest on the east bank of the river, but its exact position is not clear. There are m twisted paths leading from this village to the river and ending at points Bi = (b, y'i). The lengths of all these paths are known, the length of the path that leads from the eastern village to point Bi, equals li.The villagers want to choose exactly one point on the left bank of river Ai, exactly one point on the right bank Bj and connect them by a straight-line bridge so as to make the total distance between the villages (the sum of |OAi| + |AiBj| + lj, where |XY| is the Euclidean distance between points X and Y) were minimum. The Euclidean distance between points (x1, y1) and (x2, y2) equals .Help them and find the required pair of points.InputThe first line contains integers n, m, a, b (1 ≀ n, m ≀ 105, 0 < a < b < 106). The second line contains n integers in the ascending order: the i-th integer determines the coordinate of point Ai and equals yi (|yi| ≀ 106). The third line contains m integers in the ascending order: the i-th integer determines the coordinate of point Bi and equals y'i (|y'i| ≀ 106). The fourth line contains m more integers: the i-th of them determines the length of the path that connects the eastern village and point Bi, and equals li (1 ≀ li ≀ 106).It is guaranteed, that there is such a point C with abscissa at least b, that |BiC| ≀ li for all i (1 ≀ i ≀ m). It is guaranteed that no two points Ai coincide. It is guaranteed that no two points Bi coincide.OutputPrint two integers β€” the numbers of points on the left (west) and right (east) banks, respectively, between which you need to build a bridge. You can assume that the points on the west bank are numbered from 1 to n, in the order in which they are given in the input. Similarly, the points on the east bank are numbered from 1 to m in the order in which they are given in the input.If there are multiple solutions, print any of them. The solution will be accepted if the final length of the path will differ from the answer of the jury by no more than 10 - 6 in absolute or relative value.ExamplesInput3 2 3 5-2 -1 4-1 27 3Output2 2
Input3 2 3 5-2 -1 4-1 27 3
Output2 2
1 second
256 megabytes
['geometry', 'ternary search', 'two pointers', '*1900']
C. Movie Criticstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre β€” an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≀ x ≀ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.InputThe first line of the input contains two integers n and k (2 ≀ k ≀ n ≀ 105), where n is the number of movies and k is the number of genres.The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≀ ai ≀ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.OutputPrint a single number β€” the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.ExamplesInput10 31 1 2 3 2 3 3 1 1 3Output3Input7 33 1 3 2 3 1 2Output1NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.
Input10 31 1 2 3 2 3 3 1 1 3
Output3
2 seconds
256 megabytes
['greedy', '*1600']
B. Restoring IPv6time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons β€” 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full.Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000"  →  "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address.Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below: "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::"; "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0"; "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0"; "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000"; "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.You've got several short records of IPv6 addresses. Restore their full record.InputThe first line contains a single integer n β€” the number of records to restore (1 ≀ n ≀ 100).Each of the following n lines contains a string β€” the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:".It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.OutputFor each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.ExamplesInput6a56f:d3:0:0124:01:f19a:1000:00a56f:00d3:0000:0124:0001::a56f::0124:0001:0000:1234:0ff0a56f:0000::0000:0001:0000:1234:0ff0::0ea::4d:f4:6:0Outputa56f:00d3:0000:0124:0001:f19a:1000:0000a56f:00d3:0000:0124:0001:0000:0000:0000a56f:0000:0000:0124:0001:0000:1234:0ff0a56f:0000:0000:0000:0001:0000:1234:0ff00000:0000:0000:0000:0000:0000:0000:000000ea:0000:0000:0000:004d:00f4:0006:0000
Input6a56f:d3:0:0124:01:f19a:1000:00a56f:00d3:0000:0124:0001::a56f::0124:0001:0000:1234:0ff0a56f:0000::0000:0001:0000:1234:0ff0::0ea::4d:f4:6:0
Outputa56f:00d3:0000:0124:0001:f19a:1000:0000a56f:00d3:0000:0124:0001:0000:0000:0000a56f:0000:0000:0124:0001:0000:1234:0ff0a56f:0000:0000:0000:0001:0000:1234:0ff00000:0000:0000:0000:0000:0000:0000:000000ea:0000:0000:0000:004d:00f4:0006:0000
2 seconds
256 megabytes
['implementation', 'strings', '*1500']
A. Paper Worktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as n days. Right now his task is to make a series of reports about the company's performance for the last n days. We know that the main information in a day report is value ai, the company's profit on the i-th day. If ai is negative, then the company suffered losses on the i-th day.Polycarpus should sort the daily reports into folders. Each folder should include data on the company's performance for several consecutive days. Of course, the information on each of the n days should be exactly in one folder. Thus, Polycarpus puts information on the first few days in the first folder. The information on the several following days goes to the second folder, and so on.It is known that the boss reads one daily report folder per day. If one folder has three or more reports for the days in which the company suffered losses (ai < 0), he loses his temper and his wrath is terrible.Therefore, Polycarpus wants to prepare the folders so that none of them contains information on three or more days with the loss, and the number of folders is minimal.Write a program that, given sequence ai, will print the minimum number of folders.InputThe first line contains integer n (1 ≀ n ≀ 100), n is the number of days. The second line contains a sequence of integers a1, a2, ..., an (|ai| ≀ 100), where ai means the company profit on the i-th day. It is possible that the company has no days with the negative ai.OutputPrint an integer k β€” the required minimum number of folders. In the second line print a sequence of integers b1, b2, ..., bk, where bj is the number of day reports in the j-th folder.If there are multiple ways to sort the reports into k days, print any of them.ExamplesInput111 2 3 -4 -5 -6 5 -5 -6 -7 6Output35 3 3 Input50 -1 100 -1 0Output15 NoteHere goes a way to sort the reports from the first sample into three folders: 1 2 3 -4 -5 | -6 5 -5 | -6 -7 6 In the second sample you can put all five reports in one folder.
Input111 2 3 -4 -5 -6 5 -5 -6 -7 6
Output35 3 3
2 seconds
256 megabytes
['greedy', '*1000']
E. Endless Matrixtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA Russian space traveller Alisa Selezneva, like any other schoolgirl of the late 21 century, is interested in science. She has recently visited the MIT (Moscow Institute of Time), where its chairman and the co-inventor of the time machine academician Petrov told her about the construction of a time machine.During the demonstration of the time machine performance Alisa noticed that the machine does not have high speed and the girl got interested in the reason for such disadvantage. As it turns out on closer examination, one of the problems that should be solved for the time machine isn't solved by an optimal algorithm. If you find a way to solve this problem optimally, the time machine will run faster and use less energy.A task that none of the staff can solve optimally is as follows. There exists a matrix a, which is filled by the following rule:The cells are consecutive positive integers, starting with one. Besides, ai, j < at, k (i, j, t, k β‰₯ 1), if: max(i, j) < max(t, k); max(i, j) = max(t, k) and j < k; max(i, j) = max(t, k), j = k and i > t. So, after the first 36 numbers are inserted, matrix a will look as follows: To solve the problem, you should learn to find rather quickly for the given values of x1, y1, x2 and y2 (x1 ≀ x2, y1 ≀ y2) the meaning of expression:As the meaning of this expression can be large enough, it is sufficient to know only the last 10 digits of the sought value.So, no one in MTI can solve the given task. Alice was brave enough to use the time machine and travel the past to help you.Your task is to write a program that uses the given values x1, y1, x2 and y2 finds the last 10 digits of the given expression.InputThe first input line contains a single integer t (1 ≀ t ≀ 105) β€” the number of test sets for which you should solve the problem. Each of the next t lines contains the description of a test β€” four positive integers x1, y1, x2 and y2 (1 ≀ x1 ≀ x2 ≀ 109, 1 ≀ y1 ≀ y2 ≀ 109), separated by spaces.OutputFor each query print the meaning of the expression if it contains at most 10 characters. Otherwise, print three characters "." (without the quotes), and then ten last digits of the time expression. Print the answer to each query on a single line. Follow the format, given in the sample as closely as possible.ExamplesInput51 1 1 12 2 3 32 3 5 6100 87 288 20024 2 5 4Output124300...5679392764111
Input51 1 1 12 2 3 32 3 5 6100 87 288 20024 2 5 4
Output124300...5679392764111
3 seconds
256 megabytes
['math', '*2600']
D. Donkey and Starstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the stars, so he knew that they are exactly n. This time he wanted a challenge. He imagined a coordinate system: he put the origin of the coordinates at the intersection of the roof and the chimney, directed the OX axis to the left along the roof and the OY axis β€” up along the chimney (see figure). The Donkey imagined two rays emanating from he origin of axes at angles Ξ±1 and Ξ±2 to the OX axis. Now he chooses any star that lies strictly between these rays. After that he imagines more rays that emanate from this star at the same angles Ξ±1 and Ξ±2 to the OX axis and chooses another star that lies strictly between the new rays. He repeats the operation as long as there still are stars he can choose between the rays that emanate from a star. As a result, the Donkey gets a chain of stars. He can consecutively get to each star if he acts by the given rules.Your task is to find the maximum number of stars m that the Donkey's chain can contain.Note that the chain must necessarily start in the point of the origin of the axes, that isn't taken into consideration while counting the number m of stars in the chain.InputThe first line contains an integer n (1 ≀ n ≀ 105) β€” the number of stars. The second line contains simple fractions representing relationships "a/b c/d", such that and (0 ≀ a, b, c, d ≀ 105; ; ; ). The given numbers a, b, c, d are integers.Next n lines contain pairs of integers xi, yi (1 ≀ xi, yi ≀ 105)β€” the stars' coordinates.It is guaranteed that all stars have distinct coordinates.OutputIn a single line print number m β€” the answer to the problem.ExamplesInput151/3 2/13 16 24 22 54 56 63 41 62 17 49 35 31 315 512 4Output4NoteIn the sample the longest chain the Donkey can build consists of four stars. Note that the Donkey can't choose the stars that lie on the rays he imagines.
Input151/3 2/13 16 24 22 54 56 63 41 62 17 49 35 31 315 512 4
Output4
2 seconds
256 megabytes
['data structures', 'dp', 'geometry', 'math', 'sortings', '*2700']
E. Piglet's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPiglet has got a birthday today. His friend Winnie the Pooh wants to make the best present for him β€” a honey pot. Of course Winnie realizes that he won't manage to get the full pot to Piglet. In fact, he is likely to eat all the honey from the pot. And as soon as Winnie planned a snack on is way, the pot should initially have as much honey as possible. The day before Winnie the Pooh replenished his honey stocks. Winnie-the-Pooh has n shelves at home, each shelf contains some, perhaps zero number of honey pots. During the day Winnie came to the honey shelves q times; on the i-th time he came to some shelf ui, took from it some pots ki, tasted the honey from each pot and put all those pots on some shelf vi. As Winnie chose the pots, he followed his intuition. And that means that among all sets of ki pots on shelf ui, he equiprobably chooses one.Now Winnie remembers all actions he performed with the honey pots. He wants to take to the party the pot he didn't try the day before. For that he must know the mathematical expectation of the number m of shelves that don't have a single untasted pot. To evaluate his chances better, Winnie-the-Pooh wants to know the value m after each action he performs.Your task is to write a program that will find those values for him.InputThe first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of shelves at Winnie's place. The second line contains n integers ai (1 ≀ i ≀ n, 0 ≀ ai ≀ 100) β€” the number of honey pots on a shelf number i. The next line contains integer q (1 ≀ q ≀ 105) β€” the number of actions Winnie did the day before. Then follow q lines, the i-th of them describes an event that follows chronologically; the line contains three integers ui, vi and ki (1 ≀ ui, vi ≀ n, 1 ≀ ki ≀ 5) β€” the number of the shelf from which Winnie took pots, the number of the shelf on which Winnie put the pots after he tasted each of them, and the number of the pots Winnie tasted, correspondingly.Consider the shelves with pots numbered with integers from 1 to n. It is guaranteed that Winnie-the-Pooh Never tried taking more pots from the shelf than it has.OutputFor each Winnie's action print the value of the mathematical expectation m by the moment when this action is performed. The relative or absolute error of each value mustn't exceed 10 - 9.ExamplesInput32 2 351 2 12 1 21 2 23 1 13 2 2Output0.0000000000000.3333333333331.0000000000001.0000000000002.000000000000
Input32 2 351 2 12 1 21 2 23 1 13 2 2
Output0.0000000000000.3333333333331.0000000000001.0000000000002.000000000000
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*2600']
D. Sweets for Everyone!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!"Dr. Suess, How The Grinch Stole ChristmasChristmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street.The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets).After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food.The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets.Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street.Your task is to write a program that will determine the minimum possible value of k.InputThe first line of the input contains two space-separated integers n and t (2 ≀ n ≀ 5Β·105, 1 ≀ t ≀ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house.OutputIf there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k.ExamplesInput6 6HSHSHSOutput1Input14 100...HHHSSS...SHOutput0Input23 50HHSS.......SSHHHHHHHHHHOutput8NoteIn the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back.In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction.In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home.
Input6 6HSHSHS
Output1
2 seconds
256 megabytes
['binary search', 'greedy', 'implementation', '*2300']
C. Robo-Footballertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And yet, the notion of a giveaway is foreign to him. The combination of these features makes the Robo-Wallace the perfect footballer β€” as soon as the ball gets to him, he can just aim and hit the goal. He followed this tactics in the first half of the match, but he hit the goal rarely. The opposing team has a very good goalkeeper who catches most of the balls that fly directly into the goal. But Robo-Wallace is a quick thinker, he realized that he can cheat the goalkeeper. After all, they are playing in a football box with solid walls. Robo-Wallace can kick the ball to the other side, then the goalkeeper will not try to catch the ball. Then, if the ball bounces off the wall and flies into the goal, the goal will at last be scored.Your task is to help Robo-Wallace to detect a spot on the wall of the football box, to which the robot should kick the ball, so that the ball bounces once and only once off this wall and goes straight to the goal. In the first half of the match Robo-Wallace got a ball in the head and was severely hit. As a result, some of the schemes have been damaged. Because of the damage, Robo-Wallace can only aim to his right wall (Robo-Wallace is standing with his face to the opposing team's goal).The football box is rectangular. Let's introduce a two-dimensional coordinate system so that point (0, 0) lies in the lower left corner of the field, if you look at the box above. Robo-Wallace is playing for the team, whose goal is to the right. It is an improvised football field, so the gate of Robo-Wallace's rivals may be not in the middle of the left wall. In the given coordinate system you are given: y1, y2 β€” the y-coordinates of the side pillars of the goalposts of robo-Wallace's opponents; yw β€” the y-coordinate of the wall to which Robo-Wallace is aiming; xb, yb β€” the coordinates of the ball's position when it is hit; r β€” the radius of the ball. A goal is scored when the center of the ball crosses the OY axis in the given coordinate system between (0, y1) and (0, y2). The ball moves along a straight line. The ball's hit on the wall is perfectly elastic (the ball does not shrink from the hit), the angle of incidence equals the angle of reflection. If the ball bounces off the wall not to the goal, that is, if it hits the other wall or the goal post, then the opposing team catches the ball and Robo-Wallace starts looking for miscalculation and gets dysfunctional. Such an outcome, if possible, should be avoided. We assume that the ball touches an object, if the distance from the center of the ball to the object is no greater than the ball radius r.InputThe first and the single line contains integers y1, y2, yw, xb, yb, r (1 ≀ y1, y2, yw, xb, yb ≀ 106; y1 < y2 < yw; yb + r < yw; 2Β·r < y2 - y1).It is guaranteed that the ball is positioned correctly in the field, doesn't cross any wall, doesn't touch the wall that Robo-Wallace is aiming at. The goal posts can't be located in the field corners.OutputIf Robo-Wallace can't score a goal in the described manner, print "-1" (without the quotes). Otherwise, print a single number xw β€” the abscissa of his point of aiming. If there are multiple points of aiming, print the abscissa of any of them. When checking the correctness of the answer, all comparisons are made with the permissible absolute error, equal to 10 - 8. It is recommended to print as many characters after the decimal point as possible.ExamplesInput4 10 13 10 3 1Output4.3750000000Input1 4 6 2 2 1Output-1Input3 10 15 17 9 2Output11.3333333333NoteNote that in the first and third samples other correct values of abscissa xw are also possible.
Input4 10 13 10 3 1
Output4.3750000000
2 seconds
256 megabytes
['binary search', 'geometry', '*2000']
B. Chilly Willytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputChilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros.InputA single input line contains a single integer n (1 ≀ n ≀ 105).OutputPrint a single integer β€” the answer to the problem without leading zeroes, or "-1" (without the quotes), if the number that meet the problem condition does not exist.ExamplesInput1Output-1Input5Output10080
Input1
Output-1
2 seconds
256 megabytes
['math', 'number theory', '*1400']
A. Cupboardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t.InputThe first input line contains a single integer n β€” the number of cupboards in the kitchen (2 ≀ n ≀ 104). Then follow n lines, each containing two integers li and ri (0 ≀ li, ri ≀ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero.The numbers in the lines are separated by single spaces.OutputIn the only output line print a single integer t β€” the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.ExamplesInput50 11 00 11 10 1Output3
Input50 11 00 11 10 1
Output3
2 seconds
256 megabytes
['implementation', '*800']
E. Blood Cousins Returntime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus got hold of a family tree. The found tree describes the family relations of n people, numbered from 1 to n. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.We call the man with a number a a 1-ancestor of the man with a number b, if the man with a number a is a direct ancestor of the man with a number b.We call the man with a number a a k-ancestor (k > 1) of the man with a number b, if the man with a number b has a 1-ancestor, and the man with a number a is a (k - 1)-ancestor of the 1-ancestor of the man with a number b.In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an x-ancestor of himself, for some x, x > 0).We call a man with a number a the k-son of the man with a number b, if the man with a number b is a k-ancestor of the man with a number a.Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote m pairs of numbers vi, ki. Help him to learn for each pair vi, ki the number of distinct names among all names of the ki-sons of the man with number vi.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of people in the tree. Next n lines contain the description of people in the tree. The i-th line contains space-separated string si and integer ri (0 ≀ ri ≀ n), where si is the name of the man with a number i, and ri is either the number of the direct ancestor of the man with a number i or 0, if the man with a number i has no direct ancestor. The next line contains a single integer m (1 ≀ m ≀ 105) β€” the number of Polycarpus's records. Next m lines contain space-separated pairs of integers. The i-th line contains integers vi, ki (1 ≀ vi, ki ≀ n).It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.OutputPrint m whitespace-separated integers β€” the answers to Polycarpus's records. Print the answers to the records in the order, in which the records occur in the input.ExamplesInput6pasha 0gerald 1gerald 1valera 2igor 3olesya 151 11 21 33 16 1Output22010Input6valera 0valera 1valera 1gerald 0valera 4kolya 471 11 22 12 24 15 16 1Output1000200
Input6pasha 0gerald 1gerald 1valera 2igor 3olesya 151 11 21 33 16 1
Output22010
3 seconds
256 megabytes
['binary search', 'data structures', 'dfs and similar', 'dp', 'sortings', '*2400']
D. Colorful Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cuΒ :  cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.InputThe first line contains two space-separated integers n, m (1 ≀ n, m ≀ 105) β€” the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≀ ci ≀ 105) β€” the colors of the graph vertices. The numbers on the line are separated by spaces.Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n;Β ai ≠ bi) β€” the numbers of the vertices, connected by the i-th edge. It is guaranteed that the given graph has no self-loops or multiple edges.OutputPrint the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.ExamplesInput6 61 1 2 3 5 81 23 21 44 34 54 6Output3Input5 64 2 5 2 41 22 33 15 35 43 4Output2
Input6 61 1 2 3 5 81 23 21 44 34 54 6
Output3
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'graphs', '*1600']
C. Beauty Pageanttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGeneral Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.All soldiers in the battalion have different beauty that is represented by a positive integer. The value ai represents the beauty of the i-th soldier.On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers.Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty.InputThe first line contains two integers n, k (1 ≀ n ≀ 50; 1 ≀ k ≀  ) β€” the number of soldiers and the number of days in the pageant, correspondingly. The second line contains space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 107) β€” the beauties of the battalion soldiers.It is guaranteed that Payne's battalion doesn't have two soldiers with the same beauty.OutputPrint k lines: in the i-th line print the description of the detachment that will participate in the pageant on the i-th day. The description consists of integer ci (1 ≀ ci ≀ n) β€” the number of soldiers in the detachment on the i-th day of the pageant and ci distinct integers p1, i, p2, i, ..., pci, i β€” the beauties of the soldiers in the detachment on the i-th day of the pageant. The beauties of the soldiers are allowed to print in any order.Separate numbers on the lines by spaces. It is guaranteed that there is the solution that meets the problem conditions. If there are multiple solutions, print any of them.ExamplesInput3 31 2 3Output1 11 22 3 2Input2 17 12Output1 12
Input3 31 2 3
Output1 11 22 3 2
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'greedy', '*1600']
B. Increase and Decreasetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: he chooses two elements of the array ai, aj (i ≠ j); he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≀ 104) β€” the original array.OutputPrint a single integer β€” the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.ExamplesInput22 1Output1Input31 4 1Output3
Input22 1
Output1
2 seconds
256 megabytes
['greedy', 'math', '*1300']
A. Buggy Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of n integers a1, a2, ..., an in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. The input of the program gets number n and array a.loop integer variable i from 1 to n - 1Β Β Β Β loop integer variable j from i to n - 1Β Β Β Β Β Β Β Β if (aj > aj + 1), then swap the values of elements aj and aj + 1But Valera could have made a mistake, because he hasn't yet fully learned the sorting algorithm. If Valera made a mistake in his program, you need to give a counter-example that makes his program work improperly (that is, the example that makes the program sort the array not in the non-decreasing order). If such example for the given value of n doesn't exist, print -1.InputYou've got a single integer n (1 ≀ n ≀ 50) β€” the size of the sorted array.OutputPrint n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 100) β€” the counter-example, for which Valera's algorithm won't work correctly. If the counter-example that meets the described conditions is impossible to give, print -1.If there are several counter-examples, consisting of n numbers, you are allowed to print any of them.ExamplesInput1Output-1
Input1
Output-1
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*900']
H. Queries for Number of Palindromestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a string s = s1s2... s|s| of length |s|, consisting of lowercase English letters. There also are q queries, each query is described by two integers li, ri (1 ≀ li ≀ ri ≀ |s|). The answer to the query is the number of substrings of string s[li... ri], which are palindromes.String s[l... r] = slsl + 1... sr (1 ≀ l ≀ r ≀ |s|) is a substring of string s = s1s2... s|s|.String t is called a palindrome, if it reads the same from left to right and from right to left. Formally, if t = t1t2... t|t| = t|t|t|t| - 1... t1.InputThe first line contains string s (1 ≀ |s| ≀ 5000). The second line contains a single integer q (1 ≀ q ≀ 106) β€” the number of queries. Next q lines contain the queries. The i-th of these lines contains two space-separated integers li, ri (1 ≀ li ≀ ri ≀ |s|) β€” the description of the i-th query.It is guaranteed that the given string consists only of lowercase English letters.OutputPrint q integers β€” the answers to the queries. Print the answers in the order, in which the queries are given in the input. Separate the printed numbers by whitespaces.ExamplesInputcaaaba51 11 42 34 64 5Output17342NoteConsider the fourth query in the first test case. String s[4... 6] = Β«abaΒ». Its palindrome substrings are: Β«aΒ», Β«bΒ», Β«aΒ», Β«abaΒ».
Inputcaaaba51 11 42 34 64 5
Output17342
5 seconds
256 megabytes
['dp', 'hashing', 'strings', '*1800']
G. Suggested Friendstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus works as a programmer in a start-up social network. His boss gave his a task to develop a mechanism for determining suggested friends. Polycarpus thought much about the task and came to the folowing conclusion. Let's say that all friendship relationships in a social network are given as m username pairs ai, bi (ai ≠ bi). Each pair ai, bi means that users ai and bi are friends. Friendship is symmetric, that is, if ai is friends with bi, then bi is also friends with ai. User y is a suggested friend for user x, if the following conditions are met: x ≠ y; x and y aren't friends; among all network users who meet the first two conditions, user y has most of all common friends with user x. User z is a common friend of user x and user y (z ≠ x, z ≠ y), if x and z are friends, and y and z are also friends. Your task is to help Polycarpus to implement a mechanism for determining suggested friends.InputThe first line contains a single integer m (1 ≀ m ≀ 5000) β€” the number of pairs of friends in the social network. Next m lines contain pairs of names of the users who are friends with each other. The i-th line contains two space-separated names ai and bi (ai ≠ bi). The users' names are non-empty and consist of at most 20 uppercase and lowercase English letters. It is guaranteed that each pair of friends occurs only once in the input. For example, the input can't contain x, y and y, x at the same time. It is guaranteed that distinct users have distinct names. It is guaranteed that each social network user has at least one friend. The last thing guarantees that each username occurs at least once in the input.OutputIn the first line print a single integer n β€” the number of network users. In next n lines print the number of suggested friends for each user. In the i-th line print the name of the user ci and the number of his suggested friends di after a space. You can print information about the users in any order.ExamplesInput5Mike GeraldKate MikeKate TankGerald TankGerald DavidOutput5Mike 1Gerald 1Kate 1Tank 1David 2Input4valera vanyavalera edikpasha valeraigor valeraOutput5valera 0vanya 3edik 3pasha 3igor 3NoteIn the first test case consider user David. Users Mike and Tank have one common friend (Gerald) with David. User Kate has no common friends with David. That's why David's suggested friends are users Mike and Tank.
Input5Mike GeraldKate MikeKate TankGerald TankGerald David
Output5Mike 1Gerald 1Kate 1Tank 1David 2
2 seconds
256 megabytes
['brute force', 'graphs', '*2200']
F. Log Stream Analysistime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format.The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description).Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m.InputThe first line of the input contains two space-separated integers n and m (1 ≀ n, m ≀ 10000).The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program. It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5Β·106 (in particular, this means that the length of some line does not exceed 5Β·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty.OutputIf there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) β€” the first moment of time when the number of warnings for the last n seconds got no less than m.ExamplesInput60 32012-03-16 16:15:25: Disk size is2012-03-16 16:15:25: Network failute2012-03-16 16:16:29: Cant write varlog2012-03-16 16:16:42: Unable to start process2012-03-16 16:16:43: Disk size is too small2012-03-16 16:16:53: Timeout detectedOutput2012-03-16 16:16:43Input1 22012-03-16 23:59:59:Disk size2012-03-17 00:00:00: Network2012-03-17 00:00:01:Cant write varlogOutput-1Input2 22012-03-16 23:59:59:Disk size is too sm2012-03-17 00:00:00:Network failute dete2012-03-17 00:00:01:Cant write varlogmysqOutput2012-03-17 00:00:00
Input60 32012-03-16 16:15:25: Disk size is2012-03-16 16:15:25: Network failute2012-03-16 16:16:29: Cant write varlog2012-03-16 16:16:42: Unable to start process2012-03-16 16:16:43: Disk size is too small2012-03-16 16:16:53: Timeout detected
Output2012-03-16 16:16:43
2 seconds
256 megabytes
['binary search', 'brute force', 'implementation', 'strings', '*2000']
E. Mishap in Clubtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen.On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, each time a visitor left the club, Polycarpus put character "-" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.InputThe only line of the input contains a sequence of characters "+" and "-", the characters are written one after another without any separators. The characters are written in the order, in which the corresponding events occurred. The given sequence has length from 1 to 300 characters, inclusive.OutputPrint the sought minimum number of peopleExamplesInput+-+-+Output1Input---Output3
Input+-+-+
Output1
2 seconds
256 megabytes
['greedy', 'implementation', '*1400']
D. Restoring Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation.For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers a1, a2, ..., an. He also wrote a square matrix b of size n × n. The element of matrix b that sits in the i-th row in the j-th column (we'll denote it as bij) equals: the "bitwise AND" of numbers ai and aj (that is, bij = aiΒ &Β aj), if i ≠ j; -1, if i = j. Having written out matrix b, Polycarpus got very happy and wiped a off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly.Help Polycarpus, given matrix b, restore the sequence of numbers a1, a2, ..., an, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 109.InputThe first line contains a single integer n (1 ≀ n ≀ 100) β€” the size of square matrix b. Next n lines contain matrix b. The i-th of these lines contains n space-separated integers: the j-th number represents the element of matrix bij. It is guaranteed, that for all i (1 ≀ i ≀ n) the following condition fulfills: bii = -1. It is guaranteed that for all i, j (1 ≀ i, j ≀ n;Β i ≠ j) the following condition fulfills: 0 ≀ bij ≀ 109, bij = bji.OutputPrint n non-negative integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the sequence that Polycarpus wiped off the board. Separate the numbers by whitespaces. It is guaranteed that there is sequence a that satisfies the problem conditions. If there are multiple such sequences, you are allowed to print any of them.ExamplesInput1-1Output0 Input3-1 18 018 -1 00 0 -1Output18 18 0 Input4-1 128 128 128128 -1 148 160128 148 -1 128128 160 128 -1Output128 180 148 160 NoteIf you do not know what is the "bitwise AND" operation please read: http://en.wikipedia.org/wiki/Bitwise_operation.
Input1-1
Output0
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1500']
C. Game with Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo pirates Polycarpus and Vasily play a very interesting game. They have n chests with coins, the chests are numbered with integers from 1 to n. Chest number i has ai coins. Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer x (2Β·x + 1 ≀ n) and take a coin from each chest with numbers x, 2Β·x, 2Β·x + 1. It may turn out that some chest has no coins, in this case the player doesn't take a coin from this chest. The game finishes when all chests get emptied.Polycarpus isn't a greedy scrooge. Polycarpys is a lazy slob. So he wonders in what minimum number of moves the game can finish. Help Polycarpus, determine the minimum number of moves in which the game can finish. Note that Polycarpus counts not only his moves, he also counts Vasily's moves.InputThe first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of chests with coins. The second line contains a sequence of space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 1000), where ai is the number of coins in the chest number i at the beginning of the game.OutputPrint a single integer β€” the minimum number of moves needed to finish the game. If no sequence of turns leads to finishing the game, print -1.ExamplesInput11Output-1Input31 2 3Output3NoteIn the first test case there isn't a single move that can be made. That's why the players won't be able to empty the chests.In the second sample there is only one possible move x = 1. This move should be repeated at least 3 times to empty the third chest.
Input11
Output-1
2 seconds
256 megabytes
['greedy', '*1700']
B. Internet Addresstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>] where: <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes), <domain> is a non-empty string, consisting of lowercase English letters, the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters. If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context).When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".".Help Vasya to restore the possible address of the recorded Internet resource.InputThe first line contains a non-empty string that Vasya wrote out in his notebook. This line consists of lowercase English letters only. It is guaranteed that the given string contains at most 50 letters. It is guaranteed that the given string can be obtained from some correct Internet resource address, described above.OutputPrint a single line β€” the address of the Internet resource that Vasya liked. If there are several addresses that meet the problem limitations, you are allowed to print any of them.ExamplesInputhttpsunruxOutputhttp://sun.ru/xInputftphttprururuOutputftp://http.ru/ruruNoteIn the second sample there are two more possible answers: "ftp://httpruru.ru" and "ftp://httpru.ru/ru".
Inputhttpsunrux
Outputhttp://sun.ru/x
2 seconds
256 megabytes
['implementation', 'strings', '*1100']
A. System Administratortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus is a system administrator. There are two servers under his strict guidance β€” a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10;Β x, y β‰₯ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.InputThe first line contains a single integer n (2 ≀ n ≀ 1000) β€” the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers β€” the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≀ ti ≀ 2;Β xi, yi β‰₯ 0;Β xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost.It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.OutputIn the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes).In the second line print the state of server b in the similar format.ExamplesInput21 5 52 6 4OutputLIVELIVEInput31 0 102 0 101 10 0OutputLIVEDEADNoteConsider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.
Input21 5 52 6 4
OutputLIVELIVE
2 seconds
256 megabytes
['implementation', '*800']
B. Undoubtedly Lucky Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky.Let's call a positive integer a undoubtedly lucky, if there are such digits x and y (0 ≀ x, y ≀ 9), that the decimal representation of number a (without leading zeroes) contains only digits x and y.Polycarpus has integer n. He wants to know how many positive integers that do not exceed n, are undoubtedly lucky. Help him, count this number.InputThe first line contains a single integer n (1 ≀ n ≀ 109) β€” Polycarpus's number.OutputPrint a single integer that says, how many positive integers that do not exceed n are undoubtedly lucky.ExamplesInput10Output10Input123Output113NoteIn the first test sample all numbers that do not exceed 10 are undoubtedly lucky.In the second sample numbers 102, 103, 104, 105, 106, 107, 108, 109, 120, 123 are not undoubtedly lucky.
Input10
Output10
2 seconds
256 megabytes
['bitmasks', 'brute force', 'dfs and similar', '*1600']
A. Dividing Orangetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Ms Swan bought an orange in a shop. The orange consisted of nΒ·k segments, numbered with integers from 1 to nΒ·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 ≀ i ≀ k) child wrote the number ai (1 ≀ ai ≀ nΒ·k). All numbers ai accidentally turned out to be different.Now the children wonder, how to divide the orange so as to meet these conditions: each child gets exactly n orange segments; the i-th child gets the segment with number ai for sure; no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.InputThe first line contains two integers n, k (1 ≀ n, k ≀ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 ≀ ai ≀ nΒ·k), where ai is the number of the orange segment that the i-th child would like to get.It is guaranteed that all numbers ai are distinct.OutputPrint exactly nΒ·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces.You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.ExamplesInput2 24 1Output2 4 1 3 Input3 12Output3 2 1
Input2 24 1
Output2 4 1 3
2 seconds
256 megabytes
['implementation', '*900']
E. Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider an n × n square matrix, consisting of digits one and zero.We'll consider a matrix good, if it meets the following condition: in each row of the matrix all ones go in one group. That is, each row of the matrix looks like that 00...0011...1100...00 (or simply consists of zeroes if it has no ones).You are given matrix a of size n × n, consisting of zeroes and ones. Your task is to determine whether you can get a good matrix b from it by rearranging the columns or not.InputThe first line contains integer n (1 ≀ n ≀ 500) β€” the size of matrix a.Each of n following lines contains n characters "0" and "1" β€” matrix a. Note that the characters are written without separators.OutputPrint "YES" in the first line, if you can rearrange the matrix columns so as to get a good matrix b. In the next n lines print the good matrix b. If there are multiple answers, you are allowed to print any of them.If it is impossible to get a good matrix, print "NO".ExamplesInput6100010110110011001010010000100011001OutputYES011000111100000111001100100000000111Input3110101011OutputNO
Input6100010110110011001010010000100011001
OutputYES011000111100000111001100100000000111
2 seconds
256 megabytes
['data structures', '*3000']
D. Cubestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Petya got a set of wooden cubes as a present from his mom. Petya immediately built a whole city from these cubes.The base of the city is an n × n square, divided into unit squares. The square's sides are parallel to the coordinate axes, the square's opposite corners have coordinates (0, 0) and (n, n). On each of the unit squares Petya built a tower of wooden cubes. The side of a wooden cube also has a unit length.After that Petya went an infinitely large distance away from his masterpiece and looked at it in the direction of vector v = (vx, vy, 0). Petya wonders, how many distinct cubes are visible from this position. Help him, find this number.Each cube includes the border. We think that a cube is visible if there is a ray emanating from some point p, belonging to the cube, in the direction of vector  - v, that doesn't contain any points, belonging to other cubes.InputThe first line contains three integers n, vx and vy (1 ≀ n ≀ 103, |vx|, |vy| ≀ |104|, |vx| + |vy| > 0).Next n lines contain n integers each: the j-th integer in the i-th line aij (0 ≀ aij ≀ 109, 1 ≀ i, j ≀ n) represents the height of the cube tower that stands on the unit square with opposite corners at points (i - 1, j - 1) and (i, j).OutputPrint a single integer β€” the number of visible cubes.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput5 -1 25 0 0 0 10 0 0 0 20 0 0 1 20 0 0 0 22 2 2 2 3Output20Input5 1 -25 0 0 0 10 0 0 0 20 0 0 1 20 0 0 0 22 2 2 2 3Output15
Input5 -1 25 0 0 0 10 0 0 0 20 0 0 1 20 0 0 0 22 2 2 2 3
Output20
5 seconds
256 megabytes
['data structures', 'dp', 'geometry', 'two pointers', '*2700']
C. Colorado Potato Beetletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOld MacDonald has a farm and a large potato field, (1010 + 1) × (1010 + 1) square meters in size. The field is divided into square garden beds, each bed takes up one square meter.Old McDonald knows that the Colorado potato beetle is about to invade his farm and can destroy the entire harvest. To fight the insects, Old McDonald wants to spray some beds with insecticides.So Old McDonald went to the field, stood at the center of the central field bed and sprayed this bed with insecticides. Now he's going to make a series of movements and spray a few more beds. During each movement Old McDonald moves left, right, up or down the field some integer number of meters. As Old McDonald moves, he sprays all the beds he steps on. In other words, the beds that have any intersection at all with Old McDonald's trajectory, are sprayed with insecticides.When Old McDonald finished spraying, he wrote out all his movements on a piece of paper. Now he wants to know how many beds won't be infected after the invasion of the Colorado beetles.It is known that the invasion of the Colorado beetles goes as follows. First some bed on the field border gets infected. Than any bed that hasn't been infected, hasn't been sprayed with insecticides and has a common side with an infected bed, gets infected as well. Help Old McDonald and determine the number of beds that won't be infected by the Colorado potato beetle.InputThe first line contains an integer n (1 ≀ n ≀ 1000) β€” the number of Old McDonald's movements.Next n lines contain the description of Old McDonald's movements. The i-th of these lines describes the i-th movement. Each movement is given in the format "di xi", where di is the character that determines the direction of the movement ("L", "R", "U" or "D" for directions "left", "right", "up" and "down", correspondingly), and xi (1 ≀ xi ≀ 106) is an integer that determines the number of meters in the movement.OutputPrint a single integer β€” the number of beds that won't be infected by the Colorado potato beetle.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.ExamplesInput5R 8U 9L 9D 8L 2Output101Input7R 10D 2L 7U 9D 2R 3D 10Output52
Input5R 8U 9L 9D 8L 2
Output101
2 seconds
256 megabytes
['dfs and similar', 'implementation', '*2200']
B. Hydratime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph.A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges.Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra.InputThe first line contains four integers n, m, h, t (1 ≀ n, m ≀ 105, 1 ≀ h, t ≀ 100) β€” the number of nodes and edges in graph G, and the number of a hydra's heads and tails.Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≀ ai, bi ≀ n, a ≠ b) β€” the numbers of the nodes, connected by the i-th edge.It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n.OutputIf graph G has no hydra, print "NO" (without the quotes).Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers β€” the numbers of nodes u and v. In the third line print h numbers β€” the numbers of the nodes that are the heads. In the fourth line print t numbers β€” the numbers of the nodes that are the tails. All printed numbers should be distinct.If there are multiple possible answers, you are allowed to print any of them.ExamplesInput9 12 2 31 22 31 31 42 54 54 66 56 77 58 79 1OutputYES4 15 6 9 3 2 Input7 10 3 31 22 31 31 42 54 54 66 56 77 5OutputNONoteThe first sample is depicted on the picture below:
Input9 12 2 31 22 31 31 42 54 54 66 56 77 58 79 1
OutputYES4 15 6 9 3 2
2 seconds
256 megabytes
['graphs', 'sortings', '*2000']
A. The Brand New Functiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an.Let's define function f(l, r) (l, r are integer, 1 ≀ l ≀ r ≀ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = alΒ |Β al + 1Β |Β ... Β |Β ar. Polycarpus took a piece of paper and wrote out the values of function f(l, r) for all l, r (l, r are integer, 1 ≀ l ≀ r ≀ n). Now he wants to know, how many distinct values he's got in the end. Help Polycarpus, count the number of distinct values of function f(l, r) for the given sequence a.Expression xΒ |Β y means applying the operation of bitwise OR to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal β€” as "or".InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of elements of sequence a. The second line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 106) β€” the elements of sequence a.OutputPrint a single integer β€” the number of distinct values of function f(l, r) for the given sequence a.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.ExamplesInput31 2 0Output4Input101 2 3 4 5 6 1 2 9 10Output11NoteIn the first test case Polycarpus will have 6 numbers written on the paper: f(1, 1) = 1, f(1, 2) = 3, f(1, 3) = 3, f(2, 2) = 2, f(2, 3) = 2, f(3, 3) = 0. There are exactly 4 distinct numbers among them: 0, 1, 2, 3.
Input31 2 0
Output4
2 seconds
256 megabytes
['bitmasks', '*1600']
E. XOR on Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got an array a, consisting of n integers a1, a2, ..., an. You are allowed to perform two operations on this array: Calculate the sum of current array elements on the segment [l, r], that is, count value al + al + 1 + ... + ar. Apply the xor operation with a given number x to each array element on the segment [l, r], that is, execute . This operation changes exactly r - l + 1 array elements. Expression means applying bitwise xor operation to numbers x and y. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as "^", in Pascal β€” as "xor".You've got a list of m operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 106) β€” the original array.The third line contains integer m (1 ≀ m ≀ 5Β·104) β€” the number of operations with the array. The i-th of the following m lines first contains an integer ti (1 ≀ ti ≀ 2) β€” the type of the i-th query. If ti = 1, then this is the query of the sum, if ti = 2, then this is the query to change array elements. If the i-th operation is of type 1, then next follow two integers li, ri (1 ≀ li ≀ ri ≀ n). If the i-th operation is of type 2, then next follow three integers li, ri, xi (1 ≀ li ≀ ri ≀ n, 1 ≀ xi ≀ 106). The numbers on the lines are separated by single spaces.OutputFor each query of type 1 print in a single line the sum of numbers on the given segment. Print the answers to the queries in the order in which the queries go in the input.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams, or the %I64d specifier.ExamplesInput54 10 3 13 781 2 42 1 3 31 2 41 3 32 2 5 51 1 52 1 2 101 2 3Output262203411Input64 7 4 0 7 352 2 3 81 1 52 3 5 12 4 5 61 2 3Output3828
Input54 10 3 13 781 2 42 1 3 31 2 41 3 32 2 5 51 1 52 1 2 101 2 3
Output262203411
4 seconds
256 megabytes
['bitmasks', 'data structures', '*2000']
D. Disputetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera has n counters numbered from 1 to n. Some of them are connected by wires, and each of the counters has a special button.Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one.Valera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of n integers a1, a2, ..., an. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number i, which has value ai, then Valera loses the dispute, otherwise he wins the dispute.Help Valera to determine on which counters he needs to press a button to win the dispute.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105), that denote the number of counters Valera has and the number of pairs of counters connected by wires.Each of the following m lines contains two space-separated integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi), that mean that counters with numbers ui and vi are connected by a wire. It is guaranteed that each pair of connected counters occurs exactly once in the input.The last line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 105), where ai is the value that Ignat choose for the i-th counter.OutputIf Valera can't win the dispute print in the first line -1.Otherwise, print in the first line integer k (0 ≀ k ≀ n). In the second line print k distinct space-separated integers β€” the numbers of the counters, where Valera should push buttons to win the dispute, in arbitrary order.If there exists multiple answers, you are allowed to print any of them.ExamplesInput5 52 34 11 55 32 11 1 2 0 2Output21 2Input4 21 23 40 0 0 0Output31 3 4
Input5 52 34 11 55 32 11 1 2 0 2
Output21 2
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', '*2100']
C. King's Pathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≀ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.InputThe first line contains four space-separated integers x0, y0, x1, y1 (1 ≀ x0, y0, x1, y1 ≀ 109), denoting the initial and the final positions of the king.The second line contains a single integer n (1 ≀ n ≀ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≀ ri, ai, bi ≀ 109, ai ≀ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily.It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.OutputIf there is no path between the initial and final position along allowed cells, print -1.Otherwise print a single integer β€” the minimum number of moves the king needs to get from the initial position to the final one.ExamplesInput5 7 6 1135 3 86 7 115 2 5Output4Input3 4 3 1033 1 44 5 93 10 10Output6Input1 1 2 1021 1 32 6 10Output-1
Input5 7 6 1135 3 86 7 115 2 5
Output4
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'hashing', 'shortest paths', '*1800']
B. Big Segmenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a ≀ c ≀ d ≀ b. InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li, ri (1 ≀ li ≀ ri ≀ 109) β€” the borders of the i-th segment.It is guaranteed that no two segments coincide.OutputPrint a single integer β€” the number of the segment that covers all other segments in the set. If there's no solution, print -1.The segments are numbered starting from 1 in the order in which they appear in the input.ExamplesInput31 12 23 3Output-1Input61 52 31 107 107 710 10Output3
Input31 12 23 3
Output-1
2 seconds
256 megabytes
['implementation', 'sortings', '*1100']
A. Heads or Tailstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.InputThe single line contains four integers x, y, a, b (1 ≀ a ≀ x ≀ 100, 1 ≀ b ≀ y ≀ 100). The numbers on the line are separated by a space.OutputIn the first line print integer n β€” the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di β€” the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci, di) in the strictly increasing order.Let us remind you that the pair of numbers (p1, q1) is less than the pair of numbers (p2, q2), if p1 < p2, or p1 = p2 and also q1 < q2.ExamplesInput3 2 1 1Output32 13 13 2Input2 4 2 2Output0
Input3 2 1 1
Output32 13 13 2
2 seconds
256 megabytes
['brute force', 'implementation', '*1100']
F. Racetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Old City is a rectangular city represented as an m × n grid of blocks. This city contains many buildings, straight two-way streets and junctions. Each junction and each building is exactly one block. All the streets have width of one block and are either vertical or horizontal. There is a junction on both sides of each street. We call two blocks adjacent if and only if they share a common side. No two blocks of different streets are adjacent and no two junctions are adjacent. There is an annual festival and as a part of it, The Old Peykan follows a special path in the city. This path starts from a block in a street, continues with many junctions and ends in a block of some street. For each street block, we know how much time it takes for the Old Peykan to go from this block to an adjacent block. Also the Old Peykan can go from each junction to its adjacent street blocks in one minute. Of course Old Peykan can't go to building blocks.We know the initial position of the Old Peykan and the sequence of junctions that it passes to reach its destination. After passing all the junctions and reaching the destination, it will stay there forever. Your task is to find out where will the Old Peykan be k minutes after it starts moving. Consider that The Old Peykan always follows the shortest path that passes through the given sequence of junctions and reaches the destination.Note that the Old Peykan may visit some blocks more than once.InputThe first line of input contains three integers m, n and k (3 ≀ m, n ≀ 100, 1 ≀ k ≀ 100000). Next m lines are representing the city's map. Each of them containts n characters, each character is a block: Character "#" represents a building. Digits "1", "2", ..., "9" represent a block of an street and this digit means the number of minutes it takes for the Old Peykan to pass this block. Characters "a", "b", ..., "z" means that this block is a junction and this character is it's name. All the junction names are unique. Consider that all blocks have the coordinates: the j-th in the i-th line have coordinates (i, j) (1 ≀ i ≀ m, 1 ≀ j ≀ n).The (m + 2)th line contains two integers rs and cs (1 ≀ rs ≀ m, 1 ≀ cs ≀ n), string s and another two integers re and ce (1 ≀ re ≀ m, 1 ≀ ce ≀ n). The path starts from block (rs, cs), continues through junctions in the order that is specified by s and will end in block (re, ce). Length of s is between 1 and 1000.It's guaranteed that string s denotes a correct path from the start position to the end position and string s doesn't contain two consecutive equal letters. Also start position (rs, cs) and the end position (re, ce) are street blocks.OutputIn a single line print two integers rf and cf β€” (rf, cf) being the position of the Old Peykan after exactly k minutes.ExamplesInput3 10 12###########z1a1111b###########2 3 ab 2 8Output2 8Input10 3 5####w##1##a##1##1##1##1##b####3 2 abababababababab 6 2Output8 2Input3 10 6###########z1a1311b###########2 3 ab 2 8Output2 7
Input3 10 12###########z1a1111b###########2 3 ab 2 8
Output2 8
2 seconds
256 megabytes
['brute force', 'implementation', '*2300']
E. Flightstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLiLand is a country, consisting of n cities. The cities are numbered from 1 to n. The country is well known because it has a very strange transportation system. There are many one-way flights that make it possible to travel between the cities, but the flights are arranged in a way that once you leave a city you will never be able to return to that city again.Previously each flight took exactly one hour, but recently Lily has become the new manager of transportation system and she wants to change the duration of some flights. Specifically, she wants to change the duration of some flights to exactly 2 hours in such a way that all trips from city 1 to city n take the same time regardless of their path.Your task is to help Lily to change the duration of flights.InputFirst line of the input contains two integer numbers n and m (2 ≀ n ≀ 1000;Β 1 ≀ m ≀ 5000) specifying the number of cities and the number of flights.Each of the next m lines contains two integers ai and bi (1 ≀ ai < bi ≀ n) specifying a one-directional flight from city ai to city bi. It is guaranteed that there exists a way to travel from city number 1 to city number n using the given flights. It is guaranteed that there is no sequence of flights that forms a cyclical path and no two flights are between the same pair of cities.OutputIf it is impossible for Lily to do her task, print "No" (without quotes) on the only line of the output. Otherwise print "Yes" (without quotes) on the first line of output, then print an integer ansi (1 ≀ ansi ≀ 2) to each of the next m lines being the duration of flights in new transportation system. You should print these numbers in the order that flights are given in the input.If there are multiple solutions for the input, output any of them.ExamplesInput3 31 22 31 3OutputYes112Input4 41 22 33 41 4OutputNoInput5 61 22 33 51 44 51 3OutputYes111212
Input3 31 22 31 3
OutputYes112
2 seconds
256 megabytes
['graphs', 'shortest paths', '*2600']
D. Numberstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a sequence of n distinct integers a1, a2, ..., an (1 ≀ ai ≀ n). You want to remove some integers in such a way that the resulting sequence of integers satisfies the following three conditions: the resulting sequence is not empty; the exclusive or (xor operation) of all the integers in the resulting sequence equals 0; if you write all the integers of the resulting sequence (from beginning to the end) in a row in the decimal numeral system and without any spaces, the written number is divisible by p. You are given the sequence of n integers a and a prime number p, find a way to satisfy the described conditions.InputThe first line of the input contains two integers n and p (1 ≀ n, p ≀ 50000). Next line contains n space-separated distinct integers a1, a2, ..., an (1 ≀ ai ≀ n).It is guaranteed that p is a prime number.OutputIf there is no solution for the given input, print "No" (without quotes) in the only line of the output.Otherwise print "Yes" in the first line of output. The second line should contain an integer k (k > 0) specifying the number of remaining elements and the third line should contain k distinct integers x1, x2, ..., xk (1 ≀ xi ≀ n). These integers mean that you should remove all integers from the sequence except integers ax1, ax2, ..., axk to satisfy the described conditions.If there are multiple solutions, any of them will be accepted.ExamplesInput3 31 2 3OutputYes31 2 3 Input3 51 2 3OutputNo
Input3 31 2 3
OutputYes31 2 3
4 seconds
256 megabytes
['*2900']
C. Mirror Boxtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMirror Box is a name of a popular game in the Iranian National Amusement Park (INAP). There is a wooden box, 105 cm long and 100 cm high in this game. Some parts of the box's ceiling and floor are covered by mirrors. There are two negligibly small holes in the opposite sides of the box at heights hl and hr centimeters above the floor. The picture below shows what the box looks like. In the game, you will be given a laser gun to shoot once. The laser beam must enter from one hole and exit from the other one. Each mirror has a preset number vi, which shows the number of points players gain if their laser beam hits that mirror. Also β€” to make things even funnier β€” the beam must not hit any mirror more than once.Given the information about the box, your task is to find the maximum score a player may gain. Please note that the reflection obeys the law "the angle of incidence equals the angle of reflection".InputThe first line of the input contains three space-separated integers hl, hr, n (0 < hl, hr < 100, 0 ≀ n ≀ 100) β€” the heights of the holes and the number of the mirrors.Next n lines contain the descriptions of the mirrors. The i-th line contains space-separated vi, ci, ai, bi; the integer vi (1 ≀ vi ≀ 1000) is the score for the i-th mirror; the character ci denotes i-th mirror's position β€” the mirror is on the ceiling if ci equals "T" and on the floor if ci equals "F"; integers ai and bi (0 ≀ ai < bi ≀ 105) represent the x-coordinates of the beginning and the end of the mirror.No two mirrors will share a common point. Consider that the x coordinate increases in the direction from left to right, so the border with the hole at height hl has the x coordinate equal to 0 and the border with the hole at height hr has the x coordinate equal to 105.OutputThe only line of output should contain a single integer β€” the maximum possible score a player could gain.ExamplesInput50 50 710 F 1 8000020 T 1 8000030 T 81000 8200040 T 83000 8400050 T 85000 8600060 T 87000 8800070 F 81000 89000Output100Input80 72 915 T 8210 1567910 F 11940 2239950 T 30600 4478950 F 32090 365795 F 45520 48519120 F 49250 552298 F 59700 8060935 T 61940 649392 T 92540 97769Output120NoteThe second sample is depicted above. The red beam gets 10 + 50 + 5 + 35 + 8 + 2 = 110 points and the blue one gets 120.The red beam on the picture given in the statement shows how the laser beam can go approximately, this is just illustration how the laser beam can gain score. So for the second sample there is no such beam that gain score 110.
Input50 50 710 F 1 8000020 T 1 8000030 T 81000 8200040 T 83000 8400050 T 85000 8600060 T 87000 8800070 F 81000 89000
Output100
2 seconds
256 megabytes
['geometry', 'implementation', '*2000']
B. Friendstime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n friends and you want to take m pictures of them. Exactly two of your friends should appear in each picture and no two pictures should contain the same pair of your friends. So if you have n = 3 friends you can take 3 different pictures, each containing a pair of your friends.Each of your friends has an attractiveness level which is specified by the integer number ai for the i-th friend. You know that the attractiveness of a picture containing the i-th and the j-th friends is equal to the exclusive-or (xor operation) of integers ai and aj.You want to take pictures in a way that the total sum of attractiveness of your pictures is maximized. You have to calculate this value. Since the result may not fit in a 32-bit integer number, print it modulo 1000000007 (109 + 7).InputThe first line of input contains two integers n and m β€” the number of friends and the number of pictures that you want to take. Next line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 109) β€” the values of attractiveness of the friends.OutputThe only line of output should contain an integer β€” the optimal total sum of attractiveness of your pictures.ExamplesInput3 11 2 3Output3Input3 21 2 3Output5Input3 31 2 3Output6
Input3 11 2 3
Output3
6 seconds
256 megabytes
['binary search', 'bitmasks', 'data structures', 'math', '*2700']
A. Old Peykantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c1, c2, ..., cn. The Old Peykan wants to travel from city c1 to cn using roads. There are (n - 1) one way roads, the i-th road goes from city ci to city ci + 1 and is di kilometers long.The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.Each city ci (except for the last city cn) has a supply of si liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly k hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times. Initially (at time zero) the Old Peykan is at city c1 and s1 liters of fuel is transferred to it's empty tank from c1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.Find the minimum time the Old Peykan needs to reach city cn.InputThe first line of the input contains two space-separated integers m and k (1 ≀ m, k ≀ 1000). The value m specifies the number of roads between cities which is equal to n - 1.The next line contains m space-separated integers d1, d2, ..., dm (1 ≀ di ≀ 1000) and the following line contains m space-separated integers s1, s2, ..., sm (1 ≀ si ≀ 1000).OutputIn the only line of the output print a single integer β€” the minimum time required for The Old Peykan to reach city cn from city c1.ExamplesInput4 61 2 5 22 3 3 4Output10Input2 35 65 5Output14NoteIn the second sample above, the Old Peykan stays in c1 for 3 hours.
Input4 61 2 5 22 3 3 4
Output10
2 seconds
256 megabytes
['greedy', '*1300']
F. TorCodertime limit per test3 secondsmemory limit per test256 megabytesinputinput.txtoutputoutput.txtA boy named Leo doesn't miss a single TorCoder contest round. On the last TorCoder round number 100666 Leo stumbled over the following problem. He was given a string s, consisting of n lowercase English letters, and m queries. Each query is characterised by a pair of integers li, ri (1 ≀ li ≀ ri ≀ n). We'll consider the letters in the string numbered from 1 to n from left to right, that is, s = s1s2... sn. After each query he must swap letters with indexes from li to ri inclusive in string s so as to make substring (li, ri) a palindrome. If there are multiple such letter permutations, you should choose the one where string (li, ri) will be lexicographically minimum. If no such permutation exists, you should ignore the query (that is, not change string s).Everybody knows that on TorCoder rounds input line and array size limits never exceed 60, so Leo solved this problem easily. Your task is to solve the problem on a little bit larger limits. Given string s and m queries, print the string that results after applying all m queries to string s.InputThe first input line contains two integers n and m (1 ≀ n, m ≀ 105) β€” the string length and the number of the queries.The second line contains string s, consisting of n lowercase Latin letters.Each of the next m lines contains a pair of integers li, ri (1 ≀ li ≀ ri ≀ n) β€” a query to apply to the string. OutputIn a single line print the result of applying m queries to string s. Print the queries in the order in which they are given in the input.ExamplesInput7 2aabcbaa1 35 7OutputabacabaInput3 2abc1 22 3OutputabcNoteA substring (li, ri) 1 ≀ li ≀ ri ≀ n) of string s = s1s2... sn of length n is a sequence of characters slisli + 1...sri.A string is a palindrome, if it reads the same from left to right and from right to left.String x1x2... xp is lexicographically smaller than string y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or exists such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1.
Input7 2aabcbaa1 35 7
Outputabacaba
3 seconds
256 megabytes
['data structures', '*2600']
E. Road Repairstime limit per test2 secondsmemory limit per test256 megabytesinputinput.txtoutputoutput.txtA country named Berland has n cities. They are numbered with integers from 1 to n. City with index 1 is the capital of the country. Some pairs of cities have monodirectional roads built between them. However, not all of them are in good condition. For each road we know whether it needs repairing or not. If a road needs repairing, then it is forbidden to use it. However, the Berland government can repair the road so that it can be used.Right now Berland is being threatened by the war with the neighbouring state. So the capital officials decided to send a military squad to each city. The squads can move only along the existing roads, as there's no time or money to build new roads. However, some roads will probably have to be repaired in order to get to some cities.Of course the country needs much resources to defeat the enemy, so you want to be careful with what you're going to throw the forces on. That's why the Berland government wants to repair the minimum number of roads that is enough for the military troops to get to any city from the capital, driving along good or repaired roads. Your task is to help the Berland government and to find out, which roads need to be repaired.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of cities and the number of roads in Berland.Next m lines contain three space-separated integers ai, bi, ci (1 ≀ ai, bi ≀ n, ai ≠ bi, 0 ≀ ci ≀ 1), describing the road from city ai to city bi. If ci equals 0, than the given road is in a good condition. If ci equals 1, then it needs to be repaired.It is guaranteed that there is not more than one road between the cities in each direction.OutputIf even after all roads are repaired, it is still impossible to get to some city from the capital, print  - 1. Otherwise, on the first line print the minimum number of roads that need to be repaired, and on the second line print the numbers of these roads, separated by single spaces.The roads are numbered starting from 1 in the order, in which they are given in the input.If there are multiple sets, consisting of the minimum number of roads to repair to make travelling to any city from the capital possible, print any of them.If it is possible to reach any city, driving along the roads that already are in a good condition, print 0 in the only output line.ExamplesInput3 21 3 03 2 1Output12Input4 42 3 03 4 04 1 04 2 1Output-1Input4 31 2 01 3 01 4 0Output0
Input3 21 3 03 2 1
Output12
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', '*2800']
B. Easy Tape Programmingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. Current character pointer (CP); Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right.We repeat the following steps until the first moment that CP points to somewhere outside the sequence. If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one. If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated.It's obvious the every program in this language terminates after some steps.We have a sequence s1, s2, ..., sn of "<", ">" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence sl, sl + 1, ..., sr as an independent program in this language.InputThe first line of input contains two integers n and q (1 ≀ n, q ≀ 100) β€” represents the length of the sequence s and the number of queries. The second line contains s, a sequence of "<", ">" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces. The next q lines each contains two integers li and ri (1 ≀ li ≀ ri ≀ n) β€” the i-th query.OutputFor each query print 10 space separated integers: x0, x1, ..., x9 where xi equals the number of times the interpreter prints i while running the corresponding program. Print answers to the queries in the order they are given in input.ExamplesInput7 41>3>22<1 34 77 71 7Output0 1 0 1 0 0 0 0 0 0 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 2 1 0 0 0 0 0 0
Input7 41>3>22<1 34 77 71 7
Output0 1 0 1 0 0 0 0 0 0 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 2 1 0 0 0 0 0 0
2 seconds
256 megabytes
['brute force', 'implementation', '*1500']
A. Two Bags of Potatoestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera had two bags of potatoes, the first of these bags contains x (x β‰₯ 1) potatoes, and the second β€” y (y β‰₯ 1) potatoes. Valera β€” very scattered boy, so the first bag of potatoes (it contains x potatoes) Valera lost. Valera remembers that the total amount of potatoes (x + y) in the two bags, firstly, was not gerater than n, and, secondly, was divisible by k.Help Valera to determine how many potatoes could be in the first bag. Print all such possible numbers in ascending order.InputThe first line of input contains three integers y, k, n (1 ≀ y, k, n ≀ 109;  ≀ 105).OutputPrint the list of whitespace-separated integers β€” all possible values of x in ascending order. You should print each possible value of x exactly once.If there are no such values of x print a single integer -1.ExamplesInput10 1 10Output-1Input10 6 40Output2 8 14 20 26
Input10 1 10
Output-1
1 second
256 megabytes
['greedy', 'implementation', 'math', '*1200']
E. Meeting Hertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUrpal lives in a big city. He has planned to meet his lover tonight. The city has n junctions numbered from 1 to n. The junctions are connected by m directed streets, all the roads have equal length. Urpal lives in junction a and the date is planned in a restaurant in junction b. He wants to use public transportation to get to junction b. There are k bus transportation companies. At the beginning of every second, a bus from the i-th company chooses a random shortest path between junction si and junction ti and passes through it. There might be no path from si to ti. In that case no bus will leave from si to ti. If a bus passes through a junction where Urpal stands, he can get on the bus. He can also get off the bus at any junction along the path. Now Urpal wants to know if it's possible to go to the date using public transportation in a finite amount of time (the time of travel is the sum of length of the traveled roads) and what is the minimum number of buses he should take in the worst case.At any moment Urpal knows only his own position and the place where the date will be. When he gets on the bus he knows only the index of the company of this bus. Of course Urpal knows the city map and the the pairs (si, ti) for each company.Note that Urpal doesn't know buses velocity. InputThe first line of the input contains four integers n, m, a, b (2 ≀ n ≀ 100;Β 0 ≀ m ≀ nΒ·(n - 1);Β 1 ≀ a, b ≀ n;Β a ≠ b). The next m lines contain two integers each ui and vi (1 ≀ ui, vi ≀ n;Β ui ≠ vi) describing a directed road from junction ui to junction vi. All roads in the input will be distinct. The next line contains an integer k (0 ≀ k ≀ 100). There will be k lines after this, each containing two integers si and ti (1 ≀ si, ti ≀ n;Β si ≠ ti) saying there is a bus route starting at si and ending at ti. Please note that there might be no path from si to ti, this case is described in the problem statement.OutputIn the only line of output print the minimum number of buses Urpal should get on on his way in the worst case. If it's not possible to reach the destination in the worst case print -1.ExamplesInput7 8 1 71 21 32 43 44 64 56 75 732 71 45 7Output2Input4 4 1 21 21 32 43 411 4Output-1
Input7 8 1 71 21 32 43 44 64 56 75 732 71 45 7
Output2
2 seconds
256 megabytes
['dp', 'graphs', 'shortest paths', '*2600']
D. Tape Programmingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. Current character pointer (CP); Direction pointer (DP) which can point left or right; Initially CP points to the leftmost character of the sequence and DP points to the right.We repeat the following steps until the first moment that CP points to somewhere outside the sequence. If CP is pointing to a digit the interpreter prints that digit then CP moves one step according to the direction of DP. After that the value of the printed digit in the sequence decreases by one. If the printed digit was 0 then it cannot be decreased therefore it's erased from the sequence and the length of the sequence decreases by one. If CP is pointing to "<" or ">" then the direction of DP changes to "left" or "right" correspondingly. Then CP moves one step according to DP. If the new character that CP is pointing to is "<" or ">" then the previous character will be erased from the sequence. If at any moment the CP goes outside of the sequence the execution is terminated.It's obvious the every program in this language terminates after some steps.We have a sequence s1, s2, ..., sn of "<", ">" and digits. You should answer q queries. Each query gives you l and r and asks how many of each digit will be printed if we run the sequence sl, sl + 1, ..., sr as an independent program in this language.InputThe first line of input contains two integers n and q (1 ≀ n, q ≀ 105) β€” represents the length of the sequence s and the number of queries. The second line contains s, a sequence of "<", ">" and digits (0..9) written from left to right. Note, that the characters of s are not separated with spaces. The next q lines each contains two integers li and ri (1 ≀ li ≀ ri ≀ n) β€” the i-th query.OutputFor each query print 10 space separated integers: x0, x1, ..., x9 where xi equals the number of times the interpreter prints i while running the corresponding program. Print answers to the queries in the order they are given in input.ExamplesInput7 41>3>22<1 34 77 71 7Output0 1 0 1 0 0 0 0 0 02 2 2 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 02 3 2 1 0 0 0 0 0 0
Input7 41>3>22<1 34 77 71 7
Output0 1 0 1 0 0 0 0 0 02 2 2 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 02 3 2 1 0 0 0 0 0 0
2 seconds
256 megabytes
['data structures', 'implementation', '*2900']
C. World Eater Brotherstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou must have heard of the two brothers dreaming of ruling the world. With all their previous plans failed, this time they decided to cooperate with each other in order to rule the world. As you know there are n countries in the world. These countries are connected by n - 1 directed roads. If you don't consider direction of the roads there is a unique path between every pair of countries in the world, passing through each road at most once. Each of the brothers wants to establish his reign in some country, then it's possible for him to control the countries that can be reached from his country using directed roads. The brothers can rule the world if there exists at most two countries for brothers to choose (and establish their reign in these countries) so that any other country is under control of at least one of them. In order to make this possible they want to change the direction of minimum number of roads. Your task is to calculate this minimum number of roads.InputThe first line of input contains an integer n (1 ≀ n ≀ 3000). Each of the next n - 1 lines contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n;Β ai ≠ bi) saying there is a road from country ai to country bi.Consider that countries are numbered from 1 to n. It's guaranteed that if you don't consider direction of the roads there is a unique path between every pair of countries in the world, passing through each road at most once.OutputIn the only line of output print the minimum number of roads that their direction should be changed so that the brothers will be able to rule the world.ExamplesInput42 13 14 1Output1Input52 12 34 34 5Output0
Input42 13 14 1
Output1
2 seconds
256 megabytes
['dfs and similar', 'dp', 'greedy', 'trees', '*2100']
B. Boring Partitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is the most boring one you've ever seen. Given a sequence of integers a1, a2, ..., an and a non-negative integer h, our goal is to partition the sequence into two subsequences (not necessarily consist of continuous elements). Each element of the original sequence should be contained in exactly one of the result subsequences. Note, that one of the result subsequences can be empty.Let's define function f(ai, aj) on pairs of distinct elements (that is i ≠ j) in the original sequence. If ai and aj are in the same subsequence in the current partition then f(ai, aj) = ai + aj otherwise f(ai, aj) = ai + aj + h. Consider all possible values of the function f for some partition. We'll call the goodness of this partiotion the difference between the maximum value of function f and the minimum value of function f.Your task is to find a partition of the given sequence a that have the minimal possible goodness among all possible partitions.InputThe first line of input contains integers n and h (2 ≀ n ≀ 105, 0 ≀ h ≀ 108). In the second line there is a list of n space-separated integers representing a1, a2, ..., an (0 ≀ ai ≀ 108).OutputThe first line of output should contain the required minimum goodness. The second line describes the optimal partition. You should print n whitespace-separated integers in the second line. The i-th integer is 1 if ai is in the first subsequence otherwise it should be 2.If there are several possible correct answers you are allowed to print any of them.ExamplesInput3 21 2 3Output11 2 2 Input5 100 1 0 2 1Output32 2 2 2 2 NoteIn the first sample the values of f are as follows: f(1, 2) = 1 + 2 + 2 = 5, f(1, 3) = 1 + 3 + 2 = 6 and f(2, 3) = 2 + 3 = 5. So the difference between maximum and minimum values of f is 1.In the second sample the value of h is large, so it's better for one of the sub-sequences to be empty.
Input3 21 2 3
Output11 2 2
2 seconds
256 megabytes
['constructive algorithms', '*1800']
A. Not Wool Sequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of non-negative integers a1, a2, ..., an of length n is called a wool sequence if and only if there exists two integers l and r (1 ≀ l ≀ r ≀ n) such that . In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0.The expression means applying the operation of a bitwise xor to numbers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is marked as "^", in Pascal β€” as "xor".In this problem you are asked to compute the number of sequences made of n integers from 0 to 2m - 1 that are not a wool sequence. You should print this number modulo 1000000009 (109 + 9).InputThe only line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 105).OutputPrint the required number of sequences modulo 1000000009 (109 + 9) on the only line of output.ExamplesInput3 2Output6NoteSequences of length 3 made of integers 0, 1, 2 and 3 that are not a wool sequence are (1, 3, 1), (1, 2, 1), (2, 1, 2), (2, 3, 2), (3, 1, 3) and (3, 2, 3).
Input3 2
Output6
1 second
256 megabytes
['constructive algorithms', 'math', '*1300']
E. Build Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou desperately need to build some string t. For that you've got n more strings s1, s2, ..., sn. To build string t, you are allowed to perform exactly |t| (|t| is the length of string t) operations on these strings. Each operation looks like that: choose any non-empty string from strings s1, s2, ..., sn; choose an arbitrary character from the chosen string and write it on a piece of paper; remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings s1, s2, ..., sn decreases by 1. We are assumed to build string t, if the characters, written on the piece of paper, in the order of performed operations form string t.There are other limitations, though. For each string si you know number ai β€” the maximum number of characters you are allowed to delete from string si. You also know that each operation that results in deleting a character from string si, costs i rubles. That is, an operation on string s1 is the cheapest (it costs 1 ruble), and the operation on string sn is the most expensive one (it costs n rubles).Your task is to count the minimum amount of money (in rubles) you will need to build string t by the given rules. Consider the cost of building string t to be the sum of prices of the operations you use.InputThe first line of the input contains string t β€” the string that you need to build.The second line contains a single integer n (1 ≀ n ≀ 100) β€” the number of strings to which you are allowed to apply the described operation. Each of the next n lines contains a string and an integer. The i-th line contains space-separated string si and integer ai (0 ≀ ai ≀ 100). Number ai represents the maximum number of characters that can be deleted from string si.All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.OutputPrint a single number β€” the minimum money (in rubles) you need in order to build string t. If there is no solution, print -1.ExamplesInputbbaze3bzb 2aeb 3ba 10Output8Inputabacaba4aba 2bcc 1caa 2bbb 5Output18Inputxyz4axx 8za 1efg 4t 1Output-1NoteNotes to the samples:In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" ΠΈ "b" with price 2 rubles. The price of the string t in this case is 2Β·1 + 3Β·2 = 8.In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string t in this case is 2Β·1 + 1Β·2 + 2Β·3 + 2Β·4 = 18.In the third sample the solution doesn't exist because there is no character "y" in given strings.
Inputbbaze3bzb 2aeb 3ba 10
Output8
2 seconds
256 megabytes
['flows', 'graphs', '*2000']
D. T-decompositiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a undirected tree s, consisting of n nodes. Your task is to build an optimal T-decomposition for it. Let's define a T-decomposition as follows.Let's denote the set of all nodes s as v. Let's consider an undirected tree t, whose nodes are some non-empty subsets of v, we'll call them xi . The tree t is a T-decomposition of s, if the following conditions holds: the union of all xi equals v; for any edge (a, b) of tree s exists the tree node t, containing both a and b; if the nodes of the tree t xi and xj contain the node a of the tree s, then all nodes of the tree t, lying on the path from xi to xj also contain node a. So this condition is equivalent to the following: all nodes of the tree t, that contain node a of the tree s, form a connected subtree of tree t. There are obviously many distinct trees t, that are T-decompositions of the tree s. For example, a T-decomposition is a tree that consists of a single node, equal to set v.Let's define the cardinality of node xi as the number of nodes in tree s, containing in the node. Let's choose the node with the maximum cardinality in t. Let's assume that its cardinality equals w. Then the weight of T-decomposition t is value w. The optimal T-decomposition is the one with the minimum weight.Your task is to find the optimal T-decomposition of the given tree s that has the minimum number of nodes.InputThe first line contains a single integer n (2 ≀ n ≀ 105), that denotes the number of nodes in tree s.Each of the following n - 1 lines contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n;Β ai ≠ bi), denoting that the nodes of tree s with indices ai and bi are connected by an edge.Consider the nodes of tree s indexed from 1 to n. It is guaranteed that s is a tree.OutputIn the first line print a single integer m that denotes the number of nodes in the required T-decomposition.Then print m lines, containing descriptions of the T-decomposition nodes. In the i-th (1 ≀ i ≀ m) of them print the description of node xi of the T-decomposition. The description of each node xi should start from an integer ki, that represents the number of nodes of the initial tree s, that are contained in the node xi. Then you should print ki distinct space-separated integers β€” the numbers of nodes from s, contained in xi, in arbitrary order.Then print m - 1 lines, each consisting two integers pi, qi (1 ≀ pi, qi ≀ m;Β pi ≠ qi). The pair of integers pi, qi means there is an edge between nodes xpi and xqi of T-decomposition.The printed T-decomposition should be the optimal T-decomposition for the given tree s and have the minimum possible number of nodes among all optimal T-decompositions. If there are multiple optimal T-decompositions with the minimum number of nodes, print any of them.ExamplesInput21 2Output12 1 2Input31 22 3Output22 1 22 2 31 2Input42 13 14 1Output32 2 12 3 12 4 11 22 3
Input21 2
Output12 1 2
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', 'trees', '*2000']
C. Primes on Intervaltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors.Consider positive integers a, a + 1, ..., b (a ≀ b). You want to find the minimum integer l (1 ≀ l ≀ b - a + 1) such that for any integer x (a ≀ x ≀ b - l + 1) among l integers x, x + 1, ..., x + l - 1 there are at least k prime numbers. Find and print the required minimum l. If no value l meets the described limitations, print -1.InputA single line contains three space-separated integers a, b, k (1 ≀ a, b, k ≀ 106;Β a ≀ b).OutputIn a single line print a single integer β€” the required minimum l. If there's no solution, print -1.ExamplesInput2 4 2Output3Input6 13 1Output4Input1 4 3Output-1
Input2 4 2
Output3
1 second
256 megabytes
['binary search', 'number theory', 'two pointers', '*1600']
B. Young Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got table a, consisting of n rows, numbered from 1 to n. The i-th line of table a contains ci cells, at that for all i (1 < i ≀ n) holds ci ≀ ci - 1. Let's denote s as the total number of cells of table a, that is, . We know that each cell of the table contains a single integer from 1 to s, at that all written integers are distinct. Let's assume that the cells of the i-th row of table a are numbered from 1 to ci, then let's denote the number written in the j-th cell of the i-th row as ai, j. Your task is to perform several swap operations to rearrange the numbers in the table so as to fulfill the following conditions: for all i, j (1 < i ≀ n;Β 1 ≀ j ≀ ci) holds ai, j > ai - 1, j; for all i, j (1 ≀ i ≀ n;Β 1 < j ≀ ci) holds ai, j > ai, j - 1. In one swap operation you are allowed to choose two different cells of the table and swap the recorded there numbers, that is the number that was recorded in the first of the selected cells before the swap, is written in the second cell after it. Similarly, the number that was recorded in the second of the selected cells, is written in the first cell after the swap.Rearrange the numbers in the required manner. Note that you are allowed to perform any number of operations, but not more than s. You do not have to minimize the number of operations.InputThe first line contains a single integer n (1 ≀ n ≀ 50) that shows the number of rows in the table. The second line contains n space-separated integers ci (1 ≀ ci ≀ 50;Β ci ≀ ci - 1) β€” the numbers of cells on the corresponding rows.Next n lines contain table Π°. The i-th of them contains ci space-separated integers: the j-th integer in this line represents ai, j.It is guaranteed that all the given numbers ai, j are positive and do not exceed s. It is guaranteed that all ai, j are distinct.OutputIn the first line print a single integer m (0 ≀ m ≀ s), representing the number of performed swaps.In the next m lines print the description of these swap operations. In the i-th line print four space-separated integers xi, yi, pi, qi (1 ≀ xi, pi ≀ n;Β 1 ≀ yi ≀ cxi;Β 1 ≀ qi ≀ cpi). The printed numbers denote swapping the contents of cells axi, yi and api, qi. Note that a swap operation can change the contents of distinct table cells. Print the swaps in the order, in which they should be executed.ExamplesInput33 2 14 3 56 12Output21 1 2 22 1 3 1Input144 3 2 1Output21 1 1 41 2 1 3
Input33 2 14 3 56 12
Output21 1 2 22 1 3 1
2 seconds
256 megabytes
['implementation', 'sortings', '*1500']
A. Free Cashtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately. Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe. Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.InputThe first line contains a single integer n (1 ≀ n ≀ 105), that is the number of cafe visitors.Each of the following n lines has two space-separated integers hi and mi (0 ≀ hi ≀ 23;Β 0 ≀ mi ≀ 59), representing the time when the i-th person comes into the cafe. Note that the time is given in the chronological order. All time is given within one 24-hour period.OutputPrint a single integer β€” the minimum number of cashes, needed to serve all clients next day.ExamplesInput48 08 108 108 45Output2Input30 1210 1122 22Output1NoteIn the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.In the second sample all visitors will come in different times, so it will be enough one cash.
Input48 08 108 108 45
Output2
2 seconds
256 megabytes
['implementation', '*1000']
B. Easy Number Challengetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum:Find the sum modulo 1073741824 (230).InputThe first line contains three space-separated integers a, b and c (1 ≀ a, b, c ≀ 100).OutputPrint a single integer β€” the required sum modulo 1073741824 (230).ExamplesInput2 2 2Output20Input5 6 7Output1520NoteFor the first example. d(1Β·1Β·1) = d(1) = 1; d(1Β·1Β·2) = d(2) = 2; d(1Β·2Β·1) = d(2) = 2; d(1Β·2Β·2) = d(4) = 3; d(2Β·1Β·1) = d(2) = 2; d(2Β·1Β·2) = d(4) = 3; d(2Β·2Β·1) = d(4) = 3; d(2Β·2Β·2) = d(8) = 4. So the result is 1 + 2 + 2 + 3 + 2 + 3 + 3 + 4 = 20.
Input2 2 2
Output20
2 seconds
256 megabytes
['implementation', 'number theory', '*1300']
A. Boy or Girltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThose days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. But yesterday, he came to see "her" in the real world and found out "she" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.This is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.InputThe first line contains a non-empty string, that contains only lowercase English letters β€” the user name. This string contains at most 100 letters.OutputIf it is a female by our hero's method, print "CHAT WITH HER!" (without the quotes), otherwise, print "IGNORE HIM!" (without the quotes).ExamplesInputwjmzbmrOutputCHAT WITH HER!InputxiaodaoOutputIGNORE HIM!InputsevenkplusOutputCHAT WITH HER!NoteFor the first example. There are 6 distinct characters in "wjmzbmr". These characters are: "w", "j", "m", "z", "b", "r". So wjmzbmr is a female and you should print "CHAT WITH HER!".
Inputwjmzbmr
OutputCHAT WITH HER!
1 second
256 megabytes
['brute force', 'implementation', 'strings', '*800']
E. Number Challengetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum:Find the sum modulo 1073741824 (230).InputThe first line contains three space-separated integers a, b and c (1 ≀ a, b, c ≀ 2000).OutputPrint a single integer β€” the required sum modulo 1073741824 (230).ExamplesInput2 2 2Output20Input4 4 4Output328Input10 10 10Output11536NoteFor the first example. d(1Β·1Β·1) = d(1) = 1; d(1Β·1Β·2) = d(2) = 2; d(1Β·2Β·1) = d(2) = 2; d(1Β·2Β·2) = d(4) = 3; d(2Β·1Β·1) = d(2) = 2; d(2Β·1Β·2) = d(4) = 3; d(2Β·2Β·1) = d(4) = 3; d(2Β·2Β·2) = d(8) = 4. So the result is 1 + 2 + 2 + 3 + 2 + 3 + 3 + 4 = 20.
Input2 2 2
Output20
3 seconds
512 megabytes
['combinatorics', 'dp', 'implementation', 'math', 'number theory', '*2600']
D. Graph Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn computer science, there is a method called "Divide And Conquer By Node" to solve some hard problems about paths on a tree. Let's desribe how this method works by function:solve(t) (t is a tree): Chose a node x (it's common to chose weight-center) in tree t. Let's call this step "Line A". Deal with all paths that pass x. Then delete x from tree t. After that t becomes some subtrees. Apply solve on each subtree. This ends when t has only one node because after deleting it, there's nothing. Now, WJMZBMR has mistakenly believed that it's ok to chose any node in "Line A". So he'll chose a node at random. To make the situation worse, he thinks a "tree" should have the same number of edges and nodes! So this procedure becomes like that.Let's define the variable totalCost. Initially the value of totalCost equal to 0. So, solve(t) (now t is a graph): totalCost = totalCost + (sizeΒ ofΒ t). The operation "=" means assignment. (SizeΒ ofΒ t) means the number of nodes in t. Choose a node x in graph t at random (uniformly among all nodes of t). Then delete x from graph t. After that t becomes some connected components. Apply solve on each component. He'll apply solve on a connected graph with n nodes and n edges. He thinks it will work quickly, but it's very slow. So he wants to know the expectation of totalCost of this procedure. Can you help him?InputThe first line contains an integer n (3 ≀ n ≀ 3000) β€” the number of nodes and edges in the graph. Each of the next n lines contains two space-separated integers ai, bi (0 ≀ ai, bi ≀ n - 1) indicating an edge between nodes ai and bi.Consider that the graph nodes are numbered from 0 to (n - 1). It's guaranteed that there are no self-loops, no multiple edges in that graph. It's guaranteed that the graph is connected.OutputPrint a single real number β€” the expectation of totalCost. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.ExamplesInput53 42 32 40 41 2Output13.166666666666666Input30 11 20 2Output6.000000000000000Input50 11 22 03 04 1Output13.166666666666666NoteConsider the second example. No matter what we choose first, the totalCost will always be 3 + 2 + 1 = 6.
Input53 42 32 40 41 2
Output13.166666666666666
2 seconds
256 megabytes
['graphs', '*3000']
C. Cyclical Questtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSome days ago, WJMZBMR learned how to answer the query "how many times does a string x occur in a string s" quickly by preprocessing the string s. But now he wants to make it harder.So he wants to ask "how many consecutive substrings of s are cyclical isomorphic to a given string x". You are given string s and n strings xi, for each string xi find, how many consecutive substrings of s are cyclical isomorphic to xi.Two strings are called cyclical isomorphic if one can rotate one string to get the other one. 'Rotate' here means 'to take some consecutive chars (maybe none) from the beginning of a string and put them back at the end of the string in the same order'. For example, string "abcde" can be rotated to string "deabc". We can take characters "abc" from the beginning and put them at the end of "de".InputThe first line contains a non-empty string s. The length of string s is not greater than 106 characters.The second line contains an integer n (1 ≀ n ≀ 105) β€” the number of queries. Then n lines follow: the i-th line contains the string xi β€” the string for the i-th query. The total length of xi is less than or equal to 106 characters.In this problem, strings only consist of lowercase English letters.OutputFor each query xi print a single integer that shows how many consecutive substrings of s are cyclical isomorphic to xi. Print the answers to the queries in the order they are given in the input.ExamplesInputbaabaabaaa5ababaaaabaaaabaOutput75735Inputaabbaa3aaaabbabbaOutput233
Inputbaabaabaaa5ababaaaabaaaaba
Output75735
3 seconds
512 megabytes
['data structures', 'string suffix structures', 'strings', '*2700']
B. Let's Play Osu!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're playing a game called Osu! Here's a simplified version of it. There are n clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of n characters "O" and "X".Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be 22 + 32 + 22 = 17. If there are no correct clicks in a play then the score for the play equals to 0.You know that the probability to click the i-th (1 ≀ i ≀ n) click correctly is pi. In other words, the i-th character in the play sequence has pi probability to be "O", 1 - pi to be "X". You task is to calculate the expected score for your play.InputThe first line contains an integer n (1 ≀ n ≀ 105) β€” the number of clicks. The second line contains n space-separated real numbers p1, p2, ..., pn (0 ≀ pi ≀ 1).There will be at most six digits after the decimal point in the given pi.OutputPrint a single real number β€” the expected score for your play. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.ExamplesInput30.5 0.5 0.5Output2.750000000000000Input40.7 0.2 0.1 0.9Output2.489200000000000Input51 1 1 1 1Output25.000000000000000NoteFor the first example. There are 8 possible outcomes. Each has a probability of 0.125. "OOO"  →  32 = 9; "OOX"  →  22 = 4; "OXO"  →  12 + 12 = 2; "OXX"  →  12 = 1; "XOO"  →  22 = 4; "XOX"  →  12 = 1; "XXO"  →  12 = 1; "XXX"  →  0. So the expected score is
Input30.5 0.5 0.5
Output2.750000000000000
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*2000']
A. LCM Challengetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than n. Can you help me to find the maximum possible least common multiple of these three integers?InputThe first line contains an integer n (1 ≀ n ≀ 106) β€” the n mentioned in the statement.OutputPrint a single integer β€” the maximum possible LCM of three not necessarily distinct positive integers that are not greater than n.ExamplesInput9Output504Input7Output210NoteThe least common multiple of some positive integers is the least positive integer which is multiple for each of them.The result may become very large, 32-bit integer won't be enough. So using 64-bit integers is recommended.For the last example, we can chose numbers 7, 6, 5 and the LCM of them is 7Β·6Β·5 = 210. It is the maximum value we can get.
Input9
Output504
2 seconds
256 megabytes
['number theory', '*1600']
H. Merging Two Deckstime limit per test2 secondsmemory limit per test256 megabytesinputinput.txtoutputoutput.txtThere are two decks of cards lying on the table in front of you, some cards in these decks lay face up, some of them lay face down. You want to merge them into one deck in which each card is face down. You're going to do it in two stages.The first stage is to merge the two decks in such a way that the relative order of the cards from the same deck doesn't change. That is, for any two different cards i and j in one deck, if card i lies above card j, then after the merge card i must also be above card j.The second stage is performed on the deck that resulted from the first stage. At this stage, the executed operation is the turning operation. In one turn you can take a few of the top cards, turn all of them, and put them back. Thus, each of the taken cards gets turned and the order of these cards is reversed. That is, the card that was on the bottom before the turn, will be on top after it.Your task is to make sure that all the cards are lying face down. Find such an order of merging cards in the first stage and the sequence of turning operations in the second stage, that make all the cards lie face down, and the number of turns is minimum.InputThe first input line contains a single integer n β€” the number of cards in the first deck (1 ≀ n ≀ 105).The second input line contains n integers, separated by single spaces a1, a2, ..., an (0 ≀ ai ≀ 1). Value ai equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost one to the bottommost one.The third input line contains integer m β€” the number of cards in the second deck (1 ≀ m ≀ 105).The fourth input line contains m integers, separated by single spaces b1, b2, ..., bm (0 ≀ bi ≀ 1). Value bi equals 0, if the i-th card is lying face down, and 1, if the card is lying face up. The cards are given in the order from the topmost to the bottommost.OutputIn the first line print n + m space-separated integers β€” the numbers of the cards in the order, in which they will lie after the first stage. List the cards from top to bottom. The cards from the first deck should match their indexes from 1 to n in the order from top to bottom. The cards from the second deck should match their indexes, increased by n, that is, numbers from n + 1 to n + m in the order from top to bottom.In the second line print a single integer x β€” the minimum number of turn operations you need to make all cards in the deck lie face down. In the third line print x integers: c1, c2, ..., cx (1 ≀ ci ≀ n + m), each of them represents the number of cards to take from the top of the deck to perform a turn operation. Print the operations in the order, in which they should be performed. If there are multiple optimal solutions, print any of them. It is guaranteed that the minimum number of operations doesn't exceed 6Β·105. ExamplesInput31 0 141 1 1 1Output1 4 5 6 7 2 335 6 7Input51 1 1 1 150 1 0 1 0Output6 1 2 3 4 5 7 8 9 1041 7 8 9
Input31 0 141 1 1 1
Output1 4 5 6 7 2 335 6 7
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*2000']
G. Practicetime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtLittle time is left before Berland annual football championship. Therefore the coach of team "Losewille Rangers" decided to resume the practice, that were indefinitely interrupted for uncertain reasons. Overall there are n players in "Losewille Rangers". Each player on the team has a number β€” a unique integer from 1 to n. To prepare for the championship, the coach Mr. Floppe decided to spend some number of practices.Mr. Floppe spent some long nights of his holiday planning how to conduct the practices. He came to a very complex practice system. Each practice consists of one game, all n players of the team take part in the game. The players are sorted into two teams in some way. In this case, the teams may have different numbers of players, but each team must have at least one player.The coach wants to be sure that after the series of the practice sessions each pair of players had at least one practice, when they played in different teams. As the players' energy is limited, the coach wants to achieve the goal in the least number of practices.Help him to schedule the practices.InputA single input line contains integer n (2 ≀ n ≀ 1000).OutputIn the first line print m β€” the minimum number of practices the coach will have to schedule. Then print the descriptions of the practices in m lines.In the i-th of those lines print fi β€” the number of players in the first team during the i-th practice (1 ≀ fi < n), and fi numbers from 1 to n β€” the numbers of players in the first team. The rest of the players will play in the second team during this practice. Separate numbers on a line with spaces. Print the numbers of the players in any order. If there are multiple optimal solutions, print any of them.ExamplesInput2Output11 1Input3Output22 1 21 1
Input2
Output11 1
1 second
256 megabytes
['constructive algorithms', 'divide and conquer', 'implementation', '*1600']
F. Fencetime limit per test2 secondsmemory limit per test256 megabytesinputinput.txtoutputoutput.txtVasya should paint a fence in front of his own cottage. The fence is a sequence of n wooden boards arranged in a single row. Each board is a 1 centimeter wide rectangle. Let's number the board fence using numbers 1, 2, ..., n from left to right. The height of the i-th board is hi centimeters.Vasya has a 1 centimeter wide brush and the paint of two colors, red and green. Of course, the amount of the paint is limited. Vasya counted the area he can paint each of the colors. It turned out that he can not paint over a square centimeters of the fence red, and he can not paint over b square centimeters green. Each board of the fence should be painted exactly one of the two colors. Perhaps Vasya won't need one of the colors.In addition, Vasya wants his fence to look smart. To do this, he should paint the fence so as to minimize the value that Vasya called the fence unattractiveness value. Vasya believes that two consecutive fence boards, painted different colors, look unattractive. The unattractiveness value of a fence is the total length of contact between the neighboring boards of various colors. To make the fence look nice, you need to minimize the value as low as possible. Your task is to find what is the minimum unattractiveness Vasya can get, if he paints his fence completely. The picture shows the fence, where the heights of boards (from left to right) are 2,3,2,4,3,1. The first and the fifth boards are painted red, the others are painted green. The first and the second boards have contact length 2, the fourth and fifth boards have contact length 3, the fifth and the sixth have contact length 1. Therefore, the unattractiveness of the given painted fence is 2+3+1=6.InputThe first line contains a single integer n (1 ≀ n ≀ 200) β€” the number of boards in Vasya's fence.The second line contains two integers a and b (0 ≀ a, b ≀ 4Β·104) β€” the area that can be painted red and the area that can be painted green, correspondingly.The third line contains a sequence of n integers h1, h2, ..., hn (1 ≀ hi ≀ 200) β€” the heights of the fence boards.All numbers in the lines are separated by single spaces.OutputPrint a single number β€” the minimum unattractiveness value Vasya can get if he paints his fence completely. If it is impossible to do, print  - 1.ExamplesInput45 73 3 4 1Output3Input32 31 3 1Output2Input33 32 2 2Output-1
Input45 73 3 4 1
Output3
2 seconds
256 megabytes
['dp', '*1800']
E. Champions' Leaguetime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtIn the autumn of this year, two Russian teams came into the group stage of the most prestigious football club competition in the world β€” the UEFA Champions League. Now, these teams have already started to play in the group stage and are fighting for advancing to the playoffs. In this problem we are interested in the draw stage, the process of sorting teams into groups.The process of the draw goes as follows (the rules that are described in this problem, are somehow simplified compared to the real life). Suppose n teams will take part in the group stage (n is divisible by four). The teams should be divided into groups of four. Let's denote the number of groups as m (). Each team has a rating β€” an integer characterizing the team's previous achievements. The teams are sorted by the rating's decreasing (no two teams have the same rating).After that four "baskets" are formed, each of which will contain m teams: the first m teams with the highest rating go to the first basket, the following m teams go to the second one, and so on.Then the following procedure repeats m - 1 times. A team is randomly taken from each basket, first from the first basket, then from the second, then from the third, and at last, from the fourth. The taken teams form another group. After that, they are removed from their baskets.The four teams remaining in the baskets after (m - 1) such procedures are performed, form the last group.In the real draw the random selection of teams from the basket is performed by people β€” as a rule, the well-known players of the past. As we have none, we will use a random number generator, which is constructed as follows. Its parameters are four positive integers x, a, b, c. Every time there is a call to the random number generator, it produces the following actions: calculates ; replaces parameter x by value y (assigns ); returns x as another random number. Operation means taking the remainder after division: , .A random number generator will be used in the draw as follows: each time we need to randomly choose a team from the basket, it will generate a random number k. The teams that yet remain in the basket are considered numbered with consecutive integers from 0 to s - 1, in the order of decreasing rating, where s is the current size of the basket. Then a team number is taken from the basket.Given a list of teams and the parameters of the random number generator, determine the result of the draw. InputThe first input line contains integer n (4 ≀ n ≀ 64, n is divisible by four) β€” the number of teams that take part in the sorting. The second line contains four space-separated integers x, a, b, c (1 ≀ x, a, b, c ≀ 1000) β€” the parameters of the random number generator. Each of the following n lines describes one team. The description consists of the name of the team and its rating, separated by a single space. The name of a team consists of uppercase and lowercase English letters and has length from 1 to 20 characters. A team's rating is an integer from 0 to 1000. All teams' names are distinct. All team's ratings are also distinct.OutputPrint the way the teams must be sorted into groups. Print the groups in the order, in which they are formed in the sorting. Number the groups by consecutive uppercase English letters, starting from letter 'A'. Inside each group print the teams' names one per line, in the order of decreasing of the teams' rating. See samples for a better understanding of the output format.ExamplesInput81 3 1 7Barcelona 158Milan 90Spartak 46Anderlecht 48Celtic 32Benfica 87Zenit 79Malaga 16OutputGroup A:BarcelonaBenficaSpartakCelticGroup B:MilanZenitAnderlechtMalagaNoteIn the given sample the random number generator will be executed four times: , , , .
Input81 3 1 7Barcelona 158Milan 90Spartak 46Anderlecht 48Celtic 32Benfica 87Zenit 79Malaga 16
OutputGroup A:BarcelonaBenficaSpartakCelticGroup B:MilanZenitAnderlechtMalaga
1 second
256 megabytes
['implementation', '*1600']
D. Cinematime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtOverall there are m actors in Berland. Each actor has a personal identifier β€” an integer from 1 to m (distinct actors have distinct identifiers). Vasya likes to watch Berland movies with Berland actors, and he has k favorite actors. He watched the movie trailers for the next month and wrote the following information for every movie: the movie title, the number of actors who starred in it, and the identifiers of these actors. Besides, he managed to copy the movie titles and how many actors starred there, but he didn't manage to write down the identifiers of some actors. Vasya looks at his records and wonders which movies may be his favourite, and which ones may not be. Once Vasya learns the exact cast of all movies, his favorite movies will be determined as follows: a movie becomes favorite movie, if no other movie from Vasya's list has more favorite actors.Help the boy to determine the following for each movie: whether it surely will be his favourite movie; whether it surely won't be his favourite movie; can either be favourite or not.InputThe first line of the input contains two integers m and k (1 ≀ m ≀ 100, 1 ≀ k ≀ m) β€” the number of actors in Berland and the number of Vasya's favourite actors. The second line contains k distinct integers ai (1 ≀ ai ≀ m) β€” the identifiers of Vasya's favourite actors.The third line contains a single integer n (1 ≀ n ≀ 100) β€” the number of movies in Vasya's list.Then follow n blocks of lines, each block contains a movie's description. The i-th movie's description contains three lines: the first line contains string si (si consists of lowercase English letters and can have the length of from 1 to 10 characters, inclusive) β€” the movie's title, the second line contains a non-negative integer di (1 ≀ di ≀ m) β€” the number of actors who starred in this movie, the third line has di integers bi, j (0 ≀ bi, j ≀ m) β€” the identifiers of the actors who star in this movie. If bi, j = 0, than Vasya doesn't remember the identifier of the j-th actor. It is guaranteed that the list of actors for a movie doesn't contain the same actors. All movies have distinct names. The numbers on the lines are separated by single spaces.OutputPrint n lines in the output. In the i-th line print: 0, if the i-th movie will surely be the favourite; 1, if the i-th movie won't surely be the favourite; 2, if the i-th movie can either be favourite, or not favourite. ExamplesInput5 31 2 36firstfilm30 0 0secondfilm40 0 4 5thirdfilm12fourthfilm15fifthfilm14sixthfilm21 0Output221112Input5 31 3 54jumanji30 0 0theeagle51 2 3 4 0matrix32 4 0sourcecode22 4Output2011NoteNote to the second sample: Movie jumanji can theoretically have from 1 to 3 Vasya's favourite actors. Movie theeagle has all three favourite actors, as the actor Vasya failed to remember, can only have identifier 5. Movie matrix can have exactly one favourite actor. Movie sourcecode doesn't have any favourite actors. Thus, movie theeagle will surely be favourite, movies matrix and sourcecode won't surely be favourite, and movie jumanji can be either favourite (if it has all three favourite actors), or not favourite.
Input5 31 2 36firstfilm30 0 0secondfilm40 0 4 5thirdfilm12fourthfilm15fifthfilm14sixthfilm21 0
Output221112
1 second
256 megabytes
['implementation', '*1600']
C. Weathertime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtScientists say a lot about the problems of global warming and cooling of the Earth. Indeed, such natural phenomena strongly influence all life on our planet.Our hero Vasya is quite concerned about the problems. He decided to try a little experiment and observe how outside daily temperature changes. He hung out a thermometer on the balcony every morning and recorded the temperature. He had been measuring the temperature for the last n days. Thus, he got a sequence of numbers t1, t2, ..., tn, where the i-th number is the temperature on the i-th day.Vasya analyzed the temperature statistics in other cities, and came to the conclusion that the city has no environmental problems, if first the temperature outside is negative for some non-zero number of days, and then the temperature is positive for some non-zero number of days. More formally, there must be a positive integer k (1 ≀ k ≀ n - 1) such that t1 < 0, t2 < 0, ..., tk < 0 and tk + 1 > 0, tk + 2 > 0, ..., tn > 0. In particular, the temperature should never be zero. If this condition is not met, Vasya decides that his city has environmental problems, and gets upset.You do not want to upset Vasya. Therefore, you want to select multiple values of temperature and modify them to satisfy Vasya's condition. You need to know what the least number of temperature values needs to be changed for that.InputThe first line contains a single integer n (2 ≀ n ≀ 105) β€” the number of days for which Vasya has been measuring the temperature. The second line contains a sequence of n integers t1, t2, ..., tn (|ti| ≀ 109) β€” the sequence of temperature values. Numbers ti are separated by single spaces.OutputPrint a single integer β€” the answer to the given task.ExamplesInput4-1 1 -2 1Output1Input50 -1 1 2 -5Output2NoteNote to the first sample: there are two ways to change exactly one number so that the sequence met Vasya's condition. You can either replace the first number 1 by any negative number or replace the number -2 by any positive number.
Input4-1 1 -2 1
Output1
1 second
256 megabytes
['dp', 'implementation', '*1300']
B. Readingtime limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtVasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed k hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.Vasya has a train lighting schedule for all n hours of the trip β€” n numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose k hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.InputThe first input line contains two integers n and k (1 ≀ n ≀ 1000, 1 ≀ k ≀ n) β€” the number of hours on the train and the number of hours to read, correspondingly. The second line contains n space-separated integers ai (0 ≀ ai ≀ 100), ai is the light level at the i-th hour.OutputIn the first output line print the minimum light level Vasya will read at. In the second line print k distinct space-separated integers b1, b2, ..., bk, β€” the indexes of hours Vasya will read at (1 ≀ bi ≀ n). The hours are indexed starting from 1. If there are multiple optimal solutions, print any of them. Print the numbers bi in an arbitrary order.ExamplesInput5 320 10 30 40 10Output201 3 4 Input6 590 20 35 40 60 100Output351 3 4 5 6 NoteIn the first sample Vasya should read at the first hour (light 20), third hour (light 30) and at the fourth hour (light 40). The minimum light Vasya will have to read at is 20.
Input5 320 10 30 40 10
Output201 3 4
1 second
256 megabytes
['sortings', '*1000']
A. Lefthanders and Righthanders time limit per test1 secondmemory limit per test256 megabytesinputinput.txtoutputoutput.txtOne fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.InputThe first input line contains a single even integer n (4 ≀ n ≀ 100) β€” the number of students in the class. The second line contains exactly n capital English letters "L" and "R". If the i-th letter at the second line equals "L", then the student number i is a lefthander, otherwise he is a righthander.OutputPrint integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.ExamplesInput6LLRLLLOutput1 42 56 3Input4RRLLOutput3 14 2
Input6LLRLLL
Output1 42 56 3
1 second
256 megabytes
['implementation', '*1200']
B. Non-square Equationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider equation:x2 + s(x)Β·x - n = 0,  where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots.InputA single line contains integer n (1 ≀ n ≀ 1018) β€” the equation parameter.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier. OutputPrint -1, if the equation doesn't have integer positive roots. Otherwise print such smallest integer x (x > 0), that the equation given in the statement holds.ExamplesInput2Output1Input110Output10Input4Output-1NoteIn the first test case x = 1 is the minimum root. As s(1) = 1 and 12 + 1Β·1 - 2 = 0.In the second test case x = 10 is the minimum root. As s(10) = 1 + 0 = 1 and 102 + 1Β·10 - 110 = 0.In the third test case the equation has no roots.
Input2
Output1
1 second
256 megabytes
['binary search', 'brute force', 'math', '*1400']
A. Perfect Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 ≀ i ≀ n) (n is the permutation size) the following equations hold ppi = i and pi ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.InputA single line contains a single integer n (1 ≀ n ≀ 100) β€” the permutation size.OutputIf a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn β€” permutation p, that is perfect. Separate printed numbers by whitespaces.ExamplesInput1Output-1Input2Output2 1 Input4Output2 1 4 3
Input1
Output-1
2 seconds
256 megabytes
['implementation', 'math', '*800']
E. Quick Tortoisetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputJohn Doe has a field, which is a rectangular table of size n × m. We assume that the field rows are numbered from 1 to n from top to bottom, and the field columns are numbered from 1 to m from left to right. Then the cell of the field at the intersection of the x-th row and the y-th column has coordinates (x; y).We know that some cells of John's field are painted white, and some are painted black. Also, John has a tortoise, which can move along the white cells of the field. The tortoise can get from a white cell with coordinates (x; y) into cell (x + 1; y) or (x; y + 1), if the corresponding cell is painted white. In other words, the turtle can move only along the white cells of the field to the right or down. The turtle can not go out of the bounds of the field.In addition, John has q queries, each of them is characterized by four numbers x1, y1, x2, y2 (x1 ≀ x2, y1 ≀ y2). For each query John wants to know whether the tortoise can start from the point with coordinates (x1; y1), and reach the point with coordinates (x2; y2), moving only along the white squares of the field.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 500) β€” the field sizes.Each of the next n lines contains m characters "#" and ".": the j-th character of the i-th line equals "#", if the cell (i; j) is painted black and ".", if it is painted white.The next line contains integer q (1 ≀ q ≀ 6Β·105) β€” the number of queries. Next q lines contain four space-separated integers x1, y1, x2 and y2 (1 ≀ x1 ≀ x2 ≀ n, 1 ≀ y1 ≀ y2 ≀ m) β€” the coordinates of the starting and the finishing cells. It is guaranteed that cells (x1; y1) and (x2; y2) are white.OutputFor each of q queries print on a single line "Yes", if there is a way from cell (x1; y1) to cell (x2; y2), that meets the requirements, and "No" otherwise. Print the answers to the queries in the order, in which the queries are given in the input.ExamplesInput3 3....##.#.51 1 3 31 1 1 31 1 3 11 1 1 21 1 2 1OutputNoYesYesYesYesInput5 5......###.......###......51 1 5 51 1 1 51 1 3 42 1 2 51 1 2 5OutputYesYesYesNoYes
Input3 3....##.#.51 1 3 31 1 1 31 1 3 11 1 1 21 1 2 1
OutputNoYesYesYesYes
3 seconds
512 megabytes
['bitmasks', 'divide and conquer', 'dp', '*3000']
D. Fencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Doe has a crooked fence, consisting of n rectangular planks, lined up from the left to the right: the plank that goes i-th (1 ≀ i ≀ n) (from left to right) has width 1 and height hi. We will assume that the plank that goes i-th (1 ≀ i ≀ n) (from left to right) has index i.A piece of the fence from l to r (1 ≀ l ≀ r ≀ n) is a sequence of planks of wood with indices from l to r inclusive, that is, planks with indices l, l + 1, ..., r. The width of the piece of the fence from l to r is value r - l + 1.Two pieces of the fence from l1 to r1 and from l2 to r2 are called matching, if the following conditions hold: the pieces do not intersect, that is, there isn't a single plank, such that it occurs in both pieces of the fence; the pieces are of the same width; for all i (0 ≀ i ≀ r1 - l1) the following condition holds: hl1 + i + hl2 + i = hl1 + hl2. John chose a few pieces of the fence and now wants to know how many distinct matching pieces are for each of them. Two pieces of the fence are distinct if there is a plank, which belongs to one of them and does not belong to the other one.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of wood planks in the fence. The second line contains n space-separated integers h1, h2, ..., hn (1 ≀ hi ≀ 109) β€” the heights of fence planks.The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. Next q lines contain two space-separated integers li and ri (1 ≀ li ≀ ri ≀ n) β€” the boundaries of the i-th piece of the fence.OutputFor each query on a single line print a single integer β€” the number of pieces of the fence that match the given one. Print the answers to the queries in the order, in which the queries are given in the input.ExamplesInput101 2 2 1 100 99 99 100 100 10061 41 23 41 59 1010 10Output122029
Input101 2 2 1 100 99 99 100 100 10061 41 23 41 59 1010 10
Output122029
3 seconds
256 megabytes
['binary search', 'data structures', 'string suffix structures', '*2900']
C. Doe Graphstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Doe decided that some mathematical object must be named after him. So he invented the Doe graphs. The Doe graphs are a family of undirected graphs, each of them is characterized by a single non-negative number β€” its order. We'll denote a graph of order k as D(k), and we'll denote the number of vertices in the graph D(k) as |D(k)|. Then let's define the Doe graphs as follows: D(0) consists of a single vertex, that has number 1. D(1) consists of two vertices with numbers 1 and 2, connected by an edge. D(n) for n β‰₯ 2 is obtained from graphs D(n - 1) and D(n - 2). D(n - 1) and D(n - 2) are joined in one graph, at that numbers of all vertices of graph D(n - 2) increase by |D(n - 1)| (for example, vertex number 1 of graph D(n - 2) becomes vertex number 1 + |D(n - 1)|). After that two edges are added to the graph: the first one goes between vertices with numbers |D(n - 1)| and |D(n - 1)| + 1, the second one goes between vertices with numbers |D(n - 1)| + 1 and 1. Note that the definition of graph D(n) implies, that D(n) is a connected graph, its vertices are numbered from 1 to |D(n)|. The picture shows the Doe graphs of order 1, 2, 3 and 4, from left to right. John thinks that Doe graphs are that great because for them exists a polynomial algorithm for the search of Hamiltonian path. However, your task is to answer queries of finding the shortest-length path between the vertices ai and bi in the graph D(n).A path between a pair of vertices u and v in the graph is a sequence of vertices x1, x2, ..., xk (k > 1) such, that x1 = u, xk = v, and for any i (i < k) vertices xi and xi + 1 are connected by a graph edge. The length of path x1, x2, ..., xk is number (k - 1).InputThe first line contains two integers t and n (1 ≀ t ≀ 105;Β 1 ≀ n ≀ 103) β€” the number of queries and the order of the given graph. The i-th of the next t lines contains two integers ai and bi (1 ≀ ai, bi ≀ 1016, ai ≠ bi) β€” numbers of two vertices in the i-th query. It is guaranteed that ai, bi ≀ |D(n)|.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier. OutputFor each query print a single integer on a single line β€” the length of the shortest path between vertices ai and bi. Print the answers to the queries in the order, in which the queries are given in the input.ExamplesInput10 51 21 31 41 52 32 42 53 43 54 5Output1112123121
Input10 51 21 31 41 52 32 42 53 43 54 5
Output1112123121
3 seconds
256 megabytes
['constructive algorithms', 'divide and conquer', 'dp', 'graphs', 'shortest paths', '*2600']
B. Tabletime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Doe has an n × m table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size n × n have exactly k points.John Doe wondered, how many distinct ways to fill the table with points are there, provided that the condition must hold. As this number can be rather large, John Doe asks to find its remainder after dividing by 1000000007 (109 + 7).You should assume that John always paints a point exactly in the center of some cell. Two ways to fill a table are considered distinct, if there exists a table cell, that has a point in one way and doesn't have it in the other.InputA single line contains space-separated integers n, m, k (1 ≀ n ≀ 100;Β n ≀ m ≀ 1018;Β 0 ≀ k ≀ n2) β€” the number of rows of the table, the number of columns of the table and the number of points each square must contain.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 a single line print a single integer β€” the remainder from dividing the described number of ways by 1000000007 (109 + 7).ExamplesInput5 6 1Output45NoteLet's consider the first test case: The gray area belongs to both 5 × 5 squares. So, if it has one point, then there shouldn't be points in any other place. If one of the white areas has a point, then the other one also must have a point. Thus, there are about 20 variants, where the point lies in the gray area and 25 variants, where each of the white areas contains a point. Overall there are 45 variants.
Input5 6 1
Output45
4 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'math', '*1900']
A. Cyclestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly k cycles of length 3. A cycle of length 3 is an unordered group of three distinct graph vertices a, b and c, such that each pair of them is connected by a graph edge. John has been painting for long, but he has not been a success. Help him find such graph. Note that the number of vertices there shouldn't exceed 100, or else John will have problems painting it.InputA single line contains an integer k (1 ≀ k ≀ 105) β€” the number of cycles of length 3 in the required graph.OutputIn the first line print integer n (3 ≀ n ≀ 100) β€” the number of vertices in the found graph. In each of next n lines print n characters "0" and "1": the i-th character of the j-th line should equal "0", if vertices i and j do not have an edge between them, otherwise it should equal "1". Note that as the required graph is undirected, the i-th character of the j-th line must equal the j-th character of the i-th line. The graph shouldn't contain self-loops, so the i-th character of the i-th line must equal "0" for all i.ExamplesInput1Output3011101110Input10Output50111110111110111110111110
Input1
Output3011101110
1 second
256 megabytes
['binary search', 'constructive algorithms', 'graphs', 'greedy', '*1600']
E. Cactustime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle.A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, ..., vt (t > 2), such that for any i (1 ≀ i < t) exists an edge between vertices vi and vi + 1, and also exists an edge between vertices v1 and vt.A simple path in a undirected graph is a sequence of not necessarily distinct vertices v1, v2, ..., vt (t > 0), such that for any i (1 ≀ i < t) exists an edge between vertices vi and vi + 1 and furthermore each edge occurs no more than once. We'll say that a simple path v1, v2, ..., vt starts at vertex v1 and ends at vertex vt.You've got a graph consisting of n vertices and m edges, that is a vertex cactus. Also, you've got a list of k pairs of interesting vertices xi, yi, for which you want to know the following information β€” the number of distinct simple paths that start at vertex xi and end at vertex yi. We will consider two simple paths distinct if the sets of edges of the paths are distinct.For each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo 1000000007 (109 + 7). InputThe first line contains two space-separated integers n, m (2 ≀ n ≀ 105;Β 1 ≀ m ≀ 105) β€” the number of vertices and edges in the graph, correspondingly. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n) β€” the indexes of the vertices connected by the i-th edge.The next line contains a single integer k (1 ≀ k ≀ 105) β€” the number of pairs of interesting vertices. Next k lines contain the list of pairs of interesting vertices: the i-th line contains two space-separated numbers xi, yi (1 ≀ xi, yi ≀ n;Β xi ≠ yi) β€” the indexes of interesting vertices in the i-th pair.It is guaranteed that the given graph is a vertex cactus. It is guaranteed that the graph contains no loops or multiple edges. Consider the graph vertices are numbered from 1 to n.OutputPrint k lines: in the i-th line print a single integer β€” the number of distinct simple ways, starting at xi and ending at yi, modulo 1000000007 (109 + 7).ExamplesInput10 111 22 33 41 43 55 68 68 77 67 99 1061 23 56 99 29 39 10Output222441
Input10 111 22 33 41 43 55 68 68 77 67 99 1061 23 56 99 29 39 10
Output222441
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'dp', 'graphs', 'trees', '*2100']
D. Magic Boxtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point (0, 0, 0), and the opposite one is at point (x1, y1, z1). The six faces of the box contain some numbers a1, a2, ..., a6, exactly one number right in the center of each face. The numbers are located on the box like that: number a1 is written on the face that lies on the ZOX plane; a2 is written on the face, parallel to the plane from the previous point; a3 is written on the face that lies on the XOY plane; a4 is written on the face, parallel to the plane from the previous point; a5 is written on the face that lies on the YOZ plane; a6 is written on the face, parallel to the plane from the previous point. At the moment Vasya is looking at the box from point (x, y, z). Find the sum of numbers that Vasya sees. Note that all faces of the box are not transparent and Vasya can't see the numbers through the box. The picture contains transparent faces just to make it easier to perceive. You can consider that if Vasya is looking from point, lying on the plane of some face, than he can not see the number that is written on this face. It is enough to see the center of a face to see the corresponding number for Vasya. Also note that Vasya always reads correctly the ai numbers that he sees, independently of their rotation, angle and other factors (that is, for example, if Vasya sees some ai = 6, then he can't mistake this number for 9 and so on). InputThe fist input line contains three space-separated integers x, y and z (|x|, |y|, |z| ≀ 106) β€” the coordinates of Vasya's position in space. The second line contains three space-separated integers x1, y1, z1 (1 ≀ x1, y1, z1 ≀ 106) β€” the coordinates of the box's vertex that is opposite to the vertex at point (0, 0, 0). The third line contains six space-separated integers a1, a2, ..., a6 (1 ≀ ai ≀ 106) β€” the numbers that are written on the box faces. It is guaranteed that point (x, y, z) is located strictly outside the box.OutputPrint a single integer β€” the sum of all numbers on the box faces that Vasya sees.ExamplesInput2 2 21 1 11 2 3 4 5 6Output12Input0 0 103 2 31 2 3 4 5 6Output4NoteThe first sample corresponds to perspective, depicted on the picture. Vasya sees numbers a2 (on the top face that is the darkest), a6 (on the right face that is the lightest) and a4 (on the left visible face).In the second sample Vasya can only see number a4.
Input2 2 21 1 11 2 3 4 5 6
Output12
2 seconds
256 megabytes
['brute force', 'geometry', '*1600']
C. To Add or Not to Addtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA piece of paper contains an array of n integers a1, a2, ..., an. Your task is to find a number that occurs the maximum number of times in this array.However, before looking for such number, you are allowed to perform not more than k following operations β€” choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one.InputThe first line contains two integers n and k (1 ≀ n ≀ 105; 0 ≀ k ≀ 109) β€” the number of elements in the array and the number of operations you are allowed to perform, correspondingly.The third line contains a sequence of n integers a1, a2, ..., an (|ai| ≀ 109) β€” the initial array. The numbers in the lines are separated by single spaces.OutputIn a single line print two numbers β€” the maximum number of occurrences of some number in the array after at most k allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.ExamplesInput5 36 3 4 0 2Output3 4Input3 45 5 5Output3 5Input5 33 1 2 2 1Output4 2NoteIn the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6, 4, 4, 0, 4, where number 4 occurs 3 times.In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5, 5, 5, if we increase each by one, we get 6, 6, 6. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6.In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3, 2, 2, 2, 2, where number 2 occurs 4 times.
Input5 36 3 4 0 2
Output3 4
2 seconds
256 megabytes
['binary search', 'sortings', 'two pointers', '*1600']
B. Magic, Wizardry and Wonderstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.Help Vasya to recover the initial set of cards with numbers.InputThe single line contains three space-separated integers: n (2 ≀ n ≀ 100) β€” the initial number of cards on the table, d (|d| ≀ 104) β€” the number on the card that was left on the table after all the magical actions, and l (1 ≀ l ≀ 100) β€” the limits for the initial integers.OutputIf Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.ExamplesInput3 3 2Output2 1 2 Input5 -4 3Output-1Input5 -4 4Output2 4 1 4 1
Input3 3 2
Output2 1 2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1500']
A. Teamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.InputThe first input line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.OutputPrint a single integer β€” the number of problems the friends will implement on the contest.ExamplesInput31 1 01 1 11 0 0Output2Input21 0 00 1 1Output1NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution.
Input31 1 01 1 11 0 0
Output2
2 seconds
256 megabytes
['brute force', 'greedy', '*800']
B. T-primestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Π’-prime, if t has exactly three distinct positive divisors.You are given an array of n positive integers. For each of them determine whether it is Π’-prime or not.InputThe first line contains a single positive integer, n (1 ≀ n ≀ 105), showing how many numbers are in the array. The next line contains n space-separated integers xi (1 ≀ xi ≀ 1012).Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is advised to use the cin, cout streams or the %I64d specifier.OutputPrint n lines: the i-th line should contain "YES" (without the quotes), if number xi is Π’-prime, and "NO" (without the quotes), if it isn't.ExamplesInput34 5 6OutputYESNONONoteThe given test has three numbers. The first number 4 has exactly three divisors β€” 1, 2 and 4, thus the answer for this number is "YES". The second number 5 has two divisors (1 and 5), and the third number 6 has four divisors (1, 2, 3, 6), hence the answer for them is "NO".
Input34 5 6
OutputYESNONO
2 seconds
256 megabytes
['binary search', 'implementation', 'math', 'number theory', '*1300']
A. Dragonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1 ≀ i ≀ n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.InputThe first line contains two space-separated integers s and n (1 ≀ s ≀ 104, 1 ≀ n ≀ 103). Then n lines follow: the i-th line contains space-separated integers xi and yi (1 ≀ xi ≀ 104, 0 ≀ yi ≀ 104) β€” the i-th dragon's strength and the bonus for defeating it.OutputOn a single line print "YES" (without the quotes), if Kirito can move on to the next level and print "NO" (without the quotes), if he can't.ExamplesInput2 21 99100 0OutputYESInput10 1100 100OutputNONoteIn the first sample Kirito's strength initially equals 2. As the first dragon's strength is less than 2, Kirito can fight it and defeat it. After that he gets the bonus and his strength increases to 2 + 99 = 101. Now he can defeat the second dragon and move on to the next level.In the second sample Kirito's strength is too small to defeat the only dragon and win.
Input2 21 99100 0
OutputYES
2 seconds
256 megabytes
['greedy', 'sortings', '*1000']
E. Giftstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with n gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for n names of items from the list. If the fish's list has p occurrences of the given name, then the old man can't ask for this name of item more than p times.The old man knows that if he asks for s gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose s gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the n names in such a way that he can get n gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly.The old man wondered, what is the probability that he can get n most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 1000) β€” the number of the old man's wishes and the number of distinct names in the goldfish's list, correspondingly. Then m lines follow: the i-th line first contains integer ki (ki > 0)Β β€” the number of distinct prices of gifts with the i-th name, then ki distinct space-separated integers cij (1 ≀ cij ≀ 109), the gifts' prices. It is guaranteed that the sum of all ki doesn't exceed 1000. It is guaranteed that n is not greater than the total number of the gifts.OutputOn a single line print one real number β€” the probability of getting n most valuable gifts. The answer will be considered correct if its absolute or relative error does not exceed 10 - 9.ExamplesInput3 13 10 20 30Output1.000000000Input3 21 404 10 20 30 40Output0.166666667
Input3 13 10 20 30
Output1.000000000
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'probabilities', '*2600']
D. Towerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe city of D consists of n towers, built consecutively on a straight line. The height of the tower that goes i-th (from left to right) in the sequence equals hi. The city mayor decided to rebuild the city to make it beautiful. In a beautiful city all towers are are arranged in non-descending order of their height from left to right.The rebuilding consists of performing several (perhaps zero) operations. An operation constitutes using a crane to take any tower and put it altogether on the top of some other neighboring tower. In other words, we can take the tower that stands i-th and put it on the top of either the (i - 1)-th tower (if it exists), or the (i + 1)-th tower (of it exists). The height of the resulting tower equals the sum of heights of the two towers that were put together. After that the two towers can't be split by any means, but more similar operations can be performed on the resulting tower. Note that after each operation the total number of towers on the straight line decreases by 1.Help the mayor determine the minimum number of operations required to make the city beautiful.InputThe first line contains a single integer n (1 ≀ n ≀ 5000)Β β€” the number of towers in the city. The next line contains n space-separated integers: the i-th number hi (1 ≀ hi ≀ 105) determines the height of the tower that is i-th (from left to right) in the initial tower sequence.OutputPrint a single integer β€” the minimum number of operations needed to make the city beautiful.ExamplesInput58 2 7 3 1Output3Input35 2 1Output2
Input58 2 7 3 1
Output3
2 seconds
256 megabytes
['dp', 'greedy', 'two pointers', '*2100']
C. Trianglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with n vertices, chooses some m edges and keeps them. Bob gets the remaining edges.Alice and Bob are fond of "triangles" in graphs, that is, cycles of length 3. That's why they wonder: what total number of triangles is there in the two graphs formed by Alice and Bob's edges, correspondingly?InputThe first line contains two space-separated integers n and m (1 ≀ n ≀ 106, 0 ≀ m ≀ 106) β€” the number of vertices in the initial complete graph and the number of edges in Alice's graph, correspondingly. Then m lines follow: the i-th line contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi), β€” the numbers of the two vertices connected by the i-th edge in Alice's graph. It is guaranteed that Alice's graph contains no multiple edges and self-loops. It is guaranteed that the initial complete graph also contains no multiple edges and self-loops.Consider the graph vertices to be indexed in some way from 1 to n.OutputPrint a single number β€” the total number of cycles of length 3 in Alice and Bob's graphs together.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is advised to use the cin, cout streams or the %I64d specifier.ExamplesInput5 51 21 32 32 43 4Output3Input5 31 22 31 3Output4NoteIn the first sample Alice has 2 triangles: (1, 2, 3) and (2, 3, 4). Bob's graph has only 1 triangle : (1, 4, 5). That's why the two graphs in total contain 3 triangles.In the second sample Alice's graph has only one triangle: (1, 2, 3). Bob's graph has three triangles: (1, 4, 5), (2, 4, 5) and (3, 4, 5). In this case the answer to the problem is 4.
Input5 51 21 32 32 43 4
Output3
2 seconds
256 megabytes
['combinatorics', 'graphs', 'math', '*1900']
B. Planetstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGoa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time t + 1, unless there are more travellers arriving at time t + 1 to the same planet.Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n.InputThe first line contains two space-separated integers: n (2 ≀ n ≀ 105), the number of planets in the galaxy, and m (0 ≀ m ≀ 105) β€” the number of pairs of planets between which Jack can travel using stargates. Then m lines follow, containing three integers each: the i-th line contains numbers of planets ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi), which are connected through stargates, and the integer transfer time (in seconds) ci (1 ≀ ci ≀ 104) between these planets. It is guaranteed that between any pair of planets there is at most one stargate connection.Then n lines follow: the i-th line contains an integer ki (0 ≀ ki ≀ 105) that denotes the number of moments of time when other travellers arrive to the planet with index i. Then ki distinct space-separated integers tij (0 ≀ tij < 109) follow, sorted in ascending order. An integer tij means that at time tij (in seconds) another traveller arrives to the planet i. It is guaranteed that the sum of all ki does not exceed 105.OutputPrint a single number β€” the least amount of time Jack needs to get from planet 1 to planet n. If Jack can't get to planet n in any amount of time, print number -1.ExamplesInput4 61 2 21 3 31 4 82 3 42 4 53 4 301 32 3 40Output7Input3 11 2 301 30Output-1NoteIn the first sample Jack has three ways to go from planet 1. If he moves to planet 4 at once, he spends 8 seconds. If he transfers to planet 3, he spends 3 seconds, but as other travellers arrive to planet 3 at time 3 and 4, he can travel to planet 4 only at time 5, thus spending 8 seconds in total. But if Jack moves to planet 2, and then β€” to planet 4, then he spends a total of only 2 + 5 = 7 seconds.In the second sample one can't get from planet 1 to planet 3 by moving through stargates.
Input4 61 2 21 3 31 4 82 3 42 4 53 4 301 32 3 40
Output7
2 seconds
256 megabytes
['binary search', 'data structures', 'graphs', 'shortest paths', '*1700']
A. Shiftstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100".Determine the minimum number of moves needed to make some table column consist only of numbers 1.InputThe first line contains two space-separated integers: n (1 ≀ n ≀ 100)Β β€” the number of rows in the table and m (1 ≀ m ≀ 104)Β β€” the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table.It is guaranteed that the description of the table contains no other characters besides "0" and "1".OutputPrint a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.ExamplesInput3 6101010000100100000Output3Input2 3111000Output-1NoteIn the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s.In the second sample one can't shift the rows to get a column containing only 1s.
Input3 6101010000100100000
Output3
2 seconds
256 megabytes
['brute force', 'two pointers', '*1500']
E. The Road to Berland is Paved With Good Intentionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not.The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home.Unfortunately, not everything is as great as Valera II would like. The main part of the group were gastarbeiters β€” illegal immigrants who are enthusiastic but not exactly good at understanding orders in Berlandian. Therefore, having received orders to asphalt the roads coming from some of the city, the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it.Upon learning of this progress, Valera II was very upset, but since it was too late to change anything, he asked you to make a program that determines whether you can in some way asphalt Berlandian roads in at most n days. Help the king.InputThe first line contains two space-separated integers n, m β€” the number of cities and roads in Berland, correspondingly. Next m lines contain the descriptions of roads in Berland: the i-th line contains three space-separated integers ai, bi, ci (1 ≀ ai, bi ≀ n;Β ai ≠ bi;Β 0 ≀ ci ≀ 1). The first two integers (ai, bi) are indexes of the cities that are connected by the i-th road, the third integer (ci) equals 1, if the road was initially asphalted, and 0 otherwise. Consider the cities in Berland indexed from 1 to n, and the roads indexed from 1 to m. It is guaranteed that between two Berlandian cities there is not more than one road.OutputIn the first line print a single integer x (0 ≀ x ≀ n) β€” the number of days needed to asphalt all roads. In the second line print x space-separated integers β€” the indexes of the cities to send the workers to. Print the cities in the order, in which Valera send the workers to asphalt roads. If there are multiple solutions, print any of them. If there's no way to asphalt all roads, print "Impossible" (without the quotes).ExamplesInput4 41 2 12 4 04 3 13 2 0Output43 2 1 3Input3 31 2 02 3 03 1 0OutputImpossible
Input4 41 2 12 4 04 3 13 2 0
Output43 2 1 3
1 second
256 megabytes
['2-sat', 'dfs and similar', 'dsu', 'graphs', '*1900']
D. Zigzagtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe court wizard Zigzag wants to become a famous mathematician. For that, he needs his own theorem, like the Cauchy theorem, or his sum, like the Minkowski sum. But most of all he wants to have his sequence, like the Fibonacci sequence, and his function, like the Euler's totient function.The Zigag's sequence with the zigzag factor z is an infinite sequence Siz (i β‰₯ 1;Β z β‰₯ 2), that is determined as follows: Siz = 2, when ; , when ; , when . Operation means taking the remainder from dividing number x by number y. For example, the beginning of sequence Si3 (zigzag factor 3) looks as follows: 1, 2, 3, 2, 1, 2, 3, 2, 1.Let's assume that we are given an array a, consisting of n integers. Let's define element number i (1 ≀ i ≀ n) of the array as ai. The Zigzag function is function , where l, r, z satisfy the inequalities 1 ≀ l ≀ r ≀ n, z β‰₯ 2.To become better acquainted with the Zigzag sequence and the Zigzag function, the wizard offers you to implement the following operations on the given array a. The assignment operation. The operation parameters are (p, v). The operation denotes assigning value v to the p-th array element. After the operation is applied, the value of the array element ap equals v. The Zigzag operation. The operation parameters are (l, r, z). The operation denotes calculating the Zigzag function Z(l, r, z). Explore the magical powers of zigzags, implement the described operations.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” The number of elements in array a. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the array. The third line contains integer m (1 ≀ m ≀ 105) β€” the number of operations. Next m lines contain the operations' descriptions. An operation's description starts with integer ti (1 ≀ ti ≀ 2) β€” the operation type. If ti = 1 (assignment operation), then on the line follow two space-separated integers: pi, vi (1 ≀ pi ≀ n;Β 1 ≀ vi ≀ 109) β€” the parameters of the assigning operation. If ti = 2 (Zigzag operation), then on the line follow three space-separated integers: li, ri, zi (1 ≀ li ≀ ri ≀ n;Β 2 ≀ zi ≀ 6) β€” the parameters of the Zigzag operation. You should execute the operations in the order, in which they are given in the input.OutputFor each Zigzag operation print the calculated value of the Zigzag function on a single line. Print the values for Zigzag functions in the order, in which they are given in the input.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.ExamplesInput52 3 1 5 542 2 3 22 1 5 31 3 52 1 5 3Output52638NoteExplanation of the sample test: Result of the first operation is Z(2, 3, 2) = 3Β·1 + 1Β·2 = 5. Result of the second operation is Z(1, 5, 3) = 2Β·1 + 3Β·2 + 1Β·3 + 5Β·2 + 5Β·1 = 26. After the third operation array a is equal to 2, 3, 5, 5, 5. Result of the forth operation is Z(1, 5, 3) = 2Β·1 + 3Β·2 + 5Β·3 + 5Β·2 + 5Β·1 = 38.
Input52 3 1 5 542 2 3 22 1 5 31 3 52 1 5 3
Output52638
3 seconds
256 megabytes
['data structures', '*2100']
C. Fractal Detectortime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Vasya likes painting fractals very much.He does it like this. First the boy cuts out a 2 × 2-cell square out of squared paper. Then he paints some cells black. The boy calls the cut out square a fractal pattern. Then he takes a clean square sheet of paper and paints a fractal by the following algorithm: He divides the sheet into four identical squares. A part of them is painted black according to the fractal pattern. Each square that remained white, is split into 4 lesser white squares, some of them are painted according to the fractal pattern. Each square that remained black, is split into 4 lesser black squares. In each of the following steps step 2 repeats. To draw a fractal, the boy can make an arbitrary positive number of steps of the algorithm. But he need to make at least two steps. In other words step 2 of the algorithm must be done at least once. The resulting picture (the square with painted cells) will be a fractal. The figure below shows drawing a fractal (here boy made three steps of the algorithm). One evening Vasya got very tired, so he didn't paint the fractal, he just took a sheet of paper, painted a n × m-cell field. Then Vasya paint some cells black. Now he wonders, how many squares are on the field, such that there is a fractal, which can be obtained as described above, and which is equal to that square. Square is considered equal to some fractal if they consist of the same amount of elementary not divided cells and for each elementary cell of the square corresponding elementary cell of the fractal have the same color.InputThe first line contains two space-separated integers n, m (2 ≀ n, m ≀ 500) β€” the number of rows and columns of the field, correspondingly. Next n lines contain m characters each β€” the description of the field, painted by Vasya. Character "." represents a white cell, character "*" represents a black cell.It is guaranteed that the field description doesn't contain other characters than "." and "*".OutputOn a single line print a single integer β€” the number of squares on the field, such that these squares contain a drawn fractal, which can be obtained as described above.ExamplesInput6 11......*.****.*.*....**.***....*.*..***.*.....*.*.....**......*.*..Output3Input4 4..**..**........Output0NoteThe answer for the first sample is shown on the picture below. Fractals are outlined by red, blue and green squares. The answer for the second sample is 0. There is no fractal, equal to the given picture.
Input6 11......*.****.*.*....**.***....*.*..***.*.....*.*.....**......*.*..
Output3
4 seconds
256 megabytes
['dp', 'hashing', '*2000']
B. Two Tablestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got two rectangular tables with sizes na × ma and nb × mb cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the i-th row and the j-th column, as ai, j; we will define the element of the second table, located at the intersection of the i-th row and the j-th column, as bi, j. We will call the pair of integers (x, y) a shift of the second table relative to the first one. We'll call the overlap factor of the shift (x, y) value:where the variables i, j take only such values, in which the expression ai, jΒ·bi + x, j + y makes sense. More formally, inequalities 1 ≀ i ≀ na, 1 ≀ j ≀ ma, 1 ≀ i + x ≀ nb, 1 ≀ j + y ≀ mb must hold. If there are no values of variables i, j, that satisfy the given inequalities, the value of the sum is considered equal to 0. Your task is to find the shift with the maximum overlap factor among all possible shifts.InputThe first line contains two space-separated integers na, ma (1 ≀ na, ma ≀ 50) β€” the number of rows and columns in the first table. Then na lines contain ma characters each β€” the elements of the first table. Each character is either a "0", or a "1".The next line contains two space-separated integers nb, mb (1 ≀ nb, mb ≀ 50) β€” the number of rows and columns in the second table. Then follow the elements of the second table in the format, similar to the first table.It is guaranteed that the first table has at least one number "1". It is guaranteed that the second table has at least one number "1".OutputPrint two space-separated integers x, y (|x|, |y| ≀ 109) β€” a shift with maximum overlap factor. If there are multiple solutions, print any of them.ExamplesInput3 20110002 3001111Output0 1Input3 30000100001 11Output-1 -1
Input3 20110002 3001111
Output0 1
2 seconds
256 megabytes
['brute force', 'implementation', '*1400']
A. Is your horseshoe on the other hoof?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to the store and buy some few more horseshoes, not to lose face in front of his stylish comrades.Fortunately, the store sells horseshoes of all colors under the sun and Valera has enough money to buy any four of them. However, in order to save the money, he would like to spend as little money as possible, so you need to help Valera and determine what is the minimum number of horseshoes he needs to buy to wear four horseshoes of different colors to a party.InputThe first line contains four space-separated integers s1, s2, s3, s4 (1 ≀ s1, s2, s3, s4 ≀ 109) β€” the colors of horseshoes Valera has.Consider all possible colors indexed with integers.OutputPrint a single integer β€” the minimum number of horseshoes Valera needs to buy.ExamplesInput1 7 3 3Output1Input7 7 7 7Output3
Input1 7 3 3
Output1
2 seconds
256 megabytes
['implementation', '*800']
B. Effective Approachtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≀ ai ≀ n) β€” the elements of array. The third line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≀ bi ≀ n) β€” the search queries. Note that the queries can repeat.OutputPrint two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.ExamplesInput21 211Output1 2Input22 111Output2 1Input33 1 231 2 3Output6 6NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).
Input21 211
Output1 2
2 seconds
256 megabytes
['implementation', '*1100']
A. Where do I Turn?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTrouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point C and began to terrorize the residents of the surrounding villages.A brave hero decided to put an end to the dragon. He moved from point A to fight with Gorynych. The hero rode from point A along a straight road and met point B on his way. The hero knows that in this land for every pair of roads it is true that they are either parallel to each other, or lie on a straight line, or are perpendicular to each other. He also knows well that points B and C are connected by a road. So the hero must either turn 90 degrees to the left or continue riding straight ahead or turn 90 degrees to the right. But he forgot where the point C is located.Fortunately, a Brave Falcon flew right by. It can see all three points from the sky. The hero asked him what way to go to get to the dragon's lair.If you have not got it, you are the falcon. Help the hero and tell him how to get him to point C: turn left, go straight or turn right.At this moment the hero is believed to stand at point B, turning his back to point A.InputThe first input line contains two space-separated integers xa, ya (|xa|, |ya| ≀ 109) β€” the coordinates of point A. The second line contains the coordinates of point B in the same form, the third line contains the coordinates of point C.It is guaranteed that all points are pairwise different. It is also guaranteed that either point B lies on segment AC, or angle ABC is right.OutputPrint a single line. If a hero must turn left, print "LEFT" (without the quotes); If he must go straight ahead, print "TOWARDS" (without the quotes); if he should turn right, print "RIGHT" (without the quotes).ExamplesInput0 00 11 1OutputRIGHTInput-1 -1-3 -3-4 -4OutputTOWARDSInput-4 -6-3 -7-2 -6OutputLEFTNoteThe picture to the first sample: The red color shows points A, B and C. The blue arrow shows the hero's direction. The green color shows the hero's trajectory.The picture to the second sample:
Input0 00 11 1
OutputRIGHT
2 seconds
256 megabytes
['geometry', '*1300']
E. Noble Knight's Pathtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland each feudal owns exactly one castle and each castle belongs to exactly one feudal.Each feudal, except one (the King) is subordinate to another feudal. A feudal can have any number of vassals (subordinates).Some castles are connected by roads, it is allowed to move along the roads in both ways. Two castles have a road between them if and only if the owner of one of these castles is a direct subordinate to the other owner.Each year exactly one of these two events may happen in Berland. The barbarians attacked castle c. The interesting fact is, the barbarians never attacked the same castle twice throughout the whole Berlandian history. A noble knight sets off on a journey from castle a to castle b (provided that on his path he encounters each castle not more than once). Let's consider the second event in detail. As the journey from a to b is not short, then the knight might want to stop at a castle he encounters on his way to have some rest. However, he can't stop at just any castle: his nobility doesn't let him stay in the castle that has been desecrated by the enemy's stench. A castle is desecrated if and only if it has been attacked after the year of y. So, the knight chooses the k-th castle he encounters, starting from a (castles a and b aren't taken into consideration), that hasn't been attacked in years from y + 1 till current year.The knights don't remember which castles were attacked on what years, so he asked the court scholar, aka you to help them. You've got a sequence of events in the Berland history. Tell each knight, in what city he should stop or else deliver the sad news β€” that the path from city a to city b has less than k cities that meet his requirements, so the knight won't be able to rest.InputThe first input line contains integer n (2 ≀ n ≀ 105) β€” the number of feudals. The next line contains n space-separated integers: the i-th integer shows either the number of the i-th feudal's master, or a 0, if the i-th feudal is the King. The third line contains integer m (1 ≀ m ≀ 105) β€” the number of queries.Then follow m lines that describe the events. The i-th line (the lines are indexed starting from 1) contains the description of the event that occurred in year i. Each event is characterised by type ti (1 ≀ ti ≀ 2). The description of the first type event looks as two space-separated integers ti ci (ti = 1;Β 1 ≀ ci ≀ n), where ci is the number of the castle that was attacked by the barbarians in the i-th year. The description of the second type contains five space-separated integers: ti ai bi ki yi (ti = 2;Β 1 ≀ ai, bi, ki ≀ n;Β ai ≠ bi;Β 0 ≀ yi < i), where ai is the number of the castle from which the knight is setting off, bi is the number of the castle to which the knight is going, ki and yi are the k and y from the second event's description.You can consider the feudals indexed from 1 to n. It is guaranteed that there is only one king among the feudals. It is guaranteed that for the first type events all values ci are different.OutputFor each second type event print an integer β€” the number of the castle where the knight must stay to rest, or -1, if he will have to cover the distance from ai to bi without a rest. Separate the answers by whitespaces.Print the answers in the order, in which the second type events are given in the input.ExamplesInput30 1 252 1 3 1 01 22 1 3 1 02 1 3 1 12 1 3 1 2Output2-1-12Input62 5 2 2 0 532 1 6 2 01 22 4 5 1 0Output5-1NoteIn the first sample there is only castle 2 on the knight's way from castle 1 to castle 3. When the knight covers the path 1 - 3 for the first time, castle 2 won't be desecrated by an enemy and the knight will stay there. In the second year the castle 2 will become desecrated, so the knight won't have anywhere to stay for the next two years (as finding a castle that hasn't been desecrated from years 1 and 2, correspondingly, is important for him). In the fifth year the knight won't consider the castle 2 desecrated, so he will stay there again.
Input30 1 252 1 3 1 01 22 1 3 1 02 1 3 1 12 1 3 1 2
Output2-1-12
4 seconds
256 megabytes
['data structures', 'trees', '*2900']