problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
βŒ€
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
A. Game Outcometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8 + 3 + 6 + 7 = 24, sum of its row numbers equals 9 + 5 + 3 + 2 = 19, and 24 > 19.InputThe first line contains an integer n (1 ≀ n ≀ 30). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.OutputPrint the single number β€” the number of the winning squares.ExamplesInput11Output0Input21 23 4Output2Input45 7 8 49 5 3 21 6 6 49 5 7 3Output6NoteIn the first example two upper squares are winning.In the third example three left squares in the both middle rows are winning:5 7 8 49 5 3 21 6 6 49 5 7 3
Input11
Output0
2 seconds
256 megabytes
['brute force', '*800']
E. Mrs. Hudson's Pancakestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMrs. Hudson hasn't made her famous pancakes for quite a while and finally she decided to make them again. She has learned m new recipes recently and she can't wait to try them. Those recipes are based on n special spices. Mrs. Hudson has these spices in the kitchen lying in jars numbered with integers from 0 to n - 1 (each spice lies in an individual jar). Each jar also has the price of the corresponding spice inscribed β€” some integer ai.We know three values for the i-th pancake recipe: di, si, ci. Here di and ci are integers, and si is the pattern of some integer written in the numeral system with radix di. The pattern contains digits, Latin letters (to denote digits larger than nine) and question marks. Number x in the di-base numeral system matches the pattern si, if we can replace question marks in the pattern with digits and letters so that we obtain number x (leading zeroes aren't taken into consideration when performing the comparison). More formally: each question mark should be replaced by exactly one digit or exactly one letter. If after we replace all question marks we get a number with leading zeroes, we can delete these zeroes. For example, number 40A9875 in the 11-base numeral system matches the pattern "??4??987?", and number 4A9875 does not.To make the pancakes by the i-th recipe, Mrs. Hudson should take all jars with numbers whose representation in the di-base numeral system matches the pattern si. The control number of the recipe (zi) is defined as the sum of number ci and the product of prices of all taken jars. More formally: (where j is all such numbers whose representation in the di-base numeral system matches the pattern si).Mrs. Hudson isn't as interested in the control numbers as she is in their minimum prime divisors. Your task is: for each recipe i find the minimum prime divisor of number zi. If this divisor exceeds 100, then you do not have to find it, print -1.InputThe first line contains the single integer n (1 ≀ n ≀ 104). The second line contains space-separated prices of the spices a0, a1, ..., an - 1, where ai is an integer (1 ≀ ai ≀ 1018).The third line contains the single integer m (1 ≀ m ≀ 3Β·104) β€” the number of recipes Mrs. Hudson has learned. Next m lines describe the recipes, one per line. First you are given an integer di, written in the decimal numeral system (2 ≀ di ≀ 16). Then after a space follows the si pattern β€” a string from 1 to 30 in length, inclusive, consisting of digits from "0" to "9", letters from "A" to "F" and signs "?". Letters from "A" to "F" should be considered as digits from 10 to 15 correspondingly. It is guaranteed that all digits of the pattern (including the digits that are represented by letters) are strictly less than di. Then after a space follows an integer ci, written in the decimal numeral system (1 ≀ ci ≀ 1018).Please do not use the %lld specificator to read or write 64-bit integers in Π‘++, in is preferred to use cin, cout, strings or the %I64d specificator instead.OutputFor each recipe count by what minimum prime number the control number is divided and print this prime number on the single line. If this number turns out larger than 100, print -1.ExamplesInput1112 ? 1Output2Input42 3 5 742 ?0 112 ?1 132 0? 172 1? 19Output32232Input11000000000000000000116 ?????????????? 1Output-1NoteIn the first test any one-digit number in the binary system matches. The jar is only one and its price is equal to 1, the number c is also equal to 1, the control number equals 2. The minimal prime divisor of 2 is 2.In the second test there are 4 jars with numbers from 0 to 3, and the prices are equal 2, 3, 5 and 7 correspondingly β€” the first four prime numbers. In all recipes numbers should be two-digit. In the first recipe the second digit always is 0, in the second recipe the second digit always is 1, in the third recipe the first digit must be 0, in the fourth recipe the first digit always is 1. Consequently, the control numbers ​​are as follows: in the first recipe 2 × 5 + 11 = 21 (the minimum prime divisor is 3), in the second recipe 3 × 7 + 13 = 44 (the minimum prime divisor is 2), in the third recipe 2 × 3 + 17 = 23 (the minimum prime divisor is 23) and, finally, in the fourth recipe 5 × 7 + 19 = 54 (the minimum prime divisor is 2).In the third test, the number should consist of fourteen digits and be recorded in a sixteen-base numeral system. Number 0 (the number of the single bottles) matches, the control number will be equal to 1018 + 1. The minimum prime divisor of this number is equal to 101 and you should print -1.
Input1112 ? 1
Output2
5 seconds
256 megabytes
['brute force', 'dp', '*3000']
D. Cluestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues.Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B. Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T.Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way. As the number of different ways can turn out rather big, print it modulo k.InputThe first line contains three space-separated integers n, m, k (1 ≀ n ≀ 105, 0 ≀ m ≀ 105, 1 ≀ k ≀ 109) β€” the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation.Each of next m lines contains two integers a and b (1 ≀ a, b ≀ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual.OutputPrint the single number β€” the answer to the problem modulo k.ExamplesInput2 0 1000000000Output1Input3 0 100Output3Input4 1 10000000001 4Output8NoteThe first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link.The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime β€” there are 3 ways to do it.The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime.
Input2 0 1000000000
Output1
2 seconds
256 megabytes
['combinatorics', 'graphs', '*2500']
C. Ciphertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSherlock Holmes found a mysterious correspondence of two VIPs and made up his mind to read it. But there is a problem! The correspondence turned out to be encrypted. The detective tried really hard to decipher the correspondence, but he couldn't understand anything. At last, after some thought, he thought of something. Let's say there is a word s, consisting of |s| lowercase Latin letters. Then for one operation you can choose a certain position p (1 ≀ p < |s|) and perform one of the following actions: either replace letter sp with the one that alphabetically follows it and replace letter sp + 1 with the one that alphabetically precedes it; or replace letter sp with the one that alphabetically precedes it and replace letter sp + 1 with the one that alphabetically follows it. Let us note that letter "z" doesn't have a defined following letter and letter "a" doesn't have a defined preceding letter. That's why the corresponding changes are not acceptable. If the operation requires performing at least one unacceptable change, then such operation cannot be performed.Two words coincide in their meaning iff one of them can be transformed into the other one as a result of zero or more operations.Sherlock Holmes needs to learn to quickly determine the following for each word: how many words can exist that coincide in their meaning with the given word, but differs from the given word in at least one character? Count this number for him modulo 1000000007 (109 + 7).InputThe input data contains several tests. The first line contains the only integer t (1 ≀ t ≀ 104) β€” the number of tests.Next t lines contain the words, one per line. Each word consists of lowercase Latin letters and has length from 1 to 100, inclusive. Lengths of words can differ.OutputFor each word you should print the number of different other words that coincide with it in their meaning β€” not from the words listed in the input data, but from all possible words. As the sought number can be very large, print its value modulo 1000000007 (109 + 7).ExamplesInput1abOutput1Input1aaaaaaaaaaaOutput0Input2yaklmbfxzbOutput24320092793NoteSome explanations about the operation: Note that for each letter, we can clearly define the letter that follows it. Letter "b" alphabetically follows letter "a", letter "c" follows letter "b", ..., "z" follows letter "y". Preceding letters are defined in the similar manner: letter "y" precedes letter "z", ..., "a" precedes letter "b". Note that the operation never changes a word's length. In the first sample you can obtain the only other word "ba". In the second sample you cannot obtain any other word, so the correct answer is 0.Consider the third sample. One operation can transform word "klmbfxzb" into word "klmcexzb": we should choose p = 4, and replace the fourth letter with the following one ("b"  →  "c"), and the fifth one β€” with the preceding one ("f"  →  "e"). Also, we can obtain many other words from this one. An operation can transform word "ya" only into one other word "xb". Word "ya" coincides in its meaning with words "xb", "wc", "vd", ..., "ay" (overall there are 24 other words). The word "klmbfxzb has many more variants β€” there are 3320092814 other words that coincide with in the meaning. So the answer for the first word equals 24 and for the second one equals 320092793 β€” the number 3320092814 modulo 109 + 7
Input1ab
Output1
2 seconds
256 megabytes
['combinatorics', 'dp', '*2000']
B. Suspectstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs Sherlock Holmes was investigating a crime, he identified n suspects. He knows for sure that exactly one of them committed the crime. To find out which one did it, the detective lines up the suspects and numbered them from 1 to n. After that, he asked each one: "Which one committed the crime?". Suspect number i answered either "The crime was committed by suspect number ai", or "Suspect number ai didn't commit the crime". Also, the suspect could say so about himself (ai = i).Sherlock Holmes understood for sure that exactly m answers were the truth and all other answers were a lie. Now help him understand this: which suspect lied and which one told the truth?InputThe first line contains two integers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ n) β€” the total number of suspects and the number of suspects who told the truth. Next n lines contain the suspects' answers. The i-th line contains either "+ai" (without the quotes), if the suspect number i says that the crime was committed by suspect number ai, or "-ai" (without the quotes), if the suspect number i says that the suspect number ai didn't commit the crime (ai is an integer, 1 ≀ ai ≀ n).It is guaranteed that at least one suspect exists, such that if he committed the crime, then exactly m people told the truth.OutputPrint n lines. Line number i should contain "Truth" if suspect number i has told the truth for sure. Print "Lie" if the suspect number i lied for sure and print "Not defined" if he could lie and could tell the truth, too, depending on who committed the crime.ExamplesInput1 1+1OutputTruthInput3 2-1-2-3OutputNot definedNot definedNot definedInput4 1+2-3+4-1OutputLieNot definedLieNot definedNoteThe first sample has the single person and he confesses to the crime, and Sherlock Holmes knows that one person is telling the truth. That means that this person is telling the truth.In the second sample there are three suspects and each one denies his guilt. Sherlock Holmes knows that only two of them are telling the truth. Any one of them can be the criminal, so we don't know for any of them, whether this person is telling the truth or not.In the third sample the second and the fourth suspect defend the first and the third one. But only one is telling the truth, thus, the first or the third one is the criminal. Both of them can be criminals, so the second and the fourth one can either be lying or telling the truth. The first and the third one are lying for sure as they are blaming the second and the fourth one.
Input1 1+1
OutputTruth
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'implementation', '*1600']
A. Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: Insert one letter to any end of the string. Delete one letter from any end of the string. Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.InputThe first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.OutputPrint the only integer β€” the minimum number of changes that Dr. Moriarty has to make with the string that you choose.ExamplesInputaaaaaaaaOutput0InputabcabcbcdOutput1InputabcdefklmnopqOutput7NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
Inputaaaaaaaa
Output0
2 seconds
256 megabytes
['brute force', '*1700']
B. Combinationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?InputThe first line contains a single integer n (1 ≀ n ≀ 1000) β€” the number of cards Ilya has.Each of the next n lines contains two non-negative space-separated integers β€” ai and bi (0 ≀ ai, bi ≀ 104) β€” the numbers, written at the top and the bottom of the i-th card correspondingly.OutputPrint the single number β€” the maximum number of points you can score in one round by the described rules.ExamplesInput21 02 0Output2Input31 02 00 2Output3NoteIn the first sample none of two cards brings extra moves, so you should play the one that will bring more points.In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards.
Input21 02 0
Output2
2 seconds
256 megabytes
['greedy', 'sortings', '*1100']
A. I_love_%username%time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number β€” the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.InputThe first line contains the single integer n (1 ≀ n ≀ 1000) β€” the number of contests where the coder participated.The next line contains n space-separated non-negative integer numbers β€” they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.OutputPrint the single number β€” the number of amazing performances the coder has had during his whole history of participating in the contests.ExamplesInput5100 50 200 150 200Output2Input104664 6496 5814 7010 5762 5736 6944 4850 3698 7242Output4NoteIn the first sample the performances number 2 and 3 are amazing.In the second sample the performances number 2, 4, 9 and 10 are amazing.
Input5100 50 200 150 200
Output2
2 seconds
256 megabytes
['brute force', '*800']
E. Martian Colonytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe first ship with the Earth settlers landed on Mars. The colonists managed to build n necessary structures on the surface of the planet (which can be regarded as a plane, and the construction can be regarded as points on it). But one day the scanners recorded suspicious activity on the outskirts of the colony. It was decided to use the protective force field generating system to protect the colony against possible trouble.The system works as follows: the surface contains a number of generators of the field (they can also be considered as points). The active range of each generator is a circle of radius r centered at the location of the generator (the boundary of the circle is also included in the range). After the system is activated, it stretches the protective force field only over the part of the surface, which is within the area of all generators' activity. That is, the protected part is the intersection of the generators' active ranges.The number of generators available to the colonists is not limited, but the system of field generation consumes a lot of energy. More precisely, the energy consumption does not depend on the number of generators, but it is directly proportional to the area, which is protected by the field. Also, it is necessary that all the existing buildings are located within the protected area.Determine the smallest possible area of the protected part of the surface containing all the buildings.InputThe first line contains two integers n and r (1 ≀ n ≀ 105, 1 ≀ r ≀ 50000) β€” the number of buildings and the active ranges of the generators, correspondingly.Next n lines contains the buildings' coordinates. The i + 1-th (1 ≀ i ≀ n) line contains two real numbers with at most three digits after the decimal point xi and yi (|xi|, |yi| ≀ 50000) β€” coordinates of the i-th building. It is guaranteed that no two buildings are located at the same point, and no two different buildings are located closer than 1.It is guaranteed that there exists a circle with radius r that contains all the buildings.OutputPrint the single real number β€” the minimum area of the protected part containing all the buildings. The answer is accepted if absolute or relative error doesn't exceed 10 - 4.ExamplesInput3 50.00 0.0000.0 8.006 8.00Output78.5398163397Input4 10000.0 0.00 2.002.00 22.0 0.00Output4.0026666140Input4 53.00 0.0-3 0.000.000 10.0 -1.00Output8.1750554397NoteIn the first sample the given radius equals the radius of the circle circumscribed around the given points. That's why the circle that corresponds to it is the sought area. The answer is 25Ο€.In the second sample the area nearly coincides with the square which has vertexes in the given points.The area for the third sample is shown on the picture below.
Input3 50.00 0.0000.0 8.006 8.00
Output78.5398163397
4 seconds
256 megabytes
['geometry', '*3000']
D. Flatland Fencingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe King of Flatland will organize a knights' tournament! The winner will get half the kingdom and the favor of the princess of legendary beauty and wisdom. The final test of the applicants' courage and strength will be a fencing tournament. The tournament is held by the following rules: the participants fight one on one, the winner (or rather, the survivor) transfers to the next round.Before the battle both participants stand at the specified points on the Ox axis with integer coordinates. Then they make moves in turn. The first participant moves first, naturally. During a move, the first participant can transfer from the point x to any integer point of the interval [x + a; x + b]. The second participant can transfer during a move to any integer point of the interval [x - b; x - a]. That is, the options for the players' moves are symmetric (note that the numbers a and b are not required to be positive, and if a ≀ 0 ≀ b, then staying in one place is a correct move). At any time the participants can be located arbitrarily relative to each other, that is, it is allowed to "jump" over the enemy in any direction. A participant wins if he uses his move to transfer to the point where his opponent is.Of course, the princess has already chosen a husband and now she wants to make her sweetheart win the tournament. He has already reached the tournament finals and he is facing the last battle. The princess asks the tournament manager to arrange the tournament finalists in such a way that her sweetheart wins the tournament, considering that both players play optimally. However, the initial location of the participants has already been announced, and we can only pull some strings and determine which participant will be first and which one will be second. But how do we know which participant can secure the victory? Alas, the princess is not learned in the military affairs... Therefore, she asks you to determine how the battle will end considering that both opponents play optimally. Also, if the first player wins, your task is to determine his winning move.InputThe first line contains four space-separated integers β€” x1, x2, a and b (x1 ≠ x2, a ≀ b,  - 109 ≀ x1, x2, a, b ≀ 109) β€” coordinates of the points where the first and the second participant start, and the numbers that determine the players' moves, correspondingly.OutputOn the first line print the outcome of the battle as "FIRST" (without the quotes), if both players play optimally and the first player wins. Print "SECOND" (without the quotes) if the second player wins and print "DRAW" (without the quotes), if nobody is able to secure the victory.If the first player wins, print on the next line the single integer x β€” the coordinate of the point where the first player should transfer to win. The indicated move should be valid, that is, it should meet the following condition: x1 + a ≀ x ≀ x1 + b. If there are several winning moves, print any of them. If the first participant can't secure the victory, then you do not have to print anything.ExamplesInput0 2 0 4OutputFIRST2Input0 2 1 1OutputSECONDInput0 2 0 1OutputDRAWNoteIn the first sample the first player can win in one move.In the second sample the first participant must go to point 1, where the second participant immediately goes and wins. In the third sample changing the position isn't profitable to either participant, so nobody wins.
Input0 2 0 4
OutputFIRST2
2 seconds
256 megabytes
['games', 'math', '*2400']
C. Double Profilestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have been offered a job in a company developing a large social network. Your first task is connected with searching profiles that most probably belong to the same user.The social network contains n registered profiles, numbered from 1 to n. Some pairs there are friends (the "friendship" relationship is mutual, that is, if i is friends with j, then j is also friends with i). Let's say that profiles i and j (i ≠ j) are doubles, if for any profile k (k ≠ i, k ≠ j) one of the two statements is true: either k is friends with i and j, or k isn't friends with either of them. Also, i and j can be friends or not be friends.Your task is to count the number of different unordered pairs (i, j), such that the profiles i and j are doubles. Note that the pairs are unordered, that is, pairs (a, b) and (b, a) are considered identical.InputThe first line contains two space-separated integers n and m (1 ≀ n ≀ 106, 0 ≀ m ≀ 106), β€” the number of profiles and the number of pairs of friends, correspondingly. Next m lines contains descriptions of pairs of friends in the format "v u", where v and u (1 ≀ v, u ≀ n, v ≠ u) are numbers of profiles that are friends with each other. It is guaranteed that each unordered pair of friends occurs no more than once and no profile is friends with itself.OutputPrint the single integer β€” the number of unordered pairs of profiles that are doubles. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the %I64d specificator.ExamplesInput3 31 22 31 3Output3Input3 0Output3Input4 11 3Output2NoteIn the first and second sample any two profiles are doubles.In the third sample the doubles are pairs of profiles (1, 3) and (2, 4).
Input3 31 22 31 3
Output3
3 seconds
256 megabytes
['graphs', 'hashing', 'sortings', '*2300']
B. Colliderstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBy 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses: "Success" if the activation was successful. "Already on", if the i-th collider was already activated before the request. "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program: "Success", if the deactivation was successful. "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 105) β€” the number of colliders and the number of requests, correspondingly.Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) β€” activate the i-th collider, or "-Β i" (without the quotes) β€” deactivate the i-th collider (1 ≀ i ≀ n).OutputPrint m lines β€” the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.ExamplesInput10 10+ 6+ 10+ 5- 10- 5- 6+ 10+ 3+ 6+ 3OutputSuccessConflict with 6SuccessAlready offSuccessSuccessSuccessSuccessConflict with 10Already onNoteNote that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3".
Input10 10+ 6+ 10+ 5- 10- 5- 6+ 10+ 3+ 6+ 3
OutputSuccessConflict with 6SuccessAlready offSuccessSuccessSuccessSuccessConflict with 10Already on
2 seconds
256 megabytes
['math', 'number theory', '*1600']
A. Hometasktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of N-ish. The spelling rules state that N-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".InputThe first line contains a non-empty string s, consisting of lowercase Latin letters β€” that's the initial sentence in N-ish, written by Sergey. The length of string s doesn't exceed 105.The next line contains integer k (0 ≀ k ≀ 13) β€” the number of forbidden pairs of letters.Next k lines contain descriptions of forbidden pairs of letters. Each line contains exactly two different lowercase Latin letters without separators that represent the forbidden pairs. It is guaranteed that each letter is included in no more than one pair.OutputPrint the single number β€” the smallest number of letters that need to be removed to get a string without any forbidden pairs of neighboring letters. Please note that the answer always exists as it is always possible to remove all letters.ExamplesInputababa1abOutput2Inputcodeforces2docsOutput1NoteIn the first sample you should remove two letters b.In the second sample you should remove the second or the third letter. The second restriction doesn't influence the solution.
Inputababa1ab
Output2
2 seconds
256 megabytes
['greedy', '*1600']
E. Euclidean Distancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a multiset of points on the plane with integer coordinates. Find the maximum distance between two points from this multiset.InputThe first line of input contains the number of points n (2 ≀ n ≀ 50). Next, n pairs of lines follow, each describing a single point: the first line contains x-coordinate, the second one β€” the y-coordinate ( - 50 ≀ x, y ≀ 50). Some of the points can have identical coordinates.OutputOutput the maximum distance between two points from this multiset. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 4.ExamplesInput3012345Output5.656854249Input31012-581012Output15.5241747NoteIn the first case the maximum distance is between points (0, 1) and (4, 5). In the second case two of the points are the same, so the maximum distance is between one of them and the third point.
Input3012345
Output5.656854249
2 seconds
256 megabytes
['*special problem', '*2100']
D. Date Changetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a date in "DD.MM.YYYY" ("day.month.year") format and a number of days shift you have to add to this date. Output the resulting date.InputThe first line of input contains the date in "DD.MM.YYYY" format: two digits for day (with leading zero if needed), dot, two digits for month (with leading zero if needed), dot, four digits for year. The notation is guaranteed to give a valid date between 1980 and 2020, inclusive.The second line contains an integer shift ( - 1000 ≀ shift ≀ 1000).OutputOutput a date equal to the given one + shift days, in the same format "DD.MM.YYYY".ExamplesInput10.02.201212Output22.02.2012Input01.02.2010-40Output23.12.2009Input01.01.2000365Output31.12.2000Input13.08.1990-609Output12.12.1988NoteWhen manipulating the dates, take into account leap years; don't care about time zones/daylight saving time.
Input10.02.201212
Output22.02.2012
2 seconds
256 megabytes
['*special problem', '*2000']
C. Caesar Ciphertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCaesar cipher is one of the simplest encryption techniques. To transform the original message into encrypted one using key k, one has to replace each letter with a letter which is k positions later in the alphabet (if this takes the position beyond Z, the rest of it is counted from the start of the alphabet). In a more formal way, if letters of the alphabet are enumerated starting with 0, the result of encryption for character x will be (26 is the number of letters in the Latin alphabet).You are given the original message and the encryption key k. Output the resulting cipher.InputThe first line of input contains the original message β€” a sequence uppercase Latin letters (Β«AΒ»-Β«ZΒ»). The length of the message is from 1 to 10, inclusive.The second line contains an integer k (0 ≀ k ≀ 25).OutputOutput the result of encryption.ExamplesInputCODEFORCES5OutputHTIJKTWHJXInputWIXYZILWYM6OutputCODEFORCES
InputCODEFORCES5
OutputHTIJKTWHJX
2 seconds
256 megabytes
['*special problem', '*2200']
B. Binary notationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. Output its binary notation.InputThe only line of input data contains an integer n (1 ≀ n ≀ 106).OutputOutput the binary notation of n (without any leading zeros).ExamplesInput5Output101Input13Output1101NoteIn the first example 5 = 1 * 22 + 0 * 21 + 1 * 20.
Input5
Output101
2 seconds
256 megabytes
['*special problem', '*1800']
A. A + Btime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers A and B. Calculate their sum and output it without leading zeros.InputTwo lines of input data contain integers A and B (1 ≀ A, B ≀ 105).OutputOutput A + B without leading zeros.ExamplesInput123Output15Input1005Output105NoteThe code provided in the post about the round doesn't solve the task.
Input123
Output15
2 seconds
256 megabytes
['*special problem', '*1600']
E. Gardentime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a very beautiful country garden that can be represented as an n × m rectangular field divided into nΒ·m squares. One beautiful day Vasya remembered that he needs to pave roads between k important squares that contain buildings. To pave a road, he can cover some squares of his garden with concrete.For each garden square we know number aij that represents the number of flowers that grow in the square with coordinates (i, j). When a square is covered with concrete, all flowers that grow in the square die.Vasya wants to cover some squares with concrete so that the following conditions were fulfilled: all k important squares should necessarily be covered with concrete from each important square there should be a way to any other important square. The way should go be paved with concrete-covered squares considering that neighboring squares are squares that have a common side the total number of dead plants should be minimum As Vasya has a rather large garden, he asks you to help him.InputThe first input line contains three integers n, m and k (1 ≀ n, m ≀ 100, nΒ·m ≀ 200, 1 ≀ k ≀ min(nΒ·m, 7)) β€” the garden's sizes and the number of the important squares. Each of the next n lines contains m numbers aij (1 ≀ aij ≀ 1000) β€” the numbers of flowers in the squares. Next k lines contain coordinates of important squares written as "x y" (without quotes) (1 ≀ x ≀ n, 1 ≀ y ≀ m). The numbers written on one line are separated by spaces. It is guaranteed that all k important squares have different coordinates.OutputIn the first line print the single integer β€” the minimum number of plants that die during the road construction. Then print n lines each containing m characters β€” the garden's plan. In this plan use character "X" (uppercase Latin letter X) to represent a concrete-covered square and use character "." (dot) for a square that isn't covered with concrete. If there are multiple solutions, print any of them.ExamplesInput3 3 21 2 31 2 31 2 31 23 3Output9.X..X..XXInput4 5 41 4 5 1 22 2 2 2 72 4 1 4 53 2 1 7 11 11 54 14 4Output26X..XXXXXX.X.X..X.XX.
Input3 3 21 2 31 2 31 2 31 23 3
Output9.X..X..XX
2 seconds
256 megabytes
['bitmasks', 'dp', 'graphs', 'trees', '*2500']
D. Framestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya got hold of a sheet of checkered paper n × m squares in size. Our Vasya adores geometrical figures, so he painted two rectangles on the paper. The rectangles' sides are parallel to the coordinates' axes, also the length of each side of each rectangle is no less than 3 squares and the sides are painted by the grid lines. The sides can also be part of the sheet of paper's edge. Then Vasya hatched all squares on the rectangles' frames.Let's define a rectangle's frame as the set of squares inside the rectangle that share at least one side with its border.A little later Vasya found a sheet of paper of exactly the same size and couldn't guess whether it is the same sheet of paper or a different one. So, he asked you to check whether the sheet of paper he had found contains two painted frames and nothing besides them.Please note that the frames painted by Vasya can arbitrarily intersect, overlap or even completely coincide.The coordinates on the sheet of paper are introduced in such a way that the X axis goes from top to bottom, the x coordinates of the squares' numbers take values from 1 to n and the Y axis goes from the left to the right and the y coordinates of the squares' numbers take values from 1 to m.InputThe first input line contains two integers n and m (3 ≀ n, m ≀ 1000) β€” the sizes of the sheet of paper Vasya found. Next n lines, each consisting of m symbols "." (dot) and "#" (number sign), describe the found sheet of paper. The symbol "#" represents a hatched square and the symbol "." represents a non-hatched square.OutputIn the first line print the single word "YES" or "NO", meaning whether it is true that the found sheet of paper has two frames painted on it. If the answer is positive, then print in the second line 4 integers: the coordinates of the upper left and lower right corners of the first frame. In the third line print 4 integers: the coordinates of the upper left and the lower right corners of the second frame. If there are multiple answers, print any of them.ExamplesInput4 5######.#.####.######OutputYES1 1 3 31 1 4 5Input5 6...###...########.#...#.#####.OutputNONoteIn the first sample there are two frames on the picture. The first one is:###..#.#..###.......The second one is:######...##...######In the second sample the painted figures are not frames. Note that the height and width of valid frames is no less than 3.
Input4 5######.#.####.######
OutputYES1 1 3 31 1 4 5
2 seconds
256 megabytes
['brute force', '*2600']
C. Pocket Booktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≀ i < j ≀ n, 1 ≀ k ≀ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).InputThe first input line contains two integers n and m (1 ≀ n, m ≀ 100) β€” the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.OutputPrint the single number β€” the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).ExamplesInput2 3AABBAAOutput4Input4 5ABABABCGDGAAAAAYABSAOutput216NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".
Input2 3AABBAA
Output4
2 seconds
256 megabytes
['combinatorics', '*1400']
B. Stepstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple.Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≀ x ≀ n, 1 ≀ y ≀ m), where x is the index of the row and y is the index of the column.Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps).A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step.Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.InputThe first input line contains two integers n and m (1 ≀ n, m ≀ 109) β€” the yard's sizes. The second line contains integers xc and yc β€” the initial square's coordinates (1 ≀ xc ≀ n, 1 ≀ yc ≀ m).The third line contains an integer k (1 ≀ k ≀ 104) β€” the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≀ 109, |dx| + |dy| β‰₯ 1).OutputPrint the single number β€” the number of steps Vasya had made.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.ExamplesInput4 51 131 11 10 -2Output4Input10 101 21-1 0Output0NoteIn the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0,  - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps.In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.
Input4 51 131 11 10 -2
Output4
2 seconds
256 megabytes
['binary search', 'implementation', '*1300']
A. Markstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.Your task is to find the number of successful students in the group.InputThe first input line contains two integers n and m (1 ≀ n, m ≀ 100) β€” the number of students and the number of subjects, correspondingly. Next n lines each containing m characters describe the gradebook. Each character in the gradebook is a number from 1 to 9. Note that the marks in a rows are not sepatated by spaces.OutputPrint the single number β€” the number of successful students in the given group.ExamplesInput3 3223232112Output2Input3 5917281182811111Output3NoteIn the first sample test the student number 1 is the best at subjects 1 and 3, student 2 is the best at subjects 1 and 2, but student 3 isn't the best at any subject.In the second sample test each student is the best at at least one subject.
Input3 3223232112
Output2
1 second
256 megabytes
['implementation', '*900']
B. Phone Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWinters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type). If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.InputThe first line contains an integer n (1 ≀ n ≀ 100) β€” the number of friends. Then follow n data blocks that describe each friend's phone books. Each block is presented in the following form: first goes the line that contains integer si and string namei (0 ≀ si ≀ 100) β€” the number of phone numbers in the phone book of the i-th friend and the name of the i-th friend. The name is a non-empty sequence of uppercase and lowercase Latin letters, containing no more than 20 characters. Next si lines contain numbers as "XX-XX-XX", where X is arbitrary digits from 0 to 9.OutputIn the first line print the phrase "If you want to call a taxi, you should call: ". Then print names of all friends whose phone books contain maximal number of taxi phone numbers. In the second line print the phrase "If you want to order a pizza, you should call: ". Then print names of all friends who have maximal number of pizza phone numbers. In the third line print the phrase "If you want to go to a cafe with a wonderful girl, you should call: ". Then print names of all friends who have maximal number of girls' phone numbers. Print the names in the order in which they are given in the input data. Separate two consecutive names with a comma and a space. Each line should end with exactly one point. For clarifications concerning the output form, see sample tests. It is necessary that you follow the output form strictly. Extra spaces are not allowed.ExamplesInput42 Fedorov22-22-2298-76-543 Melnikov75-19-0923-45-6799-99-987 Rogulenko22-22-2211-11-1133-33-3344-44-4455-55-5566-66-6695-43-213 Kaluzhin11-11-1199-99-9998-65-32OutputIf you want to call a taxi, you should call: Rogulenko.If you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.If you want to go to a cafe with a wonderful girl, you should call: Melnikov.Input35 Gleb66-66-6655-55-5501-01-0165-43-2112-34-563 Serega55-55-5587-65-4365-55-215 Melnik12-42-1287-73-0136-04-1288-12-2282-11-43OutputIf you want to call a taxi, you should call: Gleb.If you want to order a pizza, you should call: Gleb, Serega.If you want to go to a cafe with a wonderful girl, you should call: Melnik.Input33 Kulczynski22-22-2265-43-2198-12-004 Pachocki11-11-1111-11-1111-11-1198-76-540 SmietankaOutputIf you want to call a taxi, you should call: Pachocki.If you want to order a pizza, you should call: Kulczynski, Pachocki.If you want to go to a cafe with a wonderful girl, you should call: Kulczynski.NoteIn the first sample you are given four friends. Fedorov's phone book contains one taxi number and one pizza delivery number, Melnikov's phone book only has 3 numbers of girls, Rogulenko's one has 6 taxi numbers and one pizza delivery number, Kaluzhin's one contains 2 taxi numbers and one pizza delivery number.Thus, if you need to order a taxi, you should obviously call Rogulenko, if you need to order a pizza you should call anybody of the following: Rogulenko, Fedorov, Kaluzhin (each of them has one number). Melnikov has maximal number of phone numbers of girls.
Input42 Fedorov22-22-2298-76-543 Melnikov75-19-0923-45-6799-99-987 Rogulenko22-22-2211-11-1133-33-3344-44-4455-55-5566-66-6695-43-213 Kaluzhin11-11-1199-99-9998-65-32
OutputIf you want to call a taxi, you should call: Rogulenko.If you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.If you want to go to a cafe with a wonderful girl, you should call: Melnikov.
2 seconds
256 megabytes
['implementation', 'strings', '*1200']
A. Soft Drinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt.To make a toast, each friend needs nl milliliters of the drink, a slice of lime and np grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?InputThe first and only line contains positive integers n, k, l, c, d, p, nl, np, not exceeding 1000 and no less than 1. The numbers are separated by exactly one space.OutputPrint a single integer β€” the number of toasts each friend can make.ExamplesInput3 4 5 10 8 100 3 1Output2Input5 100 10 1 19 90 4 3Output3Input10 1000 1000 25 23 1 50 1Output0NoteA comment to the first sample: Overall the friends have 4 * 5 = 20 milliliters of the drink, it is enough to make 20 / 3 = 6 toasts. The limes are enough for 10 * 8 = 80 toasts and the salt is enough for 100 / 1 = 100 toasts. However, there are 3 friends in the group, so the answer is min(6, 80, 100) / 3 = 2.
Input3 4 5 10 8 100 3 1
Output2
2 seconds
256 megabytes
['implementation', 'math', '*800']
E. Freezing with Styletime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis winter is so... well, you've got the idea :-) The Nvodsk road system can be represented as n junctions connected with n - 1 bidirectional roads so that there is a path between any two junctions. The organizers of some event want to choose a place to accommodate the participants (junction v), and the place to set up the contests (junction u). Besides, at the one hand, they want the participants to walk about the city and see the neighbourhood (that's why the distance between v and u should be no less than l). On the other hand, they don't want the participants to freeze (so the distance between v and u should be no more than r). Besides, for every street we know its beauty β€” some integer from 0 to 109. Your task is to choose the path that fits in the length limits and has the largest average beauty. We shall define the average beauty as a median of sequence of the beauties of all roads along the path.We can put it more formally like that: let there be a path with the length k. Let ai be a non-decreasing sequence that contains exactly k elements. Each number occurs there exactly the number of times a road with such beauty occurs along on path. We will represent the path median as number a⌊k / 2βŒ‹, assuming that indexation starting from zero is used. ⌊xβŒ‹ β€” is number Ρ…, rounded down to the nearest integer.For example, if a = {0, 5, 12}, then the median equals to 5, and if a = {0, 5, 7, 12}, then the median is number 7.It is guaranteed that there will be at least one path with the suitable quantity of roads.InputThe first line contains three integers n, l, r (1 ≀ l ≀ r < n ≀ 105).Next n - 1 lines contain descriptions of roads of the Nvodsk, each line contains three integers ai, bi, ci (1 ≀ ai, bi ≀ n, 0 ≀ ci ≀ 109, ai ≠ bi) β€” junctions ai and bi are connected with a street whose beauty equals ci.OutputPrint two integers β€” numbers of the junctions, where to accommodate the participants and set up the contests, correspondingly. If there are multiple optimal variants, print any of them.ExamplesInput6 3 41 2 12 3 13 4 14 5 15 6 1Output4 1Input6 3 41 2 12 3 13 4 14 5 25 6 2Output6 3Input5 1 41 2 11 3 43 4 73 5 2Output4 3Input8 3 61 2 92 3 73 4 74 5 85 8 23 6 32 7 4Output5 1NoteIn the first sample all roads have the same beauty. That means that all paths of the positive length have the same median. Thus, any path with length from 3 to 4, inclusive will be valid for us.In the second sample the city looks like that: 1 - 2 - 3 - 4 - 5 - 6. Two last roads are more valuable and we should choose any path that contains both of them and has the suitable length. It is either the path between 2 and 6 or the path between 3 and 6.
Input6 3 41 2 12 3 13 4 14 5 15 6 1
Output4 1
7 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'trees', '*3000']
D. Mission Impassabletime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMarket stalls now have the long-awaited game The Colder Scrools V: Nvodsk. The game turned out to be difficult as hell and most students can't complete the last quest ("We don't go to Nvodsk..."). That threatened winter exams. The rector already started to wonder whether he should postpone the winter exams till April (in fact, he wanted to complete the quest himself). But all of a sudden a stranger appeared at the door of his office. "Good afternoon. My name is Chuck and I solve any problems" β€” he said.And here they are sitting side by side but still they can't complete the mission. The thing is, to kill the final boss one should prove one's perfect skills in the art of managing letters. One should be a real magician to do that. And can you imagine what happens when magicians start competing... But let's put it more formally: you are given a string and a set of integers ai. You are allowed to choose any substring that is a palindrome and delete it. At that we receive some number of points equal to ak, where k is the length of the deleted palindrome. For some k, ak = -1, which means that deleting palindrome strings of such length is forbidden. After a substring is deleted, the remaining part "shifts together", that is, at no moment of time the string has gaps. The process is repeated while the string has at least one palindrome substring that can be deleted. All gained points are summed up.Determine what maximum number of points can be earned."Oh" β€” said Chuck, raising from the chair, β€” "I used to love deleting palindromes, just like you, but one day I took an arrow in the Knee".InputThe first line contains an integer l (1 ≀ l ≀ 150) β€” the length of the string.The second line contains exactly l integers ak ( - 1 ≀ ak ≀ 105) β€” the points a player gains for deleting.The third line contains exactly l lowercase Latin letters β€” the original string from which a player can delete palindromes. The line contains no other characters apart from the newline character at the end of the string.OutputPrint a single number β€” the maximum number of points one can gain if he plays on the given string.ExamplesInput7-1 -1 -1 -1 -1 -1 -1abacabaOutput0Input71 -1 -1 -1 -1 -1 -1abacabaOutput7Input71 5 -1 -1 -1 -1 10abacabaOutput16NoteIn the first sample we cannot delete any substring, so the best result is 0. In the second sample we are allowed to delete only those palindromes whose length equals 1, thus, if we delete the whole string, we get 7 points. In the third sample the optimal strategy is: first we delete character c, then string aa, then bb, and the last one aa. At that we get 1 + 3 * 5 = 16 points.
Input7-1 -1 -1 -1 -1 -1 -1abacaba
Output0
3 seconds
256 megabytes
['dp', 'strings', '*2600']
C. Smart Cheatertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputI guess there's not much point in reminding you that Nvodsk winters aren't exactly hot. That increased the popularity of the public transport dramatically. The route of bus 62 has exactly n stops (stop 1 goes first on its way and stop n goes last). The stops are positioned on a straight line and their coordinates are 0 = x1 < x2 < ... < xn. Each day exactly m people use bus 62. For each person we know the number of the stop where he gets on the bus and the number of the stop where he gets off the bus. A ticket from stop a to stop b (a < b) costs xb - xa rubles. However, the conductor can choose no more than one segment NOT TO SELL a ticket for. We mean that conductor should choose C and D (Π‘ <= D) and sell a ticket for the segments [A, C] and [D, B], or not sell the ticket at all. The conductor and the passenger divide the saved money between themselves equally. The conductor's "untaxed income" is sometimes interrupted by inspections that take place as the bus drives on some segment of the route located between two consecutive stops. The inspector fines the conductor by c rubles for each passenger who doesn't have the ticket for this route's segment.You know the coordinated of all stops xi; the numbers of stops where the i-th passenger gets on and off, ai and bi (ai < bi); the fine c; and also pi β€” the probability of inspection on segment between the i-th and the i + 1-th stop. The conductor asked you to help him make a plan of selling tickets that maximizes the mathematical expectation of his profit.InputThe first line contains three integers n, m and c (2 ≀ n ≀ 150 000, 1 ≀ m ≀ 300 000, 1 ≀ c ≀ 10 000).The next line contains n integers xi (0 ≀ xi ≀ 109, x1 = 0, xi < xi + 1) β€” the coordinates of the stops on the bus's route.The third line contains n - 1 integer pi (0 ≀ pi ≀ 100) β€” the probability of inspection in percents on the segment between stop i and stop i + 1.Then follow m lines that describe the bus's passengers. Each line contains exactly two integers ai and bi (1 ≀ ai < bi ≀ n) β€” the numbers of stops where the i-th passenger gets on and off.OutputPrint the single real number β€” the maximum expectation of the conductor's profit. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput3 3 100 10 100100 01 22 31 3Output90.000000000Input10 8 1870 10 30 70 150 310 630 1270 2550 5110013 87 65 0 100 44 67 3 41 102 93 81 56 102 74 104 5Output76859.990000000NoteA comment to the first sample:The first and third passengers get tickets from stop 1 to stop 2. The second passenger doesn't get a ticket. There always is inspection on the segment 1-2 but both passengers have the ticket for it. There never is an inspection on the segment 2-3, that's why the second passenger gets away with the cheating. Our total profit is (0 + 90 / 2 + 90 / 2) = 90.
Input3 3 100 10 100100 01 22 31 3
Output90.000000000
5 seconds
256 megabytes
['data structures', 'math', 'probabilities', '*2200']
B. Quantity of Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJust in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to find their quantity modulo 1000000007 (109 + 7). Be careful and don't miss a string or two!Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.InputThe first and only line contains three integers: n, m and k (1 ≀ n, m, k ≀ 2000).OutputPrint a single integer β€” the number of strings of the described type modulo 1000000007 (109 + 7).ExamplesInput1 1 1Output1Input5 2 4Output2NoteIn the first sample only one string is valid: "a" (let's denote the only letter of our alphabet as "a").In the second sample (if we denote the alphabet letters as "a" and "b") the following strings are valid: "aaaaa" and "bbbbb".
Input1 1 1
Output1
2 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'graphs', 'math', '*1600']
A. Win or Freezetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself. The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.InputThe first line contains the only integer q (1 ≀ q ≀ 1013).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.OutputIn the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer β€” his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.ExamplesInput6Output2Input30Output16Input1Output10NoteNumber 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory.
Input6
Output2
2 seconds
256 megabytes
['games', 'math', 'number theory', '*1400']
E. Martian Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up. Imagine a Martian who has exactly n eyes located in a row and numbered from the left to the right from 1 to n. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string s consisting of uppercase Latin letters. The string's length is n. "Ding dong!" β€” the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only m Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. More formally, the Martian chooses four numbers a, b, c, d, (1 ≀ a ≀ b < c ≀ d ≀ n) and opens all eyes with numbers i such that a ≀ i ≀ b or c ≀ i ≀ d. After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word.Let's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.InputThe first line contains a non-empty string s consisting of uppercase Latin letters. The strings' length is n (2 ≀ n ≀ 105). The second line contains an integer m (1 ≀ m ≀ 100) β€” the number of beautiful words. Next m lines contain the beautiful words pi, consisting of uppercase Latin letters. Their length is from 1 to 1000. All beautiful strings are pairwise different.OutputPrint the single integer β€” the number of different beautiful strings the Martian can see this morning.ExamplesInputABCBABA2BAABABBAOutput1NoteLet's consider the sample test. There the Martian can get only the second beautiful string if he opens segments of eyes a = 1, b = 2 and c = 4, d = 5 or of he opens segments of eyes a = 1, b = 2 and c = 6, d = 7.
InputABCBABA2BAABABBA
Output1
2 seconds
256 megabytes
['string suffix structures', 'strings', '*2300']
D. Coloring Bracketstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as "(())()" and "()" are correct bracket sequences and such sequences as ")()" and "(()" are not.In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one. You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled: Each bracket is either not colored any color, or is colored red, or is colored blue. For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored. No two neighboring colored brackets have the same color. Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo 1000000007 (109 + 7).InputThe first line contains the single string s (2 ≀ |s| ≀ 700) which represents a correct bracket sequence. OutputPrint the only number β€” the number of ways to color the bracket sequence that meet the above given conditions modulo 1000000007 (109 + 7).ExamplesInput(())Output12Input(()())Output40Input()Output4NoteLet's consider the first sample test. The bracket sequence from the sample can be colored, for example, as is shown on two figures below. The two ways of coloring shown below are incorrect.
Input(())
Output12
2 seconds
256 megabytes
['dp', '*1900']
C. Division into Teamstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled: Each boy plays for exactly one team (x + y = n). The sizes of teams differ in no more than one (|x - y| ≀ 1). The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.InputThe first line contains the only integer n (2 ≀ n ≀ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≀ ai ≀ 104), the i-th number represents the i-th boy's playing skills. OutputOn the first line print an integer x β€” the number of boys playing for the first team. On the second line print x integers β€” the individual numbers of boys playing for the first team. On the third line print an integer y β€” the number of boys playing for the second team, on the fourth line print y integers β€” the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≀ 1, and the condition that limits the total skills.If there are multiple ways to solve the problem, print any of them.The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.ExamplesInput31 2 1Output21 2 13 Input52 3 3 1 1Output34 1 3 25 2 NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≀ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≀ 2) is fulfilled.
Input31 2 1
Output21 2 13
1 second
256 megabytes
['greedy', 'math', 'sortings', '*1500']
B. Martian Clocktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHaving stayed home alone, Petya decided to watch forbidden films on the Net in secret. "What ungentlemanly behavior!" β€” you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored adventure stories that featured lasers and robots. Today Petya is watching a shocking blockbuster about the Martians called "R2:D2". What can "R2:D2" possibly mean? It might be the Martian time represented in the Martian numeral system. Petya knows that time on Mars is counted just like on the Earth (that is, there are 24 hours and each hour has 60 minutes). The time is written as "a:b", where the string a stands for the number of hours (from 0 to 23 inclusive), and string b stands for the number of minutes (from 0 to 59 inclusive). The only thing Petya doesn't know is in what numeral system the Martian time is written.Your task is to print the radixes of all numeral system which can contain the time "a:b".InputThe first line contains a single string as "a:b" (without the quotes). There a is a non-empty string, consisting of numbers and uppercase Latin letters. String a shows the number of hours. String b is a non-empty string that consists of numbers and uppercase Latin letters. String b shows the number of minutes. The lengths of strings a and b are from 1 to 5 characters, inclusive. Please note that strings a and b can have leading zeroes that do not influence the result in any way (for example, string "008:1" in decimal notation denotes correctly written time).We consider characters 0, 1, ..., 9 as denoting the corresponding digits of the number's representation in some numeral system, and characters A, B, ..., Z correspond to numbers 10, 11, ..., 35.OutputPrint the radixes of the numeral systems that can represent the time "a:b" in the increasing order. Separate the numbers with spaces or line breaks. If there is no numeral system that can represent time "a:b", print the single integer 0. If there are infinitely many numeral systems that can represent the time "a:b", print the single integer -1.Note that on Mars any positional numeral systems with positive radix strictly larger than one are possible.ExamplesInput11:20Output3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22Input2A:13Output0Input000B:00001Output-1NoteLet's consider the first sample. String "11:20" can be perceived, for example, as time 4:6, represented in the ternary numeral system or as time 17:32 in hexadecimal system. Let's consider the second sample test. String "2A:13" can't be perceived as correct time in any notation. For example, let's take the base-11 numeral notation. There the given string represents time 32:14 that isn't a correct time.Let's consider the third sample. String "000B:00001" can be perceived as a correct time in the infinite number of numeral systems. If you need an example, you can take any numeral system with radix no less than 12.
Input11:20
Output3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
2 seconds
256 megabytes
['implementation', '*1600']
A. Business triptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhat joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" β€” thought Petya. He know for a fact that if he fulfills the parents' task in the i-th (1 ≀ i ≀ 12) month of the year, then the flower will grow by ai centimeters, and if he doesn't water the flower in the i-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by k centimeters. Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by k centimeters.InputThe first line contains exactly one integer k (0 ≀ k ≀ 100). The next line contains twelve space-separated integers: the i-th (1 ≀ i ≀ 12) number in the line represents ai (0 ≀ ai ≀ 100). OutputPrint the only integer β€” the minimum number of months when Petya has to water the flower so that the flower grows no less than by k centimeters. If the flower can't grow by k centimeters in a year, print -1.ExamplesInput51 1 1 1 2 2 3 2 2 1 1 1Output2Input00 0 0 0 0 0 0 1 1 2 3 0Output0Input111 1 4 1 1 5 1 1 4 1 1 1Output3NoteLet's consider the first sample test. There it is enough to water the flower during the seventh and the ninth month. Then the flower grows by exactly five centimeters.In the second sample Petya's parents will believe him even if the flower doesn't grow at all (k = 0). So, it is possible for Petya not to water the flower at all.
Input51 1 1 1 2 2 3 2 2 1 1 1
Output2
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*900']
E. Porcelaintime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring her tantrums the princess usually smashes some collectable porcelain. Every furious shriek is accompanied with one item smashed.The collection of porcelain is arranged neatly on n shelves. Within each shelf the items are placed in one row, so that one can access only the outermost items β€” the leftmost or the rightmost item, not the ones in the middle of the shelf. Once an item is taken, the next item on that side of the shelf can be accessed (see example). Once an item is taken, it can't be returned to the shelves.You are given the values of all items. Your task is to find the maximal damage the princess' tantrum of m shrieks can inflict on the collection of porcelain.InputThe first line of input data contains two integers n (1 ≀ n ≀ 100) and m (1 ≀ m ≀ 10000). The next n lines contain the values of the items on the shelves: the first number gives the number of items on this shelf (an integer between 1 and 100, inclusive), followed by the values of the items (integers between 1 and 100, inclusive), in the order in which they appear on the shelf (the first number corresponds to the leftmost item, the last one β€” to the rightmost one). The total number of items is guaranteed to be at least m.OutputOutput the maximal total value of a tantrum of m shrieks.ExamplesInput2 33 3 7 23 4 1 5Output15Input1 34 4 3 1 2Output9NoteIn the first case there are two shelves, each with three items. To maximize the total value of the items chosen, one can take two items from the left side of the first shelf and one item from the right side of the second shelf.In the second case there is only one shelf, so all three items are taken from it β€” two from the left side and one from the right side.
Input2 33 3 7 23 4 1 5
Output15
1 second
256 megabytes
['dp', '*1900']
D. Bag of micetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chance.They take turns drawing a mouse from a bag which initially contains w white and b black mice. The person who is the first to draw a white mouse wins. After each mouse drawn by the dragon the rest of mice in the bag panic, and one of them jumps out of the bag itself (the princess draws her mice carefully and doesn't scare other mice). Princess draws first. What is the probability of the princess winning?If there are no more mice in the bag and nobody has drawn a white mouse, the dragon wins. Mice which jump out of the bag themselves are not considered to be drawn (do not define the winner). Once a mouse has left the bag, it never returns to it. Every mouse is drawn from the bag with the same probability as every other one, and every mouse jumps out of the bag with the same probability as every other one.InputThe only line of input data contains two integers w and b (0 ≀ w, b ≀ 1000).OutputOutput the probability of the princess winning. The answer is considered to be correct if its absolute or relative error does not exceed 10 - 9.ExamplesInput1 3Output0.500000000Input5 5Output0.658730159NoteLet's go through the first sample. The probability of the princess drawing a white mouse on her first turn and winning right away is 1/4. The probability of the dragon drawing a black mouse and not winning on his first turn is 3/4 * 2/3 = 1/2. After this there are two mice left in the bag β€” one black and one white; one of them jumps out, and the other is drawn by the princess on her second turn. If the princess' mouse is white, she wins (probability is 1/2 * 1/2 = 1/4), otherwise nobody gets the white mouse, so according to the rule the dragon wins.
Input1 3
Output0.500000000
2 seconds
256 megabytes
['dp', 'games', 'math', 'probabilities', '*1800']
C. Terse princesstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputΒ«Next pleaseΒ», β€” the princess called and cast an estimating glance at the next groom.The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured Β«Oh...Β». Whenever the groom is richer than all previous ones added together, she exclaims Β«Wow!Β» (no Β«Oh...Β» in this case). At the sight of the first groom the princess stays calm and says nothing.The fortune of each groom is described with an integer between 1 and 50000. You know that during the day the princess saw n grooms, said Β«Oh...Β» exactly a times and exclaimed Β«Wow!Β» exactly b times. Your task is to output a sequence of n integers t1, t2, ..., tn, where ti describes the fortune of i-th groom. If several sequences are possible, output any of them. If no sequence exists that would satisfy all the requirements, output a single number -1.InputThe only line of input data contains three integer numbers n, a and b (1 ≀ n ≀ 100, 0 ≀ a, b ≀ 15, n > a + b), separated with single spaces.OutputOutput any sequence of integers t1, t2, ..., tn, where ti (1 ≀ ti ≀ 50000) is the fortune of i-th groom, that satisfies the given constraints. If no sequence exists that would satisfy all the requirements, output a single number -1.ExamplesInput10 2 3Output5 1 3 6 16 35 46 4 200 99Input5 0 0Output10 10 6 6 5NoteLet's have a closer look at the answer for the first sample test. The princess said Β«Oh...Β» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99. The princess exclaimed Β«Wow!Β» (highlighted in bold): 5 1 3 6 16 35 46 4 200 99.
Input10 2 3
Output5 1 3 6 16 35 46 4 200 99
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1700']
B. Escapetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe princess is going to escape the dragon's cave, and she needs to plan it carefully.The princess runs at vp miles per hour, and the dragon flies at vd miles per hour. The dragon will discover the escape after t hours and will chase the princess immediately. Looks like there's no chance to success, but the princess noticed that the dragon is very greedy and not too smart. To delay him, the princess decides to borrow a couple of bijous from his treasury. Once the dragon overtakes the princess, she will drop one bijou to distract him. In this case he will stop, pick up the item, return to the cave and spend f hours to straighten the things out in the treasury. Only after this will he resume the chase again from the very beginning.The princess is going to run on the straight. The distance between the cave and the king's castle she's aiming for is c miles. How many bijous will she need to take from the treasury to be able to reach the castle? If the dragon overtakes the princess at exactly the same moment she has reached the castle, we assume that she reached the castle before the dragon reached her, and doesn't need an extra bijou to hold him off.InputThe input data contains integers vp, vd, t, f and c, one per line (1 ≀ vp, vd ≀ 100, 1 ≀ t, f ≀ 10, 1 ≀ c ≀ 1000).OutputOutput the minimal number of bijous required for the escape to succeed.ExamplesInput121110Output2Input12118Output1NoteIn the first case one hour after the escape the dragon will discover it, and the princess will be 1 mile away from the cave. In two hours the dragon will overtake the princess 2 miles away from the cave, and she will need to drop the first bijou. Return to the cave and fixing the treasury will take the dragon two more hours; meanwhile the princess will be 4 miles away from the cave. Next time the dragon will overtake the princess 8 miles away from the cave, and she will need the second bijou, but after this she will reach the castle without any further trouble.The second case is similar to the first one, but the second time the dragon overtakes the princess when she has reached the castle, and she won't need the second bijou.
Input121110
Output2
2 seconds
256 megabytes
['implementation', 'math', '*1500']
A. Insomnia curetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputΒ«One dragon. Two dragon. Three dragonΒ», β€” the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every k-th dragon got punched in the face with a frying pan. Every l-th dragon got his tail shut into the balcony door. Every m-th dragon got his paws trampled with sharp heels. Finally, she threatened every n-th dragon to call her mom, and he withdrew in panic.How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of d dragons?InputInput data contains integer numbers k, l, m, n and d, each number in a separate line (1 ≀ k, l, m, n ≀ 10, 1 ≀ d ≀ 105).OutputOutput the number of damaged dragons.ExamplesInput123412Output12Input234524Output17NoteIn the first case every first dragon got punched with a frying pan. Some of the dragons suffered from other reasons as well, but the pan alone would be enough.In the second case dragons 1, 7, 11, 13, 17, 19 and 23 escaped unharmed.
Input123412
Output12
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'math', '*800']
B. Smile Housetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA smile house is created to raise the mood. It has n rooms. Some of the rooms are connected by doors. For each two rooms (number i and j), which are connected by a door, Petya knows their value cij β€” the value which is being added to his mood when he moves from room i to room j.Petya wondered whether he can raise his mood infinitely, moving along some cycle? And if he can, then what minimum number of rooms he will need to visit during one period of a cycle?InputThe first line contains two positive integers n and m (), where n is the number of rooms, and m is the number of doors in the Smile House. Then follows the description of the doors: m lines each containing four integers i, j, cij ΠΈ cji (1 ≀ i, j ≀ n, i ≠ j,  - 104 ≀ cij, cji ≀ 104). It is guaranteed that no more than one door connects any two rooms. No door connects the room with itself.OutputPrint the minimum number of rooms that one needs to visit during one traverse of the cycle that can raise mood infinitely. If such cycle does not exist, print number 0.ExamplesInput4 41 2 -10 31 3 1 -102 4 -10 -13 4 0 -3Output4NoteCycle is such a sequence of rooms a1, a2, ..., ak, that a1 is connected with a2, a2 is connected with a3, ..., ak - 1 is connected with ak, ak is connected with a1. Some elements of the sequence can coincide, that is, the cycle should not necessarily be simple. The number of rooms in the cycle is considered as k, the sequence's length. Note that the minimum possible length equals two.
Input4 41 2 -10 31 3 1 -102 4 -10 -13 4 0 -3
Output4
3 seconds
256 megabytes
['binary search', 'graphs', 'matrices', '*2500']
A. Punctuationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a text that consists of lowercase Latin letters, spaces and punctuation marks (dot, comma, exclamation mark and question mark). A word is defined as a sequence of consecutive Latin letters.Your task is to add spaces to the text by the following rules: if there is no punctuation mark between two words, then they should be separated by exactly one space there should be no spaces before each punctuation mark there should be exactly one space after each punctuation mark It is guaranteed that there is at least one word between any two punctuation marks. The text begins and ends with a Latin letter.InputThe input data contains of a single non-empty line β€” the text whose length is no more than 10000 characters.OutputPrint the text, edited according to the rules. In this problem you should follow the output format very strictly. For example, extra space at the end of the output line is considered as wrong answer. Note that a newline character at the end of the line doesn't matter.ExamplesInputgalileo galilei was an italian physicist ,mathematician,astronomerOutputgalileo galilei was an italian physicist, mathematician, astronomerInputgalileo was born in pisaOutputgalileo was born in pisa
Inputgalileo galilei was an italian physicist ,mathematician,astronomer
Outputgalileo galilei was an italian physicist, mathematician, astronomer
2 seconds
256 megabytes
['implementation', 'strings', '*1300']
B. Lucky Masktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya calls a mask of a positive integer n the number that is obtained after successive writing of all lucky digits of number n from the left to the right. For example, the mask of number 72174994 is number 7744, the mask of 7 is 7, the mask of 9999047 is 47. Obviously, mask of any number is always a lucky number.Petya has two numbers β€” an arbitrary integer a and a lucky number b. Help him find the minimum number c (c > a) such that the mask of number c equals b.InputThe only line contains two integers a and b (1 ≀ a, b ≀ 105). It is guaranteed that number b is lucky.OutputIn the only line print a single number β€” the number c that is sought by Petya.ExamplesInput1 7Output7Input100 47Output147
Input1 7
Output7
2 seconds
256 megabytes
['brute force', 'implementation', '*1300']
A. Lucky Tickettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals n (n is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first n / 2 digits) equals the sum of digits in the second half (the sum of the last n / 2 digits). Check if the given ticket is lucky.InputThe first line contains an even integer n (2 ≀ n ≀ 50) β€” the length of the ticket number that needs to be checked. The second line contains an integer whose length equals exactly n β€” the ticket number. The number may contain leading zeros.OutputOn the first line print "YES" if the given ticket number is lucky. Otherwise, print "NO" (without the quotes).ExamplesInput247OutputNOInput44738OutputNOInput44774OutputYESNoteIn the first sample the sum of digits in the first half does not equal the sum of digits in the second half (4 ≠ 7).In the second sample the ticket number is not the lucky number.
Input247
OutputNO
2 seconds
256 megabytes
['implementation', '*800']
E. Lucky Queriestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya brought home string s with the length of n. The string only consists of lucky digits. The digits are numbered from the left to the right starting with 1. Now Petya should execute m queries of the following form: switch l r β€” "switch" digits (i.e. replace them with their opposites) at all positions with indexes from l to r, inclusive: each digit 4 is replaced with 7 and each digit 7 is replaced with 4 (1 ≀ l ≀ r ≀ n); count β€” find and print on the screen the length of the longest non-decreasing subsequence of string s. Subsequence of a string s is a string that can be obtained from s by removing zero or more of its elements. A string is called non-decreasing if each successive digit is not less than the previous one.Help Petya process the requests.InputThe first line contains two integers n and m (1 ≀ n ≀ 106, 1 ≀ m ≀ 3Β·105) β€” the length of the string s and the number of queries correspondingly. The second line contains n lucky digits without spaces β€” Petya's initial string. Next m lines contain queries in the form described in the statement.OutputFor each query count print an answer on a single line.ExamplesInput2 347countswitch 1 2countOutput21Input3 5747countswitch 1 1countswitch 1 3countOutput232NoteIn the first sample the chronology of string s after some operations are fulfilled is as follows (the sought maximum subsequence is marked with bold): 47 74 74 In the second sample: 747 447 447 774 774
Input2 347countswitch 1 2count
Output21
3 seconds
256 megabytes
['data structures', '*2400']
D. Lucky Pairtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has an array a of n integers. The numbers in the array are numbered starting from 1. Unfortunately, Petya has been misbehaving and so, his parents don't allow him play with arrays that have many lucky numbers. It is guaranteed that no more than 1000 elements in the array a are lucky numbers. Petya needs to find the number of pairs of non-intersecting segments [l1;r1] and [l2;r2] (1 ≀ l1 ≀ r1 < l2 ≀ r2 ≀ n, all four numbers are integers) such that there's no such lucky number that occurs simultaneously in the subarray a[l1..r1] and in the subarray a[l2..r2]. Help Petya count the number of such pairs.InputThe first line contains an integer n (2 ≀ n ≀ 105) β€” the size of the array a. The second line contains n space-separated integers ai (1 ≀ ai ≀ 109) β€” array a. It is guaranteed that no more than 1000 elements in the array a are lucky numbers. OutputOn the single line print the only number β€” the answer to the problem.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 4 2 4Output9Input24 7Output1Input44 4 7 7Output9NoteThe subarray a[l..r] is an array that consists of elements al, al + 1, ..., ar.In the first sample there are 9 possible pairs that satisfy the condition: [1, 1] and [2, 2], [1, 1] and [2, 3], [1, 1] and [2, 4], [1, 1] and [3, 3], [1, 1] and [3, 4], [1, 1] and [4, 4], [1, 2] and [3, 3], [2, 2] and [3, 3], [3, 3] and [4, 4].In the second sample there is only one pair of segments β€” [1;1] and [2;2] and it satisfies the condition.
Input41 4 2 4
Output9
2 seconds
256 megabytes
['combinatorics', 'data structures', 'implementation', '*2900']
C. Lucky Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has sequence a consisting of n integers.The subsequence of the sequence a is such subsequence that can be obtained from a by removing zero or more of its elements.Two sequences are considered different if index sets of numbers included in them are different. That is, the values ​of the elements ​do not matter in the comparison of subsequences. In particular, any sequence of length n has exactly 2n different subsequences (including an empty subsequence).A subsequence is considered lucky if it has a length exactly k and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times).Help Petya find the number of different lucky subsequences of the sequence a. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number 1000000007 (109 + 7).InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n integers ai (1 ≀ ai ≀ 109) β€” the sequence a. OutputOn the single line print the single number β€” the answer to the problem modulo prime number 1000000007 (109 + 7).ExamplesInput3 210 10 10Output3Input4 24 4 7 7Output4NoteIn the first sample all 3 subsequences of the needed length are considered lucky.In the second sample there are 4 lucky subsequences. For them the sets of indexes equal (the indexation starts from 1): {1, 3}, {1, 4}, {2, 3} and {2, 4}.
Input3 210 10 10
Output3
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*2100']
B. Lucky Number 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.InputThe single line contains four integers a1, a2, a3 and a4 (1 ≀ a1, a2, a3, a4 ≀ 106).OutputOn the single line print without leading zeroes the answer to the problem β€” the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).ExamplesInput2 2 1 1Output4774Input4 7 3 1Output-1
Input2 2 1 1
Output4774
2 seconds
256 megabytes
['constructive algorithms', '*1800']
A. Lucky Conversiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types: replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4); swap any pair of digits in string a. Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.InputThe first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105.OutputPrint on the single line the single number β€” the minimum number of operations needed to convert string a into string b.ExamplesInput4774Output1Input774744Output1Input777444Output3NoteIn the first sample it is enough simply to swap the first and the second digit.In the second sample we should replace the second digit with its opposite.In the third number we should replace all three digits with their opposites.
Input4774
Output1
2 seconds
256 megabytes
['greedy', 'implementation', '*1200']
E. Competitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe secondary diagonal of a square matrix is a diagonal going from the top right to the bottom left corner. Let's define an n-degree staircase as a square matrix n × n containing no squares above the secondary diagonal (the picture below shows a 5-degree staircase). The squares of the n-degree staircase contain m sportsmen. A sportsman needs one second to move to a side-neighboring square of the staircase. Before the beginning of the competition each sportsman must choose one of the shortest ways to the secondary diagonal. After the starting whistle the competition begins and all sportsmen start moving along the chosen paths. When a sportsman reaches a cell of the secondary diagonal, he stops and moves no more. The competition ends when all sportsmen reach the secondary diagonal. The competition is considered successful if during it no two sportsmen were present in the same square simultaneously. Any square belonging to the secondary diagonal also cannot contain more than one sportsman. If a sportsman at the given moment of time leaves a square and another sportsman comes to it, then they are not considered to occupy the same square simultaneously. Note that other extreme cases (for example, two sportsmen moving towards each other) are impossible as the chosen ways are the shortest ones.You are given positions of m sportsmen on the staircase. Your task is to choose among them the maximum number of sportsmen for who the competition can be successful, that is, so that there existed such choice of shortest ways for the sportsmen at which no two sportsmen find themselves in the same square simultaneously. All other sportsmen that are not chosen will be removed from the staircase before the competition starts. InputThe first line contains two integers n and m (1 ≀ n, m ≀ 105). Then m lines contain coordinates of sportsmen on the staircase as pairs of integers ri, ci (1 ≀ ri, ci ≀ n, n - ci < ri), where ri is the number of the staircase row, ci is the number of the staircase column (to understand the principle of numbering rows and columns see the explanatory pictures). No two sportsmen stand on the same square of the staircase.OutputIn the first line print the number of the chosen sportsmen. In the second line print the numbers of chosen sportsmen in any order, separating the numbers with spaces. If there are several answers, you are permitted to print any of them. The sportsmen are numbered starting from one in the order in which they are given in the input data.ExamplesInput3 32 33 23 3Output31 2 3 NoteA note to the first sample. The picture shows a three-degree staircase. The arrows show the shortest paths that the sportsmen choose.
Input3 32 33 23 3
Output31 2 3
2 seconds
256 megabytes
['data structures', 'greedy', '*2200']
D. Missile Silostime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.InputThe first line contains three integers n, m and s (2 ≀ n ≀ 105, , 1 ≀ s ≀ n) β€” the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≀ vi, ui ≀ n, vi ≠ ui, 1 ≀ wi ≀ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≀ l ≀ 109) β€” the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads. OutputPrint the single number β€” the number of Super Duper Secret Missile Silos that are located in Berland.ExamplesInput4 6 11 2 11 3 32 3 12 4 13 4 11 4 22Output3Input5 6 33 1 13 2 13 4 13 5 11 2 64 5 84Output3NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Input4 6 11 2 11 3 32 3 12 4 13 4 11 4 22
Output3
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'shortest paths', '*1900']
C. Anagram Searchtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".You are given a string s, consisting of lowercase Latin letters and characters "?". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = Β«abaΒ», then the string "a??" is good, and the string Β«?bcΒ» is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).InputThe first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters "?". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.OutputPrint the single number representing the number of good substrings of string s.Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.ExamplesInputbb??x???aabOutput2Inputab?cacbOutput2NoteConsider the first sample test. Here the string s has two good substrings: "b??" (after we replace the question marks we get "baa"), "???" (after we replace the question marks we get "baa").Let's consider the second sample test. Here the string s has two good substrings: "ab?" ("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a").
Inputbb??x???aab
Output2
2 seconds
256 megabytes
['implementation', 'strings', '*1500']
B. Meetingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits.Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number ri β€” the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to ri, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (x1, y1) and (x2, y2) is Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place.The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.InputThe first input line contains coordinates of two opposite table corners xa, ya, xb, yb (xa ≠ xb, ya ≠ yb). The second line contains integer n β€” the number of radiators (1 ≀ n ≀ 103). Then n lines contain the heaters' coordinates as "xi yi ri", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1 ≀ ri ≀ 1000. Several radiators can be located at the same point.OutputPrint the only number β€” the number of blankets you should bring.ExamplesInput2 5 4 233 1 25 3 11 3 2Output4Input5 2 6 326 2 26 5 3Output0NoteIn the first sample the generals are sitting at points: (2, 2), (2, 3), (2, 4), (2, 5), (3, 2), (3, 5), (4, 2), (4, 3), (4, 4), (4, 5). Among them, 4 generals are located outside the heating range. They are the generals at points: (2, 5), (3, 5), (4, 4), (4, 5).In the second sample the generals are sitting at points: (5, 2), (5, 3), (6, 2), (6, 3). All of them are located inside the heating range.
Input2 5 4 233 1 25 3 11 3 2
Output4
2 seconds
256 megabytes
['implementation', '*1300']
A. Arrival of the Generaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.InputThe first input line contains the only integer n (2 ≀ n ≀ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, ..., an (1 ≀ ai ≀ 100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, ..., an are not necessarily different.OutputPrint the only integer β€” the minimum number of seconds the colonel will need to form a line-up the general will like.ExamplesInput433 44 11 22Output2Input710 10 58 31 63 40 76Output10NoteIn the first sample the colonel will need to swap the first and second soldier and then the third and fourth soldier. That will take 2 seconds. The resulting position of the soldiers is (44, 33, 22, 11).In the second sample the colonel may swap the soldiers in the following sequence: (10, 10, 58, 31, 63, 40, 76) (10, 58, 10, 31, 63, 40, 76) (10, 58, 10, 31, 63, 76, 40) (10, 58, 10, 31, 76, 63, 40) (10, 58, 31, 10, 76, 63, 40) (10, 58, 31, 76, 10, 63, 40) (10, 58, 31, 76, 63, 10, 40) (10, 58, 76, 31, 63, 10, 40) (10, 76, 58, 31, 63, 10, 40) (76, 10, 58, 31, 63, 10, 40) (76, 10, 58, 31, 63, 40, 10)
Input433 44 11 22
Output2
2 seconds
256 megabytes
['implementation', '*800']
B. Help Kingdom of Far Far Away 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer.The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows: A number contains the integer part and the fractional part. The two parts are separated with a character "." (decimal point). To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character "," (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678 In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests). When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets. Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency β€” snakes ($), that's why right before the number in the financial format we should put the sign "$". If the number should be written in the brackets, then the snake sign should also be inside the brackets. For example, by the above given rules number 2012 will be stored in the financial format as "$2,012.00" and number -12345678.9 will be stored as "($12,345,678.90)".The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?InputThe input contains a number that needs to be converted into financial format. The number's notation length does not exceed 100 characters, including (possible) signs "-" (minus) and "." (decimal point). The number's notation is correct, that is: The number's notation only contains characters from the set {"0" – "9", "-", "."}. The decimal point (if it is present) is unique and is preceded and followed by a non-zero quantity on decimal digits A number cannot start with digit 0, except for a case when its whole integer part equals zero (in this case the integer parts is guaranteed to be a single zero: "0"). The minus sign (if it is present) is unique and stands in the very beginning of the number's notation If a number is identically equal to 0 (that is, if it is written as, for example, "0" or "0.000"), than it is not preceded by the minus sign. The input data contains no spaces. The number's notation contains at least one decimal digit. OutputPrint the number given in the input in the financial format by the rules described in the problem statement.ExamplesInput2012Output$2,012.00Input0.000Output$0.00Input-0.00987654321Output($0.00)Input-12345678.9Output($12,345,678.90)NotePay attention to the second and third sample tests. They show that the sign of a number in the financial format (and consequently, the presence or absence of brackets) is determined solely by the sign of the initial number. It does not depend on the sign of the number you got after translating the number to the financial format.
Input2012
Output$2,012.00
2 seconds
256 megabytes
['implementation', 'strings', '*1200']
A. Help Vasilisa the Wise 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 × 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below. The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below. Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.InputThe input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 ≀ r1, r2, c1, c2, d1, d2 ≀ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement. OutputPrint the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).If there are several solutions, output any.ExamplesInput3 74 65 5Output1 23 4Input11 1013 85 16Output4 79 1Input1 23 45 6Output-1Input10 1010 1010 10Output-1NotePay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Input3 74 65 5
Output1 23 4
2 seconds
256 megabytes
['brute force', 'math', '*1000']
E. Help Greg the Dwarf 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGreg the Dwarf has been really busy recently with excavations by the Neverland Mountain. However for the well-known reasons (as you probably remember he is a very unusual dwarf and he cannot stand sunlight) Greg can only excavate at night. And in the morning he should be in his crypt before the first sun ray strikes. That's why he wants to find the shortest route from the excavation point to his crypt. Greg has recollected how the Codeforces participants successfully solved the problem of transporting his coffin to a crypt. So, in some miraculous way Greg appeared in your bedroom and asks you to help him in a highly persuasive manner. As usual, you didn't feel like turning him down.After some thought, you formalized the task as follows: as the Neverland mountain has a regular shape and ends with a rather sharp peak, it can be represented as a cone whose base radius equals r and whose height equals h. The graveyard where Greg is busy excavating and his crypt can be represented by two points on the cone's surface. All you've got to do is find the distance between points on the cone's surface. The task is complicated by the fact that the mountain's base on the ground level and even everything below the mountain has been dug through by gnome (one may wonder whether they've been looking for the same stuff as Greg...). So, one can consider the shortest way to pass not only along the side surface, but also along the cone's base (and in a specific case both points can lie on the cone's base β€” see the first sample test)Greg will be satisfied with the problem solution represented as the length of the shortest path between two points β€” he can find his way pretty well on his own. He gave you two hours to solve the problem and the time is ticking!InputThe first input line contains space-separated integers r and h (1 ≀ r, h ≀ 1000) β€” the base radius and the cone height correspondingly. The second and third lines contain coordinates of two points on the cone surface, groups of three space-separated real numbers. The coordinates of the points are given in the systems of coordinates where the origin of coordinates is located in the centre of the cone's base and its rotation axis matches the OZ axis. In this coordinate system the vertex of the cone is located at the point (0, 0, h), the base of the cone is a circle whose center is at the point (0, 0, 0), lying on the XOY plane, and all points on the cone surface have a non-negative coordinate z. It is guaranteed that the distances from the points to the cone surface do not exceed 10 - 12. All real numbers in the input have no more than 16 digits after decimal point.OutputPrint the length of the shortest path between the points given in the input, with absolute or relative error not exceeding 10 - 6.ExamplesInput2 21.0 0.0 0.0-1.0 0.0 0.0Output2.000000000Input2 21.0 0.0 0.01.0 0.0 1.0Output2.414213562Input2 21.0 0.0 1.0-1.0 0.0 1.0Output2.534324263Input2 21.0 0.0 0.00.0 1.0 1.0Output3.254470198
Input2 21.0 0.0 0.0-1.0 0.0 0.0
Output2.000000000
2 seconds
256 megabytes
['geometry', '*3000']
D. Help Shrek and Donkey 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHaving learned (not without some help from the Codeforces participants) to play the card game from the previous round optimally, Shrek and Donkey (as you may remember, they too live now in the Kingdom of Far Far Away) have decided to quit the boring card games and play with toy soldiers.The rules of the game are as follows: there is a battlefield, its size equals n × m squares, some squares contain the toy soldiers (the green ones belong to Shrek and the red ones belong to Donkey). Besides, each of the n lines of the area contains not more than two soldiers. During a move a players should select not less than 1 and not more than k soldiers belonging to him and make them either attack or retreat.An attack is moving all of the selected soldiers along the lines on which they stand in the direction of an enemy soldier, if he is in this line. If this line doesn't have an enemy soldier, then the selected soldier on this line can move in any direction during the player's move. Each selected soldier has to move at least by one cell. Different soldiers can move by a different number of cells. During the attack the soldiers are not allowed to cross the cells where other soldiers stand (or stood immediately before the attack). It is also not allowed to go beyond the battlefield or finish the attack in the cells, where other soldiers stand (or stood immediately before attack).A retreat is moving all of the selected soldiers along the lines on which they stand in the direction from an enemy soldier, if he is in this line. The other rules repeat the rules of the attack.For example, let's suppose that the original battlefield had the form (here symbols "G" mark Shrek's green soldiers and symbols "R" mark Donkey's red ones): -G-R--R-G- Let's suppose that k = 2 and Shrek moves first. If he decides to attack, then after his move the battlefield can look like that: --GR- --GR- -G-R--RG-- -R-G- -RG-- If in the previous example Shrek decides to retreat, then after his move the battlefield can look like that: G--R- G--R- -G-R--R--G -R-G- -R--G On the other hand, the followings fields cannot result from Shrek's correct move: G--R- ---RG --GR--RG-- -R-G- GR--- Shrek starts the game. To make a move means to attack or to retreat by the rules. A player who cannot make a move loses and his opponent is the winner. Determine the winner of the given toy soldier game if Shrek and Donkey continue to be under the yellow pills from the last rounds' problem. Thus, they always play optimally (that is, they try to win if it is possible, or finish the game in a draw, by ensuring that it lasts forever, if they cannot win).InputThe first line contains space-separated integers n, m and k (1 ≀ n, m, k ≀ 100). Then n lines contain m characters each. These characters belong to the set {"-", "G", "R"}, denoting, respectively, a battlefield's free cell, a cell occupied by Shrek's soldiers and a cell occupied by Donkey's soldiers.It is guaranteed that each line contains no more than two soldiers.OutputPrint "First" (without the quotes) if Shrek wins in the given Toy Soldier game. If Donkey wins, print "Second" (without the quotes). If the game continues forever, print "Draw" (also without the quotes).ExamplesInput2 3 1R-GRG-OutputFirstInput3 3 2G-RR-GG-ROutputSecondInput2 3 1-R--G-OutputDrawInput2 5 2-G-R--R-G-OutputFirst
Input2 3 1R-GRG-
OutputFirst
2 seconds
256 megabytes
['games', '*2600']
C. Help Caretakertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAutumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space): ### ..# .#. #...#. ### .#. ###.#. ..# ### #.. Simon faced a quite natural challenge: placing in the given n × m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse.Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?InputThe only line contains two space-separated integers n and m β€” the sizes of the warehouse (1 ≀ n, m ≀ 9).OutputIn the first line print the maximum number of turboplows that can be positioned in the warehouse. In each of the next n lines print m characters. Use "." (dot) to mark empty space and use successive capital Latin letters ("A" for the first turboplow, "B" for the second one and so on until you reach the number of turboplows in your scheme) to mark place for the corresponding turboplows considering that they are positioned in the optimal manner in the warehouse. The order in which you number places for the turboplows does not matter. If there are several optimal solutions for a warehouse of the given size, print any of them.ExamplesInput3 3Output1AAA.A..A.Input5 6Output4A..C..AAAC..ABCCCD.B.DDDBBB..DInput2 2Output0....
Input3 3
Output1AAA.A..A.
3 seconds
256 megabytes
['brute force', 'dp', '*2300']
B. Help Generaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot had a major argument with the Fairy Godmother (there were rumors that the argument occurred after the general spoke badly of the Godmother's flying techniques. That seemed to hurt the Fairy Godmother very deeply). As the result of the argument, the Godmother put a rather strange curse upon the general. It sounded all complicated and quite harmless: "If the squared distance between some two soldiers equals to 5, then those soldiers will conflict with each other!"The drill exercises are held on a rectangular n × m field, split into nm square 1 × 1 segments for each soldier. Thus, the square of the distance between the soldiers that stand on squares (x1, y1) and (x2, y2) equals exactly (x1 - x2)2 + (y1 - y2)2. Now not all nm squad soldiers can participate in the drill exercises as it was before the Fairy Godmother's curse. Unless, of course, the general wants the soldiers to fight with each other or even worse... For example, if he puts a soldier in the square (2, 2), then he cannot put soldiers in the squares (1, 4), (3, 4), (4, 1) and (4, 3) β€” each of them will conflict with the soldier in the square (2, 2).Your task is to help the general. You are given the size of the drill exercise field. You are asked to calculate the maximum number of soldiers that can be simultaneously positioned on this field, so that no two soldiers fall under the Fairy Godmother's curse.InputThe single line contains space-separated integers n and m (1 ≀ n, m ≀ 1000) that represent the size of the drill exercise field.OutputPrint the desired maximum number of warriors.ExamplesInput2 4Output4Input3 4Output6NoteIn the first sample test Sir Lancelot can place his 4 soldiers on the 2 × 4 court as follows (the soldiers' locations are marked with gray circles on the scheme): In the second sample test he can place 6 soldiers on the 3 × 4 site in the following manner:
Input2 4
Output4
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1800']
A. Help Farmertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored AΒ·BΒ·C hay blocks and stored them in a barn as a rectangular parallelepiped A layers high. Each layer had B rows and each row had C blocks.At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing (A - 1) × (B - 2) × (C - 2) hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single 1 × 1 × 1 blocks and scattered them around the barn. After the theft Sam counted n hay blocks in the barn but he forgot numbers A, B ΠΈ C.Given number n, find the minimally possible and maximally possible number of stolen hay blocks.InputThe only line contains integer n from the problem's statement (1 ≀ n ≀ 109).OutputPrint space-separated minimum and maximum number of hay blocks that could have been stolen by the thieves.Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. 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.ExamplesInput4Output28 41Input7Output47 65Input12Output48 105NoteLet's consider the first sample test. If initially Sam has a parallelepiped consisting of 32 = 2 × 4 × 4 hay blocks in his barn, then after the theft the barn has 4 = (2 - 1) × (4 - 2) × (4 - 2) hay blocks left. Thus, the thieves could have stolen 32 - 4 = 28 hay blocks. If Sam initially had a parallelepiped consisting of 45 = 5 × 3 × 3 hay blocks in his barn, then after the theft the barn has 4 = (5 - 1) × (3 - 2) × (3 - 2) hay blocks left. Thus, the thieves could have stolen 45 - 4 = 41 hay blocks. No other variants of the blocks' initial arrangement (that leave Sam with exactly 4 blocks after the theft) can permit the thieves to steal less than 28 or more than 41 blocks.
Input4
Output28 41
1 second
256 megabytes
['brute force', 'math', '*1600']
E. Clearing Uptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter Santa Claus and his assistant Elf delivered all the presents and made all the wishes come true, they returned to the North Pole and found out that it is all covered with snow. Both of them were quite tired and they decided only to remove the snow from the roads connecting huts. The North Pole has n huts connected with m roads. One can go along the roads in both directions. The Elf offered to split: Santa Claus will clear up the wide roads and the Elf will tread out the narrow roads. For each road they decided who will clear it: Santa Claus or the Elf. To minimize the efforts they decided to clear the road so as to fulfill both those conditions: between any two huts should exist exactly one simple path along the cleared roads; Santa Claus and the Elf should clear the same number of roads. At this point Santa Claus and his assistant Elf wondered which roads should they clear up?InputThe first input line contains two positive integers n and m (1 ≀ n ≀ 103, 1 ≀ m ≀ 105) β€” the number of huts and the number of roads. Then follow m lines, each of them contains a road description: the numbers of huts it connects β€” x and y (1 ≀ x, y ≀ n) and the person responsible for clearing out this road ("S" β€” for the Elf or "M" for Santa Claus). It is possible to go on each road in both directions. Note that there can be more than one road between two huts and a road can begin and end in the same hut.OutputPrint "-1" without the quotes if it is impossible to choose the roads that will be cleared by the given rule. Otherwise print in the first line how many roads should be cleared and in the second line print the numbers of those roads (the roads are numbered from 1 in the order of occurrence in the input). It is allowed to print the numbers of the roads in any order. Each number should be printed exactly once. As you print the numbers, separate them with spaces.ExamplesInput1 21 1 S1 1 MOutput0Input3 31 2 S1 3 M2 3 SOutput22 1 Input5 61 1 S1 2 M1 3 S1 4 M1 5 M2 2 SOutput-1NoteA path is called simple if all huts on it are pairwise different.
Input1 21 1 S1 1 M
Output0
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'dsu', 'graphs', '*2300']
D. Take-off Rampstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya participates in a ski race along the X axis. The start is at point 0, and the finish is at L, that is, at a distance L meters from the start in the positive direction of the axis. Vasya has been training so hard that he can run one meter in exactly one second.Besides, there are n take-off ramps on the track, each ramp is characterized by four numbers: xi represents the ramp's coordinate di represents from how many meters Vasya will land if he goes down this ramp ti represents the flight time in seconds pi is the number, indicating for how many meters Vasya should gather speed to get ready and fly off the ramp. As Vasya gathers speed, he should ski on the snow (that is, he should not be flying), but his speed still equals one meter per second. Vasya is allowed to move in any direction on the X axis, but he is prohibited to cross the start line, that is go to the negative semiaxis. Vasya himself chooses which take-off ramps he will use and in what order, that is, he is not obliged to take off from all the ramps he encounters. Specifically, Vasya can skip the ramp. It is guaranteed that xi + di ≀ L, that is, Vasya cannot cross the finish line in flight.Vasya can jump from the ramp only in the positive direction of X axis. More formally, when using the i-th ramp, Vasya starts gathering speed at point xi - pi, jumps at point xi, and lands at point xi + di. He cannot use the ramp in opposite direction.Your task is to find the minimum time that Vasya will spend to cover the distance.InputThe first line contains two integers n and L (0 ≀ n ≀ 105, 1 ≀ L ≀ 109). Then n lines contain the descriptions of the ramps, each description is on a single line. Each description is a group of four non-negative integers xi, di, ti, pi (0 ≀ xi ≀ L, 1 ≀ di, ti, pi ≀ 109, xi + di ≀ L).OutputPrint in the first line the minimum time in seconds Vasya needs to complete the track. Print in the second line k β€” the number of take-off ramps that Vasya needs to use, and print on the third line of output k numbers the number the take-off ramps Vasya used in the order in which he used them. Print each number exactly once, separate the numbers with a space. The ramps are numbered starting from 1 in the order in which they are given in the input.ExamplesInput2 205 10 5 54 16 1 7Output1511 Input2 209 8 12 615 5 1 1Output1612 NoteIn the first sample, Vasya cannot use ramp 2, because then he will need to gather speed starting from point -3, which is not permitted by the statement. The optimal option is using ramp 1, the resulting time is: moving to the point of gathering speed + gathering speed until reaching the takeoff ramp + flight time + moving to the finish line = 0 + 5 + 5 + 5 = 15.In the second sample using ramp 1 is not optimal for Vasya as t1 > d1. The optimal option is using ramp 2, the resulting time is: moving to the point of gathering speed + gathering speed until reaching the takeoff ramp + flight time + moving to the finish line = 14 + 1 + 1 + 0 = 16.
Input2 205 10 5 54 16 1 7
Output1511
4 seconds
256 megabytes
['graphs', 'shortest paths', '*2300']
C. Queuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the Main Berland Bank n people stand in a queue at the cashier, everyone knows his/her height hi, and the heights of the other people in the queue. Each of them keeps in mind number ai β€” how many people who are taller than him/her and stand in queue in front of him.After a while the cashier has a lunch break and the people in the queue seat on the chairs in the waiting room in a random order.When the lunch break was over, it turned out that nobody can remember the exact order of the people in the queue, but everyone remembers his number ai.Your task is to restore the order in which the people stood in the queue if it is possible. There may be several acceptable orders, but you need to find any of them. Also, you need to print a possible set of numbers hi β€” the heights of people in the queue, so that the numbers ai are correct.InputThe first input line contains integer n β€” the number of people in the queue (1 ≀ n ≀ 3000). Then n lines contain descriptions of the people as "namei ai" (one description on one line), where namei is a non-empty string consisting of lowercase Latin letters whose length does not exceed 10 characters (the i-th person's name), ai is an integer (0 ≀ ai ≀ n - 1), that represents the number of people who are higher and stand in the queue in front of person i. It is guaranteed that all names are different.OutputIf there's no acceptable order of the people in the queue, print the single line containing "-1" without the quotes. Otherwise, print in n lines the people as "namei hi", where hi is the integer from 1 to 109 (inclusive), the possible height of a man whose name is namei. Print the people in the order in which they stand in the queue, starting from the head of the queue and moving to its tail. Numbers hi are not necessarily unique.ExamplesInput4a 0b 2c 0d 0Outputa 150c 170d 180b 160Input4vasya 0petya 1manya 3dunay 3Output-1
Input4a 0b 2c 0d 0
Outputa 150c 170d 180b 160
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*1800']
B. Hopscotchtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSo nearly half of the winter is over and Maria is dreaming about summer. She's fed up with skates and sleds, she was dreaming about Hopscotch all night long. It's a very popular children's game. The game field, the court, looks as is shown in the figure (all blocks are square and are numbered from bottom to top, blocks in the same row are numbered from left to right). Let us describe the hopscotch with numbers that denote the number of squares in the row, staring from the lowest one: 1-1-2-1-2-1-2-(1-2)..., where then the period is repeated (1-2). The coordinate system is defined as shown in the figure. Side of all the squares are equal and have length a.Maria is a very smart and clever girl, and she is concerned with quite serious issues: if she throws a stone into a point with coordinates (x, y), then will she hit some square? If the answer is positive, you are also required to determine the number of the square.It is believed that the stone has fallen into the square if it is located strictly inside it. In other words a stone that has fallen on the square border is not considered a to hit a square.InputThe only input line contains three integers: a, x, y, where a (1 ≀ a ≀ 100) is the side of the square, x and y ( - 106 ≀ x ≀ 106, 0 ≀ y ≀ 106) are coordinates of the stone.OutputPrint the number of the square, inside which the stone fell. If the stone is on a border of some stone or outside the court, print "-1" without the quotes.ExamplesInput1 0 0Output-1Input3 1 1Output1Input3 0 10Output5Input3 0 7Output-1Input3 4 0Output-1
Input1 0 0
Output-1
2 seconds
256 megabytes
['geometry', 'math', '*1400']
A. Amusing Joketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSo, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door.The next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters.Help the "New Year and Christmas Men" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.InputThe input file consists of three lines: the first line contains the guest's name, the second line contains the name of the residence host and the third line contains letters in a pile that were found at the door in the morning. All lines are not empty and contain only uppercase Latin letters. The length of each line does not exceed 100.OutputPrint "YES" without the quotes, if the letters in the pile could be permuted to make the names of the "New Year and Christmas Men". Otherwise, print "NO" without the quotes.ExamplesInputSANTACLAUSDEDMOROZSANTAMOROZDEDCLAUSOutputYESInputPAPAINOELJOULUPUKKIJOULNAPAOILELUPUKKIOutputNOInputBABBONATALEFATHERCHRISTMASBABCHRISTMASBONATALLEFATHEROutputNONoteIn the first sample the letters written in the last line can be used to write the names and there won't be any extra letters left.In the second sample letter "P" is missing from the pile and there's an extra letter "L".In the third sample there's an extra letter "L".
InputSANTACLAUSDEDMOROZSANTAMOROZDEDCLAUS
OutputYES
2 seconds
256 megabytes
['implementation', 'sortings', 'strings', '*800']
F. New Year Snowflaketime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs Gerald ..., in other words, on a New Year Eve Constantine prepared an unusual present for the Beautiful Lady. The present is the magic New Year snowflake that can make any dream come true.The New Year snowflake consists of tiny ice crystals, which can be approximately regarded as points on the plane. The beauty of the New Year snowflake is that it has a center of symmetry. This is a point such that for each crystal of the snowflake exists another crystal, symmetrical to it relative to that point. One of the crystals can be placed directly in the center of symmetry.While Constantine was choosing a snowflake among millions of other snowflakes, no less symmetrical and no less magical, then endured a difficult path through the drifts to the house of his mistress, while he was waiting with bated breath for a few long moments before the Beautiful Lady opens the door, some of the snowflake crystals melted and naturally disappeared. Constantine is sure that there were no more than k of such crystals, because he handled the snowflake very carefully. Now he is ready to demonstrate to the Beautiful Lady all the power of nanotechnology and restore the symmetry of snowflakes.You are given the coordinates of the surviving snowflake crystals, given in nanometers. Your task is to identify all possible positions of the original center of symmetry.InputThe first line contains two integers n and k (1 ≀ n ≀ 200 000, 0 ≀ k ≀ 10) β€” the number of the surviving snowflake crystals and the maximum number of melted crystals, correspondingly. Next n lines contain the coordinates of the crystals that are left in the following form: "xi yi". The coordinates are integers and do not exceed 5Β·108 in absolute value. All given points are different.OutputThe first line contains an integer c β€” the number of possible symmetry centers. Next c lines should contain the centers' descriptions. Each symmetry center is described by a couple of coordinates "x y", separated by a space. Print the coordinates with absolute error not exceeding 10 - 6. You are allowed to print the symmetry centers in any order. All printed points should be different. If there exist an infinite number of possible symmetry centers, print the single number "-1".ExamplesInput4 00 00 11 01 1Output10.5 0.5Input4 20 00 11 01 1Output50.0 0.50.5 0.00.5 0.50.5 1.01.0 0.5Input4 40 00 11 01 1Output-1
Input4 00 00 11 01 1
Output10.5 0.5
1 second
256 megabytes
['geometry', 'sortings', '*2600']
E. New Year Garlandtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs Gerald, Alexander, Sergey and Gennady are already busy with the usual New Year chores, Edward hastily decorates the New Year Tree. And any decent New Year Tree must be decorated with a good garland. Edward has lamps of m colors and he wants to make a garland from them. That garland should represent a sequence whose length equals L. Edward's tree is n layers high and Edward plans to hang the garland so as to decorate the first layer with the first l1 lamps, the second layer β€” with the next l2 lamps and so on. The last n-th layer should be decorated with the last ln lamps, Edward adores all sorts of math puzzles, so he suddenly wondered: how many different ways to assemble the garland are there given that the both following two conditions are met: Any two lamps that follow consecutively in the same layer should have different colors. The sets of used colors in every two neighbouring layers must be different. We consider unordered sets (not multisets), where every color occurs no more than once. So the number of lamps of particular color does not matter. Help Edward find the answer to this nagging problem or else he won't manage to decorate the Tree by New Year. You may consider that Edward has an unlimited number of lamps of each of m colors and it is not obligatory to use all m colors. The garlands are considered different if they differ in at least one position when represented as sequences. Calculate the answer modulo p.InputThe first line contains three integers n, m and p (1 ≀ n, m ≀ 106, 2 ≀ p ≀ 109) which are the number of the tree's layers, the number of the lamps' colors and module correspondingly. The next line contains n integers li (1 ≀ li ≀ 5000, ).OutputPrint the only integer β€” the number of garlands modulo p.ExamplesInput3 2 10003 1 2Output8Input2 3 10002 2Output24Input1 1 10005Output0NoteIn the first sample the following variants are possible: 121|1|12, 121|1|21, 121|2|12, 121|2|21, 212|1|12, 212|1|21, 212|2|12, 212|2|21. In the second sample the following variants are possible: 12|13, 12|23, 12|31, 12|32 and so on. Figure for the first sample:
Input3 2 10003 1 2
Output8
5 seconds
256 megabytes
['combinatorics', 'dp', '*2600']
D. New Year Contesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest.The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.).Gennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the i-th problem will take ai minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the i-th problem always equals ai minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.).Help Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum.InputThe first line contains an integer n (1 ≀ n ≀ 100) β€” the number of the problems. The next line contains n space-separated integers ai (1 ≀ ai ≀ 720) β€” each number shows how much time in minutes Gennady will spend writing a solution to the problem.OutputPrint two integers β€” the number of problems Gennady will solve and the total penalty time considering that he chooses the optimal strategy.ExamplesInput330 330 720Output2 10NoteIn the sample, one of Gennady's possible optimal strategies is as follows. At 18:10 (6:10 PM) he begins to write the first problem and solves it in 30 minutes (18:40 or 6.40 P.M.). At 18:40 (6.40 P.M.) he begins to write the second problem. There are 320 minutes left before the New Year, so Gennady does not have the time to finish writing the second problem before the New Year. At 0:00 (12.00 A.M.) he distracts from the second problem, submits the first one, and returns immediately to writing the second problem. At 0:10 (0.10 A.M.), he completes the solution for the second problem, submits it and gets 10 minute penalty time. Note that as the total duration of the contest is 720 minutes and Gennady has already spent 10 minutes on reading the problems, he will not have time to solve the third problem during the contest. Yes, such problems happen to exist.Competitions by the given rules are held annually on the site http://b23.ru/3wvc
Input330 330 720
Output2 10
2 seconds
256 megabytes
['greedy', 'sortings', '*1800']
C. New Year Snowmentime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of snowballs. The next line contains n integers β€” the balls' radii r1, r2, ..., rn (1 ≀ ri ≀ 109). The balls' radii can coincide.OutputPrint on the first line a single number k β€” the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers β€” the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.ExamplesInput71 2 3 4 5 6 7Output23 2 16 5 4Input32 2 3Output0
Input71 2 3 4 5 6 7
Output23 2 16 5 4
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', '*1800']
B. New Year Cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the i-th friend sent to Alexander a card number i.Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules: He will never send to a firend a card that this friend has sent to him. Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times.Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to n. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card.Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible.Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.InputThe first line contains an integer n (2 ≀ n ≀ 300) β€” the number of Alexander's friends, equal to the number of cards. Next n lines contain his friends' preference lists. Each list consists of n different integers from 1 to n. The last line contains Alexander's preference list in the same format.OutputPrint n space-separated numbers: the i-th number should be the number of the friend, whose card Alexander receives right before he should send a card to the i-th friend. If there are several solutions, print any of them.ExamplesInput41 2 3 44 1 3 24 3 1 23 4 2 13 1 2 4Output2 1 1 4NoteIn the sample, the algorithm of actions Alexander and his friends perform is as follows: Alexander receives card 1 from the first friend. Alexander sends the card he has received (at the moment he only has one card, and therefore it is the most preferable for him) to friends with the numbers 2 and 3. Alexander receives card 2 from the second friend, now he has two cards β€” 1 and 2. Alexander sends a card to the first friend. Despite the fact that Alexander likes card 1 more, he sends card 2 as he cannot send a friend the card sent by that very friend. Alexander receives card 3 from the third friend. Alexander receives card 4 from the fourth friend. Among the cards Alexander has number 3 is his favorite and he sends it to the fourth friend. Note that Alexander can send cards to multiple friends at a time (in this case the second and the third one). Alexander can send card 3 to the fourth friend after he receives the third card or after he receives the fourth card (both variants are correct).
Input41 2 3 44 1 3 24 3 1 23 4 2 13 1 2 4
Output2 1 1 4
2 seconds
256 megabytes
['brute force', 'greedy', 'implementation', '*1800']
A. New Year Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald is setting the New Year table. The table has the form of a circle; its radius equals R. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal r. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for n plates.InputThe first line contains three integers n, R and r (1 ≀ n ≀ 100, 1 ≀ r, R ≀ 1000) β€” the number of plates, the radius of the table and the plates' radius.OutputPrint "YES" (without the quotes) if it is possible to place n plates on the table by the rules given above. If it is impossible, print "NO".Remember, that each plate must touch the edge of the table. ExamplesInput4 10 4OutputYESInput5 10 4OutputNOInput1 10 10OutputYESNoteThe possible arrangement of the plates for the first sample is:
Input4 10 4
OutputYES
2 seconds
256 megabytes
['geometry', 'math', '*1700']
B. Wallpapertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHaving bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has n rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height).Boris chose m types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type.The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely.After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.InputThe first line contains a positive integer n (1 ≀ n ≀ 500) β€” the number of rooms in Boris's apartment.Each of the next n lines contains three space-separated positive integers β€” the length, width and height of the walls in a given room in meters, respectively.The next line contains a positive integer m (1 ≀ m ≀ 500) β€” the number of available wallpaper types.Each of the following m lines contains three space-separated positive integers β€” the length and width in meters of a given wallpaper and the price of one roll, respectively.All numbers in the input data do not exceed 500. It is guaranteed that each room can be papered using these types of wallpaper.OutputPrint a single number β€” the minimum total cost of the rolls.ExamplesInput15 5 3310 1 10015 2 3203 19 500Output640NoteNote to the sample:The total length of the walls (the perimeter) of the room is 20 m.One roll of the first type can be cut into pieces to get three vertical 1 meter wide strips, ergo you need 7 rolls of this type, the price equals 700.A roll of the second type can be cut into pieces to get five 2 meter wide strips, we need 2 rolls, the price is 640.One roll of the third type can immediately paper 19 meters out of 20, but we cannot use other types and we have to buy a second roll, the price is 1000.
Input15 5 3310 1 10015 2 3203 19 500
Output640
2 seconds
256 megabytes
['implementation', 'math', '*1600']
A. Petr and Booktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages.Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Some days are so busy that Petr will have no time to read whatsoever. However, we know that he will be able to read at least one page a week.Assuming that Petr will not skip days and will read as much as he can every day, determine on which day of the week he will read the last page of the book.InputThe first input line contains the single integer n (1 ≀ n ≀ 1000) β€” the number of pages in the book.The second line contains seven non-negative space-separated integers that do not exceed 1000 β€” those integers represent how many pages Petr can read on Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday correspondingly. It is guaranteed that at least one of those numbers is larger than zero.OutputPrint a single number β€” the number of the day of the week, when Petr will finish reading the book. The days of the week are numbered starting with one in the natural order: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.ExamplesInput10015 20 20 15 10 30 45Output6Input21 0 0 0 0 0 0Output1NoteNote to the first sample:By the end of Monday and therefore, by the beginning of Tuesday Petr has 85 pages left. He has 65 pages left by Wednesday, 45 by Thursday, 30 by Friday, 20 by Saturday and on Saturday Petr finishes reading the book (and he also has time to read 10 pages of something else).Note to the second sample:On Monday of the first week Petr will read the first page. On Monday of the second week Petr will read the second page and will finish reading the book.
Input10015 20 20 15 10 30 45
Output6
2 seconds
256 megabytes
['implementation', '*1000']
E. Hellish Constraintstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKatya recently started to invent programming tasks and prepare her own contests. What she does not like is boring and simple constraints. Katya is fed up with all those "N does not exceed a thousand" and "the sum of ai does not exceed a million" and she decided to come up with something a little more complicated.The last problem written by Katya deals with strings. The input is a string of small Latin letters. To make the statement longer and strike terror into the people who will solve the contest, Katya came up with the following set of k restrictions of the same type (characters in restrictions can be repeated and some restrictions may contradict each other): The number of characters c1 in a string is not less than l1 and not more than r1. ... The number of characters ci in a string is not less than li and not more than ri. ... The number of characters ck in a string is not less than lk and not more than rk. However, having decided that it is too simple and obvious, Katya added the following condition: a string meets no less than L and not more than R constraints from the above given list.Katya does not like to compose difficult and mean tests, so she just took a big string s and wants to add to the tests all its substrings that meet the constraints. However, Katya got lost in her conditions and asked you to count the number of substrings of the string s that meet the conditions (each occurrence of the substring is counted separately).InputThe first line contains a non-empty string s, consisting of small Latin letters. The length of the string s does not exceed 105.The second line contains three space-separated integers k, L and R (0 ≀ L ≀ R ≀ k ≀ 500).Next k lines contain Katya's constrictions in the following form "ci li ri". All letters ci are small Latin letters, li and ri are integers (0 ≀ li ≀ ri ≀ |s|, where |s| is the length of string s). Letters ci are not necessarily different.OutputPrint a single number β€” the number of substrings that meet the constrictions.Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cout stream or the %I64d specificator.ExamplesInputcodeforces2 0 0o 1 2e 1 2Output7Inputcodeforces2 1 1o 1 2o 1 2Output0NoteIn the first test we should count the number of strings that do not contain characters "e" and "o". All such strings are as follows (in the order of occurrence in the initial string from the left to the right): "c", "d"', "f", "r", "rc", "c", "s".In the second test we cannot achieve fulfilling exactly one of the two identical constrictions, so the answer is 0.
Inputcodeforces2 0 0o 1 2e 1 2
Output7
3 seconds
256 megabytes
['brute force', 'dp', 'two pointers', '*2900']
D. World of Darkrafttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Roma has become the happy owner of a new game World of Darkraft. This game combines elements of virtually all known genres, and on one of the later stages of the game Roma faced difficulties solving a puzzle.In this part Roma fights with a cunning enemy magician. The battle takes place on a rectangular field plaid n × m. Each cell contains one magical character: L, R or X. Initially all the squares of the field are "active".The players, Roma and enemy magician, take turns. Roma makes the first move. During a move a player selects one of the active cells. Then depending on the image in the character in the cell one of the following actions takes place: L β€” magical waves radiate from the cell to the left downwards and to the right upwards along diagonal paths. All cells on the path of the waves (including the selected cell too) become inactive. The waves continue until the next inactive cell or to the edge of the field if there are no inactive cells on the way. R β€” the magical waves radiate to the left upwards and to the right downwards. X β€” the magical waves radiate in all four diagonal directions. If the next player cannot make a move (i.e., all cells are inactive), he loses.Roma has been trying to defeat the computer opponent for three days but he just keeps losing. He asks you to help him and determine whether it is guaranteed that he can beat the opponent, or he will have to hack the game.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 20).Next n lines contain m characters describing the playing field: the j-th character of the i-th line equals to the magical character of the corresponding field square.OutputOn the first line print "WIN" if Roma can win or "LOSE" if it is impossible to win considering that the opponent pays optimally.ExamplesInput2 2RLLROutputLOSEInput2 2RRRROutputWINNoteIn the first test each move makes one diagonal line of the square inactive, thus it is guaranteed that Roma loses after two moves.There are three variants of making a move in the second test: to "finish off" the main diagonal line or any of the squares that are left. That means that after three moves the game stops and Roma wins.
Input2 2RLLR
OutputLOSE
2 seconds
256 megabytes
['dp', 'games', '*2500']
C. Mushroom Gnomes - 2time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Natalia was walking in the woods when she met a little mushroom gnome. The gnome told her the following story:Everybody knows that the mushroom gnomes' power lies in the magic mushrooms that grow in the native woods of the gnomes. There are n trees and m magic mushrooms in the woods: the i-th tree grows at a point on a straight line with coordinates ai and has the height of hi, the j-th mushroom grows at the point with coordinates bj and has magical powers zj.But one day wild mushroommunchers, the sworn enemies of mushroom gnomes unleashed a terrible storm on their home forest. As a result, some of the trees began to fall and crush the magic mushrooms. The supreme oracle of mushroom gnomes calculated in advance the probability for each tree that it will fall to the left, to the right or will stand on. If the tree with the coordinate x and height h falls to the left, then all the mushrooms that belong to the right-open interval [x - h, x), are destroyed. If a tree falls to the right, then the mushrooms that belong to the left-open interval (x, x + h] are destroyed. Only those mushrooms that are not hit by a single tree survive.Knowing that all the trees fall independently of each other (i.e., all the events are mutually independent, and besides, the trees do not interfere with other trees falling in an arbitrary direction), the supreme oracle was also able to quickly calculate what would be the expectation of the total power of the mushrooms which survived after the storm. His calculations ultimately saved the mushroom gnomes from imminent death.Natalia, as a good Olympiad programmer, got interested in this story, and she decided to come up with a way to quickly calculate the expectation of the sum of the surviving mushrooms' power.InputThe first line contains two integers n and m (1 ≀ n ≀ 105, 1 ≀ m ≀ 104) β€” the number of trees and mushrooms, respectively.Each of the next n lines contain four integers β€” ai, hi, li, ri (|ai| ≀ 109, 1 ≀ hi ≀ 109, 0 ≀ li, ri, li + ri ≀ 100) which represent the coordinate of the i-th tree, its height, the percentage of the probabilities that the tree falls to the left and to the right, respectively (the remaining percentage is the probability that the tree will stand on).Each of next m lines contain two integers bj, zj (|bj| ≀ 109, 1 ≀ zj ≀ 103) which represent the coordinate and the magical power of the j-th mushroom, respectively.An arbitrary number of trees and mushrooms can grow in one point.OutputPrint a real number β€” the expectation of the total magical power of the surviving mushrooms. The result is accepted with relative or absolute accuracy 10 - 4.ExamplesInput1 12 2 50 501 1Output0.5000000000Input2 12 2 50 504 2 50 503 1Output0.2500000000NoteIt is believed that the mushroom with the coordinate x belongs to the right-open interval [l, r) if and only if l ≀ x < r. Similarly, the mushroom with the coordinate x belongs to the left-open interval (l, r] if and only if l < x ≀ r.In the first test the mushroom survives with the probability of 50%, depending on where the single tree falls.In the second test the mushroom survives only if neither of the two trees falls on it. It occurs with the probability of 50%  ×  50% = 25%.Pretest β„–12 is the large test with 105 trees and one mushroom.
Input1 12 2 50 501 1
Output0.5000000000
1 second
256 megabytes
['binary search', 'data structures', 'probabilities', 'sortings', '*2200']
B. Digits Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.Given number n, can you find the two digit permutations that have this property?InputThe first line contains a positive integer n β€” the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.OutputPrint two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.ExamplesInput198Output981819Input500Output500500
Input198
Output981819
1 second
256 megabytes
['greedy', '*1900']
A. Literature Lessontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.Two lines rhyme if their suffixes that start from the k-th vowels (counting from the end) match. If a line has less than k vowels, then such line can't rhyme with any other line. For example, if k = 1, lines commit and hermit rhyme (the corresponding suffixes equal it), and if k = 2, they do not rhyme (ommit ≠ ermit).Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): Clerihew (aabb); Alternating (abab); Enclosed (abba). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by aaaa).If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is aaaa. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme.Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.InputThe first line contains two integers n and k (1 ≀ n ≀ 2500, 1 ≀ k ≀ 5)Β β€” the number of quatrains in the poem and the vowel's number, correspondingly. Next 4n lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104.If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.OutputPrint the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.ExamplesInput1 1daymaysunfunOutputaabbInput1 1daymaygraywayOutputaaaaInput2 1aaaaaaeeOutputaabbInput2 1daymaysunfuntesthillfestthrillOutputNONoteIn the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
Input1 1daymaysunfun
Outputaabb
2 seconds
256 megabytes
['implementation', '*1600']
E. Last Chancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHaving read half of the book called "Storm and Calm" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Innocentius suggested the algorithm of solving equations of the fifth degree in the general case, Ms. Watkins had no other choice but to give him a new task.The teacher asked to write consecutively (without spaces) all words from the "Storm and Calm" in one long string s. She thought that a string is good if the number of vowels in the string is no more than twice more than the number of consonants. That is, the string with v vowels and c consonants is good if and only if v ≀ 2c.The task Innocentius had to solve turned out to be rather simple: he should find the number of the longest good substrings of the string s.InputThe only input line contains a non-empty string s consisting of no more than 2Β·105 uppercase and lowercase Latin letters. We shall regard letters "a", "e", "i", "o", "u" and their uppercase variants as vowels.OutputPrint on a single line two numbers without a space: the maximum length of a good substring and the number of good substrings with this length. If no good substring exists, print "No solution" without the quotes.Two substrings are considered different if their positions of occurrence are different. So if some string occurs more than once, then it should be counted more than once.ExamplesInputAboOutput3 1InputOEISOutput3 1InputauBAAbeeliiOutput9 3InputAaaBRAaaCAaaDAaaBRAaaOutput18 4InputEAOutputNo solutionNoteIn the first sample there is only one longest good substring: "Abo" itself. The other good substrings are "b", "Ab", "bo", but these substrings have shorter length.In the second sample there is only one longest good substring: "EIS". The other good substrings are: "S", "IS".
InputAbo
Output3 1
2 seconds
256 megabytes
['data structures', 'implementation', 'strings', '*2000']
D. Palindromestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFriday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite game Fur2 and didn't have enough time to do the literature task. As Innocentius didn't want to get an F, he decided to do the task and read the book called "Storm and Calm" during the IT and Math lessons (he never used to have problems with these subjects). When the IT teacher Mr. Watkins saw this, he decided to give Innocentius another task so that the boy concentrated more on the lesson and less β€” on the staff that has nothing to do with IT. Mr. Watkins said that a palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. A concatenation of strings a, b is a string ab that results from consecutive adding of string b to string a. Of course, Innocentius knew it all but the task was much harder than he could have imagined. Mr. Watkins asked change in the "Storm and Calm" the minimum number of characters so that the text of the book would also be a concatenation of no more than k palindromes. Innocentius can't complete the task and therefore asks you to help him.InputThe first input line contains a non-empty string s which is the text of "Storm and Calm" (without spaces). The length of the string s does not exceed 500 characters. String s consists of uppercase and lowercase Latin letters. The second line contains a single number k (1 ≀ k ≀ |s|, where |s| represents the length of the string s).OutputPrint on the first line the minimum number of changes that Innocentius will have to make. Print on the second line the string consisting of no more than k palindromes. Each palindrome should be non-empty and consist of uppercase and lowercase Latin letters. Use the character "+" (ASCII-code 43) to separate consecutive palindromes. If there exist several solutions, print any of them.The letters' case does matter, that is an uppercase letter is not considered equivalent to the corresponding lowercase letter.ExamplesInputabacaba1Output0abacabaInputabdcaba2Output1abdcdbaInputabdcaba5Output0a+b+d+c+abaInputabacababababbcbabcd3Output1abacaba+babab+bcbabcb
Inputabacaba1
Output0abacaba
2 seconds
256 megabytes
['dp', 'strings', '*1900']
C. Historytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.Everybody knows that the World history encompasses exactly n events: the i-th event had continued from the year ai to the year bi inclusive (ai < bi). Polycarpus easily learned the dates when each of n events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event j includes an event i if aj < ai and bi < bj. Your task is simpler: find the number of events that are included in some other event.InputThe first input line contains integer n (1 ≀ n ≀ 105) which represents the number of events. Next n lines contain descriptions of the historical events, one event per line. The i + 1 line contains two integers ai and bi (1 ≀ ai < bi ≀ 109) β€” the beginning and the end of the i-th event. No two events start or finish in the same year, that is, ai ≠ aj, ai ≠ bj, bi ≠ aj, bi ≠ bj for all i, j (where i ≠ j). Events are given in arbitrary order.OutputPrint the only integer β€” the answer to the problem.ExamplesInput51 102 93 84 75 6Output4Input51 1002 5051 9952 9810 60Output4Input11 1000000000Output0NoteIn the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third β€” in the second and the second β€” in the first.In the second example all events except the first one are contained in the first.In the third example only one event, so the answer is 0.
Input51 102 93 84 75 6
Output4
2 seconds
256 megabytes
['sortings', '*1500']
B. Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output"Hey, it's homework time" β€” thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).InputThe first line of the input data contains an integer n (1 ≀ n ≀ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≀ ai ≀ 5000, 1 ≀ i ≀ n).OutputPrint the only number β€” the minimum number of changes needed to get the permutation.ExamplesInput33 1 2Output0Input22 2Output1Input55 3 3 3 1Output2NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.
Input33 1 2
Output0
2 seconds
256 megabytes
['greedy', '*1000']
A. Postcards and photostime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put all the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?InputThe only line of the input data contains a non-empty string consisting of letters "Π‘" and "P" whose length does not exceed 100 characters. If the i-th character in the string is the letter "Π‘", that means that the i-th object (the numbering goes from the left to the right) on Polycarpus' wall is a postcard. And if the i-th character is the letter "P", than the i-th object on the wall is a photo.OutputPrint the only number β€” the minimum number of times Polycarpus has to visit the closet.ExamplesInputCPCPCPCOutput7InputCCCCCCPPPPPPOutput4InputCCCCCCPPCPPPPPPPPPPOutput6InputCCCCCCCCCCOutput2NoteIn the first sample Polycarpus needs to take one item to the closet 7 times.In the second sample Polycarpus can first take 3 postcards to the closet; then 3 more. He can take the 6 photos that are left in the similar way, going to the closet twice.In the third sample Polycarpus can visit the closet twice, both times carrying 3 postcards. Then he can take there 2 photos at once, then one postcard and finally, he can carry the last 10 photos if he visits the closet twice.In the fourth sample Polycarpus can visit the closet twice and take there all 10 postcards (5 items during each go).
InputCPCPCPC
Output7
2 seconds
256 megabytes
['implementation', '*900']
B. Ternary Logictime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the xor operation is performed on this computer (and whether there is anything like it).It turned out that the operation does exist (however, it is called tor) and it works like this. Suppose that we need to calculate the value of the expression a tor b. Both numbers a and b are written in the ternary notation one under the other one (b under a). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren't transferred). For example: 1410 tor 5010 = 01123 tor 12123 = 10213 = 3410.Petya wrote numbers a and c on a piece of paper. Help him find such number b, that a tor b = c. If there are several such numbers, print the smallest one.InputThe first line contains two integers a and c (0 ≀ a, c ≀ 109). Both numbers are written in decimal notation.OutputPrint the single integer b, such that a tor b = c. If there are several possible numbers b, print the smallest one. You should print the number in decimal notation.ExamplesInput14 34Output50Input50 34Output14Input387420489 225159023Output1000000001Input5 5Output0
Input14 34
Output50
2 seconds
256 megabytes
['implementation', 'math', '*1100']
A. Presentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.InputThe first line contains one integer n (1 ≀ n ≀ 100) β€” the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi β€” the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.OutputPrint n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.ExamplesInput42 3 4 1Output4 1 2 3Input31 3 2Output1 3 2Input21 2Output1 2
Input42 3 4 1
Output4 1 2 3
2 seconds
256 megabytes
['implementation', '*800']
E. Weak Subsequencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya very much likes strings. Recently he has received a voucher to purchase a string as a gift from his mother. The string can be bought in the local shop. One can consider that the shop has all sorts of strings over the alphabet of fixed size. The size of the alphabet is equal to k. However, the voucher has a string type limitation: specifically, the voucher can be used to purchase string s if the length of string's longest substring that is also its weak subsequence (see the definition given below) equals w.String a with the length of n is considered the weak subsequence of the string s with the length of m, if there exists such a set of indexes 1 ≀ i1 < i2 < ... < in ≀ m, that has the following two properties: ak = sik for all k from 1 to n; there exists at least one such k (1 ≀ k < n), for which ik + 1 – ik > 1. Petya got interested how many different strings are available for him to purchase in the shop. As the number of strings can be very large, please find it modulo 1000000007 (109 + 7). If there are infinitely many such strings, print "-1".InputThe first line contains two integers k (1 ≀ k ≀ 106) and w (2 ≀ w ≀ 109) β€” the alphabet size and the required length of the maximum substring that also is the weak subsequence, correspondingly.OutputPrint a single number β€” the number of strings Petya can buy using the voucher, modulo 1000000007 (109 + 7). If there are infinitely many such strings, print "-1" (without the quotes).ExamplesInput2 2Output10Input3 5Output1593Input2 139Output717248223NoteIn the first sample Petya can buy the following strings: aaa, aab, abab, abb, abba, baa, baab, baba, bba, bbb.
Input2 2
Output10
3 seconds
256 megabytes
['combinatorics', '*3000']
D. Cycletime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1".OutputPrint a single number β€” the length of the longest cool cycle in the table. If such cycles do not exist, print 0.ExamplesInput3 3111101111Output8Input5 50101010101010101010101010Output0Input7 71111111100010110001011000101100011110000011111111Output24Input5 51111110001101011000111111Output0NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle.
Input3 3111101111
Output8
3 seconds
256 megabytes
['brute force', 'dfs and similar', 'implementation', '*2500']
C. Zero-Onetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him.Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01010101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 0100101. The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it.An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.InputThe first line contains a sequence of characters each of which can either be a "0", a "1" or a "?". This sequence determines the initial arrangement of cards on the table from the left to the right. The characters "?" mean that the given card was spoiled before the game. The sequence's length ranges from 2 to 105, inclusive.OutputPrint the set of outcomes for all possible initial digits arrangements. Print each possible outcome on a single line. Each outcome should be represented by two characters: the digits written on the cards that were left by the end of the game. The outcomes should be sorted lexicographically in ascending order (see the first sample).ExamplesInput????Output00011011Input1010Output10Input1?1Output0111NoteIn the first sample all 16 variants of numbers arrangement are possible. For the variant 0000 the outcome is 00. For the variant 1111 the outcome is 11. For the variant 0011 the outcome is 01. For the variant 1100 the outcome is 10. Regardless of outcomes for all other variants the set which we are looking for will contain all 4 possible outcomes.In the third sample only 2 variants of numbers arrangement are possible: 111 and 101. For the variant 111 the outcome is 11. For the variant 101 the outcome is 01, because on the first turn Masha can remove the first card from the left after which the game will end.
Input????
Output00011011
2 seconds
256 megabytes
['constructive algorithms', 'games', 'greedy', '*1900']
B. Rectangle and Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.InputYou are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.OutputPrint in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct.If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.ExamplesInput0 010 1110 00 111 12 22 11 2OutputYES5 6 7 81 2 3 4Input0 01 12 23 34 45 56 67 7OutputNOInput0 04 44 00 41 22 33 22 1OutputYES1 2 3 45 6 7 8NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
Input0 010 1110 00 111 12 22 11 2
OutputYES5 6 7 81 2 3 4
2 seconds
256 megabytes
['brute force', 'geometry', 'math', '*1600']
A. Replacementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.InputThe first line contains a single integer n (1 ≀ n ≀ 105), which represents how many numbers the array has. The next line contains n space-separated integers β€” the array's description. All elements of the array lie in the range from 1 to 109, inclusive.OutputPrint n space-separated integers β€” the minimum possible values of each array element after one replacement and the sorting are performed.ExamplesInput51 2 3 4 5Output1 1 2 3 4Input52 3 4 5 6Output1 2 3 4 5Input32 2 2Output1 2 2
Input51 2 3 4 5
Output1 1 2 3 4
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*1300']
C. Swapstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n players sitting at a round table. All of them have s cards of n colors in total. Besides, initially the first person had cards of only the first color, the second one had cards of only the second color and so on. They can swap the cards by the following rules: as the players swap, a player can give a card of his color only; a player can't accept a card of a color he already has (particularly, he can't take cards of his color, no matter whether he has given out all of them or not); during one swap a pair of people swaps cards (each person gives one card and takes one card). The aim of all n people is as follows: each of them should give out all the cards he had initially (that is, all cards of his color). Your task is to denote whether such sequence of swaps is possible. If the answer is positive, you should list all the swaps.InputThe first line contains integers n (1 ≀ n ≀ 200000) and s (1 ≀ s ≀ 200000). The second line contains n numbers, the i-th number stands for how many cards the i-th player has by the moment the game starts. It is possible that a player has no cards initially.OutputOn the first line print "No" if such sequence of swaps is impossible. Otherwise, print "Yes". If the answer is positive, next print number k β€” the number of the swaps. Then on k lines describe the swaps by pairs of indices of the swapping players. Print the swaps and the numbers of the swaps in any order.ExamplesInput4 82 2 2 2OutputYes44 34 21 31 2Input6 121 1 2 2 3 3OutputYes66 56 46 35 45 32 1Input5 50 0 0 0 5OutputNo
Input4 82 2 2 2
OutputYes44 34 21 31 2
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'greedy', '*2200']
B. Pairs of Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.InputThe input contains the only integer n (1 ≀ n ≀ 106).OutputPrint the only integer k.ExamplesInput5Output3Input1Output0NoteThe pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1)  →  (1,2)  →  (3,2)  →  (5,2).
Input5
Output3
1 second
256 megabytes
['brute force', 'dfs and similar', 'math', 'number theory', '*1900']
A. Average Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).InputThe first line contains the integer n (2 ≀ n ≀ 2Β·105). The second line contains elements of the sequence a1, a2, ..., an (1 ≀ ai ≀ 1000). All the elements are positive integers.OutputPrint on the first line the number of the sought indices. Print on the second line the sought indices in the increasing order. All indices are integers from 1 to n.If the sought elements do not exist, then the first output line should contain number 0. In this case you may either not print the second line or print an empty line.ExamplesInput51 2 3 4 5Output13 Input450 50 50 50Output41 2 3 4
Input51 2 3 4 5
Output13
1 second
256 megabytes
['brute force', 'implementation', '*1200']
B. Unarytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUnary is a minimalistic Brainfuck dialect in which programs are written using only one token. Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm. First, replace each command with a corresponding binary code, using the following conversion table: ">"  →  1000, "<"  →  1001, "+"  →  1010, "-"  →  1011, "."  →  1100, ","  →  1101, "["  →  1110, "]"  →  1111. Next, concatenate the resulting binary codes into one binary number in the same order as in the program. Finally, write this number using unary numeral system β€” this is the Unary program equivalent to the original Brainfuck one.You are given a Brainfuck program. Your task is to calculate the size of the equivalent Unary program, and print it modulo 1000003 (106 + 3).InputThe input will consist of a single line p which gives a Brainfuck program. String p will contain between 1 and 100 characters, inclusive. Each character of p will be "+", "-", "[", "]", "<", ">", "." or ",".OutputOutput the size of the equivalent Unary program modulo 1000003 (106 + 3).ExamplesInput,.Output220Input++++[>,.<-]Output61425NoteTo write a number n in unary numeral system, one simply has to write 1 n times. For example, 5 written in unary system will be 11111.In the first example replacing Brainfuck commands with binary code will give us 1101 1100. After we concatenate the codes, we'll get 11011100 in binary system, or 220 in decimal. That's exactly the number of tokens in the equivalent Unary program.
Input,.
Output220
2 seconds
256 megabytes
['implementation', '*1200']
A. HQ9+time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHQ9+ is a joke programming language which has only four one-character instructions: "H" prints "Hello, World!", "Q" prints the source code of the program itself, "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.ExamplesInputHi!OutputYESInputCodeforcesOutputNONoteIn 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.
InputHi!
OutputYES
2 seconds
256 megabytes
['implementation', '*900']
E. Bits of merry old Englandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnother feature of Shakespeare language is that the variables are named after characters of plays by Shakespeare, and all operations on them (value assignment, output etc.) look like a dialog with other characters. New values of variables are defined in a rather lengthy way, so a programmer should try to minimize their usage.You have to print the given sequence of n integers. To do this, you have m variables and two types of operations on them: variable=integer print(variable) Any of the m variables can be used as variable. Variables are denoted by lowercase letters between "a" and "z", inclusive. Any integer number can be used as integer.Let's say that the penalty for using first type of operations equals to the number of set bits in the number integer. There is no penalty on using second type of operations. Find and output the program which minimizes the penalty for printing the given sequence of numbers.InputThe first line of input contains integers n and m (1 ≀ n ≀ 250, 1 ≀ m ≀ 26). The second line contains the sequence to be printed. Each element of the sequence is an integer between 1 and 109, inclusive. The sequence has to be printed in the given order (from left to right).OutputOutput the number of lines in the optimal program and the optimal penalty. Next, output the program itself, one command per line. If there are several programs with minimal penalty, output any of them (you have only to minimize the penalty).ExamplesInput7 21 2 2 4 2 1 2Output11 4b=1print(b)a=2print(a)print(a)b=4print(b)print(a)b=1print(b)print(a)Input6 31 2 3 1 2 3Output9 4c=1print(c)b=2print(b)a=3print(a)print(c)print(b)print(a)
Input7 21 2 2 4 2 1 2
Output11 4b=1print(b)a=2print(a)print(a)b=4print(b)print(a)b=1print(b)print(a)
2 seconds
256 megabytes
['flows', 'graphs', '*2700']
D. Constants in the language of Shakespearetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputShakespeare is a widely known esoteric programming language in which programs look like plays by Shakespeare, and numbers are given by combinations of ornate epithets. In this problem we will have a closer look at the way the numbers are described in Shakespeare.Each constant in Shakespeare is created from non-negative powers of 2 using arithmetic operations. For simplicity we'll allow only addition and subtraction and will look for a representation of the given number which requires a minimal number of operations.You are given an integer n. You have to represent it as n = a1 + a2 + ... + am, where each of ai is a non-negative power of 2, possibly multiplied by -1. Find a representation which minimizes the value of m.InputThe only line of input contains a positive integer n, written as its binary notation. The length of the notation is at most 106. The first digit of the notation is guaranteed to be 1.OutputOutput the required minimal m. After it output m lines. Each line has to be formatted as "+2^x" or "-2^x", where x is the power coefficient of the corresponding term. The order of the lines doesn't matter.ExamplesInput1111Output2+2^4-2^0Input1010011Output4+2^0+2^1+2^4+2^6
Input1111
Output2+2^4-2^0
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*2100']
C. Logo Turtletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward").You are given a list of commands that will be given to the turtle. You have to change exactly n commands from the list (one command can be changed several times). How far from the starting point can the turtle move after it follows all the commands of the modified list?InputThe first line of input contains a string commands β€” the original list of commands. The string commands contains between 1 and 100 characters, inclusive, and contains only characters "T" and "F".The second line contains an integer n (1 ≀ n ≀ 50) β€” the number of commands you have to change in the list.OutputOutput the maximum distance from the starting point to the ending point of the turtle's path. The ending point of the turtle's path is turtle's coordinate after it follows all the commands of the modified list.ExamplesInputFT1Output2InputFFFTFFF2Output6NoteIn the first example the best option is to change the second command ("T") to "F" β€” this way the turtle will cover a distance of 2 units.In the second example you have to change two commands. One of the ways to cover maximal distance of 6 units is to change the fourth command and first or last one.
InputFT1
Output2
2 seconds
256 megabytes
['dp', '*1800']
B. Piettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPiet is one of the most known visual esoteric programming languages. The programs in Piet are constructed from colorful blocks of pixels and interpreted using pretty complicated rules. In this problem we will use a subset of Piet language with simplified rules.The program will be a rectangular image consisting of colored and black pixels. The color of each pixel will be given by an integer number between 0 and 9, inclusive, with 0 denoting black. A block of pixels is defined as a rectangle of pixels of the same color (not black). It is guaranteed that all connected groups of colored pixels of the same color will form rectangular blocks. Groups of black pixels can form arbitrary shapes.The program is interpreted using movement of instruction pointer (IP) which consists of three parts: current block pointer (BP); note that there is no concept of current pixel within the block; direction pointer (DP) which can point left, right, up or down; block chooser (CP) which can point to the left or to the right from the direction given by DP; in absolute values CP can differ from DP by 90 degrees counterclockwise or clockwise, respectively.Initially BP points to the block which contains the top-left corner of the program, DP points to the right, and CP points to the left (see the orange square on the image below).One step of program interpretation changes the state of IP in a following way. The interpreter finds the furthest edge of the current color block in the direction of the DP. From all pixels that form this edge, the interpreter selects the furthest one in the direction of CP. After this, BP attempts to move from this pixel into the next one in the direction of DP. If the next pixel belongs to a colored block, this block becomes the current one, and two other parts of IP stay the same. It the next pixel is black or outside of the program, BP stays the same but two other parts of IP change. If CP was pointing to the left, now it points to the right, and DP stays the same. If CP was pointing to the right, now it points to the left, and DP is rotated 90 degrees clockwise.This way BP will never point to a black block (it is guaranteed that top-left pixel of the program will not be black).You are given a Piet program. You have to figure out which block of the program will be current after n steps.InputThe first line of the input contains two integer numbers m (1 ≀ m ≀ 50) and n (1 ≀ n ≀ 5Β·107). Next m lines contain the rows of the program. All the lines have the same length between 1 and 50 pixels, and consist of characters 0-9. The first character of the first line will not be equal to 0.OutputOutput the color of the block which will be current after n steps of program interpretation.ExamplesInput2 101243Output1Input3 12142366246625Output6Input5 91034523456345674567856789Output5NoteIn the first example IP changes in the following way. After step 1 block 2 becomes current one and stays it after two more steps. After step 4 BP moves to block 3, after step 7 β€” to block 4, and finally after step 10 BP returns to block 1. The sequence of states of IP is shown on the image: the arrows are traversed clockwise, the main arrow shows direction of DP, the side one β€” the direction of CP.
Input2 101243
Output1
2 seconds
256 megabytes
['implementation', '*2100']