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
B. Codeforces World Finalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe king Copa often has been reported about the Codeforces site, which is rapidly getting more and more popular among the brightest minds of the humanity, who are using it for training and competing. Recently Copa understood that to conquer the world he needs to organize the world Codeforces tournament. He hopes that after it the brightest minds will become his subordinates, and the toughest part of conquering the world will be completed.The final round of the Codeforces World Finals 20YY is scheduled for DD.MM.YY, where DD is the day of the round, MM is the month and YY are the last two digits of the year. Bob is lucky to be the first finalist form Berland. But there is one problem: according to the rules of the competition, all participants must be at least 18 years old at the moment of the finals. Bob was born on BD.BM.BY. This date is recorded in his passport, the copy of which he has already mailed to the organizers. But Bob learned that in different countries the way, in which the dates are written, differs. For example, in the US the month is written first, then the day and finally the year. Bob wonders if it is possible to rearrange the numbers in his date of birth so that he will be at least 18 years old on the day DD.MM.YY. He can always tell that in his motherland dates are written differently. Help him.According to another strange rule, eligible participant must be born in the same century as the date of the finals. If the day of the finals is participant's 18-th birthday, he is allowed to participate. As we are considering only the years from 2001 to 2099 for the year of the finals, use the following rule: the year is leap if it's number is divisible by four.InputThe first line contains the date DD.MM.YY, the second line contains the date BD.BM.BY. It is guaranteed that both dates are correct, and YY and BY are always in [01;99].It could be that by passport Bob was born after the finals. In this case, he can still change the order of numbers in date.OutputIf it is possible to rearrange the numbers in the date of birth so that Bob will be at least 18 years old on the DD.MM.YY, output YES. In the other case, output NO. Each number contains exactly two digits and stands for day, month or year in a date. Note that it is permitted to rearrange only numbers, not digits.ExamplesInput01.01.9801.01.80OutputYESInput20.10.2010.02.30OutputNOInput28.02.7428.02.64OutputNO
Input01.01.9801.01.80
OutputYES
2 seconds
256 megabytes
['implementation', '*1700']
A. Accountingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient X — the coefficient of income growth during one year. This coefficient should satisfy the equation:A·Xn = B.Surely, the king is not going to do this job by himself, and demands you to find such number X.It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient X must be integers. The number X may be zero or negative.InputThe input contains three integers A, B, n (|A|, |B| ≤ 1000, 1 ≤ n ≤ 10).OutputOutput the required integer coefficient X, or «No solution», if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them.ExamplesInput2 18 2Output3Input-1 8 3Output-2Input0 0 10Output5Input1 16 5OutputNo solution
Input2 18 2
Output3
2 seconds
256 megabytes
['brute force', 'math', '*1400']
E. Quarreltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFriends Alex and Bob live in Bertown. In this town there are n crossroads, some of them are connected by bidirectional roads of equal length. Bob lives in a house at the crossroads number 1, Alex — in a house at the crossroads number n.One day Alex and Bob had a big quarrel, and they refused to see each other. It occurred that today Bob needs to get from his house to the crossroads n and Alex needs to get from his house to the crossroads 1. And they don't want to meet at any of the crossroads, but they can meet in the middle of the street, when passing it in opposite directions. Alex and Bob asked you, as their mutual friend, to help them with this difficult task.Find for Alex and Bob such routes with equal number of streets that the guys can follow these routes and never appear at the same crossroads at the same time. They are allowed to meet in the middle of the street when moving toward each other (see Sample 1). Among all possible routes, select such that the number of streets in it is the least possible. Until both guys reach their destinations, none of them can stay without moving. The guys are moving simultaneously with equal speeds, i.e. it is possible that when one of them reaches some of the crossroads, the other one leaves it. For example, Alex can move from crossroad 1 to crossroad 2, while Bob moves from crossroad 2 to crossroad 3.If the required routes don't exist, your program should output -1.InputThe first line contains two integers n and m (2 ≤ n ≤ 500, 1 ≤ m ≤ 10000) — the amount of crossroads and the amount of roads. Each of the following m lines contains two integers — the numbers of crossroads connected by the road. It is guaranteed that no road connects a crossroads with itself and no two crossroads are connected by more than one road.OutputIf the required routes don't exist, output -1. Otherwise, the first line should contain integer k — the length of shortest routes (the length of the route is the amount of roads in it). The next line should contain k + 1 integers — Bob's route, i.e. the numbers of k + 1 crossroads passed by Bob. The last line should contain Alex's route in the same format. If there are several optimal solutions, output any of them.ExamplesInput2 11 2Output11 2 2 1 Input7 51 22 77 62 33 4Output-1Input7 61 22 77 62 33 41 5Output61 2 3 4 3 2 7 7 6 7 2 1 5 1
Input2 11 2
Output11 2 2 1
1 second
256 megabytes
['graphs', 'shortest paths', '*2400']
D. Ant on the Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConnected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.InputThe first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.OutputIf the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.ExamplesInput31 22 33Output1 2 3 2 1 Input61 21 32 44 54 65 6 3Output1 2 4 5 4 6 4 2 1 3 1 Input61 21 32 44 54 65 3 6Output-1
Input31 22 33
Output1 2 3 2 1
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'trees', '*2000']
C. Mail Stampstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sent via some intermediate cities. Post officers never send a letter in such a way that the route of this letter contains some city more than once. Bob is sure that the post officers stamp the letters accurately.There are n stamps on the envelope of Bob's letter. He understands that the possible routes of this letter are only two. But the stamps are numerous, and Bob can't determine himself none of these routes. That's why he asks you to help him. Find one of the possible routes of the letter.InputThe first line contains integer n (1 ≤ n ≤ 105) — amount of mail stamps on the envelope. Then there follow n lines with two integers each — description of the stamps. Each stamp is described with indexes of the cities between which a letter is sent. The indexes of cities are integers from 1 to 109. Indexes of all the cities are different. Every time the letter is sent from one city to another, exactly one stamp is put on the envelope. It is guaranteed that the given stamps correspond to some valid route from some city to some other city. OutputOutput n + 1 numbers — indexes of cities in one of the two possible routes of the letter.ExamplesInput21 100100 2Output2 100 1 Input33 1100 23 2Output100 2 3 1
Input21 100100 2
Output2 100 1
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'implementation', '*1700']
B. Traffic Lightstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA car moves from point A to point B at speed v meters per second. The action takes place on the X-axis. At the distance d meters from A there are traffic lights. Starting from time 0, for the first g seconds the green light is on, then for the following r seconds the red light is on, then again the green light is on for the g seconds, and so on.The car can be instantly accelerated from 0 to v and vice versa, can instantly slow down from the v to 0. Consider that it passes the traffic lights at the green light instantly. If the car approaches the traffic lights at the moment when the red light has just turned on, it doesn't have time to pass it. But if it approaches the traffic lights at the moment when the green light has just turned on, it can move. The car leaves point A at the time 0.What is the minimum time for the car to get from point A to point B without breaking the traffic rules?InputThe first line contains integers l, d, v, g, r (1 ≤ l, d, v, g, r ≤ 1000, d < l) — the distance between A and B (in meters), the distance from A to the traffic lights, car's speed, the duration of green light and the duration of red light.OutputOutput a single number — the minimum time that the car needs to get from point A to point B. Your output must have relative or absolute error less than 10 - 6.ExamplesInput2 1 3 4 5Output0.66666667Input5 4 3 1 1Output2.33333333
Input2 1 3 4 5
Output0.66666667
2 seconds
256 megabytes
['implementation', '*1500']
A. Spit Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.The trajectory of a camel's spit is an arc, i.e. if the camel in position x spits d meters right, he can hit only the camel in position x + d, if such a camel exists.InputThe first line contains integer n (1 ≤ n ≤ 100) — the amount of camels in the zoo. Each of the following n lines contains two integers xi and di ( - 104 ≤ xi ≤ 104, 1 ≤ |di| ≤ 2·104) — records in Bob's notepad. xi is a position of the i-th camel, and di is a distance at which the i-th camel spitted. Positive values of di correspond to the spits right, negative values correspond to the spits left. No two camels may stand in the same position.OutputIf there are two camels, which spitted at each other, output YES. Otherwise, output NO.ExamplesInput20 11 -1OutputYESInput30 11 12 -2OutputNOInput52 -103 100 55 -510 1OutputYES
Input20 11 -1
OutputYES
2 seconds
256 megabytes
['brute force', '*1000']
E. DravDe saves the worldtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHow horrible! The empire of galactic chickens tries to conquer a beautiful city "Z", they have built a huge incubator that produces millions of chicken soldiers a day, and fenced it around. The huge incubator looks like a polygon on the plane Oxy with n vertices. Naturally, DravDe can't keep still, he wants to destroy the chicken empire. For sure, he will start with the incubator.DravDe is strictly outside the incubator's territory in point A(xa, ya), and wants to get inside and kill all the chickens working there. But it takes a lot of doing! The problem is that recently DravDe went roller skating and has broken both his legs. He will get to the incubator's territory in his jet airplane LEVAP-41.LEVAP-41 flies at speed V(xv, yv, zv). DravDe can get on the plane in point A, fly for some time, and then air drop himself. DravDe is very heavy, that's why he falls vertically at speed Fdown, but in each point of his free fall DravDe can open his parachute, and from that moment he starts to fall at the wind speed U(xu, yu, zu) until he lands. Unfortunately, DravDe isn't good at mathematics. Would you help poor world's saviour find such an air dropping plan, that allows him to land on the incubator's territory? If the answer is not unique, DravDe wants to find the plan with the minimum time of his flight on the plane. If the answers are still multiple, he wants to find the one with the minimum time of his free fall before opening his parachuteInputThe first line contains the number n (3 ≤ n ≤ 104) — the amount of vertices of the fence. Then there follow n lines containing the coordinates of these vertices (two integer numbers xi, yi) in clockwise or counter-clockwise order. It's guaranteed, that the fence does not contain self-intersections.The following four lines contain coordinates of point A(xa, ya), speeds V(xv, yv, zv), Fdown and speed U(xu, yu, zu). All the input numbers are integer. All the coordinates don't exceed 104 in absolute value. It's guaranteed, that zv > 0 and Fdown, zu < 0, and point A is strictly outside the incubator's territory.OutputIn the first line output two numbers t1, t2 such, that if DravDe air drops at time t1 (counting from the beginning of the flight), he lands on the incubator's territory (landing on the border is regarder as landing on the territory). If DravDe doesn't open his parachute, the second number should be equal to the duration of DravDe's falling down. If it's impossible for DravDe to get to the incubator's territory, output -1 -1. If the answer is not unique, output the answer with the minimum t1. If the answers are still multiple, output the answer with the minimum t2. Your answer must have an absolute or relative error less than 10 - 6.ExamplesInput40 01 01 10 10 -11 0 1-10 1 -1Output1.00000000 0.00000000Input40 00 11 11 00 -1-1 -1 1-10 1 -1Output-1.00000000 -1.00000000Input40 01 01 10 10 -11 1 1-11 1 -1Output0.50000000 0.00000000
Input40 01 01 10 10 -11 0 1-10 1 -1
Output1.00000000 0.00000000
1 second
256 megabytes
['geometry', 'math', '*2800']
D. Don't fear, DravDe is kindtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA motorcade of n trucks, driving from city «Z» to city «З», has approached a tunnel, known as Tunnel of Horror. Among truck drivers there were rumours about monster DravDe, who hunts for drivers in that tunnel. Some drivers fear to go first, others - to be the last, but let's consider the general case. Each truck is described with four numbers: v — value of the truck, of its passangers and cargo c — amount of passanger on the truck, the driver included l — total amount of people that should go into the tunnel before this truck, so that the driver can overcome his fear («if the monster appears in front of the motorcade, he'll eat them first») r — total amount of people that should follow this truck, so that the driver can overcome his fear («if the monster appears behind the motorcade, he'll eat them first»). Since the road is narrow, it's impossible to escape DravDe, if he appears from one side. Moreover, the motorcade can't be rearranged. The order of the trucks can't be changed, but it's possible to take any truck out of the motorcade, and leave it near the tunnel for an indefinite period. You, as the head of the motorcade, should remove some of the trucks so, that the rest of the motorcade can move into the tunnel and the total amount of the left trucks' values is maximal. InputThe first input line contains integer number n (1 ≤ n ≤ 105) — amount of trucks in the motorcade. The following n lines contain four integers each. Numbers in the i-th line: vi, ci, li, ri (1 ≤ vi ≤ 104, 1 ≤ ci ≤ 105, 0 ≤ li, ri ≤ 105) — describe the i-th truck. The trucks are numbered from 1, counting from the front of the motorcade.OutputIn the first line output number k — amount of trucks that will drive into the tunnel. In the second line output k numbers — indexes of these trucks in ascending order. Don't forget please that you are not allowed to change the order of trucks. If the answer is not unique, output any.ExamplesInput51 1 0 31 1 1 21 1 2 11 1 3 02 1 3 0Output41 2 3 5 Input51 1 0 310 1 2 12 2 1 110 1 1 23 1 3 0Output31 3 5
Input51 1 0 31 1 1 21 1 2 11 1 3 02 1 3 0
Output41 2 3 5
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'hashing', '*2400']
C. Bath Queuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.InputThe first line contains two positive integers n and m (1 ≤ n, m ≤ 50) — the amount of students and the amount of rooms. The second line contains m integers a1, a2, ... , am (1 ≤ ai ≤ 50). ai means the amount of wash basins in the i-th room.OutputOutput single number: the expected value of the size of the largest queue. Your answer must have an absolute or relative error less than 10 - 9.ExamplesInput1 12Output1.00000000000000000000Input2 21 1Output1.50000000000000000000Input2 31 1 1Output1.33333333333333350000Input7 51 1 2 3 1Output2.50216960000000070000
Input1 12
Output1.00000000000000000000
2 seconds
256 megabytes
['combinatorics', 'dp', 'probabilities', '*2200']
B. pSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move i-th cell can exchange it's value with the value of some other j-th cell, if |i - j| = di, where di is a favourite number of i-th cell. Cells make moves in any order, the number of moves is unlimited.The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to n. You are to determine whether the game could move to this state.InputThe first line contains positive integer n (1 ≤ n ≤ 100) — the number of cells in the array. The second line contains n distinct integers from 1 to n — permutation. The last line contains n integers from 1 to n — favourite numbers of the cells.OutputIf the given state is reachable in the described game, output YES, otherwise NO.ExamplesInput55 4 3 2 11 1 1 1 1OutputYESInput74 3 5 1 2 7 64 6 6 1 6 6 1OutputNOInput74 2 5 1 3 7 64 6 6 1 6 6 1OutputYES
Input55 4 3 2 11 1 1 1 1
OutputYES
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', '*1600']
A. Bender Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRobot Bender decided to make Fray a birthday present. He drove n nails and numbered them from 1 to n in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coordinate axes. Polyline is allowed to have self-intersections. Bender can take a rod and fold it exactly once in any place to form an angle of 90 degrees. Then he can attach the place of the fold to some unoccupied nail and attach two ends of this rod to adjacent nails. A nail is considered unoccupied if there is no rod attached to it (neither by it's end nor the by the fold place). No rod could be used twice. It is not required to use all the rods.Help Bender to solve this difficult task.InputThe first line contains two positive integers n and m (4 ≤ n ≤ 500, 2 ≤ m ≤ 500, n is even) — the amount of nails and the amount of rods. i-th of the following n lines contains a pair of integers, denoting the coordinates of the i-th nail. Nails should be connected in the same order as they are given in the input. The last line contains m integers — the lenghts of the rods. All coordinates do not exceed 104 by absolute value. Lengths of the rods are between 1 and 200 000. No rod can be used twice. It is guaranteed that all segments of the given polyline are parallel to coordinate axes. No three consecutive nails lie on the same line.OutputIf it is impossible to solve Bender's problem, output NO. Otherwise, output YES in the first line, and in the second line output n numbers — i-th of them should be the number of rod, which fold place is attached to the i-th nail, or -1, if there is no such rod.If there are multiple solutions, print any of them.ExamplesInput4 20 00 22 22 04 4OutputYES1 -1 2 -1 Input6 30 01 01 12 12 20 23 2 3OutputYES1 -1 2 -1 3 -1 Input6 30 01 01 12 12 20 22 2 3OutputNO
Input4 20 00 22 22 04 4
OutputYES1 -1 2 -1
2 seconds
256 megabytes
['implementation', '*1600']
E. Number With The Given Amount Of Divisorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven the number n, find the smallest positive integer which has exactly n divisors. It is guaranteed that for the given n the answer will not exceed 1018.InputThe first line of the input contains integer n (1 ≤ n ≤ 1000).OutputOutput the smallest positive integer with exactly n divisors.ExamplesInput4Output6Input6Output12
Input4
Output6
2 seconds
256 megabytes
['brute force', 'dp', 'number theory', '*2000']
D. Ring Road 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is well known that Berland has n cities, which form the Silver ring — cities i and i + 1 (1 ≤ i < n) are connected by a road, as well as the cities n and 1. The goverment have decided to build m new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should be a curve which lies inside or outside the ring. New roads will have no common points with the ring (except the endpoints of the road).Now the designers of the constructing plan wonder if it is possible to build the roads in such a way that no two roads intersect (note that the roads may intersect at their endpoints). If it is possible to do, which roads should be inside the ring, and which should be outside?InputThe first line contains two integers n and m (4 ≤ n ≤ 100, 1 ≤ m ≤ 100). Each of the following m lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). No two cities will be connected by more than one road in the list. The list will not contain the roads which exist in the Silver ring.OutputIf it is impossible to build the roads in such a way that no two roads intersect, output Impossible. Otherwise print m characters. i-th character should be i, if the road should be inside the ring, and o if the road should be outside the ring. If there are several solutions, output any of them.ExamplesInput4 21 32 4OutputioInput6 31 33 55 1Outputooo
Input4 21 32 4
Outputio
2 seconds
256 megabytes
['2-sat', 'dfs and similar', 'dsu', 'graphs', '*2200']
C. Unordered Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe sequence is called ordered if it is non-decreasing or non-increasing. For example, sequnces [3, 1, 1, 0] and [1, 2, 3, 100] are ordered, but the sequence [1, 3, 3, 1] is not. You are given a sequence of numbers. You are to find it's shortest subsequence which is not ordered.A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements.InputThe first line of the input contains one integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers — the given sequence. All numbers in this sequence do not exceed 106 by absolute value.OutputIf the given sequence does not contain any unordered subsequences, output 0. Otherwise, output the length k of the shortest such subsequence. Then output k integers from the range [1..n] — indexes of the elements of this subsequence. If there are several solutions, output any of them.ExamplesInput567 499 600 42 23Output31 3 5Input31 2 3Output0Input32 3 1Output31 2 3
Input567 499 600 42 23
Output31 3 5
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1900']
B. Tournamenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. n·(n - 1) / 2 games were played during the tournament, and each participant had a match with each other participant. The rules of the game are quite simple — the participant who falls asleep first wins. The secretary made a record of each game in the form «xi yi», where xi and yi are the numbers of participants. The first number in each pair is a winner (i.e. xi is a winner and yi is a loser). There is no draws.Recently researches form the «Institute Of Sleep» have found that every person is characterized by a value pj — the speed of falling asleep. The person who has lower speed wins. Every person has its own value pj, constant during the life. It is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game.InputThe first line contains one integer n (3 ≤ n ≤ 50) — the number of participants. The following n·(n - 1) / 2 - 1 lines contain the results of the games. Each game is described in a single line by two integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi и yi are the numbers of the opponents in this game. It is known that during the tournament each of the n participants played n - 1 games, one game with each other participant.OutputOutput two integers x and y — the missing record. If there are several solutions, output any of them.ExamplesInput44 24 12 32 13 1Output4 3
Input44 24 12 32 13 1
Output4 3
2 seconds
256 megabytes
['bitmasks', 'brute force', 'dfs and similar', 'greedy', '*1300']
A. Next Testtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.InputThe first line contains one integer n (1 ≤ n ≤ 3000) — the amount of previously added tests. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 3000) — indexes of these tests.OutputOutput the required default value for the next test index.ExamplesInput31 7 2Output3
Input31 7 2
Output3
2 seconds
256 megabytes
['implementation', 'sortings', '*1200']
E. Multithreadingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the following concurrent program. There are N processes and the i-th process has the following pseudocode: repeat ni times yi := y y := yi + 1end repeatHere y is a shared variable. Everything else is local for the process. All actions on a given row are atomic, i.e. when the process starts executing a row it is never interrupted. Beyond that all interleavings are possible, i.e. every process that has yet work to do can be granted the rights to execute its next row. In the beginning y = 0. You will be given an integer W and ni, for i = 1, ... , N. Determine if it is possible that after all processes terminate, y = W, and if it is possible output an arbitrary schedule that will produce this final value.InputIn the first line of the input you will be given two space separated integers N (1 ≤ N ≤ 100) and W ( - 109 ≤ W ≤ 109). In the second line there are N space separated integers ni (1 ≤ ni ≤ 1000).OutputOn the first line of the output write Yes if it is possible that at the end y = W, or No otherwise. If the answer is No then there is no second line, but if the answer is Yes, then on the second line output a space separated list of integers representing some schedule that leads to the desired result. For more information see note.ExamplesInput1 1011OutputNoInput2 34 4OutputYes1 1 2 1 2 2 2 2 2 1 2 1 1 1 1 2Input3 61 2 3OutputYes1 1 2 2 2 2 3 3 3 3 3 3NoteFor simplicity, assume that there is no repeat statement in the code of the processes, but the code from the loop is written the correct amount of times. The processes are numbered starting from 1. The list of integers represent which process works on its next instruction at a given step. For example, consider the schedule 1 2 2 1 3. First process 1 executes its first instruction, then process 2 executes its first two instructions, after that process 1 executes its second instruction, and finally process 3 executes its first instruction. The list must consists of exactly 2·Σ i = 1...N ni numbers.
Input1 1011
OutputNo
2 seconds
256 megabytes
['constructive algorithms', '*2400']
D. Ticketstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.InputThe input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).OutputOutput on a single line the desired probability with at least 4 digits after the decimal point.ExamplesInput5 3 1Output0.857143Input0 5 5Output1Input0 1 0Output0
Input5 3 1
Output0.857143
2 seconds
256 megabytes
['combinatorics', 'math', 'probabilities', '*2400']
C. Parquettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Bob decided to lay a parquet floor in his living room. The living room is of size n × m metres. Bob had planks of three types: a planks 1 × 2 meters, b planks 2 × 1 meters, and c planks 2 × 2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks.InputThe first input line contains 5 space-separated integer numbers n, m, a, b, c (1 ≤ n, m ≤ 100, 0 ≤ a, b, c ≤ 104), n and m — the living room dimensions, a, b and c — amount of planks 1 × 2, 2 × 1 и 2 × 2 respectively. It's not allowed to turn the planks.OutputIf it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room — output n lines with m lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any.ExamplesInput2 6 2 2 1OutputaabccaaabddaInput1 1 100 100 100OutputIMPOSSIBLEInput4 4 10 10 10Outputaabbaabbbbaabbaa
Input2 6 2 2 1
Outputaabccaaabdda
2 seconds
256 megabytes
['combinatorics', 'constructive algorithms', 'greedy', 'implementation', '*2000']
B. Regular Bracket Sequencetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?InputInput consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106.OutputOutput the maximum possible length of a regular bracket sequence.ExamplesInput(()))(Output4Input((()())Output6
Input(()))(
Output4
5 seconds
256 megabytes
['greedy', '*1400']
A. Almost Primetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and n, inclusive.InputInput contains one integer number n (1 ≤ n ≤ 3000).OutputOutput the amount of almost prime numbers between 1 and n, inclusive.ExamplesInput10Output2Input21Output8
Input10
Output2
2 seconds
256 megabytes
['number theory', '*900']
E. Testtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s1, the second enters an infinite loop if the input data contains the substring s2, and the third requires too much memory if the input data contains the substring s3. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions?InputThere are exactly 3 lines in the input data. The i-th line contains string si. All the strings are non-empty, consists of lowercase Latin letters, the length of each string doesn't exceed 105.OutputOutput one number — what is minimal length of the string, containing s1, s2 and s3 as substrings.ExamplesInputabbccdOutput4InputabacabaabaabaxOutput11
Inputabbccd
Output4
2 seconds
256 megabytes
['hashing', 'strings', '*2200']
D. Roads not only in Berlandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are n cities in Berland and neighboring countries in total and exactly n - 1 two-way roads. Because of the recent financial crisis, the Berland Government is strongly pressed for money, so to build a new road it has to close some of the existing ones. Every day it is possible to close one existing road and immediately build a new one. Your task is to determine how many days would be needed to rebuild roads so that from each city it became possible to reach all the others, and to draw a plan of closure of old roads and building of new ones.InputThe first line contains integer n (2 ≤ n ≤ 1000) — amount of cities in Berland and neighboring countries. Next n - 1 lines contain the description of roads. Each road is described by two space-separated integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — pair of cities, which the road connects. It can't be more than one road between a pair of cities. No road connects the city with itself.OutputOutput the answer, number t — what is the least amount of days needed to rebuild roads so that from each city it became possible to reach all the others. Then output t lines — the plan of closure of old roads and building of new ones. Each line should describe one day in the format i j u v — it means that road between cities i and j became closed and a new road between cities u and v is built. Cities are numbered from 1. If the answer is not unique, output any.ExamplesInput21 2Output0Input71 22 33 14 55 66 7Output13 1 3 7
Input21 2
Output0
2 seconds
256 megabytes
['dsu', 'graphs', 'trees', '*1900']
C. Roads in Berlandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.InputThe first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads.Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.OutputOutput k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.ExamplesInput20 55 011 2 3Output3 Input30 4 54 0 95 9 022 3 81 2 1Output17 12
Input20 55 011 2 3
Output3
2 seconds
256 megabytes
['graphs', 'shortest paths', '*1900']
B. Phone numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.InputThe first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.OutputOutput any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.ExamplesInput6549871Output54-98-71Input71198733Output11-987-33
Input6549871
Output54-98-71
2 seconds
256 megabytes
['implementation', '*1100']
A. IQ testtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.InputThe first line contains integer n (3 ≤ n ≤ 100) — amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.OutputOutput index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.ExamplesInput52 4 7 8 10Output3Input41 2 1 1Output2
Input52 4 7 8 10
Output3
2 seconds
256 megabytes
['brute force', '*1300']
E. Berland collidertime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently the construction of Berland collider has been completed. Collider can be represented as a long narrow tunnel that contains n particles. We associate with collider 1-dimensional coordinate system, going from left to right. For each particle we know its coordinate and velocity at the moment of start of the collider. The velocities of the particles don't change after the launch of the collider. Berland scientists think that the big bang will happen at the first collision of particles, whose velocities differs in directions. Help them to determine how much time elapses after the launch of the collider before the big bang happens.InputThe first line contains single integer n (1 ≤ n ≤ 5·105) — amount of particles in the collider. Next n lines contain description of particles. Each particle is described by two integers xi, vi ( - 109 ≤ xi, vi ≤ 109, vi ≠ 0) — coordinate and velocity respectively. All the coordinates are distinct. The particles are listed in order of increasing of coordinates. All the coordinates are in meters, and all the velocities — in meters per second. The negative velocity means that after the start of collider the particle will move to the left, and the positive — that the particle will move to the right.OutputIf there will be no big bang, output -1. Otherwise output one number — how much time in seconds elapses after the launch of the collider before the big bang happens. Your answer must have a relative or absolute error less than 10 - 9.ExamplesInput3-5 90 15 -1Output1.00000000000000000000Input61 32 33 34 -35 -16 -100Output0.02912621359223301065
Input3-5 90 15 -1
Output1.00000000000000000000
1.5 seconds
256 megabytes
['binary search', '*2300']
D. Broken robottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of N rows and M columns of cells. The robot is initially at some cell on the i-th row and the j-th column. Then at every step the robot could go to some another cell. The aim is to go to the bottommost (N-th) row. The robot can stay at it's current cell, move to the left, move to the right, or move to the cell below the current. If the robot is in the leftmost column it cannot move to the left, and if it is in the rightmost column it cannot move to the right. At every step all possible moves are equally probable. Return the expected number of step to reach the bottommost row.InputOn the first line you will be given two space separated integers N and M (1 ≤ N, M ≤ 1000). On the second line you will be given another two space separated integers i and j (1 ≤ i ≤ N, 1 ≤ j ≤ M) — the number of the initial row and the number of the initial column. Note that, (1, 1) is the upper left corner of the board and (N, M) is the bottom right corner.OutputOutput the expected number of steps on a line of itself with at least 4 digits after the decimal point.ExamplesInput10 1010 4Output0.0000000000Input10 145 14Output18.0038068653
Input10 1010 4
Output0.0000000000
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*2400']
C. Sequence of pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj.InputOn the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000.OutputOn a single line output the coordinates of Mj, space separated.ExamplesInput3 40 01 12 3-5 3Output14 0Input3 15 51000 1000-1000 10003 100Output1995 1995
Input3 40 01 12 3-5 3
Output14 0
2 seconds
256 megabytes
['geometry', 'implementation', 'math', '*1800']
B. F1 Championstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFormula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.InputThe first line contain integer t (1 ≤ t ≤ 20), where t is the number of races. After that all races are described one by one. Every race description start with an integer n (1 ≤ n ≤ 50) on a line of itself, where n is the number of clasified drivers in the given race. After that n lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.OutputYour output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.ExamplesInput33HamiltonVettelWebber2WebberVettel2HamiltonVettelOutputVettelHamiltonInput27ProstSurteesNakajimaSchumacherButtonDeLaRosaBuemi8AlonsoProstNinoFarinaJimClarkDeLaRosaNakajimaPatreseSurteesOutputProstProstNoteIt is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50.
Input33HamiltonVettelWebber2WebberVettel2HamiltonVettel
OutputVettelHamilton
2 seconds
256 megabytes
['implementation', '*1500']
A. Ring roadtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?InputThe first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.OutputOutput single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.ExamplesInput31 3 11 2 13 2 1Output1Input31 3 11 2 53 2 1Output2Input61 5 45 3 82 4 151 6 162 3 234 6 42Output39Input41 2 92 3 83 4 74 1 5Output0
Input31 3 11 2 13 2 1
Output1
2 seconds
256 megabytes
['graphs', '*1400']
E. Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can get in his new game for a given tree.InputThe first input line contains integer number n (1 ≤ n ≤ 700) — amount of vertices in the tree. The following n - 1 lines contain the description of the edges. Each line contains the pair of vertices' indexes, joined by an edge, ai, bi (1 ≤ ai, bi ≤ n). It's guaranteed that the graph described in the input is a tree.OutputOutput the only number — the maximum product of sizes of the connected components, that Bob can get after deleting some of the tree's edges.ExamplesInput51 22 33 44 5Output6Input81 21 32 42 53 63 76 8Output18Input31 21 3Output3
Input51 22 33 44 5
Output6
2 seconds
256 megabytes
['dp', '*2500']
D. Tetragontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given the centers of three equal sides of a strictly convex tetragon. Your task is to restore the initial tetragon.InputThe first input line contains one number T — amount of tests (1 ≤ T ≤ 5·104). Each of the following T lines contains numbers x1, y1, x2, y2, x3, y3 — coordinates of different points that are the centers of three equal sides (non-negative integer numbers, not exceeding 10).OutputFor each test output two lines. If the required tetragon exists, output in the first line YES, in the second line — four pairs of numbers — coordinates of the polygon's vertices in clockwise or counter-clockwise order. Don't forget, please, that the tetragon should be strictly convex, i.e. no 3 of its points lie on one line. Output numbers with 9 characters after a decimal point.If the required tetragon doen't exist, output NO in the first line, and leave the second line empty.ExamplesInput31 1 2 2 3 30 1 1 0 2 29 3 7 9 9 8OutputNOYES3.5 1.5 0.5 2.5 -0.5 -0.5 2.5 0.5NO
Input31 1 2 2 3 30 1 1 0 2 29 3 7 9 9 8
OutputNOYES3.5 1.5 0.5 2.5 -0.5 -0.5 2.5 0.5NO
3 seconds
256 megabytes
['geometry', 'math', '*2600']
C. Oranges and Applestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn 2N - 1 boxes there are apples and oranges. Your task is to choose N boxes so, that they will contain not less than half of all the apples and not less than half of all the oranges.InputThe first input line contains one number T — amount of tests. The description of each test starts with a natural number N — amount of boxes. Each of the following 2N - 1 lines contains numbers ai and oi — amount of apples and oranges in the i-th box (0 ≤ ai, oi ≤ 109). The sum of N in all the tests in the input doesn't exceed 105. All the input numbers are integer.OutputFor each test output two lines. In the first line output YES, if it's possible to choose N boxes, or NO otherwise. If the answer is positive output in the second line N numbers — indexes of the chosen boxes. Boxes are numbered from 1 in the input order. Otherwise leave the second line empty. Separate the numbers with one space.ExamplesInput2210 155 720 1810 0OutputYES1 3YES1
Input2210 155 720 1810 0
OutputYES1 3YES1
1.5 seconds
256 megabytes
['constructive algorithms', 'sortings', '*2500']
B. Partytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly 2, 3, ..., n - 1 friends among those who stayed by the moment of their leaving, did the same.What is the maximum amount of people that could stay at the party in the end? InputThe first input line contains one number t — amount of tests (1 ≤ t ≤ 105). Each of the following t lines contains one integer number n (1 ≤ n ≤ 105).OutputFor each test output in a separate line one number — the maximum amount of people that could stay in the end.ExamplesInput13Output1
Input13
Output1
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'math', '*1600']
A. You're Given a String...time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).InputThe first input line contains the string. It's guaranteed, that the string is non-empty, consists of lower-case Latin letters, and its length doesn't exceed 100.OutputOutput one number — length of the longest substring that can be met in the string at least twice.ExamplesInputabcdOutput0InputababaOutput3InputzzzOutput2
Inputabcd
Output0
2 seconds
256 megabytes
['brute force', 'greedy', '*1200']
E. Schemetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third member, and so on; i.e. a person with index i got a person with index fi, to whom he has to call, if he learns the news. With time BolgenOS community members understood that their scheme doesn't work sometimes — there were cases when some members didn't learn the news at all. Now they want to supplement the scheme: they add into the scheme some instructions of type (xi, yi), which mean that person xi has to call person yi as well. What is the minimum amount of instructions that they need to add so, that at the end everyone learns the news, no matter who is the first to learn it?InputThe first input line contains number n (2 ≤ n ≤ 105) — amount of BolgenOS community members. The second line contains n space-separated integer numbers fi (1 ≤ fi ≤ n, i ≠ fi) — index of a person, to whom calls a person with index i.OutputIn the first line output one number — the minimum amount of instructions to add. Then output one of the possible variants to add these instructions into the scheme, one instruction in each line. If the solution is not unique, output any.ExamplesInput33 3 2Output13 1Input72 3 1 3 4 4 1Output32 52 63 7
Input33 3 2
Output13 1
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*2300']
D. Segmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?InputThe first line of the input contains single integer number n (1 ≤ n ≤ 1000) — amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers — endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points.OutputThe first line should contain one integer number — the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any.ExamplesInput20 22 5Output12 Input50 34 24 88 107 7Output37 10 3
Input20 22 5
Output12
1 second
256 megabytes
['greedy', 'sortings', '*1900']
C. System Administratortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.InputThe first input line contains 3 space-separated integer numbers n, m, v (3 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ v ≤ n), n — amount of servers, m — amount of direct connections, v — index of the server that fails and leads to the failure of the whole system.OutputIf it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each — description of all the direct connections in the system. Each direct connection is described by two numbers — indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.ExamplesInput5 6 3Output1 22 33 44 51 33 5Input6 100 1Output-1
Input5 6 3
Output1 22 33 44 51 33 5
1 second
256 megabytes
['graphs', '*1700']
B. Bargaining Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room n × m meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office.InputThe first line contains 2 space-separated numbers n and m (1 ≤ n, m ≤ 25) — the office room dimensions. Then there follow n lines with m characters 0 or 1 each. 0 stands for a free square meter of the office room. 1 stands for an occupied square meter. It's guaranteed that at least one square meter in the room is free.OutputOutput one number — the maximum possible perimeter of a bargaining table for Bob's office room.ExamplesInput3 3000010000Output8Input5 411000000000000000000Output16
Input3 3000010000
Output8
2 seconds
256 megabytes
['brute force', 'dp', '*1500']
A. Second Order Statisticstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. Help Bob solve this problem.InputThe first input line contains integer n (1 ≤ n ≤ 100) — amount of numbers in the sequence. The second line contains n space-separated integer numbers — elements of the sequence. These numbers don't exceed 100 in absolute value.OutputIf the given sequence has the second order statistics, output this order statistics, otherwise output NO.ExamplesInput41 2 2 -4Output1Input51 2 3 1 1Output2
Input41 2 2 -4
Output1
2 seconds
256 megabytes
['brute force', '*800']
D. Traveling Graphtime limit per test0.5 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself).InputThe first line of the input contains two integers n and m (1 ≤ n ≤ 15, 0 ≤ m ≤ 2000), n is the amount of vertices, and m is the amount of edges. Following m lines contain edges as a triples x, y, w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10000), x, y are edge endpoints, and w is the edge length.OutputOutput minimal cycle length or -1 if it doesn't exists.ExamplesInput3 31 2 12 3 13 1 1Output3Input3 21 2 32 3 4Output14
Input3 31 2 12 3 13 1 1
Output3
0.5 second
64 megabytes
['bitmasks', 'graph matchings', 'graphs', '*2400']
C. Stripe 2time limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputOnce Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?InputThe first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.OutputOutput the amount of ways to cut the stripe into three non-empty pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.ExamplesInput41 2 3 3Output1Input51 2 3 4 5Output0
Input41 2 3 3
Output1
1 second
64 megabytes
['binary search', 'dp', 'sortings', '*2000']
B. Intersectiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two set of points. The first set is determined by the equation A1x + B1y + C1 = 0, and the second one is determined by the equation A2x + B2y + C2 = 0.Write the program which finds the number of points in the intersection of two given sets.InputThe first line of the input contains three integer numbers A1, B1, C1 separated by space. The second line contains three integer numbers A2, B2, C2 separated by space. All the numbers are between -100 and 100, inclusive.OutputPrint the number of points in the intersection or -1 if there are infinite number of points.ExamplesInput1 1 02 2 0Output-1Input1 1 02 -2 0Output1
Input1 1 02 2 0
Output-1
1 second
256 megabytes
['implementation', 'math', '*2000']
A. Jabber IDtime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. <hostname> — is a sequence of word separated by periods (characters «.»), where each word should contain only characters allowed for <username>, the length of each word is between 1 and 16, inclusive. The length of <hostname> is between 1 and 32, inclusive. <resource> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <resource> is between 1 and 16, inclusive. The content of square brackets is optional — it can be present or can be absent.There are the samples of correct Jabber IDs: [email protected], [email protected]/contest.Your task is to write program which checks if given string is a correct Jabber ID.InputThe input contains of a single line. The line has the length between 1 and 100 characters, inclusive. Each characters has ASCII-code between 33 and 127, inclusive.OutputPrint YES or NO.ExamplesInput[email protected]OutputYESInput[email protected]/contest.icpc/12OutputNO
Input[email protected]
OutputYES
0.5 second
256 megabytes
['implementation', 'strings', '*1900']
C. Dijkstra?time limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.InputThe first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge.It is possible that the graph has loops and multiple edges between pair of vertices.OutputWrite the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.ExamplesInput5 61 2 22 5 52 3 41 4 14 3 33 5 1Output1 4 3 5 Input5 61 2 22 5 52 3 41 4 14 3 33 5 1Output1 4 3 5
Input5 61 2 22 5 52 3 41 4 14 3 33 5 1
Output1 4 3 5
1 second
64 megabytes
['graphs', 'shortest paths', '*1900']
B. Equationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an equation: Ax2 + Bx + C = 0. Your task is to find the number of distinct roots of the equation and print all of them in ascending order.InputThe first line contains three integer numbers A, B and C ( - 105 ≤ A, B, C ≤ 105). Any coefficient may be equal to 0.OutputIn case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.ExamplesInput1 -5 6Output22.00000000003.0000000000
Input1 -5 6
Output22.00000000003.0000000000
1 second
256 megabytes
['math', '*2000']
A. BerOS file systemtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe new operating system BerOS has a nice feature. It is possible to use any number of characters '/' as a delimiter in path instead of one traditional '/'. For example, strings //usr///local//nginx/sbin// and /usr/local/nginx///sbin are equivalent. The character '/' (or some sequence of such characters) at the end of the path is required only in case of the path to the root directory, which can be represented as single character '/'.A path called normalized if it contains the smallest possible number of characters '/'.Your task is to transform a given path to the normalized form.InputThe first line of the input contains only lowercase Latin letters and character '/' — the path to some directory. All paths start with at least one character '/'. The length of the given line is no more than 100 characters, it is not empty.OutputThe path in normalized form.ExamplesInput//usr///local//nginx/sbinOutput/usr/local/nginx/sbin
Input//usr///local//nginx/sbin
Output/usr/local/nginx/sbin
2 seconds
64 megabytes
['implementation', '*1700']
E. Fairytime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper n points and joined some of them with segments, each of the segments starts in some point and ends in some other point. Having drawn that picture, she asked the young man to erase one of the segments from the sheet. Then she tries to colour each point red or blue so, that there is no segment having points of the same colour as its ends. If she manages to do so, the prediction will come true. B wants to meet the most beautiful princess, that's why he asks you to help him. Find all the segments that will help him to meet the princess.InputThe first input line contains two integer numbers: n — amount of the drawn points and m — amount of the drawn segments (1 ≤ n ≤ 104, 0 ≤ m ≤ 104). The following m lines contain the descriptions of the segments. Each description contains two different space-separated integer numbers v, u (1 ≤ v ≤ n, 1 ≤ u ≤ n) — indexes of the points, joined by this segment. No segment is met in the description twice.OutputIn the first line output number k — amount of the segments in the answer. In the second line output k space-separated numbers — indexes of these segments in ascending order. Each index should be output only once. Segments are numbered from 1 in the input order.ExamplesInput4 41 21 32 43 4Output41 2 3 4 Input4 51 22 33 44 11 3Output15
Input4 41 21 32 43 4
Output41 2 3 4
1.5 seconds
256 megabytes
['dfs and similar', 'divide and conquer', 'dsu', '*2900']
D. Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point (0, 0) is located in the bottom-left corner, Ox axis is directed right, Oy axis is directed up. Pete gives Bob requests of three types: add x y — on the sheet of paper Bob marks a point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is not yet marked on Bob's sheet at the time of the request. remove x y — on the sheet of paper Bob erases the previously marked point with coordinates (x, y). For each request of this type it's guaranteed that point (x, y) is already marked on Bob's sheet at the time of the request. find x y — on the sheet of paper Bob finds all the marked points, lying strictly above and strictly to the right of point (x, y). Among these points Bob chooses the leftmost one, if it is not unique, he chooses the bottommost one, and gives its coordinates to Pete. Bob managed to answer the requests, when they were 10, 100 or 1000, but when their amount grew up to 2·105, Bob failed to cope. Now he needs a program that will answer all Pete's requests. Help Bob, please!InputThe first input line contains number n (1 ≤ n ≤ 2·105) — amount of requests. Then there follow n lines — descriptions of the requests. add x y describes the request to add a point, remove x y — the request to erase a point, find x y — the request to find the bottom-left point. All the coordinates in the input file are non-negative and don't exceed 109.OutputFor each request of type find x y output in a separate line the answer to it — coordinates of the bottommost among the leftmost marked points, lying strictly above and to the right of point (x, y). If there are no points strictly above and to the right of point (x, y), output -1.ExamplesInput7add 1 1add 3 4find 0 0remove 1 1find 0 0add 1 1find 0 0Output1 13 41 1Input13add 5 5add 5 6add 5 7add 6 5add 6 6add 6 7add 7 5add 7 6add 7 7find 6 6remove 7 7find 6 6find 4 4Output7 7-15 5
Input7add 1 1add 3 4find 0 0remove 1 1find 0 0add 1 1find 0 0
Output1 13 41 1
2 seconds
256 megabytes
['data structures', '*2800']
C. Deletion of Repeatstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length x is such a substring of length 2x, that its first half coincides character by character with its second half. Bob started deleting all the repeats from the string. He does it as follows: while it's possible, Bob takes the shortest repeat, if it is not unique, he takes the leftmost one, and deletes its left half and everything that is to the left of this repeat.You're given the string seen by Bob. Find out, what it will look like after Bob deletes all the repeats in the way described above.InputThe first input line contains integer n (1 ≤ n ≤ 105) — length of the string. The following line contains n space-separated integer numbers from 0 to 109 inclusive — numbers that stand for the letters of the string. It's guaranteed that each letter can be met in the string at most 10 times.OutputIn the first line output the length of the string's part, left after Bob's deletions. In the second line output all the letters (separated by a space) of the string, left after Bob deleted all the repeats in the described way.ExamplesInput61 2 3 1 2 3Output31 2 3 Input74 5 6 5 6 7 7Output17
Input61 2 3 1 2 3
Output31 2 3
2 seconds
256 megabytes
['greedy', 'hashing', 'string suffix structures', '*2200']
B. Checkout Assistanttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob came to a cash & carry store, put n items into his trolley, and went to the checkout counter to pay. Each item is described by its price ci and time ti in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. To steal one item Bob needs exactly 1 second. What is the minimum amount of money that Bob will have to pay to the checkout assistant? Remember, please, that it is Bob, who determines the order of items for the checkout assistant.InputThe first input line contains number n (1 ≤ n ≤ 2000). In each of the following n lines each item is described by a pair of numbers ti, ci (0 ≤ ti ≤ 2000, 1 ≤ ci ≤ 109). If ti is 0, Bob won't be able to steal anything, while the checkout assistant is occupied with item i.OutputOutput one number — answer to the problem: what is the minimum amount of money that Bob will have to pay.ExamplesInput42 100 201 51 3Output8Input30 10 100 100Output111
Input42 100 201 51 3
Output8
1 second
256 megabytes
['dp', '*1900']
A. World Football Cuptime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputEveryone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: the final tournament features n teams (n is always even) the first n / 2 teams (according to the standings) come through to the knockout stage the standings are made on the following principle: for a victory a team gets 3 points, for a draw — 1 point, for a defeat — 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place — in decreasing order of the difference between scored and missed goals; in the third place — in the decreasing order of scored goals it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.InputThe first input line contains the only integer n (1 ≤ n ≤ 50) — amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following n·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 — names of the teams; num1, num2 (0 ≤ num1, num2 ≤ 100) — amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.OutputOutput n / 2 lines — names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.ExamplesInput4ABCDA-B 1:1A-C 2:2A-D 1:0B-C 1:0B-D 0:3C-D 0:3OutputADInput2aAa-A 2:1Outputa
Input4ABCDA-B 1:1A-C 2:2A-D 1:0B-C 1:0B-D 0:3C-D 0:3
OutputAD
2 seconds
64 megabytes
['implementation', '*1400']
E. Flag 2time limit per test2 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputAccording to a new ISO standard, a flag of every country should have, strangely enough, a chequered field n × m, each square should be wholly painted one of 26 colours. The following restrictions are set: In each row at most two different colours can be used. No two adjacent squares can be painted the same colour. Pay attention, please, that in one column more than two different colours can be used.Berland's government took a decision to introduce changes into their country's flag in accordance with the new standard, at the same time they want these changes to be minimal. By the given description of Berland's flag you should find out the minimum amount of squares that need to be painted different colour to make the flag meet the new ISO standard. You are as well to build one of the possible variants of the new Berland's flag.InputThe first input line contains 2 integers n and m (1 ≤ n, m ≤ 500) — amount of rows and columns in Berland's flag respectively. Then there follows the flag's description: each of the following n lines contains m characters. Each character is a letter from a to z, and it stands for the colour of the corresponding square.OutputIn the first line output the minimum amount of squares that need to be repainted to make the flag meet the new ISO standard. The following n lines should contain one of the possible variants of the new flag. Don't forget that the variant of the flag, proposed by you, should be derived from the old flag with the minimum amount of repainted squares. If the answer isn't unique, output any.ExamplesInput3 4aaaabbbbccccOutput6ababbabaacacInput3 3abaabazzzOutput4abababzbz
Input3 4aaaabbbbcccc
Output6ababbabaacac
2 seconds
128 megabytes
['dp', '*2000']
D. Seller Bobtime limit per test2 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputLast year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place: A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars. Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it. Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally.InputThe first input line contains number n (1 ≤ n ≤ 5000) — amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0 ≤ x ≤ 2000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0 ≤ x ≤ 2000).OutputOutput the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.ExamplesInput7win 10win 5win 3sell 5sell 3win 10sell 10Output1056Input3win 5sell 6sell 4Output0
Input7win 10win 5win 3sell 5sell 3win 10sell 10
Output1056
2 seconds
128 megabytes
['brute force', 'dp', 'greedy', '*2000']
C. Stripetime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputOnce Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?InputThe first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.OutputOutput the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.ExamplesInput91 5 -6 7 9 -16 0 -2 2Output3Input31 1 1Output0Input20 0Output1
Input91 5 -6 7 9 -16 0 -2 2
Output3
2 seconds
64 megabytes
['data structures', 'implementation', '*1200']
B. Platformstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIn one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l < m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the point, where Bob will fall down. The grasshopper falls down, if he finds himself not on the platform, but if he finds himself on the edge of the platform, he doesn't fall down.InputThe first input line contains 4 integer numbers n, d, m, l (1 ≤ n, d, m, l ≤ 106, l < m) — respectively: amount of platforms, length of the grasshopper Bob's jump, and numbers m and l needed to find coordinates of the k-th platform: [(k - 1)m, (k - 1)m + l].OutputOutput the coordinates of the point, where the grosshopper will fall down. Don't forget that if Bob finds himself on the platform edge, he doesn't fall down.ExamplesInput2 2 5 3Output4Input5 4 11 8Output20
Input2 2 5 3
Output4
2 seconds
64 megabytes
['brute force', 'math', '*1700']
A. Triangletime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputAt a geometry lesson Bob learnt that a triangle is called right-angled if it is nondegenerate and one of its angles is right. Bob decided to draw such a triangle immediately: on a sheet of paper he drew three points with integer coordinates, and joined them with segments of straight lines, then he showed the triangle to Peter. Peter said that Bob's triangle is not right-angled, but is almost right-angled: the triangle itself is not right-angled, but it is possible to move one of the points exactly by distance 1 so, that all the coordinates remain integer, and the triangle become right-angled. Bob asks you to help him and find out if Peter tricks him. By the given coordinates of the triangle you should find out if it is right-angled, almost right-angled, or neither of these.InputThe first input line contains 6 space-separated integers x1, y1, x2, y2, x3, y3 — coordinates of the triangle's vertices. All the coordinates are integer and don't exceed 100 in absolute value. It's guaranteed that the triangle is nondegenerate, i.e. its total area is not zero.OutputIf the given triangle is right-angled, output RIGHT, if it is almost right-angled, output ALMOST, and if it is neither of these, output NEITHER.ExamplesInput0 0 2 0 0 1OutputRIGHTInput2 3 4 5 6 6OutputNEITHERInput-1 0 2 0 0 1OutputALMOST
Input0 0 2 0 0 1
OutputRIGHT
2 seconds
64 megabytes
['brute force', 'geometry', '*1500']
E. Palisectiontime limit per test2 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputIn an English class Nick had nothing to do at all, and remembered about wonderful strings called palindromes. We should remind you that a string is called a palindrome if it can be read the same way both from left to right and from right to left. Here are examples of such strings: «eye», «pop», «level», «aba», «deed», «racecar», «rotor», «madam». Nick started to look carefully for all palindromes in the text that they were reading in the class. For each occurrence of each palindrome in the text he wrote a pair — the position of the beginning and the position of the ending of this occurrence in the text. Nick called each occurrence of each palindrome he found in the text subpalindrome. When he found all the subpalindromes, he decided to find out how many different pairs among these subpalindromes cross. Two subpalindromes cross if they cover common positions in the text. No palindrome can cross itself.Let's look at the actions, performed by Nick, by the example of text «babb». At first he wrote out all subpalindromes:• «b» — 1..1 • «bab» — 1..3 • «a» — 2..2 • «b» — 3..3 • «bb» — 3..4 • «b» — 4..4 Then Nick counted the amount of different pairs among these subpalindromes that cross. These pairs were six: 1. 1..1 cross with 1..3 2. 1..3 cross with 2..2 3. 1..3 cross with 3..3 4. 1..3 cross with 3..4 5. 3..3 cross with 3..4 6. 3..4 cross with 4..4 Since it's very exhausting to perform all the described actions manually, Nick asked you to help him and write a program that can find out the amount of different subpalindrome pairs that cross. Two subpalindrome pairs are regarded as different if one of the pairs contains a subpalindrome that the other does not.InputThe first input line contains integer n (1 ≤ n ≤ 2·106) — length of the text. The following line contains n lower-case Latin letters (from a to z).OutputIn the only line output the amount of different pairs of two subpalindromes that cross each other. Output the answer modulo 51123987.ExamplesInput4babbOutput6Input2aaOutput2
Input4babb
Output6
2 seconds
128 megabytes
['strings', '*2900']
D. Notepadtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputNick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.InputThe only input line contains three space-separated integers b, n and c (2 ≤ b < 10106, 1 ≤ n < 10106, 1 ≤ c ≤ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.OutputIn the only line output the amount of numbers written on the same page as the last number.ExamplesInput2 3 3Output1Input2 3 4Output4NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.
Input2 3 3
Output1
2 seconds
64 megabytes
['number theory', '*2400']
C. Balancetime limit per test3 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputNick likes strings very much, he likes to rotate them, sort them, rearrange characters within a string... Once he wrote a random string of characters a, b, c on a piece of paper and began to perform the following operations: to take two adjacent characters and replace the second character with the first one, to take two adjacent characters and replace the first character with the second one To understand these actions better, let's take a look at a string «abc». All of the following strings can be obtained by performing one of the described operations on «abc»: «bbc», «abb», «acc». Let's denote the frequency of a character for each of the characters a, b and c as the number of occurrences of this character in the string. For example, for string «abc»: |a| = 1, |b| = 1, |c| = 1, and for string «bbc»: |a| = 0, |b| = 2, |c| = 1. While performing the described operations, Nick sometimes got balanced strings. Let's say that a string is balanced, if the frequencies of each character differ by at most 1. That is  - 1 ≤ |a| - |b| ≤ 1,  - 1 ≤ |a| - |c| ≤ 1 и  - 1 ≤ |b| - |c| ≤ 1. Would you help Nick find the number of different balanced strings that can be obtained by performing the operations described above, perhaps multiple times, on the given string s. This number should be calculated modulo 51123987.InputThe first line contains integer n (1 ≤ n ≤ 150) — the length of the given string s. Next line contains the given string s. The initial string can be balanced as well, in this case it should be counted too. The given string s consists only of characters a, b and c.OutputOutput the only number — the number of different balanced strings that can be obtained by performing the described operations, perhaps multiple times, on the given string s, modulo 51123987.ExamplesInput4abcaOutput7Input4abbcOutput3Input2abOutput1NoteIn the first sample it is possible to get 51 different strings through the described operations, but only 7 of them are balanced: «abca», «bbca», «bcca», «bcaa», «abcc», «abbc», «aabc». In the second sample: «abbc», «aabc», «abcc». In the third sample there is only one balanced string — «ab» itself.
Input4abca
Output7
3 seconds
128 megabytes
['dp', '*2500']
B. Hierarchytime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputNick's company employed n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: «employee ai is ready to become a supervisor of employee bi at extra cost ci». The qualification qj of each employee is known, and for each application the following is true: qai > qbi. Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.InputThe first input line contains integer n (1 ≤ n ≤ 1000) — amount of employees in the company. The following line contains n space-separated numbers qj (0 ≤ qj ≤ 106)— the employees' qualifications. The following line contains number m (0 ≤ m ≤ 10000) — amount of received applications. The following m lines contain the applications themselves, each of them in the form of three space-separated numbers: ai, bi and ci (1 ≤ ai, bi ≤ n, 0 ≤ ci ≤ 106). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application qai > qbi.OutputOutput the only line — the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.ExamplesInput47 2 3 141 2 52 4 13 4 11 3 5Output11Input31 2 323 1 23 1 3Output-1NoteIn the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer is -1.
Input47 2 3 141 2 52 4 13 4 11 3 5
Output11
2 seconds
64 megabytes
['dfs and similar', 'dsu', 'greedy', 'shortest paths', '*1500']
A. Noldbach problemtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputNick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. Since Nick is interested only in prime numbers, Noldbach problem states that at least k prime numbers from 2 to n inclusively can be expressed as the sum of three integer numbers: two neighboring prime numbers and 1. For example, 19 = 7 + 11 + 1, or 13 = 5 + 7 + 1.Two prime numbers are called neighboring if there are no other prime numbers between them.You are to help Nick, and find out if he is right or wrong.InputThe first line of the input contains two integers n (2 ≤ n ≤ 1000) and k (0 ≤ k ≤ 1000).OutputOutput YES if at least k prime numbers from 2 to n inclusively can be expressed as it was described above. Otherwise output NO.ExamplesInput27 2OutputYESInput45 7OutputNONoteIn the first sample the answer is YES since at least two numbers can be expressed as it was described (for example, 13 and 19). In the second sample the answer is NO since it is impossible to express 7 prime numbers from 2 to 45 in the desired form.
Input27 2
OutputYES
2 seconds
64 megabytes
['brute force', 'math', 'number theory', '*1000']
E. Fishtime limit per test3 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputn fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.InputThe first line contains integer n (1 ≤ n ≤ 18) — the amount of fish in the lake. Then there follow n lines with n real numbers each — matrix a. aij (0 ≤ aij ≤ 1) — the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij = 1 - aji. All real numbers are given with not more than 6 characters after the decimal point.OutputOutput n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.ExamplesInput20 0.50.5 0Output0.500000 0.500000 Input50 1 1 1 10 0 0.5 0.5 0.50 0.5 0 0.5 0.50 0.5 0.5 0 0.50 0.5 0.5 0.5 0Output1.000000 0.000000 0.000000 0.000000 0.000000
Input20 0.50.5 0
Output0.500000 0.500000
3 seconds
128 megabytes
['bitmasks', 'dp', 'probabilities', '*1900']
D. Loggingtime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer — Alex — managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format «[time]: message». So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written.So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications).We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day.InputThe first input line contains number n (1 ≤ n ≤ 100). The following n lines contain recordings in format «[time]: message», where time is given in format «hh:mm x.m.». For hh two-digit numbers from 01 to 12 are used, for mm two-digit numbers from 00 to 59 are used, and x is either character «a» or character «p». A message is a non-empty sequence of Latin letters and/or spaces, it doesn't start or end with a space. The length of each message doesn't exceed 20.OutputOutput one number — the minimum amount of days covered by the log.ExamplesInput5[05:00 a.m.]: Server is started[05:00 a.m.]: Rescan initialized[01:13 p.m.]: Request processed[01:10 p.m.]: Request processed[11:40 p.m.]: Rescan completedOutput2Input3[09:00 a.m.]: User logged in[08:00 a.m.]: User logged in[07:00 a.m.]: User logged inOutput3NoteFormally the 12-hour time format is described at: http://en.wikipedia.org/wiki/12-hour_clock. The problem authors recommend you to look through these descriptions before you start with the problem.
Input5[05:00 a.m.]: Server is started[05:00 a.m.]: Rescan initialized[01:13 p.m.]: Request processed[01:10 p.m.]: Request processed[11:40 p.m.]: Rescan completed
Output2
1 second
64 megabytes
['implementation', 'strings', '*1900']
C. Monitortime limit per test0.5 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputReca company makes monitors, the most popular of their models is AB999 with the screen size a × b centimeters. Because of some production peculiarities a screen parameters are integer numbers. Recently the screen sides ratio x: y became popular with users. That's why the company wants to reduce monitor AB999 size so that its screen sides ratio becomes x: y, at the same time they want its total area to be maximal of all possible variants. Your task is to find the screen parameters of the reduced size model, or find out that such a reduction can't be performed.InputThe first line of the input contains 4 integers — a, b, x and y (1 ≤ a, b, x, y ≤ 2·109).OutputIf the answer exists, output 2 positive integers — screen parameters of the reduced size model. Output 0 0 otherwise.ExamplesInput800 600 4 3Output800 600Input1920 1200 16 9Output1920 1080Input1 1 1 2Output0 0
Input800 600 4 3
Output800 600
0.5 second
64 megabytes
['binary search', 'number theory', '*1800']
B. Burglar and Matchestime limit per test0.5 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputA burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.InputThe first line of the input contains integer n (1 ≤ n ≤ 2·108) and integer m (1 ≤ m ≤ 20). The i + 1-th line contains a pair of numbers ai and bi (1 ≤ ai ≤ 108, 1 ≤ bi ≤ 10). All the input numbers are integer.OutputOutput the only number — answer to the problem.ExamplesInput7 35 102 53 6Output62Input3 31 32 23 1Output7
Input7 35 102 53 6
Output62
0.5 second
64 megabytes
['greedy', 'implementation', 'sortings', '*900']
A. Flagtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputAccording to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland's government asked you to find out whether their flag meets the new ISO standard.InputThe first line of the input contains numbers n and m (1 ≤ n, m ≤ 100), n — the amount of rows, m — the amount of columns on the flag of Berland. Then there follows the description of the flag: each of the following n lines contain m characters. Each character is a digit between 0 and 9, and stands for the colour of the corresponding square.OutputOutput YES, if the flag meets the new ISO standard, and NO otherwise.ExamplesInput3 3000111222OutputYESInput3 3000000111OutputNOInput3 3000111002OutputNO
Input3 3000111222
OutputYES
2 seconds
64 megabytes
['implementation', '*800']
E. Trianglestime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputLast summer Peter was at his granny's in the country, when a wolf attacked sheep in the nearby forest. Now he fears to walk through the forest, to walk round the forest, even to get out of the house. He explains this not by the fear of the wolf, but by a strange, in his opinion, pattern of the forest that has n levels, where n is an even number.In the local council you were given an area map, where the granny's house is marked by point H, parts of dense forest are marked grey (see the picture to understand better).After a long time at home Peter decided to yield to his granny's persuasions and step out for a breath of fresh air. Being prudent, Peter plans the route beforehand. The route, that Peter considers the most suitable, has the following characteristics: it starts and ends in the same place — the granny's house; the route goes along the forest paths only (these are the segments marked black in the picture); the route has positive length (to step out for a breath of fresh air Peter has to cover some distance anyway); the route cannot cross itself; there shouldn't be any part of dense forest within the part marked out by this route; You should find the amount of such suitable oriented routes modulo 1000000009. The example of the area map for n = 12 is given in the picture. Since the map has a regular structure, you can construct it for other n by analogy using the example.InputThe input data contain the only even integer n (2 ≤ n ≤ 106).OutputOutput the only number — the amount of Peter's routes modulo 1000000009.ExamplesInput2Output10Input4Output74
Input2
Output10
1 second
64 megabytes
['combinatorics', 'dp', '*2600']
D. Maptime limit per test2 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputThere is an area map that is a rectangular matrix n × m, each cell of the matrix contains the average height of a corresponding area part. Peter works for a company that has to build several cities within this area, each of the cities will occupy a rectangle a × b cells on the map. To start construction works in a particular place Peter needs to remove excess ground from the construction site where a new city will be built. To do so he chooses a cell of the minimum height within this site, and removes excess ground from other cells of the site down to this minimum level. Let's consider that to lower the ground level from h2 to h1 (h1 ≤ h2) they need to remove h2 - h1 ground units.Let's call a site's position optimal, if the amount of the ground removed from this site is minimal compared to other possible positions. Peter constructs cities according to the following algorithm: from all the optimum site's positions he chooses the uppermost one. If this position is not unique, he chooses the leftmost one. Then he builds a city on this site. Peter repeats this process untill he can build at least one more city. For sure, he cannot carry out construction works on the occupied cells. Would you, please, help Peter place cities according to the algorithm? InputThe first line contains four space-separated integers: map sizes n, m and city sizes a, b (1 ≤ a ≤ n ≤ 1000, 1 ≤ b ≤ m ≤ 1000). Then there follow n lines, each contains m non-negative space-separated numbers, describing the height matrix. Each number doesn't exceed 109. OutputIn the first line output k — the amount of constructed cities. In each of the following k lines output 3 space-separated numbers — the row number and the column number of the upper-left corner of a subsequent construction site, and the amount of the ground to remove from it. Output the sites in the order of their building up.ExamplesInput2 2 1 21 23 5Output21 1 12 1 2Input4 4 2 21 5 3 42 7 6 11 1 2 22 2 1 2Output33 1 23 3 31 2 9
Input2 2 1 21 23 5
Output21 1 12 1 2
2 seconds
128 megabytes
['data structures', 'implementation', 'sortings', '*2500']
C. Industrial Nimtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThere are n stone quarries in Petrograd.Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it.Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses.Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone «tolik» and the other one «bolik».InputThe first line of the input contains one integer number n (1 ≤ n ≤ 105) — the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1 ≤ xi, mi ≤ 1016) — the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry.OutputOutput «tolik» if the oligarch who takes a stone first wins, and «bolik» otherwise.ExamplesInput22 13 2OutputtolikInput41 11 11 11 1Outputbolik
Input22 13 2
Outputtolik
2 seconds
64 megabytes
['games', '*2000']
B. Lasertime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputPetya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of n × m cells and a robotic arm. Each cell of the field is a 1 × 1 square. The robotic arm has two lasers pointed at the field perpendicularly to its surface. At any one time lasers are pointed at the centres of some two cells. Since the lasers are on the robotic hand, their movements are synchronized — if you move one of the lasers by a vector, another one moves by the same vector.The following facts about the experiment are known: initially the whole field is covered with a chocolate bar of the size n × m, both lasers are located above the field and are active; the chocolate melts within one cell of the field at which the laser is pointed; all moves of the robotic arm should be parallel to the sides of the field, after each move the lasers should be pointed at the centres of some two cells; at any one time both lasers should be pointed at the field. Petya doesn't want to become a second Gordon Freeman. You are given n, m and the cells (x1, y1) and (x2, y2), where the lasers are initially pointed at (xi is a column number, yi is a row number). Rows are numbered from 1 to m from top to bottom and columns are numbered from 1 to n from left to right. You are to find the amount of cells of the field on which the chocolate can't be melted in the given conditions.InputThe first line contains one integer number t (1 ≤ t ≤ 10000) — the number of test sets. Each of the following t lines describes one test set. Each line contains integer numbers n, m, x1, y1, x2, y2, separated by a space (2 ≤ n, m ≤ 109, 1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m). Cells (x1, y1) and (x2, y2) are distinct.OutputEach of the t lines of the output should contain the answer to the corresponding input test set.ExamplesInput24 4 1 1 3 34 3 1 1 2 2Output82
Input24 4 1 1 3 34 3 1 1 2 2
Output82
1 second
64 megabytes
['math', '*1800']
A. Cottage Villagetime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputA new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?InputThe first line of the input data contains numbers n and t (1 ≤ n, t ≤ 1000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi — x-coordinate of the centre of the i-th house, and ai — length of its side ( - 1000 ≤ xi ≤ 1000, 1 ≤ ai ≤ 1000).OutputOutput the amount of possible positions of the new house.ExamplesInput2 20 46 2Output4Input2 20 45 2Output3Input2 30 45 2Output2NoteIt is possible for the x-coordinate of the new house to have non-integer value.
Input2 20 46 2
Output4
2 seconds
64 megabytes
['implementation', 'sortings', '*1200']
E. Camelstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputBob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with t humps, representing them as polylines in the plane. Each polyline consists of n vertices with coordinates (x1, y1), (x2, y2), ..., (xn, yn). The first vertex has a coordinate x1 = 1, the second — x2 = 2, etc. Coordinates yi might be any, but should satisfy the following conditions: there should be t humps precisely, i.e. such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 < yj > yj + 1, there should be precisely t - 1 such indexes j (2 ≤ j ≤ n - 1), so that yj - 1 > yj < yj + 1, no segment of a polyline should be parallel to the Ox-axis, all yi are integers between 1 and 4. For a series of his drawings of camels with t humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with t humps for a given number n.InputThe first line contains a pair of integers n and t (3 ≤ n ≤ 20, 1 ≤ t ≤ 10).OutputOutput the required amount of camels with t humps.ExamplesInput6 1Output6Input4 2Output0NoteIn the first sample test sequences of y-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 и 234321 (each digit corresponds to one value of yi).
Input6 1
Output6
2 seconds
64 megabytes
['dp', '*1900']
D. Two Pathstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputAs you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.InputThe first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).OutputOutput the maximum possible profit.ExamplesInput41 22 33 4Output1Input71 21 31 41 51 61 7Output0Input61 22 32 45 46 4Output4
Input41 22 33 4
Output1
2 seconds
64 megabytes
['dfs and similar', 'dp', 'graphs', 'shortest paths', 'trees', 'two pointers', '*1900']
C. Four Segmentstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputSeveral months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the program detects if the four given segments form a rectangle of a positive area and with sides parallel to coordinate axes. As Alex does badly at school and can't write this program by himself, he asks you to help him.InputThe input data contain four lines. Each of these lines contains four integers x1, y1, x2, y2 ( - 109 ≤ x1, y1, x2, y2 ≤ 109) — coordinates of segment's beginning and end positions. The given segments can degenerate into points.OutputOutput the word «YES», if the given four segments form the required rectangle, otherwise output «NO».ExamplesInput1 1 6 11 0 6 06 0 6 11 1 1 0OutputYESInput0 0 0 32 0 0 02 2 2 00 2 2 2OutputNO
Input1 1 6 11 0 6 06 0 6 11 1 1 0
OutputYES
2 seconds
64 megabytes
['brute force', 'constructive algorithms', 'geometry', 'implementation', 'math', '*1700']
B. Young Photographertime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputAmong other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second — from a2 to b2What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.InputThe first line of the input file contains integers n and x0 (1 ≤ n ≤ 100; 0 ≤ x0 ≤ 1000). The following n lines contain pairs of integers ai, bi (0 ≤ ai, bi ≤ 1000; ai ≠ bi).OutputOutput the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.ExamplesInput3 30 714 24 6Output1
Input3 30 714 24 6
Output1
2 seconds
64 megabytes
['implementation', '*1000']
A. Lettertime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputA boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.InputThe first line of the input data contains numbers n and m (1 ≤ n, m ≤ 50), n — amount of lines, and m — amount of columns on Bob's sheet. The following n lines contain m characters each. Character «.» stands for a non-shaded square on the sheet, and «*» — for a shaded square. It is guaranteed that Bob has shaded at least one square.OutputOutput the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better.ExamplesInput6 7.........***....*......***....*......***..Output****..****..***Input3 3****.****Output****.****
Input6 7.........***....*......***....*......***..
Output****..****..***
1 second
64 megabytes
['implementation', '*800']
E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai, then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInput8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2Output8 78 57 3
Input8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2
Output8 78 57 3
1 second
64 megabytes
['data structures', 'dsu', '*2700']
D. Trianglestime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputLittle Petya likes to draw. He drew N red and M blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.InputThe first line contains two non-negative integer numbers N and M (0 ≤ N ≤ 500, 0 ≤ M ≤ 500) — the number of red and blue points respectively. The following N lines contain two integer numbers each — coordinates of red points. The following M lines contain two integer numbers each — coordinates of blue points. All coordinates do not exceed 109 by absolute value.OutputOutput one integer — the number of distinct triangles with vertices in red points which do not contain any blue point inside.ExamplesInput4 10 010 010 105 42 1Output2Input5 55 106 18 6-6 -77 -15 -110 -4-10 -8-10 5-2 -8Output7
Input4 10 010 010 105 42 1
Output2
2 seconds
64 megabytes
['dp', 'geometry', '*2600']
C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInput53 2 -1 2 11Output4Input52 1 1 1 1Output1
Input53 2 -1 2 11
Output4
1 second
64 megabytes
['dp', 'sortings', '*2200']
B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInput34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputYESNOYES
Input34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1
OutputYESNOYES
1 second
64 megabytes
['geometry', 'implementation', '*2000']
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction, written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInput5Output7/3Input3Output2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
Input5
Output7/3
1 second
64 megabytes
['implementation', 'math', '*1000']
E. Start of the seasontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBefore the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size n × n (n is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to n - 1, main diagonal should contain only zeroes and matrix should be symmetric. Moreover, all numbers in each row should be different. Magicians are very tired of the thinking process, so they ask you to write a program to find such matrix.InputThe first line contains one integer n (2 ≤ n ≤ 1000), n is even.OutputOutput n lines with n numbers each — the required matrix. Separate numbers with spaces. If there are several solutions, output any.ExamplesInput2Output0 11 0Input4Output0 1 3 21 0 2 33 2 0 12 3 1 0
Input2
Output0 11 0
2 seconds
256 megabytes
['constructive algorithms', '*2100']
D. Balltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputN ladies attend the ball in the King's palace. Every lady can be described with three values: beauty, intellect and richness. King's Master of Ceremonies knows that ladies are very special creatures. If some lady understands that there is other lady at the ball which is more beautiful, smarter and more rich, she can jump out of the window. He knows values of all ladies and wants to find out how many probable self-murderers will be on the ball. Lets denote beauty of the i-th lady by Bi, her intellect by Ii and her richness by Ri. Then i-th lady is a probable self-murderer if there is some j-th lady that Bi < Bj, Ii < Ij, Ri < Rj. Find the number of probable self-murderers.InputThe first line contains one integer N (1 ≤ N ≤ 500000). The second line contains N integer numbers Bi, separated by single spaces. The third and the fourth lines contain sequences Ii and Ri in the same format. It is guaranteed that 0 ≤ Bi, Ii, Ri ≤ 109.OutputOutput the answer to the problem.ExamplesInput31 4 24 3 22 5 3Output1
Input31 4 24 3 22 5 3
Output1
2 seconds
256 megabytes
['data structures', 'sortings', '*2400']
C. Fruitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times. When he came to the fruit stall of Ashot, he saw that the seller hadn't distributed price tags to the goods, but put all price tags on the counter. Later Ashot will attach every price tag to some kind of fruits, and Valera will be able to count the total price of all fruits from his list. But Valera wants to know now what can be the smallest total price (in case of the most «lucky» for him distribution of price tags) and the largest total price (in case of the most «unlucky» for him distribution of price tags).InputThe first line of the input contains two integer number n and m (1 ≤ n, m ≤ 100) — the number of price tags (which is equal to the number of different kinds of fruits that Ashot sells) and the number of items in Valera's list. The second line contains n space-separated positive integer numbers. Each of them doesn't exceed 100 and stands for the price of one fruit of some kind. The following m lines contain names of the fruits from the list. Each name is a non-empty string of small Latin letters which length doesn't exceed 32. It is guaranteed that the number of distinct fruits from the list is less of equal to n. Also it is known that the seller has in stock all fruits that Valera wants to buy.OutputPrint two numbers a and b (a ≤ b) — the minimum and the maximum possible sum which Valera may need to buy all fruits from his list.ExamplesInput5 34 2 1 10 5appleorangemangoOutput7 19Input6 53 5 1 6 8 1peachgrapefruitbananaorangeorangeOutput11 30
Input5 34 2 1 10 5appleorangemango
Output7 19
1 second
256 megabytes
['greedy', 'implementation', 'sortings', '*1100']
B. Correct Solution?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said:—Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.—No problem! — said Bob and immediately gave her an answer.Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.InputThe first line contains one integer n (0 ≤ n ≤ 109) without leading zeroes. The second lines contains one integer m (0 ≤ m ≤ 109) — Bob's answer, possibly with leading zeroes.OutputPrint OK if Bob's answer is correct and WRONG_ANSWER otherwise.ExamplesInput33101033OutputOKInput45OutputWRONG_ANSWER
Input33101033
OutputOK
2 seconds
256 megabytes
['implementation', 'sortings', '*1100']
A. Super Agenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3 × 3 with digits from 1 to 9.Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.InputInput contains the matrix of three rows of three symbols each. Symbol «X» means that the corresponding button was pressed, and «.» means that is was not pressed. The matrix may contain no «X», also it may contain no «.».OutputPrint YES if the password is symmetric with respect to the central button of the terminal and NO otherwise.ExamplesInputXX.....XXOutputYESInputX.XX.....OutputNONoteIf you are not familiar with the term «central symmetry», you may look into http://en.wikipedia.org/wiki/Central_symmetry
InputXX.....XX
OutputYES
2 seconds
256 megabytes
['implementation', '*800']
E. Forward, march!time limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputJack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or — horror of horrors! — stops for a while. For example, if Jack uses the sequence 'right, left, break', when the sergeant yells: 'Left! Right! Left! Right! Left! Right!', Jack first makes a step with the right foot, then one with the left foot, then he is confused and stops for a moment, then again - this time according to the order - starts with the right foot, then uses the left foot, then - to the sergeant's irritation - he stops to catch his breath, to incorrectly start with the right foot again... Marching this way, Jack will make the step that he is supposed to in the given moment in only one third of cases.When the officers convinced him he should do something about it, Jack decided to modify the basic sequence of steps that he repeats. However, in order not to get too tired, he has decided that the only thing he'll do is adding any number of breaks in any positions of the original sequence (a break corresponds to stopping for the duration of one step). Of course, Jack can't make a step on the same foot twice in a row, if there is no pause between these steps. It is, however, not impossible that the sequence of steps he used so far is incorrect (it would explain a lot, actually).Help Private Jack! Given the sequence of steps he keeps repeating, calculate the maximal percentage of time that he can spend marching correctly after adding some breaks to his scheme.InputThe first line of input contains a sequence consisting only of characters 'L', 'R' and 'X', where 'L' corresponds to a step with the left foot, 'R' — with the right foot, and 'X' — to a break. The length of the sequence will not exceed 106.OutputOutput the maximum percentage of time that Jack can spend marching correctly, rounded down to exactly six digits after the decimal point.ExamplesInputXOutput0.000000InputLXRROutput50.000000NoteIn the second example, if we add two breaks to receive LXXRXR, Jack will march: LXXRXRLXXRXRL... instead of LRLRLRLRLRLRL... and will make the correct step in half the cases. If we didn't add any breaks, the sequence would be incorrect — Jack can't step on his right foot twice in a row.
InputX
Output0.000000
1 second
64 megabytes
['binary search', 'dp', 'greedy', '*2800']
D. A Simple Tasktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges.InputThe first line of input contains two integers n and m (1 ≤ n ≤ 19, 0 ≤ m) – respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two integers a and b, (1 ≤ a, b ≤ n, a ≠ b) indicating that vertices a and b are connected by an undirected edge. There is no more than one edge connecting any pair of vertices.OutputOutput the number of cycles in the given graph.ExamplesInput4 61 21 31 42 32 43 4Output7NoteThe example graph is a clique and contains four cycles of length 3 and three cycles of length 4.
Input4 61 21 31 42 32 43 4
Output7
2 seconds
256 megabytes
['bitmasks', 'dp', 'graphs', '*2200']
C. How Many Squares?time limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a 0-1 rectangular matrix. What is the number of squares in it? A square is a solid square frame (border) with linewidth equal to 1. A square should be at least 2 × 2. We are only interested in two types of squares: squares with each side parallel to a side of the matrix; squares with each side parallel to a diagonal of the matrix. For example the following matrix contains only one square of the first type: 0000000 0111100 0100100 0100100 0111100The following matrix contains only one square of the second type:00000000010000010100000100000000000Regardless of type, a square must contain at least one 1 and can't touch (by side or corner) any foreign 1. Of course, the lengths of the sides of each square should be equal.How many squares are in the given matrix?InputThe first line contains integer t (1 ≤ t ≤ 10000), where t is the number of test cases in the input. Then test cases follow. Each case starts with a line containing integers n and m (2 ≤ n, m ≤ 250), where n is the number of rows and m is the number of columns. The following n lines contain m characters each (0 or 1).The total number of characters in all test cases doesn't exceed 106 for any input file.OutputYou should output exactly t lines, with the answer to the i-th test case on the i-th line.ExamplesInput28 8000100010010100001000100100000100100010000101000110100111100001110 101111111000100000100010110010001011001010100000110110010010101010101000100100100010000010001111111000Output12Input112 11111111111111000000000110111111101101000001011010110010110101100101101000001011010000010110111111101100000000011111111111100000000000Output3
Input28 8000100010010100001000100100000100100010000101000110100111100001110 101111111000100000100010110010001011001010100000110110010010101010101000100100100010000010001111111000
Output12
2 seconds
64 megabytes
['implementation', '*2200']
B. Jumping Jacktime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputJack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point x. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or right with each jump. He wonders how many jumps he needs to reach x.InputThe input data consists of only one integer x ( - 109 ≤ x ≤ 109).OutputOutput the minimal number of jumps that Jack requires to reach x.ExamplesInput2Output3Input6Output3Input0Output0
Input2
Output3
1 second
64 megabytes
['math', '*1600']
A. Increasing Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputA sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t.You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing?InputThe first line of the input contains two integer numbers n and d (2 ≤ n ≤ 2000, 1 ≤ d ≤ 106). The second line contains space separated sequence b0, b1, ..., bn - 1 (1 ≤ bi ≤ 106).OutputOutput the minimal number of moves needed to make the sequence increasing.ExamplesInput4 21 3 3 2Output3
Input4 21 3 3 2
Output3
1 second
64 megabytes
['constructive algorithms', 'implementation', 'math', '*900']
E. Greedy Changetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBilly investigates the question of applying greedy algorithm to different spheres of life. At the moment he is studying the application of greedy algorithm to the problem about change. There is an amount of n coins of different face values, and the coins of each value are not limited in number. The task is to collect the sum x with the minimum amount of coins. Greedy algorithm with each its step takes the coin of the highest face value, not exceeding x. Obviously, if among the coins' face values exists the face value 1, any sum x can be collected with the help of greedy algorithm. However, greedy algorithm does not always give the optimal representation of the sum, i.e. the representation with the minimum amount of coins. For example, if there are face values {1, 3, 4} and it is asked to collect the sum 6, greedy algorithm will represent the sum as 4 + 1 + 1, while the optimal representation is 3 + 3, containing one coin less. By the given set of face values find out if there exist such a sum x that greedy algorithm will collect in a non-optimal way. If such a sum exists, find out the smallest of these sums.InputThe first line contains an integer n (1 ≤ n ≤ 400) — the amount of the coins' face values. The second line contains n integers ai (1 ≤ ai ≤ 109), describing the face values. It is guaranteed that a1 > a2 > ... > an and an = 1.OutputIf greedy algorithm collects any sum in an optimal way, output -1. Otherwise output the smallest sum that greedy algorithm collects in a non-optimal way.ExamplesInput525 10 5 2 1Output-1Input34 3 1Output6
Input525 10 5 2 1
Output-1
2 seconds
256 megabytes
['constructive algorithms', '*2600']
D. LCIStime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem differs from one which was on the online contest.The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.InputThe first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.OutputIn the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.ExamplesInput72 3 1 6 5 4 641 3 5 6Output33 5 6 Input51 2 0 2 131 0 1Output20 1
Input72 3 1 6 5 4 641 3 5 6
Output33 5 6
1 second
256 megabytes
['dp', '*2800']
C. Digital Roottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNot long ago Billy came across such a problem, where there were given three natural numbers A, B and C from the range [1, N], and it was asked to check whether the equation AB = C is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root d(x) of the number x is the sum s(x) of all the digits of this number, if s(x) ≤ 9, otherwise it is d(s(x)). For example, a digital root of the number 6543 is calculated as follows: d(6543) = d(6 + 5 + 4 + 3) = d(18) = 9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors' digital roots, i.e. d(xy) = d(d(x)d(y)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient. That's why he asks you to find out the amount of test examples for the given problem such that the algorithm proposed by Billy makes mistakes.InputThe first line contains the only number N (1 ≤ N ≤ 106).OutputOutput one number — the amount of required A, B and C from the range [1, N].ExamplesInput4Output2Input5Output6NoteFor the first sample the required triples are (3, 4, 3) and (4, 3, 3).
Input4
Output2
2 seconds
256 megabytes
['number theory', '*2000']
B. Cinema Cashiertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAll cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the responsibility of a special seating program. It was found out that the large majority of Berland's inhabitants go to the cinema in order to watch a movie, that's why they want to sit as close to the hall center as possible. Moreover, a company of M people, who come to watch a movie, want necessarily to occupy M successive seats in one row. Let's formulate the algorithm, according to which the program chooses seats and sells tickets. As the request for M seats comes, the program should determine the row number x and the segment [yl, yr] of the seats numbers in this row, where yr - yl + 1 = M. From all such possible variants as a final result the program should choose the one with the minimum function value of total seats remoteness from the center. Say, — the row and the seat numbers of the most "central" seat. Then the function value of seats remoteness from the hall center is . If the amount of minimum function values is more than one, the program should choose the one that is closer to the screen (i.e. the row number x is lower). If the variants are still multiple, it should choose the one with the minimum yl. If you did not get yet, your task is to simulate the work of this program. InputThe first line contains two integers N and K (1 ≤ N ≤ 1000, 1 ≤ K ≤ 99) — the amount of requests and the hall size respectively. The second line contains N space-separated integers Mi from the range [1, K] — requests to the program.OutputOutput N lines. In the i-th line output «-1» (without quotes), if it is impossible to find Mi successive seats in one row, otherwise output three numbers x, yl, yr. Separate the numbers with a space.ExamplesInput2 11 1Output1 1 1-1Input4 31 2 3 1Output2 2 21 1 23 1 32 1 1
Input2 11 1
Output1 1 1-1
1 second
256 megabytes
['dp', 'implementation', '*1500']
A. Power Consumption Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTom is interested in power consumption of his favourite laptop. His laptop has three modes. In normal mode laptop consumes P1 watt per minute. T1 minutes after Tom moved the mouse or touched the keyboard for the last time, a screensaver starts and power consumption changes to P2 watt per minute. Finally, after T2 minutes from the start of the screensaver, laptop switches to the "sleep" mode and consumes P3 watt per minute. If Tom moves the mouse or touches the keyboard when the laptop is in the second or in the third mode, it switches to the first (normal) mode. Tom's work with the laptop can be divided into n time periods [l1, r1], [l2, r2], ..., [ln, rn]. During each interval Tom continuously moves the mouse and presses buttons on the keyboard. Between the periods Tom stays away from the laptop. Find out the total amount of power consumed by the laptop during the period [l1, rn].InputThe first line contains 6 integer numbers n, P1, P2, P3, T1, T2 (1 ≤ n ≤ 100, 0 ≤ P1, P2, P3 ≤ 100, 1 ≤ T1, T2 ≤ 60). The following n lines contain description of Tom's work. Each i-th of these lines contains two space-separated integers li and ri (0 ≤ li < ri ≤ 1440, ri < li + 1 for i < n), which stand for the start and the end of the i-th period of work.OutputOutput the answer to the problem.ExamplesInput1 3 2 1 5 100 10Output30Input2 8 4 2 5 1020 3050 100Output570
Input1 3 2 1 5 100 10
Output30
1 second
256 megabytes
['implementation', '*900']
E. Interesting Graph and Applestime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputHexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A funny ring is a cycle that goes through all the vertices just once. Moreover, loops are funny rings too.She has already drawn the apples and some of the graph edges. But now it is not clear, how to connect the rest of the vertices to get an interesting graph as a result. The answer should contain the minimal amount of added edges. And furthermore, the answer should be the lexicographically smallest one. The set of edges (x1, y1), (x2, y2), ..., (xn, yn), where xi ≤ yi, is lexicographically smaller than the set (u1, v1), (u2, v2), ..., (un, vn), where ui ≤ vi, provided that the sequence of integers x1, y1, x2, y2, ..., xn, yn is lexicographically smaller than the sequence u1, v1, u2, v2, ..., un, vn. If you do not cope, Hexadecimal will eat you. ...eat you alive.InputThe first line of the input data contains a pair of integers n and m (1 ≤ n ≤ 50, 0 ≤ m ≤ 2500) — the amount of vertices and edges respectively. The following lines contain pairs of numbers xi and yi (1 ≤ xi, yi ≤ n) — the vertices that are already connected by edges. The initial graph may contain multiple edges and loops.OutputIn the first line output «YES» or «NO»: if it is possible or not to construct an interesting graph. If the answer is «YES», in the second line output k — the amount of edges that should be added to the initial graph. Finally, output k lines: pairs of vertices xj and yj, between which edges should be drawn. The result may contain multiple edges and loops. k can be equal to zero.ExamplesInput3 21 22 3OutputYES11 3
Input3 21 22 3
OutputYES11 3
1 second
64 megabytes
['dfs and similar', 'dsu', 'graphs', '*2300']