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
I. Sort the Tabletime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a rectangular table containing words. Each of its columns has its own name. You are also given the list of rules of sorting in form "FIELD_NAME SORT_ORDER", where SORT_ORDER is either ASC (nondescending order) or DESC (nonascending order). Rules in the list are separated by a single comma with a single space. You have to sort rows of the table primarily by the first rule, then, in case of a tie sort by the second rule. And so on. If two rows are equal in terms of every rule, then preserve their relative order. You can assume that each element of the table has type "string", so you have to use lexicographic comparison.InputThe first line contains column names. The second line contains the list of rules. The rest of the input data contains the table. All the words and column names are separated by single spaces. The number of rows and columns is between 1 and 100, inclusive. Names of columns and elements are strings containing only uppercase and lowercase Latin letters and digits, having the length between 1 and 10, inclusive.OutputPrint the table after the sorting.ExamplesInputNAME GROUP AGEGROUP ASC, AGE DESCAlex 412 19Peter 422 19Sergey 412 18Andrey 311 18OutputAndrey 311 18Alex 412 19Sergey 412 18Peter 422 19
InputNAME GROUP AGEGROUP ASC, AGE DESCAlex 412 19Peter 422 19Sergey 412 18Andrey 311 18
OutputAndrey 311 18Alex 412 19Sergey 412 18Peter 422 19
2 seconds
64 megabytes
['*special problem', 'sortings', '*2400']
H. Table Bowlingtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputTable bowling tournament participant completed the competition according to the given final standings table. The table is given as a sequence of lines, each line has a format "name score". Your task is to prepare another table consisting of lines in the form "place name". Sort participant by score (desc.) and by the name lexicographically in the case of a tie. Places are numerated from 1. If more than one participant has some score, all of them share the places and you should output something like "12-14 john".Please, look into the samples for clarification.InputThe first line contains n (1 ≤ n ≤ 100) — the number of rows in the table. Following n lines contain the given table. Each line has the form "name score", where "name" is a sequence of lowercase Latin letters, and "score" — is an integer number between 0 and 1000, inclusive. All the names are distinct. The length of each name is between 1 and 10 characters, inclusive. There is single space between the name and the score in each line.OutputPrint the required table. Look at the sample outputs for clarifications.ExamplesInput5vasya 10ted 11petya 10katya 33mike 44Output1 mike2 katya3 ted4-5 petya4-5 vasyaInput3a 1b 13c 1Output1 b2-3 a2-3 c
Input5vasya 10ted 11petya 10katya 33mike 44
Output1 mike2 katya3 ted4-5 petya4-5 vasya
2 seconds
64 megabytes
['*special problem', 'sortings', '*2300']
G. Path Canonizationtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputA path in some Unix-similar file system is given. The path consists of elements separated with characters "/". For example: "/usr/share/mysql/../tomcat6/conf/server.xml". The path starts with the root directory (i.e. starts with the character "/"). Each element means a name of file or directory, or it is one of two special elements: "." или "..". First of them stands for the current directory (for example, path "/./usr/././share" is equal to "/usr/share"). The second element ".." stands for the moving to the parent directory (for example, path "/usr/share/../lib" is equal to "/usr/lib").You task is to convert the given path to such a path, which doesn't contain special elements "." and/or "..". If it is impossible, print "-1". The only reason for it is an attempt to move to the parent directory from the root.InputThe only line contains the given path. The path starts with "/" and consists of elements separated with "/". No two "/" follow one after another (consecutively). The only path which can end with "/" is the root directory path equal to "/".Each element may contain "a"-"z", "0"-"9" and dots. Any element different from specials "." and ".." contains at least one character different from the dots.The path length is between 1 and 1000 inclusively.OutputPrint the required path or "-1".ExamplesInput/usr/share/mysql/../tomcat6/conf/server.xmlOutput/usr/share/tomcat6/conf/server.xmlInput/a/./././..Output/
Input/usr/share/mysql/../tomcat6/conf/server.xml
Output/usr/share/tomcat6/conf/server.xml
2 seconds
64 megabytes
['*special problem', '*2200']
F. Domaintime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThis problem doesn't contain real-world specifications about domains, just use the problem statement as a formal document to solve the problem.The given string s is a domain name if it contains the characters "a"-"z", "0"-"9" and dots. No two dots shoud follow one after another (consecutive). The dots split the given string s into the parts, the last (most right) part should have the length 2 or 3. Domain can't start or end with a dot.You are given the string s, check if it is domain name.InputThe only line of the input contains given string s. The string may contain any characters with ASCII codes from 33 to 127, inclusive. The string length is between 1 and 100, inclusive.OutputPrint "YES" if the given string s is a domain name, or print "NO" if it is not.ExamplesInputcodeforces.comOutputYESInputmail.v-kontakte.ruOutputNO
Inputcodeforces.com
OutputYES
2 seconds
64 megabytes
['*special problem', 'expression parsing', '*2000']
E. Prime Segmenttime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputPositive integer number x is called prime, if it has exactly two positive integer divisors. For example, 2, 3, 17, 97 are primes, but 1, 10, 120 are not.You are given an integer number n, find the shortest segment [a, b], which contains n (i.e. a ≤ n ≤ b) and a, b are primes.InputThe only given line contains an integer number n (2 ≤ n ≤ 10000).OutputPrint the space separated pair of the required numbers a, b.ExamplesInput10Output7 11Input97Output97 97
Input10
Output7 11
2 seconds
64 megabytes
['*special problem', 'brute force', 'math', 'number theory', '*1800']
D. Presentstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given the prices of three presents. Also there are three sisters. It is known that the most valuable present is for the eldest sister. The second (by price) is for the second sister. And the less valuable present is for the youngest sister. If two (or three) presents have the same price, corresponding sisters may get the in a random way.InputThe only line contains three integer numbers a1, a2, a3 (1 ≤ a1, a2, a3 ≤ 100) — the prices of the presents.OutputPrint three numbers i1, i2, i3 (1 ≤ i1, i2, i3 ≤ 3), all of them should be distinct. The first number stands for the seniority of the sister which will get the first present (1 stands for the eldest, 3 for the youngest). The second and third numbers mean the seniority of the sisters which get the second and the third present respectively.If there are multiple answers, print any of them.ExamplesInput11 13 1Output2 1 3 Input30 10 30Output1 3 2 NoteIn the second sample another possible answer is "2 3 1".
Input11 13 1
Output2 1 3
2 seconds
64 megabytes
['*special problem', 'greedy', '*1800']
C. Tabletime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe integer numbers from 1 to nm was put into rectangular table having n rows and m columns. The numbers was put from left to right, from top to bottom, i.e. the first row contains integers 1, 2, ..., m, the second — m + 1, m + 2, ..., 2 * m and so on.After it these numbers was written on the paper in another order: from top to bottom, from left to right. First, the numbers in the first column was written (from top to bottom) and so on.Print the k-th number on the paper.InputThe only line in the input contains three integer numbers n, m and k (1 ≤ n, m ≤ 20000, 1 ≤ k ≤ nm).OutputPrint the required number.ExamplesInput3 4 11Output8Input20000 10000 200000000Output200000000
Input3 4 11
Output8
2 seconds
64 megabytes
['*special problem', 'greedy', 'implementation', 'math', '*1600']
B. Expressiontime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a line «n#m», where «n» and «m» are digits, and «#» is a sign «+» or «-». Print the value of the given expression.InputThe only given line has a string in form «n#m», where «n» and «m» are digits (from 0 to 9), and «#» is a sign «+» or «-».OutputPrint the value of the given expression.ExamplesInput1-5Output-4
Input1-5
Output-4
2 seconds
64 megabytes
['*special problem', 'expression parsing', '*1500']
A. Factorialtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputPrint the factorial of the given integer number n. The factorial of n is equal to 1·2·...·n.InputThe only line contains n (1 ≤ n ≤ 10).OutputPrint the factorial of n.ExamplesInput3Output6Input5Output120
Input3
Output6
2 seconds
64 megabytes
['*special problem', 'implementation', '*1300']
E. Sweets Gametime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKarlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake as a reward.The box of chocolates has the form of a hexagon. It contains 19 cells for the chocolates, some of which contain a chocolate. The players move in turns. During one move it is allowed to eat one or several chocolates that lay in the neighboring cells on one line, parallel to one of the box's sides. The picture below shows the examples of allowed moves and of an unacceptable one. The player who cannot make a move loses. Karlsson makes the first move as he is Lillebror's guest and not vice versa. The players play optimally. Determine who will get the cake.InputThe input data contains 5 lines, containing 19 words consisting of one symbol. The word "O" means that the cell contains a chocolate and a "." stands for an empty cell. It is guaranteed that the box contains at least one chocolate. See the examples for better understanding.OutputIf Karlsson gets the cake, print "Karlsson" (without the quotes), otherwise print "Lillebror" (yet again without the quotes).ExamplesInput . . . . . O .. . O O . . . . . . . .OutputLillebrorInput . . . . . . O. . . O . O . O . . O .OutputKarlsson
Input . . . . . O .. . O O . . . . . . . .
OutputLillebror
3 seconds
256 megabytes
['bitmasks', 'dfs and similar', 'dp', 'games', 'implementation', '*2000']
D. Dividing Islandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA revolution took place on the Buka Island. New government replaced the old one. The new government includes n parties and each of them is entitled to some part of the island according to their contribution to the revolution. However, they can't divide the island.The island can be conventionally represented as two rectangles a × b and c × d unit squares in size correspondingly. The rectangles are located close to each other. At that, one of the sides with the length of a and one of the sides with the length of c lie on one line. You can see this in more details on the picture. The i-th party is entitled to a part of the island equal to xi unit squares. Every such part should fully cover several squares of the island (it is not allowed to cover the squares partially) and be a connected figure. A "connected figure" presupposes that from any square of this party one can move to any other square of the same party moving through edge-adjacent squares also belonging to that party.Your task is to divide the island between parties.InputThe first line contains 5 space-separated integers — a, b, c, d and n (1 ≤ a, b, c, d ≤ 50, b ≠ d, 1 ≤ n ≤ 26). The second line contains n space-separated numbers. The i-th of them is equal to number xi (1 ≤ xi ≤ a × b + c × d). It is guaranteed that .OutputIf dividing the island between parties in the required manner is impossible, print "NO" (without the quotes). Otherwise, print "YES" (also without the quotes) and, starting from the next line, print max(b, d) lines each containing a + c characters. To mark what square should belong to what party, use lowercase Latin letters. For the party that is first in order in the input data, use "a", for the second one use "b" and so on. Use "." for the squares that belong to the sea. The first symbol of the second line of the output data should correspond to the square that belongs to the rectangle a × b. The last symbol of the second line should correspond to the square that belongs to the rectangle c × d.If there are several solutions output any.ExamplesInput3 4 2 2 35 8 3OutputYESaaabbaabbbcbb..ccb..Input3 2 1 4 41 2 3 4OutputYESabbdcccd...d...d
Input3 4 2 2 35 8 3
OutputYESaaabbaabbbcbb..ccb..
2 seconds
256 megabytes
['constructive algorithms', '*1900']
C. Bulls and Cowstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it.The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "x bulls y cows". x represents the number of digits in the experimental number that occupy the same positions as in the sought number. y represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present.For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one). When the guesser is answered "4 bulls 0 cows", the game is over.Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.InputThe first input line contains an integer n (1 ≤ n ≤ 10) which represents the number of already made guesses. Then follow n lines in the form of "ai bi ci", where ai is the i-th experimental number, bi is the number of bulls, ci is the number of cows (1 ≤ i ≤ n, 0 ≤ bi, ci, bi + ci ≤ 4). The experimental numbers are correct, i.e., each of them contains exactly four digits, in each of them all the four digits are different, and there can be a leading zero. All the experimental numbers are different. As the guesser hasn't guessed the number yet, the answer "4 bulls 0 cows" is not present.OutputIf the input data is enough to determine the sought number, print the number with four digits on a single line. If it has less than four digits, add leading zero. If the data is not enough, print "Need more data" without the quotes. If the thinker happens to have made a mistake in his replies, print "Incorrect data" without the quotes.ExamplesInput21263 1 28103 2 1OutputNeed more dataInput21234 2 21256 0 2Output2134Input20123 1 14567 1 2OutputIncorrect data
Input21263 1 28103 2 1
OutputNeed more data
2 seconds
256 megabytes
['brute force', 'implementation', '*1700']
B. Settlers' Trainingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly n soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease.Every soldier has a rank — some natural number from 1 to k. 1 stands for a private and k stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank.To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the n soldiers are present.At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank k are present, exactly one soldier increases his rank by one.You know the ranks of all n soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank k.InputThe first line contains two integers n and k (1 ≤ n, k ≤ 100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains n numbers in the non-decreasing order. The i-th of them, ai, represents the rank of the i-th soldier in the defense building (1 ≤ i ≤ n, 1 ≤ ai ≤ k).OutputPrint a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.ExamplesInput4 41 2 2 3Output4Input4 31 1 1 1Output5NoteIn the first example the ranks will be raised in the following manner:1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4Thus totals to 4 training sessions that require 4 golden coins.
Input4 41 2 2 3
Output4
2 seconds
256 megabytes
['implementation', '*1200']
A. Sinking Shiptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.InputThe first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.OutputPrint n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.ExamplesInput6Jack captainAlice womanCharlie manTeddy ratBob childJulia womanOutputTeddyAliceBobJuliaCharlieJack
Input6Jack captainAlice womanCharlie manTeddy ratBob childJulia woman
OutputTeddyAliceBobJuliaCharlieJack
2 seconds
256 megabytes
['implementation', 'sortings', 'strings', '*900']
E. World Eviltime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a result of Pinky and Brain's mysterious experiments in the Large Hadron Collider some portals or black holes opened to the parallel dimension. And the World Evil has crept to the veil between their world and ours. Brain quickly evaluated the situation and he understood that the more evil tentacles creep out and become free, the higher is the possibility that Brain will rule the world.The collider's constriction is a rectangular grid rolled into a cylinder and consisting of n rows and m columns such as is shown in the picture below: In this example n = 4, m = 5. Dotted lines are corridores that close each column to a ring, i. e. connect the n-th and the 1-th rows of the grid.In the leftmost column of the grid the portals are situated and the tentacles of the World Evil are ready to creep out from there. In the rightmost column the exit doors are located. The tentacles can only get out through those doors. The segments joining the nodes of the grid are corridors.Brain would be glad to let all the tentacles out but he faces a problem: the infinite number of tentacles can creep out of the portals, every tentacle possesses infinite length and some width and the volume of the corridors are, unfortunately, quite limited. Brain could approximately evaluate the maximal number of tentacles that will be able to crawl through every corridor.Now help the mice to determine the maximal number of tentacles of the World Evil that will crawl out of the Large Hadron Collider.InputThe first line of the input file contains two integers n and m (2 ≤ n ≤ 5, 2 ≤ m ≤ 105). They are the sizes of the Large Hadron Collider grid. The next m - 1 lines contain n numbers each. They are the horizontal corridors' capacities. The next m lines contain n numbers each. They are the vertical corridors' capacities. Corridors are described from left to right and from top to bottom. Every n-th vertical corridor connects nodes of the n-th and 1-th rows. A corridor's capacity is a non-negative integer that does not exceed 109.OutputPrint a single number, the number of the World Evil tentacles Pinky and Brain will command.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).ExamplesInput3 44 4 41 1 55 5 34 1 21 3 13 5 41 4 3Output7Input2 29 22 36 1Output11
Input3 44 4 41 1 55 5 34 1 21 3 13 5 41 4 3
Output7
5 seconds
256 megabytes
['dp', 'flows', '*2700']
D. Wormhousetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArnie the Worm has finished eating an apple house yet again and decided to move. He made up his mind on the plan, the way the rooms are located and how they are joined by corridors. He numbered all the rooms from 1 to n. All the corridors are bidirectional.Arnie wants the new house to look just like the previous one. That is, it should have exactly n rooms and, if a corridor from room i to room j existed in the old house, it should be built in the new one. We know that during the house constructing process Arnie starts to eat an apple starting from some room and only stops when he eats his way through all the corridors and returns to the starting room. It is also known that Arnie eats without stopping. That is, until Arnie finishes constructing the house, he is busy every moment of his time gnawing a new corridor. Arnie doesn't move along the already built corridors.However, gnawing out corridors in one and the same order any time you change a house is a very difficult activity. That's why Arnie, knowing the order in which the corridors were located in the previous house, wants to gnaw corridors in another order. It is represented as a list of rooms in the order in which they should be visited. The new list should be lexicographically smallest, but it also should be strictly lexicographically greater than the previous one. Help the worm. InputThe first line contains two integers n and m (3 ≤ n ≤ 100, 3 ≤ m ≤ 2000). It is the number of rooms and corridors in Arnie's house correspondingly. The next line contains m + 1 positive integers that do not exceed n. They are the description of Arnie's old path represented as a list of rooms he visited during the gnawing. It is guaranteed that the last number in the list coincides with the first one.The first room described in the list is the main entrance, that's why Arnie should begin gnawing from it.You may assume that there is no room which is connected to itself and there is at most one corridor between any pair of rooms. However, it is possible to find some isolated rooms which are disconnected from others.OutputPrint m + 1 positive integers that do not exceed n. Those numbers are the description of the new path, according to which Arnie should gnaw out his new house. If it is impossible to find new path you should print out No solution. The first number in your answer should be equal to the last one. Also it should be equal to the main entrance.ExamplesInput3 31 2 3 1Output1 3 2 1 Input3 31 3 2 1OutputNo solution
Input3 31 2 3 1
Output1 3 2 1
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*2300']
C. Inquisitiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Medieval times existed the tradition of burning witches at steaks together with their pets, black cats. By the end of the 15-th century the population of black cats ceased to exist. The difficulty of the situation led to creating the EIC - the Emergency Inquisitory Commission.The resolution #666 says that a white cat is considered black when and only when the perimeter of its black spots exceeds the acceptable norm. But what does the acceptable norm equal to? Every inquisitor will choose it himself depending on the situation. And your task is to find the perimeter of black spots on the cat's fur.The very same resolution says that the cat's fur is a white square with the length of 105. During the measurement of spots it is customary to put the lower left corner of the fur into the origin of axes (0;0) and the upper right one — to the point with coordinates (105;105). The cats' spots are nondegenerate triangles. The spots can intersect and overlap with each other, but it is guaranteed that each pair of the triangular spots' sides have no more than one common point.We'll regard the perimeter in this problem as the total length of the boarders where a cat's fur changes color.InputThe first input line contains a single integer n (0 ≤ n ≤ 100). It is the number of spots on the cat's fur. The i-th of the last n lines contains 6 integers: x1i, y1i, x2i, y2i, x3i, y3i. They are the coordinates of the i-th triangular spot (0 < xji, yji < 105).OutputPrint a single number, the answer to the problem, perimeter of the union of triangles. Your answer should differ from the correct one in no more than 10 - 6.ExamplesInput11 1 2 1 1 2Output3.4142135624Input33 3 10 3 3 101 1 9 4 5 62 2 11 7 6 11Output37.7044021497
Input11 1 2 1 1 2
Output3.4142135624
3 seconds
256 megabytes
['geometry', 'implementation', 'sortings', '*2300']
B. Tyndex.Brometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user.Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant!How does this splendid function work? That's simple! For each potential address a function of the F error is calculated by the following rules: for every letter ci from the potential address c the closest position j of the letter ci in the address (s) entered by the user is found. The absolute difference |i - j| of these positions is added to F. So for every i (1 ≤ i ≤ |c|) the position j is chosen such, that ci = sj, and |i - j| is minimal possible. if no such letter ci exists in the address entered by the user, then the length of the potential address |c| is added to F. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the F function for an address given by the user and some set of potential addresses. Good luck!InputThe first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105). They are the number of potential addresses and the length of the address entered by the user. The next line contains k lowercase Latin letters. They are the address entered by the user (s). Each next i-th (1 ≤ i ≤ n) line contains a non-empty sequence of lowercase Latin letters. They are the potential address. It is guaranteed that the total length of all the lines does not exceed 2·105.OutputOn each n line of the output file print a single number: the value of the error function when the current potential address is chosen.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).ExamplesInput2 10codeforcescodeforcescodehorsesOutput012Input9 9vkontaktevcontactevkontraktevkollapsevkrokodilevtopkevkapustevpechkevkvcodeforceseOutput18143647142930084
Input2 10codeforcescodeforcescodehorses
Output012
2 seconds
256 megabytes
['binary search', 'implementation', '*1800']
A. A Student's Dreamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStatistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them.A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable professor of all times, a three times Soviet Union Hero, a Noble Prize laureate in student expulsion, venerable Petr Palych.The poor student couldn't answer a single question. Thus, instead of a large spacious office he is going to apply for a job to thorium mines. But wait a minute! Petr Palych decided to give the student the last chance! Yes, that is possible only in dreams. So the professor began: "Once a Venusian girl and a Marsian boy met on the Earth and decided to take a walk holding hands. But the problem is the girl has al fingers on her left hand and ar fingers on the right one. The boy correspondingly has bl and br fingers. They can only feel comfortable when holding hands, when no pair of the girl's fingers will touch each other. That is, they are comfortable when between any two girl's fingers there is a boy's finger. And in addition, no three fingers of the boy should touch each other. Determine if they can hold hands so that the both were comfortable."The boy any the girl don't care who goes to the left and who goes to the right. The difference is only that if the boy goes to the left of the girl, he will take her left hand with his right one, and if he goes to the right of the girl, then it is vice versa.InputThe first line contains two positive integers not exceeding 100. They are the number of fingers on the Venusian girl's left and right hand correspondingly. The second line contains two integers not exceeding 100. They are the number of fingers on the Marsian boy's left and right hands correspondingly.OutputPrint YES or NO, that is, the answer to Petr Palych's question.ExamplesInput5 110 5OutputYESInput4 53 3OutputYESInput1 211 6OutputNONoteThe boy and the girl don't really care who goes to the left.
Input5 110 5
OutputYES
2 seconds
256 megabytes
['greedy', 'math', '*1300']
E. Enemy is weaktime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep". Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number.In Shapur's opinion the weakness of an army is equal to the number of triplets i, j, k such that i < j < k and ai > aj > ak where ax is the power of man standing at position x. The Roman army has one special trait — powers of all the people in it are distinct.Help Shapur find out how weak the Romans are.InputThe first line of input contains a single number n (3 ≤ n ≤ 106) — the number of men in Roman army. Next line contains n different positive integers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 109) — powers of men in the Roman army. OutputA single integer number, the weakness of the Roman army. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).ExamplesInput33 2 1Output1Input32 3 1Output0Input410 8 3 1Output4Input41 5 4 3Output1
Input33 2 1
Output1
5 seconds
256 megabytes
['data structures', 'trees', '*1900']
D. Eternal Victorytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these n cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities.All cities are numbered 1 to n. Shapur is currently in the city 1 and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city.Help Shapur find how much He should travel.InputFirst line contains a single natural number n (1 ≤ n ≤ 105) — the amount of cities.Next n - 1 lines contain 3 integer numbers each xi, yi and wi (1 ≤ xi, yi ≤ n, 0 ≤ wi ≤ 2 × 104). xi and yi are two ends of a road and wi is the length of that road.OutputA single integer number, the minimal length of Shapur's travel.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).ExamplesInput31 2 32 3 4Output7Input31 2 31 3 3Output9
Input31 2 32 3 4
Output7
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', 'shortest paths', 'trees', '*1800']
C. Capture Valeriantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's now 260 AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran.Recently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is captured by Shapur and Shapur is now going to capture Valerian, the Roman emperor.Being defeated, the cowardly Valerian hid in a room at the top of one of his castles. To capture him, Shapur has to open many doors. Fortunately Valerian was too scared to make impenetrable locks for the doors.Each door has 4 parts. The first part is an integer number a. The second part is either an integer number b or some really odd sign which looks like R. The third one is an integer c and the fourth part is empty! As if it was laid for writing something. Being extremely gifted, after opening the first few doors, Shapur found out the secret behind the locks.c is an integer written in base a, to open the door we should write it in base b. The only bad news is that this R is some sort of special numbering system that is used only in Roman empire, so opening the doors is not just a piece of cake!Here's an explanation of this really weird number system that even doesn't have zero:Roman numerals are based on seven symbols: a stroke (identified with the letter I) for a unit, a chevron (identified with the letter V) for a five, a cross-stroke (identified with the letter X) for a ten, a C (identified as an abbreviation of Centum) for a hundred, etc.: I=1 V=5 X=10 L=50 C=100 D=500 M=1000Symbols are iterated to produce multiples of the decimal (1, 10, 100, 1, 000) values, with V, L, D substituted for a multiple of five, and the iteration continuing: I 1, II 2, III 3, V 5, VI 6, VII 7, etc., and the same for other bases: X 10, XX 20, XXX 30, L 50, LXXX 80; CC 200, DCC 700, etc. At the fourth and ninth iteration, a subtractive principle must be employed, with the base placed before the higher base: IV 4, IX 9, XL 40, XC 90, CD 400, CM 900.Also in bases greater than 10 we use A for 10, B for 11, etc.Help Shapur capture Valerian and bring peace back to Persia, especially Armenia.InputThe first line contains two integers a and b (2 ≤ a, b ≤ 25). Only b may be replaced by an R which indicates Roman numbering system.The next line contains a single non-negative integer c in base a which may contain leading zeros but its length doesn't exceed 103. It is guaranteed that if we have Roman numerals included the number would be less than or equal to 300010 and it won't be 0. In any other case the number won't be greater than 101510.OutputWrite a single line that contains integer c in base b. You must omit leading zeros.ExamplesInput10 21Output1Input16 R5OutputVInput5 R4OutputIVInput2 21111001Output1111001Input12 13AOutputANoteYou can find more information about roman numerals here: http://en.wikipedia.org/wiki/Roman_numerals
Input10 21
Output1
2 seconds
256 megabytes
['math', '*2000']
B. Hard Worktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher gave them 3 strings and asked them to concatenate them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation.Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked.Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers.Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said: As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin. As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include "-", ";" and "_". These characters are my own invention of course! And I call them Signs. The length of all initial strings was less than or equal to 100 and the lengths of my students' answers are less than or equal to 600 My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes. Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN You should indicate for any of my students if his answer was right or wrong. Do this by writing "WA" for Wrong answer or "ACC" for a correct answer. I should remind you that none of the strings (initial strings or answers) are empty. Finally, do these as soon as possible. You have less than 2 hours to complete this. InputThe first three lines contain a string each. These are the initial strings. They consists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). All the initial strings have length from 1 to 100, inclusively.In the fourth line there is a single integer n (0 ≤ n ≤ 1000), the number of students.Next n lines contain a student's answer each. It is guaranteed that the answer meets what the teacher said. Each answer iconsists only of lowercase and uppercase Latin letters and signs ("-", ";" and "_"). Length is from 1 to 600, inclusively.OutputFor each student write in a different line. Print "WA" if his answer is wrong or "ACC" if his answer is OK.ExamplesInputIran_Persian;W_o;n;d;e;r;f;u;l;7WonderfulPersianIranwonderful_PersIAN_IRAN;;_WONDERFUL___IRAN__PERSIAN__;;Ira__Persiann__WonderfulWonder;;fulPersian___;I;r;a;n;__________IranPersianWonderful__________PersianIran_is_WonderfulOutputACCACCACCWAACCACCWAInputShapur;;is___a_genius3Shapur__a_is___geniUsis___shapur___a__Genius;Shapur;;is;;a;;geni;;us;;OutputWAACCACC
InputIran_Persian;W_o;n;d;e;r;f;u;l;7WonderfulPersianIranwonderful_PersIAN_IRAN;;_WONDERFUL___IRAN__PERSIAN__;;Ira__Persiann__WonderfulWonder;;fulPersian___;I;r;a;n;__________IranPersianWonderful__________PersianIran_is_Wonderful
OutputACCACCACCWAACCACCWA
2 seconds
256 megabytes
['strings', '*1300']
A. Ultra-Fast Mathematiciantime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputShapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The i-th digit of the answer is 1 if and only if the i-th digit of the two given numbers differ. In the other case the i-th digit of the answer is 0.Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.Now you are going to take part in Shapur's contest. See if you are faster and more accurate.InputThere are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100.OutputWrite one line — the corresponding answer. Do not omit the leading 0s.ExamplesInput10101000100101Output1110001Input000111Output111Input11101010Output0100Input0111001100Output00010
Input10101000100101
Output1110001
2 seconds
256 megabytes
['implementation', '*800']
E. Mushroom Gnomestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighboring ones. The mushroom gnomes loved it when everything was in order, that's why they always planted the mushrooms in one line in the order of their weights' increasing. Well... The gnomes planted the mushrooms and went to eat. After x minutes they returned and saw that new mushrooms had grown up, so that the increasing order had been violated. The gnomes replanted all the mushrooms in the correct order, that is, they sorted the mushrooms in the order of the weights' increasing. And went to eat again (those gnomes were quite big eaters). What total weights modulo p will the mushrooms have in another y minutes?InputThe first line contains four integers n, x, y, p (1 ≤ n ≤ 106, 0 ≤ x, y ≤ 1018, x + y > 0, 2 ≤ p ≤ 109) which represent the number of mushrooms, the number of minutes after the first replanting, the number of minutes after the second replanting and the module. The next line contains n integers ai which represent the mushrooms' weight in the non-decreasing order (0 ≤ ai ≤ 109).Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).OutputThe answer should contain a single number which is the total weights of the mushrooms modulo p in the end after x + y minutes.ExamplesInput2 1 0 6572765451 2Output6Input2 1 1 8884502821 2Output14Input4 5 0 100001 2 3 4Output1825
Input2 1 0 6572765451 2
Output6
3 seconds
256 megabytes
['math', 'matrices', '*2600']
D. Saviortime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisha decided to help Pasha and Akim be friends again. He had a cunning plan — to destroy all the laughy mushrooms. He knows that the laughy mushrooms can easily burst when they laugh. Mushrooms grow on the lawns. There are a[t] mushrooms on the t-th lawn.Misha knows that the lawns where the mushrooms grow have a unique ability. A lawn (say, i) can transfer laugh to other lawn (say, j) if there exists an integer (say, b) such, that some permutation of numbers a[i], a[j] and b is a beautiful triple (i ≠ j). A beautiful triple is such three pairwise coprime numbers x, y, z, which satisfy the following condition: x2 + y2 = z2.Misha wants to know on which minimal number of lawns he should laugh for all the laughy mushrooms to burst.InputThe first line contains one integer n (1 ≤ n ≤ 106) which is the number of lawns. The next line contains n integers ai which are the number of mushrooms on the i-lawn (1 ≤ ai ≤ 107). All the numbers are different.OutputPrint a single number — the minimal number of lawns on which Misha should laugh for all the mushrooms to burst.ExamplesInput12Output1Input21 2Output2Input23 5Output1
Input12
Output1
4 seconds
256 megabytes
['brute force', 'dsu', 'math', '*2500']
C. Mushroom Strifetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha and Akim were making a forest map — the lawns were the graph's vertexes and the roads joining the lawns were its edges. They decided to encode the number of laughy mushrooms on every lawn in the following way: on every edge between two lawns they wrote two numbers, the greatest common divisor (GCD) and the least common multiple (LCM) of the number of mushrooms on these lawns. But one day Pasha and Akim had an argument about the laughy mushrooms and tore the map. Pasha was left with just some part of it, containing only m roads. Your task is to help Pasha — use the map he has to restore the number of mushrooms on every lawn. As the result is not necessarily unique, help Pasha to restore any one or report that such arrangement of mushrooms does not exist. It is guaranteed that the numbers on the roads on the initial map were no less that 1 and did not exceed 106.InputThe first line contains two numbers n and m () which are the numbers of lawns and roads we know about. Each of the following m lines contains four numbers which are the numbers of lawns the road connects, the GCD and the LCM of the numbers of mushrooms on these lawns (1 ≤ GCD, LCM ≤ 106).It is guaranteed, that no road connects lawn to itself, and no two lawns are connected by more than one road.OutputThe answer should contain "YES" or "NO" on the first line, saying whether it is possible or not to perform the arrangement. If the answer is "YES", print on the following line n numbers which are the numbers of mushrooms on the corresponding lawns.ExamplesInput1 0OutputYES1 Input2 11 2 1 3OutputYES1 3 Input3 23 2 1 23 1 1 10OutputYES5 1 2 Input2 11 2 3 7OutputNO
Input1 0
OutputYES1
2 seconds
256 megabytes
['brute force', 'dfs and similar', '*2100']
B. Serial Time!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k × n × m, that is, it has k layers (the first layer is the upper one), each of which is a rectangle n × m with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square (x, y) of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment.Note: the water fills all the area within reach (see sample 4). Water flows in each of the 6 directions, through faces of 1 × 1 × 1 cubes.InputThe first line contains three numbers k, n, m (1 ≤ k, n, m ≤ 10) which are the sizes of the plate. Then follow k rectangles consisting of n lines each containing m characters '.' or '#', which represents the "layers" of the plate in the order from the top to the bottom. The rectangles are separated by empty lines (see the samples). The last line contains x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) which are the tap's coordinates. x is the number of the line and y is the number of the column. Lines of each layer are numbered from left to right by the integers from 1 to n, columns of each layer are numbered from top to bottom by the integers from 1 to m.OutputThe answer should contain a single number, showing in how many minutes the plate will be filled.ExamplesInput1 1 1.1 1Output1Input2 1 1.#1 1Output1Input2 2 2.###....1 1Output5Input3 2 2#.###..#....1 2Output7Input3 3 3.#.#####..#######..........1 1Output13
Input1 1 1.1 1
Output1
2 seconds
256 megabytes
['dfs and similar', 'dsu', '*1400']
A. Where Are My Flakes?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the left of the i-th box" ("To the left of i"), "Hidden to the right of the i-th box" ("To the right of i"). Such hints mean that there are no flakes in the i-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.InputThe first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000) which represent the number of boxes and the number of hints correspondingly. Next m lines contain hints like "To the left of i" and "To the right of i", where i is integer (1 ≤ i ≤ n). The hints may coincide.OutputThe answer should contain exactly one integer — the number of boxes that should necessarily be checked or "-1" if the hints are contradictory.ExamplesInput2 1To the left of 2Output1Input3 2To the right of 1To the right of 2Output1Input3 1To the left of 3Output2Input3 2To the left of 2To the right of 1Output-1
Input2 1To the left of 2
Output1
2 seconds
256 megabytes
['implementation', 'two pointers', '*1300']
E. Shortest Pathtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Ancient Berland there were n cities and m two-way roads of equal length. The cities are numbered with integers from 1 to n inclusively. According to an ancient superstition, if a traveller visits three cities ai, bi, ci in row, without visiting other cities between them, a great disaster awaits him. Overall there are k such city triplets. Each triplet is ordered, which means that, for example, you are allowed to visit the cities in the following order: ai, ci, bi. Vasya wants to get from the city 1 to the city n and not fulfil the superstition. Find out which minimal number of roads he should take. Also you are required to find one of his possible path routes.InputThe first line contains three integers n, m, k (2 ≤ n ≤ 3000, 1 ≤ m ≤ 20000, 0 ≤ k ≤ 105) which are the number of cities, the number of roads and the number of the forbidden triplets correspondingly. Then follow m lines each containing two integers xi, yi (1 ≤ xi, yi ≤ n) which are the road descriptions. The road is described by the numbers of the cities it joins. No road joins a city with itself, there cannot be more than one road between a pair of cities. Then follow k lines each containing three integers ai, bi, ci (1 ≤ ai, bi, ci ≤ n) which are the forbidden triplets. Each ordered triplet is listed mo more than one time. All three cities in each triplet are distinct.City n can be unreachable from city 1 by roads.OutputIf there are no path from 1 to n print -1. Otherwise on the first line print the number of roads d along the shortest path from the city 1 to the city n. On the second line print d + 1 numbers — any of the possible shortest paths for Vasya. The path should start in the city 1 and end in the city n.ExamplesInput4 4 11 22 33 41 31 4 3Output21 3 4Input3 1 01 2Output-1Input4 4 21 22 33 41 31 2 31 3 4Output41 3 2 3 4
Input4 4 11 22 33 41 31 4 3
Output21 3 4
3 seconds
256 megabytes
['graphs', 'shortest paths', '*2000']
D. Team Arrangementtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently personal training sessions have finished in the Berland State University Olympiad Programmer Training Centre. By the results of these training sessions teams are composed for the oncoming team contest season. Each team consists of three people. All the students of the Centre possess numbers from 1 to 3n, and all the teams possess numbers from 1 to n. The splitting of students into teams is performed in the following manner: while there are people who are not part of a team, a person with the best total score is chosen among them (the captain of a new team), this person chooses for himself two teammates from those who is left according to his list of priorities. The list of every person's priorities is represented as a permutation from the rest of 3n - 1 students who attend the centre, besides himself.You are given the results of personal training sessions which are a permutation of numbers from 1 to 3n, where the i-th number is the number of student who has won the i-th place. No two students share a place. You are also given the arrangement of the already formed teams in the order in which they has been created. Your task is to determine the list of priorities for the student number k. If there are several priority lists, choose the lexicographically minimal one.InputThe first line contains an integer n (1 ≤ n ≤ 105) which is the number of resulting teams. The second line contains 3n space-separated integers from 1 to 3n which are the results of personal training sessions. It is guaranteed that every student appears in the results exactly once.Then follow n lines each containing three integers from 1 to 3n — each line describes the members of a given team. The members of one team can be listed in any order, but the teams themselves are listed in the order in which they were created. It is guaranteed that the arrangement is correct, that is that every student is a member of exactly one team and those teams could really be created from the given results using the method described above.The last line contains number k (1 ≤ k ≤ 3n) which is the number of a student for who the list of priorities should be found.OutputPrint 3n - 1 numbers — the lexicographically smallest list of priorities for the student number k. The lexicographical comparison is performed by the standard < operator in modern programming languages. The list a is lexicographically less that the list b if exists such an i (1 ≤ i ≤ 3n), that ai < bi, and for any j (1 ≤ j < i) aj = bj. Note, that the list 1 9 10 is lexicographically less than the list 1 10 9. That is, the comparison of lists is different from the comparison of lines.ExamplesInput35 4 1 2 6 3 7 8 95 6 29 3 41 7 84Output2 3 5 6 9 1 7 8 Input35 4 1 2 6 3 7 8 95 6 29 3 41 7 88Output1 2 3 4 5 6 7 9 Input24 1 3 2 5 64 6 51 2 34Output5 6 1 2 3
Input35 4 1 2 6 3 7 8 95 6 29 3 41 7 84
Output2 3 5 6 9 1 7 8
3 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*2000']
C. Titletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has recently finished writing a book. Now he faces the problem of giving it the title. Vasya wants the title to be vague and mysterious for his book to be noticeable among others. That's why the title should be represented by a single word containing at least once each of the first k Latin letters and not containing any other ones. Also, the title should be a palindrome, that is it should be read similarly from the left to the right and from the right to the left.Vasya has already composed the approximate variant of the title. You are given the title template s consisting of lowercase Latin letters and question marks. Your task is to replace all the question marks by lowercase Latin letters so that the resulting word satisfies the requirements, described above. Each question mark should be replaced by exactly one letter, it is not allowed to delete characters or add new ones to the template. If there are several suitable titles, choose the first in the alphabetical order, for Vasya's book to appear as early as possible in all the catalogues.InputThe first line contains an integer k (1 ≤ k ≤ 26) which is the number of allowed alphabet letters. The second line contains s which is the given template. In s only the first k lowercase letters of Latin alphabet and question marks can be present, the length of s is from 1 to 100 characters inclusively.OutputIf there is no solution, print IMPOSSIBLE. Otherwise, a single line should contain the required title, satisfying the given template. The title should be a palindrome and it can only contain the first k letters of the Latin alphabet. At that, each of those k letters must be present at least once. If there are several suitable titles, print the lexicographically minimal one. The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if exists such an i (1 ≤ i ≤ |s|), that ai < bi, and for any j (1 ≤ j < i) aj = bj. |s| stands for the length of the given template.ExamplesInput3a?cOutputIMPOSSIBLEInput2a??aOutputabbaInput2?b?aOutputabba
Input3a?c
OutputIMPOSSIBLE
2 seconds
256 megabytes
['expression parsing', '*1600']
B. Fortune Tellingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMarina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces alternatively "Loves" and "Doesn't love", at that Marina always starts with "Loves". There are n camomiles growing in the field, possessing the numbers of petals equal to a1, a2, ... an. Marina wants to pick a bouquet with the maximal possible total number of petals so that the result would still be "Loves". Help her do that; find the maximal number of petals possible in the bouquet.InputThe first line contains an integer n (1 ≤ n ≤ 100), which is the number of flowers growing in the field. The second line contains n integers ai (1 ≤ ai ≤ 100) which represent the number of petals on a given i-th camomile.OutputPrint a single number which is the maximal number of petals in the bouquet, the fortune telling on which would result in "Loves". If there are no such bouquet, print 0 instead. The bouquet may consist of a single flower.ExamplesInput11Output1Input12Output0Input35 6 7Output13
Input11
Output1
2 seconds
256 megabytes
['implementation', 'number theory', '*1200']
A. Wordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.InputThe first line contains a word s — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100.OutputPrint the corrected word s. If the given word s has strictly more uppercase letters, make the word written in the uppercase register, otherwise - in the lowercase one.ExamplesInputHoUseOutputhouseInputViPOutputVIPInputmaTRIxOutputmatrix
InputHoUse
Outputhouse
2 seconds
256 megabytes
['implementation', 'strings', '*800']
E. Expressiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya was solving arithmetical problems. He wrote down an expression a + b = c in his notebook. When the teacher checked Vasya's work it turned out that Vasya had solved the problem incorrectly. Now Vasya tries to find excuses. He says that he simply forgot to write down several digits in numbers a, b and c, but he can't remember what numbers they actually were. Help Vasya, find such numbers x, y and z, with which the following conditions are met: x + y = z, from the expression x + y = z several digits can be erased in such a way that the result will be a + b = c, the expression x + y = z should have the minimal length. InputThe first and only input line contains the expression a + b = c (1 ≤ a, b, c ≤ 106, a, b and c don't contain leading zeroes) which is the expression Vasya wrote down.OutputPrint the correct expression x + y = z (x, y and z are non-negative numbers without leading zeroes). The expression a + b = c must be met in x + y = z as a subsequence. The printed solution should have the minimal possible number of characters. If there are several such solutions, you can print any of them.ExamplesInput2+4=5Output21+4=25Input1+1=3Output1+31=32Input1+1=2Output1+1=2
Input2+4=5
Output21+4=25
2 seconds
256 megabytes
['dp', '*2400']
D. Calendartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerOilGasDiamondBank has branches in n cities, at that n is an even number. The bank management wants to publish a calendar with the names of all those cities written in two columns: the calendar should consist of exactly n / 2 lines of strictly equal length, each of which contains exactly two names and exactly one separator character between them. The name of every city should be used in the calendar exactly once. For historical reasons the symbol d is used as the separator of words in the calendar. The BerOilGasDiamondBank management wants to show that all its branches are equally important to it, that's why the order of their appearance in the calendar should be following: if we "glue"(concatinate) all the n / 2 calendar lines (from top to bottom) to make a single line, then the lexicographically minimal line is obtained. No separator character will be used to separate calendar lines. For example, if the lines are "bertown!berville", "newberville!bera", then the resulting line is "bertown!bervillenewberville!bera". In some sense one has to find the lexicographically minimal calendar, where the comparison of calendars happens line by line.Help BerOilGasDiamondBank and construct the required calendar.InputThe first line contains an integer n (1 ≤ n ≤ 104, n is even) which is the number of branches. Then follow n lines which are the names of the cities. All the names consist of lowercase Latin letters; their lengths are no less than 1 and no more than 10 symbols. The next line contains a single symbol d (d has an ASCII-code from 33 to 126 inclusively, excluding lowercase Latin letters) which is the separator between words in the calendar lines. It is guaranteed that the calendar is possible to be constructed and all the names are different.OutputPrint n / 2 lines of similar length which are the required calendar. Every line should contain exactly two words and exactly one separator between them. If there are several solutions, print the lexicographically minimal one. The lexicographical comparison of lines is realized by the "<" operator in the modern programming languages.ExamplesInput4baahgc.Outputaa.bc.hgInput2aaa!Outputa!aaInput2aaa|Outputaa|a
Input4baahgc.
Outputaa.bc.hg
2 seconds
256 megabytes
['greedy', 'strings', '*2000']
C. Treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn Bertown's main street n trees are growing, the tree number i has the height of ai meters (1 ≤ i ≤ n). By the arrival of the President of Berland these trees were decided to be changed so that their heights formed a beautiful sequence. This means that the heights of trees on ends (the 1st one and the n-th one) should be equal to each other, the heights of the 2-nd and the (n - 1)-th tree must also be equal to each other, at that the height of the 2-nd tree should be larger than the height of the first tree by 1, and so on. In other words, the heights of the trees, standing at equal distance from the edge (of one end of the sequence) must be equal to each other, and with the increasing of the distance from the edge by 1 the tree height must also increase by 1. For example, the sequences "2 3 4 5 5 4 3 2" and "1 2 3 2 1" are beautiful, and '1 3 3 1" and "1 2 3 1" are not. Changing the height of a tree is a very expensive operation, using advanced technologies invented by Berland scientists. In one operation you can choose any tree and change its height to any number, either increase or decrease. Note that even after the change the height should remain a positive integer, i. e, it can't be less than or equal to zero. Identify the smallest number of changes of the trees' height needed for the sequence of their heights to become beautiful.InputThe first line contains integer n (1 ≤ n ≤ 105) which is the number of trees. The second line contains integers ai (1 ≤ ai ≤ 105) which are the heights of the trees.OutputPrint a single number which is the minimal number of trees whose heights will have to be changed for the sequence to become beautiful.ExamplesInput32 2 2Output1Input41 2 2 1Output0
Input32 2 2
Output1
2 seconds
256 megabytes
['brute force', '*1800']
B. Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland a money reform is being prepared. New coins are being introduced. After long economic calculations was decided that the most expensive coin should possess the denomination of exactly n Berland dollars. Also the following restriction has been introduced for comfort: the denomination of each coin should be divisible by the denomination of any cheaper coin. It is known that among all the possible variants the variant with the largest number of new coins will be chosen. Find this variant. Print in the order of decreasing of the coins' denominations.InputThe first and only line contains an integer n (1 ≤ n ≤ 106) which represents the denomination of the most expensive coin. OutputPrint the denominations of all the coins in the order of decreasing. The number of coins must be the largest possible (with the given denomination n of the most expensive coin). Also, the denomination of every coin must be divisible by the denomination of any cheaper coin. Naturally, the denominations of all the coins should be different. If there are several solutins to that problem, print any of them.ExamplesInput10Output10 5 1Input4Output4 2 1Input3Output3 1
Input10
Output10 5 1
2 seconds
256 megabytes
['greedy', '*1300']
A. Chat roomtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word s.InputThe first and only line contains the word s, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters.OutputIf Vasya managed to say hello, print "YES", otherwise print "NO".ExamplesInputahhellllloouOutputYESInputhleloOutputNO
Inputahhellllloou
OutputYES
1 second
256 megabytes
['greedy', 'strings', '*1000']
E. Chesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBrian the Rabbit adores chess. Not long ago he argued with Stewie the Rabbit that a knight is better than a king. To prove his point he tries to show that the knight is very fast but Stewie doesn't accept statements without evidence. He constructed an infinite chessboard for Brian, where he deleted several squares to add some more interest to the game. Brian only needs to count how many different board squares a knight standing on a square with coordinates of (0, 0) can reach in no more than k moves. Naturally, it is forbidden to move to the deleted squares.Brian doesn't very much like exact sciences himself and is not acquainted with programming, that's why he will hardly be able to get ahead of Stewie who has already started solving the problem. Help Brian to solve the problem faster than Stewie.InputThe first line contains two integers k and n (0 ≤ k ≤ 1018, 0 ≤ n ≤ 440) which are correspondingly the maximal number of moves a knight can make and the number of deleted cells. Then follow n lines, each giving the coordinates of a deleted square in the form (xi, yi) (|xi| ≤ 10, |yi| ≤ 10). All the numbers are integer, the deleted squares are different and it is guaranteed that the square (0, 0) is not deleted.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).OutputYou must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.ExamplesInput1 0Output9Input2 7-1 21 22 12 -11 -2-1 -2-2 -1Output9
Input1 0
Output9
2 seconds
256 megabytes
['math', 'shortest paths', '*3000']
D. Journeytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStewie the Rabbit explores a new parallel universe. This two dimensional universe has the shape of a rectangular grid, containing n lines and m columns. The universe is very small: one cell of the grid can only contain one particle. Each particle in this universe is either static or dynamic. Each static particle always remains in one and the same position. Due to unintelligible gravitation laws no two static particles in the parallel universe can be present in one column or row, and they also can't be present in the diagonally adjacent cells. A dynamic particle appears in a random empty cell, randomly chooses the destination cell (destination cell may coincide with the start cell, see the samples) and moves there along the shortest path through the cells, unoccupied by the static particles. All empty cells have the same probability of being selected as the beginning or end of the path. Having reached the destination cell, the particle disappears. Only one dynamic particle can exist at one moment of time. This particle can move from a cell to a cell if they have an adjacent side, and this transition takes exactly one galactic second. Stewie got interested in what is the average lifespan of one particle in the given universe.InputThe first line contains two space-separated integers: n, m (2 ≤ n, m ≤ 1000) which represent the sizes of the universe. The next n lines containing m symbols each describe the universe without dynamic particles — the j-th symbol of the i-th line equals to 'X' if the cell is occupied by a static particle, and to '.' if it is empty. It is guaranteed that the described universe satisfies the properties described above, that is no two static particles can be in one column or in one row, besides, they can't be positioned in the diagonally adjacent cells.OutputYou have to print on a single line a single number which is the average life span of a particle with an accuracy of at least 6 decimal places.The answer will be accepted if it is within 10 - 6 of absolute or relative error from the correct answer.ExamplesInput2 2...XOutput0.888888888889Input3 3....X....Output2.000000000000
Input2 2...X
Output0.888888888889
1 second
256 megabytes
['dp', 'math', '*2500']
C. Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputChris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of n, containing only integers from 1 to n. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions: each elements, starting from the second one, is no more than the preceding one each element, starting from the second one, is no less than the preceding one Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.InputThe single line contains an integer n which is the size of the array (1 ≤ n ≤ 105).OutputYou must print the answer on a single line. As it can be rather long, you should print it modulo 1000000007.ExamplesInput2Output4Input3Output17
Input2
Output4
2 seconds
256 megabytes
['combinatorics', 'math', '*1900']
B. Martian Architecturetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputChris the Rabbit found the traces of an ancient Martian civilization. The brave astronomer managed to see through a small telescope an architecture masterpiece — "A Road to the Sun". The building stands on cubical stones of the same size. The foundation divides the entire "road" into cells, into which the cubical stones are fit tightly. Thus, to any cell of the foundation a coordinate can be assigned. To become the leader of the tribe, a Martian should build a Road to the Sun, that is to build from those cubical stones on a given foundation a stairway. The stairway should be described by the number of stones in the initial coordinate and the coordinates of the stairway's beginning and end. Each following cell in the coordinate's increasing order should contain one cubical stone more than the previous one. At that if the cell has already got stones, they do not count in this building process, the stairways were simply built on them. In other words, let us assume that a stairway is built with the initial coordinate of l, the final coordinate of r and the number of stones in the initial coordinate x. That means that x stones will be added in the cell l, x + 1 stones will be added in the cell l + 1, ..., x + r - l stones will be added in the cell r.Chris managed to find an ancient manuscript, containing the descriptions of all the stairways. Now he wants to compare the data to be sure that he has really found "A Road to the Sun". For that he chose some road cells and counted the total number of cubical stones that has been accumulated throughout the Martian history and then asked you to count using the manuscript to what the sum should ideally total.InputThe first line contains three space-separated integers: n, m, k (1 ≤ n, m ≤ 105, 1 ≤ k ≤ min(n, 100)) which is the number of cells, the number of "Roads to the Sun" and the number of cells in the query correspondingly. Each of the following m roads contain three space-separated integers: ai, bi, ci (1 ≤ ai ≤ bi ≤ n, 1 ≤ ci ≤ 1000) which are the stairway's description, its beginning, end and the initial cell's height. Then follow a line, containing k different space-separated integers bi. All these numbers ranging from 1 to n are cells, the number of stones in which interests Chris.OutputYou have to print a single number on a single line which is the sum of stones in all the cells Chris is interested in.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).ExamplesInput5 2 11 5 12 4 13Output5Input3 2 11 3 11 3 12Output4Input3 2 11 3 11 3 13Output6
Input5 2 11 5 12 4 13
Output5
2 seconds
256 megabytes
['implementation', '*1600']
A. Square Earth?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMeg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side n. Thus, the task has been reduced to finding the shortest path between two dots on a square (the path should go through the square sides). To simplify the task let us consider the vertices of the square to lie at points whose coordinates are: (0, 0), (n, 0), (0, n) and (n, n).InputThe single line contains 5 space-separated integers: n, x1, y1, x2, y2 (1 ≤ n ≤ 1000, 0 ≤ x1, y1, x2, y2 ≤ n) which correspondingly represent a side of the square, the coordinates of the first point and the coordinates of the second point. It is guaranteed that the points lie on the sides of the square.OutputYou must print on a single line the shortest distance between the points.ExamplesInput2 0 0 1 0Output1Input2 0 1 2 1Output4Input100 0 0 100 100Output200
Input2 0 0 1 0
Output1
2 seconds
256 megabytes
['dfs and similar', 'greedy', 'implementation', '*1300']
E. Domino Principletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is interested in arranging dominoes. He is fed up with common dominoes and he uses the dominoes of different heights. He put n dominoes on the table along one axis, going from left to right. Every domino stands perpendicular to that axis so that the axis passes through the center of its base. The i-th domino has the coordinate xi and the height hi. Now Vasya wants to learn for every domino, how many dominoes will fall if he pushes it to the right. Help him do that. Consider that a domino falls if it is touched strictly above the base. In other words, the fall of the domino with the initial coordinate x and height h leads to the fall of all dominoes on the segment [x + 1, x + h - 1].InputThe first line contains integer n (1 ≤ n ≤ 105) which is the number of dominoes. Then follow n lines containing two integers xi and hi ( - 108 ≤ xi ≤ 108, 2 ≤ hi ≤ 108) each, which are the coordinate and height of every domino. No two dominoes stand on one point.OutputPrint n space-separated numbers zi — the number of dominoes that will fall if Vasya pushes the i-th domino to the right (including the domino itself).ExamplesInput416 520 510 1018 2Output3 1 4 1 Input40 101 59 1015 10Output4 1 2 1
Input416 520 510 1018 2
Output3 1 4 1
2 seconds
256 megabytes
['binary search', 'data structures', 'sortings', '*2200']
D. Changing a Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a string s, consisting of capital Latin letters. Let's denote its current length as |s|. During one move it is allowed to apply one of the following operations to it: INSERT pos ch — insert a letter ch in the string s in the position pos (1 ≤ pos ≤ |s| + 1, A ≤ ch ≤ Z). The letter ch becomes the pos-th symbol of the string s, at that the letters shift aside and the length of the string increases by 1. DELETE pos — delete a character number pos (1 ≤ pos ≤ |s|) from the string s. At that the letters shift together and the length of the string decreases by 1. REPLACE pos ch — the letter in the position pos of the line s is replaced by ch (1 ≤ pos ≤ |s|, A ≤ ch ≤ Z). At that the length of the string does not change. Your task is to find in which minimal number of moves one can get a t string from an s string. You should also find the sequence of actions leading to the required results.InputThe first line contains s, the second line contains t. The lines consist only of capital Latin letters, their lengths are positive numbers from 1 to 1000.OutputIn the first line print the number of moves k in the given sequence of operations. The number should be the minimal possible one. Then print k lines containing one operation each. Print the operations in the format, described above. If there are several solutions, print any of them.ExamplesInputABAABBBAOutput2INSERT 3 BINSERT 4 BInputACCEPTEDWRONGANSWEROutput10REPLACE 1 WREPLACE 2 RREPLACE 3 OREPLACE 4 NREPLACE 5 GREPLACE 6 AINSERT 7 NINSERT 8 SINSERT 9 WREPLACE 11 R
InputABAABBBA
Output2INSERT 3 BINSERT 4 B
2 seconds
256 megabytes
['dp', '*2100']
C. Corporation Mailtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: employee ::= name. | name:employee1,employee2, ... ,employeek. name ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description.For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself.In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is s writes a letter to another person whose name is also s. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates).Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.InputThe first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.OutputPrint a single number — the number of uncomfortable situations in the company.ExamplesInputMIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...Output3InputA:A..Output1InputA:C:C:C:C.....Output6
InputMIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...
Output3
2 seconds
256 megabytes
['data structures', 'expression parsing', 'implementation', '*1700']
B. Spoilt Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya collects coins: he has exactly one coin for every year from 1 to n. Naturally, Vasya keeps all the coins in his collection in the order in which they were released. Once Vasya's younger brother made a change — he took all the coins whose release year dated from l to r inclusively and put them in the reverse order. That is, he took a certain segment [l, r] and reversed it. At that the segment's endpoints did not coincide. For example, if n = 8, then initially Vasya's coins were kept in the order 1 2 3 4 5 6 7 8. If Vasya's younger brother chose the segment [2, 6], then after the reversal the coin order will change to 1 6 5 4 3 2 7 8. Vasya suspects that someone else could have spoilt the permutation after his brother. Help him to find that out. Check if the given permutation can be obtained from the permutation 1 2 ... n using exactly one segment reversal. If it is possible, find the segment itself.InputThe first line contains an integer n (1 ≤ n ≤ 1000) which is the number of coins in Vasya's collection. The second line contains space-separated n integers which are the spoilt sequence of coins. It is guaranteed that the given sequence is a permutation, i.e. it contains only integers from 1 to n, and every number is used exactly 1 time.OutputIf it is impossible to obtain the given permutation from the original one in exactly one action, print 0 0. Otherwise, print two numbers l r (1 ≤ l < r ≤ n) which are the endpoints of the segment that needs to be reversed to obtain from permutation 1 2 ... n the given one.ExamplesInput81 6 5 4 3 2 7 8Output2 6Input42 3 4 1Output0 0Input41 2 3 4Output0 0
Input81 6 5 4 3 2 7 8
Output2 6
2 seconds
256 megabytes
['implementation', '*1300']
A. Bartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAccording to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINEInputThe first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators.Only the drinks from the list given above should be considered alcohol.OutputPrint a single number which is the number of people Vasya should check to guarantee the law enforcement.ExamplesInput518VODKACOKE1917Output2NoteIn the sample test the second and fifth clients should be checked.
Input518VODKACOKE1917
Output2
2 seconds
256 megabytes
['implementation', '*1000']
E. Very simple problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a convex polygon. Count, please, the number of triangles that contain a given point in the plane and their vertices are the vertices of the polygon. It is guaranteed, that the point doesn't lie on the sides and the diagonals of the polygon.InputThe first line contains integer n — the number of vertices of the polygon (3 ≤ n ≤ 100000). The polygon description is following: n lines containing coordinates of the vertices in clockwise order (integer x and y not greater than 109 by absolute value). It is guaranteed that the given polygon is nondegenerate and convex (no three points lie on the same line).The next line contains integer t (1 ≤ t ≤ 20) — the number of points which you should count the answer for. It is followed by t lines with coordinates of the points (integer x and y not greater than 109 by absolute value).OutputThe output should contain t integer numbers, each on a separate line, where i-th number is the answer for the i-th point.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).ExamplesInput45 00 00 55 511 3Output2Input30 00 55 021 110 10Output10Input57 66 34 11 22 443 32 35 54 2Output5334
Input45 00 00 55 511 3
Output2
3 seconds
256 megabytes
['geometry', 'two pointers', '*2500']
D. Beautiful numberstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVolodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.InputThe first line of the input contains the number of cases t (1 ≤ t ≤ 10). Each of the next t lines contains two natural numbers li and ri (1 ≤ li ≤ ri ≤ 9 ·1018).Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).OutputOutput should contain t numbers — answers to the queries, one number per line — quantities of beautiful numbers in given intervals (from li to ri, inclusively).ExamplesInput11 9Output9Input112 15Output2
Input11 9
Output9
4 seconds
256 megabytes
['dp', 'number theory', '*2500']
C. Pie or dietime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVolodya and Vlad play the following game. There are k pies at the cells of n  ×  m board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.InputFirst line contains 3 integers, separated by space: 1 ≤ n, m ≤ 100 — dimensions of the board and 0 ≤ k ≤ 100 — the number of pies. Each of the next k lines contains 2 integers, separated by space: 1 ≤ x ≤ n, 1 ≤ y ≤ m — coordinates of the corresponding pie. There could be more than one pie at a cell. OutputOutput only one word: "YES" — if Volodya wins, "NO" — otherwise.ExamplesInput2 2 11 2OutputYESInput3 4 0OutputNOInput100 50 250 2550 25OutputNO
Input2 2 11 2
OutputYES
2 seconds
256 megabytes
['games', '*1900']
B. Smallest numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.InputFirst line contains four integers separated by space: 0 ≤ a, b, c, d ≤ 1000 — the original numbers. Second line contains three signs ('+' or '*' each) separated by space — the sequence of the operations in the order of performing. ('+' stands for addition, '*' — multiplication)OutputOutput one integer number — the minimal result which can be obtained.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).ExamplesInput1 1 1 1+ + *Output3Input2 2 2 2* * +Output8Input1 2 3 4* + +Output9
Input1 1 1 1+ + *
Output3
2 seconds
256 megabytes
['brute force', '*1600']
A. Flea traveltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA flea is sitting at one of the n hassocks, arranged in a circle, at the moment. After minute number k the flea jumps through k - 1 hassoсks (clockwise). For example, after the first minute the flea jumps to the neighboring hassock. You should answer: will the flea visit all the hassocks or not. We assume that flea has infinitely much time for this jumping.InputThe only line contains single integer: 1 ≤ n ≤ 1000 — number of hassocks.OutputOutput "YES" if all the hassocks will be visited and "NO" otherwise.ExamplesInput1OutputYESInput3OutputNO
Input1
OutputYES
1 second
256 megabytes
['implementation', 'math', '*1200']
E. Vacuum Сleanertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne winter evening the Hedgehog was relaxing at home in his cozy armchair and clicking through the TV channels. Stumbled on an issue of «TopShop», the Hedgehog was about to change the channel when all of a sudden he was stopped by an advertisement of a new wondrous invention.Actually, a vacuum cleaner was advertised there. It was called Marvellous Vacuum and it doesn't even need a human to operate it while it cleans! The vacuum cleaner can move around the flat on its own: it moves in some direction and if it hits an obstacle there, it automatically chooses a new direction. Sooner or later this vacuum cleaner will travel through all the room and clean it all. Having remembered how much time the Hedgehog spends every time on cleaning (surely, no less than a half of the day), he got eager to buy this wonder.However, the Hedgehog quickly understood that the cleaner has at least one weak point: it won't clean well in the room's corners because it often won't able to reach the corner due to its shape. To estimate how serious is this drawback in practice, the Hedgehog asked you to write for him the corresponding program.You will be given the cleaner's shape in the top view. We will consider only the cases when the vacuum cleaner is represented as a convex polygon. The room is some infinitely large rectangle. We consider one corner of this room and want to find such a rotation of the vacuum cleaner so that it, being pushed into this corner, will leave the minimum possible area in the corner uncovered.InputThe first line contains an integer N which represents the number of vertices of the vacuum cleaner's polygon (3 ≤ N ≤ 4·104). Then follow N lines each containing two numbers — the coordinates of a vertex of the polygon. All the coordinates are integer and their absolute values do not exceed 106.It is guaranteed that the given polygon is nondegenerate and convex (no three points lie on the same line). The polygon vertices are given in a clockwise or counter-clockwise direction.OutputPrint the minimum possible uncovered area. The answer will be accepted if it is within 10 - 6 of absolute or relative error from the correct answer.ExamplesInput40 01 01 10 1Output0.00000000000000000000Input81 22 12 -11 -2-1 -2-2 -1-2 1-1 2Output0.50000000000000000000
Input40 01 01 10 1
Output0.00000000000000000000
1 second
256 megabytes
['geometry', '*2700']
D. Writing a Songtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne of the Hedgehog and his friend's favorite entertainments is to take some sentence or a song and replace half of the words (sometimes even all of them) with each other's names.The friend's birthday is approaching and the Hedgehog decided to make a special present to his friend: a very long song, where his name will be repeated many times. But try as he might, he can't write a decent song!The problem is that the Hedgehog has already decided how long the resulting sentence should be (i.e. how many letters it should contain) and in which positions in the sentence the friend's name should occur, and it must not occur in any other position in the sentence. Besides, the Hedgehog decided to limit himself to using only the first K letters of an English alphabet in this sentence (so it will be not even a sentence, but one long word).The resulting problem is indeed quite complicated, that's why the Hedgehog asks you to help him and write a program that will make the desired word by the given name P, the length N of the required word, the given positions of the occurrences of the name P in the desired word and the alphabet's size K. Note that the occurrences of the name can overlap with each other.InputThe first line contains numbers N and K which are the length of the required string and the alphabet size accordingly. The limitations are: 1 ≤ N ≤ 100, 2 ≤ K ≤ 26.The second line contains the name P which is a non-empty string whose length does not exceed N characters. The string consists only of the first K lowercase symbols of an English alphabet.The third line contains the string of length N - length(P) + 1, consisting only of numbers zero and one. A number one in the i-th position means that an occurrence of the name P should start from i-th position of the desired word, while a zero means that there is no occurrence starting here. OutputPrint the desired word S. If there are several answers, print any of them.If there is no solution, then print "No solution".ExamplesInput5 2aba101OutputababaInput5 2a10001OutputabbbaInput6 2abba101OutputNo solution
Input5 2aba101
Outputababa
2 seconds
256 megabytes
['brute force', 'dp', 'strings', '*2100']
C. First Digit Lawtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law).Having read about it on Codeforces, the Hedgehog got intrigued by the statement and wishes to thoroughly explore it. He finds the following similar problem interesting in particular: there are N random variables, the i-th of which can take any integer value from some segment [Li;Ri] (all numbers from this segment are equiprobable). It means that the value of the i-th quantity can be equal to any integer number from a given interval [Li;Ri] with probability 1 / (Ri - Li + 1).The Hedgehog wants to know the probability of the event that the first digits of at least K% of those values will be equal to one. In other words, let us consider some set of fixed values of these random variables and leave only the first digit (the MSD — most significant digit) of each value. Then let's count how many times the digit 1 is encountered and if it is encountered in at least K per cent of those N values, than such set of values will be called a good one. You have to find the probability that a set of values of the given random variables will be a good one.InputThe first line contains number N which is the number of random variables (1 ≤ N ≤ 1000). Then follow N lines containing pairs of numbers Li, Ri, each of whom is a description of a random variable. It is guaranteed that 1 ≤ Li ≤ Ri ≤ 1018.The last line contains an integer K (0 ≤ K ≤ 100).All the numbers in the input file are integers.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).OutputPrint the required probability. Print the fractional number with such a precision that the relative or absolute error of the result won't exceed 10 - 9.ExamplesInput11 250Output0.500000000000000Input21 29 1150Output0.833333333333333
Input11 250
Output0.500000000000000
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*2000']
B. Cutting Jigsaw Puzzletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Hedgehog recently remembered one of his favorite childhood activities, — solving puzzles, and got into it with new vigor. He would sit day in, day out with his friend buried into thousands of tiny pieces of the picture, looking for the required items one by one.Soon the Hedgehog came up with a brilliant idea: instead of buying ready-made puzzles, one can take his own large piece of paper with some picture and cut it into many small rectangular pieces, then mix them and solve the resulting puzzle, trying to piece together the picture. The resulting task is even more challenging than the classic puzzle: now all the fragments have the same rectangular shape, and one can assemble the puzzle only relying on the picture drawn on the pieces.All puzzle pieces turn out to be of the same size X × Y, because the picture is cut first by horizontal cuts with the pitch of X, then with vertical cuts with the pitch of Y. If we denote the initial size of the picture as A × B, then A must be divisible by X and B must be divisible by Y (X and Y are integer numbers). However, not every such cutting of the picture will result in a good puzzle. The Hedgehog finds a puzzle good if no two pieces in it are the same (It is allowed to rotate the pieces when comparing them, but it is forbidden to turn them over). Your task is to count for a given picture the number of good puzzles that you can make from it, and also to find the puzzle with the minimal piece size.InputThe first line contains two numbers A and B which are the sizes of the picture. They are positive integers not exceeding 20.Then follow A lines containing B symbols each, describing the actual picture. The lines only contain uppercase English letters.OutputIn the first line print the number of possible good puzzles (in other words, the number of pairs (X, Y) such that the puzzle with the corresponding element sizes will be good). This number should always be positive, because the whole picture is a good puzzle itself. In the second line print two numbers — the sizes X and Y of the smallest possible element among all good puzzles. The comparison is made firstly by the area XY of one element and secondly — by the length X.ExamplesInput2 4ABDCABDCOutput32 1Input2 6ABCCBAABCCBAOutput12 6NoteThe picture in the first sample test has the following good puzzles: (2, 1), (2, 2), (2, 4).
Input2 4ABDCABDC
Output32 1
2 seconds
256 megabytes
['hashing', 'implementation', '*1800']
A. Presentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Hedgehog likes to give presents to his friend, but no less he likes to receive them.Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following N days. Besides, he is guided by the principle: on each holiday day the Hedgehog will necessarily receive a present, he receives presents at least every K days (i.e., if he received a present on the i-th day, he will receive the next present no later than on the i + K-th day). For the given N and K, as well as the list of holidays among the following N days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).InputThe first line contains integers N and K (1 ≤ N ≤ 365, 1 ≤ K ≤ N).The second line contains a number C which represents the number of holidays (0 ≤ C ≤ N). Then in the same line follow C numbers ranging from 1 to N which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.OutputPrint a single number — the minimal number of presents the Hedgehog will receive over the following N days.ExamplesInput5 21 3Output3Input10 13 6 7 8Output10
Input5 21 3
Output3
2 seconds
256 megabytes
['implementation', '*1300']
E. Dead Endstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLife in Bertown has become hard. The city has too many roads and the government spends too much to maintain them. There are n junctions and m two way roads, at which one can get from each junction to any other one. The mayor wants to close some roads so that the number of roads left totaled to n - 1 roads and it were still possible to get from each junction to any other one. Besides, the mayor is concerned with the number of dead ends which are the junctions from which only one road goes. There shouldn't be too many or too few junctions. Having discussed the problem, the mayor and his assistants decided that after the roads are closed, the road map should contain exactly k dead ends. Your task is to count the number of different ways of closing the roads at which the following conditions are met: There are exactly n - 1 roads left. It is possible to get from each junction to any other one. There are exactly k dead ends on the resulting map. Two ways are considered different if there is a road that is closed in the first way, and is open in the second one.InputThe first line contains three integers n, m and k (3 ≤ n ≤ 10, n - 1 ≤ m ≤ n·(n - 1) / 2, 2 ≤ k ≤ n - 1) which represent the number of junctions, roads and dead ends correspondingly. Then follow m lines each containing two different integers v1 and v2 (1 ≤ v1, v2 ≤ n, v1 ≠ v2) which represent the number of junctions connected by another road. There can be no more than one road between every pair of junctions. The junctions are numbered with integers from 1 to n. It is guaranteed that it is possible to get from each junction to any other one along the original roads.OutputPrint a single number — the required number of ways.ExamplesInput3 3 21 22 31 3Output3Input4 6 21 22 33 44 11 32 4Output12Input4 6 31 22 33 44 11 32 4Output4
Input3 3 21 22 31 3
Output3
5 seconds
256 megabytes
['bitmasks', 'dp', '*2500']
D. Physical Educationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.InputThe first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.OutputIn the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.ExamplesInput41 2 3 23 2 1 2Output42 31 23 42 3Input21 1005001 100500Output0
Input41 2 3 23 2 1 2
Output42 31 23 42 3
2 seconds
256 megabytes
['sortings', '*1500']
C. Little Frogtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.InputThe single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds.OutputPrint n integers pi (1 ≤ pi ≤ n) which are the frog's route plan. All the pi's should be mutually different. All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1). If there are several solutions, output any.ExamplesInput2Output1 2 Input3Output1 3 2
Input2
Output1 2
2 seconds
256 megabytes
['constructive algorithms', '*1200']
B. Blog Phototime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the height / width quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 (2x for some integer x). If those rules don't indicate the size of the cut are clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, you should choose the answer with the maximal height.InputThe first line contains a pair of integers h and w (1 ≤ h, w ≤ 109) which are the height and width of the uploaded photo in pixels.OutputPrint two integers which are the height and width of the cut area.ExamplesInput2 1Output1 1Input2 2Output2 2Input5 5Output5 4
Input2 1
Output1 1
2 seconds
256 megabytes
['binary search', 'implementation', '*1700']
A. Autocompletetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAutocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s.InputThe first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only.OutputIf s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s.The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages.ExamplesInputnext2nextpermutationnextelementOutputnextelementInputfind4findfindfirstoffinditfandOutputfindInputfind4fondfindfondfirstoffonditfandOutputfind
Inputnext2nextpermutationnextelement
Outputnextelement
2 seconds
256 megabytes
['implementation', '*1100']
C. Circular RMQtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given circular array a0, a1, ..., an - 1. There are two types of operations with it: inc(lf, rg, v) — this operation increases each element on the segment [lf, rg] (inclusively) by v; rmq(lf, rg) — this operation returns minimal value on the segment [lf, rg] (inclusively). Assume segments to be circular, so if n = 5 and lf = 3, rg = 1, it means the index sequence: 3, 4, 0, 1.Write program to process given sequence of operations.InputThe first line contains integer n (1 ≤ n ≤ 200000). The next line contains initial state of the array: a0, a1, ..., an - 1 ( - 106 ≤ ai ≤ 106), ai are integer. The third line contains integer m (0 ≤ m ≤ 200000), m — the number of operartons. Next m lines contain one operation each. If line contains two integer lf, rg (0 ≤ lf, rg ≤ n - 1) it means rmq operation, it contains three integers lf, rg, v (0 ≤ lf, rg ≤ n - 1; - 106 ≤ v ≤ 106) — inc operation.OutputFor each rmq operation write result for it. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).ExamplesInput41 2 3 443 03 0 -10 12 1Output100
Input41 2 3 443 03 0 -10 12 1
Output100
1.5 seconds
256 megabytes
['data structures', '*2200']
B. Right Trianglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a n × m field consisting only of periods ('.') and asterisks ('*'). Your task is to count all right triangles with two sides parallel to the square sides, whose vertices are in the centers of '*'-cells. A right triangle is a triangle in which one angle is a right angle (that is, a 90 degree angle).InputThe first line contains two positive integer numbers n and m (1 ≤ n, m ≤ 1000). The following n lines consist of m characters each, describing the field. Only '.' and '*' are allowed.OutputOutput a single number — total number of square triangles in the field. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).ExamplesInput2 2***.Output1Input3 4*..*.**.*.**Output9
Input2 2***.
Output1
2 seconds
256 megabytes
['combinatorics', '*1600']
A. 123-sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.InputThe first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3).OutputPrint the minimum number of replacements needed to be performed to make all the numbers in the sequence equal.ExamplesInput91 3 2 2 2 1 1 2 3Output5NoteIn the example all the numbers equal to 1 and 3 should be replaced by 2.
Input91 3 2 2 2 1 1 2 3
Output5
2 seconds
256 megabytes
['implementation', '*900']
F. Caterpillartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn undirected graph is called a caterpillar if it is a connected graph without cycles and it has such a path p that any vertex is located at a distance of at most 1 from the path p. The caterpillar can contain loops (edges from a vertex to itself) but cannot contain multiple (parallel) edges.The picture contains an example of a caterpillar: You are given an undirected graph G. You are allowed to do a merging operations, each such operation merges two vertices into one vertex. For that two any vertices a and b (a ≠ b) are chosen. These verteces are deleted together with their edges (which are incident to at least one of the vertices a or b) but a new vertex w is added together with edges (x, w) for each edge (a, w) and/or (b, w). If there was the edge (a, b) it transforms to the loop (w, w). The resulting graph (after the merging operation) may contain multiple (parallel) edges between pairs of vertices and loops. Let us note that this operation decreases the number of vertices of graph by 1 but leaves the number of edges in the graph unchanged.The merging operation can be informally described as a unity of two vertices of the graph into one with the natural transformation of the graph edges.You may apply this operation consecutively and make the given graph to be a caterpillar. Write a program that will print the minimal number of merging operations required to make the given graph a caterpillar.InputThe first line contains a pair of integers n, m (1 ≤ n ≤ 2000;0 ≤ m ≤ 105), where n represents the number of vertices in the graph and m is the number of edges in it. Then the following m lines contain edge descriptions, one edge description per line. Every line contains a pair of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), ai, bi which represent the indices of the vertices connected by the edge. The vertices are numbered from 1 to n. In the given graph it will be no more than one edge between any pair of vertices. The given graph is not necessarily connected.OutputPrint the minimal required number of operations.ExamplesInput4 41 22 33 44 2Output2Input6 31 23 45 6Output2Input7 61 22 31 44 51 66 7Output1
Input4 41 22 33 44 2
Output2
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'trees', '*2800']
E. Pentagontime limit per test10 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAccording to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase.InputThe first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads.OutputPrint the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).ExamplesInput5 51 22 33 44 55 1Output1Input5 101 21 31 41 52 32 42 53 43 54 5Output12
Input5 51 22 33 44 55 1
Output1
10 seconds
256 megabytes
['combinatorics', 'graphs', 'matrices', '*2400']
D. Geometrical problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ..., ak, where ai = c·bi - 1 for some real numbers c and b. For example, the sequences [2, -4, 8], [0, 0, 0, 0], [199] are geometric progressions and [0, 1, 2, 3] is not.Recently Polycarp has found a sequence and he can't classify it. Help him to do it. Determine whether it is a geometric progression. If it is not, check if it can become a geometric progression if an element is deleted from it.InputThe first line contains an integer n (1 ≤ n ≤ 105) — the number of elements in the given sequence. The second line contains the given sequence. The numbers are space-separated. All the elements of the given sequence are integers and their absolute value does not exceed 104.OutputPrint 0, if the given sequence is a geometric progression. Otherwise, check if it is possible to make the sequence a geometric progression by deleting a single element. If it is possible, print 1. If it is impossible, print 2.ExamplesInput43 6 12 24Output0Input4-8 -16 24 -32Output1Input40 1 2 3Output2
Input43 6 12 24
Output0
1 second
256 megabytes
['implementation', '*2200']
C. Three Base Stationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe New Vasjuki village is stretched along the motorway and that's why every house on it is characterized by its shift relative to some fixed point — the xi coordinate. The village consists of n houses, the i-th house is located in the point with coordinates of xi.TELE3, a cellular communication provider planned to locate three base stations so as to provide every house in the village with cellular communication. The base station having power d located in the point t provides with communication all the houses on the segment [t - d, t + d] (including boundaries).To simplify the integration (and simply not to mix anything up) all the three stations are planned to possess the equal power of d. Which minimal value of d is enough to provide all the houses in the village with cellular communication.InputThe first line contains an integer n (1 ≤ n ≤ 2·105) which represents the number of houses in the village. The second line contains the coordinates of houses — the sequence x1, x2, ..., xn of integer numbers (1 ≤ xi ≤ 109). It is possible that two or more houses are located on one point. The coordinates are given in a arbitrary order.OutputPrint the required minimal power d. In the second line print three numbers — the possible coordinates of the base stations' location. Print the coordinates with 6 digits after the decimal point. The positions of the stations can be any from 0 to 2·109 inclusively. It is accepted for the base stations to have matching coordinates. If there are many solutions, print any of them.ExamplesInput41 2 3 4Output0.5000001.500000 2.500000 3.500000Input310 20 30Output010.000000 20.000000 30.000000Input510003 10004 10001 10002 1Output0.5000001.000000 10001.500000 10003.500000
Input41 2 3 4
Output0.5000001.500000 2.500000 3.500000
1 second
256 megabytes
['binary search', 'greedy', '*1800']
B. bHTML Tables Analisystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.A string is a bHTML table, if it satisfies the grammar: TABLE ::= <table>ROWS</table>ROWS ::= ROW | ROW ROWSROW ::= <tr>CELLS</tr>CELLS ::= CELL | CELL CELLSCELL ::= <td></td> | <td>TABLE</td>Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables.As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.InputFor convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s.OutputPrint the sizes of all the tables in the non-decreasing order.ExamplesInput<table><tr><td></td></tr></table>Output1 Input<table><tr><td><table><tr><td></td></tr><tr><td></td></tr><tr><td></td></tr><tr><td></td></tr></table></td></tr></table>Output1 4 Input<table><tr><td><table><tr><td><table><tr><td><table><tr><td></td><td></td></tr><tr><td></td></tr></table></td></tr></table></td></tr></table></td></tr></table>Output1 1 1 3
Input<table><tr><td></td></tr></table>
Output1
2 seconds
256 megabytes
['expression parsing', '*1700']
A. Cheaterius's Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2 × 2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2 × 2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk.InputThe first line contains an integer n (1 ≤ n ≤ 1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located.OutputPrint the required number of piles.ExamplesInput43123**3123**1332**3213Output1Input45126**5435**2561**4553Output2
Input43123**3123**1332**3213
Output1
2 seconds
256 megabytes
['implementation', '*1300']
E. Square Equation Rootstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple: x2 + 2bx + c = 0 where b, c are natural numbers.Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all. Moreover it turned out that several different square equations can have a common root.Petya is interested in how many different real roots have all the equations of the type described above for all the possible pairs of numbers b and c such that 1 ≤ b ≤ n, 1 ≤ c ≤ m. Help Petya find that number.InputThe single line contains two integers n and m. (1 ≤ n, m ≤ 5000000).OutputPrint a single number which is the number of real roots of the described set of equations.ExamplesInput3 3Output12Input1 2Output1NoteIn the second test from the statement the following equations are analysed: b = 1, c = 1: x2 + 2x + 1 = 0; The root is x =  - 1 b = 1, c = 2: x2 + 2x + 2 = 0; No roots Overall there's one rootIn the second test the following equations are analysed: b = 1, c = 1: x2 + 2x + 1 = 0; The root is x =  - 1 b = 1, c = 2: x2 + 2x + 2 = 0; No roots b = 1, c = 3: x2 + 2x + 3 = 0; No roots b = 2, c = 1: x2 + 4x + 1 = 0; The roots are b = 2, c = 2: x2 + 4x + 2 = 0; The roots are b = 2, c = 3: x2 + 4x + 3 = 0; The roots are x1 =  - 3, x2 =  - 1 b = 3, c = 1: x2 + 6x + 1 = 0; The roots are b = 3, c = 2: x2 + 6x + 2 = 0; The roots are b = 3, c = 3: x2 + 6x + 3 = 0; The roots are Overall there are 13 roots and as the root  - 1 is repeated twice, that means there are 12 different roots.
Input3 3
Output12
5 seconds
256 megabytes
['math', '*2300']
D. Bombingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used.The enemy has N strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least K important objects of the enemy. The bombing impact point is already determined and has coordinates of [X0; Y0].The nuclear warhead is marked by the estimated impact radius R ≥ 0. All the buildings that are located closer than R to the bombing epicentre will be destroyed. All the buildings that are located further than R from the epicentre, can also be deactivated with some degree of probability. Let's assume that D is the distance between a building and the epicentre. This building's deactivation probability P(D, R) is calculated according to the following formula: We should regard as ea, where e ≈ 2.7182818284590452353602874713527If the estimated impact radius of the warhead is equal to zero, then all the buildings located in the impact point will be completely demolished and all the rest of important objects will not be damaged.The commanding officers want the probability of failing the task to be no more than ε. Nuclear warheads are too expensive a luxury, that's why you have to minimise the estimated impact radius of the warhead. InputThe first line contains an integer N which represents the number of the enemy's objects (1 ≤ N ≤ 100). The second line contains two integers: K is the required number of deactivated objects, and ε is the maximally permitted probability of not completing the task, given in per mils (1 ≤ K ≤ N, 1 ≤ ε ≤ 999). The third line contains X0 and Y0 which are the coordinates of the strike impact point. The next N lines contain two numbers Xi and Yi each which are the coordinates of every strategically important object. All the coordinates are integer, their absolute values do not exceed 1000.Let us remind you that there are a thousand per mils in unity (number one).There can be several objects in one point.OutputPrint the sought estimated impact radius of the warhead. The absolute or relative measure of the inaccuracy of your answer should not exceed 10 - 6.ExamplesInput11 5005 51 2Output3.84257761518762740Input53 1000 03 460 70100 10010 105 12Output13.45126176453737600
Input11 5005 51 2
Output3.84257761518762740
2 seconds
256 megabytes
['binary search', 'dp', 'probabilities', '*2100']
C. Happy Farm 5time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them. For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum.The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to 1, and the length of a diagonal step is equal to . The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.InputThe first line contains an integer N which represents the number of cows in the herd (1 ≤ N ≤ 105). Each of the next N lines contains two integers Xi and Yi which represent the coordinates of one cow of (|Xi|, |Yi| ≤ 106). Several cows can stand on one point.OutputPrint the single number — the minimum number of moves in the sought path.ExamplesInput41 15 15 31 3Output16NotePicture for the example test: The coordinate grid is painted grey, the coordinates axes are painted black, the cows are painted red and the sought route is painted green.
Input41 15 15 31 3
Output16
2 seconds
256 megabytes
['geometry', '*2000']
B. Choosing Symbol Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that1. 1 ≤ i, j ≤ N2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.InputThe single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.OutputPrint a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.ExamplesInputgreat10Output7InputaaaaaaaaaaOutput100
Inputgreat10
Output7
2 seconds
256 megabytes
['strings', '*1500']
A. Domino pilingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:1. Each domino completely covers two squares.2. No two dominoes overlap.3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.Find the maximum number of dominoes, which can be placed under these restrictions.InputIn a single line you are given two integers M and N — board sizes in squares (1 ≤ M ≤ N ≤ 16).OutputOutput one number — the maximal number of dominoes, which can be placed.ExamplesInput2 4Output4Input3 3Output4
Input2 4
Output4
2 seconds
256 megabytes
['greedy', 'math', '*800']
E. Common ancestortime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe DNA sequence for every living creature in Berland can be represented as a non-empty line consisting of lowercase Latin letters. Berland scientists found out that all the creatures evolve by stages. During one stage exactly one symbol of the DNA line is replaced by exactly two other ones. At that overall there are n permissible substitutions. The substitution ai->bici means that any one symbol ai can be replaced with two symbols bici. Every substitution could happen an unlimited number of times.They say that two creatures with DNA sequences s1 and s2 can have a common ancestor if there exists such a DNA sequence s3 that throughout evolution it can result in s1 and s2, perhaps after a different number of stages. Your task is to find out by the given s1 and s2 whether the creatures possessing such DNA sequences can have a common ancestor. If the answer is positive, you have to find the length of the shortest sequence of the common ancestor’s DNA.InputThe first line contains a non-empty DNA sequence s1, the second line contains a non-empty DNA sequence s2. The lengths of these lines do not exceed 50, the lines contain only lowercase Latin letters. The third line contains an integer n (0 ≤ n ≤ 50) — the number of permissible substitutions. Then follow n lines each of which describes a substitution in the format ai->bici. The characters ai, bi, and ci are lowercase Latin letters. Lines s1 and s2 can coincide, the list of substitutions can contain similar substitutions.OutputIf s1 and s2 cannot have a common ancestor, print -1. Otherwise print the length of the shortest sequence s3, from which s1 and s2 could have evolved.ExamplesInputababaaba2c->bac->ccOutput2Inputababaaba7c->bac->cce->abz->eab->bad->ddd->abOutput1Inputababaaba1c->baOutput-1
Inputababaaba2c->bac->cc
Output2
5 seconds
256 megabytes
['dp', '*2300']
D. Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win.InputThe first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one.OutputIf Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win.ExamplesInput6111010Output1Input510001Output1Input71100010Output2Input500100Output2NoteIn the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white.In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black.
Input6111010
Output1
2 seconds
256 megabytes
['brute force', 'dp', 'implementation', '*1800']
C. Dispositiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya bought the collected works of a well-known Berland poet Petya in n volumes. The volumes are numbered from 1 to n. He thinks that it does not do to arrange the book simply according to their order. Vasya wants to minimize the number of the disposition’s divisors — the positive integers i such that for at least one j (1 ≤ j ≤ n) is true both: j mod i = 0 and at the same time p(j) mod i = 0, where p(j) is the number of the tome that stands on the j-th place and mod is the operation of taking the division remainder. Naturally, one volume can occupy exactly one place and in one place can stand exactly one volume.Help Vasya — find the volume disposition with the minimum number of divisors.InputThe first line contains number n (1 ≤ n ≤ 100000) which represents the number of volumes and free places.OutputPrint n numbers — the sought disposition with the minimum divisor number. The j-th number (1 ≤ j ≤ n) should be equal to p(j) — the number of tome that stands on the j-th place. If there are several solutions, print any of them.ExamplesInput2Output2 1 Input3Output1 3 2
Input2
Output2 1
2 seconds
256 megabytes
['constructive algorithms', 'math', '*1700']
B. Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya studies positional numeral systems. Unfortunately, he often forgets to write the base of notation in which the expression is written. Once he saw a note in his notebook saying a + b = ?, and that the base of the positional notation wasn’t written anywhere. Now Vasya has to choose a base p and regard the expression as written in the base p positional notation. Vasya understood that he can get different results with different bases, and some bases are even invalid. For example, expression 78 + 87 in the base 16 positional notation is equal to FF16, in the base 15 positional notation it is equal to 11015, in the base 10 one — to 16510, in the base 9 one — to 1769, and in the base 8 or lesser-based positional notations the expression is invalid as all the numbers should be strictly less than the positional notation base. Vasya got interested in what is the length of the longest possible expression value. Help him to find this length.The length of a number should be understood as the number of numeric characters in it. For example, the length of the longest answer for 78 + 87 = ? is 3. It is calculated like that in the base 15 (11015), base 10 (16510), base 9 (1769) positional notations, for example, and in some other ones.InputThe first letter contains two space-separated numbers a and b (1 ≤ a, b ≤ 1000) which represent the given summands.OutputPrint a single number — the length of the longest answer.ExamplesInput78 87Output3Input1 1Output2
Input78 87
Output3
2 seconds
256 megabytes
['math', '*1500']
A. Sleuthtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.The English alphabet vowels are: A, E, I, O, U, YThe English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, ZInputThe single line contains a question represented by a non-empty line consisting of large and small Latin letters, spaces and a question mark. The line length does not exceed 100. It is guaranteed that the question mark occurs exactly once in the line — as the last symbol and that the line contains at least one letter.OutputPrint answer for the question in a single line: YES if the answer is "Yes", NO if the answer is "No".Remember that in the reply to the question the last letter, not the last character counts. I. e. the spaces and the question mark do not count as letters.ExamplesInputIs it a melon?OutputNOInputIs it an apple?OutputYESInput Is it a banana ?OutputYESInputIs it an apple and a banana simultaneouSLY?OutputYES
InputIs it a melon?
OutputNO
2 seconds
256 megabytes
['implementation', '*800']
H. Black and Whitetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAccording to the legends the king of Berland Berl I was noted for his love of beauty and order. One day he ordered to tile the palace hall's floor where balls and receptions used to take place with black and white tiles according to a regular geometrical pattern invented by him. However, as is after the case, due to low financing there were only a black and b white tiles delivered to the palace. The other c tiles were black and white (see the picture). The initial plan failed! Having learned of that, the king gave a new command: tile the floor with the available tiles so that no black side of a tile touched a white one. The tiles are squares of one size 1 × 1, every black and white tile can be rotated in one of the four ways. The court programmer was given the task to work out the plan of tiling and he coped with the task and didn't suffer the consequences of disobedience. And can you cope with it?InputThe first line contains given integers n and m (1 ≤ n, m ≤ 100) which represent the sizes of the rectangle that needs to be tiled. The next line contains non-negative numbers a, b and c, a + b + c = nm, c ≥ m. OutputPrint 2n lines containing 2m characters each — the tiling scheme. Every tile is represented by a square 2 × 2 in the following manner (the order corresponds to the order of the picture above): If multiple solutions exist, output any.ExamplesInput2 20 0 4Output\../#\/#\##/.\/.Input2 31 2 3Output###/\###/..\#/..../.....
Input2 20 0 4
Output\../#\/#\##/.\/.
2 seconds
256 megabytes
['constructive algorithms', '*2800']
G. Galaxy Uniontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a far away galaxy there are n inhabited planets numbered with numbers from 1 to n. One day the presidents of all the n planets independently from each other came up with an idea of creating the Galaxy Union. Now they need to share this wonderful idea with their galaxymates, that’s why each president is busy working out a project of negotiating with the other presidents.For negotiations between some pairs of the planets there are bidirectional communication channels, each of which is characterized with "dial duration" ti which, as a rule, takes several hours and exceeds the call duration greatly. Overall the galaxy has n communication channels and they unite all the planets into a uniform network. That means that it is possible to phone to any planet v from any planet u, perhaps, using some transitional planets v1, v2, ..., vm via the existing channels between u and v1, v1 and v2, ..., vm - 1 and vm, vm and v. At that the dial duration from u to v will be equal to the sum of dial durations of the used channels.So, every president has to talk one by one to the presidents of all the rest n - 1 planets. At that the negotiations take place strictly consecutively, and until the negotiations with a planet stop, the dial to another one does not begin. As the matter is urgent, from the different ways to call the needed planet every time the quickest one is chosen. Little time is needed to assure another president on the importance of the Galaxy Union, that’s why the duration of the negotiations with each planet can be considered equal to the dial duration time for those planets. As the presidents know nothing about each other’s plans, they do not take into consideration the possibility that, for example, the sought president may call himself or already know about the founding of the Galaxy Union from other sources.The governments of all the n planets asked you to work out the negotiation plans. First you are to find out for every president how much time his supposed negotiations will take.InputThe first line contains an integer n (3 ≤ n ≤ 200000) which represents the number of planets in the Galaxy and the number of communication channels equal to it. The next n lines contain three integers each ai, bi and ti (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ti ≤ 103) that represent the numbers of planet joined by a communication channel and its "dial duration". There can be no more than one communication channel between a pair of planets. OutputIn the first line output n integers — the durations of the supposed negotiations for each president. Separate the numbers by spaces.ExamplesInput31 2 32 3 21 3 1Output4 5 3Input31 2 32 3 21 3 5Output8 5 7Input41 2 32 3 23 4 14 1 4Output12 8 8 8
Input31 2 32 3 21 3 1
Output4 5 3
3 seconds
256 megabytes
['dp', 'trees', 'two pointers', '*2700']
F. Snow sellerstime limit per test10 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe New Year celebrations in Berland last n days. Only this year the winter is snowless, that’s why the winter celebrations’ organizers should buy artificial snow. There are m snow selling companies in Berland. Every day the i-th company produces wi cubic meters of snow. Next day the snow thaws and the company has to produce wi cubic meters of snow again. During the celebration new year discounts are on, that’s why the snow cost decreases every day. It is known that on the first day the total cost of all the snow produced by the i-th company is equal to ci bourles. Every day this total cost decreases by ai bourles, i.e. on the second day it is equal to ci - ai,and on the third day — to ci - 2ai, and so on. It is known that for one company the cost of the snow produced by it does not get negative or equal to zero. You have to organize the snow purchase so as to buy every day exactly W snow cubic meters. At that it is not necessary to buy from any company all the snow produced by it. If you buy ni cubic meters of snow (0 ≤ ni ≤ wi, the number ni is not necessarily integer!) from the i-th company at one of the days when the cost of its snow is equal to si, then its price will total to bourles. During one day one can buy the snow from several companies. In different days one can buy the snow from different companies. It is required to make the purchases so as to spend as little money as possible. It is guaranteed that the snow produced by the companies will be enough.InputThe first line contains integers n, m and W (1 ≤ n ≤ 100, 1 ≤ m ≤ 500000, 1 ≤ W ≤ 109) which represent the number of days, the number of companies and the amount of snow that needs to be purchased on every one of the n days. The second line contains m integers wi. The third line contains m integers ci. The fourth line contains m integers ai. All the numbers are strictly positive and do not exceed 109. For all the i the inequation ci - (n - 1)ai > 0 holds true. OutputPrint a single number — the answer to the given problem. Print the answer in the format with the decimal point (even if the answer is integer, it must contain the decimal point), without "e" and without leading zeroes. The answer should differ with the right one by no more than 10 - 9.ExamplesInput2 3 104 4 45 5 81 2 5Output22.000000000000000Input100 2 1000000000999999998 9999999991000000000 10000000001 1Output99999995149.999995249999991
Input2 3 104 4 45 5 81 2 5
Output22.000000000000000
10 seconds
256 megabytes
['greedy', 'sortings', '*2800']
E. Ivan the Fool VS Gorynych the Dragontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time in a kingdom far, far away… Okay, let’s start at the point where Ivan the Fool met Gorynych the Dragon. Ivan took out his magic sword and the battle began. First Gorynych had h heads and t tails. With each strike of the sword Ivan can either cut off several heads (from 1 to n, but not more than Gorynych has at the moment), or several tails (from 1 to m, but not more than Gorynych has at the moment). At the same time, horrible though it seems, Gorynych the Dragon can also grow new heads and tails. And the number of growing heads and tails is determined uniquely by the number of heads or tails cut by the current strike. When the total number of heads and tails exceeds R, Gorynych the Dragon strikes its final blow and destroys Ivan the Fool. That’s why Ivan aims to cut off all the dragon’s heads and tails as quickly as possible and win. The events can also develop in a third way: neither of the opponents can win over the other one and they will continue fighting forever.The tale goes like this; easy to say, hard to do. Your task is to write a program that will determine the battle’s outcome. Consider that Ivan strikes consecutively. After each blow Gorynych grows a number of new heads and tails depending on the number of cut ones. Gorynych the Dragon is defeated if after the blow he loses all his heads and tails and can’t grow new ones. Ivan fights in the optimal way (fools are lucky), i.e. if Ivan can win, he wins having struck the least number of blows; if it is impossible to defeat Gorynych, but is possible to resist him for an infinitely long period of time, then that’s the strategy Ivan chooses; if Gorynych wins in any case, Ivan aims to resist him for as long as possible. InputThe first line contains three integers h, t and R (0 ≤ h, t, R ≤ 200, 0 < h + t ≤ R) which represent the initial numbers of Gorynych’s heads and tails and the largest total number of heads and tails with which Gorynych the Dragon does not yet attack. The next line contains integer n (1 ≤ n ≤ 200). The next n contain pairs of non-negative numbers "hi ti" which represent the number of heads and the number of tails correspondingly, that will grow if Gorynych has i heads (1 ≤ i ≤ n) cut. The next line contains an integer m (1 ≤ m ≤ 200) and then — the description of Gorynych’s behavior when his tails are cut off in the format identical to the one described above. All the numbers in the input file do not exceed 200. OutputPrint "Ivan" (without quotes) in the first line if Ivan wins, or "Zmey" (that means a dragon in Russian) if Gorynych the Dragon wins. In the second line print a single integer which represents the number of blows Ivan makes. If the battle will continue forever, print in the first line "Draw".ExamplesInput2 2 421 00 130 10 10 0OutputIvan2Input2 2 410 111 0OutputDrawInput2 2 511 113 0OutputZmey2
Input2 2 421 00 130 10 10 0
OutputIvan2
2 seconds
256 megabytes
['dp', 'games', 'graphs', '*2100']
D. Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation is a sequence of integers from 1 to n of length n containing each number exactly once. For example, (1), (4, 3, 5, 1, 2), (3, 2, 1) are permutations, and (1, 1), (4, 3, 1), (2, 3, 4) are not. There are many tasks on permutations. Today you are going to solve one of them. Let’s imagine that somebody took several permutations (perhaps, with a different number of elements), wrote them down consecutively as one array and then shuffled the resulting array. The task is to restore the initial permutations if it is possible.InputThe first line contains an integer n (1 ≤ n ≤ 105). The next line contains the mixed array of n integers, divided with a single space. The numbers in the array are from 1 to 105.OutputIf this array can be split into several permutations so that every element of the array belongs to exactly one permutation, print in the first line the number of permutations. The second line should contain n numbers, corresponding to the elements of the given array. If the i-th element belongs to the first permutation, the i-th number should be 1, if it belongs to the second one, then its number should be 2 and so on. The order of the permutations’ numbering is free.If several solutions are possible, print any one of them. If there’s no solution, print in the first line  - 1.ExamplesInput91 2 3 1 2 1 4 2 5Output33 1 2 1 2 2 2 3 2Input44 3 2 1Output11 1 1 1 Input41 2 2 3Output-1NoteIn the first sample test the array is split into three permutations: (2, 1), (3, 2, 1, 4, 5), (1, 2). The first permutation is formed by the second and the fourth elements of the array, the second one — by the third, the fifth, the sixth, the seventh and the ninth elements, the third one — by the first and the eigth elements. Clearly, there are other splitting variants possible.
Input91 2 3 1 2 1 4 2 5
Output33 1 2 1 2 2 2 3 2
1 second
256 megabytes
['greedy', '*1500']
C. The Racetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery year a race takes place on the motorway between cities A and B. This year Vanya decided to take part in the race and drive his own car that has been around and bears its own noble name — The Huff-puffer.So, Vasya leaves city A on the Huff-puffer, besides, at the very beginning he fills the petrol tank with α liters of petrol (α ≥ 10 is Vanya's favorite number, it is not necessarily integer). Petrol stations are located on the motorway at an interval of 100 kilometers, i.e. the first station is located 100 kilometers away from the city A, the second one is 200 kilometers away from the city A, the third one is 300 kilometers away from the city A and so on. The Huff-puffer spends 10 liters of petrol every 100 kilometers. Vanya checks the petrol tank every time he passes by a petrol station. If the petrol left in the tank is not enough to get to the next station, Vanya fills the tank with α liters of petrol. Otherwise, he doesn't stop at the station and drives on. For example, if α = 43.21, then the car will be fuelled up for the first time at the station number 4, when there'll be 3.21 petrol liters left. After the fuelling up the car will have 46.42 liters. Then Vanya stops at the station number 8 and ends up with 6.42 + 43.21 = 49.63 liters. The next stop is at the station number 12, 9.63 + 43.21 = 52.84. The next stop is at the station number 17 and so on. You won't believe this but the Huff-puffer has been leading in the race! Perhaps it is due to unexpected snow. Perhaps it is due to video cameras that have been installed along the motorway which register speed limit breaking. Perhaps it is due to the fact that Vanya threatened to junk the Huff-puffer unless the car wins. Whatever the reason is, the Huff-puffer is leading, and jealous people together with other contestants wrack their brains trying to think of a way to stop that outrage.One way to do this is to mine the next petrol station where Vanya will stop. Your task is to calculate at which station this will happen and warn Vanya. You don't know the α number, however, you are given the succession of the numbers of the stations where Vanya has stopped. Find the number of the station where the next stop will be.InputThe first line contains an integer n (1 ≤ n ≤ 1000) which represents the number of petrol stations where Vanya has stopped. The next line has n space-separated integers which represent the numbers of the stations. The numbers are positive and do not exceed 106, they are given in the increasing order. No two numbers in the succession match. It is guaranteed that there exists at least one number α ≥ 10, to which such a succession of stops corresponds.OutputPrint in the first line "unique" (without quotes) if the answer can be determined uniquely. In the second line print the number of the station where the next stop will take place. If the answer is not unique, print in the first line "not unique".ExamplesInput31 2 4Outputunique5Input21 2Outputnot uniqueNoteIn the second example the answer is not unique. For example, if α = 10, we'll have such a sequence as 1, 2, 3, and if α = 14, the sequence will be 1, 2, 4.
Input31 2 4
Outputunique5
2 seconds
256 megabytes
['math', '*1800']
B. Land Lottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.InputThe first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m.OutputPrint the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n.ExamplesInput2 21 01 11 1Output0Input4 50 0 1 0 10 1 1 1 01 0 1 0 11 1 1 1 12 3Output2NoteIn the second example the upper left square is (1,1) and the lower right is (3,2).
Input2 21 01 11 1
Output0
2 seconds
256 megabytes
['brute force', 'implementation', '*1200']
A. Rock-paper-scissorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUncle Fyodor, Matroskin the Cat and Sharic the Dog live their simple but happy lives in Prostokvashino. Sometimes they receive parcels from Uncle Fyodor’s parents and sometimes from anonymous benefactors, in which case it is hard to determine to which one of them the package has been sent. A photographic rifle is obviously for Sharic who loves hunting and fish is for Matroskin, but for whom was a new video game console meant? Every one of the three friends claimed that the present is for him and nearly quarreled. Uncle Fyodor had an idea how to solve the problem justly: they should suppose that the console was sent to all three of them and play it in turns. Everybody got relieved but then yet another burning problem popped up — who will play first? This time Matroskin came up with a brilliant solution, suggesting the most fair way to find it out: play rock-paper-scissors together. The rules of the game are very simple. On the count of three every player shows a combination with his hand (or paw). The combination corresponds to one of three things: a rock, scissors or paper. Some of the gestures win over some other ones according to well-known rules: the rock breaks the scissors, the scissors cut the paper, and the paper gets wrapped over the stone. Usually there are two players. Yet there are three friends, that’s why they decided to choose the winner like that: If someone shows the gesture that wins over the other two players, then that player wins. Otherwise, another game round is required. Write a program that will determine the winner by the gestures they have shown.InputThe first input line contains the name of the gesture that Uncle Fyodor showed, the second line shows which gesture Matroskin showed and the third line shows Sharic’s gesture. OutputPrint "F" (without quotes) if Uncle Fyodor wins. Print "M" if Matroskin wins and "S" if Sharic wins. If it is impossible to find the winner, print "?".ExamplesInputrockrockrockOutput?InputpaperrockrockOutputFInputscissorsrockrockOutput?InputscissorspaperrockOutput?
Inputrockrockrock
Output?
2 seconds
256 megabytes
['implementation', 'schedules', '*900']
E. Cannontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the Ox axis is directed rightwards in the city's direction, the Oy axis is directed upwards (to the sky). The cannon will make n more shots. The cannon balls' initial speeds are the same in all the shots and are equal to V, so that every shot is characterized by only one number alphai which represents the angle at which the cannon fires. Due to the cannon's technical peculiarities this angle does not exceed 45 angles (π / 4). We disregard the cannon sizes and consider the firing made from the point (0, 0).The balls fly according to the known physical laws of a body thrown towards the horizon at an angle: vx(t) = V·cos(alpha) vy(t) = V·sin(alpha)  –  g·t x(t) = V·cos(alpha)·t y(t) = V·sin(alpha)·t  –  g·t2 / 2Think of the acceleration of gravity g as equal to 9.8.Bertown defends m walls. The i-th wall is represented as a vertical segment (xi, 0) - (xi, yi). When a ball hits a wall, it gets stuck in it and doesn't fly on. If a ball doesn't hit any wall it falls on the ground (y = 0) and stops. If the ball exactly hits the point (xi, yi), it is considered stuck. Your task is to find for each ball the coordinates of the point where it will be located in the end.InputThe first line contains integers n and V (1 ≤ n ≤ 104, 1 ≤ V ≤ 1000) which represent the number of shots and the initial speed of every ball. The second line contains n space-separated real numbers alphai (0 < alphai < π / 4) which represent the angles in radians at which the cannon will fire. The third line contains integer m (1 ≤ m ≤ 105) which represents the number of walls. Then follow m lines, each containing two real numbers xi and yi (1 ≤ xi ≤ 1000, 0 ≤ yi ≤ 1000) which represent the wall’s coordinates. All the real numbers have no more than 4 decimal digits. The walls may partially overlap or even coincide.OutputPrint n lines containing two real numbers each — calculate for every ball the coordinates of its landing point. Your answer should have the relative or absolute error less than 10 - 4.ExamplesInput2 100.78530.335.0 5.04.0 2.46.0 1.9Output5.000000000 2.5494993694.000000000 0.378324889Input2 100.78530.324.0 2.46.0 1.9Output10.204081436 0.0000000004.000000000 0.378324889
Input2 100.78530.335.0 5.04.0 2.46.0 1.9
Output5.000000000 2.5494993694.000000000 0.378324889
3 seconds
256 megabytes
['data structures', 'geometry', 'sortings', '*2200']
D. Safetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.InputThe first input line contains two integers n and m (6 ≤ n ≤ 35, 1 ≤ m ≤ 10) which represent the number of numbers in the code and the number of attempts made by Vasya. Then follow m lines, each containing space-separated si and ci which correspondingly indicate Vasya’s attempt (a line containing n numbers which are 0 or 1) and the system’s response (an integer from 0 to 5 inclusively).OutputPrint the single number which indicates how many possible code variants that do not contradict the m system responses are left.ExamplesInput6 2000000 2010100 4Output6Input6 3000000 2010100 4111100 0Output0Input6 3000000 2010100 4111100 2Output1
Input6 2000000 2010100 4
Output6
5 seconds
256 megabytes
['brute force', '*2200']
C. Crosswordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical.The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification.Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order.InputSix lines contain the given words. Every word consists of no more than 30 and no less than 3 uppercase Latin letters. OutputIf it is impossible to solve the problem, print Impossible. Otherwise, print the sought crossword. All the empty squares should be marked as dots.If there can be several solutions to that problem, print the lexicographically minimum one. I.e. the solution where the first line is less than the first line of other solutions should be printed. If the two lines are equal, compare the second lines and so on. The lexicographical comparison of lines is realized by the < operator in the modern programming languages.ExamplesInputNODBAAYARDAIRWAYNEWTONBURNOutputBAA...U.I...R.R...NEWTON..A..O..YARDInputAAAAAAAAAAAAAAAAAAAAAAOutputAAA..A.A..AAAAA..A.A..AAAInputPTCJYNYFDSGIZGPPCIXEJNDOPJJFSSSXXQOFGJUZOutputJJFS....Y..S....N..X....Y..X....F..Q....D..O....S..F....G..G....IXEJNDOP...U...T...ZGPPC
InputNODBAAYARDAIRWAYNEWTONBURN
OutputBAA...U.I...R.R...NEWTON..A..O..YARD
2 seconds
256 megabytes
['implementation', '*2000']
B. Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal.InputThe input data contains the results of all the weighting, one result on each line. It is guaranteed that every coin pair was weighted exactly once. Vasya labelled the coins with letters «A», «B» and «C». Each result is a line that appears as (letter)(> or < sign)(letter). For example, if coin "A" proved lighter than coin "B", the result of the weighting is A<B.OutputIt the results are contradictory, print Impossible. Otherwise, print without spaces the rearrangement of letters «A», «B» and «C» which represent the coins in the increasing order of their weights.ExamplesInputA>BC<BA>COutputCBAInputA<BB>CC>AOutputACB
InputA>BC<BA>C
OutputCBA
2 seconds
256 megabytes
['implementation', '*1200']
A. Triangular numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. . You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number).Your task is to find out if a given integer is a triangular number.InputThe first line contains the single number n (1 ≤ n ≤ 500) — the given integer.OutputIf the given integer is a triangular number output YES, otherwise output NO.ExamplesInput1OutputYESInput2OutputNOInput3OutputYES
Input1
OutputYES
2 seconds
256 megabytes
['brute force', 'math', '*800']
G. Emperor's Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt happened at the times of the Great Berland Empire. Once the Emperor dreamt that the Messenger from the gods ordered to build a temple whose base would be a convex polygon with n angles. Next morning the Emperor gave the command to build a temple whose base was a regular polygon with n angles. The temple was built but soon the Empire was shaken with disasters and crop failures. After an earthquake destroyed the temple, the Emperor understood that he somehow caused the wrath of gods to fall on his people. He ordered to bring the wise man. When the wise man appeared, the Emperor retold the dream to him and asked "Oh the wisest among the wisest, tell me how could I have infuriated the Gods?". "My Lord," the wise man answered. "As far as I can judge, the gods are angry because you were too haste to fulfill their order and didn't listen to the end of the message".Indeed, on the following night the Messenger appeared again. He reproached the Emperor for having chosen an imperfect shape for the temple. "But what shape can be more perfect than a regular polygon!?" cried the Emperor in his dream. To that the Messenger gave a complete and thorough reply. All the vertices of the polygon should be positioned in the lattice points. All the lengths of its sides should be different. From the possible range of such polygons a polygon which maximum side is minimal possible must be chosen. You are an obedient architect who is going to make the temple's plan. Note that the polygon should be simple (having a border without self-intersections and overlapping) and convex, however, it is acceptable for three consecutive vertices to lie on the same line.InputThe first line contains the single number n (3 ≤ n ≤ 10000).OutputPrint "YES" (without quotes) in the first line if it is possible to build a polygon possessing the needed qualities. In the next n lines print integer coordinates of the polygon vertices in the order in which they would be passed counter clockwise. The absolute value of the coordinates shouldn't exceed 109. No two vertices can coincide. It is permitted to print any of the possible solutions. Print "NO" if to build the polygon is impossible.ExamplesInput3OutputYES0 01 00 2Input3OutputYES0 1-1 0-1 -1
Input3
OutputYES0 01 00 2
2 seconds
256 megabytes
['geometry', '*2500']
F. Hercule Poirot Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books. You are not informed on what crime was committed, when and where the corpse was found and other details. We only know that the crime was committed in a house that has n rooms and m doors between the pairs of rooms. The house residents are very suspicious, that's why all the doors can be locked with keys and all the keys are different. According to the provided evidence on Thursday night all the doors in the house were locked, and it is known in what rooms were the residents, and what kind of keys had any one of them. The same is known for the Friday night, when all the doors were also locked. On Friday it was raining heavily, that's why nobody left the house and nobody entered it. During the day the house residents could open and close doors to the neighboring rooms using the keys at their disposal (every door can be opened and closed from each side); move freely from a room to a room if a corresponding door is open; give keys to one another, being in one room. "Little grey matter" of Hercule Poirot are not capable of coping with such amount of information. Find out if the positions of people and keys on the Thursday night could result in the positions on Friday night, otherwise somebody among the witnesses is surely lying.InputThe first line contains three preset integers n, m и k (1 ≤ n, m, k ≤ 1000) — the number of rooms, the number of doors and the number of house residents respectively. The next m lines contain pairs of room numbers which join the doors. The rooms are numbered with integers from 1 to n. There cannot be more that one door between the pair of rooms. No door connects a room with itself. The next k lines describe the residents' position on the first night. Every line contains a resident's name (a non-empty line consisting of no more than 10 Latin letters), then after a space follows the room number, then, after a space — the number of keys the resident has. Then follow written space-separated numbers of the doors that can be unlocked by these keys. The doors are numbered with integers from 1 to m in the order in which they are described in the input data. All the residents have different names, uppercase and lowercase letters considered to be different. Every m keys occurs exactly once in the description. Multiple people may be present in one room, some rooms may be empty. The next k lines describe the position of the residents on the second night in the very same format. It is guaranteed that in the second night's description the residents' names remain the same and every m keys occurs exactly once.OutputPrint "YES" (without quotes) if the second arrangement can result from the first one, otherwise, print "NO".ExamplesInput2 1 21 2Dmitry 1 1 1Natalia 2 0Natalia 1 1 1Dmitry 2 0OutputYESInput4 4 31 31 22 33 4Artem 1 1 4Dmitry 1 1 2Edvard 4 2 1 3Artem 2 0Dmitry 1 0Edvard 4 4 1 2 3 4OutputNO
Input2 1 21 2Dmitry 1 1 1Natalia 2 0Natalia 1 1 1Dmitry 2 0
OutputYES
2 seconds
256 megabytes
['dsu', 'graphs', '*2300']
E. Combtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHaving endured all the hardships, Lara Croft finally found herself in a room with treasures. To her surprise she didn't find golden mountains there. Lara looked around and noticed on the floor a painted table n × m panels in size with integers written on the panels. There also was a huge number of stones lying by the wall. On the pillar near the table Lara found a guidance note which said that to get hold of the treasures one has to choose some non-zero number of the first panels in each row of the table and put stones on all those panels to push them down. After that she will receive a number of golden coins equal to the sum of numbers written on the chosen panels. Lara quickly made up her mind on how to arrange the stones and was about to start when she noticed an addition to the note in small font below. According to the addition, for the room ceiling not to crush and smash the adventurer, the chosen panels should form a comb. It was explained that the chosen panels form a comb when the sequence c1, c2, ..., cn made from the quantities of panels chosen in each table line satisfies the following property: c1 > c2 < c3 > c4 < ..., i.e. the inequation mark interchanges between the neighboring elements. Now Lara is bewildered and doesn't know what to do. Help her to determine the largest number of coins she can get and survive at the same time.InputThe first line contains a pair of integers n, m (2 ≤ n, m ≤ 1500). Next n lines contain m integers each — that is the table itself. The absolute value of the numbers in the table does not exceed 10000.OutputPrint the single number — the maximum number of coins Lara can get.ExamplesInput2 2-1 21 3Output2
Input2 2-1 21 3
Output2
1 second
256 megabytes
['data structures', 'dp', '*1900']
D. Parking Lottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as L meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than b meters and the distance between his car and the one in front of his will be no less than f meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point L. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.InputThe first line contains three integers L, b и f (10 ≤ L ≤ 100000, 1 ≤ b, f ≤ 100). The second line contains an integer n (1 ≤ n ≤ 100) that indicates the number of requests the program has got. Every request is described on a single line and is given by two numbers. The first number represents the request type. If the request type is equal to 1, then in that case the second number indicates the length of a car (in meters) that enters the street looking for a place to park. And if the request type is equal to 2, then the second number identifies the number of such a request (starting with 1) that the car whose arrival to the parking lot was described by a request with this number, leaves the parking lot. It is guaranteed that that car was parked at the moment the request of the 2 type was made. The lengths of cars are integers from 1 to 1000.OutputFor every request of the 1 type print number -1 on the single line if the corresponding car couldn't find place to park along the street. Otherwise, print a single number equal to the distance between the back of the car in its parked position and the beginning of the parking lot zone.ExamplesInput30 1 261 51 41 52 21 51 4Output06111723Input30 1 161 51 41 52 21 51 4Output0611176Input10 1 111 12Output-1
Input30 1 261 51 41 52 21 51 4
Output06111723
2 seconds
256 megabytes
['data structures', 'implementation', '*1800']