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
E2. Space Voyagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet.The Smart Beaver is going to bring some presents from ABBYY to the planets he will be visiting. The presents are packed in suitcases, x presents in each. The Beaver will take to the ship exactly a1 + ... + an suitcases.As the Beaver lands on the i-th planet, he takes ai suitcases and goes out. On the first day on the planet the Beaver takes a walk and gets to know the citizens. On the second and all subsequent days the Beaver gives presents to the citizens β€” each of the bi citizens gets one present per day. The Beaver leaves the planet in the evening of the day when the number of presents left is strictly less than the number of citizens (i.e. as soon as he won't be able to give away the proper number of presents the next day). He leaves the remaining presents at the hotel.The Beaver is going to spend exactly c days traveling. The time spent on flights between the planets is considered to be zero. In how many ways can one choose the positive integer x so that the planned voyage will take exactly c days?InputThe first input line contains space-separated integers n and c β€” the number of planets that the Beaver is going to visit and the number of days he is going to spend traveling, correspondingly.The next n lines contain pairs of space-separated integers ai, bi (1 ≀ i ≀ n) β€” the number of suitcases he can bring to the i-th planet and the number of citizens of the i-th planet, correspondingly.The input limitations for getting 30 points are: 1 ≀ n ≀ 100 1 ≀ ai ≀ 100 1 ≀ bi ≀ 100 1 ≀ c ≀ 100 The input limitations for getting 100 points are: 1 ≀ n ≀ 104 0 ≀ ai ≀ 109 1 ≀ bi ≀ 109 1 ≀ c ≀ 109 Due to possible overflow, it is recommended to use the 64-bit arithmetic. In some solutions even the 64-bit arithmetic can overflow. So be careful in calculations!OutputPrint a single number k β€” the number of ways to choose x so as to travel for exactly c days. If there are infinitely many possible values of x, print -1.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.ExamplesInput2 51 52 4Output1NoteIn the first example there is only one suitable value x = 5. Then the Beaver takes 1 suitcase with 5 presents to the first planet. Here he spends 2 days: he hangs around on the first day, and he gives away five presents on the second day. He takes 2 suitcases with 10 presents to the second planet. Here he spends 3 days β€” he gives away 4 presents on the second and the third days and leaves the remaining 2 presents at the hotel. In total, the Beaver spends 5 days traveling.For x = 4 or less the Beaver won't have enough presents for the second day on the first planet, so the voyage will end too soon. For x = 6 and more the Beaver will spend at least one more day on the second planet, and the voyage will take too long.
Input2 51 52 4
Output1
2 seconds
256 megabytes
['binary search', '*1900']
E1. Space Voyagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet.The Smart Beaver is going to bring some presents from ABBYY to the planets he will be visiting. The presents are packed in suitcases, x presents in each. The Beaver will take to the ship exactly a1 + ... + an suitcases.As the Beaver lands on the i-th planet, he takes ai suitcases and goes out. On the first day on the planet the Beaver takes a walk and gets to know the citizens. On the second and all subsequent days the Beaver gives presents to the citizens β€” each of the bi citizens gets one present per day. The Beaver leaves the planet in the evening of the day when the number of presents left is strictly less than the number of citizens (i.e. as soon as he won't be able to give away the proper number of presents the next day). He leaves the remaining presents at the hotel.The Beaver is going to spend exactly c days traveling. The time spent on flights between the planets is considered to be zero. In how many ways can one choose the positive integer x so that the planned voyage will take exactly c days?InputThe first input line contains space-separated integers n and c β€” the number of planets that the Beaver is going to visit and the number of days he is going to spend traveling, correspondingly.The next n lines contain pairs of space-separated integers ai, bi (1 ≀ i ≀ n) β€” the number of suitcases he can bring to the i-th planet and the number of citizens of the i-th planet, correspondingly.The input limitations for getting 30 points are: 1 ≀ n ≀ 100 1 ≀ ai ≀ 100 1 ≀ bi ≀ 100 1 ≀ c ≀ 100 The input limitations for getting 100 points are: 1 ≀ n ≀ 104 0 ≀ ai ≀ 109 1 ≀ bi ≀ 109 1 ≀ c ≀ 109 Due to possible overflow, it is recommended to use the 64-bit arithmetic. In some solutions even the 64-bit arithmetic can overflow. So be careful in calculations!OutputPrint a single number k β€” the number of ways to choose x so as to travel for exactly c days. If there are infinitely many possible values of x, print -1.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.ExamplesInput2 51 52 4Output1NoteIn the first example there is only one suitable value x = 5. Then the Beaver takes 1 suitcase with 5 presents to the first planet. Here he spends 2 days: he hangs around on the first day, and he gives away five presents on the second day. He takes 2 suitcases with 10 presents to the second planet. Here he spends 3 days β€” he gives away 4 presents on the second and the third days and leaves the remaining 2 presents at the hotel. In total, the Beaver spends 5 days traveling.For x = 4 or less the Beaver won't have enough presents for the second day on the first planet, so the voyage will end too soon. For x = 6 and more the Beaver will spend at least one more day on the second planet, and the voyage will take too long.
Input2 51 52 4
Output1
2 seconds
256 megabytes
['binary search', '*1700']
D2. Encrypting Messagestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≀ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.Help the Beaver to write a program that will encrypt messages in the described manner.InputThe first input line contains three integers n, m and c, separated by single spaces. The second input line contains n integers ai (0 ≀ ai < c), separated by single spaces β€” the original message. The third input line contains m integers bi (0 ≀ bi < c), separated by single spaces β€” the encryption key.The input limitations for getting 30 points are: 1 ≀ m ≀ n ≀ 103 1 ≀ c ≀ 103 The input limitations for getting 100 points are: 1 ≀ m ≀ n ≀ 105 1 ≀ c ≀ 103 OutputPrint n space-separated integers β€” the result of encrypting the original message.ExamplesInput4 3 21 1 1 11 1 1Output0 1 1 0Input3 1 51 2 34Output0 1 2NoteIn the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
Input4 3 21 1 1 11 1 1
Output0 1 1 0
2 seconds
256 megabytes
['data structures', '*1500']
D1. Encrypting Messagestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≀ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.Help the Beaver to write a program that will encrypt messages in the described manner.InputThe first input line contains three integers n, m and c, separated by single spaces. The second input line contains n integers ai (0 ≀ ai < c), separated by single spaces β€” the original message. The third input line contains m integers bi (0 ≀ bi < c), separated by single spaces β€” the encryption key.The input limitations for getting 30 points are: 1 ≀ m ≀ n ≀ 103 1 ≀ c ≀ 103 The input limitations for getting 100 points are: 1 ≀ m ≀ n ≀ 105 1 ≀ c ≀ 103 OutputPrint n space-separated integers β€” the result of encrypting the original message.ExamplesInput4 3 21 1 1 11 1 1Output0 1 1 0Input3 1 51 2 34Output0 1 2NoteIn the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.
Input4 3 21 1 1 11 1 1
Output0 1 1 0
2 seconds
256 megabytes
['brute force', '*1200']
C2. Partytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2, a3, ..., ap - 1 such that all pairs of people ai and ai + 1 (1 ≀ i < p) are friends. Help the Beaver find the maximum number of acquaintances he can invite.InputThe first line of input contains an integer n β€” the number of the Beaver's acquaintances. The second line contains an integer k β€” the number of pairs of friends. Next k lines contain space-separated pairs of integers ui, vi β€” indices of people who form the i-th pair of friends.The next line contains an integer m β€” the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described.Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time.The input limitations for getting 30 points are: 2 ≀ n ≀ 14 The input limitations for getting 100 points are: 2 ≀ n ≀ 2000 OutputOutput a single number β€” the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0.ExamplesInput981 21 32 34 56 77 88 99 621 67 9Output3NoteLet's have a look at the example. Two groups of people can be invited: {1, 2, 3} and {4, 5}, thus the answer will be the size of the largest of these groups. Group {6, 7, 8, 9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1, 2, 3, 4, 5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected).
Input981 21 32 34 56 77 88 99 621 67 9
Output3
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'dsu', 'graphs', '*1500']
C1. Partytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2, a3, ..., ap - 1 such that all pairs of people ai and ai + 1 (1 ≀ i < p) are friends. Help the Beaver find the maximum number of acquaintances he can invite.InputThe first line of input contains an integer n β€” the number of the Beaver's acquaintances. The second line contains an integer k β€” the number of pairs of friends. Next k lines contain space-separated pairs of integers ui, vi β€” indices of people who form the i-th pair of friends.The next line contains an integer m β€” the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described.Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time.The input limitations for getting 30 points are: 2 ≀ n ≀ 14 The input limitations for getting 100 points are: 2 ≀ n ≀ 2000 OutputOutput a single number β€” the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0.ExamplesInput981 21 32 34 56 77 88 99 621 67 9Output3NoteLet's have a look at the example. Two groups of people can be invited: {1, 2, 3} and {4, 5}, thus the answer will be the size of the largest of these groups. Group {6, 7, 8, 9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1, 2, 3, 4, 5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected).
Input981 21 32 34 56 77 88 99 621 67 9
Output3
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', '*1500']
B2. Rectangular Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = aΒ·b. 10 pebbles are arranged in two rows, each row has 5 pebbles Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble. The game process can be represented as a finite sequence of integers c1, ..., ck, where: c1 = n ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≀ i < k). Note that ci > ci + 1. ck = 1 The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.InputThe single line of the input contains a single integer n β€” the initial number of pebbles the Smart Beaver has.The input limitations for getting 30 points are: 2 ≀ n ≀ 50 The input limitations for getting 100 points are: 2 ≀ n ≀ 109 OutputPrint a single number β€” the maximum possible result of the game.ExamplesInput10Output16Input8Output15NoteConsider the first example (c1 = 10). The possible options for the game development are: Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11. Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) β€” 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13. Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 β€” the maximum possible result.
Input10
Output16
2 seconds
256 megabytes
['number theory', '*1200']
B1. Rectangular Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY decided to have a day off. But doing nothing the whole day turned out to be too boring, and he decided to play a game with pebbles. Initially, the Beaver has n pebbles. He arranges them in a equal rows, each row has b pebbles (a > 1). Note that the Beaver must use all the pebbles he has, i. e. n = aΒ·b. 10 pebbles are arranged in two rows, each row has 5 pebbles Once the Smart Beaver has arranged the pebbles, he takes back any of the resulting rows (that is, b pebbles) and discards all other pebbles. Then he arranges all his pebbles again (possibly choosing other values of a and b) and takes back one row, and so on. The game continues until at some point the Beaver ends up with exactly one pebble. The game process can be represented as a finite sequence of integers c1, ..., ck, where: c1 = n ci + 1 is the number of pebbles that the Beaver ends up with after the i-th move, that is, the number of pebbles in a row after some arrangement of ci pebbles (1 ≀ i < k). Note that ci > ci + 1. ck = 1 The result of the game is the sum of numbers ci. You are given n. Find the maximum possible result of the game.InputThe single line of the input contains a single integer n β€” the initial number of pebbles the Smart Beaver has.The input limitations for getting 30 points are: 2 ≀ n ≀ 50 The input limitations for getting 100 points are: 2 ≀ n ≀ 109 OutputPrint a single number β€” the maximum possible result of the game.ExamplesInput10Output16Input8Output15NoteConsider the first example (c1 = 10). The possible options for the game development are: Arrange the pebbles in 10 rows, one pebble per row. Then c2 = 1, and the game ends after the first move with the result of 11. Arrange the pebbles in 5 rows, two pebbles per row. Then c2 = 2, and the game continues. During the second move we have two pebbles which can be arranged in a unique way (remember that you are not allowed to put all the pebbles in the same row!) β€” 2 rows, one pebble per row. c3 = 1, and the game ends with the result of 13. Finally, arrange the pebbles in two rows, five pebbles per row. The same logic leads us to c2 = 5, c3 = 1, and the game ends with the result of 16 β€” the maximum possible result.
Input10
Output16
2 seconds
256 megabytes
['number theory', '*1000']
A2. Good Matrix Elementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.InputThe first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix.The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101 OutputPrint a single integer β€” the sum of good matrix elements.ExamplesInput31 2 34 5 67 8 9Output45Input51 1 1 1 11 1 1 1 11 1 1 1 11 1 1 1 11 1 1 1 1Output17NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Input31 2 34 5 67 8 9
Output45
2 seconds
256 megabytes
['implementation', '*800']
A1. Good Matrix Elementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good: Elements of the main diagonal. Elements of the secondary diagonal. Elements of the "middle" row β€” the row which has exactly rows above it and the same number of rows below it. Elements of the "middle" column β€” the column that has exactly columns to the left of it and the same number of columns to the right of it. The figure shows a 5 × 5 matrix. The good elements are marked with green. Help the Smart Beaver count the sum of good elements of the given matrix.InputThe first line of input data contains a single odd integer n. Each of the next n lines contains n integers aij (0 ≀ aij ≀ 100) separated by single spaces β€” the elements of the given matrix.The input limitations for getting 30 points are: 1 ≀ n ≀ 5 The input limitations for getting 100 points are: 1 ≀ n ≀ 101 OutputPrint a single integer β€” the sum of good matrix elements.ExamplesInput31 2 34 5 67 8 9Output45Input51 1 1 1 11 1 1 1 11 1 1 1 11 1 1 1 11 1 1 1 1Output17NoteIn the first sample all matrix elements will be good. Good elements in the second sample are shown on the figure.
Input31 2 34 5 67 8 9
Output45
2 seconds
256 megabytes
['implementation', '*800']
E. Archaeologytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago.Overall they've dug out n villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overall there were exactly n - 1 roads, and from any village one could get to any other one.The tribes were not peaceful and they had many wars. As a result of the wars, some villages were destroyed completely. During more peaceful years some of the villages were restored.At each moment of time people used only those roads that belonged to some shortest way between two villages that existed at the given moment. In other words, people used the minimum subset of roads in such a way, that it was possible to get from any existing village to any other existing one. Note that throughout the island's whole history, there existed exactly n - 1 roads that have been found by the researchers. There never were any other roads.The researchers think that observing the total sum of used roads’ lengths at different moments of time can help to better understand the tribes' culture and answer several historical questions.You will be given the full history of the tribes' existence. Your task is to determine the total length of used roads at some moments of time.InputThe first line contains an integer n (1 ≀ n ≀ 105) β€” the number of villages. The next n - 1 lines describe the roads. The i-th of these lines contains three integers ai, bi and ci (1 ≀ ai, bi ≀ n, ai ≠ bi, 1 ≀ ci ≀ 109, 1 ≀ i < n) β€” the numbers of villages that are connected by the i-th road and the road's length. The numbers in the lines are separated by a space.The next line contains an integer q (1 ≀ q ≀ 105) β€” the number of queries. Then follow q queries, one per line, ordered by time. Each query belongs to one of three types: "+ x" β€” village number x is restored (1 ≀ x ≀ n). "- x" β€” village number x is destroyed (1 ≀ x ≀ n). "?" β€” the archaeologists want to know the total length of the roads which were used for that time period.It is guaranteed that the queries do not contradict each other, that is, there won't be queries to destroy non-existing villages or restore the already existing ones. It is guaranteed that we have at least one query of type "?". It is also guaranteed that one can get from any village to any other one by the given roads.At the initial moment of time no village is considered to exist.OutputFor each query of type "?" print the total length of used roads on a single line. You should print the answers to the queries in the order, in which they are given in the input.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specifier.ExamplesInput61 2 11 3 54 1 74 5 36 4 210+ 3+ 1?+ 6?+ 5?- 6- 3?Output5141710
Input61 2 11 3 54 1 74 5 36 4 210+ 3+ 1?+ 6?+ 5?- 6- 3?
Output5141710
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'trees', '*3100']
D. Hyper Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPaul ErdΕ‘s's prediction came true. Finally an alien force landed on the Earth. In contrary to our expectation they didn't asked the humans to compute the value of a Ramsey number (maybe they had solved it themselves). They asked another question which seemed as hard as calculating Ramsey numbers. Aliens threatened that if humans don't solve this problem in less than 2 hours they will destroy the Earth. Before telling the problem they introduced the concept of Hyper Strings. A Hyper String is made by concatenation of some base strings. Suppose you are given a list of base strings b1, b2, ..., bn. Now the Hyper String made from indices list i1, i2, ..., im is concatenation of base strings bi1, bi2, ..., bim. A Hyper String can be very large and doing operations on it is very costly for computers. The aliens asked humans to compute the length of the longest common sub-sequence of a Hyper String t with a string s.InputThe first line of input contains the single integer n (1 ≀ n ≀ 2000) β€” the number of base strings. The next n lines contains values of base strings. Each base string is made of lowercase Latin letters. A base string cannot be empty string and the sum of lengths of all n base strings doesn't exceed 106. The next line contains the single integer m (1 ≀ m ≀ 2000) β€” the number of base strings in the given Hyper String t. The next line contains m space-separated integer numbers i1, i2, ..., im (1 ≀ ij ≀ n) β€” the indices of base strings in the Hyper String t.The last line contains a non-empty string s. String s is made of lowercase Latin letters and its length is no more than 2000 characters.OutputPrint the length of longest common sub-sequence of Hyper String t and string s. If there is no common sub-sequence print 0.ExamplesInput2cbadgh21 2aedfhrOutput3Input2ba51 2 1 2 1aaaOutput2NoteThe length of string s is the number of characters in it. If the length of string s is marked as |s|, then string s can be represented as s = s1s2... s|s|.A non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≀ p1 < p2 < ... < p|y| ≀ |s|) is a subsequence of string s. For example, "coders" is a subsequence of "codeforces".
Input2cbadgh21 2aedfhr
Output3
2 seconds
256 megabytes
['dp', '*2500']
C. Playing with Supergluetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo players play a game. The game is played on a rectangular board with n × m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.We'll describe the rules of the game in more detail.The players move in turns. The first player begins.With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible β€” he can always spread the glue on the square from which the first player has just moved the chip.We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.InputThe first line contains six integers n, m, x1, y1, x2, y2 β€” the board sizes and the coordinates of the first and second chips, correspondingly (1 ≀ n, m ≀ 100; 2 ≀ n × m; 1 ≀ x1, x2 ≀ n; 1 ≀ y1, y2 ≀ m). The numbers in the line are separated by single spaces.It is guaranteed that the chips are located in different squares.OutputIf the first player wins, print "First" without the quotes. Otherwise, print "Second" without the quotes.ExamplesInput1 6 1 2 1 6OutputFirstInput6 5 4 3 2 1OutputFirstInput10 10 1 1 10 10OutputSecond
Input1 6 1 2 1 6
OutputFirst
2 seconds
256 megabytes
['combinatorics', 'constructive algorithms', '*2000']
B. Word Cuttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x ≠ a holds.InputThe first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters.The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations.OutputPrint a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).ExamplesInputabab2Output1Inputabababababab1Output2Inputabba2Output0NoteThe sought way in the first sample is:ab  →  a|b  →  ba  →  b|a  →  abIn the second sample the two sought ways are: ababab  →  abab|ab  →  ababab ababab  →  ab|abab  →  ababab
Inputabab2
Output1
2 seconds
256 megabytes
['dp', '*1700']
A. Trading Businesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the selling are made only once. To carry out his plan, Qwerty is going to take a bank loan that covers all expenses and to return the loaned money at the end of the operation (the money is returned without the interest). At the same time, Querty wants to get as much profit as possible.The system has n planets in total. On each of them Qwerty can buy or sell items of m types (such as food, medicine, weapons, alcohol, and so on). For each planet i and each type of items j Qwerty knows the following: aij β€” the cost of buying an item; bij β€” the cost of selling an item; cij β€” the number of remaining items.It is not allowed to buy more than cij items of type j on planet i, but it is allowed to sell any number of items of any kind.Knowing that the hold of Qwerty's ship has room for no more than k items, determine the maximum profit which Qwerty can get.InputThe first line contains three space-separated integers n, m and k (2 ≀ n ≀ 10, 1 ≀ m, k ≀ 100) β€” the number of planets, the number of question types and the capacity of Qwerty's ship hold, correspondingly.Then follow n blocks describing each planet.The first line of the i-th block has the planet's name as a string with length from 1 to 10 Latin letters. The first letter of the name is uppercase, the rest are lowercase. Then in the i-th block follow m lines, the j-th of them contains three integers aij, bij and cij (1 ≀ bij < aij ≀ 1000, 0 ≀ cij ≀ 100) β€” the numbers that describe money operations with the j-th item on the i-th planet. The numbers in the lines are separated by spaces.It is guaranteed that the names of all planets are different.OutputPrint a single number β€” the maximum profit Qwerty can get.ExamplesInput3 3 10Venus6 5 37 6 58 6 10Earth10 9 08 6 410 9 3Mars4 3 08 4 127 2 5Output16NoteIn the first test case you should fly to planet Venus, take a loan on 74 units of money and buy three items of the first type and 7 items of the third type (3Β·6 + 7Β·8 = 74). Then the ranger should fly to planet Earth and sell there all the items he has bought. He gets 3Β·9 + 7Β·9 = 90 units of money for the items, he should give 74 of them for the loan. The resulting profit equals 16 units of money. We cannot get more profit in this case.
Input3 3 10Venus6 5 37 6 58 6 10Earth10 9 08 6 410 9 3Mars4 3 08 4 127 2 5
Output16
2 seconds
256 megabytes
['greedy', 'sortings', '*1200']
F. Gnomes of Might and Magictime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays a popular game the Gnomes of Might and Magic.In this game Vasya manages the kingdom of gnomes, consisting of several castles, connected by bidirectional roads. The kingdom road network has a special form. The kingdom has m main castles a1, a2, ..., am, which form the Good Path. This path consists of roads between the castles ai, ai + 1 (1 ≀ i < m) as well as the road between am and a1. There are no other roads between the castles of the Good Path.In addition, for each pair of neighboring Good Path castles u and v there is exactly one Evil Shortcut β€” a path that goes along the roads leading from the first castle (u) to the second one (v) and not having any common vertexes with the Good Path except for the vertexes u and v. It is known that there are no other roads and castles in the kingdom there, that is, every road and every castle lies either on the Good Path or the Evil Shortcut (castles can lie in both of them). In addition, no two Evil Shortcuts have any common castles, different than the castles of the Good Path.At the beginning of each week in the kingdom appears one very bad gnome who stands on one of the roads of the kingdom, and begins to rob the corovans going through this road. One road may accumulate multiple very bad gnomes. Vasya cares about his corovans, so sometimes he sends the Mission of Death from one castle to another.Let's suggest that the Mission of Death should get from castle s to castle t. Then it will move from castle s to castle t, destroying all very bad gnomes, which are on the roads of the Mission's path. Vasya is so tough that his Mission of Death can destroy any number of gnomes on its way. However, Vasya is very kind, so he always chooses such path between castles s and t, following which he will destroy the smallest number of gnomes. If there are multiple such paths, then Vasya chooses the path that contains the smallest number of roads among them. If there are multiple such paths still, Vasya chooses the lexicographically minimal one among them.Help Vasya to simulate the life of the kingdom in the Gnomes of Might and Magic game.A path is a sequence of castles, such that each pair of the neighboring castles on the path is connected by a road. Also, path x1, x2, ... , xp is lexicographically less than path y1, y2, ... , yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or exists such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1.InputThe first line contains two integers n and m (3 ≀ m ≀ n ≀ 100000) β€” the number of castles in the kingdom, and the number of castles on the Good Path, respectively.The second line contains m integers, which are numbers of Good Path castles (the castles are numbered from 1 to n) in the order of occurrence on the Path, starting with some castle. All Good Path castles are different.Each of the following m lines describes an Evil Shortcut. First a line contains an integer ki (3 ≀ ki ≀ 100000) β€” the number of castles on the corresponding Evil Shortcut (with the two castles which are on the Good Path), followed by a ki integers β€” number of castles in the order of occurrence in the given Shortcut. All castles in one Evil Shortcut are different. It is guaranteed that the first and the last castles from the Shortcut are on the Good Path and the first castles in the Evil Shortcuts form the Good Path and are presented in the same order in which the Path was represented on the second line.The next line contains an integer q (1 ≀ q ≀ 100000) β€” the number of events in the life of the kingdom. Each of the following q lines describes a single event. An event is described by the symbol cj and two numbers or castles sj and tj (the character and numbers of castles are separated by a single space). If the character of cj is equal to "+" (a plus), it means that a very bad gnome (probably not the first one) has appeared on the road between castles sj and tj. If cj equals "?" (a question), then Vasya sent a Mission of Death from castle sj to castle tj. It is guaranteed that for each request "+", the road between castles sj and tj exists. The events are given in chronological order, starting with the earliest one. Initially there are no very bad gnomes on the roads.All numbers in all lines are separated by single spaces. It is guaranteed that all the given Evil Shortcuts and Good Path fit in the limitations given in the problem statement.OutputFor each query "?" print a single number on a single line β€” the number of very bad gnomes destroyed by the corresponding Mission of Death. Print the answers to queries in the chronological order.ExamplesInput6 31 2 33 1 4 23 2 5 33 3 6 110+ 1 2+ 4 2+ 1 3+ 2 3? 1 2+ 2 5? 1 2? 1 2+ 1 2? 1 2Output0101NoteIn the example after the first four requests there is only one path from castle 1 to castle 2, which does not contain roads with very bad gnomes: 1 6 3 5 2.After a gnome stood on the road (2, 5), the next Mission of Death moves along path 1 2, and destroys the gnome, who was on the road (1, 2). The next Mission of Death follows the same path which is already free of gnomes.After yet another gnome stood on the road (1, 2), the next Mission of Death goes on the path 1 2, and kills the gnome.
Input6 31 2 33 1 4 23 2 5 33 3 6 110+ 1 2+ 4 2+ 1 3+ 2 3? 1 2+ 2 5? 1 2? 1 2+ 1 2? 1 2
Output0101
8 seconds
256 megabytes
['data structures', 'graphs', 'implementation', 'shortest paths', '*3000']
E. Power Defencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays the Power Defence. He must pass the last level of the game. In order to do this he must kill the Main Villain, who moves in a straight line at speed 1 meter per second from the point ( -β€‰βˆž, 0) to the point ( +β€‰βˆž, 0) of the game world. In the points (x, 1) and (x,  - 1), where x is an integer number, Vasya can build towers of three types: fire-tower, electric-tower or freezing-tower. However, it is not allowed to build two towers at the same point. Towers of each type have a certain action radius and the value of damage per second (except freezing-tower). If at some point the Main Villain is in the range of action of k freezing towers then his speed is decreased by k + 1 times.The allowed number of towers of each type is known. It is necessary to determine the maximum possible damage we can inflict on the Main Villain.All distances in the problem are given in meters. The size of the Main Villain and the towers are so small, that they can be considered as points on the plane. The Main Villain is in the action radius of a tower if the distance between him and tower is less than or equal to the action radius of the tower.InputThe first line contains three integer numbers nf, ne and ns β€” the maximum number of fire-towers, electric-towers and freezing-towers that can be built (0 ≀ nf, ne, ns ≀ 20, 1 ≀ nf + ne + ns ≀ 20). The numbers are separated with single spaces.The second line contains three integer numbers rf, re and rs (1 ≀ rf, re, rs ≀ 1000) β€” the action radii of fire-towers, electric-towers and freezing-towers. The numbers are separated with single spaces.The third line contains two integer numbers df and de (1 ≀ df, de ≀ 1000) β€” the damage a fire-tower and an electronic-tower can inflict on the Main Villain per second (in the case when the Main Villain is in the action radius of the tower). The numbers are separated with single space.OutputPrint the only real number β€” the maximum possible damage to the Main Villain with absolute or relative error not more than 10 - 6.ExamplesInput1 0 010 10 10100 100Output1989.97487421Input1 0 110 10 10100 100Output3979.94974843NoteIn the first sample we've got one fire-tower that always inflicts the same damage, independently of its position. In the second sample we've got another freezing-tower of the same action radius. If we build the two towers opposite each other, then the Main Villain's speed will be two times lower, whenever he enters the fire-tower's action radius. That means that the enemy will be inflicted with twice more damage.
Input1 0 010 10 10100 100
Output1989.97487421
3 seconds
256 megabytes
['brute force', 'dp', 'geometry', 'greedy', '*2600']
D. Plane of Tanks: Dueltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays the Plane of Tanks.Tanks are described with the following attributes: the number of hit points; the interval between two gun shots (the time required to recharge the gun); the probability that the gun shot will not pierce armor of the enemy tank; the damage to the enemy's tank. The gun damage is described with a segment [l, r], where l and r are integer numbers. The potential gun damage x is chosen with equal probability among all integer numbers of the segment [l, r]. If the shot pierces the armor of an enemy's tank then the enemy loses x hit points. If the number of hit points becomes non-positive then the enemy tank is considered destroyed. It is possible that the shot does not pierce the armor of a tank. In this case the number of hit points doesn't change. The probability that the armor will not be pierced is considered as the shooting tank attribute and does not depend on players' behavior.The victory is near and there is only one enemy tank left. Vasya is ready for the battle β€” one more battle between the Good and the Evil is inevitable! Two enemies saw each other and each of them fired a shot at the same moment... The last battle has begun! Help Vasya to determine what is the probability that he will win the battle by destroying the enemy tank? If both tanks are destroyed (after simultaneous shots), then Vasya is considered a winner. You can assume that each player fires a shot just after the gun recharge and each tank has infinite number of ammo.InputThe first line contains five integer numbers separated with spaces describing Vasya's tank: the number of hit points hp (10 ≀ hp ≀ 200), the interval between two shots dt (1 ≀ dt ≀ 30), gun damage segment l and r (10 ≀ l ≀ r ≀ 100), the probability that the enemy's tank armor will not be pierced p (0 ≀ p ≀ 100) (percents).The second line describes the tank of Vasya's enemy in the same format.OutputPrint the only number with absolute or relative error no more than 10 - 4 β€” probability of Vasya's victory.ExamplesInput100 3 50 50 0100 3 50 50 0Output1.000000Input100 3 50 50 0100 2 48 50 0Output0.888889Input100 3 50 50 0100 1 50 50 50Output0.500000NoteIn the first example both tanks are destroyed at once after the second shot. The probability of destroying the enemy tank is 1.In the second example Vasya's enemy tank fires the second shot before Vasya's tank, but has no time for the third shot. In order to destroy Vasya's tank it is necessary to fire two shots with damage 50. The probability of that event is = . Otherwise, Vasya wins.In the third example Vasya's enemy tank fires three shots with probability of armor piercing 0.5. In order to destroy Vasya's tank it is necessary that at least 2 of 3 shots pierce the armor of Vasya's tank. The probability of this event is 0.5.
Input100 3 50 50 0100 3 50 50 0
Output1.000000
2 seconds
256 megabytes
['brute force', 'dp', 'math', 'probabilities', '*2400']
C. Geometry Horsetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays the Geometry Horse.The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ciΒ·f points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≀ i ≀ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.InputThe first line contains the only integer number n (1 ≀ n ≀ 100) β€” the number of figure types.Each of the following n lines contains two integer numbers ki and ci (1 ≀ ki ≀ 109, 0 ≀ ci ≀ 1000), separated with space β€” the number of figures of the i-th type and the cost of one i-type figure, correspondingly.The next line contains the only integer number t (1 ≀ t ≀ 100) β€” the number that describe the factor's changes. The next line contains t integer numbers pi (1 ≀ p1 < p2 < ... < pt ≀ 1012), separated with spaces.Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.OutputPrint the only number β€” the maximum number of points Vasya can get.ExamplesInput15 1023 6Output70Input23 85 10120Output74NoteIn the first example Vasya destroys three figures first and gets 3Β·1Β·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2Β·2Β·10 = 40 points. As a result Vasya will get 70 points.In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3Β·8 + 5Β·10)Β·1 = 74 points.
Input15 1023 6
Output70
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', 'two pointers', '*1600']
B. Plane of Tanks: Protime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has n records in total.In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category: "noob" β€” if more than 50% of players have better results; "random" β€” if his result is not worse than the result that 50% of players have, but more than 20% of players have better results; "average" β€” if his result is not worse than the result that 80% of players have, but more than 10% of players have better results; "hardcore" β€” if his result is not worse than the result that 90% of players have, but more than 1% of players have better results; "pro" β€” if his result is not worse than the result that 99% of players have. When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have.Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.InputThe first line contains the only integer number n (1 ≀ n ≀ 1000) β€” a number of records with the players' results.Each of the next n lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.OutputPrint on the first line the number m β€” the number of players, who participated in one round at least.Each one of the next m lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: "noob", "random", "average", "hardcore" or "pro" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.ExamplesInput5vasya 100vasya 200artem 100kolya 200igor 250Output4artem noobigor prokolya randomvasya randomInput3vasya 200kolya 1000vasya 1000Output2kolya provasya proNoteIn the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category "noob". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category "random". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category "pro".In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category "pro".
Input5vasya 100vasya 200artem 100kolya 200igor 250
Output4artem noobigor prokolya randomvasya random
2 seconds
256 megabytes
['implementation', '*1400']
A. Robot Bicorn Attacktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays Robot Bicorn Attack.The game consists of three rounds. For each one a non-negative integer amount of points is given. The result of the game is the sum of obtained points. Vasya has already played three rounds and wrote obtained points one by one (without leading zeros) into the string s. Vasya decided to brag about his achievement to the friends. However, he has forgotten how many points he got for each round. The only thing he remembers is the string s.Help Vasya to find out what is the maximum amount of points he could get. Take into account that Vasya played Robot Bicorn Attack for the first time, so he could not get more than 1000000 (106) points for one round.InputThe only line of input contains non-empty string s obtained by Vasya. The string consists of digits only. The string length does not exceed 30 characters.OutputPrint the only number β€” the maximum amount of points Vasya could get. If Vasya is wrong and the string could not be obtained according to the rules then output number -1.ExamplesInput1234Output37Input9000Output90Input0009Output-1NoteIn the first example the string must be split into numbers 1, 2 and 34.In the second example the string must be split into numbers 90, 0 and 0. In the third example the string is incorrect, because after splitting the string into 3 numbers number 00 or 09 will be obtained, but numbers cannot have leading zeroes.
Input1234
Output37
2 seconds
256 megabytes
['brute force', 'implementation', '*1400']
C. Range Incrementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l, r]. In other words, this function does the following: function rangeIncrement(l, r) for i := l .. r do a[i] = a[i] + 1Polycarpus knows the state of the array a after a series of function calls. He wants to determine the minimum number of function calls that lead to such state. In addition, he wants to find what function calls are needed in this case. It is guaranteed that the required number of calls does not exceed 105.Before calls of function rangeIncrement(l, r) all array elements equal zero.InputThe first input line contains a single integer n (1 ≀ n ≀ 105) β€” the length of the array a[1... n]. The second line contains its integer space-separated elements, a[1], a[2], ..., a[n] (0 ≀ a[i] ≀ 105) after some series of function calls rangeIncrement(l, r). It is guaranteed that at least one element of the array is positive. It is guaranteed that the answer contains no more than 105 calls of function rangeIncrement(l, r).OutputPrint on the first line t β€” the minimum number of calls of function rangeIncrement(l, r), that lead to the array from the input data. It is guaranteed that this number will turn out not more than 105.Then print t lines β€” the descriptions of function calls, one per line. Each line should contain two integers li, ri (1 ≀ li ≀ ri ≀ n) β€” the arguments of the i-th call rangeIncrement(l, r). Calls can be applied in any order.If there are multiple solutions, you are allowed to print any of them.ExamplesInput61 2 1 1 4 1Output52 25 55 55 51 6Input51 0 1 0 1Output31 13 35 5NoteThe first sample requires a call for the entire array, and four additional calls: one for the segment [2,2] (i.e. the second element of the array), three for the segment [5,5] (i.e. the fifth element of the array).
Input61 2 1 1 4 1
Output52 25 55 55 51 6
2 seconds
256 megabytes
['data structures', 'greedy', '*1800']
B. File Listtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEudokimus, a system administrator is in trouble again. As a result of an error in some script, a list of names of very important files has been damaged. Since they were files in the BerFS file system, it is known that each file name has a form "name.ext", where: name is a string consisting of lowercase Latin letters, its length is from 1 to 8 characters; ext is a string consisting of lowercase Latin letters, its length is from 1 to 3 characters. For example, "read.me", "example.txt" and "b.cpp" are valid file names and "version.info", "ntldr" and "contestdata.zip" are not.Damage to the list meant that all the file names were recorded one after another, without any separators. So now Eudokimus has a single string.Eudokimus needs to set everything right as soon as possible. He should divide the resulting string into parts so that each part would be a valid file name in BerFS. Since Eudokimus has already proved that he is not good at programming, help him. The resulting file list can contain the same file names.InputThe input data consists of a single string s, its length is from 1 to 4Β·105 characters. The string can contain only lowercase Latin letters ('a' - 'z') and periods ('.').OutputIn the first line print "YES" (without the quotes), if it is possible to divide s into parts as required. In this case, the following lines should contain the parts of the required partition, one per line in the order in which they appear in s. The required partition can contain the same file names. If there are multiple solutions, print any of them.If the solution does not exist, then print in a single line "NO" (without the quotes).ExamplesInputread.meexample.txtb.cppOutputYESread.meexample.txtb.cppInputversion.infontldrcontestdata.zipOutputNO
Inputread.meexample.txtb.cpp
OutputYESread.meexample.txtb.cpp
2 seconds
256 megabytes
['dp', 'greedy', 'implementation', '*1400']
A. Problem About Equationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA group of n merry programmers celebrate Robert Floyd's birthday. Polucarpus has got an honourable task of pouring Ber-Cola to everybody. Pouring the same amount of Ber-Cola to everybody is really important. In other words, the drink's volume in each of the n mugs must be the same.Polycarpus has already began the process and he partially emptied the Ber-Cola bottle. Now the first mug has a1 milliliters of the drink, the second one has a2 milliliters and so on. The bottle has b milliliters left and Polycarpus plans to pour them into the mugs so that the main equation was fulfilled.Write a program that would determine what volume of the drink Polycarpus needs to add into each mug to ensure that the following two conditions were fulfilled simultaneously: there were b milliliters poured in total. That is, the bottle need to be emptied; after the process is over, the volumes of the drink in the mugs should be equal. InputThe first line contains a pair of integers n, b (2 ≀ n ≀ 100, 1 ≀ b ≀ 100), where n is the total number of friends in the group and b is the current volume of drink in the bottle. The second line contains a sequence of integers a1, a2, ..., an (0 ≀ ai ≀ 100), where ai is the current volume of drink in the i-th mug.OutputPrint a single number "-1" (without the quotes), if there is no solution. Otherwise, print n float numbers c1, c2, ..., cn, where ci is the volume of the drink to add in the i-th mug. Print the numbers with no less than 6 digits after the decimal point, print each ci on a single line. Polycarpus proved that if a solution exists then it is unique.Russian locale is installed by default on the testing computer. Make sure that your solution use the point to separate the integer part of a real number from the decimal, not a comma.ExamplesInput5 501 2 3 4 5Output12.00000011.00000010.0000009.0000008.000000Input2 21 100Output-1
Input5 501 2 3 4 5
Output12.00000011.00000010.0000009.0000008.000000
2 seconds
256 megabytes
['math', '*1100']
E. Camping Groupstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA club wants to take its members camping. In order to organize the event better the club directors decided to partition the members into several groups. Club member i has a responsibility value ri and an age value ai. A group is a non-empty subset of club members with one member known as group leader. A group leader should be one of the most responsible members of the group (his responsibility value is not less than responsibility of any other group member) and his age absolute difference with any other group member should not exceed k. Some club members are friends and want to be in the same group. They also like their group to be as large as possible. Now you should write a program that answers a series of questions like "What's the largest size of a group containing club member x and club member y?". It's possible for x or y to be the group leader.InputThe first line contains two integers n and k (2 ≀ n ≀ 105, 0 ≀ k ≀ 109) β€” the number of club members and the age restriction for one group. The next line contains integer numbers r1, r2, ..., rn (1 ≀ ri ≀ 109) separated by space: ri denotes the i-th club member's responsibility. In the same way there are integers a1, a2, ..., an (1 ≀ ai ≀ 109) in the third line: ai denotes the i-th club member's age.The next line contains an integer q denoting the number of questions that you should answer (1 ≀ q ≀ 105). The next q lines describe the questions. Each line contains two space-separated integers xi and yi (1 ≀ xi, yi ≀ n, xi ≠ yi) β€” the indices of the club members that should end up in the same group. OutputFor each question print the maximum size of the group in a line. If making such a group is impossible print -1 instead.ExamplesInput5 11 5 4 1 24 4 3 2 245 32 32 54 1Output43-14NoteIn the first query the largest group with members 3 and 5 is {1, 3, 4, 5} where member 3 is the leader.In the second query member 2 should be the leader so the group will be {1, 2, 3}.In the third query the leader of the group should have age 3 so the only leader can be member 3, who is less responsible than member 2. So making a group is impossible.The group for the fourth query is the same as first query.
Input5 11 5 4 1 24 4 3 2 245 32 32 54 1
Output43-14
2 seconds
256 megabytes
['data structures', 'sortings', '*2600']
D. Deputiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Trinitarian kingdom has exactly n = 3k cities. All of them are located on the shores of river Trissisipi, which flows through the whole kingdom. Some of the cities are located on one side of the river, and all the rest are on the other side.Some cities are connected by bridges built between them. Each bridge connects two cities that are located on the opposite sides of the river. Between any two cities exists no more than one bridge.The recently inaugurated King Tristan the Third is busy distributing his deputies among cities. In total there are k deputies and the king wants to commission each of them to control exactly three cities. However, no deputy can be entrusted to manage the cities, which are connected by a bridge β€” the deputy can set a too high fee for travelling over the bridge to benefit his pocket, which is bad for the reputation of the king.Help King Tristan the Third distribute the deputies between the cities, if it is possible.InputThe first line contains two integers n and m β€” the number of cities and bridges (3 ≀ n < 105, n = 3k, 0 ≀ m ≀ 105). Next m lines describe the bridges. The i-th line contains two integers ai and bi β€” the numbers of cities that are connected by the i-th bridge (1 ≀ ai, bi ≀ n, ai ≠ bi, 1 ≀ i ≀ m).It is guaranteed that no bridge connects a city with itself and that any two cities are connected with no more than one bridge.OutputIf distributing the deputies in the required manner is impossible, print in a single line "NO" (without the quotes).Otherwise, in the first line print "YES" (without the quotes), and in the second line print which deputy should be put in charge of each city. The i-th number should represent the number of the deputy (from 1 to k), who should be in charge of city numbered i-th in the input β€” overall there should be n numbers.If there are multiple solutions, print any of them.ExamplesInput6 61 24 13 56 52 64 6OutputYES1 2 1 2 2 1 Input3 11 2OutputNO
Input6 61 24 13 56 52 64 6
OutputYES1 2 1 2 2 1
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'greedy', 'implementation', '*2500']
C. Spiral Maximumtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider a k × k square, divided into unit squares. Please note that k β‰₯ 3 and is odd. We'll paint squares starting from the upper left square in the following order: first we move to the right, then down, then to the left, then up, then to the right again and so on. We finish moving in some direction in one of two cases: either we've reached the square's border or the square following after the next square is already painted. We finish painting at the moment when we cannot move in any direction and paint a square. The figure that consists of the painted squares is a spiral. The figure shows examples of spirals for k = 3, 5, 7, 9. You have an n × m table, each of its cells contains a number. Let's consider all possible spirals, formed by the table cells. It means that we consider all spirals of any size that don't go beyond the borders of the table. Let's find the sum of the numbers of the cells that form the spiral. You have to find the maximum of those values among all spirals.InputThe first line contains two integers n and m (3 ≀ n, m ≀ 500) β€” the sizes of the table.Each of the next n lines contains m space-separated integers: the j-th number in the i-th line aij ( - 1000 ≀ aij ≀ 1000) is the number recorded in the j-th cell of the i-th row of the table.OutputPrint a single number β€” the maximum sum of numbers among all spirals.ExamplesInput6 50 0 0 0 01 1 1 1 10 0 0 0 11 1 1 0 11 0 0 0 11 1 1 1 1Output17Input3 31 1 11 0 01 1 1Output6Input6 6-3 2 0 1 5 -14 -1 2 -3 0 1-5 1 2 4 1 -20 -2 1 3 -1 23 1 4 -3 -2 0-1 2 -1 3 1 2Output13NoteIn the first sample the spiral with maximum sum will cover all 1's of the table.In the second sample the spiral may cover only six 1's.
Input6 50 0 0 0 01 1 1 1 10 0 0 0 11 1 1 0 11 0 0 0 11 1 1 1 1
Output17
3 seconds
256 megabytes
['brute force', 'dp', '*1900']
B. Chamber of Secretstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output"The Chamber of Secrets has been opened again" β€” this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny.The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. The left light ray passes through a regular column, and the right ray β€” through the magic column. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. This figure illustrates the first sample test. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.InputThe first line of the input contains two integer numbers n and m (2 ≀ n, m ≀ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column.OutputPrint the minimum number of columns to make magic or -1 if it's impossible to do.ExamplesInput3 3.#.....#.Output2Input4 3##.....#..#.Output2NoteThe figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns.
Input3 3.#.....#.
Output2
2 seconds
256 megabytes
['dfs and similar', 'shortest paths', '*1800']
A. Rock-Paper-Scissorstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.InputThe first line contains integer n (1 ≀ n ≀ 2Β·109) β€” the number of the game's rounds.The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≀ m, k ≀ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.OutputPrint two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.ExamplesInput7RPSRSPPOutput3 2Input5RRRRRRRRROutput0 0NoteIn the first sample the game went like this: R - R. Draw. P - S. Nikephoros loses. S - P. Polycarpus loses. R - P. Nikephoros loses. P - R. Polycarpus loses. S - S. Draw. R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.
Input7RPSRSPP
Output3 2
3 seconds
256 megabytes
['implementation', 'math', '*1300']
E. BHTML+BCSStime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is about imaginary languages BHTML and BCSS, which slightly resemble HTML and CSS. Read the problem statement carefully as the resemblance is rather slight and the problem uses very simplified analogs.You are given a BHTML document that resembles HTML but is much simpler. It is recorded as a sequence of opening and closing tags. A tag that looks like "<tagname>" is called an opening tag and a tag that looks like "</tagname>" is called a closing tag. Besides, there are self-closing tags that are written as "<tagname/>" and in this problem they are fully equivalent to "<tagname></tagname>". All tagnames in this problem are strings consisting of lowercase Latin letters with length from 1 to 10 characters. Tagnames of different tags may coincide.The document tags form a correct bracket sequence, that is, we can obtain an empty sequence from the given one using the following operations: remove any self-closing tag "<tagname/>", remove a pair of an opening and a closing tag that go consecutively (in this order) and have the same names. In other words, remove substring "<tagname></tagname>". For example, you may be given such document: "<header><p><a/><b></b></p></header><footer></footer>" but you may not be given documents "<a>", "<a></b>", "</a><a>" or "<a><b></a></b>".Obviously, for any opening tag there is the only matching closing one β€” each such pair is called an element. A self-closing tag also is an element. Let's consider that one element is nested inside another one, if tags of the first element are between tags of the second one. An element is not nested to itself. For instance, in the example above element "b" is nested in "header" and in "p", but it isn't nested in "a" and "footer", also it isn't nested to itself ("b"). Element "header" has three elements nested in it, and "footer" has zero.We need the BCSS rules to apply styles when displaying elements of the BHTML documents. Each rule is recorded as a subsequence of words "x1 x2 ... xn". This rule has effect over all such elements t, which satisfy both conditions from the list: there is a sequence of nested elements with tagnames "x1", "x2", ..., "xn" (that is, the second element is nested in the first one, the third element is nested in the second one and so on), this sequence ends with element t (i.e. tagname of element t equals "xn"). For example, element "b" meets the conditions of the rule "a b" if for element "b" exists element "a" in which it is nested. Element "c" meets the conditions of the rule "a b b c", if three elements exist: "a", "b", "b", and in the chain "a"-"b"-"b"-"c" each following element is nested in the previous one.Given a BHTML document and a set of BCSS rules, write a program that determines the number of elements that meet the conditions of each rule.InputThe first line of the input contains a BHTML-document. The document has length from 4 to 106 characters. The document has a correct structure, doesn't contain spaces or any other unnecessary characters. Tagnames consist of lowercase Latin letters, their lengths are from 1 to 10 characters.The second line contains an integer m (1 ≀ m ≀ 200) β€” the number of queries. Then m lines contain the queries, one per line. Each query is a sequence x1, x2, ..., xn, where xi is the i-th element of the query, and n (1 ≀ n ≀ 200) is the number of elements in the query. The elements are separated by single spaces. Each query doesn't begin with and doesn't end with a space. Each query element is a sequence of lowercase Latin letters with length from 1 to 10.OutputPrint m lines, the j-th line should contain the number of elements of the document that correspond to the j-th BCSS-rule. If there are no such elements at all, print on the line 0.ExamplesInput<a><b><b></b></b></a><a><b></b><b><v/></b></a><b></b>4aa b ba bb aOutput2140Input<b><aa/></b><aa><b/><b/></aa>5aa bbaab aaaOutput23210
Input<a><b><b></b></b></a><a><b></b><b><v/></b></a><b></b>4aa b ba bb a
Output2140
4 seconds
256 megabytes
['*special problem', 'dfs and similar', 'expression parsing', '*2200']
D. Calendar Reformtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReforms have started in Berland again! At this time, the Parliament is discussing the reform of the calendar. To make the lives of citizens of Berland more varied, it was decided to change the calendar. As more and more people are complaining that "the years fly by...", it was decided that starting from the next year the number of days per year will begin to grow. So the coming year will have exactly a days, the next after coming year will have a + 1 days, the next one will have a + 2 days and so on. This schedule is planned for the coming n years (in the n-th year the length of the year will be equal a + n - 1 day).No one has yet decided what will become of months. An MP Palevny made the following proposal. The calendar for each month is comfortable to be printed on a square sheet of paper. We are proposed to make the number of days in each month be the square of some integer. The number of days per month should be the same for each month of any year, but may be different for different years. The number of days in each year must be divisible by the number of days per month in this year. This rule ensures that the number of months in each year is an integer. The number of days per month for each year must be chosen so as to save the maximum amount of paper to print the calendars. In other words, the number of days per month should be as much as possible. These rules provide an unambiguous method for choosing the number of days in each month for any given year length. For example, according to Palevny's proposition, a year that consists of 108 days will have three months, 36 days each. The year that consists of 99 days will have 11 months, 9 days each, and a year of 365 days will have 365 months, one day each.The proposal provoked heated discussion in the community, the famous mathematician Perelmanov quickly calculated that if the proposal is supported, then in a period of n years, beginning with the year that has a days, the country will spend p sheets of paper to print a set of calendars for these years. Perelmanov's calculations take into account the fact that the set will contain one calendar for each year and each month will be printed on a separate sheet.Repeat Perelmanov's achievement and print the required number p. You are given positive integers a and n. Perelmanov warns you that your program should not work longer than four seconds at the maximum test.InputThe only input line contains a pair of integers a, n (1 ≀ a, n ≀ 107; a + n - 1 ≀ 107).OutputPrint the required number p. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use cin, cout streams or the %I64d specifier.ExamplesInput25 3Output30Input50 5Output125NoteA note to the first sample test. A year of 25 days will consist of one month containing 25 days. A year of 26 days will consist of 26 months, one day each. A year of 27 days will have three months, 9 days each.
Input25 3
Output30
2 seconds
256 megabytes
['*special problem', 'number theory', '*1500']
C. Bustime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a bus stop near the university. The lessons are over, and n students come to the stop. The i-th student will appear at the bus stop at time ti (all ti's are distinct).We shall assume that the stop is located on the coordinate axis Ox, at point x = 0, and the bus goes along the ray Ox, that is, towards the positive direction of the coordinate axis, and back. The i-th student needs to get to the point with coordinate xi (xi > 0).The bus moves by the following algorithm. Initially it is at point 0. The students consistently come to the stop and get on it. The bus has a seating capacity which is equal to m passengers. At the moment when m students get on the bus, it starts moving in the positive direction of the coordinate axis. Also it starts moving when the last (n-th) student gets on the bus. The bus is moving at a speed of 1 unit of distance per 1 unit of time, i.e. it covers distance y in time y.Every time the bus passes the point at which at least one student needs to get off, it stops and these students get off the bus. The students need 1 + [k / 2] units of time to get off the bus, where k is the number of students who leave at this point. Expression [k / 2] denotes rounded down k / 2. As soon as the last student leaves the bus, the bus turns around and goes back to the point x = 0. It doesn't make any stops until it reaches the point. At the given point the bus fills with students once more, and everything is repeated.If students come to the stop when there's no bus, they form a line (queue) and get on the bus in the order in which they came. Any number of students get on the bus in negligible time, you should assume that it doesn't take any time. Any other actions also take no time. The bus has no other passengers apart from the students.Write a program that will determine for each student the time when he got off the bus. The moment a student got off the bus is the moment the bus stopped at the student's destination stop (despite the fact that the group of students need some time to get off).InputThe first line contains two space-separated integers n, m (1 ≀ n, m ≀ 105) β€” the number of students and the number of passengers the bus can transport, correspondingly. Next n lines contain descriptions of the students, one per line. Each line contains a pair of integers ti, xi (1 ≀ ti ≀ 105, 1 ≀ xi ≀ 104). The lines are given in the order of strict increasing of ti. Values of xi can coincide.OutputPrint n numbers w1, w2, ..., wn, wi β€” the moment of time when the i-th student got off the bus. Print the numbers on one line and separate them with single spaces.ExamplesInput1 103 5Output8Input2 13 54 5Output8 19Input5 43 54 55 56 57 1Output11 11 11 11 20Input20 428 1331 1335 636 452 653 483 284 487 193 6108 4113 6116 1125 2130 2136 13162 2166 4184 1192 2Output51 51 43 40 93 89 86 89 114 121 118 121 137 139 139 152 195 199 193 195NoteIn the first sample the bus waits for the first student for 3 units of time and drives him to his destination in additional 5 units of time. So the student leaves the bus at the moment of time 3 + 5 = 8.In the second sample the capacity of the bus equals 1, that's why it will drive the first student alone. This student is the same as the student from the first sample. So the bus arrives to his destination at the moment of time 8, spends 1 + [1 / 2] = 1 units of time on getting him off, and returns back to 0 in additional 5 units of time. That is, the bus returns to the bus stop at the moment of time 14. By this moment the second student has already came to the bus stop. So he immediately gets in the bus, and is driven to his destination in additional 5 units of time. He gets there at the moment 14 + 5 = 19. In the third sample the bus waits for the fourth student for 6 units of time, then drives for 5 units of time, then gets the passengers off for 1 + [4 / 2] = 3 units of time, then returns for 5 units of time, and then drives the fifth student for 1 unit of time.
Input1 103 5
Output8
1 second
256 megabytes
['*special problem', 'implementation', 'sortings', '*1500']
B. Pseudorandom Sequence Periodtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has recently got interested in sequences of pseudorandom numbers. He learned that many programming languages generate such sequences in a similar way: (for i β‰₯ 1). Here a, b, m are constants, fixed for the given realization of the pseudorandom numbers generator, r0 is the so-called randseed (this value can be set from the program using functions like RandSeed(r) or srand(n)), and denotes the operation of taking the remainder of division.For example, if a = 2, b = 6, m = 12, r0 = 11, the generated sequence will be: 4, 2, 10, 2, 10, 2, 10, 2, 10, 2, 10, ....Polycarpus realized that any such sequence will sooner or later form a cycle, but the cycle may occur not in the beginning, so there exist a preperiod and a period. The example above shows a preperiod equal to 1 and a period equal to 2.Your task is to find the period of a sequence defined by the given values of a, b, m and r0. Formally, you have to find such minimum positive integer t, for which exists such positive integer k, that for any i β‰₯ k: ri = ri + t.InputThe single line of the input contains four integers a, b, m and r0 (1 ≀ m ≀ 105, 0 ≀ a, b ≀ 1000, 0 ≀ r0 < m), separated by single spaces.OutputPrint a single integer β€” the period of the sequence.ExamplesInput2 6 12 11Output2Input2 3 5 1Output4Input3 6 81 9Output1NoteThe first sample is described above. In the second sample the sequence is (starting from the first element): 0, 3, 4, 1, 0, 3, 4, 1, 0, ...In the third sample the sequence is (starting from the first element): 33, 24, 78, 78, 78, 78, ...
Input2 6 12 11
Output2
2 seconds
256 megabytes
['*special problem', 'implementation', 'number theory', '*1200']
A. Phone Codetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≀ i ≀ n). Help Polycarpus determine the length of the city phone code. InputThe first line of the input contains an integer n (2 ≀ n ≀ 3Β·104) β€” the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn β€” the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.OutputPrint the number of digits in the city phone code.ExamplesInput400209002190099900909Output2Input212Output0Input3770123456789999999997701234567890123456777012345678998765432Output12NoteA prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209".In the first sample the city phone code is string "00".In the second sample the city phone code is an empty string.In the third sample the city phone code is string "770123456789".
Input400209002190099900909
Output2
2 seconds
256 megabytes
['*special problem', 'brute force', 'implementation', '*800']
H. A polylinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output InputThe input contains two integers a, b (1 ≀ a ≀ 10, 0 ≀ b ≀ 22Β·a - 1) separated by a single space.OutputOutput two integers separated by a single space.ExamplesInput1 0Output0 0Input2 15Output3 0Input4 160Output12 12
Input1 0
Output0 0
2 seconds
256 megabytes
['*special problem', 'implementation', '*1700']
G. Mysterious numbers - 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe only line of input contains three integers a1, a2, a3 (1 ≀ a1, a2, a3 ≀ 20), separated by spaces.OutputOutput a single integer.ExamplesInput2 3 2Output5Input13 14 1Output14Input14 5 9Output464Input17 18 3Output53
Input2 3 2
Output5
2 seconds
256 megabytes
['*special problem', '*1600']
F. ucyhftime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputqd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.Inputjxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 ≀ d ≀ 11184) β€” jxu edu-rqiut ydtun ev jxu ucyhf je vydt.Outputekjfkj q iydwbu dkcruh.ExamplesInput1Output13
Input1
Output13
2 seconds
64 megabytes
['*special problem', 'brute force', 'implementation', 'number theory', '*1600']
C. A Piece of Caketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHow to make a cake you'll never eat.Ingredients. 2 carrots 0 calories 100 g chocolate spread 1 pack of flour 1 egg Method. Put calories into the mixing bowl. Take carrots from refrigerator. Chop carrots. Take chocolate spread from refrigerator. Put chocolate spread into the mixing bowl. Combine pack of flour into the mixing bowl. Fold chocolate spread into the mixing bowl. Add chocolate spread into the mixing bowl. Put pack of flour into the mixing bowl. Add egg into the mixing bowl. Fold pack of flour into the mixing bowl. Chop carrots until choped. Pour contents of the mixing bowl into the baking dish. Serves 1.InputThe only line of input contains a sequence of integers a0, a1, ... (1 ≀ a0 ≀ 100, 0 ≀ ai ≀ 1000 for i β‰₯ 1).OutputOutput a single integer.ExamplesInput4 1 2 3 4Output30
Input4 1 2 3 4
Output30
2 seconds
256 megabytes
['*special problem', 'implementation', '*2000']
B. Startime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output InputThe input contains a single integer a (1 ≀ a ≀ 18257).OutputPrint a single integer output (1 ≀ output ≀ 2Β·109).ExamplesInput2Output13
Input2
Output13
2 seconds
256 megabytes
['*special problem', 'combinatorics', '*1300']
A. Mysterious numbers - 1time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe input contains two integers a1, a2 (0 ≀ ai ≀ 109), separated by a single space.OutputOutput a single integer.ExamplesInput3 14Output44Input27 12Output48Input100 200Output102
Input3 14
Output44
2 seconds
256 megabytes
['*special problem', 'constructive algorithms', '*1200']
B. Replacing Digitstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≀ j ≀ m) of sequence s means that you can choose an arbitrary position i (1 ≀ i ≀ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation.Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s.InputThe first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators.The given number a doesn't contain leading zeroes. OutputPrint the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes.ExamplesInput1024010Output1124Input9871234567Output987
Input1024010
Output1124
2 seconds
256 megabytes
['greedy', '*1100']
A. Chorestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter β€” its complexity. The complexity of the i-th chore equals hi.As Petya is older, he wants to take the chores with complexity larger than some value x (hi > x) to leave to Vasya the chores with complexity less than or equal to x (hi ≀ x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a + b = n).In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?InputThe first input line contains three integers n, a and b (2 ≀ n ≀ 2000; a, b β‰₯ 1; a + b = n) β€” the total number of chores, the number of Petya's chores and the number of Vasya's chores.The next line contains a sequence of integers h1, h2, ..., hn (1 ≀ hi ≀ 109), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different.All numbers on the lines are separated by single spaces.OutputPrint the required number of ways to choose an integer value of x. If there are no such ways, print 0.ExamplesInput5 2 36 2 3 100 1Output3Input7 3 41 1 9 1 1 1 1Output0NoteIn the first sample the possible values of x are 3, 4 or 5.In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4.
Input5 2 36 2 3 100 1
Output3
2 seconds
256 megabytes
['sortings', '*800']
B. Wizards and Minimal Spelltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's dive into one of the most interesting areas of magic β€” writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.Each spell consists of several lines. The line, whose first non-space character is character "#" is an amplifying line and it is responsible for spell power. The remaining lines are common, and determine the effect of the spell.You came across the text of some spell. Spell was too long, so you cannot understand its meaning. So you want to make it as short as possible without changing the meaning.The only way to shorten a spell that you know is the removal of some spaces and line breaks. We know that when it comes to texts of spells, the spaces carry meaning only in the amplifying lines, so we should remove all spaces in other lines. Newlines also do not matter, unless any of the two separated lines is amplifying. Thus, if two consecutive lines are not amplifying, they need to be joined into one (i.e. we should concatenate the second line to the first one). Removing spaces in amplifying lines and concatenating the amplifying lines to anything is forbidden.Note that empty lines must be processed just like all the others: they must be joined to the adjacent non-amplifying lines, or preserved in the output, if they are surrounded with amplifying lines on both sides (i.e. the line above it, if there is one, is amplifying, and the line below it, if there is one, is amplifying too).For now those are the only instructions for removing unnecessary characters that you have to follow (oh yes, a newline is a character, too).The input contains the text of the spell, which should be reduced. Remove the extra characters and print the result to the output.InputThe input contains multiple lines. All characters in the lines have codes from 32 to 127 (inclusive). Please note that the lines may begin with or end with one or more spaces. The size of the input does not exceed 1048576 ( = 220) bytes. Newlines are included in this size.In the Windows operating system used on the testing computer, a newline is a sequence of characters with codes #13#10. It is guaranteed that after each line of input there is a newline. In particular, the input ends with a newline. Note that the newline is the end of the line, and not the beginning of the next one.It is guaranteed that the input contains at least one character other than a newline.It is recommended to organize the input-output line by line, in this case the newlines will be processed correctly by the language means.OutputPrint the text of the spell where all extra characters are deleted. Please note that each output line should be followed by a newline.Please be careful: your answers will be validated by comparing them to the jury's answer byte-by-byte. So, all spaces and newlines matter.ExamplesInput # include <cstdio>using namespace std;int main ( ){puts("Hello # World"); ##}Output # include <cstdio>usingnamespacestd;intmain(){puts("Hello#World");##}Input##Output##NoteIn the first sample the amplifying lines are lines 1 and 7. So, lines 2 to 6 are concatenated to each other, all spaces are deleted from them.In the second sample the amplifying lines are lines 1 and 3. So, no lines are concatenated to each other.
Input # include <cstdio>using namespace std;int main ( ){puts("Hello # World"); ##}
Output # include <cstdio>usingnamespacestd;intmain(){puts("Hello#World");##}
2 seconds
256 megabytes
['implementation', 'strings', '*1700']
A. Wizards and Demonstrationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome country is populated by wizards. They want to organize a demonstration.There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration. So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets. Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.InputThe first line contains three space-separated integers, n, x, y (1 ≀ n, x, y ≀ 104, x ≀ n) β€” the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).OutputPrint a single integer β€” the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population). ExamplesInput10 1 14Output1Input20 10 50Output0Input1000 352 146Output1108NoteIn the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone. In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Input10 1 14
Output1
2 seconds
256 megabytes
['implementation', 'math', '*900']
E. Wizards and Betstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn some country live wizards. They like to make weird bets.Two wizards draw an acyclic directed graph with n vertices and m edges (the graph's vertices are numbered from 1 to n). A source is a vertex with no incoming edges, and a sink is the vertex with no outgoing edges. Note that a vertex could be the sink and the source simultaneously. In the wizards' graph the number of the sinks and the sources is the same.Wizards numbered the sources in the order of increasing numbers of the vertices from 1 to k. The sinks are numbered from 1 to k in the similar way.To make a bet, they, as are real wizards, cast a spell, which selects a set of k paths from all sources to the sinks in such a way that no two paths intersect at the vertices. In this case, each sink has exactly one path going to it from exactly one source. Let's suppose that the i-th sink has a path going to it from the ai's source. Then let's call pair (i, j) an inversion if i < j and ai > aj. If the number of inversions among all possible pairs (i, j), such that (1 ≀ i < j ≀ k), is even, then the first wizard wins (the second one gives him one magic coin). Otherwise, the second wizard wins (he gets one magic coin from the first one).Our wizards are captured with feverish excitement, so they kept choosing new paths again and again for so long that eventually they have chosen every possible set of paths for exactly once. The two sets of non-intersecting pathes are considered to be different, if and only if there is an edge, which lies at some path in one set and doesn't lie at any path of another set. To check their notes, they asked you to count the total winnings of the first player for all possible sets of paths modulo a prime number p.InputThe first line contains three space-separated integers n, m, p (1 ≀ n ≀ 600, 0 ≀ m ≀ 105, 2 ≀ p ≀ 109 + 7). It is guaranteed that p is prime number.Next m lines contain edges of the graph. Each line contains a pair of space-separated integers, aiΒ bi β€” an edge from vertex ai to vertex bi. It is guaranteed that the graph is acyclic and that the graph contains the same number of sources and sinks. Please note that the graph can have multiple edges.OutputPrint the answer to the problem β€” the total winnings of the first player modulo a prime number p. Please note that the winnings may be negative, but the modulo residue must be non-negative (see the sample).ExamplesInput4 2 10000031 32 4Output1Input4 2 10000034 13 2Output1000002Input4 4 10000032 12 43 13 4Output0Input6 5 10000031 41 51 62 63 6Output0Input5 2 10000035 13 4Output1NoteIn the first sample, there is exactly one set of paths β€” . The number of inversions is 0, which is an even number. Therefore, the first wizard gets 1 coin.In the second sample there is exactly one set of paths β€” . There is exactly one inversion. Therefore, the first wizard gets -1 coin. .In the third sample, there are two sets of paths, which are counted with opposite signs.In the fourth sample there are no set of paths at all.In the fifth sample, there are three sources β€” the vertices with the numbers (2, 3, 5) and three sinks β€” the vertices with numbers (1, 2, 4). For a single set of paths are 2 inversions, that is, their number is even.
Input4 2 10000031 32 4
Output1
3 seconds
256 megabytes
['dfs and similar', 'graphs', 'math', 'matrices', '*2900']
D. Wizards and Roadstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn some country live wizards. They love to build cities and roads.The country used to have k cities, the j-th city (1 ≀ j ≀ k) was located at a point (xj, yj). It was decided to create another n - k cities. And the i-th one (k < i ≀ n) was created at a point with coordinates (xi, yi): xi = (aΒ·xi - 1 + b)Β modΒ (109 + 9) yi = (cΒ·yi - 1 + d)Β modΒ (109 + 9) Here a, b, c, d are primes. Also, a ≠ c, b ≠ d.After the construction of all n cities, the wizards have noticed something surprising. It turned out that for every two different cities i and j, xi ≠ xj and yi ≠ yj holds.The cities are built, it's time to build roads! It was decided to use the most difficult (and, of course, the most powerful) spell for the construction of roads. Using this spell creates a road between the towns of u, v (yu > yv) if and only if for any city w which lies strictly inside the corner at the point u, v (see below), there is a city s that does not lie in the corner, which is located along the x-coordinate strictly between w and u and simultaneously ys > yv.A corner on the points p2(x2, y2), p1(x1, y1) (y1 < y2) is the set of points (x, y), for which at least one of the two conditions is fulfilled: min(x1, x2) ≀ x ≀ max(x1, x2) and y β‰₯ y1 y1 ≀ y ≀ y2 and (x - x2)Β·(x1 - x2) β‰₯ 0 The pictures showing two different corners In order to test the spell, the wizards will apply it to all the cities that lie on the x-coordinate in the interval [L, R]. After the construction of roads the national government wants to choose the maximum number of pairs of cities connected by the road, so that no city occurs in two or more pairs. Your task is for each m offered variants of values L, R to calculate the maximum number of such pairs after the construction of the roads. Please note that the cities that do not lie in the interval [L, R] on the x-coordinate, do not affect the construction of roads in any way.InputThe first line contains two space-separated integers n, k (1 ≀ k ≀ n ≀ 105, k ≀ 30). Next k lines contain coordinates of the cities' location points from the first to the k-th one. The j-th line contains space-separated pair of integers xj, yj (0 ≀ xj, yj < 109 + 9) β€” coordinates of the j-th city.The next line contains space-separated integers a, b, c, d (2 ≀ a, b, c, d < 109 + 9). It is guaranteed that those numbers are prime and also that a ≠ c, b ≠ d. It's guaranteed, that for every two different cities i and j, xi ≠ xj and yi ≠ yj holds.The next line contains integer m (1 ≀ m ≀ 105) β€” the number of variants to build the roads. Next m lines contain pairs of space-separated integers Li, Ri (0 ≀ Li ≀ Ri < 109 + 9) β€” the variants of choosing the cities to build the roads.OutputFor any pair of numbers Li, Ri print the answer to the problem on a single line. Print the answers for the pairs in the order, in which the pairs are given in the input data.ExamplesInput6 60 01 12 23 34 45 52 3 3 240 51 42 33 3Output3210Input6 10 03 5 23917 1140 10000000080 10100 150200 10000Output2101NoteIn the first sample the roads connect the cities in a chain in the order of increasing of x. In the second sample the remaining 5 cities will be located at points (5,  11);Β (20,  263098);Β (65,  292514823);Β (200,  76958738);Β (605,  622120197).
Input6 60 01 12 23 34 45 52 3 3 240 51 42 33 3
Output3210
3 seconds
256 megabytes
['data structures', 'divide and conquer', 'graph matchings', 'graphs', 'greedy', '*3000']
C. Wizards and Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn some country live wizards. They love playing with numbers. The blackboard has two numbers written on it β€” a and b. The order of the numbers is not important. Let's consider a ≀ b for the sake of definiteness. The players can cast one of the two spells in turns: Replace b with b - ak. Number k can be chosen by the player, considering the limitations that k > 0 and b - ak β‰₯ 0. Number k is chosen independently each time an active player casts a spell. Replace b with bΒ modΒ a. If a > b, similar moves are possible.If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses.To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second.InputThe first line contains a single integer t β€” the number of input data sets (1 ≀ t ≀ 104). Each of the next t lines contains two integers a, b (0 ≀ a, b ≀ 1018). The numbers are separated by a space.Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.OutputFor any of the t input sets print "First" (without the quotes) if the player who moves first wins. Print "Second" (without the quotes) if the player who moves second wins. Print the answers to different data sets on different lines in the order in which they are given in the input. ExamplesInput410 2131 100 110 30OutputFirstSecondSecondFirstNoteIn the first sample, the first player should go to (11,10). Then, after a single move of the second player to (1,10), he will take 10 modulo 1 and win.In the second sample the first player has two moves to (1,10) and (21,10). After both moves the second player can win.In the third sample, the first player has no moves.In the fourth sample, the first player wins in one move, taking 30 modulo 10.
Input410 2131 100 110 30
OutputFirstSecondSecondFirst
2 seconds
256 megabytes
['games', 'math', '*2300']
B. Wizards and Huge Prizetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees.One of such magic schools consists of n tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've brought with you have space for no more than k huge prizes.Besides the fact that you want to take all the prizes home, you also want to perform well. You will consider your performance good if you win at least l tours.In fact, years of organizing contests proved to the organizers that transporting huge prizes is an issue for the participants. Alas, no one has ever invented a spell that would shrink the prizes... So, here's the solution: for some tours the winner gets a bag instead of a huge prize. Each bag is characterized by number ai β€” the number of huge prizes that will fit into it.You already know the subject of all tours, so you can estimate the probability pi of winning the i-th tour. You cannot skip the tour under any circumstances.Find the probability that you will perform well on the contest and will be able to take all won prizes home (that is, that you will be able to fit all the huge prizes that you won into the bags that you either won or brought from home).InputThe first line contains three integers n, l, k (1 ≀ n ≀ 200, 0 ≀ l, k ≀ 200) β€” the number of tours, the minimum number of tours to win, and the number of prizes that you can fit in the bags brought from home, correspondingly.The second line contains n space-separated integers, pi (0 ≀ pi ≀ 100) β€” the probability to win the i-th tour, in percents.The third line contains n space-separated integers, ai (1 ≀ ai ≀ 200) β€” the capacity of the bag that will be awarded to you for winning the i-th tour, or else -1, if the prize for the i-th tour is a huge prize and not a bag.OutputPrint a single real number β€” the answer to the problem. The answer will be accepted if the absolute or relative error does not exceed 10 - 6.ExamplesInput3 1 010 20 30-1 -1 2Output0.300000000000Input1 1 1100123Output1.000000000000NoteIn the first sample we need either win no tour or win the third one. If we win nothing we wouldn't perform well. So, we must to win the third tour. Other conditions will be satisfied in this case. Probability of wining the third tour is 0.3.In the second sample we win the only tour with probability 1.0, and go back home with bag for it.
Input3 1 010 20 30-1 -1 2
Output0.300000000000
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*1800']
A. Wizards and Trolleybusestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn some country live wizards. They love to ride trolleybuses.A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it leaves at the moment of time ti seconds, can go at a speed of no greater than vi meters per second, and accelerate with an acceleration no greater than a meters per second squared. A trolleybus can decelerate as quickly as you want (magic!). It can change its acceleration as fast as you want, as well. Note that the maximum acceleration is the same for all trolleys.Despite the magic the trolleys are still powered by an electric circuit and cannot overtake each other (the wires are to blame, of course). If a trolleybus catches up with another one, they go together one right after the other until they arrive at the final station. Also, the drivers are driving so as to arrive at the final station as quickly as possible.You, as head of the trolleybuses' fans' club, are to determine for each trolley the minimum time by which it can reach the final station. At the time of arrival at the destination station the trolleybus does not necessarily have zero speed. When a trolley is leaving the depot, its speed is considered equal to zero. From the point of view of physics, the trolleybuses can be considered as material points, and also we should ignore the impact on the speed of a trolley bus by everything, except for the acceleration and deceleration provided by the engine.InputThe first input line contains three space-separated integers n, a, d (1 ≀ n ≀ 105, 1 ≀ a, d ≀ 106) β€” the number of trolleybuses, their maximum acceleration and the distance from the depot to the final station, correspondingly.Next n lines contain pairs of integers ti vi (0 ≀ t1 < t2... < tn - 1 < tn ≀ 106, 1 ≀ vi ≀ 106) β€” the time when the i-th trolleybus leaves the depot and its maximum speed, correspondingly. The numbers in the lines are separated by spaces.OutputFor each trolleybus print a single line the time it arrives to the final station. Print the times for the trolleybuses in the order in which the trolleybuses are given in the input. The answer will be accepted if the absolute or relative error doesn't exceed 10 - 4.ExamplesInput3 10 100000 105 111000 1Output1000.50000000001000.500000000011000.0500000000Input1 2 2628 29Output33.0990195136NoteIn the first sample the second trolleybus will catch up with the first one, that will happen at distance 510.5 meters from the depot. The trolleybuses will go the remaining 9489.5 meters together at speed 10 meters per second. As a result, both trolleybuses will arrive to the final station by the moment of time 1000.5 seconds. The third trolleybus will not catch up with them. It will arrive to the final station by the moment of time 11000.05 seconds.
Input3 10 100000 105 111000 1
Output1000.50000000001000.500000000011000.0500000000
1 second
256 megabytes
['implementation', 'math', '*1600']
E. Tetrahedrontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). InputThe first line contains the only integer n (1 ≀ n ≀ 107) β€” the required length of the cyclic path.OutputPrint the only integer β€” the required number of ways modulo 1000000007 (109 + 7).ExamplesInput2Output3Input4Output21NoteThe required paths in the first sample are: D - A - D D - B - D D - C - D
Input2
Output3
2 seconds
256 megabytes
['dp', 'math', 'matrices', '*1500']
D. Shoe Storetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe warehouse in your shop has n shoe pairs. Each pair is characterized by two integers: its price ci and its size si. We know that on this very day all numbers si are different, that is, there is no more than one pair of each size.The shop has m customers who came at the same time. The customer number i has di money and the size of his feet equals li. The customer number i can buy the pair number j, if cj ≀ di, and also if li = sj or li = sj - 1; that is, it is necessary that he has enough money to pay for the shoes. It is also necessary that the size of his feet equals to or is less by 1 than the size of the shoes he chooses.Your task is to sell some customers pairs of shoes (a pair per person) so as to maximize the sum of the sold pairs cj that is, the profit. It is guaranteed that each customer buys no more than one pair and each pair will be bought by no more than one customer.InputThe first input line contains the only integer n (1 ≀ n ≀ 105) β€” the number of shoe pairs in the warehouse. Then n lines contain the descriptions of pairs of shoes as two integers ci and si (1 ≀ ci, si ≀ 109), the numbers are separated by a space. It is guaranteed that all numbers si are different.The next line contains an integer m (1 ≀ m ≀ 105) β€” the number of customers in the shop. Next m lines contain the customers' descriptions as two integers di and li (1 ≀ di, li ≀ 109), the numbers are separated by a space.OutputIn the first line print the only integer β€” the maximum profit you can get from selling shoes. In the second line print an integer k β€” the number of shoe pairs you will sell. In the following k lines print the descriptions of the sold pairs β€” two space-separated integers where the first number is the customer's number and the second number is the number of the shoes the customer will buy.You can print pairs of numbers "the customer's number and the shoes' number" in any order, the customers and the pairs of shoes are numbered starting from 1 in the order in which they are given in the input. If there are several optimal answers, you are allowed to print any of them.Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator instead.ExamplesInput310 130 220 3220 120 2Output3022 31 1Input310 420 530 6270 450 5Output5022 31 2
Input310 130 220 3220 120 2
Output3022 31 1
2 seconds
256 megabytes
['dp', 'graph matchings', 'greedy', 'sortings', 'two pointers', '*2500']
C. Mediantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA median in an array with the length of n is an element which occupies position number after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) β€” the number 17.We define an expression as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.InputThe first input line contains two space-separated integers n and x (1 ≀ n ≀ 500, 1 ≀ x ≀ 105) β€” the initial array's length and the required median's value. The second line contains n space-separated numbers β€” the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.OutputPrint the only integer β€” the minimum number of elements Petya needs to add to the array so that its median equals x.ExamplesInput3 1010 20 30Output1Input3 41 2 3Output4NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.
Input3 1010 20 30
Output1
2 seconds
256 megabytes
['greedy', 'math', 'sortings', '*1500']
B. Polygonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got another geometrical task. You are given two non-degenerate polygons A and B as vertex coordinates. Polygon A is strictly convex. Polygon B is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.Your task is to check whether polygon B is positioned strictly inside polygon A. It means that any point of polygon B should be strictly inside polygon A. "Strictly" means that the vertex of polygon B cannot lie on the side of the polygon A.InputThe first line contains the only integer n (3 ≀ n ≀ 105) β€” the number of vertices of polygon A. Then n lines contain pairs of integers xi, yi (|xi|, |yi| ≀ 109) β€” coordinates of the i-th vertex of polygon A. The vertices are given in the clockwise order.The next line contains a single integer m (3 ≀ m ≀ 2Β·104) β€” the number of vertices of polygon B. Then following m lines contain pairs of integers xj, yj (|xj|, |yj| ≀ 109) β€” the coordinates of the j-th vertex of polygon B. The vertices are given in the clockwise order.The coordinates of the polygon's vertices are separated by a single space. It is guaranteed that polygons A and B are non-degenerate, that polygon A is strictly convex, that polygon B has no self-intersections and self-touches and also for each polygon no three consecutively following vertices are located on the same straight line.OutputPrint on the only line the answer to the problem β€” if polygon B is strictly inside polygon A, print "YES", otherwise print "NO" (without the quotes).ExamplesInput6-2 10 33 34 13 -22 -240 12 23 11 0OutputYESInput51 24 23 -3-2 -2-2 140 11 24 12 -1OutputNOInput5-1 22 34 13 -20 -351 01 13 15 -12 -1OutputNO
Input6-2 10 33 34 13 -22 -240 12 23 11 0
OutputYES
2 seconds
256 megabytes
['geometry', 'sortings', '*2100']
A. Rank Listtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnother programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either pa > pb, or pa = pb and ta < tb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places y + 1, y + 2, ..., y + x. The teams that performed worse than the teams from this group, get their places in the results table starting from the y + x + 1-th place.Your task is to count what number of teams from the given list shared the k-th place. InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1 ≀ pi, ti ≀ 50) β€” the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces. OutputIn the only line print the sought number of teams that got the k-th place in the final results' table.ExamplesInput7 24 104 104 103 202 12 11 10Output3Input5 43 13 15 33 13 1Output4NoteThe final results' table for the first sample is: 1-3 places β€” 4 solved problems, the penalty time equals 10 4 place β€” 3 solved problems, the penalty time equals 20 5-6 places β€” 2 solved problems, the penalty time equals 1 7 place β€” 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is: 1 place β€” 5 solved problems, the penalty time equals 3 2-5 places β€” 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams.
Input7 24 104 104 103 202 12 11 10
Output3
2 seconds
256 megabytes
['binary search', 'implementation', 'sortings', '*1100']
E. Compatible Numberstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo integers x and y are compatible, if the result of their bitwise "AND" equals zero, that is, a & b = 0. For example, numbers 90 (10110102) and 36 (1001002) are compatible, as 10110102 & 1001002 = 02, and numbers 3 (112) and 6 (1102) are not compatible, as 112 & 1102 = 102.You are given an array of integers a1, a2, ..., an. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.InputThe first line contains an integer n (1 ≀ n ≀ 106) β€” the number of elements in the given array. The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 4Β·106) β€” the elements of the given array. The numbers in the array can coincide.OutputPrint n integers ansi. If ai isn't compatible with any other element of the given array a1, a2, ..., an, then ansi should be equal to -1. Otherwise ansi is any such number, that ai & ansi = 0, and also ansi occurs in the array a1, a2, ..., an.ExamplesInput290 36Output36 90Input43 6 3 6Output-1 -1 -1 -1Input510 6 9 8 2Output-1 8 2 2 8
Input290 36
Output36 90
4 seconds
256 megabytes
['bitmasks', 'brute force', 'dfs and similar', 'dp', '*2200']
D. Beard Graphtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a non-oriented connected graph of n vertices and n - 1 edges as a beard, if all of its vertices except, perhaps, one, have the degree of 2 or 1 (that is, there exists no more than one vertex, whose degree is more than two). Let us remind you that the degree of a vertex is the number of edges that connect to it. Let each edge be either black or white. Initially all edges are black.You are given the description of the beard graph. Your task is to analyze requests of the following types: paint the edge number i black. The edge number i is the edge that has this number in the description. It is guaranteed that by the moment of this request the i-th edge is white paint the edge number i white. It is guaranteed that by the moment of this request the i-th edge is black find the length of the shortest path going only along the black edges between vertices a and b or indicate that no such path exists between them (a path's length is the number of edges in it) The vertices are numbered with integers from 1 to n, and the edges are numbered with integers from 1 to n - 1.InputThe first line of the input contains an integer n (2 ≀ n ≀ 105) β€” the number of vertices in the graph. Next n - 1 lines contain edges described as the numbers of vertices vi, ui (1 ≀ vi, ui ≀ n, vi ≠ ui) connected by this edge. It is guaranteed that the given graph is connected and forms a beard graph, and has no self-loops or multiple edges.The next line contains an integer m (1 ≀ m ≀ 3Β·105) β€” the number of requests. Next m lines contain requests in the following form: first a line contains an integer type, which takes values ​​from 1 to 3, and represents the request type.If type = 1, then the current request is a request to paint the edge black. In this case, in addition to number type the line should contain integer id (1 ≀ id ≀ n - 1), which represents the number of the edge to paint.If type = 2, then the current request is a request to paint the edge white, its form is similar to the previous request.If type = 3, then the current request is a request to find the distance. In this case, in addition to type, the line should contain two integers a, b (1 ≀ a, b ≀ n, a can be equal to b) β€” the numbers of vertices, the distance between which must be found.The numbers in all lines are separated by exactly one space. The edges are numbered in the order in which they are given in the input.OutputFor each request to "find the distance between vertices a and b" print the result. If there is no path going only along the black edges between vertices a and b, then print "-1" (without the quotes). Print the results in the order of receiving the requests, separate the numbers with spaces or line breaks.ExamplesInput31 22 373 1 23 1 33 2 32 23 1 23 1 33 2 3Output1211-1-1Input61 56 42 33 55 663 3 42 53 2 63 1 22 33 3 1Output3-132NoteIn the first sample vertices 1 and 2 are connected with edge number 1, and vertices 2 and 3 are connected with edge number 2. Before the repainting edge number 2 each vertex is reachable from each one along the black edges. Specifically, the shortest path between 1 and 3 goes along both edges.If we paint edge number 2 white, vertex 3 will end up cut off from other vertices, that is, no path exists from it to any other vertex along the black edges.
Input31 22 373 1 23 1 33 2 32 23 1 23 1 33 2 3
Output1211-1-1
4 seconds
256 megabytes
['data structures', 'dsu', 'trees', '*2100']
C. Another Problem on Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".InputThe first line contains the single integer k (0 ≀ k ≀ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.OutputPrint the single number β€” the number of substrings of the given string, containing exactly k characters "1".Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput11010Output6Input201010Output4Input10001010Output0NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".
Input11010
Output6
2 seconds
256 megabytes
['binary search', 'brute force', 'dp', 'math', 'strings', 'two pointers', '*1600']
B. Burning Midnight Oiltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day a highly important task was commissioned to Vasya β€” writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as lines, drinks another cup of tea, then he writes lines and so on: , , , ...The expression is regarded as the integral part from dividing number a by number b.The moment the current value equals 0, Vasya immediately falls asleep and he wakes up only in the morning, when the program should already be finished.Vasya is wondering, what minimum allowable value v can take to let him write not less than n lines of code before he falls asleep.InputThe input consists of two integers n and k, separated by spaces β€” the size of the program in lines and the productivity reduction coefficient, 1 ≀ n ≀ 109, 2 ≀ k ≀ 10.OutputPrint the only integer β€” the minimum value of v that lets Vasya write the program in one night.ExamplesInput7 2Output4Input59 9Output54NoteIn the first sample the answer is v = 4. Vasya writes the code in the following portions: first 4 lines, then 2, then 1, and then Vasya falls asleep. Thus, he manages to write 4 + 2 + 1 = 7 lines in a night and complete the task.In the second sample the answer is v = 54. Vasya writes the code in the following portions: 54, 6. The total sum is 54 + 6 = 60, that's even more than n = 59.
Input7 2
Output4
2 seconds
256 megabytes
['binary search', 'implementation', '*1500']
A. Supercentral Pointtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y): point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y point (x', y') is (x, y)'s left neighbor, if x' < x and y' = y point (x', y') is (x, y)'s lower neighbor, if x' = x and y' < y point (x', y') is (x, y)'s upper neighbor, if x' = x and y' > y We'll consider point (x, y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.InputThe first input line contains the only integer n (1 ≀ n ≀ 200) β€” the number of points in the given set. Next n lines contain the coordinates of the points written as "x y" (without the quotes) (|x|, |y| ≀ 1000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different.OutputPrint the only number β€” the number of supercentral points of the given set.ExamplesInput81 14 23 11 20 20 11 01 3Output2Input50 00 11 00 -1-1 0Output1NoteIn the first sample the supercentral points are only points (1, 1) and (1, 2).In the second sample there is one supercental point β€” point (0, 0).
Input81 14 23 11 20 20 11 01 3
Output2
2 seconds
256 megabytes
['implementation', '*1000']
E. Polycarpus and Taskstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has many tasks. Each task is characterized by three integers li, ri and ti. Three integers (li, ri, ti) mean that to perform task i, one needs to choose an integer si (li ≀ si;Β si + ti - 1 ≀ ri), then the task will be carried out continuously for ti units of time, starting at time si and up to time si + ti - 1, inclusive. In other words, a task is performed for a continuous period of time lasting ti, should be started no earlier than li, and completed no later than ri.Polycarpus's tasks have a surprising property: for any task j, k (with j < k) lj < lk and rj < rk.Let's suppose there is an ordered set of tasks A, containing |A| tasks. We'll assume that aj = (lj, rj, tj) (1 ≀ j ≀ |A|). Also, we'll assume that the tasks are ordered by increasing lj with the increase in number.Let's consider the following recursive function f, whose argument is an ordered set of tasks A, and the result is an integer. The function f(A) is defined by the greedy algorithm, which is described below in a pseudo-language of programming. Step 1. , ans = 0. Step 2. We consider all tasks in the order of increasing of their numbers in the set A. Lets define the current task counter i = 0. Step 3. Consider the next task: i = i + 1. If i > |A| fulfilled, then go to the 8 step. Step 4. If you can get the task done starting at time si = max(ans + 1, li), then do the task i: si = max(ans + 1, li), ans = si + ti - 1, . Go to the next task (step 3). Step 5. Otherwise, find such task , that first, task ai can be done at time si = max, and secondly, the value of is positive and takes the maximum value among all bk that satisfy the first condition. If you can choose multiple tasks as bk, choose the one with the maximum number in set A. Step 6. If you managed to choose task bk, then , . Go to the next task (step 3). Step 7. If you didn't manage to choose task bk, then skip task i. Go to the next task (step 3). Step 8. Return ans as a result of executing f(A). Polycarpus got entangled in all these formulas and definitions, so he asked you to simulate the execution of the function f, calculate the value of f(A).InputThe first line of the input contains a single integer n (1 ≀ n ≀ 105) β€” the number of tasks in set A. Then n lines describe the tasks. The i-th line contains three space-separated integers li, ri, ti (1 ≀ li ≀ ri ≀ 109, 1 ≀ ti ≀ ri - li + 1) β€” the description of the i-th task.It is guaranteed that for any tasks j, k (considering that j < k) the following is true: lj < lk and rj < rk.OutputFor each task i print a single integer β€” the result of processing task i on the i-th iteration of the cycle (step 3) in function f(A). In the i-th line print: 0 β€” if you managed to add task i on step 4. -1 β€” if you didn't manage to add or replace task i (step 7). resi (1 ≀ resi ≀ n) β€” if you managed to replace the task (step 6): resi equals the task number (in set A), that should be chosen as bk and replaced by task ai. ExamplesInput51 8 52 9 33 10 38 11 411 12 2Output0 0 1 0 -1 Input131 8 52 9 43 10 14 11 38 12 59 13 510 14 511 15 112 16 113 17 114 18 315 19 316 20 2Output0 0 0 2 -1 -1 0 0 0 0 7 0 12
Input51 8 52 9 33 10 38 11 411 12 2
Output0 0 1 0 -1
3 seconds
256 megabytes
['*3100']
D. Minimum Diametertime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points on the plane. You need to delete exactly k of them (k < n) so that the diameter of the set of the remaining n - k points were as small as possible. The diameter of a set of points is the maximum pairwise distance between the points of the set. The diameter of a one point set equals zero.InputThe first input line contains a pair of integers n, k (2 ≀ n ≀ 1000, 1 ≀ k ≀ 30, k < n) β€” the numbers of points on the plane and the number of points to delete, correspondingly.Next n lines describe the points, one per line. Each description consists of a pair of integers xi, yi (0 ≀ xi, yi ≀ 32000) β€” the coordinates of the i-th point. The given points can coincide.OutputPrint k different space-separated integers from 1 to n β€” the numbers of points to delete. The points are numbered in the order, in which they are given in the input from 1 to n. You can print the numbers in any order. If there are multiple solutions, print any of them.ExamplesInput5 21 20 02 21 13 3Output5 2Input4 10 00 01 11 1Output3
Input5 21 20 02 21 13 3
Output5 2
1.5 seconds
256 megabytes
['binary search', 'brute force', '*3100']
C. Machine Programmingtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne remarkable day company "X" received k machines. And they were not simple machines, they were mechanical programmers! This was the last unsuccessful step before switching to android programmers, but that's another story.The company has now n tasks, for each of them we know the start time of its execution si, the duration of its execution ti, and the company profit from its completion ci. Any machine can perform any task, exactly one at a time. If a machine has started to perform the task, it is busy at all moments of time from si to si + ti - 1, inclusive, and it cannot switch to another task.You are required to select a set of tasks which can be done with these k machines, and which will bring the maximum total profit.InputThe first line contains two integer numbers n and k (1 ≀ n ≀ 1000, 1 ≀ k ≀ 50) β€” the numbers of tasks and machines, correspondingly.The next n lines contain space-separated groups of three integers si, ti, ci (1 ≀ si, ti ≀ 109, 1 ≀ ci ≀ 106), si is the time where they start executing the i-th task, ti is the duration of the i-th task and ci is the profit of its execution.OutputPrint n integers x1, x2, ..., xn. Number xi should equal 1, if task i should be completed and otherwise it should equal 0.If there are several optimal solutions, print any of them.ExamplesInput3 12 7 51 3 34 1 3Output0 1 1Input5 21 5 41 4 51 3 24 1 25 6 1Output1 1 0 0 1NoteIn the first sample the tasks need to be executed at moments of time 2 ... 8, 1 ... 3 and 4 ... 4, correspondingly. The first task overlaps with the second and the third ones, so we can execute either task one (profit 5) or tasks two and three (profit 6).
Input3 12 7 51 3 34 1 3
Output0 1 1
5 seconds
256 megabytes
['flows', 'graphs', '*2400']
B. Ancient Berland Hieroglyphstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus enjoys studying Berland hieroglyphs. Once Polycarp got hold of two ancient Berland pictures, on each of which was drawn a circle of hieroglyphs. We know that no hieroglyph occurs twice in either the first or the second circle (but in can occur once in each of them).Polycarpus wants to save these pictures on his laptop, but the problem is, laptops do not allow to write hieroglyphs circles. So Polycarp had to break each circle and write down all of its hieroglyphs in a clockwise order in one line. A line obtained from the first circle will be called a, and the line obtained from the second one will be called b.There are quite many ways to break hieroglyphic circles, so Polycarpus chooses the method, that makes the length of the largest substring of string a, which occurs as a subsequence in string b, maximum.Help Polycarpus β€” find the maximum possible length of the desired substring (subsequence) if the first and the second circles are broken optimally.The length of string s is the number of characters in it. If we denote the length of string s as |s|, we can write the string as s = s1s2... s|s|.A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≀ a ≀ b ≀ |s|). For example, "code" and "force" are substrings of "codeforces", while "coders" is not. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≀ p1 < p2 < ... < p|y| ≀ |s|). For example, "coders" is a subsequence of "codeforces".InputThe first line contains two integers la and lb (1 ≀ la, lb ≀ 1000000) β€” the number of hieroglyphs in the first and second circles, respectively.Below, due to difficulties with encoding of Berland hieroglyphs, they are given as integers from 1 to 106.The second line contains la integers β€” the hieroglyphs in the first picture, in the clockwise order, starting with one of them.The third line contains lb integers β€” the hieroglyphs in the second picture, in the clockwise order, starting with one of them.It is guaranteed that the first circle doesn't contain a hieroglyph, which occurs twice. The second circle also has this property.OutputPrint a single number β€” the maximum length of the common substring and subsequence. If at any way of breaking the circles it does not exist, print 0.ExamplesInput5 41 2 3 4 51 3 5 6Output2Input4 61 3 5 21 2 3 4 5 6Output3Input3 31 2 33 2 1Output2NoteIn the first test Polycarpus picks a string that consists of hieroglyphs 5 and 1, and in the second sample β€” from hieroglyphs 1, 3 and 5.
Input5 41 2 3 4 51 3 5 6
Output2
1.5 seconds
256 megabytes
['two pointers', '*2000']
A. Variable, or There and Back Againtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLife is not easy for the perfectly common variable named Vasya. Wherever it goes, it is either assigned a value, or simply ignored, or is being used!Vasya's life goes in states of a program. In each state, Vasya can either be used (for example, to calculate the value of another variable), or be assigned a value, or ignored. Between some states are directed (oriented) transitions.A path is a sequence of states v1, v2, ..., vx, where for any 1 ≀ i < x exists a transition from vi to vi + 1.Vasya's value in state v is interesting to the world, if exists path p1, p2, ..., pk such, that pi = v for some i (1 ≀ i ≀ k), in state p1 Vasya gets assigned a value, in state pk Vasya is used and there is no state pi (except for p1) where Vasya gets assigned a value.Help Vasya, find the states in which Vasya's value is interesting to the world.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the numbers of states and transitions, correspondingly.The second line contains space-separated n integers f1, f2, ..., fn (0 ≀ fi ≀ 2), fi described actions performed upon Vasya in state i: 0 represents ignoring, 1 β€” assigning a value, 2 β€” using.Next m lines contain space-separated pairs of integers ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi), each pair represents the transition from the state number ai to the state number bi. Between two states can be any number of transitions.OutputPrint n integers r1, r2, ..., rn, separated by spaces or new lines. Number ri should equal 1, if Vasya's value in state i is interesting to the world and otherwise, it should equal 0. The states are numbered from 1 to n in the order, in which they are described in the input.ExamplesInput4 31 0 0 21 22 33 4Output1111Input3 11 0 21 3Output101Input3 12 0 11 3Output000NoteIn the first sample the program states can be used to make the only path in which the value of Vasya interests the world, 1 2 3 4; it includes all the states, so in all of them Vasya's value is interesting to the world.The second sample the only path in which Vasya's value is interesting to the world is , β€” 1 3; state 2 is not included there.In the third sample we cannot make from the states any path in which the value of Vasya would be interesting to the world, so the value of Vasya is never interesting to the world.
Input4 31 0 0 21 22 33 4
Output1111
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*1700']
E. e-Governmenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe best programmers of Embezzland compete to develop a part of the project called "e-Government" β€” the system of automated statistic collecting and press analysis.We know that any of the k citizens can become a member of the Embezzland government. The citizens' surnames are a1, a2, ..., ak. All surnames are different. Initially all k citizens from this list are members of the government. The system should support the following options: Include citizen ai to the government. Exclude citizen ai from the government. Given a newspaper article text, calculate how politicized it is. To do this, for every active government member the system counts the number of times his surname occurs in the text as a substring. All occurrences are taken into consideration, including the intersecting ones. The degree of politicization of a text is defined as the sum of these values for all active government members. Implement this system.InputThe first line contains space-separated integers n and k (1 ≀ n, k ≀ 105) β€” the number of queries to the system and the number of potential government members.Next k lines contain the surnames a1, a2, ..., ak, one per line. All surnames are pairwise different.Next n lines contain queries to the system, one per line. Each query consists of a character that determines an operation and the operation argument, written consecutively without a space.Operation "include in the government" corresponds to the character "+", operation "exclude" corresponds to "-". An argument of those operations is an integer between 1 and k β€” the index of the citizen involved in the operation. Any citizen can be included and excluded from the government an arbitrary number of times in any order. Including in the government a citizen who is already there or excluding the citizen who isn't there changes nothing.The operation "calculate politicization" corresponds to character "?". Its argument is a text.All strings β€” surnames and texts β€” are non-empty sequences of lowercase Latin letters. The total length of all surnames doesn't exceed 106, the total length of all texts doesn't exceed 106.OutputFor any "calculate politicization" operation print on a separate line the degree of the politicization of the given text. Print nothing for other operations.ExamplesInput7 3aaaab?aaab-2?aaab-3?aaab+2?aabbaaOutput6436
Input7 3aaaab?aaab-2?aaab-3?aaab+2?aabbaa
Output6436
1 second
256 megabytes
['data structures', 'dfs and similar', 'dp', 'strings', 'trees', '*2800']
D. Large Refrigeratortime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya wants to buy a new refrigerator. He believes that a refrigerator should be a rectangular parallelepiped with integer edge lengths. Vasya calculated that for daily use he will need a refrigerator with volume of at least V. Moreover, Vasya is a minimalist by nature, so the volume should be no more than V, either β€” why take up extra space in the apartment? Having made up his mind about the volume of the refrigerator, Vasya faced a new challenge β€” for a fixed volume of V the refrigerator must have the minimum surface area so that it is easier to clean.The volume and the surface area of a refrigerator with edges a, b, c are equal to V = abc and S = 2(ab + bc + ca), correspondingly.Given the volume V, help Vasya find the integer lengths for the refrigerator's edges a, b, c so that the refrigerator's volume equals V and its surface area S is minimized.InputThe first line contains a single integer t (1 ≀ t ≀ 500) β€” the number of data sets.The description of t data sets follows. Each set consists of a single integer V (2 ≀ V ≀ 1018), given by its factorization as follows.Let V = p1a1p2a2... pkak, where pi are different prime numbers and ai are positive integer powers. Then the first line describing a data set contains a single positive integer k β€” the number of different prime divisors of V. Next k lines contain prime numbers pi and their powers ai, separated by spaces. All pi are different, all ai > 0.OutputPrint t lines, on the i-th line print the answer to the i-th data set as four space-separated integers: the minimum possible surface area S and the corresponding edge lengths a, b, c. If there are multiple variants of the lengths of edges that give the minimum area, you are allowed to print any of them. You can print the lengths of the fridge's edges in any order.ExamplesInput312 3117 133 12 35 1Output24 2 2 270 1 1 17148 4 6 5NoteIn the first data set of the sample the fridge's volume V = 23 = 8, and the minimum surface area will be produced by the edges of equal length.In the second data set the volume V = 17, and it can be produced by only one set of integer lengths.
Input312 3117 133 12 35 1
Output24 2 2 270 1 1 17148 4 6 5
5 seconds
256 megabytes
['brute force', '*2900']
C. Conveyortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton came to a chocolate factory. There he found a working conveyor and decided to run on it from the beginning to the end.The conveyor is a looped belt with a total length of 2l meters, of which l meters are located on the surface and are arranged in a straight line. The part of the belt which turns at any moment (the part which emerges from under the floor to the surface and returns from the surface under the floor) is assumed to be negligibly short.The belt is moving uniformly at speed v1 meters per second. Anton will be moving on it in the same direction at the constant speed of v2 meters per second, so his speed relatively to the floor will be v1 + v2 meters per second. Anton will neither stop nor change the speed or the direction of movement.Here and there there are chocolates stuck to the belt (n chocolates). They move together with the belt, and do not come off it. Anton is keen on the chocolates, but he is more keen to move forward. So he will pick up all the chocolates he will pass by, but nothing more. If a chocolate is at the beginning of the belt at the moment when Anton starts running, he will take it, and if a chocolate is at the end of the belt at the moment when Anton comes off the belt, he will leave it. The figure shows an example with two chocolates. One is located in the position a1 = l - d, and is now on the top half of the belt, the second one is in the position a2 = 2l - d, and is now on the bottom half of the belt. You are given the positions of the chocolates relative to the initial start position of the belt 0 ≀ a1 < a2 < ... < an < 2l. The positions on the belt from 0 to l correspond to the top, and from l to 2l β€” to the the bottom half of the belt (see example). All coordinates are given in meters.Anton begins to run along the belt at a random moment of time. This means that all possible positions of the belt at the moment he starts running are equiprobable. For each i from 0 to n calculate the probability that Anton will pick up exactly i chocolates.InputThe first line contains space-separated integers n, l, v1 and v2 (1 ≀ n ≀ 105, 1 ≀ l, v1, v2 ≀ 109) β€” the number of the chocolates, the length of the conveyor's visible part, the conveyor's speed and Anton's speed.The second line contains a sequence of space-separated integers a1, a2, ..., an (0 ≀ a1 < a2 < ... < an < 2l) β€” the coordinates of the chocolates.OutputPrint n + 1 numbers (one per line): the probabilities that Anton picks up exactly i chocolates, for each i from 0 (the first line) to n (the last line). The answer will be considered correct if each number will have absolute or relative error of at most than 10 - 9.ExamplesInput1 1 1 10Output0.750000000000000000000.25000000000000000000Input2 3 1 22 5Output0.333333333333333310000.666666666666666630000.00000000000000000000NoteIn the first sample test Anton can pick up a chocolate if by the moment he starts running its coordinate is less than 0.5; but if by the moment the boy starts running the chocolate's coordinate is greater than or equal to 0.5, then Anton won't be able to pick it up. As all positions of the belt are equiprobable, the probability of picking up the chocolate equals , and the probability of not picking it up equals .
Input1 1 1 10
Output0.750000000000000000000.25000000000000000000
1 second
256 megabytes
['sortings', 'two pointers', '*2100']
B. Lemmingstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you know, lemmings like jumping. For the next spectacular group jump n lemmings gathered near a high rock with k comfortable ledges on it. The first ledge is situated at the height of h meters, the second one is at the height of 2h meters, and so on (the i-th ledge is at the height of iΒ·h meters). The lemmings are going to jump at sunset, and there's not much time left.Each lemming is characterized by its climbing speed of vi meters per minute and its weight mi. This means that the i-th lemming can climb to the j-th ledge in minutes.To make the jump beautiful, heavier lemmings should jump from higher ledges: if a lemming of weight mi jumps from ledge i, and a lemming of weight mj jumps from ledge j (for i < j), then the inequation mi ≀ mj should be fulfilled.Since there are n lemmings and only k ledges (k ≀ n), the k lemmings that will take part in the jump need to be chosen. The chosen lemmings should be distributed on the ledges from 1 to k, one lemming per ledge. The lemmings are to be arranged in the order of non-decreasing weight with the increasing height of the ledge. In addition, each lemming should have enough time to get to his ledge, that is, the time of his climb should not exceed t minutes. The lemmings climb to their ledges all at the same time and they do not interfere with each other.Find the way to arrange the lemmings' jump so that time t is minimized.InputThe first line contains space-separated integers n, k and h (1 ≀ k ≀ n ≀ 105, 1 ≀ h ≀ 104) β€” the total number of lemmings, the number of ledges and the distance between adjacent ledges.The second line contains n space-separated integers m1, m2, ..., mn (1 ≀ mi ≀ 109), where mi is the weight of i-th lemming.The third line contains n space-separated integers v1, v2, ..., vn (1 ≀ vi ≀ 109), where vi is the speed of i-th lemming.OutputPrint k different numbers from 1 to n β€” the numbers of the lemmings who go to ledges at heights h, 2h, ..., kh, correspondingly, if the jump is organized in an optimal way. If there are multiple ways to select the lemmings, pick any of them.ExamplesInput5 3 21 2 3 2 11 2 1 2 10Output5 2 4Input5 3 103 4 3 2 15 4 3 2 1Output4 3 1NoteLet's consider the first sample case. The fifth lemming (speed 10) gets to the ledge at height 2 in minutes; the second lemming (speed 2) gets to the ledge at height 4 in 2 minutes; the fourth lemming (speed 2) gets to the ledge at height 6 in 3 minutes. All lemmings manage to occupy their positions in 3 minutes.
Input5 3 21 2 3 2 11 2 1 2 10
Output5 2 4
1 second
256 megabytes
['binary search', '*2000']
A. Substring and Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences.The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|.A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≀ a ≀ b ≀ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same.A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≀ p1 < p2 < ... < p|y| ≀ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different.InputThe input consists of two lines. The first of them contains s (1 ≀ |s| ≀ 5000), and the second one contains t (1 ≀ |t| ≀ 5000). Both strings consist of lowercase Latin letters.OutputPrint a single number β€” the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7).ExamplesInputaaaaOutput5InputcodeforcesforceofcodeOutput60NoteLet's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1Β 2]".
Inputaaaa
Output5
2 seconds
256 megabytes
['dp', '*1700']
J. Bracketstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters "+" and "1". For example, sequences "(())()", "()" and "(()(()))" are balanced, while ")(", "(()" and "(()))(" are not.You are given a string which consists of opening and closing round brackets. Check whether it is a balanced bracket sequence.InputThe only line of input contains a string between 1 and 100 characters long, inclusive. Each character in the string will be "(" or ")".OutputOutput "YES" if the bracket sequence is balanced, and "NO" otherwise (quotes for clarity only).ExamplesInput(()(()))()OutputYESInput())()OutputNO
Input(()(()))()
OutputYES
3 seconds
256 megabytes
['*special problem', '*1800']
I. Truncatable primestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA truncatable prime is a prime number which contains no zeros in decimal notation and all its suffixes are primes. 1 is considered to be not a prime.You are given a positive integer n. Figure out whether it is a truncatable prime.InputThe only line of input contains an integer n (2 ≀ n ≀ 107).OutputOutput "YES" if n is a truncatable prime. Output "NO" otherwise. Quotes for clarity only.ExamplesInput19OutputNOInput9137OutputYESNoteIn the first sample 19 is a prime but its suffix 9 is not.In the second sample 9137, 137, 37 and 7 are all primes, so 9137 is a truncatable prime.
Input19
OutputNO
3 seconds
256 megabytes
['*special problem', '*2000']
H. Alternating casetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string consisting of alphabet letters. Convert it to alternating case: the letters on odd positions should be in uppercase, and the letters on even positions should be lowercase. The letters are numbered staring from 1.InputThe only line of input contains a string between 1 and 100 characters long. Each character of the string is either an uppercase ('A'-'Z') or a lowercase ('a'-'z') letter.OutputOutput the resulting string.ExamplesInputCodeforcesOutputCoDeFoRcEsInputVKCupOutputVkCuP
InputCodeforces
OutputCoDeFoRcEs
3 seconds
256 megabytes
['*special problem', '*1800']
G. Non-decimal sumtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers written in base radix. Calculate their sum and output it written in the same base.InputThe first line of the input contains an integer n (1 ≀ n ≀ 10) β€” the size of the array. The second line contains an integer radix (2 ≀ radix ≀ 36) β€” the base of the numeral system used. Next n lines contain the elements of the array, one per line. Each element is a non-negative integer written in radix-based notation, possibly with leading zeros, which contains between 1 and 5 digits, inclusive. The digits of the notation will be 0, 1, ..., 9, A, B, ..., Z in the given order. OutputOutput the sum of array elements in radix-based notation. Use the same format as in the input.ExamplesInput316F020B004Output2FFInput2101234Output46
Input316F020B004
Output2FF
3 seconds
256 megabytes
['*special problem', '*2000']
F. Factorial zerostime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. Output the number of trailing zeros in n! (n! denotes a product of integers between 1 and n, inclusive).InputThe only line of input contains an integer n (1 ≀ n ≀ 1000000).OutputOutput the number of trailing zeros in n!.ExamplesInput6Output1Input24Output4NoteIn the first sample 6! = 720.In the second sample 24! = 620448401733239439360000.
Input6
Output1
3 seconds
256 megabytes
['*special problem', '*1800']
E. HQ9+time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHQ9+ is a joke programming language which has only four one-character instructions: "H" prints "Hello, World!", "Q" prints the whole source code of the program itself (at each call), "9" prints the lyrics of "99 Bottles of Beer" song, "+" increments the value stored in the internal accumulator.Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.InputThe input will consist of a single line p which will give a program in HQ9+. String p will contain between 1 and 100 characters, inclusive. ASCII-code of each character of p will be between 33 (exclamation mark) and 126 (tilde), inclusive.OutputOutput "YES", if executing the program will produce any output, and "NO" otherwise (quotes for clarity only).ExamplesInputHello!OutputYESInputVK_Cup_2012!OutputNONoteIn the first case the program contains only one instruction β€” "H", which prints "Hello, World!".In the second case none of the program characters are language instructions.
InputHello!
OutputYES
3 seconds
256 megabytes
['*special problem', '*1800']
D. Remove digitstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string. Remove all digits from it. When a character is removed from a string, all characters to the right of it are shifted one position to the left.InputThe only line of input contains a string between 1 and 100 characters long. Each character of the string has ASCII-code between 33 (exclamation mark) and 126 (tilde), inclusive.OutputOutput the given string with all digits removed from it. If the original string had only digits, output an empty string.ExamplesInputVK-Cup-2012!OutputVK-Cup-!InputGo,Codeforces!OutputGo,Codeforces!
InputVK-Cup-2012!
OutputVK-Cup-!
3 seconds
256 megabytes
['*special problem', '*1900']
C. Prime factorizationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. Output its prime factorization.If n = a1b1 a2b2 ... akbk (bi > 0), where ak are prime numbers, the output of your program should look as follows: a1*...*a1*a2*...*a2*...*ak*...*ak, where the factors are ordered in non-decreasing order, and each factor ai is printed bi times.InputThe only line of input contains an integer n (2 ≀ n ≀ 10000).OutputOutput the prime factorization of n, as described above.ExamplesInput245Output5*7*7Input19Output19
Input245
Output5*7*7
3 seconds
256 megabytes
['*special problem', '*1800']
B. Binary notationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. Output its binary notation.InputThe only line of input data contains an integer n (1 ≀ n ≀ 106).OutputOutput the binary notation of n (without any leading zeros).ExamplesInput5Output101Input126Output1111110NoteIn the first example 5 = 1 * 22 + 0 * 21 + 1 * 20.
Input5
Output101
3 seconds
256 megabytes
['*special problem', '*1800']
A. Pentagonal numberstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPentagonal numbers are figurate numbers which can be calculated using the formula pn = (3n2 - n) / 2 (always integer). You are given n; calculate n-th pentagonal number.InputThe only line of input contains an integer n (1 ≀ n ≀ 100).OutputOutput the n-th pentagonal number.ExamplesInput2Output5Input5Output35
Input2
Output5
3 seconds
256 megabytes
['*special problem', 'implementation', '*1100']
E. Polycarpus the Safecrackertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has t safes. The password for each safe is a square matrix consisting of decimal digits '0' ... '9' (the sizes of passwords to the safes may vary). Alas, Polycarpus has forgotten all passwords, so now he has to restore them.Polycarpus enjoys prime numbers, so when he chose the matrix passwords, he wrote a prime number in each row of each matrix. To his surprise, he found that all the matrices turned out to be symmetrical (that is, they remain the same after transposition). Now, years later, Polycarp was irritated to find out that he remembers only the prime numbers pi, written in the first lines of the password matrices.For each safe find the number of matrices which can be passwords to it.The number of digits in pi determines the number of rows and columns of the i-th matrix. One prime number can occur in several rows of the password matrix or in several matrices. The prime numbers that are written not in the first row of the matrix may have leading zeros.InputThe first line of the input contains an integer t (1 ≀ t ≀ 30) β€” the number of safes. Next t lines contain integers pi (10 ≀ pi ≀ 99999), pi is a prime number written in the first row of the password matrix for the i-th safe. All pi's are written without leading zeros.OutputPrint t numbers, the i-th of them should be the number of matrices that can be a password to the i-th safe. Print the numbers on separate lines.ExamplesInput4112394019001Output428612834NoteHere is a possible password matrix for the second safe: 239307977Here is a possible password matrix for the fourth safe: 9001000200021223
Input4112394019001
Output428612834
3 seconds
256 megabytes
['brute force', 'dp', '*2500']
D. Distance in Treetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA tree is a connected graph that doesn't contain any cycles.The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.InputThe first line contains two integers n and k (1 ≀ n ≀ 50000, 1 ≀ k ≀ 500) β€” the number of vertices and the required distance between the vertices.Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≀ ai, bi ≀ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.OutputPrint a single integer β€” the number of distinct pairs of the tree's vertices which have a distance of exactly k between them.Please do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.ExamplesInput5 21 22 33 42 5Output4Input5 31 22 33 44 5Output2NoteIn the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).
Input5 21 22 33 42 5
Output4
3 seconds
512 megabytes
['dfs and similar', 'dp', 'trees', '*1800']
C. Abracadabratime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm: On the first step the string consists of a single character "a". On the k-th step Polycarpus concatenates two copies of the string obtained on the (k - 1)-th step, while inserting the k-th character of the alphabet between them. Polycarpus uses the alphabet that consists of lowercase Latin letters and digits (a total of 36 characters). The alphabet characters are numbered like this: the 1-st character is "a", the 2-nd β€” "b", ..., the 26-th β€” "z", the 27-th β€” "0", the 28-th β€” "1", ..., the 36-th β€” "9". Let's have a closer look at the algorithm. On the second step Polycarpus will concatenate two strings "a" and insert the character "b" between them, resulting in "aba" string. The third step will transform it into "abacaba", and the fourth one - into "abacabadabacaba". Thus, the string constructed on the k-th step will consist of 2k - 1 characters. Polycarpus wrote down the string he got after 30 steps of the given algorithm and chose two non-empty substrings of it. Your task is to find the length of the longest common substring of the two substrings selected by Polycarpus.A substring s[i... j] (1 ≀ i ≀ j ≀ |s|) of string s = s1s2... s|s| is a string sisi + 1... sj. For example, substring s[2...4] of string s = "abacaba" equals "bac". The string is its own substring.The longest common substring of two strings s and t is the longest string that is a substring of both s and t. For example, the longest common substring of "contest" and "systemtesting" is string "test". There can be several common substrings of maximum length.InputThe input consists of a single line containing four integers l1, r1, l2, r2 (1 ≀ li ≀ ri ≀ 109, i = 1, 2). The numbers are separated by single spaces. li and ri give the indices of the first and the last characters of the i-th chosen substring, correspondingly (i = 1, 2). The characters of string abracadabra are numbered starting from 1.OutputPrint a single number β€” the length of the longest common substring of the given strings. If there are no common substrings, print 0.ExamplesInput3 6 1 4Output2Input1 1 4 4Output0NoteIn the first sample the first substring is "acab", the second one is "abac". These two substrings have two longest common substrings "ac" and "ab", but we are only interested in their length β€” 2.In the second sample the first substring is "a", the second one is "c". These two substrings don't have any common characters, so the length of their longest common substring is 0.
Input3 6 1 4
Output2
1 second
256 megabytes
['divide and conquer', '*2400']
B. Discountstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!Polycarpus has k carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.Polycarpus must use all k carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.InputThe first input line contains two integers n and k (1 ≀ k ≀ n ≀ 103) β€” the number of items in the supermarket and the number of carts, correspondingly. Next n lines describe the items as "ci ti" (without the quotes), where ci (1 ≀ ci ≀ 109) is an integer denoting the price of the i-th item, ti (1 ≀ ti ≀ 2) is an integer representing the type of item i (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.OutputIn the first line print a single real number with exactly one decimal place β€” the minimum total price of the items, including the discounts.In the following k lines print the descriptions of the items in the carts. In the i-th line print the description of the i-th cart as "t b1 b2 ... bt" (without the quotes), where t is the number of items in the i-th cart, and the sequence b1, b2, ..., bt (1 ≀ bj ≀ n) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to n in the order in which they are specified in the input.If there are multiple optimal distributions, you are allowed to print any of them.ExamplesInput3 22 13 23 1Output5.52 1 21 3Input4 34 11 22 23 2Output8.01 12 4 21 3NoteIn the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2Β·0.5 + (3 + 3Β·0.5) = 1 + 4.5 = 5.5.
Input3 22 13 23 1
Output5.52 1 21 3
3 seconds
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*1700']
A. Dress'em in Vests!time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.The Two-dimensional kingdom has a regular army of n people. Each soldier registered himself and indicated the desired size of the bulletproof vest: the i-th soldier indicated size ai. The soldiers are known to be unpretentious, so the command staff assumes that the soldiers are comfortable in any vests with sizes from ai - x to ai + y, inclusive (numbers x, y β‰₯ 0 are specified). The Two-dimensional kingdom has m vests at its disposal, the j-th vest's size equals bj. Help mobilize the Two-dimensional kingdom's army: equip with vests as many soldiers as possible. Each vest can be used only once. The i-th soldier can put on the j-th vest, if ai - x ≀ bj ≀ ai + y.InputThe first input line contains four integers n, m, x and y (1 ≀ n, m ≀ 105, 0 ≀ x, y ≀ 109) β€” the number of soldiers, the number of vests and two numbers that specify the soldiers' unpretentiousness, correspondingly.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109) in non-decreasing order, separated by single spaces β€” the desired sizes of vests. The third line contains m integers b1, b2, ..., bm (1 ≀ bj ≀ 109) in non-decreasing order, separated by single spaces β€” the sizes of the available vests.OutputIn the first line print a single integer k β€” the maximum number of soldiers equipped with bulletproof vests. In the next k lines print k pairs, one pair per line, as "ui vi" (without the quotes). Pair (ui, vi) means that soldier number ui must wear vest number vi. Soldiers and vests are numbered starting from one in the order in which they are specified in the input. All numbers of soldiers in the pairs should be pairwise different, all numbers of vests in the pairs also should be pairwise different. You can print the pairs in any order.If there are multiple optimal answers, you are allowed to print any of them.ExamplesInput5 3 0 01 2 3 3 41 3 5Output21 13 2Input3 3 2 21 5 93 5 7Output31 12 23 3NoteIn the first sample you need the vests' sizes to match perfectly: the first soldier gets the first vest (size 1), the third soldier gets the second vest (size 3). This sample allows another answer, which gives the second vest to the fourth soldier instead of the third one.In the second sample the vest size can differ from the desired size by at most 2 sizes, so all soldiers can be equipped.
Input5 3 0 01 2 3 3 41 3 5
Output21 13 2
3 seconds
256 megabytes
['binary search', 'brute force', 'greedy', 'two pointers', '*1300']
E. Buses and Peopletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe main Bertown street is represented by a straight line. There are 109 bus stops located on the line. The stops are numbered with integers from 1 to 109 in the order in which they follow on the road. The city has n buses. Every day the i-th bus drives from stop number si to stop number fi (si < fi), it stops on all intermediate stops and returns only at night. The bus starts driving at time ti and drives so fast that it finishes driving also at time ti. The time ti is different for all buses. The buses have infinite capacity.Bertown has m citizens. Today the i-th person should get from stop number li to stop number ri (li < ri); the i-th citizen comes to his initial stop (li) at time bi. Each person, on the one hand, wants to get to the destination point as quickly as possible, and on the other hand, definitely does not want to change the buses as he rides. More formally: the i-th person chooses bus j, with minimum time tj, such that sj ≀ li, ri ≀ fj and bi ≀ tj. Your task is to determine for each citizen whether he can ride to the destination point today and if he can, find the number of the bus on which the citizen will ride.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 105) β€” the number of buses and the number of people. Then n lines follow, each of them contains three integers: si, fi, ti (1 ≀ si, fi, ti ≀ 109, si < fi) β€” the description of the buses. It is guaranteed that all ti-s are different.Then m lines follow, each of them contains three integers: li, ri, bi (1 ≀ li, ri, bi ≀ 109, li < ri) β€” the Bertown citizens' description. Some bi-s could coincide.OutputIn the first line print m space-separated integers: the i-th number should be equal either to -1, if the person number i can't get to the destination point, or to the number of the bus that will ride the person number i. The buses are numbered with integers from 1 to n in the input order.ExamplesInput4 31 10 105 6 26 7 35 7 45 7 11 2 11 10 11Output4 1 -1Input1 11 1000000000 10000000001 1000000000 1000000000Output1
Input4 31 10 105 6 26 7 35 7 45 7 11 2 11 10 11
Output4 1 -1
1 second
256 megabytes
['binary search', 'data structures', 'sortings', '*2400']
D. Edges in MSTtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the given tree contains. The minimum spanning tree (MST) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique.Your task is to determine the following for each edge of the given graph: whether it is either included in any MST, or included at least in one MST, or not included in any MST.InputThe first line contains two integers n and m (2 ≀ n ≀ 105, ) β€” the number of the graph's vertexes and edges, correspondingly. Then follow m lines, each of them contains three integers β€” the description of the graph's edges as "ai bi wi" (1 ≀ ai, bi ≀ n, 1 ≀ wi ≀ 106, ai ≠ bi), where ai and bi are the numbers of vertexes connected by the i-th edge, wi is the edge's weight. It is guaranteed that the graph is connected and doesn't contain loops or multiple edges.OutputPrint m lines β€” the answers for all edges. If the i-th edge is included in any MST, print "any"; if the i-th edge is included at least in one MST, print "at least one"; if the i-th edge isn't included in any MST, print "none". Print the answers for the edges in the order in which the edges are specified in the input.ExamplesInput4 51 2 1011 3 1002 3 22 4 23 4 1Outputnoneanyat least oneat least oneanyInput3 31 2 12 3 11 3 2OutputanyanynoneInput3 31 2 12 3 11 3 1Outputat least oneat least oneat least oneNoteIn the second sample the MST is unique for the given graph: it contains two first edges.In the third sample any two edges form the MST for the given graph. That means that each edge is included at least in one MST.
Input4 51 2 1011 3 1002 3 22 4 23 4 1
Outputnoneanyat least oneat least oneany
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'sortings', '*2300']
C. Find Pairtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got another problem dealing with arrays. Let's consider an arbitrary sequence containing n (not necessarily different) integers a1, a2, ..., an. We are interested in all possible pairs of numbers (ai, aj), (1 ≀ i, j ≀ n). In other words, let's consider all n2 pairs of numbers, picked from the given array.For example, in sequence a = {3, 1, 5} are 9 pairs of numbers: (3, 3), (3, 1), (3, 5), (1, 3), (1, 1), (1, 5), (5, 3), (5, 1), (5, 5).Let's sort all resulting pairs lexicographically by non-decreasing. Let us remind you that pair (p1, q1) is lexicographically less than pair (p2, q2) only if either p1 < p2, or p1 = p2 and q1 < q2.Then the sequence, mentioned above, will be sorted like that: (1, 1), (1, 3), (1, 5), (3, 1), (3, 3), (3, 5), (5, 1), (5, 3), (5, 5)Let's number all the pair in the sorted list from 1 to n2. Your task is formulated like this: you should find the k-th pair in the ordered list of all possible pairs of the array you've been given.InputThe first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ n2). The second line contains the array containing n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109). The numbers in the array can coincide. All numbers are separated with spaces.Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout, streams or the %I64d specificator instead.OutputIn the single line print two numbers β€” the sought k-th pair.ExamplesInput2 42 1Output2 2Input3 23 1 5Output1 3NoteIn the first sample the sorted sequence for the given array looks as: (1, 1), (1, 2), (2, 1), (2, 2). The 4-th of them is pair (2, 2).The sorted sequence for the array from the second sample is given in the statement. The 2-nd pair there is (1, 3).
Input2 42 1
Output2 2
1 second
256 megabytes
['implementation', 'math', 'sortings', '*1700']
B. Unlucky Tickettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half.But of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following unluckiness criterion that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is strictly less than the corresponding digit from the second one or each digit from the first half is strictly more than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such bijective correspondence between the digits of the first and the second half of the ticket, that either each digit of the first half turns out strictly less than the corresponding digit of the second half or each digit of the first half turns out strictly more than the corresponding digit from the second half.For example, ticket 2421 meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is 2 > 1 and 4 > 2), ticket 0135 also meets the criterion (the sought correspondence is 0 < 3 and 1 < 5), and ticket 3754 does not meet the criterion. You have a ticket in your hands, it contains 2n digits. Your task is to check whether it meets the unluckiness criterion.InputThe first line contains an integer n (1 ≀ n ≀ 100). The second line contains a string that consists of 2n digits and defines your ticket.OutputIn the first line print "YES" if the ticket meets the unluckiness criterion. Otherwise, print "NO" (without the quotes).ExamplesInput22421OutputYESInput20135OutputYESInput23754OutputNO
Input22421
OutputYES
2 seconds
256 megabytes
['greedy', 'sortings', '*1100']
A. Twinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. "But why split the money equally?" β€” you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.InputThe first line contains integer n (1 ≀ n ≀ 100) β€” the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1 ≀ ai ≀ 100) β€” the coins' values. All numbers are separated with spaces.OutputIn the single line print the single number β€” the minimum needed number of coins.ExamplesInput23 3Output2Input32 1 2Output2NoteIn the first sample you will have to take 2 coins (you and your twin have sums equal to 6, 0 correspondingly). If you take 1 coin, you get sums 3, 3. If you take 0 coins, you get sums 0, 6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.In the second sample one coin isn't enough for us, too. You can pick coins with values 1, 2 or 2, 2. In any case, the minimum number of coins equals 2.
Input23 3
Output2
2 seconds
256 megabytes
['greedy', 'sortings', '*900']
E. Zebra Towertime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters β€” color ci and size si. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower. A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.InputThe first line contains an integer n (2 ≀ n ≀ 105) β€” the number of cubes. Next n lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers ci and si (1 ≀ ci, si ≀ 109) β€” the i-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.OutputPrint the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to n in the order in which they were given in the input.If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInput41 21 32 43 3Output932 3 1 Input21 12 1Output222 1
Input41 21 32 43 3
Output932 3 1
1.5 seconds
256 megabytes
['*special problem', 'data structures', 'greedy', 'sortings', '*1700']
D. Palindrome pairstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 ≀ a ≀ b < x ≀ y ≀ |s| and substrings s[a... b], s[x... y] are palindromes.A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes.A substring s[i... j] (1 ≀ i ≀ j ≀ |s|) of string s = s1s2... s|s| is a string sisi + 1... sj. For example, substring s[2...4] of string s = "abacaba" equals "bac".InputThe first line of input contains a non-empty string s which consists of lowercase letters ('a'...'z'), s contains at most 2000 characters.OutputOutput a single number β€” the quantity of pairs of non-overlapping palindromic substrings of s.Please do not use the %lld format specifier to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d format specifier.ExamplesInputaaOutput1InputaaaOutput5InputabacabaOutput36
Inputaa
Output1
3 seconds
256 megabytes
['*special problem', 'brute force', 'dp', 'strings', '*1500']
C. String Manipulation 1.0time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name s, a user can pick number p and character c and delete the p-th occurrence of character c from the name. After the user changed his name, he can't undo the change.For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc". Polycarpus learned that some user initially registered under nickname t, where t is a concatenation of k copies of string s. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name.InputThe first line contains an integer k (1 ≀ k ≀ 2000). The second line contains a non-empty string s, consisting of lowercase Latin letters, at most 100 characters long. The third line contains an integer n (0 ≀ n ≀ 20000) β€” the number of username changes. Each of the next n lines contains the actual changes, one per line. The changes are written as "pi ci" (without the quotes), where pi (1 ≀ pi ≀ 200000) is the number of occurrences of letter ci, ci is a lowercase Latin letter. It is guaranteed that the operations are correct, that is, the letter to be deleted always exists, and after all operations not all letters are deleted from the name. The letters' occurrences are numbered starting from 1.OutputPrint a single string β€” the user's final name after all changes are applied to it.ExamplesInput2bac32 a1 b2 cOutputacbInput1abacaba41 a1 a1 c2 bOutputbaaNoteLet's consider the first sample. Initially we have name "bacbac"; the first operation transforms it into "bacbc", the second one β€” to "acbc", and finally, the third one transforms it into "acb".
Input2bac32 a1 b2 c
Outputacb
3 seconds
256 megabytes
['*special problem', 'binary search', 'brute force', 'data structures', 'strings', '*1400']
B. Matchmakertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj = xi.Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.InputThe first input line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of markers and the number of caps, correspondingly. Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1 ≀ xi, yi ≀ 1000) β€” the i-th marker's color and diameter, correspondingly.Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1 ≀ aj, bj ≀ 1000) β€” the color and diameter of the j-th cap, correspondingly.OutputPrint two space-separated integers u, v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.ExamplesInput3 41 23 42 45 42 41 11 2Output3 2Input2 21 22 13 45 1Output1 0NoteIn the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed β€” the first and the third markers.
Input3 41 23 42 45 42 41 11 2
Output3 2
3 seconds
256 megabytes
['*special problem', 'greedy', 'sortings', '*1100']
A. Friends or Nottime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has a hobby β€” he develops an unusual social network. His work is almost completed, and there is only one more module to implement β€” the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that user A sent user B a message at time t1, and user B sent user A a message at time t2. If 0 < t2 - t1 ≀ d, then user B's message was an answer to user A's one. Users A and B are considered to be friends if A answered at least one B's message or B answered at least one A's message.You are given the log of messages in chronological order and a number d. Find all pairs of users who will be considered to be friends.InputThe first line of the input contains two integers n and d (1 ≀ n, d ≀ 1000). The next n lines contain the messages log. The i-th line contains one line of the log formatted as "Ai Bi ti" (without the quotes), which means that user Ai sent a message to user Bi at time ti (1 ≀ i ≀ n). Ai and Bi are non-empty strings at most 20 characters long, consisting of lowercase letters ('a' ... 'z'), and ti is an integer (0 ≀ ti ≀ 10000). It is guaranteed that the lines are given in non-decreasing order of ti's and that no user sent a message to himself. The elements in the lines are separated by single spaces.OutputIn the first line print integer k β€” the number of pairs of friends. In the next k lines print pairs of friends as "Ai Bi" (without the quotes). You can print users in pairs and the pairs themselves in any order. Each pair must be printed exactly once.ExamplesInput4 1vasya petya 1petya vasya 2anya ivan 2ivan anya 4Output1petya vasyaInput1 1000a b 0Output0NoteIn the first sample test case Vasya and Petya are friends because their messages' sending times are one second apart. Anya and Ivan are not, because their messages' sending times differ by more than one second.
Input4 1vasya petya 1petya vasya 2anya ivan 2ivan anya 4
Output1petya vasya
3 seconds
256 megabytes
['*special problem', 'greedy', 'implementation', '*1400']
E. Phone Talkstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has n calls planned. For each call we know the moment ti (in seconds since the start of the day) when it is scheduled to start and its duration di (in seconds). All ti are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second t, and the call continues for d seconds, then Mr. Jackson is busy at seconds t, t + 1, ..., t + d - 1, and he can start a new call at second t + d. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most k calls. Note that a call which comes while he is busy talking can be ignored as well.What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.InputThe first input line contains a pair of integers n, k (0 ≀ k ≀ n ≀ 4000) separated by a space. Following n lines contain the description of calls for today. The description of each call is located on the single line and consists of two space-separated integers ti and di, (1 ≀ ti, di ≀ 86400). All ti are distinct, the calls are given in the order of strict increasing ti.Scheduled times of calls [ti, ti + di - 1] can arbitrarily intersect.OutputPrint a number from 0 to 86400, inclusive β€” the maximally possible number of seconds for Mr. Jackson to sleep today.ExamplesInput3 230000 1500040000 1500050000 15000Output49999Input5 11 2000010000 1000020000 2000025000 1000080000 60000Output39999NoteIn the first sample the most convenient way is to ignore the first two calls.In the second sample it is best to ignore the third call. In this case Mr. Jackson will have been speaking: first call: from 1-st to 20000-th second, second call: from 20001-st to 30000-th second, fourth call: from 30001-st to 40000-th second (the third call is ignored), fifth call: from 80000-th to 139999-th second. Thus, the longest period of free time is from the 40001-th to the 79999-th second.
Input3 230000 1500040000 1500050000 15000
Output49999
3 seconds
256 megabytes
['*special problem', 'dp', 'sortings', '*1900']
D. Ice Sculpturestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti β€” the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that: the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n), the sum of the ti values of the remaining sculptures is maximized. Help the Vice Rector to analyze the criticism β€” find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.InputThe first input line contains an integer n (3 ≀ n ≀ 20000) β€” the initial number of sculptures. The second line contains a sequence of integers t1, t2, ..., tn, ti β€” the degree of the i-th sculpture's attractiveness ( - 1000 ≀ ti ≀ 1000). The numbers on the line are separated by spaces.OutputPrint the required maximum sum of the sculptures' attractiveness.ExamplesInput81 2 -3 4 -5 5 2 3Output14Input61 -2 3 -4 5 -6Output9Input61 2 3 4 5 6Output21NoteIn the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 ΠΈ 3.
Input81 2 -3 4 -5 5 2 3
Output14
3 seconds
256 megabytes
['*special problem', 'brute force', 'number theory', '*1300']
C. Cd and pwd commandstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name β€” a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory β€” the one that contains the given directory. It is denoted as "..".The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. Β«..Β» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.The command pwd should display the absolute path to the current directory. This path must not contain "..".Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.InputThe first line of the input data contains the single integer n (1 ≀ n ≀ 50) β€” the number of commands.Then follow n lines, each contains one command. Each of these lines contains either command pwd, or command cd, followed by a space-separated non-empty parameter.The command parameter cd only contains lower case Latin letters, slashes and dots, two slashes cannot go consecutively, dots occur only as the name of a parent pseudo-directory. The command parameter cd does not end with a slash, except when it is the only symbol that points to the root directory. The command parameter has a length from 1 to 200 characters, inclusive.Directories in the file system can have the same names.OutputFor each command pwd you should print the full absolute path of the given directory, ending with a slash. It should start with a slash and contain the list of slash-separated directories in the order of being nested from the root to the current folder. It should contain no dots.ExamplesInput7pwdcd /home/vasyapwdcd ..pwdcd vasya/../petyapwdOutput//home/vasya//home//home/petya/Input4cd /a/bpwdcd ../a/bpwdOutput/a/b//a/a/b/
Input7pwdcd /home/vasyapwdcd ..pwdcd vasya/../petyapwd
Output//home/vasya//home//home/petya/
3 seconds
256 megabytes
['*special problem', 'data structures', 'implementation', '*1400']
B. Taxitime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≀ si ≀ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≀ si ≀ 4). The integers are separated by a space, si is the number of children in the i-th group.OutputPrint the single number β€” the minimum number of taxis necessary to drive all children to Polycarpus.ExamplesInput51 2 4 3 3Output4Input82 3 4 4 2 1 3 1Output5NoteIn the first test we can sort the children into four cars like this: the third group (consisting of four children), the fourth group (consisting of three children), the fifth group (consisting of three children), the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars.
Input51 2 4 3 3
Output4
3 seconds
256 megabytes
['*special problem', 'greedy', 'implementation', '*1100']
A. Next Roundtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules.A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many participants will advance to the next round.InputThe first line of the input contains two integers n and k (1 ≀ k ≀ n ≀ 50) separated by a single space.The second line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 100), where ai is the score earned by the participant who got the i-th place. The given sequence is non-increasing (that is, for all i from 1 to n - 1 the following condition is fulfilled: ai β‰₯ ai + 1).OutputOutput the number of participants who advance to the next round.ExamplesInput8 510 9 8 7 7 7 5 5Output6Input4 20 0 0 0Output0NoteIn the first example the participant on the 5th place earned 7 points. As the participant on the 6th place also earned 7 points, there are 6 advancers.In the second example nobody got a positive score.
Input8 510 9 8 7 7 7 5 5
Output6
3 seconds
256 megabytes
['*special problem', 'implementation', '*800']
B. Tracetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides, any two neighboring parts were painted different colors, that is, the red and the blue color were alternating, i. e. followed one after the other. The outer area of the wall (the area that lied outside all circles) was painted blue. Help Sherlock Holmes determine the total area of red parts of the wall.Let us remind you that two circles are called concentric if their centers coincide. Several circles are called concentric if any two of them are concentric.InputThe first line contains the single integer n (1 ≀ n ≀ 100). The second line contains n space-separated integers ri (1 ≀ ri ≀ 1000) β€” the circles' radii. It is guaranteed that all circles are different.OutputPrint the single real number β€” total area of the part of the wall that is painted red. The answer is accepted if absolute or relative error doesn't exceed 10 - 4.ExamplesInput11Output3.1415926536Input31 4 2Output40.8407044967NoteIn the first sample the picture is just one circle of radius 1. Inner part of the circle is painted red. The area of the red part equals π × 12 = π.In the second sample there are three circles of radii 1, 4 and 2. Outside part of the second circle is painted blue. Part between the second and the third circles is painted red. Part between the first and the third is painted blue. And, finally, the inner part of the first circle is painted red. Overall there are two red parts: the ring between the second and the third circles and the inner part of the first circle. Total area of the red parts is equal (π × 42 - π × 22) + π × 12 = π × 12 + π = 13Ο€
Input11
Output3.1415926536
2 seconds
256 megabytes
['geometry', 'sortings', '*1000']