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
C. Football Championshiptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAny resemblance to any real championship and sport is accidental.The Berland National team takes part in the local Football championship which now has a group stage. Let's describe the formal rules of the local championship: the team that kicked most balls in the enemy's goal area wins the game; the victory gives 3 point to the team, the draw gives 1 point and the defeat gives 0 points; a group consists of four teams, the teams are ranked by the results of six games: each team plays exactly once with each other team; the teams that get places 1 and 2 in the group stage results, go to the next stage of the championship. In the group stage the team's place is defined by the total number of scored points: the more points, the higher the place is. If two or more teams have the same number of points, then the following criteria are used (the criteria are listed in the order of falling priority, starting from the most important one): the difference between the total number of scored goals and the total number of missed goals in the championship: the team with a higher value gets a higher place; the total number of scored goals in the championship: the team with a higher value gets a higher place; the lexicographical order of the name of the teams' countries: the country with the lexicographically smaller name gets a higher place. The Berland team plays in the group where the results of 5 out of 6 games are already known. To be exact, there is the last game left. There the Berand national team plays with some other team. The coach asks you to find such score X:Y (where X is the number of goals Berland scored and Y is the number of goals the opponent scored in the game), that fulfills the following conditions: X > Y, that is, Berland is going to win this game; after the game Berland gets the 1st or the 2nd place in the group; if there are multiple variants, you should choose such score X:Y, where value X - Y is minimum; if it is still impossible to come up with one score, you should choose the score where value Y (the number of goals Berland misses) is minimum. InputThe input has five lines.Each line describes a game as "team1 team2 goals1:goals2" (without the quotes), what means that team team1 played a game with team team2, besides, team1 scored goals1 goals and team2 scored goals2 goals. The names of teams team1 and team2 are non-empty strings, consisting of uppercase English letters, with length of no more than 20 characters; goals1, goals2 are integers from 0 to 9. The Berland team is called "BERLAND". It is guaranteed that the Berland team and one more team played exactly 2 games and the the other teams played exactly 3 games.OutputPrint the required score in the last game as X:Y, where X is the number of goals Berland scored and Y is the number of goals the opponent scored. If the Berland team does not get the first or the second place in the group, whatever this game's score is, then print on a single line "IMPOSSIBLE" (without the quotes).Note, that the result score can be very huge, 10:0 for example.ExamplesInputAERLAND DERLAND 2:1DERLAND CERLAND 0:3CERLAND AERLAND 0:1AERLAND BERLAND 2:0DERLAND BERLAND 4:0Output6:0InputAERLAND DERLAND 2:2DERLAND CERLAND 2:3CERLAND AERLAND 1:3AERLAND BERLAND 2:1DERLAND BERLAND 4:1OutputIMPOSSIBLENoteIn the first sample "BERLAND" plays the last game with team "CERLAND". If Berland wins with score 6:0, the results' table looks like that in the end: AERLAND (points: 9, the difference between scored and missed goals: 4, scored goals: 5) BERLAND (points: 3, the difference between scored and missed goals: 0, scored goals: 6) DERLAND (points: 3, the difference between scored and missed goals: 0, scored goals: 5) CERLAND (points: 3, the difference between scored and missed goals: -4, scored goals: 3) In the second sample teams "AERLAND" and "DERLAND" have already won 7 and 4 points, respectively. The Berland team wins only 3 points, which is not enough to advance to the next championship stage.
InputAERLAND DERLAND 2:1DERLAND CERLAND 0:3CERLAND AERLAND 0:1AERLAND BERLAND 2:0DERLAND BERLAND 4:0
Output6:0
2 seconds
256 megabytes
['brute force', 'implementation', '*1800']
B. Drinkstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.One day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. Then he wondered, how much orange juice the cocktail has.Find the volume fraction of orange juice in the final drink.InputThe first input line contains a single integer n (1 ≀ n ≀ 100) β€” the number of orange-containing drinks in Vasya's fridge. The second line contains n integers pi (0 ≀ pi ≀ 100) β€” the volume fraction of orange juice in the i-th drink, in percent. The numbers are separated by a space.OutputPrint the volume fraction in percent of orange juice in Vasya's cocktail. The answer will be considered correct if the absolute or relative error does not exceed 10  - 4.ExamplesInput350 50 100Output66.666666666667Input40 25 50 75Output37.500000000000NoteNote to the first sample: let's assume that Vasya takes x milliliters of each drink from the fridge. Then the volume of pure juice in the cocktail will equal milliliters. The total cocktail's volume equals 3Β·x milliliters, so the volume fraction of the juice in the cocktail equals , that is, 66.(6) percent.
Input350 50 100
Output66.666666666667
2 seconds
256 megabytes
['implementation', 'math', '*800']
A. Cinematime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe capital of Berland has the only movie theater in the country. Besides, it consists of only one room. The room is divided into n rows, each row consists of m seats.There are k people lined up to the box office, each person wants to buy exactly one ticket for his own entertainment. Before the box office started selling tickets, each person found the seat that seemed best for him and remembered it as a pair of coordinates (xi, yi), where xi is the row number, and yi is the seat number in this row.It is possible that some people have chosen the same place, then when some people see their favorite seat taken in the plan of empty seats in the theater, they choose and buy a ticket to another place. Each of them has the following logic: let's assume that he originally wanted to buy a ticket to seat (x1, y1), then when he comes to the box office, he chooses such empty seat (x2, y2), which satisfies the following conditions: the value of |x1 - x2| + |y1 - y2| is minimum if the choice is not unique, then among the seats that satisfy the first condition, this person selects the one for which the value of x2 is minimum if the choice is still not unique, among the seats that satisfy the first and second conditions, this person selects the one for which the value of y2 is minimum Your task is to find the coordinates of a seat for each person.InputThe first input line contains three integers n, m, k (1 ≀ n, m ≀ 2000, 1 ≀ k ≀ min(nΒ·m, 105) β€” the number of rows in the room, the number of seats in each row and the number of people in the line, correspondingly. Each of the next k lines contains two integers xi, yi (1 ≀ xi ≀ n, 1 ≀ yi ≀ m) β€” the coordinates of the seat each person has chosen. Numbers on the same line are separated by a space. The pairs of coordinates are located in the order, in which people stand in the line, starting from the head (the first person in the line who stands in front of the box office) to the tail (the last person in the line).OutputPrint k lines, each containing a pair of integers. Print on the i-th line xi, yi β€” the coordinates of the seat, for which the person who stands i-th in the line will buy the ticket. ExamplesInput3 4 61 11 11 11 21 31 3Output1 11 22 11 31 42 3Input4 3 122 22 22 22 22 22 22 22 22 22 22 22 2Output2 21 22 12 33 21 11 33 13 34 24 14 3
Input3 4 61 11 11 11 21 31 3
Output1 11 22 11 31 42 3
1.5 seconds
256 megabytes
['brute force', 'data structures', '*2400']
B. Special Olympicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA renowned abstract artist Sasha, drawing inspiration from nowhere, decided to paint a picture entitled "Special Olympics". He justly thought that, if the regular Olympic games have five rings, then the Special ones will do with exactly two rings just fine.Let us remind you that a ring is a region located between two concentric circles with radii r and R (r < R). These radii are called internal and external, respectively. Concentric circles are circles with centers located at the same point.Soon a white canvas, which can be considered as an infinite Cartesian plane, had two perfect rings, painted with solid black paint. As Sasha is very impulsive, the rings could have different radii and sizes, they intersect and overlap with each other in any way. We know only one thing for sure: the centers of the pair of rings are not the same.When Sasha got tired and fell into a deep sleep, a girl called Ilona came into the room and wanted to cut a circle for the sake of good memories. To make the circle beautiful, she decided to cut along the contour.We'll consider a contour to be a continuous closed line through which there is transition from one color to another (see notes for clarification). If the contour takes the form of a circle, then the result will be cutting out a circle, which Iona wants.But the girl's inquisitive mathematical mind does not rest: how many ways are there to cut a circle out of the canvas?InputThe input contains two lines. Each line has four space-separated integers xi, yi, ri, Ri, that describe the i-th ring; xi and yi are coordinates of the ring's center, ri and Ri are the internal and external radii of the ring correspondingly ( - 100 ≀ xi, yi ≀ 100;Β 1 ≀ ri < Ri ≀ 100). It is guaranteed that the centers of the rings do not coinside.OutputA single integer β€” the number of ways to cut out a circle from the canvas.ExamplesInput60 60 45 5580 80 8 32Output1Input60 60 45 5580 60 15 25Output4Input50 50 35 4590 50 35 45Output0NoteFigures for test samples are given below. The possible cuts are marked with red dotted line.
Input60 60 45 5580 80 8 32
Output1
2 seconds
256 megabytes
['geometry', '*1900']
A. Hexadecimal's theoremtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - 2 + Fi - 1.So, Fibonacci numbers make a sequence of numbers: 0, 1, 1, 2, 3, 5, 8, 13, ...If you haven't run away from the PC in fear, you have to help the virus. Your task is to divide given Fibonacci number n by three not necessary different Fibonacci numbers or say that it is impossible.InputThe input contains of a single integer n (0 ≀ n < 109) β€” the number that should be represented by the rules described above. It is guaranteed that n is a Fibonacci number.OutputOutput three required numbers: a, b and c. If there is no answer for the test you have to print "I'm too stupid to solve this problem" without the quotes.If there are multiple answers, print any of them.ExamplesInput3Output1 1 1Input13Output2 3 8
Input3
Output1 1 1
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'implementation', 'number theory', '*900']
E. Gripping Storytime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOne day Qwerty the Ranger witnessed two transport ships collide with each other. As a result, all contents of their cargo holds scattered around the space. And now Qwerty wants to pick as many lost items as possible to sell them later.The thing is, both ships had lots of new gravitational grippers, transported to sale. A gripper is a device that can be installed on a spaceship and than draw items in space to itself ("grip") and transport them to the ship's cargo hold. Overall the crashed ships lost n gravitational grippers: the i-th gripper is located at a point with coordinates (xi, yi). Each gripper has two features β€” pi (the power) and ri (the action radius) and can grip any items with mass of no more than pi at distance no more than ri. A gripper itself is an item, too and it has its mass of mi.Qwerty's ship is located at point (x, y) and has an old magnetic gripper installed, its characteristics are p and r. There are no other grippers in the ship's cargo holds.Find the largest number of grippers Qwerty can get hold of. As he picks the items, he can arbitrarily install any gripper in the cargo hold of the ship, including the gripper he has just picked. At any moment of time the ship can have only one active gripper installed. We consider all items and the Qwerty's ship immobile when the ranger picks the items, except for when the gripper moves an item β€” then the item moves to the cargo holds and the ship still remains immobile. We can assume that the ship's cargo holds have enough room for all grippers. Qwerty can use any gripper he finds or the initial gripper an arbitrary number of times.InputThe first line contains five integers x, y, p, r and n ( - 109 ≀ x, y ≀ 109, 1 ≀ p, r ≀ 109, 1 ≀ n ≀ 250000) β€” the ship's initial position, the initial gripper's features and the number of grippers that got into the space during the collision.Next n lines contain the grippers' descriptions: the i-th line contains five integers xi, yi, mi, pi, ri ( - 109 ≀ xi, yi ≀ 109, 1 ≀ mi, pi, ri ≀ 109) β€” the i-th gripper's coordinates and features.It is guaranteed that all grippers are located at different points. No gripper is located at the same point with Qwerty's ship.OutputPrint a single number β€” the maximum number of grippers Qwerty can draw to his ship. You do not need to count the initial old magnet gripper.ExamplesInput0 0 5 10 55 4 7 11 5-7 1 4 7 80 2 13 5 62 -3 9 3 413 5 1 9 9Output3NoteIn the first sample you should get the second gripper, then use the second gripper to get the first one, then use the first gripper to get the fourth one. You cannot get neither the third gripper as it is too heavy, nor the fifth one as it is too far away.
Input0 0 5 10 55 4 7 11 5-7 1 4 7 80 2 13 5 62 -3 9 3 413 5 1 9 9
Output3
4 seconds
512 megabytes
['binary search', 'data structures', 'sortings', '*2400']
D. Cube Snaketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got an n × n × n cube, split into unit cubes. Your task is to number all unit cubes in this cube with positive integers from 1 to n3 so that: each number was used as a cube's number exactly once; for each 1 ≀ i < n3, unit cubes with numbers i and i + 1 were neighbouring (that is, shared a side); for each 1 ≀ i < n there were at least two different subcubes with sizes i × i × i, made from unit cubes, which are numbered with consecutive numbers. That is, there are such two numbers x and y, that the unit cubes of the first subcube are numbered by numbers x, x + 1, ..., x + i3 - 1, and the unit cubes of the second subcube are numbered by numbers y, y + 1, ..., y + i3 - 1. Find and print the required numeration of unit cubes of the cube.InputThe first line contains a single integer n (1 ≀ n ≀ 50) β€” the size of the cube, whose unit cubes need to be numbered.OutputPrint all layers of the cube as n n × n matrices. Separate them with new lines. Print the layers in the order in which they follow in the cube. See the samples for clarifications. It is guaranteed that there always is a solution that meets the conditions given in the problem statement.ExamplesInput3Output1 4 17 2 3 18 27 26 19 8 5 16 7 6 15 24 25 20 9 12 13 10 11 14 23 22 21 NoteIn the sample the cubes with sizes 2 × 2 × 2 are numbered with integers 1, ..., 8 and 5, ..., 12.
Input3
Output1 4 17 2 3 18 27 26 19 8 5 16 7 6 15 24 25 20 9 12 13 10 11 14 23 22 21
2 seconds
256 megabytes
['constructive algorithms', '*2700']
C. Delivering Carcinogentime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputQwerty the Ranger arrived to the Diatar system with a very important task. He should deliver a special carcinogen for scientific research to planet Persephone. This is urgent, so Qwerty has to get to the planet as soon as possible. A lost day may fail negotiations as nobody is going to pay for an overdue carcinogen.You can consider Qwerty's ship, the planet Persephone and the star Diatar points on a plane. Diatar is located in the origin of coordinate axes β€” at point (0, 0). Persephone goes round Diatar along a circular orbit with radius R in the counter-clockwise direction at constant linear speed vp (thus, for instance, a full circle around the star takes of time). At the initial moment of time Persephone is located at point (xp, yp).At the initial moment of time Qwerty's ship is at point (x, y). Qwerty can move in any direction at speed of at most v (v > vp). The star Diatar is hot (as all stars), so Qwerty can't get too close to it. The ship's metal sheathing melts at distance r (r < R) from the star.Find the minimum time Qwerty needs to get the carcinogen to planet Persephone.InputThe first line contains space-separated integers xp, yp and vp ( - 104 ≀ xp, yp ≀ 104, 1 ≀ vp < 104) β€” Persephone's initial position and the speed at which it goes round Diatar.The second line contains space-separated integers x, y, v and r ( - 104 ≀ x, y ≀ 104, 1 < v ≀ 104, 1 ≀ r ≀ 104) β€” The intial position of Qwerty's ship, its maximum speed and the minimum safe distance to star Diatar.It is guaranteed that r2 < x2 + y2, r2 < xp2 + yp2 and vp < v.OutputPrint a single real number β€” the minimum possible delivery time. The answer will be considered valid if its absolute or relative error does not exceed 10 - 6.ExamplesInput10 0 1-10 0 2 8Output9.584544103Input50 60 1050 60 20 40Output0.000000000
Input10 0 1-10 0 2 8
Output9.584544103
2 seconds
256 megabytes
['binary search', 'geometry', '*2400']
B. Jumping on Wallstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon.The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some areas are safe and the ninja can climb them. Others are spiky and ninja can't be there. Let's call such areas dangerous.Initially the ninja is on the lower area of the left wall. He can use each second to perform one of the following actions: climb one area up; climb one area down; jump to the opposite wall. That gets the ninja to the area that is exactly k meters higher than the area he jumped from. More formally, if before the jump the ninja is located at area x of one wall, then after the jump he is located at area x + k of the other wall. If at some point of time the ninja tries to get to an area with a number larger than n, then we can assume that the ninja got out of the canyon.The canyon gets flooded and each second the water level raises one meter. Initially the water level is at the lower border of the first area. Ninja cannot be on the area covered by water. We can assume that the ninja and the water "move in turns" β€” first the ninja performs some action, then the water raises for one meter, then the ninja performs one more action and so on.The level is considered completed if the ninja manages to get out of the canyon.After several failed attempts Vasya started to doubt whether it is possible to complete the level at all. Help him answer the question.InputThe first line contains two integers n and k (1 ≀ n, k ≀ 105) β€” the height of the canyon and the height of ninja's jump, correspondingly.The second line contains the description of the left wall β€” a string with the length of n characters. The i-th character represents the state of the i-th wall area: character "X" represents a dangerous area and character "-" represents a safe area.The third line describes the right wall in the same format.It is guaranteed that the first area of the left wall is not dangerous.OutputPrint "YES" (without the quotes) if the ninja can get out from the canyon, otherwise, print "NO" (without the quotes).ExamplesInput7 3---X--X-X--XX-OutputYESInput6 2--X-X-X--XX-OutputNONoteIn the first sample the ninja should first jump to the right wall, then go one meter down along the right wall, then jump to the left wall. The next jump can get the ninja from the canyon. In the second sample there's no way the ninja can get out of the canyon.
Input7 3---X--X-X--XX-
OutputYES
2 seconds
256 megabytes
['shortest paths', '*1400']
A. About Bacteriatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputQwerty the Ranger took up a government job and arrived on planet Mars. He should stay in the secret lab and conduct some experiments on bacteria that have funny and abnormal properties. The job isn't difficult, but the salary is high.At the beginning of the first experiment there is a single bacterium in the test tube. Every second each bacterium in the test tube divides itself into k bacteria. After that some abnormal effects create b more bacteria in the test tube. Thus, if at the beginning of some second the test tube had x bacteria, then at the end of the second it will have kx + b bacteria.The experiment showed that after n seconds there were exactly z bacteria and the experiment ended at this point.For the second experiment Qwerty is going to sterilize the test tube and put there t bacteria. He hasn't started the experiment yet but he already wonders, how many seconds he will need to grow at least z bacteria. The ranger thinks that the bacteria will divide by the same rule as in the first experiment. Help Qwerty and find the minimum number of seconds needed to get a tube with at least z bacteria in the second experiment.InputThe first line contains four space-separated integers k, b, n and t (1 ≀ k, b, n, t ≀ 106) β€” the parameters of bacterial growth, the time Qwerty needed to grow z bacteria in the first experiment and the initial number of bacteria in the second experiment, correspondingly.OutputPrint a single number β€” the minimum number of seconds Qwerty needs to grow at least z bacteria in the tube.ExamplesInput3 1 3 5Output2Input1 4 4 7Output3Input2 2 4 100Output0
Input3 1 3 5
Output2
2 seconds
256 megabytes
['implementation', 'math', '*1700']
B. Limittime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two polynomials: P(x) = a0Β·xn + a1Β·xn - 1 + ... + an - 1Β·x + an and Q(x) = b0Β·xm + b1Β·xm - 1 + ... + bm - 1Β·x + bm. Calculate limit .InputThe first line contains two space-separated integers n and m (0 ≀ n, m ≀ 100) β€” degrees of polynomials P(x) and Q(x) correspondingly.The second line contains n + 1 space-separated integers β€” the factors of polynomial P(x): a0, a1, ..., an - 1, an ( - 100 ≀ ai ≀ 100, a0 ≠ 0).The third line contains m + 1 space-separated integers β€” the factors of polynomial Q(x): b0, b1, ..., bm - 1, bm ( - 100 ≀ bi ≀ 100, b0 ≠ 0).OutputIf the limit equals  +β€‰βˆž, print "Infinity" (without quotes). If the limit equals  -β€‰βˆž, print "-Infinity" (without the quotes).If the value of the limit equals zero, print "0/1" (without the quotes).Otherwise, print an irreducible fraction β€” the value of limit , in the format "p/q" (without the quotes), where p is the β€” numerator, q (q > 0) is the denominator of the fraction.ExamplesInput2 11 1 12 5OutputInfinityInput1 0-1 32Output-InfinityInput0 111 0Output0/1Input2 22 1 64 5 -7Output1/2Input1 19 0-5 2Output-9/5NoteLet's consider all samples: You can learn more about the definition and properties of limits if you follow the link: http://en.wikipedia.org/wiki/Limit_of_a_function
Input2 11 1 12 5
OutputInfinity
2 seconds
256 megabytes
['math', '*1400']
A. Plate Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a rectangular table with length a and width b and the infinite number of plates of radius r. Two players play the following game: they take turns to put the plates on the table so that the plates don't lie on each other (but they can touch each other), and so that any point on any plate is located within the table's border. During the game one cannot move the plates that already lie on the table. The player who cannot make another move loses. Determine which player wins, the one who moves first or the one who moves second, provided that both players play optimally well.InputA single line contains three space-separated integers a, b, r (1 ≀ a, b, r ≀ 100) β€” the table sides and the plates' radius, correspondingly.OutputIf wins the player who moves first, print "First" (without the quotes). Otherwise print "Second" (without the quotes).ExamplesInput5 5 2OutputFirstInput6 7 4OutputSecondNoteIn the first sample the table has place for only one plate. The first player puts a plate on the table, the second player can't do that and loses. In the second sample the table is so small that it doesn't have enough place even for one plate. So the first player loses without making a single move.
Input5 5 2
OutputFirst
2 seconds
256 megabytes
['constructive algorithms', 'games', 'math', '*1600']
E. Opening Portalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPavel plays a famous computer game. A player is responsible for a whole country and he can travel there freely, complete quests and earn experience.This country has n cities connected by m bidirectional roads of different lengths so that it is possible to get from any city to any other one. There are portals in k of these cities. At the beginning of the game all portals are closed. When a player visits a portal city, the portal opens. Strange as it is, one can teleport from an open portal to an open one. The teleportation takes no time and that enables the player to travel quickly between rather remote regions of the country.At the beginning of the game Pavel is in city number 1. He wants to open all portals as quickly as possible. How much time will he need for that?InputThe first line contains two space-separated integers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ 105) that show how many cities and roads are in the game.Each of the next m lines contains the description of a road as three space-separated integers xi, yi, wi (1 ≀ xi, yi ≀ n, xi ≠ yi, 1 ≀ wi ≀ 109) β€” the numbers of the cities connected by the i-th road and the time needed to go from one city to the other one by this road. Any two cities are connected by no more than one road. It is guaranteed that we can get from any city to any other one, moving along the roads of the country.The next line contains integer k (1 ≀ k ≀ n) β€” the number of portals.The next line contains k space-separated integers p1, p2, ..., pk β€” numbers of the cities with installed portals. Each city has no more than one portal.OutputPrint a single number β€” the minimum time a player needs to open all portals.Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput3 31 2 11 3 12 3 131 2 3Output2Input4 31 2 12 3 52 4 1032 3 4Output16Input4 31 2 10000000002 3 10000000003 4 100000000041 2 3 4Output3000000000NoteIn the second sample the player has to come to city 2, open a portal there, then go to city 3, open a portal there, teleport back to city 2 and finally finish the journey in city 4.
Input3 31 2 11 3 12 3 131 2 3
Output2
2 seconds
256 megabytes
['dsu', 'graphs', 'shortest paths', '*2600']
D. The Next Good Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to d. You are given string s, consisting only of lowercase English letters. Find a good string t with length |s|, consisting of lowercase English letters, which is lexicographically larger than s. Of all such strings string t must be lexicographically minimum.We will call a non-empty string s[aΒ ...Β b] = sasa + 1... sb (1 ≀ a ≀ b ≀ |s|) a substring of string s = s1s2... s|s|.A non-empty string s = s1s2... sn is called a palindrome if for all i from 1 to n the following fulfills: si = sn - i + 1. In other words, palindrome read the same in both directions.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or there exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in such strings are compared like their ASCII codes.InputThe first line contains integer d (1 ≀ d ≀ |s|).The second line contains a non-empty string s, its length is no more than 4Β·105 characters. The string consists of lowercase English letters.OutputPrint the good string that lexicographically follows s, has the same length and consists of only lowercase English letters. If such string does not exist, print "Impossible" (without the quotes).ExamplesInput3aaaaaaaOutputaabbcaaInput3zzyzzzzOutputImpossibleInput4abbabbbabbbOutputabbbcaaabab
Input3aaaaaaa
Outputaabbcaa
2 seconds
256 megabytes
['data structures', 'greedy', 'hashing', 'strings', '*2800']
C. Paint Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n vertexes and n points on a plane, no three points lie on one straight line.Your task is to paint the given tree on a plane, using the given points as vertexes. That is, you should correspond each vertex of the tree to exactly one point and each point should correspond to a vertex. If two vertexes of the tree are connected by an edge, then the corresponding points should have a segment painted between them. The segments that correspond to non-adjacent edges, should not have common points. The segments that correspond to adjacent edges should have exactly one common point.InputThe first line contains an integer n (1 ≀ n ≀ 1500) β€” the number of vertexes on a tree (as well as the number of chosen points on the plane).Each of the next n - 1 lines contains two space-separated integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi) β€” the numbers of tree vertexes connected by the i-th edge.Each of the next n lines contain two space-separated integers xi and yi ( - 109 ≀ xi, yi ≀ 109) β€” the coordinates of the i-th point on the plane. No three points lie on one straight line.It is guaranteed that under given constraints problem has a solution.OutputPrint n distinct space-separated integers from 1 to n: the i-th number must equal the number of the vertex to place at the i-th point (the points are numbered in the order, in which they are listed in the input).If there are several solutions, print any of them.ExamplesInput31 32 30 01 12 0Output1 3 2Input41 22 31 4-1 -23 5-3 32 0Output4 2 1 3NoteThe possible solutions for the sample are given below.
Input31 32 30 01 12 0
Output1 3 2
2 seconds
256 megabytes
['constructive algorithms', 'divide and conquer', 'geometry', 'sortings', 'trees', '*2200']
B. Infinite Mazetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe've got a rectangular n × m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell is a wall.In this problem is a remainder of dividing number a by number b.The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 1500) β€” the height and the width of the maze that the boy used to cyclically tile the plane.Each of the next n lines contains m characters β€” the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point. The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input.OutputPrint "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes).ExamplesInput5 4##.###S##..##.###..#OutputYesInput5 4##.###S##..#..#.#.##OutputNoNoteIn the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up.In the second sample the vertical path is blocked. The path to the left doesn't work, too β€” the next "copy" of the maze traps the boy.
Input5 4##.###S##..##.###..#
OutputYes
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*2000']
A. Lexicographically Maximum Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 < p2 < ... < pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| > |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r < |x|, r < |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 > yr + 1. Characters in lines are compared like their ASCII codes.InputThe single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.OutputPrint the lexicographically maximum subsequence of string s.ExamplesInputababbaOutputbbbaInputabbcbccacbbcbaabaOutputcccccbbaNoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Inputababba
Outputbbba
2 seconds
256 megabytes
['greedy', 'strings', '*1100']
E. Building Foresttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn oriented weighted forest is an acyclic weighted digraph in which from each vertex at most one edge goes.The root of vertex v of an oriented weighted forest is a vertex from which no edge goes and which can be reached from vertex v moving along the edges of the weighted oriented forest. We denote the root of vertex v as root(v).The depth of vertex v is the sum of weights of paths passing from the vertex v to its root. Let's denote the depth of the vertex v as depth(v).Let's consider the process of constructing a weighted directed forest. Initially, the forest does not contain vertices. Vertices are added sequentially one by one. Overall, there are n performed operations of adding. The i-th (i > 0) adding operation is described by a set of numbers (k,  v1,  x1,  v2,  x2,  ... ,  vk,  xk) and means that we should add vertex number i and k edges to the graph: an edge from vertex root(v1) to vertex i with weight depth(v1) + x1, an edge from vertex root(v2) to vertex i with weight depth(v2) + x2 and so on. If k = 0, then only vertex i is added to the graph, there are no added edges.Your task is like this: given the operations of adding vertices, calculate the sum of the weights of all edges of the forest, resulting after the application of all defined operations, modulo 1000000007 (109 + 7).InputThe first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of operations of adding a vertex.Next n lines contain descriptions of the operations, the i-th line contains the description of the operation of adding the i-th vertex in the following format: the first number of a line is an integer k (0 ≀ k ≀ i - 1), then follow 2k space-separated integers: v1, x1, v2, x2, ... , vk, xk (1 ≀ vj ≀ i - 1, |xj| ≀ 109). The operations are given in the order, in which they should be applied to the graph. It is guaranteed that sum k of all operations does not exceed 105, also that applying operations of adding vertexes does not result in loops and multiple edges. OutputPrint a single number β€” the sum of weights of all edges of the resulting graph modulo 1000000007 (109 + 7).ExamplesInput6001 2 12 1 5 2 21 1 21 3 4Output30Input501 1 5002 3 1 4 3Output9NoteConside the first sample: Vertex 1 is added. k = 0, thus no edges are added. Vertex 2 is added. k = 0, thus no edges are added. Vertex 3 is added. k = 1. v1 = 2, x1 = 1. Edge from vertex root(2) = 2 to vertex 3 with weight depth(2) + x1 = 0 + 1 = 1 is added. Vertex 4 is added. k = 2. v1 = 1, x1 = 5. Edge from vertex root(1) = 1 to vertex 4 with weight depth(1) + x1 = 0 + 5 = 5 is added. v2 = 2, x2 = 2. Edge from vertex root(2) = 3 to vertex 4 with weight depth(2) + x1 = 1 + 2 = 3 is added. Vertex 5 is added. k = 1. v1 = 1, x1 = 2. Edge from vertex root(1) = 4 to vertex 5 with weight depth(1) + x1 = 5 + 2 = 7 is added. Vertex 6 is added. k = 1. v1 = 3, x1 = 4. Edge from vertex root(3) = 5 to vertex 6 with weight depth(3) + x1 = 10 + 4 = 14 is added.The resulting graph is shown on the pictore below:
Input6001 2 12 1 5 2 21 1 21 3 4
Output30
2 seconds
256 megabytes
['data structures', 'dsu', 'graphs', '*2000']
D. Analyzing Polylinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form: Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of functions. Each of the following n lines contains two space-separated integer numbers ki, bi ( - 109 ≀ ki, bi ≀ 109) that determine the i-th function.OutputPrint a single number β€” the number of angles that do not equal 180 degrees in the graph of the polyline that equals the sum of the given functions.ExamplesInput11 0Output1Input31 00 2-1 1Output2Input3-2 -41 7-5 1Output3
Input11 0
Output1
2 seconds
256 megabytes
['geometry', 'math', 'sortings', '*1900']
C. Try and Catchtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is developing his own programming language VPL (Vasya Programming Language). Right now he is busy making the system of exceptions. He thinks that the system of exceptions must function like that.The exceptions are processed by try-catch-blocks. There are two operators that work with the blocks: The try operator. It opens a new try-catch-block. The catch(<exception_type>, <message>) operator. It closes the try-catch-block that was started last and haven't yet been closed. This block can be activated only via exception of type <exception_type>. When we activate this block, the screen displays the <message>. If at the given moment there is no open try-catch-block, then we can't use the catch operator.The exceptions can occur in the program in only one case: when we use the throw operator. The throw(<exception_type>) operator creates the exception of the given type.Let's suggest that as a result of using some throw operator the program created an exception of type a. In this case a try-catch-block is activated, such that this block's try operator was described in the program earlier than the used throw operator. Also, this block's catch operator was given an exception type a as a parameter and this block's catch operator is described later that the used throw operator. If there are several such try-catch-blocks, then the system activates the block whose catch operator occurs earlier than others. If no try-catch-block was activated, then the screen displays message "Unhandled Exception".To test the system, Vasya wrote a program that contains only try, catch and throw operators, one line contains no more than one operator, the whole program contains exactly one throw operator.Your task is: given a program in VPL, determine, what message will be displayed on the screen.InputThe first line contains a single integer: n (1 ≀ n ≀ 105) the number of lines in the program. Next n lines contain the program in language VPL. Each line contains no more than one operator. It means that input file can contain empty lines and lines, consisting only of spaces.The program contains only operators try, catch and throw. It is guaranteed that the program is correct. It means that each started try-catch-block was closed, the catch operators aren't used unless there is an open try-catch-block. The program has exactly one throw operator. The program may have spaces at the beginning of a line, at the end of a line, before and after a bracket, a comma or a quote mark.The exception type is a nonempty string, that consists only of upper and lower case english letters. The length of the string does not exceed 20 symbols. Message is a nonempty string, that consists only of upper and lower case english letters, digits and spaces. Message is surrounded with quote marks. Quote marks shouldn't be printed. The length of the string does not exceed 20 symbols.Length of any line in the input file does not exceed 50 symbols. OutputPrint the message the screen will show after the given program is executed.ExamplesInput8try try throw ( AE ) catch ( BE, "BE in line 3") try catch(AE, "AE in line 5") catch(AE,"AE somewhere")OutputAE somewhereInput8try try throw ( AE ) catch ( AE, "AE in line 3") try catch(BE, "BE in line 5") catch(AE,"AE somewhere")OutputAE in line 3Input8try try throw ( CE ) catch ( BE, "BE in line 3") try catch(AE, "AE in line 5") catch(AE,"AE somewhere")OutputUnhandled ExceptionNoteIn the first sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(BE,"BE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so the second block will be activated, because operator catch(AE,"AE somewhere") has exception type AE as parameter and operator catch(BE,"BE in line 3") has exception type BE.In the second sample there are 2 try-catch-blocks such that try operator is described earlier than throw operator and catch operator is described later than throw operator: try-catch(AE,"AE in line 3") and try-catch(AE,"AE somewhere"). Exception type is AE, so both blocks can be activated, but only the first one will be activated, because operator catch(AE,"AE in line 3") is described earlier than catch(AE,"AE somewhere")In the third sample there is no blocks that can be activated by an exception of type CE.
Input8try try throw ( AE ) catch ( BE, "BE in line 3") try catch(AE, "AE in line 5") catch(AE,"AE somewhere")
OutputAE somewhere
2 seconds
256 megabytes
['expression parsing', 'implementation', '*1800']
B. After Trainingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The balls are numbered with numbers from 1 to n.Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which is minimum, where i is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.For every ball print the number of the basket where it will go according to Valeric's scheme.Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.InputThe first line contains two space-separated integers n, m (1 ≀ n, m ≀ 105) β€” the number of balls and baskets, correspondingly.OutputPrint n numbers, one per line. The i-th line must contain the number of the basket for the i-th ball.ExamplesInput4 3Output2132Input3 1Output111
Input4 3
Output2132
2 seconds
256 megabytes
['data structures', 'implementation', 'math', '*1300']
A. Let's Watch Footballtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValeric and Valerko missed the last Euro football game, so they decided to watch the game's key moments on the Net. They want to start watching as soon as possible but the connection speed is too low. If they turn on the video right now, it will "hang up" as the size of data to watch per second will be more than the size of downloaded data per second.The guys want to watch the whole video without any pauses, so they have to wait some integer number of seconds for a part of the video to download. After this number of seconds passes, they can start watching. Waiting for the whole video to download isn't necessary as the video can download after the guys started to watch.Let's suppose that video's length is c seconds and Valeric and Valerko wait t seconds before the watching. Then for any moment of time t0, t ≀ t0 ≀ c + t, the following condition must fulfill: the size of data received in t0 seconds is not less than the size of data needed to watch t0 - t seconds of the video.Of course, the guys want to wait as little as possible, so your task is to find the minimum integer number of seconds to wait before turning the video on. The guys must watch the video without pauses.InputThe first line contains three space-separated integers a, b and c (1 ≀ a, b, c ≀ 1000, a > b). The first number (a) denotes the size of data needed to watch one second of the video. The second number (b) denotes the size of data Valeric and Valerko can download from the Net per second. The third number (c) denotes the video's length in seconds.OutputPrint a single number β€” the minimum integer number of seconds that Valeric and Valerko must wait to watch football without pauses.ExamplesInput4 1 1Output3Input10 3 2Output5Input13 12 1Output1NoteIn the first sample video's length is 1 second and it is necessary 4 units of data for watching 1 second of video, so guys should download 4 Β· 1 = 4 units of data to watch the whole video. The most optimal way is to wait 3 seconds till 3 units of data will be downloaded and then start watching. While guys will be watching video 1 second, one unit of data will be downloaded and Valerik and Valerko will have 4 units of data by the end of watching. Also every moment till the end of video guys will have more data then necessary for watching.In the second sample guys need 2 Β· 10 = 20 units of data, so they have to wait 5 seconds and after that they will have 20 units before the second second ends. However, if guys wait 4 seconds, they will be able to watch first second of video without pauses, but they will download 18 units of data by the end of second second and it is less then necessary.
Input4 1 1
Output3
2 seconds
256 megabytes
['binary search', 'brute force', 'math', '*1000']
B. Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (n + 1) meters, he draws a cross (see picture for clarifications).John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw? The figure shows the order in which John draws crosses for a square with side 4. The lower left square has two crosses. Overall John paints 17 crosses. InputThe first line contains integer t (1 ≀ t ≀ 104) β€” the number of test cases. The second line contains t space-separated integers ni (1 ≀ ni ≀ 109) β€” the sides of the square for each test sample.OutputFor each test sample print on a single line the answer to it, that is, the number of crosses John will draw as he will move along the square of the corresponding size. Print the answers to the samples in the order in which the samples 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 the cin, cout streams or the %I64d specifier. ExamplesInput34 8 100Output1733401
Input34 8 100
Output1733401
2 seconds
256 megabytes
['math', '*1200']
A. Examstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day the Codeforces round author sat exams. He had n exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2. The author would need to spend too much time and effort to make the sum of his marks strictly more than k. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than k, the author's mum won't be pleased at all. The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams. Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all n exams equal exactly k.InputThe single input line contains space-separated integers n and k (1 ≀ n ≀ 50, 1 ≀ k ≀ 250) β€” the number of exams and the required sum of marks.It is guaranteed that there exists a way to pass n exams in the way that makes the sum of marks equal exactly k.OutputPrint the single number β€” the minimum number of exams that the author will get a 2 for, considering that the sum of marks for all exams must equal k.ExamplesInput4 8Output4Input4 10Output2Input1 3Output0NoteIn the first sample the author has to get a 2 for all his exams.In the second sample he should get a 3 for two exams and a 2 for two more.In the third sample he should get a 3 for one exam.
Input4 8
Output4
2 seconds
256 megabytes
['implementation', 'math', '*900']
E. Fibonacci Numbertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013. John got interested in number f (0 ≀ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list. The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...InputThe first line contains the single integer f (0 ≀ f < 1013) β€” the number, which position in the list we should find.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. OutputPrint a single number β€” the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.ExamplesInput13Output7Input377Output14
Input13
Output7
3 seconds
256 megabytes
['brute force', 'math', 'matrices', '*2900']
D. Two Segmentstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNick has some permutation consisting of p integers from 1 to n. A segment [l, r] (l ≀ r) is a set of elements pi satisfying l ≀ i ≀ r.Nick calls a pair of segments [a0, a1] and [b0, b1] (1 ≀ a0 ≀ a1 < b0 ≀ b1 ≀ n) good if all their (a1 - a0 + b1 - b0 + 2) elements, when sorted in ascending order, form an arithmetic progression with a difference of 1. That is, when they sorted in ascending order, the elements are in the form {x, x + 1, x + 2, ..., x + m - 1}, for some x and m.Your task is to find the number of distinct pairs of good segments in the given permutation. Two pairs of segments are considered distinct if the sets of elements contained in these pairs of segments are distinct. For example, any segment [l, r] (l < r) can be represented as a pair of segments, as [l, i] and [i + 1, r] (l ≀ i ≀ r). As all these pairs consist of the same set of elements, they are considered identical.See the notes accompanying the sample tests for clarification.InputThe first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the permutation size. The second line contains n space-separated distinct integers pi, (1 ≀ pi ≀ n).OutputPrint a single integer β€” the number of good pairs of segments of permutation p.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. ExamplesInput31 2 3Output3Input51 4 5 3 2Output10Input55 4 3 1 2Output10NoteIn the first sample the following pairs of segments are good: ([1, 1], [2, 2]); ([2, 2], [3, 3]); ([1, 2], [3, 3]). Pair of segments ([1, 1], [2, 3]) is by definition equivalent to pair ([1, 2], [3, 3]), since both of them covers the same set of elements, namely {1, 2, 3}.In the third sample the following pairs of segments are good: ([4, 4], [5, 5]); ([3, 3],[4, 5]); ([2, 2],[3, 5]); ([1, 1],[2, 5]); ([3, 3],[5, 5]); ([2, 3],[5, 5]); ([1, 3],[5, 5]); ([2, 2],[3, 3]); ([1, 1],[2, 3]); ([1, 1],[2, 2]).
Input31 2 3
Output3
5 seconds
256 megabytes
['data structures', '*2900']
C. Hamming Distancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≀ i ≀ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length. InputThe first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4).All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.OutputPrint -1 if there's no suitable set of strings.Otherwise print on the first line number len β€” the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them. ExamplesInput4 4 44 44Output6aaaabbaabbaabbaaaabbbbbb
Input4 4 44 44
Output6aaaabbaabbaabbaaaabbbbbb
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', 'matrices', '*2400']
B. Xortime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn Doe has four arrays: a, b, k, and p. Each array consists of n integers. Elements of all arrays are indexed starting from 1. Array p is a permutation of integers 1 to n.John invented a game for his friends and himself. Initially a player is given array a. The player must consecutively execute exactly u operations on a. You are permitted to execute the following operations: Operation 1: For each change ai into . 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 language C++ and Java it is marked as "^", in Pascal β€” as "xor". Operation 2: For each change ai into api + r. When this operation is executed, all changes are made at the same time. After all u operations are applied, the number of points the player gets is determined by the formula . John wants to find out what maximum number of points a player can win in his game. Help him.InputThe first line contains space-separated integers n, u and r (1 ≀ n, u ≀ 30, 0 ≀ r ≀ 100) β€” the number of elements in each array, the number of operations and the number that describes one of the operations. Each of the next four lines contains n space-separated integers β€” arrays a, b, k, p. The first line has array a, the second line has array b, the third line has array k and the fourth one has array p. It is guaranteed that elements of arrays a and b are positive and do not exceed 104 (1 ≀ ai, bi ≀ 104), elements of array k do not exceed 104 in the absolute value (|k| ≀ 104) and p is a permutation of numbers from 1 to n.OutputOn a single line print number s β€” the maximum number of points that a player can win in John's game.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 2 17 7 78 8 81 2 31 3 2Output96Input2 1 01 11 11 -11 2Output0NoteIn the first sample you should first apply the operation of the first type, then the operation of the second type.
Input3 2 17 7 78 8 81 2 31 3 2
Output96
4 seconds
256 megabytes
['brute force', '*2000']
A. Cutting Figuretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've gotten an n × m sheet of squared paper. Some of its squares are painted. Let's mark the set of all painted squares as A. Set A is connected. Your task is to find the minimum number of squares that we can delete from set A to make it not connected.A set of painted squares is called connected, if for every two squares a and b from this set there is a sequence of squares from the set, beginning in a and ending in b, such that in this sequence any square, except for the last one, shares a common side with the square that follows next in the sequence. An empty set and a set consisting of exactly one square are connected by definition.InputThe first input line contains two space-separated integers n and m (1 ≀ n, m ≀ 50) β€” the sizes of the sheet of paper. Each of the next n lines contains m characters β€” the description of the sheet of paper: the j-th character of the i-th line equals either "#", if the corresponding square is painted (belongs to set A), or equals "." if the corresponding square is not painted (does not belong to set A). It is guaranteed that the set of all painted squares A is connected and isn't empty.OutputOn the first line print the minimum number of squares that need to be deleted to make set A not connected. If it is impossible, print -1. ExamplesInput5 4#####..##..##..#####Output2Input5 5######...#######...######Output2NoteIn the first sample you can delete any two squares that do not share a side. After that the set of painted squares is not connected anymore.The note to the second sample is shown on the figure below. To the left there is a picture of the initial set of squares. To the right there is a set with deleted squares. The deleted squares are marked with crosses.
Input5 4#####..##..##..#####
Output2
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'trees', '*1700']
B. Walking in the Raintime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.InputThe first line contains integer n (1 ≀ n ≀ 103) β€” the boulevard's length in tiles.The second line contains n space-separated integers ai β€” the number of days after which the i-th tile gets destroyed (1 ≀ ai ≀ 103). OutputPrint a single number β€” the sought number of days.ExamplesInput410 3 5 10Output5Input510 2 8 3 5Output5NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.
Input410 3 5 10
Output5
2 seconds
256 megabytes
['brute force', 'implementation', '*1100']
A. Funky Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as , where k is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers.A well-known hipster Andrew adores everything funky and cool but unfortunately, he isn't good at maths. Given number n, help him define whether this number can be represented by a sum of two triangular numbers (not necessarily different)!InputThe first input line contains an integer n (1 ≀ n ≀ 109).OutputPrint "YES" (without the quotes), if n can be represented as a sum of two triangular numbers, otherwise print "NO" (without the quotes).ExamplesInput256OutputYESInput512OutputNONoteIn the first sample number .In the second sample number 512 can not be represented as a sum of two triangular numbers.
Input256
OutputYES
2 seconds
256 megabytes
['binary search', 'brute force', 'implementation', '*1300']
E. Thwarting Demonstrationstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt is dark times in Berland. Berlyand opposition, funded from a neighboring state, has organized a demonstration in Berland capital Bertown. Through the work of intelligence we know that the demonstrations are planned to last for k days.Fortunately, Berland has a special police unit, which can save the country. It has exactly n soldiers numbered from 1 to n. Berland general, the commander of the detachment, must schedule the detachment's work in these difficult k days. In each of these days, the general must send a certain number of police officers to disperse riots. Since the detachment is large and the general is not very smart, he can only select a set of all soldiers numbered from l to r, inclusive, where l and r are selected arbitrarily.Now the general has exactly two problems. First, he cannot send the same group twice β€” then soldiers get bored and they rebel. Second, not all soldiers are equally reliable. Every soldier has a reliability of ai. The reliability of the detachment is counted as the sum of reliabilities of soldiers in it. The reliability of a single soldier can be negative, then when you include him in the detachment, he will only spoil things. The general is distinguished by his great greed and shortsightedness, so each day he sends to the dissolution the most reliable group of soldiers possible (that is, of all the groups that have not been sent yet).The Berland Government has decided to know what would be the minimum reliability of the detachment, sent to disperse the demonstrations during these k days. The general himself can not cope with such a difficult task. Help him to not embarrass himself in front of his superiors!InputThe first line contains two integers n and k β€” the number of soldiers in the detachment and the number of times somebody goes on duty.The second line contains n space-separated integers ai, their absolute value doesn't exceed 109 β€” the soldiers' reliabilities.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++, it is preferred to use cin, cout streams of the %I64d specifier.OutputPrint a single number β€” the sought minimum reliability of the groups that go on duty during these k days.ExamplesInput3 41 4 2Output4Input4 62 -1 2 -1Output1Input8 101 -2 3 -4 5 -6 7 -8Output2
Input3 41 4 2
Output4
6 seconds
512 megabytes
['binary search', 'data structures', 'trees', '*2200']
D. Metro Schemetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland is very concerned with privacy, so almost all plans and blueprints are secret. However, a spy of the neighboring state managed to steal the Bertown subway scheme.The Bertown Subway has n stations, numbered from 1 to n, and m bidirectional tunnels connecting them. All Bertown Subway consists of lines. To be more precise, there are two types of lines: circular and radial.A radial line is a sequence of stations v1, ..., vk (k > 1), where stations vi and vi + 1 (i < k) are connected by a tunnel and no station occurs in the line more than once (vi ≠ vj for i ≠ j).A loop line is a series of stations, v1, ..., vk (k > 2), where stations vi ΠΈ vi + 1 are connected by a tunnel. In addition, stations v1 and vk are also connected by a tunnel. No station is occurs in the loop line more than once.Note that a single station can be passed by any number of lines.According to Berland standards, there can't be more than one tunnel between two stations and each tunnel belongs to exactly one line. Naturally, each line has at least one tunnel. Between any two stations there is the way along the subway tunnels. In addition, in terms of graph theory, a subway is a vertex cactus: if we consider the subway as a graph in which the stations are the vertexes and the edges are tunnels, then each vertex lies on no more than one simple cycle.Unfortunately, scheme, stolen by the spy, had only the stations and the tunnels. It was impossible to determine to which line every tunnel corresponds. But to sabotage successfully, the spy needs to know what minimum and maximum number of lines may be in the Bertown subway.Help him!InputThe first line contains two integers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ 3Β·105) β€” the number of stations and the number of tunnels, correspondingly.Each of the next m lines contain two integers β€” the numbers of stations connected by the corresponding tunnel. The stations are numbered with integers from 1 to n.It is guaranteed that the graph that corresponds to the subway has no multiple edges or loops, it is connected and it is a vertex cactus.OutputPrint two numbers β€” the minimum and maximum number of lines correspondingly.ExamplesInput3 31 22 33 1Output1 3Input8 81 22 33 44 56 44 77 22 8Output2 8Input6 61 22 32 55 63 43 5Output3 6NoteThe subway scheme with minimum possible number of lines for the second sample is:
Input3 31 22 33 1
Output1 3
2 seconds
256 megabytes
['graphs', 'greedy', '*2700']
C. Fools and Roadstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThey say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths.A simple path is the path which goes through every Berland city not more than once.The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it.Note how the fools' paths are given in the input.InputThe first line contains a single integer n (2 ≀ n ≀ 105) β€” the number of cities. Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≀ ui, vi ≀ n, ui ≠ vi), that means that there is a road connecting cities ui and vi. The next line contains integer k (0 ≀ k ≀ 105) β€” the number of pairs of fools who visit each other. Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≀ ai, bi ≀ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path.OutputPrint n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input.ExamplesInput51 21 32 42 521 43 5Output2 1 1 1 Input53 44 51 42 432 31 33 5Output3 1 1 1 NoteIn the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones.In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1.
Input51 21 32 42 521 43 5
Output2 1 1 1
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'trees', '*1900']
B. Demonstrationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares.Bertown has n squares, numbered from 1 to n, they are numbered in the order of increasing distance between them and the city center. That is, square number 1 is central, and square number n is the farthest from the center. Naturally, the opposition wants to hold a meeting as close to the city center as possible (that is, they want an square with the minimum number).There are exactly k (k < n) days left before the demonstration. Now all squares are free. But the Bertown city administration never sleeps, and the approval of an application for the demonstration threatens to become a very complex process. The process of approval lasts several days, but every day the following procedure takes place: The opposition shall apply to hold a demonstration at a free square (the one which isn't used by the administration). The administration tries to move the demonstration to the worst free square left. To do this, the administration organizes some long-term activities on the square, which is specified in the application of opposition. In other words, the administration starts using the square and it is no longer free. Then the administration proposes to move the opposition demonstration to the worst free square. If the opposition has applied for the worst free square then request is accepted and administration doesn't spend money. If the administration does not have enough money to organize an event on the square in question, the opposition's application is accepted. If administration doesn't have enough money to organize activity, then rest of administration's money spends and application is accepted If the application is not accepted, then the opposition can agree to the administration's proposal (that is, take the worst free square), or withdraw the current application and submit another one the next day. If there are no more days left before the meeting, the opposition has no choice but to agree to the proposal of City Hall. If application is accepted opposition can reject it. It means than opposition still can submit more applications later, but square remains free. In order to organize an event on the square i, the administration needs to spend ai bourles. Because of the crisis the administration has only b bourles to confront the opposition. What is the best square that the opposition can take, if the administration will keep trying to occupy the square in question each time? Note that the administration's actions always depend only on the actions of the opposition.InputThe first line contains two integers n and k β€” the number of squares and days left before the meeting, correspondingly (1 ≀ k < n ≀ 105).The second line contains a single integer b β€” the number of bourles the administration has (1 ≀ b ≀ 1018).The third line contains n space-separated integers ai β€” the sum of money, needed to organise an event on square i (1 ≀ ai ≀ 109).Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.OutputPrint a single number β€” the minimum number of the square where the opposition can organize the demonstration.ExamplesInput5 282 4 5 3 1Output2Input5 283 2 4 1 5Output5Input5 410000000000000005 4 3 2 1Output5NoteIn the first sample the opposition can act like this. On day one it applies for square 3. The administration has to organize an event there and end up with 3 bourles. If on the second day the opposition applies for square 2, the administration won't have the money to intervene.In the second sample the opposition has only the chance for the last square. If its first move occupies one of the first four squares, the administration is left with at least 4 bourles, which means that next day it can use its next move to move the opposition from any square to the last one.In the third sample administration has a lot of money, so opposition can occupy only last square.
Input5 282 4 5 3 1
Output2
2 seconds
256 megabytes
['greedy', '*1700']
A. Dynasty Puzzlestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe ancient Berlanders believed that the longer the name, the more important its bearer is. Thus, Berland kings were famous for their long names. But long names are somewhat inconvenient, so the Berlanders started to abbreviate the names of their kings. They called every king by the first letters of its name. Thus, the king, whose name was Victorious Vasily Pupkin, was always called by the berlanders VVP.In Berland over its long history many dynasties of kings replaced each other, but they were all united by common traditions. Thus, according to one Berland traditions, to maintain stability in the country, the first name of the heir should be the same as the last name his predecessor (hence, the first letter of the abbreviated name of the heir coincides with the last letter of the abbreviated name of the predecessor). Berlanders appreciate stability, so this tradition has never been broken. Also Berlanders like perfection, so another tradition requires that the first name of the first king in the dynasty coincides with the last name of the last king in this dynasty (hence, the first letter of the abbreviated name of the first king coincides with the last letter of the abbreviated name of the last king). This tradition, of course, has also been always observed.The name of a dynasty is formed by very simple rules: we take all the short names of the kings in the order in which they ruled, and write them in one line. Thus, a dynasty of kings "ab" and "ba" is called "abba", and the dynasty, which had only the king "abca", is called "abca".Vasya, a historian, has recently found a list of abbreviated names of all Berland kings and their relatives. Help Vasya to find the maximally long name of the dynasty that could have existed in Berland.Note that in his list all the names are ordered by the time, that is, if name A is earlier in the list than B, then if A and B were kings, then king A ruled before king B.InputThe first line contains integer n (1 ≀ n ≀ 5Β·105) β€” the number of names in Vasya's list. Next n lines contain n abbreviated names, one per line. An abbreviated name is a non-empty sequence of lowercase Latin letters. Its length does not exceed 10 characters.OutputPrint a single number β€” length of the sought dynasty's name in letters.If Vasya's list is wrong and no dynasty can be found there, print a single number 0.ExamplesInput3abccacbaOutput6Input4vvpvvpdamvvpOutput0Input3abcdefOutput1NoteIn the first sample two dynasties can exist: the one called "abcca" (with the first and second kings) and the one called "abccba" (with the first and third kings). In the second sample there aren't acceptable dynasties.The only dynasty in the third sample consists of one king, his name is "c".
Input3abccacba
Output6
2 seconds
256 megabytes
['dp', '*1500']
E. Counter Attacktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland has managed to repel the flatlanders' attack and is now starting the counter attack.Flatland has n cities, numbered from 1 to n, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we do not know whether is it a clever spy-proof strategy or just saving ink). In other words, if two cities are connected by a road on a flatland map, then there is in fact no road between them. The opposite situation is also true: if two cities are not connected by a road on a flatland map, then in fact, there is a road between them.The berlanders got hold of a flatland map. Now Vasya the Corporal is commissioned by General Touristov to find all such groups of flatland cities, that in each group of cities you can get from any city to any other one, moving along the actual roads. Also the cities from different groups are unreachable from each other, moving along the actual roads. Indeed, destroying such groups one by one is much easier than surrounding all Flatland at once!Help the corporal complete this task and finally become a sergeant! Don't forget that a flatland map shows a road between cities if and only if there is in fact no road between them. InputThe first line contains two space-separated integers n and m (1 ≀ n ≀ 5Β·105, 0 ≀ m ≀ 106) β€” the number of cities and the number of roads marked on the flatland map, correspondingly.Next m lines contain descriptions of the cities on the map. The i-th line contains two integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi) β€” the numbers of cities that are connected by the i-th road on the flatland map.It is guaranteed that each pair of cities occurs in the input no more than once.OutputOn the first line print number k β€” the number of groups of cities in Flatland, such that in each group you can get from any city to any other one by flatland roads. At the same time, the cities from different groups should be unreachable by flatland roads.On each of the following k lines first print ti (1 ≀ ti ≀ n) β€” the number of vertexes in the i-th group. Then print space-separated numbers of cities in the i-th group.The order of printing groups and the order of printing numbers in the groups does not matter. The total sum ti for all k groups must equal n.ExamplesInput4 41 21 34 24 3Output22 1 4 2 2 3 Input3 11 2Output13 1 2 3 NoteIn the first sample there are roads only between pairs of cities 1-4 and 2-3.In the second sample there is no road between cities 1 and 2, but still you can get from one city to the other one through city number 3.
Input4 41 21 34 24 3
Output22 1 4 2 2 3
3 seconds
256 megabytes
['data structures', 'dsu', 'graphs', 'hashing', 'sortings', '*2100']
D. Non-Secret Cyphertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.Subarray a[i... j]Β (1 ≀ i ≀ j ≀ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj).InputThe first line contains two space-separated integers n, k (1 ≀ k ≀ n ≀ 4Β·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly. The second line contains n space-separated integers ai (1 ≀ ai ≀ 109) β€” elements of the array.OutputPrint the single number β€” the number of such subarrays of array a, that they have at least k equal integers.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. In is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput4 21 2 1 2Output3Input5 31 2 1 1 3Output2Input3 11 1 1Output6NoteIn the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).
Input4 21 2 1 2
Output3
3 seconds
256 megabytes
['two pointers', '*1900']
C. STLtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--: First, a type is a string "int". Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces. No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform.InputThe first line contains a single integer n (1 ≀ n ≀ 105), showing how many numbers the type dictated by Gena contains.The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes).It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int".OutputIf it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters. It is guaranteed that if such type exists, then it is unique.Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values.ExamplesInput3pair pair int int intOutputpair<pair<int,int>,int>Input1pair intOutputError occurred
Input3pair pair int int int
Outputpair<pair<int,int>,int>
2 seconds
256 megabytes
['dfs and similar', '*1500']
B. Surroundedtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSo, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal β€” their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city β€” that's the strategy the flatlanders usually follow when they besiege cities.The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack. Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r β‰₯ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point. In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range β€” as a disk (including the border) with the center at the point where the radar is placed.InputThe input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| ≀ 104;Β 1 ≀ ri ≀ 104) β€” the city's coordinates and the distance from the city to the flatlanders, correspondingly.It is guaranteed that the cities are located at different points.OutputPrint a single real number β€” the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.ExamplesInput0 0 16 0 3Output1.000000000000000Input-10 10 310 -10 3Output11.142135623730951NoteThe figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0). The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).
Input0 0 16 0 3
Output1.000000000000000
1 second
256 megabytes
['geometry', '*1800']
A. Vasya and the Bustime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had n grown-ups and m kids..."The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could have paid for the ride.The bus fare equals one berland ruble in High Bertown. However, not everything is that easy β€” no more than one child can ride for free with each grown-up passenger. That means that a grown-up passenger who rides with his k (k > 0) children, pays overall k rubles: a ticket for himself and (k - 1) tickets for his children. Also, a grown-up can ride without children, in this case he only pays one ruble.We know that in High Bertown children can't ride in a bus unaccompanied by grown-ups.Help Vasya count the minimum and the maximum sum in Berland rubles, that all passengers of this bus could have paid in total.InputThe input file consists of a single line containing two space-separated numbers n and m (0 ≀ n, m ≀ 105) β€” the number of the grown-ups and the number of the children in the bus, correspondingly.OutputIf n grown-ups and m children could have ridden in the bus, then print on a single line two space-separated integers β€” the minimum and the maximum possible total bus fare, correspondingly. Otherwise, print "Impossible" (without the quotes).ExamplesInput1 2Output2 2Input0 5OutputImpossibleInput2 2Output2 3NoteIn the first sample a grown-up rides with two children and pays two rubles.In the second sample there are only children in the bus, so the situation is impossible. In the third sample there are two cases: Each of the two grown-ups rides with one children and pays one ruble for the tickets. In this case the passengers pay two rubles in total. One of the grown-ups ride with two children's and pays two rubles, the another one rides alone and pays one ruble for himself. So, they pay three rubles in total.
Input1 2
Output2 2
2 seconds
256 megabytes
['greedy', 'math', '*1100']
B. Counting Rhombitime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have two positive integers w and h. Your task is to count the number of rhombi which have the following properties: Have positive area. With vertices at integer points. All vertices of the rhombi are located inside or on the border of the rectangle with vertices at points (0, 0), (w, 0), (w, h), (0, h). In other words, for all vertices (xi, yi) of the rhombus the following conditions should fulfill: 0 ≀ xi ≀ w and 0 ≀ yi ≀ h. Its diagonals are parallel to the axis. Count the number of such rhombi.Let us remind you that a rhombus is a quadrilateral whose four sides all have the same length.InputThe first line contains two integers w and h (1 ≀ w, h ≀ 4000) β€” the rectangle's sizes.OutputPrint a single number β€” the number of sought rhombi.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.ExamplesInput2 2Output1Input1 2Output0NoteIn the first example there exists only one such rhombus. Its vertices are located at points (1, 0), (2, 1), (1, 2), (0, 1).
Input2 2
Output1
2 seconds
256 megabytes
['brute force', 'math', '*1300']
A. Cut Ribbontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: After the cutting each ribbon piece should have length a, b or c. After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces after the required cutting.InputThe first line contains four space-separated integers n, a, b and c (1 ≀ n, a, b, c ≀ 4000) β€” the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.OutputPrint a single number β€” the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.ExamplesInput5 5 3 2Output2Input7 5 5 2Output2NoteIn the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.
Input5 5 3 2
Output2
1 second
256 megabytes
['brute force', 'dp', '*1300']
H. Stacktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem we'll use a stack which supports two types of operations: Push a given number on the stack. Pop two numbers from the stack, perform a given operation (addition or multiplication) on them and push the result on the stack. You are given a string which describes the sequence of operations to be performed on the stack. i-th character corresponds to i-th operation: If i-th character is a digit, push the corresponding number on the stack. If i-th character is Β«+Β» or Β«*Β», perform the corresponding operation. Initially the stack is empty. Output the topmost number on the stack after executing all given operations.InputThe only line of input contains a string of operations, consisting of characters Β«+Β», Β«*Β» and digits (0..9). The length of the string will be between 1 and 20 characters, inclusive.The given sequence of operations is guaranteed to be correct, i.e. the stack will have at least two elements before every math operation. The numbers on the stack will never exceed 106. OutputOutput a single number β€” the topmost element of the stack after performing all given operations.ExamplesInput12+3*66*+Output45Input149Output9NoteIn the first case the stack will end up containing a single number β€” the result of calculating (1+2)*3+6*6.In the second case there are no math operations, so the answer will be the last number pushed on the stack.
Input12+3*66*+
Output45
2 seconds
256 megabytes
['*special problem', 'expression parsing', 'implementation', '*1800']
G. Array Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSorting arrays is traditionally associated with high-level languages. How hard can it be in Roco? Sort the given array in non-descending order.InputThe first line of input contains an integer n (1 ≀ n ≀ 100) β€” the size of the array. The following n lines contain the elements of the array, one per line. Each element of the array is an integer between 1 and 100, inclusive. The array might contain duplicate elements.OutputOutput space-separated elements of the sorted array.ExamplesInput571973Output1 3 7 7 9 Input1010011001100110011001Output1 1 1 1 1 100 100 100 100 100
Input571973
Output1 3 7 7 9
2 seconds
256 megabytes
['*special problem', 'implementation', '*1600']
F. Binary Notationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. Output its binary notation.InputThe only line of input data contains an integer n (1 ≀ n ≀ 106).OutputOutput the binary notation of n (without any leading zeros).ExamplesInput5Output101Input101Output1100101NoteIn the first example 5 = 1 * 22 + 0 * 21 + 1 * 20.
Input5
Output101
2 seconds
256 megabytes
['*special problem', 'implementation', '*1400']
E. HQ9+time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHQ9+ is a joke programming language which has only four one-character instructions: "H" prints "Hello, World!", "Q" prints the whole source code of the program itself (at each call), "9" prints the lyrics of "99 Bottles of Beer" song, "+" increments the value stored in the internal accumulator.Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.InputThe input will consist of a single line p which will give a program in HQ9+. String p will contain between 1 and 100 characters, inclusive. ASCII-code of each character of p will be between 33 (exclamation mark) and 126 (tilde), inclusive.OutputOutput "YES", if executing the program will produce any output, and "NO" otherwise (quotes for clarity only).ExamplesInputHello!OutputYESInputProgopediaOutputNONoteIn the first case the program contains only one instruction β€” "H", which prints "Hello, World!".In the second case none of the program characters are language instructions.
InputHello!
OutputYES
2 seconds
256 megabytes
['*special problem', 'implementation', '*1400']
D. Asteriskstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a number n. Print n lines, i-th line should consist of i characters "*". Lines' indices are 1-based.InputThe only line of input contains an integer n (1 ≀ n ≀ 50).OutputOutput the described pattern.ExamplesInput3Output******Input6Output*********************
Input3
Output******
2 seconds
256 megabytes
['*special problem', 'implementation', '*1100']
C. LCMtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLeast common multiple (LCM) of two numbers is the smallest positive integer which is divisible by both of them. You are given integers a and b. Calculate their LCM.InputThe input contains two integers a and b (1 ≀ a, b ≀ 103), separated by a single space.OutputOutput LCM(a, b).ExamplesInput10 42Output210Input123 41Output123
Input10 42
Output210
2 seconds
256 megabytes
['*special problem', 'implementation', 'math', '*1400']
B. A + Reverse Btime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given numbers a and b. Calculate the sum of a and reverse of b. A reverse of a number is a number which contains the same digits in reverse order. For example, reverse of 230 is 32, and reverse of 0 is 0.InputThe input contains two integers a and b (0 ≀ a, b ≀ 109), separated by a single space. The numbers are given without leading zeros.OutputOutput the sum of a and reverse of b.ExamplesInput5 15Output56Input73 9180Output892
Input5 15
Output56
2 seconds
256 megabytes
['*special problem', 'implementation', '*1300']
A. Hexagonal Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHexagonal numbers are figurate numbers which can be calculated using the formula hn = 2n2 - n. You are given n; calculate n-th hexagonal number.InputThe only line of input contains an integer n (1 ≀ n ≀ 100).OutputOutput the n-th hexagonal number.ExamplesInput3Output15Input6Output66
Input3
Output15
2 seconds
256 megabytes
['*special problem', '*1100']
E. Heaven Tourtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe story was not finished as PMP thought. God offered him one more chance to reincarnate and come back to life. But before he can come back, God told him that PMP should ask n great men including prominent programmers about their life experiences.The men are standing on a straight line. They are numbered 1 through n from left to right. The coordinate of the i-th man is xi (xi < xi + 1, i < n). PMP should visit all these people one by one in arbitrary order. Each men should be visited exactly once. At the beginning of his tour, he starts at location of s-th man and asks him about his experiences.Each time PMP wants to change his location, he should give a ticket to an angel and the angel carries him to his destination. Angels take PMP from one location, fly to his destination and put him down there. Nobody else is visited in this movement. Moving from i-th man to j-th man, takes |xi - xj| time. PMP can get back to life as soon as he visits all men.There are two types of angels: Some angels are going to the right and they only accept right tickets. Others are going the left and they only accept left tickets. There are an unlimited number of angels of each type. PMP has l left tickets and n - 1 - l right tickets.PMP wants to get back to life as soon as possible to be able to compete in this year's final instead of the final he missed last year. He wants to know the quickest way to visit all the men exactly once. He also needs to know the exact sequence moves he should make.InputThe first line of input contains three space-separated integers n, l, s (2 ≀ n ≀ 105, 0 ≀ l < n, 1 ≀ s ≀ n) β€” the number of people to visit, the number left tickets PMP got, and initial location of PMP. Next line contains n space-separated integers. The i-th integer in this line is xi (0 = x1 < x2 < ... < xn ≀ 109) β€” the location of i-th man.OutputIf PMP cannot visit all men with the tickets he got print -1 in the only line of output. Otherwise, in the first line you should print the minimum time PMP can visit all men. In the second line you should print n - 1 integers that are the numbers of the men that PMP should visit in order in one optimal solution. If there are multiple answers, output any of them.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.ExamplesInput5 2 20 10 11 21 22Output331 3 5 4Input4 3 10 1 2 3Output-1Input7 3 20 100 200 201 301 303 305Output4091 3 4 7 6 5NoteLet us remind here, a great contestant of all times, who left us about a year ago. May Renat Mullakhanov rest in peace.
Input5 2 20 10 11 21 22
Output331 3 5 4
2 seconds
256 megabytes
['data structures', 'greedy', '*2900']
D. BRT Contract time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the last war of PMP, he defeated all his opponents and advanced to the final round. But after the end of semi-final round evil attacked him from behind and killed him! God bless him. Before his death, PMP signed a contract with the bus rapid transit (BRT) that improves public transportations by optimizing time of travel estimation. You should help PMP finish his last contract.Each BRT line is straight line that passes n intersecting on its ways. At each intersection there is traffic light that periodically cycles between green and red. It starts illuminating green at time zero. During the green phase which lasts for g seconds, traffic is allowed to proceed. After the green phase the light changes to red and remains in this color for r seconds. During the red phase traffic is prohibited from proceeding. If a vehicle reaches the intersection exactly at a time when the light changes to red, it should stop, but the vehicle is clear to proceed if the light has just changed to green. All traffic lights have the same timing and are synchronized. In other words the period of red (and green) phase is the same for all of traffic lights and they all start illuminating green at time zero.The BRT Company has calculated the time that a bus requires to pass each road segment. A road segment is the distance between two consecutive traffic lights or between a traffic light and source (or destination) station. More precisely BRT specialists provide n + 1 positive integers li, the time in seconds that a bus needs to traverse i-th road segment in the path from source to destination. The l1 value denotes the time that a bus needs to pass the distance between source and the first intersection. The ln + 1 value denotes the time between the last intersection and destination.In one day q buses leave the source station. The i-th bus starts from source at time ti (in seconds). Decision makers of BRT Company want to know what time a bus gets to destination?The bus is considered as point. A bus will always move if it can. The buses do not interfere with each other. InputThe first line of input contains three space-separated positive integers n, g, r (1 ≀ n ≀ 105, 2 ≀ g + r ≀ 109) β€” the number of intersections, duration of green phase and duration of red phase. Next line contains n + 1 integers li (1 ≀ li ≀ 109) β€” the time to pass the i-th road segment in the path from source to destination. Next line contains a single integer q (1 ≀ q ≀ 105) β€” the number of buses in a day. The i-th of next q lines contains a single integer ti (1 ≀ ti ≀ 109) β€” the time when i-th bus leaves the source station.OutputIn the i-th line of output you should print a single integer β€” the time that i-th bus gets to destination.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.ExamplesInput1 3 25 2512345Output89121212Input5 3 710 1 1 8 900000005 100000000031101000000000Output190000004019000000402900000030NoteIn the first sample, buses #1, #2 and #5 will reach the destination without waiting behind the red light. But buses #3 and #4 should wait.In the second sample, first bus should wait at third, fourth and fifth intersections. Second and third buses should wait only at the fifth intersection.
Input1 3 25 2512345
Output89121212
2 seconds
256 megabytes
['data structures', '*2800']
C. Weak Memorytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZart PMP is qualified for ICPC World Finals in Harbin, China. After team excursion to Sun Island Park for snow sculpture art exposition, PMP should get back to buses before they leave. But the park is really big and he does not know how to find them.The park has n intersections numbered 1 through n. There are m bidirectional roads that connect some pairs of these intersections. At k intersections, ICPC volunteers are helping the teams and showing them the way to their destinations. Locations of volunteers are fixed and distinct.When PMP asks a volunteer the way to bus station, he/she can tell him the whole path. But the park is fully covered with ice and snow and everywhere looks almost the same. So PMP can only memorize at most q intersections after each question (excluding the intersection they are currently standing). He always tells volunteers about his weak memory and if there is no direct path of length (in number of roads) at most q that leads to bus station, the volunteer will guide PMP to another volunteer (who is at most q intersections away, of course). ICPC volunteers know the area very well and always tell PMP the best way. So if there exists a way to bus stations, PMP will definitely find it.PMP's initial location is intersection s and the buses are at intersection t. There will always be a volunteer at intersection s. Your job is to find out the minimum q which guarantees that PMP can find the buses.InputThe first line contains three space-separated integers n, m, k (2 ≀ n ≀ 105, 0 ≀ m ≀ 2Β·105, 1 ≀ k ≀ n) β€” the number of intersections, roads and volunteers, respectively. Next line contains k distinct space-separated integers between 1 and n inclusive β€” the numbers of cities where volunteers are located.Next m lines describe the roads. The i-th of these lines contains two space-separated integers ui, vi (1 ≀ ui, vi ≀ n, ui ≠ vi) β€” two intersections that i-th road connects. There will be at most one road between any two intersections.Last line of input contains two space-separated integers s, t (1 ≀ s, t ≀ n, s ≠ t) β€” the initial location of PMP and the location of the buses. It might not always be possible to reach t from s.It is guaranteed that there is always a volunteer at intersection s. OutputPrint on the only line the answer to the problem β€” the minimum value of q which guarantees that PMP can find the buses. If PMP cannot reach the buses at all, output -1 instead.ExamplesInput6 6 31 3 61 22 34 25 64 53 41 6Output3Input6 5 31 5 61 22 33 44 56 31 5Output3NoteThe first sample is illustrated below. Blue intersections are where volunteers are located. If PMP goes in the path of dashed line, it can reach the buses with q = 3: In the second sample, PMP uses intersection 6 as an intermediate intersection, thus the answer is 3.
Input6 6 31 3 61 22 34 25 64 53 41 6
Output3
2 seconds
256 megabytes
['dfs and similar', 'dsu', '*2000']
B. AlgoRacetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPMP is getting a warrior. He is practicing a lot, but the results are not acceptable yet. This time instead of programming contests, he decided to compete in a car racing to increase the spirit of victory. He decides to choose a competition that also exhibits algorithmic features.AlgoRace is a special league of car racing where different teams compete in a country of n cities. Cities are numbered 1 through n. Every two distinct cities in the country are connected with one bidirectional road. Each competing team should introduce one driver and a set of cars.The competition is held in r rounds. In i-th round, drivers will start at city si and finish at city ti. Drivers are allowed to change their cars at most ki times. Changing cars can take place in any city in no time. One car can be used multiple times in one round, but total number of changes should not exceed ki. Drivers can freely choose their path to destination.PMP has prepared m type of purpose-built cars. Beside for PMP’s driving skills, depending on properties of the car and the road, a car traverses each road in each direction in different times. PMP Warriors wants to devise best strategies of choosing car and roads in each round to maximize the chance of winning the cup. For each round they want to find the minimum time required to finish it.InputThe first line contains three space-separated integers n, m, r (2 ≀ n ≀ 60, 1 ≀ m ≀ 60, 1 ≀ r ≀ 105) β€” the number of cities, the number of different types of cars and the number of rounds in the competition, correspondingly.Next m sets of n × n matrices of integers between 0 to 106 (inclusive) will follow β€” describing the time one car requires to traverse different roads. The k-th integer in j-th line of the i-th set is the time that i-th car requires to traverse the road from j-th city to k-th city. These matrices are not necessarily symmetric, but their diagonal is always zero.Next r lines contain description of the rounds. The i-th of these lines contains space-separated integers si, ti, ki (1 ≀ si, ti ≀ n, si ≠ ti, 0 ≀ ki ≀ 1000) β€” the number of starting city, finishing city and the number of possible car changes in i-th round, correspondingly.OutputFor each round you should print the minimum required time to complete the round in a single line.ExamplesInput4 2 30 1 5 62 0 3 61 3 0 16 6 7 00 3 5 62 0 1 61 3 0 26 6 7 01 4 21 4 11 4 3Output343Input4 2 30 7 3 38 0 10 51 1 0 48 9 2 00 3 3 97 0 4 93 8 0 44 8 9 02 3 32 1 31 2 2Output453NoteIn the first sample, in all rounds PMP goes from city #1 to city #2, then city #3 and finally city #4. But the sequences of types of the cars he uses are (1, 2, 1) in the first round and (1, 2, 2) in the second round. In the third round, although he can change his car three times, he uses the same strategy as the first round which only needs two car changes.
Input4 2 30 1 5 62 0 3 61 3 0 16 6 7 00 3 5 62 0 1 61 3 0 26 6 7 01 4 21 4 11 4 3
Output343
2 seconds
256 megabytes
['dp', 'shortest paths', '*1800']
A. Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHappy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second. InputThe first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” the quantity of the numbers in the both given permutations. Next line contains n space-separated integers β€” the first permutation. Each number between 1 to n will appear in the permutation exactly once. Next line describe the second permutation in the same format.OutputPrint a single integer denoting the minimum number of moves required to convert the first permutation to the second.ExamplesInput33 2 11 2 3Output2Input51 2 3 4 51 5 2 3 4Output1Input51 5 2 3 41 2 3 4 5Output3NoteIn the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.In the second sample, he removes number 5 and inserts it after 1.In the third sample, the sequence of changes are like this: 1 5 2 3 4 1 4 5 2 3 1 3 4 5 2 1 2 3 4 5 So he needs three moves.
Input33 2 11 2 3
Output2
2 seconds
256 megabytes
['greedy', '*1500']
B. Growing Mushroomstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).InputThe first input line contains four integer numbers n, t1, t2, k (1 ≀ n, t1, t2 ≀ 1000;Β 1 ≀ k ≀ 100) β€” the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly.Each of the following n lines contains two integers. The i-th (1 ≀ i ≀ n) line contains space-separated integers ai, bi (1 ≀ ai, bi ≀ 1000) β€” the speeds which the participant number i chose.OutputPrint the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.ExamplesInput2 3 3 502 44 2Output1 15.002 15.00Input4 1 1 1544 397280 101280 101693 970Output4 1656.071 937.032 379.993 379.99Note First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2Β·3Β·0.5 + 4Β·3 > 4Β·3Β·0.5 + 2Β·3.
Input2 3 3 502 44 2
Output1 15.002 15.00
2 seconds
256 megabytes
['greedy', 'sortings', '*1200']
A. Comparing Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.InputThe first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters.The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters.The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.OutputPrint "YES", if the dwarves belong to the same race. Otherwise, print "NO".ExamplesInputabbaOutputYESInputaaabOutputNONote First example: you can simply swap two letters in string "ab". So we get "ba". Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b".
Inputabba
OutputYES
2 seconds
256 megabytes
['implementation', 'strings', '*1100']
E. Soap Time! - 2time limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImagine the Cartesian coordinate system. There are k different points containing subway stations. One can get from any subway station to any one instantly. That is, the duration of the transfer between any two subway stations can be considered equal to zero. You are allowed to travel only between subway stations, that is, you are not allowed to leave the subway somewhere in the middle of your path, in-between the stations. There are n dwarves, they are represented by their coordinates on the plane. The dwarves want to come together and watch a soap opera at some integer point on the plane. For that, they choose the gathering point and start moving towards it simultaneously. In one second a dwarf can move from point (x, y) to one of the following points: (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1). Besides, the dwarves can use the subway as many times as they want (the subway transfers the dwarves instantly). The dwarves do not interfere with each other as they move (that is, the dwarves move simultaneously and independently from each other). Help the dwarves and find the minimum time they need to gather at one point.InputThe first line contains two integers n and k (1 ≀ n ≀ 105;Β 0 ≀ k ≀ 105) β€” the number of dwarves and the number of subway stations, correspondingly.The next n lines contain the coordinates of the dwarves. The i-th line contains two space-separated integers xi and yi (|xi|, |yi| ≀ 108) β€” the coordinates of the i-th dwarf. It is guaranteed that all dwarves are located at different points.The next k lines contain the coordinates of the subway stations. The t-th line contains two space-separated integers xt and yt (|xt|, |yt| ≀ 108) β€” the coordinates of the t-th subway station. It is guaranteed that all subway stations are located at different points.OutputPrint a single number β€” the minimum time, in which all dwarves can gather together at one point to watch the soap.ExamplesInput1 02 -2Output0Input2 25 -3-4 -5-4 0-3 -2Output6
Input1 02 -2
Output0
6 seconds
256 megabytes
['binary search', 'data structures', '*3000']
D. Visit of the Greattime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Great Mushroom King descended to the dwarves, but not everyone managed to see him. Only the few chosen ones could see the King.We know that only LCM(k2l + 1, k2l + 1 + 1, ..., k2r + 1) dwarves can see the Great Mushroom King. Numbers k, l, r are chosen by the Great Mushroom King himself in some complicated manner which is unclear to common dwarves. The dwarven historians decided to document all visits of the Great Mushroom King. For each visit the dwarven historians know three integers ki, li, ri, chosen by the Great Mushroom King for this visit. They also know a prime number pi. Help them to count the remainder of dividing the number of dwarves who can see the King, by number pi, for each visit.InputThe first line contains the single integer t (1 ≀ t ≀ 105) β€” the number of the King's visits. Each of the following t input lines contains four space-separated integers ki, li, ri and pi (1 ≀ ki ≀ 106;Β 0 ≀ li ≀ ri ≀ 1018;Β 2 ≀ pi ≀ 109) β€” the numbers, chosen by the Great Mushroom King and the prime module, correspondingly. It is guaranteed that for all visits number pi is prime.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.OutputFor each visit print the answer on a single line β€” the remainder of dividing the number of the dwarves who can see the King this time, by number pi. Print the answers for the visits in the order, in which the visits are described in the input.ExamplesInput23 1 10 25 0 4 3Output00NoteWe consider that LCM(a1, a2, ..., an) represents the least common multiple of numbers a1, a2, ..., an.We consider that x0 = 1, for any x.
Input23 1 10 25 0 4 3
Output00
3 seconds
256 megabytes
['math', 'number theory', '*2600']
C. Clever Fat Rattime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Fat Rat and his friend Π‘erealguy have had a bet whether at least a few oats are going to descend to them by some clever construction. The figure below shows the clever construction. A more formal description of the clever construction is as follows. The clever construction consists of n rows with scales. The first row has n scales, the second row has (n - 1) scales, the i-th row has (n - i + 1) scales, the last row has exactly one scale. Let's number the scales in each row from the left to the right, starting from 1. Then the value of wi, k in kilograms (1 ≀ i ≀ n;Β 1 ≀ k ≀ n - i + 1) is the weight capacity parameter of the k-th scale in the i-th row. If a body whose mass is not less than wi, k falls on the scale with weight capacity wi, k, then the scale breaks. At that anything that the scale has on it, either falls one level down to the left (if possible) or one level down to the right (if possible). In other words, if the scale wi, k (i < n) breaks, then there are at most two possible variants in which the contents of the scale's pan can fall out: all contents of scale wi, k falls either on scale wi + 1, k - 1 (if it exists), or on scale wi + 1, k (if it exists). If scale wn, 1 breaks, then all its contents falls right in the Fat Rat's claws. Please note that the scales that are the first and the last in a row, have only one variant of dropping the contents.Initially, oats are simultaneously put on all scales of the first level. The i-th scale has ai kilograms of oats put on it. After that the scales start breaking and the oats start falling down in some way. You can consider everything to happen instantly. That is, the scale breaks instantly and the oats also fall instantly.The Fat Rat is sure that whatever happens, he will not get the oats from the first level. Cerealguy is sure that there is such a scenario, when the rat gets at least some number of the oats. Help the Fat Rat and the Cerealguy. Determine, which one is right.InputThe first line contains a single integer n (1 ≀ n ≀ 50) β€” the number of rows with scales.The next line contains n space-separated integers ai (1 ≀ ai ≀ 106) β€” the masses of the oats in kilograms.The next n lines contain descriptions of the scales: the i-th line contains (n - i + 1) space-separated integers wi, k (1 ≀ wi, k ≀ 106) β€” the weight capacity parameters for the scales that stand on the i-th row, in kilograms.OutputPrint "Fat Rat" if the Fat Rat is right, otherwise print "Cerealguy".ExamplesInput112OutputFat RatInput22 21 24OutputCerealguyInput22 21 25OutputFat RatNoteNotes to the examples: The first example: the scale with weight capacity 2 gets 1. That means that the lower scale don't break. The second sample: all scales in the top row obviously break. Then the oats fall on the lower row. Their total mass is 4,and that's exactly the weight that the lower scale can "nearly endure". So, as 4  β‰₯  4, the scale breaks.
Input112
OutputFat Rat
2.5 seconds
256 megabytes
['dp', '*2500']
B. Mushroom Scientiststime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (x, y, z). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals xaΒ·ybΒ·zc.To test the metric of mushroom scientists, the usual scientists offered them a task: find such x, y, z (0 ≀ x, y, z;Β x + y + z ≀ S), that the distance between the center of the Universe and the point (x, y, z) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.Note that in this problem, it is considered that 00 = 1.InputThe first line contains a single integer S (1 ≀ S ≀ 103) β€” the maximum sum of coordinates of the sought point.The second line contains three space-separated integers a, b, c (0 ≀ a, b, c ≀ 103) β€” the numbers that describe the metric of mushroom scientists.OutputPrint three real numbers β€” the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations.A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10 - 6. We think that ln(0) =  -β€‰βˆž.ExamplesInput31 1 1Output1.0 1.0 1.0Input32 0 0Output3.0 0.0 0.0
Input31 1 1
Output1.0 1.0 1.0
2 seconds
256 megabytes
['math', 'ternary search', '*1800']
A. Planttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process. Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.InputThe first line contains a single integer n (0 ≀ n ≀ 1018) β€” the number of full years when the plant grew.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.OutputPrint a single integer β€” the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).ExamplesInput1Output3Input2Output10NoteThe first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.
Input1
Output3
2 seconds
256 megabytes
['math', '*1300']
E. Candy Shoptime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe prestigious Codeforces kindergarten consists of n kids, numbered 1 through n. Each of them are given allowance in rubles by their parents.Today, they are going to the most famous candy shop in the town. The shop sells candies in packages: for all i between 1 and m, inclusive, it sells a package containing exactly i candies. A candy costs one ruble, so a package containing x candies costs x rubles.The kids will purchase candies in turns, starting from kid 1. In a single turn, kid i will purchase one candy package. Due to the highly competitive nature of Codeforces kindergarten, during a turn, the number of candies contained in the package purchased by the kid will always be strictly greater than the number of candies contained in the package purchased by the kid in the preceding turn (an exception is in the first turn: the first kid may purchase any package). Then, the turn proceeds to kid i + 1, or to kid 1 if it was kid n's turn. This process can be ended at any time, but at the end of the purchase process, all the kids must have the same number of candy packages. Of course, the amount spent by each kid on the candies cannot exceed their allowance.You work at the candy shop and would like to prepare the candies for the kids. Print the maximum number of candies that can be sold by the candy shop to the kids. If the kids cannot purchase any candy (due to insufficient allowance), print 0.InputThe first line contains two space-separated integers n and m (2 ≀ n ≀ 2Β·105, 2 ≀ m ≀ 5Β·106, n ≀ m), denoting the number of kids and the maximum number of candies in a package sold by the candy shop, respectively.Then n lines follow, each line will contain a single positive integer not exceeding denoting the allowance of a kid in rubles. The allowances are given in order from kid 1 to kid n.Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is recommended to use cin, cout streams (also you may use %I64d specificator).OutputPrint a single integer denoting the maximum number of candies that can be sold by the candy shop.ExamplesInput2 5510Output13Input3 881613Output32Input2 50000001250000250000012500002500000Output12500002500000NoteFor the first example, one of the scenarios that will result in 13 purchased candies is as follows. Turn 1. Kid 1 purchases 1 candy. Turn 2. Kid 2 purchases 3 candies. Turn 3. Kid 1 purchases 4 candies. Turn 4. Kid 2 purchases 5 candies.
Input2 5510
Output13
3 seconds
256 megabytes
['greedy', '*2900']
D. T-shirttime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are going to work in Codeforces as an intern in a team of n engineers, numbered 1 through n. You want to give each engineer a souvenir: a T-shirt from your country (T-shirts are highly desirable in Codeforces). Unfortunately you don't know the size of the T-shirt each engineer fits in. There are m different sizes, numbered 1 through m, and each engineer will fit in a T-shirt of exactly one size.You don't know the engineers' exact sizes, so you asked your friend, Gerald. Unfortunately, he wasn't able to obtain the exact sizes either, but he managed to obtain for each engineer i and for all sizes j, the probability that the size of the T-shirt that fits engineer i is j.Since you're planning to give each engineer one T-shirt, you are going to bring with you exactly n T-shirts. For those n T-shirts, you can bring any combination of sizes (you can bring multiple T-shirts with the same size too!). You don't know the sizes of T-shirts for each engineer when deciding what sizes to bring, so you have to pick this combination based only on the probabilities given by your friend, Gerald. Your task is to maximize the expected number of engineers that receive a T-shirt of his size. This is defined more formally as follows. When you finally arrive at the office, you will ask each engineer his T-shirt size. Then, if you still have a T-shirt of that size, you will give him one of them. Otherwise, you don't give him a T-shirt. You will ask the engineers in order starting from engineer 1, then engineer 2, and so on until engineer n.InputThe first line contains two space-separated integers n and m (1 ≀ n ≀ 3000, 1 ≀ m ≀ 300), denoting the number of engineers and the number of T-shirt sizes, respectively.Then n lines follow, each line contains m space-separated integers. The j-th integer in the i-th line represents the probability that the i-th engineer fits in a T-shirt of size j. Each probability will be given as an integer between 0 and 1000, inclusive. The actual probability should be calculated as the given number divided by 1000. It is guaranteed that for any engineer, the sum of the probabilities for all m T-shirts is equal to one.OutputPrint a single real number denoting the maximum possible expected number of engineers that will receive a T-shirt.For the answer the absolute or relative error of 10 - 9 is acceptable.ExamplesInput2 2500 500500 500Output1.500000000000Input3 31000 0 01000 0 00 1000 0Output3.000000000000Input1 4100 200 300 400Output0.400000000000NoteFor the first example, bring one T-shirt of each size. With 0.5 chance, either both engineers fit inside T-shirts of size 1 or both fit inside T-shirts of size 2. With the other 0.5 chance, one engineer fits inside a T-shirt of size 1 and the other inside a T-shirt of size 2. If the first is true, the number of engineers that receive a T-shirt is one. If the second is true, the number of such engineers is two. Hence, the expected number of engineers who receive a T-shirt is 1.5. This is maximum possible expected number of engineers for all sets of T-shirts. For the second example, bring two T-shirts of size 1 and one T-shirt of size 2. This way, each engineer will definitely receive a T-shirt of his size.For the third example, bring one T-shirt of size 4.
Input2 2500 500500 500
Output1.500000000000
5 seconds
256 megabytes
['dp', 'greedy', 'probabilities', '*2700']
C. Cyclic Coloringtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed graph G with n vertices and m arcs (multiple arcs and self-loops are allowed). You have to paint each vertex of the graph into one of the k (k ≀ n) colors in such way that for all arcs of the graph leading from a vertex u to vertex v, vertex v is painted with the next color of the color used to paint vertex u.The colors are numbered cyclically 1 through k. This means that for each color i (i < k) its next color is color i + 1. In addition, the next color of color k is color 1. Note, that if k = 1, then the next color for color 1 is again color 1.Your task is to find and print the largest possible value of k (k ≀ n) such that it's possible to color G as described above with k colors. Note that you don't necessarily use all the k colors (that is, for each color i there does not necessarily exist a vertex that is colored with color i).InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105), denoting the number of vertices and the number of arcs of the given digraph, respectively.Then m lines follow, each line will contain two space-separated integers ai and bi (1 ≀ ai, bi ≀ n), which means that the i-th arc goes from vertex ai to vertex bi.Multiple arcs and self-loops are allowed.OutputPrint a single integer β€” the maximum possible number of the colors that can be used to paint the digraph (i.e. k, as described in the problem statement). Note that the desired value of k must satisfy the inequality 1 ≀ k ≀ n.ExamplesInput4 41 22 13 44 3Output2Input5 21 42 5Output5Input4 51 22 33 12 44 1Output3Input4 41 11 22 11 2Output1NoteFor the first example, with k = 2, this picture depicts the two colors (arrows denote the next color of that color). With k = 2 a possible way to paint the graph is as follows. It can be proven that no larger value for k exists for this test case.For the second example, here's the picture of the k = 5 colors. A possible coloring of the graph is: For the third example, here's the picture of the k = 3 colors. A possible coloring of the graph is:
Input4 41 22 13 44 3
Output2
4 seconds
256 megabytes
['dfs and similar', '*2200']
B. Zootime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move.In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line.Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.InputThe first line contains two space-separated integers n and m (1 ≀ n ≀ 106, 1 ≀ m ≀ 250), denoting the number of binoculars and the number of flamingos, respectively.Then m lines follow, the i-th line will contain two space-separated integers xi and yi (1 ≀ xi, yi ≀ 109), which means that the i-th flamingo is located at point (xi, yi). All flamingos will be located at distinct points.OutputPrint a single integer denoting the maximum total number of flamingos that can be seen by all the binoculars.ExamplesInput5 52 14 13 24 34 4Output11NoteThis picture shows the answer to the example test case.
Input5 52 14 13 24 34 4
Output11
2 seconds
256 megabytes
['brute force', 'geometry', '*1700']
A. Headquarterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x, y) to one of these four points: to point (x - 1, y) which we will mark by letter "L", to point (x + 1, y) β€” "R", to point (x, y - 1) β€” "D", to point (x, y + 1) β€” "U".The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0, 0), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).InputThe first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” the number of the car's movements from the headquarters to the stall.Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: "UL", "UR", "DL", "DR" or "ULDR". All movements are given in chronological order. Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.OutputPrint a single integer β€” the number of different possible locations of the gang's headquarters.ExamplesInput3URULULDROutput9Input2DRDLOutput4NoteThe figure below shows the nine possible positions of the gang headquarters from the first sample: For example, the following movements can get the car from point (1, 0) to point (0, 0):
Input3URULULDR
Output9
2 seconds
256 megabytes
['constructive algorithms', 'math', '*1700']
E. Wooden Fencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has recently bought some land and decided to surround it with a wooden fence.He went to a company called "Wooden board" that produces wooden boards for fences. Vasya read in the catalog of products that the company has at its disposal n different types of wood. The company uses the i-th type of wood to produce a board of this type that is a rectangular ai by bi block.Vasya decided to order boards in this company and build a fence from them. It turned out that the storehouse of the company is so large that Vasya can order arbitrary number of boards of every type. Note that Vasya is allowed to turn the boards as he builds the fence. However, Vasya cannot turn square boards.Vasya is required to construct a fence of length l, however, an arbitrary fence won't do. Vasya wants his fence to look beautiful. We'll say that a fence is beautiful if and only if the following two conditions are fulfilled: there are no two successive boards of the same type the first board of the fence has an arbitrary length, and the length of each subsequent board equals the width of the previous one In other words, the fence is considered beautiful, if the type of the i-th board in the fence is different from the i - 1-th board's type; besides, the i-th board's length is equal to the i - 1-th board's width (for all i, starting from 2).Now Vasya wonders, how many variants of arranging a fence for his land exist. Your task is to count the number of different beautiful fences of length l.Two fences will be considered the same if the corresponding sequences of fence boards types and rotations are the same, otherwise the fences are different. Since the sought number can be large enough, you need to calculate the answer modulo 1000000007 (109 + 7).InputThe first line contains two integers n and l (1 ≀ n ≀ 100, 1 ≀ l ≀ 3000) β€” the number of different board types and the fence length, correspondingly. Next n lines contain descriptions of board types: the i-th line contains two integers ai and bi (1 ≀ ai, bi ≀ 100) β€” the sizes of the board of the i-th type. All numbers on the lines are separated by spaces.OutputPrint a single integer β€” the sought number of variants modulo 1000000007 (109 + 7).ExamplesInput2 31 22 3Output2Input1 22 2Output1Input6 62 13 22 53 35 12 1Output20NoteIn the first sample there are exactly two variants of arranging a beautiful fence of length 3: As the first fence board use the board of the first type of length 1 and width 2. As the second board use board of the second type of length 2 and width 3. Use one board of the second type after you turn it. That makes its length equal 3, and width β€” 2.
Input2 31 22 3
Output2
3 seconds
256 megabytes
['dp', '*1800']
D. Common Divisorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has recently learned at school what a number's divisor is and decided to determine a string's divisor. Here is what he came up with.String a is the divisor of string b if and only if there exists a positive integer x such that if we write out string a consecutively x times, we get string b. For example, string "abab" has two divisors β€” "ab" and "abab".Now Vasya wants to write a program that calculates the number of common divisors of two strings. Please help him.InputThe first input line contains a non-empty string s1.The second input line contains a non-empty string s2.Lengths of strings s1 and s2 are positive and do not exceed 105. The strings only consist of lowercase Latin letters.OutputPrint the number of common divisors of strings s1 and s2. ExamplesInputabcdabcdabcdabcdabcdabcdOutput2InputaaaaaOutput1NoteIn first sample the common divisors are strings "abcd" and "abcdabcd".In the second sample the common divisor is a single string "a". String "aa" isn't included in the answer as it isn't a divisor of string "aaa".
Inputabcdabcdabcdabcdabcdabcd
Output2
2 seconds
256 megabytes
['brute force', 'hashing', 'implementation', 'math', 'strings', '*1400']
C. Optimal Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnd here goes another problem on arrays. You are given positive integer len and array a which consists of n integers a1, a2, ..., an. Let's introduce two characteristics for the given array. Let's consider an arbitrary interval of the array with length len, starting in position i. Value , is the modular sum on the chosen interval. In other words, the modular sum is the sum of integers on the chosen interval with length len, taken in its absolute value. Value is the optimal sum of the array. In other words, the optimal sum of an array is the maximum of all modular sums on various intervals of array with length len. Your task is to calculate the optimal sum of the given array a. However, before you do the calculations, you are allowed to produce no more than k consecutive operations of the following form with this array: one operation means taking an arbitrary number from array ai and multiply it by -1. In other words, no more than k times you are allowed to take an arbitrary number ai from the array and replace it with  - ai. Each number of the array is allowed to choose an arbitrary number of times.Your task is to calculate the maximum possible optimal sum of the array after at most k operations described above are completed.InputThe first line contains two integers n, len (1 ≀ len ≀ n ≀ 105) β€” the number of elements in the array and the length of the chosen subinterval of the array, correspondingly. The second line contains a sequence consisting of n integers a1, a2, ..., an (|ai| ≀ 109) β€” the original array. The third line contains a single integer k (0 ≀ k ≀ n) β€” the maximum allowed number of operations. All numbers in lines are separated by a single space.OutputIn a single line print the maximum possible optimal sum after no more than k acceptable operations are fulfilled. 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.ExamplesInput5 30 -2 3 -5 12Output10Input5 21 -3 -10 4 13Output14Input3 3-2 -5 41Output11
Input5 30 -2 3 -5 12
Output10
2 seconds
256 megabytes
['data structures', 'greedy', '*2000']
B. Vasya's Calendartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present β€” the clock that shows not only the time, but also the date.The clock's face can display any number from 1 to d. It is guaranteed that ai ≀ d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d + 1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1.Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1.InputThe first line contains the single number d β€” the maximum number of the day that Vasya's clock can show (1 ≀ d ≀ 106).The second line contains a single integer n β€” the number of months in the year (1 ≀ n ≀ 2000).The third line contains n space-separated integers: ai (1 ≀ ai ≀ d) β€” the number of days in each month in the order in which they follow, starting from the first one. OutputPrint a single number β€” the number of times Vasya manually increased the day number by one throughout the last year.ExamplesInput422 2Output2Input533 4 3Output3Input311231 28 31 30 31 30 31 31 30 31 30 31Output7NoteIn the first sample the situation is like this: Day 1. Month 1. The clock shows 1. Vasya changes nothing. Day 2. Month 1. The clock shows 2. Vasya changes nothing. Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1. Day 2. Month 2. The clock shows 2. Vasya changes nothing. In total, Vasya manually changed the day number by 1 exactly 2 times.
Input422 2
Output2
1 second
256 megabytes
['implementation', '*1000']
A. Battlefieldtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya lagged behind at the University and got to the battlefield. Just joking! He's simply playing some computer game. The field is a flat platform with n trenches dug on it. The trenches are segments on a plane parallel to the coordinate axes. No two trenches intersect.There is a huge enemy laser far away from Vasya. The laser charges for a seconds, and then shoots continuously for b seconds. Then, it charges for a seconds again. Then it shoots continuously for b seconds again and so on. Vasya knows numbers a and b. He also knows that while the laser is shooting, Vasya must be in the trench, but while the laser is charging, Vasya can safely move around the field. The main thing is to have time to hide in the trench before the shot. If Vasya reaches the trench exactly at the moment when the laser starts shooting, we believe that Vasya managed to hide. Coincidentally, the length of any trench in meters numerically does not exceed b.Initially, Vasya is at point A. He needs to get to point B. Vasya moves at speed 1 meter per second in either direction. You can get in or out of the trench at any its point. Getting in or out of the trench takes no time. It is also possible to move in the trench, without leaving it.What is the minimum time Vasya needs to get from point A to point B, if at the initial time the laser has just started charging? If Vasya cannot get from point A to point B, print -1. If Vasya reaches point B at the moment when the laser begins to shoot, it is believed that Vasya managed to reach point B.InputThe first line contains two space-separated integers: a and b (1 ≀ a, b ≀ 1000), β€” the duration of charging and the duration of shooting, in seconds.The second line contains four space-separated integers: Ax, Ay, Bx, By ( - 104 ≀ Ax, Ay, Bx, By ≀ 104) β€” the coordinates of points А and B. It is guaranteed that points A and B do not belong to any trench.The third line contains a single integer: n (1 ≀ n ≀ 1000), β€” the number of trenches. Each of the following n lines contains four space-separated integers: x1, y1, x2, y2 ( - 104 ≀ xi, yi ≀ 104) β€” the coordinates of ends of the corresponding trench.All coordinates are given in meters. It is guaranteed that for any trench either x1 = x2, or y1 = y2. No two trenches intersect. The length of any trench in meters doesn't exceed b numerically.OutputIf Vasya can get from point A to point B, print the minimum time he will need for it. Otherwise, print number -1.The answer will be considered correct if the absolute or relative error does not exceed 10 - 4ExamplesInput2 40 5 6 530 0 0 41 1 4 16 0 6 4Output19.0000000000Input5 100 0 10 1015 0 5 9Output-1
Input2 40 5 6 530 0 0 41 1 4 16 0 6 4
Output19.0000000000
2 seconds
256 megabytes
['geometry', 'graphs', 'implementation', 'shortest paths', '*2200']
B. Number of Tripletstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points on a plane. All points are different.Find the number of different groups of three points (A, B, C) such that point B is the middle of segment AC. The groups of three points are considered unordered, that is, if point B is the middle of segment AC, then groups (A, B, C) and (C, B, A) are considered the same.InputThe first line contains a single integer n (3 ≀ n ≀ 3000) β€” the number of points. Next n lines contain the points. The i-th line contains coordinates of the i-th point: two space-separated integers xi, yi ( - 1000 ≀ xi, yi ≀ 1000).It is guaranteed that all given points are different.OutputPrint the single number β€” the answer to the problem. ExamplesInput31 12 23 3Output1Input30 0-1 00 1Output0
Input31 12 23 3
Output1
2 seconds
256 megabytes
['binary search', 'brute force', '*1300']
A. Series of Crimestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.The Berland capital's map is represented by an n × m rectangular table. Each cell of the table on the map represents some districts of the capital. The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map. Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.InputThe first line contains two space-separated integers n and m (2 ≀ n, m ≀ 100) β€” the number of rows and columns in the table, correspondingly.Each of the next n lines contains m characters β€” the description of the capital's map. Each character can either be a "." (dot), or an "*" (asterisk). A character equals "*" if the corresponding district has been robbed. Otherwise, it equals ".".It is guaranteed that the map has exactly three characters "*" and we can always find the fourth district that meets the problem requirements. OutputPrint two integers β€” the number of the row and the number of the column of the city district that is the fourth one to be robbed. The rows are numbered starting from one from top to bottom and the columns are numbered starting from one from left to right.ExamplesInput3 2.*..**Output1 1Input3 3*.**.....Output2 3
Input3 2.*..**
Output1 1
2 seconds
256 megabytes
['brute force', 'geometry', 'implementation', '*800']
F. Mathematical Analysis Rocks!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudents of group 199 have written their lectures dismally. Now an exam on Mathematical Analysis is approaching and something has to be done asap (that is, quickly). Let's number the students of the group from 1 to n. Each student i (1 ≀ i ≀ n) has a best friend p[i] (1 ≀ p[i] ≀ n). In fact, each student is a best friend of exactly one student. In other words, all p[i] are different. It is possible that the group also has some really "special individuals" for who i = p[i].Each student wrote exactly one notebook of lecture notes. We know that the students agreed to act by the following algorithm: on the first day of revising each student studies his own Mathematical Analysis notes, in the morning of each following day each student gives the notebook to his best friend and takes a notebook from the student who calls him the best friend. Thus, on the second day the student p[i] (1 ≀ i ≀ n) studies the i-th student's notes, on the third day the notes go to student p[p[i]] and so on. Due to some characteristics of the boys' friendship (see paragraph 1), each day each student has exactly one notebook to study.You are given two sequences that describe the situation on the third and fourth days of revising: a1, a2, ..., an, where ai means the student who gets the i-th student's notebook on the third day of revising; b1, b2, ..., bn, where bi means the student who gets the i-th student's notebook on the fourth day of revising. You do not know array p, that is you do not know who is the best friend to who. Write a program that finds p by the given sequences a and b.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of students in the group. The second line contains sequence of different integers a1, a2, ..., an (1 ≀ ai ≀ n). The third line contains the sequence of different integers b1, b2, ..., bn (1 ≀ bi ≀ n).OutputPrint sequence n of different integers p[1], p[2], ..., p[n] (1 ≀ p[i] ≀ n). It is guaranteed that the solution exists and that it is unique.ExamplesInput42 1 4 33 4 2 1Output4 3 1 2 Input55 2 3 1 41 3 2 4 5Output4 3 2 5 1 Input21 22 1Output2 1
Input42 1 4 33 4 2 1
Output4 3 1 2
1 second
256 megabytes
['constructive algorithms', 'implementation', 'math', '*1200']
E. Cubestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's imagine that you're playing the following simple computer game. The screen displays n lined-up cubes. Each cube is painted one of m colors. You are allowed to delete not more than k cubes (that do not necessarily go one after another). After that, the remaining cubes join together (so that the gaps are closed) and the system counts the score. The number of points you score equals to the length of the maximum sequence of cubes of the same color that follow consecutively. Write a program that determines the maximum possible number of points you can score.Remember, you may delete no more than k any cubes. It is allowed not to delete cubes at all.InputThe first line contains three integers n, m and k (1 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 105, 0 ≀ k < n). The second line contains n integers from 1 to m β€” the numbers of cube colors. The numbers of colors are separated by single spaces.OutputPrint the maximum possible number of points you can score.ExamplesInput10 3 21 2 1 1 3 2 1 1 2 2Output4Input10 2 21 2 1 2 1 1 2 1 1 2Output5Input3 1 21 1 1Output3NoteIn the first sample you should delete the fifth and the sixth cubes.In the second sample you should delete the fourth and the seventh cubes.In the third sample you shouldn't delete any cubes.
Input10 3 21 2 1 1 3 2 1 1 2 2
Output4
1 second
256 megabytes
['binary search', 'dp', 'two pointers', '*1800']
D. Nametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t.On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that.The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct: n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"), p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≀ k ≀ min(n, m)), here characters in strings are numbered starting from 1. Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum.InputThe first line contains a non-empty string s (1 ≀ |s| ≀ 5000), where |s| is its length. The second line contains a non-empty string t (1 ≀ |t| ≀ 5000), where |t| is its length. Both strings consist of lowercase Latin letters.OutputPrint the sought name or -1 if it doesn't exist.ExamplesInputaadaacOutputaadInputabadbobOutputdaabInputabcdefgOutput-1InputczaaababcdefOutputabczaaNoteIn the first sample the given string s is the sought one, consequently, we do not need to change the letter order there.
Inputaadaac
Outputaad
1 second
256 megabytes
['greedy', 'strings', '*1900']
C. Lettertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPatrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then β€” zero or more lowercase letters.To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.InputThe only line of the input contains a non-empty string consisting of uppercase and lowercase letters. The string's length does not exceed 105.OutputPrint a single number β€” the least number of actions needed to make the message fancy.ExamplesInputPRuvetSTAaYAOutput5InputOYPROSTIYAOPECHATALSYAPRIVETSTASYAOutput0InputhelloworldOutput0
InputPRuvetSTAaYA
Output5
1 second
256 megabytes
['dp', '*1400']
B. Divisibility Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya studies divisibility rules at school. Here are some of them: Divisibility by 2. A number is divisible by 2 if and only if its last digit is divisible by 2 or in other words, is even. Divisibility by 3. A number is divisible by 3 if and only if the sum of its digits is divisible by 3. Divisibility by 4. A number is divisible by 4 if and only if its last two digits form a number that is divisible by 4. Divisibility by 5. A number is divisible by 5 if and only if its last digit equals 5 or 0. Divisibility by 6. A number is divisible by 6 if and only if it is divisible by 2 and 3 simultaneously (that is, if the last digit is even and the sum of all digits is divisible by 3). Divisibility by 7. Vasya doesn't know such divisibility rule. Divisibility by 8. A number is divisible by 8 if and only if its last three digits form a number that is divisible by 8. Divisibility by 9. A number is divisible by 9 if and only if the sum of its digits is divisible by 9. Divisibility by 10. A number is divisible by 10 if and only if its last digit is a zero. Divisibility by 11. A number is divisible by 11 if and only if the sum of digits on its odd positions either equals to the sum of digits on the even positions, or they differ in a number that is divisible by 11.Vasya got interested by the fact that some divisibility rules resemble each other. In fact, to check a number's divisibility by 2, 4, 5, 8 and 10 it is enough to check fulfiling some condition for one or several last digits. Vasya calls such rules the 2-type rules.If checking divisibility means finding a sum of digits and checking whether the sum is divisible by the given number, then Vasya calls this rule the 3-type rule (because it works for numbers 3 and 9).If we need to find the difference between the sum of digits on odd and even positions and check whether the difference is divisible by the given divisor, this rule is called the 11-type rule (it works for number 11).In some cases we should divide the divisor into several factors and check whether rules of different types (2-type, 3-type or 11-type) work there. For example, for number 6 we check 2-type and 3-type rules, for number 66 we check all three types. Such mixed divisibility rules are called 6-type rules. And finally, there are some numbers for which no rule works: neither 2-type, nor 3-type, nor 11-type, nor 6-type. The least such number is number 7, so we'll say that in such cases the mysterious 7-type rule works, the one that Vasya hasn't discovered yet. Vasya's dream is finding divisibility rules for all possible numbers. He isn't going to stop on the decimal numbers only. As there are quite many numbers, ha can't do it all by himself. Vasya asked you to write a program that determines the divisibility rule type in the b-based notation for the given divisor d.InputThe first input line contains two integers b and d (2 ≀ b, d ≀ 100) β€” the notation system base and the divisor. Both numbers are given in the decimal notation.OutputOn the first output line print the type of the rule in the b-based notation system, where the divisor is d: "2-type", "3-type", "11-type", "6-type" or "7-type". If there are several such types, print the one that goes earlier in the given sequence. If a number belongs to the 2-type, print on the second line the least number of the last b-based digits that we will need to use to check the divisibility.ExamplesInput10 10Output2-type1Input2 3Output11-typeNoteThe divisibility rule for number 3 in binary notation looks as follows: "A number is divisible by 3 if and only if the sum of its digits that occupy the even places differs from the sum of digits that occupy the odd places, in a number that is divisible by 3". That's an 11-type rule. For example, 2110 = 101012. For it the sum of digits on odd positions equals 1 + 1 + 1 = 3, an on even positions β€” 0 + 0 = 0. The rule works and the number is divisible by 3. In some notations a number can fit into the 3-type rule and the 11-type rule. In this case the correct answer is "3-type".
Input10 10
Output2-type1
1 second
256 megabytes
['math', 'number theory', '*2300']
A. Defragmentationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you have to implement an algorithm to defragment your hard disk. The hard disk consists of a sequence of clusters, numbered by integers from 1 to n. The disk has m recorded files, the i-th file occupies clusters with numbers ai, 1, ai, 2, ..., ai, ni. These clusters are not necessarily located consecutively on the disk, but the order in which they are given corresponds to their sequence in the file (cluster ai, 1 contains the first fragment of the i-th file, cluster ai, 2 has the second fragment, etc.). Also the disc must have one or several clusters which are free from files.You are permitted to perform operations of copying the contents of cluster number i to cluster number j (i and j must be different). Moreover, if the cluster number j used to keep some information, it is lost forever. Clusters are not cleaned, but after the defragmentation is complete, some of them are simply declared unusable (although they may possibly still contain some fragments of files).Your task is to use a sequence of copy operations to ensure that each file occupies a contiguous area of memory. Each file should occupy a consecutive cluster section, the files must follow one after another from the beginning of the hard disk. After defragmentation all free (unused) clusters should be at the end of the hard disk. After defragmenting files can be placed in an arbitrary order. Clusters of each file should go consecutively from first to last. See explanatory examples in the notes.Print the sequence of operations leading to the disk defragmentation. Note that you do not have to minimize the number of operations, but it should not exceed 2n.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 200) β€” the number of clusters and the number of files, correspondingly. Next m lines contain descriptions of the files. The first number in the line is ni (ni β‰₯ 1), the number of clusters occupied by the i-th file. Then follow ni numbers ai, 1, ai, 2, ..., ai, ni (1 ≀ ai, j ≀ n). It is guaranteed that each cluster number occurs not more than once and , that is, there exists at least one unused cluster. Numbers on each line are separated by spaces. OutputIn the first line print a single integer k (0 ≀ k ≀ 2n) β€” the number of operations needed to defragment the disk. Next k lines should contain the operations' descriptions as "i j" (copy the contents of the cluster number i to the cluster number j). ExamplesInput7 22 1 23 3 4 5Output0Input7 22 1 33 2 4 5Output32 63 26 3NoteLet's say that a disk consists of 8 clusters and contains two files. The first file occupies two clusters and the second file occupies three clusters. Let's look at examples of correct and incorrect positions of files after defragmentation. Example 2: each file must occupy a contiguous area of memory.Example 3: the order of files to each other is not important, at first the second file can be written, and then β€” the first one.Example 4: violating the order of file fragments to each other is not allowed.Example 5: unused clusters should be located at the end, and in this example the unused clusters are 3, 7, 8.
Input7 22 1 23 3 4 5
Output0
1 second
256 megabytes
['implementation', '*1800']
F3. Representative Samplingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has a long history of cooperating with the "Institute of Cytology and Genetics". Recently, the Institute staff challenged the Beaver with a new problem. The problem is as follows.There is a collection of n proteins (not necessarily distinct). Each protein is a string consisting of lowercase Latin letters. The problem that the scientists offered to the Beaver is to select a subcollection of size k from the initial collection of proteins so that the representativity of the selected subset of proteins is maximum possible.The Smart Beaver from ABBYY did some research and came to the conclusion that the representativity of a collection of proteins can be evaluated by a single number, which is simply calculated. Let's suppose we have a collection {a1, ..., ak} consisting of k strings describing proteins. The representativity of this collection is the following value: where f(x, y) is the length of the longest common prefix of strings x and y; for example, f("abc", "abd") = 2, and f("ab", "bcd") = 0.Thus, the representativity of collection of proteins {"abc", "abd", "abe"} equals 6, and the representativity of collection {"aaa", "ba", "ba"} equals 2.Having discovered that, the Smart Beaver from ABBYY asked the Cup contestants to write a program that selects, from the given collection of proteins, a subcollection of size k which has the largest possible value of representativity. Help him to solve this problem!InputThe first input line contains two integers n and k (1 ≀ k ≀ n), separated by a single space. The following n lines contain the descriptions of proteins, one per line. Each protein is a non-empty string of no more than 500 characters consisting of only lowercase Latin letters (a...z). Some of the strings may be equal.The input limitations for getting 20 points are: 1 ≀ n ≀ 20 The input limitations for getting 50 points are: 1 ≀ n ≀ 100 The input limitations for getting 100 points are: 1 ≀ n ≀ 2000 OutputPrint a single number denoting the largest possible value of representativity that a subcollection of size k of the given collection of proteins can have.ExamplesInput3 2ababzdabqOutput2Input4 3eeerrrtttqqqOutput0Input4 3aaaabbaabbcabbdOutput9
Input3 2ababzdabq
Output2
2 seconds
256 megabytes
['*2500']
F2. Representative Samplingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has a long history of cooperating with the "Institute of Cytology and Genetics". Recently, the Institute staff challenged the Beaver with a new problem. The problem is as follows.There is a collection of n proteins (not necessarily distinct). Each protein is a string consisting of lowercase Latin letters. The problem that the scientists offered to the Beaver is to select a subcollection of size k from the initial collection of proteins so that the representativity of the selected subset of proteins is maximum possible.The Smart Beaver from ABBYY did some research and came to the conclusion that the representativity of a collection of proteins can be evaluated by a single number, which is simply calculated. Let's suppose we have a collection {a1, ..., ak} consisting of k strings describing proteins. The representativity of this collection is the following value: where f(x, y) is the length of the longest common prefix of strings x and y; for example, f("abc", "abd") = 2, and f("ab", "bcd") = 0.Thus, the representativity of collection of proteins {"abc", "abd", "abe"} equals 6, and the representativity of collection {"aaa", "ba", "ba"} equals 2.Having discovered that, the Smart Beaver from ABBYY asked the Cup contestants to write a program that selects, from the given collection of proteins, a subcollection of size k which has the largest possible value of representativity. Help him to solve this problem!InputThe first input line contains two integers n and k (1 ≀ k ≀ n), separated by a single space. The following n lines contain the descriptions of proteins, one per line. Each protein is a non-empty string of no more than 500 characters consisting of only lowercase Latin letters (a...z). Some of the strings may be equal.The input limitations for getting 20 points are: 1 ≀ n ≀ 20 The input limitations for getting 50 points are: 1 ≀ n ≀ 100 The input limitations for getting 100 points are: 1 ≀ n ≀ 2000 OutputPrint a single number denoting the largest possible value of representativity that a subcollection of size k of the given collection of proteins can have.ExamplesInput3 2ababzdabqOutput2Input4 3eeerrrtttqqqOutput0Input4 3aaaabbaabbcabbdOutput9
Input3 2ababzdabq
Output2
2 seconds
256 megabytes
['dp', 'sortings', 'strings', '*2200']
F1. Representative Samplingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has a long history of cooperating with the "Institute of Cytology and Genetics". Recently, the Institute staff challenged the Beaver with a new problem. The problem is as follows.There is a collection of n proteins (not necessarily distinct). Each protein is a string consisting of lowercase Latin letters. The problem that the scientists offered to the Beaver is to select a subcollection of size k from the initial collection of proteins so that the representativity of the selected subset of proteins is maximum possible.The Smart Beaver from ABBYY did some research and came to the conclusion that the representativity of a collection of proteins can be evaluated by a single number, which is simply calculated. Let's suppose we have a collection {a1, ..., ak} consisting of k strings describing proteins. The representativity of this collection is the following value: where f(x, y) is the length of the longest common prefix of strings x and y; for example, f("abc", "abd") = 2, and f("ab", "bcd") = 0.Thus, the representativity of collection of proteins {"abc", "abd", "abe"} equals 6, and the representativity of collection {"aaa", "ba", "ba"} equals 2.Having discovered that, the Smart Beaver from ABBYY asked the Cup contestants to write a program that selects, from the given collection of proteins, a subcollection of size k which has the largest possible value of representativity. Help him to solve this problem!InputThe first input line contains two integers n and k (1 ≀ k ≀ n), separated by a single space. The following n lines contain the descriptions of proteins, one per line. Each protein is a non-empty string of no more than 500 characters consisting of only lowercase Latin letters (a...z). Some of the strings may be equal.The input limitations for getting 20 points are: 1 ≀ n ≀ 20 The input limitations for getting 50 points are: 1 ≀ n ≀ 100 The input limitations for getting 100 points are: 1 ≀ n ≀ 2000 OutputPrint a single number denoting the largest possible value of representativity that a subcollection of size k of the given collection of proteins can have.ExamplesInput3 2ababzdabqOutput2Input4 3eeerrrtttqqqOutput0Input4 3aaaabbaabbcabbdOutput9
Input3 2ababzdabq
Output2
2 seconds
256 megabytes
['*1800']
D3. Magic Squarestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.The magic square is a matrix of size n × n. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number s. The sum of numbers in each column of the matrix is also equal to s. In addition, the sum of the elements on the main diagonal is equal to s and the sum of elements on the secondary diagonal is equal to s. Examples of magic squares are given in the following figure: Magic squares You are given a set of n2 integers ai. It is required to place these numbers into a square matrix of size n × n so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.It is guaranteed that a solution exists!InputThe first input line contains a single integer n. The next line contains n2 integers ai ( - 108 ≀ ai ≀ 108), separated by single spaces.The input limitations for getting 20 points are: 1 ≀ n ≀ 3 The input limitations for getting 50 points are: 1 ≀ n ≀ 4 It is guaranteed that there are no more than 9 distinct numbers among ai. The input limitations for getting 100 points are: 1 ≀ n ≀ 4 OutputThe first line of the output should contain a single integer s. In each of the following n lines print n integers, separated by spaces and describing the resulting magic square. In the resulting magic square the sums in the rows, columns and diagonals must be equal to s. If there are multiple solutions, you are allowed to print any of them.ExamplesInput31 2 3 4 5 6 7 8 9Output152 7 69 5 14 3 8Input31 0 -1 0 2 -1 -2 0 1Output01 0 -1-2 0 21 0 -1Input25 5 5 5Output105 55 5
Input31 2 3 4 5 6 7 8 9
Output152 7 69 5 14 3 8
2 seconds
256 megabytes
['*2100']
D2. Magic Squarestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.The magic square is a matrix of size n × n. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number s. The sum of numbers in each column of the matrix is also equal to s. In addition, the sum of the elements on the main diagonal is equal to s and the sum of elements on the secondary diagonal is equal to s. Examples of magic squares are given in the following figure: Magic squares You are given a set of n2 integers ai. It is required to place these numbers into a square matrix of size n × n so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.It is guaranteed that a solution exists!InputThe first input line contains a single integer n. The next line contains n2 integers ai ( - 108 ≀ ai ≀ 108), separated by single spaces.The input limitations for getting 20 points are: 1 ≀ n ≀ 3 The input limitations for getting 50 points are: 1 ≀ n ≀ 4 It is guaranteed that there are no more than 9 distinct numbers among ai. The input limitations for getting 100 points are: 1 ≀ n ≀ 4 OutputThe first line of the output should contain a single integer s. In each of the following n lines print n integers, separated by spaces and describing the resulting magic square. In the resulting magic square the sums in the rows, columns and diagonals must be equal to s. If there are multiple solutions, you are allowed to print any of them.ExamplesInput31 2 3 4 5 6 7 8 9Output152 7 69 5 14 3 8Input31 0 -1 0 2 -1 -2 0 1Output01 0 -1-2 0 21 0 -1Input25 5 5 5Output105 55 5
Input31 2 3 4 5 6 7 8 9
Output152 7 69 5 14 3 8
2 seconds
256 megabytes
['*1900']
D1. Magic Squarestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.The magic square is a matrix of size n × n. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number s. The sum of numbers in each column of the matrix is also equal to s. In addition, the sum of the elements on the main diagonal is equal to s and the sum of elements on the secondary diagonal is equal to s. Examples of magic squares are given in the following figure: Magic squares You are given a set of n2 integers ai. It is required to place these numbers into a square matrix of size n × n so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.It is guaranteed that a solution exists!InputThe first input line contains a single integer n. The next line contains n2 integers ai ( - 108 ≀ ai ≀ 108), separated by single spaces.The input limitations for getting 20 points are: 1 ≀ n ≀ 3 The input limitations for getting 50 points are: 1 ≀ n ≀ 4 It is guaranteed that there are no more than 9 distinct numbers among ai. The input limitations for getting 100 points are: 1 ≀ n ≀ 4 OutputThe first line of the output should contain a single integer s. In each of the following n lines print n integers, separated by spaces and describing the resulting magic square. In the resulting magic square the sums in the rows, columns and diagonals must be equal to s. If there are multiple solutions, you are allowed to print any of them.ExamplesInput31 2 3 4 5 6 7 8 9Output152 7 69 5 14 3 8Input31 0 -1 0 2 -1 -2 0 1Output01 0 -1-2 0 21 0 -1Input25 5 5 5Output105 55 5
Input31 2 3 4 5 6 7 8 9
Output152 7 69 5 14 3 8
2 seconds
256 megabytes
['*1500']
C3. Smart Beaver and Resolving Collisionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.We assume that the hash table consists of h cells numbered from 0 to h - 1. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value β€” an integer between 0 and h - 1, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals t and cell t of the table is already occupied. Then we try to add this object to cell (t + m)Β modΒ h. If it is also occupied, then we try cell (t + 2Β·m)Β modΒ h, then cell (t + 3Β·m)Β modΒ h, and so on. Note that in some cases it's possible that the new object can not be added to the table. It is guaranteed that the input for this problem doesn't contain such situations.The operation aΒ modΒ b means that we take the remainder of the division of number a by number b.This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell (t + iΒ·m)Β modΒ h (i β‰₯ 0), then exactly i dummy calls have been performed.Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.InputThe first line of input contains three integers h, m and n (1 ≀ m < h), separated by spaces, where h is the size of the hash table, m is the number that is used to resolve collisions, n is the number of operations.The following n lines contains the descriptions of the operations. Their execution order corresponds to the order in which they appear in the input file. Each operation is described by a single line. The operations are described as follows: "+ id hash"This is the format of the operation that adds an object to the table. The first character is "+" (ASCII 43), followed by a single space, then the object identifier id (0 ≀ id ≀ 109), then another space, and the hash value of the given object hash (0 ≀ hash < h). The object identifier and the hash value of this object are integers. "- id"This is the format of the operation that deletes an object from the table. The first character is "-" (ASCII 45), followed by a single space, then the object identifier id (0 ≀ id ≀ 109). The object identifier is an integer.It is guaranteed that for all addition operations the value of id is unique. It is also guaranteed that the initial data is correct, that is, it's always possible to add an object to the hash table and there won't be any deletions of nonexisting objects.The input limitations for getting 20 points are: 1 ≀ h ≀ 5000 1 ≀ n ≀ 5000 The input limitations for getting 50 points are: 1 ≀ h ≀ 5Β·104 1 ≀ n ≀ 5Β·104 The input limitations for getting 100 points are: 1 ≀ h ≀ 2Β·105 1 ≀ n ≀ 2Β·105 OutputPrint a single number β€” the total number of dummy calls to the hash table.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams and the %I64d specifier.ExamplesInput10 2 7+ 11 0+ 22 2+ 33 6+ 44 0+ 55 0- 22+ 66 0Output7Input5 1 6+ 123 0+ 234 1+ 345 2- 234+ 456 0+ 567 0Output4
Input10 2 7+ 11 0+ 22 2+ 33 6+ 44 0+ 55 0- 22+ 66 0
Output7
1 second
256 megabytes
['*2000']
C2. Smart Beaver and Resolving Collisionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.We assume that the hash table consists of h cells numbered from 0 to h - 1. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value β€” an integer between 0 and h - 1, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals t and cell t of the table is already occupied. Then we try to add this object to cell (t + m)Β modΒ h. If it is also occupied, then we try cell (t + 2Β·m)Β modΒ h, then cell (t + 3Β·m)Β modΒ h, and so on. Note that in some cases it's possible that the new object can not be added to the table. It is guaranteed that the input for this problem doesn't contain such situations.The operation aΒ modΒ b means that we take the remainder of the division of number a by number b.This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell (t + iΒ·m)Β modΒ h (i β‰₯ 0), then exactly i dummy calls have been performed.Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.InputThe first line of input contains three integers h, m and n (1 ≀ m < h), separated by spaces, where h is the size of the hash table, m is the number that is used to resolve collisions, n is the number of operations.The following n lines contains the descriptions of the operations. Their execution order corresponds to the order in which they appear in the input file. Each operation is described by a single line. The operations are described as follows: "+ id hash"This is the format of the operation that adds an object to the table. The first character is "+" (ASCII 43), followed by a single space, then the object identifier id (0 ≀ id ≀ 109), then another space, and the hash value of the given object hash (0 ≀ hash < h). The object identifier and the hash value of this object are integers. "- id"This is the format of the operation that deletes an object from the table. The first character is "-" (ASCII 45), followed by a single space, then the object identifier id (0 ≀ id ≀ 109). The object identifier is an integer.It is guaranteed that for all addition operations the value of id is unique. It is also guaranteed that the initial data is correct, that is, it's always possible to add an object to the hash table and there won't be any deletions of nonexisting objects.The input limitations for getting 20 points are: 1 ≀ h ≀ 5000 1 ≀ n ≀ 5000 The input limitations for getting 50 points are: 1 ≀ h ≀ 5Β·104 1 ≀ n ≀ 5Β·104 The input limitations for getting 100 points are: 1 ≀ h ≀ 2Β·105 1 ≀ n ≀ 2Β·105 OutputPrint a single number β€” the total number of dummy calls to the hash table.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams and the %I64d specifier.ExamplesInput10 2 7+ 11 0+ 22 2+ 33 6+ 44 0+ 55 0- 22+ 66 0Output7Input5 1 6+ 123 0+ 234 1+ 345 2- 234+ 456 0+ 567 0Output4
Input10 2 7+ 11 0+ 22 2+ 33 6+ 44 0+ 55 0- 22+ 66 0
Output7
1 second
256 megabytes
['*1900']
C1. Smart Beaver and Resolving Collisionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.We assume that the hash table consists of h cells numbered from 0 to h - 1. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value β€” an integer between 0 and h - 1, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals t and cell t of the table is already occupied. Then we try to add this object to cell (t + m)Β modΒ h. If it is also occupied, then we try cell (t + 2Β·m)Β modΒ h, then cell (t + 3Β·m)Β modΒ h, and so on. Note that in some cases it's possible that the new object can not be added to the table. It is guaranteed that the input for this problem doesn't contain such situations.The operation aΒ modΒ b means that we take the remainder of the division of number a by number b.This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell (t + iΒ·m)Β modΒ h (i β‰₯ 0), then exactly i dummy calls have been performed.Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.InputThe first line of input contains three integers h, m and n (1 ≀ m < h), separated by spaces, where h is the size of the hash table, m is the number that is used to resolve collisions, n is the number of operations.The following n lines contains the descriptions of the operations. Their execution order corresponds to the order in which they appear in the input file. Each operation is described by a single line. The operations are described as follows: "+ id hash"This is the format of the operation that adds an object to the table. The first character is "+" (ASCII 43), followed by a single space, then the object identifier id (0 ≀ id ≀ 109), then another space, and the hash value of the given object hash (0 ≀ hash < h). The object identifier and the hash value of this object are integers. "- id"This is the format of the operation that deletes an object from the table. The first character is "-" (ASCII 45), followed by a single space, then the object identifier id (0 ≀ id ≀ 109). The object identifier is an integer.It is guaranteed that for all addition operations the value of id is unique. It is also guaranteed that the initial data is correct, that is, it's always possible to add an object to the hash table and there won't be any deletions of nonexisting objects.The input limitations for getting 20 points are: 1 ≀ h ≀ 5000 1 ≀ n ≀ 5000 The input limitations for getting 50 points are: 1 ≀ h ≀ 5Β·104 1 ≀ n ≀ 5Β·104 The input limitations for getting 100 points are: 1 ≀ h ≀ 2Β·105 1 ≀ n ≀ 2Β·105 OutputPrint a single number β€” the total number of dummy calls to the hash table.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams and the %I64d specifier.ExamplesInput10 2 7+ 11 0+ 22 2+ 33 6+ 44 0+ 55 0- 22+ 66 0Output7Input5 1 6+ 123 0+ 234 1+ 345 2- 234+ 456 0+ 567 0Output4
Input10 2 7+ 11 0+ 22 2+ 33 6+ 44 0+ 55 0- 22+ 66 0
Output7
1 second
256 megabytes
['*1600']
B3. Greedy Merchantstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p β‰₯ 1) such that: t1 = c1 tp = c2 for any i (1 ≀ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di β‰₯ 0) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.InputThe first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire.The following m lines contain pairs of integers ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi), separated by a space β€” the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire.The next line contains a single integer k β€” the number of merchants in the empire.The following k lines contain pairs of integers si, li (1 ≀ si, li ≀ n), separated by a space, β€” si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located.The input limitations for getting 20 points are: 1 ≀ n ≀ 200 1 ≀ m ≀ 200 1 ≀ k ≀ 200 The input limitations for getting 50 points are: 1 ≀ n ≀ 2000 1 ≀ m ≀ 2000 1 ≀ k ≀ 2000 The input limitations for getting 100 points are: 1 ≀ n ≀ 105 1 ≀ m ≀ 105 1 ≀ k ≀ 105 OutputPrint exactly k lines, the i-th line should contain a single integer di β€” the number of dinars that the i-th merchant paid.ExamplesInput7 81 22 33 44 55 65 73 54 741 52 42 64 7Output2120NoteThe given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2.
Input7 81 22 33 44 55 65 73 54 741 52 42 64 7
Output2120
2 seconds
256 megabytes
['*1800']
B2. Greedy Merchantstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p β‰₯ 1) such that: t1 = c1 tp = c2 for any i (1 ≀ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di β‰₯ 0) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.InputThe first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire.The following m lines contain pairs of integers ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi), separated by a space β€” the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire.The next line contains a single integer k β€” the number of merchants in the empire.The following k lines contain pairs of integers si, li (1 ≀ si, li ≀ n), separated by a space, β€” si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located.The input limitations for getting 20 points are: 1 ≀ n ≀ 200 1 ≀ m ≀ 200 1 ≀ k ≀ 200 The input limitations for getting 50 points are: 1 ≀ n ≀ 2000 1 ≀ m ≀ 2000 1 ≀ k ≀ 2000 The input limitations for getting 100 points are: 1 ≀ n ≀ 105 1 ≀ m ≀ 105 1 ≀ k ≀ 105 OutputPrint exactly k lines, the i-th line should contain a single integer di β€” the number of dinars that the i-th merchant paid.ExamplesInput7 81 22 33 44 55 65 73 54 741 52 42 64 7Output2120NoteThe given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2.
Input7 81 22 33 44 55 65 73 54 741 52 42 64 7
Output2120
2 seconds
256 megabytes
['*1600']
B1. Greedy Merchantstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p β‰₯ 1) such that: t1 = c1 tp = c2 for any i (1 ≀ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di β‰₯ 0) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.InputThe first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire.The following m lines contain pairs of integers ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi), separated by a space β€” the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire.The next line contains a single integer k β€” the number of merchants in the empire.The following k lines contain pairs of integers si, li (1 ≀ si, li ≀ n), separated by a space, β€” si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located.The input limitations for getting 20 points are: 1 ≀ n ≀ 200 1 ≀ m ≀ 200 1 ≀ k ≀ 200 The input limitations for getting 50 points are: 1 ≀ n ≀ 2000 1 ≀ m ≀ 2000 1 ≀ k ≀ 2000 The input limitations for getting 100 points are: 1 ≀ n ≀ 105 1 ≀ m ≀ 105 1 ≀ k ≀ 105 OutputPrint exactly k lines, the i-th line should contain a single integer di β€” the number of dinars that the i-th merchant paid.ExamplesInput7 81 22 33 44 55 65 73 54 741 52 42 64 7Output2120NoteThe given sample is illustrated in the figure below. Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2.
Input7 81 22 33 44 55 65 73 54 741 52 42 64 7
Output2120
2 seconds
256 megabytes
['*1600']
A3. Educational Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k < n), and this should be done in the smallest possible number of moves.One move is choosing an integer i (1 ≀ i ≀ n) such that ai > 0 and an integer t (t β‰₯ 0) such that i + 2t ≀ n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai + 2t is increased by 1. For example, let n = 4 and a = (1, 0, 1, 2), then it is possible to make move i = 3, t = 0 and get a = (1, 0, 0, 3) or to make move i = 1, t = 1 and get a = (0, 0, 2, 2) (the only possible other move is i = 1, t = 0).You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1 ≀ k < n).InputThe first input line contains a single integer n. The second line contains n integers ai (0 ≀ ai ≀ 104), separated by single spaces.The input limitations for getting 20 points are: 1 ≀ n ≀ 300 The input limitations for getting 50 points are: 1 ≀ n ≀ 2000 The input limitations for getting 100 points are: 1 ≀ n ≀ 105 OutputPrint exactly n - 1 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero.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.ExamplesInput41 0 1 2Output113Input81 2 3 4 5 6 7 8Output13610162440
Input41 0 1 2
Output113
2 seconds
256 megabytes
['greedy', '*1100']
A2. Educational Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k < n), and this should be done in the smallest possible number of moves.One move is choosing an integer i (1 ≀ i ≀ n) such that ai > 0 and an integer t (t β‰₯ 0) such that i + 2t ≀ n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai + 2t is increased by 1. For example, let n = 4 and a = (1, 0, 1, 2), then it is possible to make move i = 3, t = 0 and get a = (1, 0, 0, 3) or to make move i = 1, t = 1 and get a = (0, 0, 2, 2) (the only possible other move is i = 1, t = 0).You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1 ≀ k < n).InputThe first input line contains a single integer n. The second line contains n integers ai (0 ≀ ai ≀ 104), separated by single spaces.The input limitations for getting 20 points are: 1 ≀ n ≀ 300 The input limitations for getting 50 points are: 1 ≀ n ≀ 2000 The input limitations for getting 100 points are: 1 ≀ n ≀ 105 OutputPrint exactly n - 1 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero.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.ExamplesInput41 0 1 2Output113Input81 2 3 4 5 6 7 8Output13610162440
Input41 0 1 2
Output113
2 seconds
256 megabytes
['greedy', '*1000']
A1. Educational Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k < n), and this should be done in the smallest possible number of moves.One move is choosing an integer i (1 ≀ i ≀ n) such that ai > 0 and an integer t (t β‰₯ 0) such that i + 2t ≀ n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai + 2t is increased by 1. For example, let n = 4 and a = (1, 0, 1, 2), then it is possible to make move i = 3, t = 0 and get a = (1, 0, 0, 3) or to make move i = 1, t = 1 and get a = (0, 0, 2, 2) (the only possible other move is i = 1, t = 0).You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1 ≀ k < n).InputThe first input line contains a single integer n. The second line contains n integers ai (0 ≀ ai ≀ 104), separated by single spaces.The input limitations for getting 20 points are: 1 ≀ n ≀ 300 The input limitations for getting 50 points are: 1 ≀ n ≀ 2000 The input limitations for getting 100 points are: 1 ≀ n ≀ 105 OutputPrint exactly n - 1 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero.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.ExamplesInput41 0 1 2Output113Input81 2 3 4 5 6 7 8Output13610162440
Input41 0 1 2
Output113
2 seconds
256 megabytes
['*1000']
G2. Fibonacci Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFibonacci strings are defined as follows: f1 = Β«aΒ» f2 = Β«bΒ» fn = fn - 1Β fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba".You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring.InputThe first line contains two space-separated integers k and m β€” the number of a Fibonacci string and the number of queries, correspondingly.Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b".The input limitations for getting 30 points are: 1 ≀ k ≀ 3000 1 ≀ m ≀ 3000 The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: 1 ≀ k ≀ 1018 1 ≀ m ≀ 104 The total length of strings si doesn't exceed 105 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 string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input.ExamplesInput6 5ababbaabaOutput35331
Input6 5ababbaaba
Output35331
2 seconds
256 megabytes
['matrices', 'strings', '*2600']
G1. Fibonacci Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFibonacci strings are defined as follows: f1 = Β«aΒ» f2 = Β«bΒ» fn = fn - 1Β fn - 2, n > 2 Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba".You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as a substring.InputThe first line contains two space-separated integers k and m β€” the number of a Fibonacci string and the number of queries, correspondingly.Next m lines contain strings si that correspond to the queries. It is guaranteed that strings si aren't empty and consist only of characters "a" and "b".The input limitations for getting 30 points are: 1 ≀ k ≀ 3000 1 ≀ m ≀ 3000 The total length of strings si doesn't exceed 3000 The input limitations for getting 100 points are: 1 ≀ k ≀ 1018 1 ≀ m ≀ 104 The total length of strings si doesn't exceed 105 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 string si print the number of times it occurs in the given Fibonacci string as a substring. Since the numbers can be large enough, print them modulo 1000000007 (109 + 7). Print the answers for the strings in the order in which they are given in the input.ExamplesInput6 5ababbaabaOutput35331
Input6 5ababbaaba
Output35331
2 seconds
256 megabytes
['strings', '*2400']
F2. Script Generationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY was offered a job of a screenwriter for the ongoing TV series. In particular, he needs to automate the hard decision: which main characters will get married by the end of the series.There are n single men and n single women among the main characters. An opinion poll showed that viewers like several couples, and a marriage of any of them will make the audience happy. The Smart Beaver formalized this fact as k triples of numbers (h, w, r), where h is the index of the man, w is the index of the woman, and r is the measure of the audience's delight in case of the marriage of this couple. The same poll showed that the marriage of any other couple will leave the audience indifferent, so the screenwriters decided not to include any such marriages in the plot.The script allows you to arrange several marriages between the heroes or not to arrange marriages at all. A subset of some of the k marriages is considered acceptable if each man and each woman is involved in at most one marriage of the subset (the series won't allow any divorces). The value of the acceptable set of marriages is the total delight the spectators will get from the marriages included in this set.Obviously, there is a finite number of acceptable sets, and they all describe some variants of the script. The screenwriters do not want to choose a set with maximum value β€” it would make the plot too predictable. So the Smart Beaver offers the following option: sort all the acceptable sets in increasing order of value and choose the t-th set from the sorted list. Thus, t = 1 corresponds to a plot without marriages, t = 2 β€” to a single marriage resulting in minimal delight for the audience, and so on.Help the Beaver to implement the algorithm for selecting the desired set.InputThe first input line contains integers n, k and t (1 ≀ k ≀ min(100, n2), 1 ≀ t ≀ 2Β·105), separated by single spaces. Next k lines contain triples of integers (h, w, r) (1 ≀ h, w ≀ n;Β 1 ≀ r ≀ 1000), separated by single spaces, which describe the possible marriages. It is guaranteed that the input data is correct: t doesn't exceed the total number of acceptable sets, and each pair (h, w) is present in at most one triple.The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 20 OutputPrint a single number β€” the value of the t-th acceptable variant.ExamplesInput2 4 31 1 11 2 22 1 32 2 7Output2Input2 4 71 1 11 2 22 1 32 2 7Output8NoteThe figure shows 7 acceptable sets of marriages that exist in the first sample.
Input2 4 31 1 11 2 22 1 32 2 7
Output2
2 seconds
256 megabytes
['*2300']
F1. Script Generationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY was offered a job of a screenwriter for the ongoing TV series. In particular, he needs to automate the hard decision: which main characters will get married by the end of the series.There are n single men and n single women among the main characters. An opinion poll showed that viewers like several couples, and a marriage of any of them will make the audience happy. The Smart Beaver formalized this fact as k triples of numbers (h, w, r), where h is the index of the man, w is the index of the woman, and r is the measure of the audience's delight in case of the marriage of this couple. The same poll showed that the marriage of any other couple will leave the audience indifferent, so the screenwriters decided not to include any such marriages in the plot.The script allows you to arrange several marriages between the heroes or not to arrange marriages at all. A subset of some of the k marriages is considered acceptable if each man and each woman is involved in at most one marriage of the subset (the series won't allow any divorces). The value of the acceptable set of marriages is the total delight the spectators will get from the marriages included in this set.Obviously, there is a finite number of acceptable sets, and they all describe some variants of the script. The screenwriters do not want to choose a set with maximum value β€” it would make the plot too predictable. So the Smart Beaver offers the following option: sort all the acceptable sets in increasing order of value and choose the t-th set from the sorted list. Thus, t = 1 corresponds to a plot without marriages, t = 2 β€” to a single marriage resulting in minimal delight for the audience, and so on.Help the Beaver to implement the algorithm for selecting the desired set.InputThe first input line contains integers n, k and t (1 ≀ k ≀ min(100, n2), 1 ≀ t ≀ 2Β·105), separated by single spaces. Next k lines contain triples of integers (h, w, r) (1 ≀ h, w ≀ n;Β 1 ≀ r ≀ 1000), separated by single spaces, which describe the possible marriages. It is guaranteed that the input data is correct: t doesn't exceed the total number of acceptable sets, and each pair (h, w) is present in at most one triple.The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 20 OutputPrint a single number β€” the value of the t-th acceptable variant.ExamplesInput2 4 31 1 11 2 22 1 32 2 7Output2Input2 4 71 1 11 2 22 1 32 2 7Output8NoteThe figure shows 7 acceptable sets of marriages that exist in the first sample.
Input2 4 31 1 11 2 22 1 32 2 7
Output2
2 seconds
256 megabytes
['*1800']