problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
β | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
C. Lucky Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly nβ-β1 edges.Petya wondered how many vertex triples (i,βj,βk) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1,β2,β3) is not equal to the triple (2,β1,β3) and is not equal to the triple (1,β3,β2). Find how many such triples of vertexes exist.InputThe first line contains the single integer n (1ββ€βnββ€β105) β the number of tree vertexes. Next nβ-β1 lines contain three integers each: ui vi wi (1ββ€βui,βviββ€βn,β1ββ€βwiββ€β109) β the pair of vertexes connected by the edge and the edge's weight.OutputOn the single line print the single number β the answer.Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is recommended to use the cin, cout streams or the %I64d specificator.ExamplesInput41 2 43 1 21 4 7Output16Input41 2 41 3 471 4 7447Output24NoteThe 16 triples of vertexes from the first sample are: (1,β2,β4),β(1,β4,β2),β(2,β1,β3),β(2,β1,β4),β(2,β3,β1),β(2,β3,β4),β(2,β4,β1),β(2,β4,β3),β(3,β2,β4),β(3,β4,β2),β(4,β1,β2),β(4,β1,β3),β(4,β2,β1),β(4,β2,β3),β(4,β3,β1),β(4,β3,β2).In the second sample all the triples should be counted: 4Β·3Β·2β=β24. | Input41 2 43 1 21 4 7 | Output16 | 2 seconds | 256 megabytes | ['dp', 'dsu', 'trees', '*1900'] |
B. Lucky Probabilitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the interval [pl,βpr] and Vasya chooses an integer v from the interval [vl,βvr] (also randomly). Both players choose their integers equiprobably. Find the probability that the interval [min(v,βp),βmax(v,βp)] contains exactly k lucky numbers.InputThe single line contains five integers pl, pr, vl, vr and k (1ββ€βplββ€βprββ€β109,β1ββ€βvlββ€βvrββ€β109,β1ββ€βkββ€β1000).OutputOn the single line print the result with an absolute error of no more than 10β-β9.ExamplesInput1 10 1 10 2Output0.320000000000Input5 6 8 10 1Output1.000000000000NoteConsider that [a,βb] denotes an interval of integers; this interval includes the boundaries. That is, In first case there are 32 suitable pairs: (1,β7),β(1,β8),β(1,β9),β(1,β10),β(2,β7),β(2,β8),β(2,β9),β(2,β10),β(3,β7),β(3,β8),β(3,β9),β(3,β10),β(4,β7),β(4,β8),β(4,β9),β(4,β10),β(7,β1),β(7,β2),β(7,β3),β(7,β4),β(8,β1),β(8,β2),β(8,β3),β(8,β4),β(9,β1),β(9,β2),β(9,β3),β(9,β4),β(10,β1),β(10,β2),β(10,β3),β(10,β4). Total number of possible pairs is 10Β·10β=β100, so answer is 32β/β100.In second case Petya always get number less than Vasya and the only lucky 7 is between this numbers, so there will be always 1 lucky number. | Input1 10 1 10 2 | Output0.320000000000 | 2 seconds | 256 megabytes | ['brute force', 'probabilities', '*1900'] |
A. Lucky Sum of Digitstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.InputThe single line contains an integer n (1ββ€βnββ€β106) β the sum of digits of the required lucky number.OutputPrint on the single line the result β the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.ExamplesInput11Output47Input10Output-1 | Input11 | Output47 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1000'] |
B. Datatypestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTattah's youngest brother, Tuftuf, is new to programming.Since his older brother is such a good programmer, his biggest dream is to outshine him. Tuftuf is a student at the German University in Cairo (GUC) where he learns to write programs in Gava.Today, Tuftuf was introduced to Gava's unsigned integer datatypes. Gava has n unsigned integer datatypes of sizes (in bits) a1,βa2,β... an. The i-th datatype have size ai bits, so it can represent every integer between 0 and 2aiβ-β1 inclusive. Tuftuf is thinking of learning a better programming language. If there exists an integer x, such that x fits in some type i (in ai bits) and xΒ·x does not fit in some other type j (in aj bits) where aiβ<βaj, then Tuftuf will stop using Gava.Your task is to determine Tuftuf's destiny.InputThe first line contains integer n (2ββ€βnββ€β105) β the number of Gava's unsigned integer datatypes' sizes. The second line contains a single-space-separated list of n integers (1ββ€βaiββ€β109) β sizes of datatypes in bits. Some datatypes may have equal sizes.OutputPrint "YES" if Tuftuf will stop using Gava, and "NO" otherwise.ExamplesInput364 16 32OutputNOInput44 2 1 3OutputYESNoteIn the second example, xβ=β7 (1112) fits in 3 bits, but x2β=β49 (1100012) does not fit in 4 bits. | Input364 16 32 | OutputNO | 2 seconds | 256 megabytes | ['math', 'sortings', '*1400'] |
A. Palindromic Timestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues.On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on the clock were the same when read from both directions i.e. a palindrome.In his sleep, he started dreaming about such rare moments of the day when the time displayed on a digital clock is a palindrome. As soon as he woke up, he felt destined to write a program that finds the next such moment.However, he still hasn't mastered the skill of programming while sleeping, so your task is to help him.InputThe first and only line of the input starts with a string with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59". Both "HH" and "MM" have exactly two digits.OutputPrint the palindromic time of day that comes soonest after the time given in the input. If the input time is palindromic, output the soonest palindromic time after the input time.ExamplesInput12:21Output13:31Input23:59Output00:00 | Input12:21 | Output13:31 | 2 seconds | 256 megabytes | ['implementation', 'strings', '*1000'] |
E. Dartstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe night after the graduation ceremony graduate students of German University in Cairo (GUC) are playing darts. As there's no real dart board available, the photographs of members of the GUC upper management are being used.So, n rectangular photos are placed on the wall. They can overlap arbitrary and even coincide. The photos are not necessarily placed horizontally or vertically, they could also be rotated before being pinned to the wall.The score of one dart throw is simply the number of photos the dart went through.Fatma has made a throw but her score was not recorded. She only remembers that she did make it into at least one photo.Assuming that the probability distribution of the throw is equal across the whole wall, what would be the expectation of Fatma's score?InputThe first line of input contains integer n (1ββ€βnββ€β500) β the number of photos on the wall. Then follow n lines describing the photos, each containing 8 single-space-separated integers (coordinates of 4 vertices): x1, y1, x2, y2, x3, y3, x4, y4. Each photo is a rectangle with a nonzero area. The coordinates are integers, not exceeding 104 by absolute value. The coordinates of the rectangle are given in either clockwise or counterclockwise order.OutputPrint the expected score of the throw. The answer will be accepted if it has absolute or relative error not exceeding 10β-β6.ExamplesInput10 0 0 2 2 2 2 0Output1.0000000000Input1-1 0 0 1 1 0 0 -1Output1.0000000000Input40 0 0 1 3 1 3 00 0 0 3 1 3 1 03 3 2 3 2 0 3 03 3 3 2 0 2 0 3Output1.5000000000Input2-1 0 0 1 1 0 0 -10 0 1 1 2 0 1 -1Output1.1428571429 | Input10 0 0 2 2 2 2 0 | Output1.0000000000 | 5 seconds | 256 megabytes | ['geometry', 'probabilities', '*2700'] |
D. Crime Managementtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZeyad wants to commit n crimes in Egypt and not be punished at the end. There are several types of crimes. For example, bribery is a crime but is not considered such when repeated twice. Therefore, bribery is not considered a crime when repeated an even number of times. Speeding is a crime, but is not considered such when repeated a number of times which is a multiple of five.More specifically, c conditions on crime repetitions are known. Each condition describes the crime type ti and its multiplicity mi. If the number of times Zeyad committed the crime ti is a multiple of mi, Zeyad will not be punished for crime ti. Some crimes may be listed more than once. In this case fulfilling at least one condition for this crime is enough to not be punished for it. Of course, if for certain crime the number of times Zeyad committed it is zero, he is innocent with respect to this crime.Now Zeyad is interested in a number of ways he can commit exactly n crimes without any punishment.The order of commiting the crimes matters. More formally, two ways, sequences w1 and w2, of committing n crimes are equal if w1iβ=βw2i, for all 1ββ€βiββ€βn.InputThe first line contains two integers n and c (0ββ€βnββ€β1018,β0ββ€βcββ€β1000) β the number of crimes Zeyad would like to commit and the number of conditions he is aware of.Then the definitions for c conditions follow. There are 26 types of crimes. Each crime definition consists of crime type β a capital Latin letter β and its multiplicity. The multiplicity of each crime is a positive integer number and the product of all multiplicities does not exceed 123. Some conditions may be repeated in the input more than once.Crime of multiplicity 1 is not yielding any punishment regardless of the number of times it was committed. The strictness of the law is compensated by the fact that it's non-mandatory.Obviously, if some crime is not listed in the set of conditions, then Zeyad will not consider it, as committing it would unavoidably lead to the punishment.Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin stream (you may also use the %I64d specificator).OutputOutput the number of different ways Zeyad can commit exactly n crimes with no punishment modulo 12345.ExamplesInput5 2A 1B 2Output16Input6 3A 1B 2C 3Output113Input8 3A 2A 3B 2Output128NoteIn the first test case, the 16 ways are: AAAAA, AAABB, AABAB, AABBA, ABAAB, ABABA, ABBAA, BAAAB, BAABA, BABAA, BBAAA, ABBBB, BABBB, BBABB, BBBAB, BBBBA. | Input5 2A 1B 2 | Output16 | 5 seconds | 256 megabytes | ['dp', 'graphs', 'matrices', '*2400'] |
C. Arrangementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the year 2500 the annual graduation ceremony in the German University in Cairo (GUC) has run smoothly for almost 500 years so far.The most important part of the ceremony is related to the arrangement of the professors in the ceremonial hall.Traditionally GUC has n professors. Each professor has his seniority level. All seniorities are different. Let's enumerate the professors from 1 to n, with 1 being the most senior professor and n being the most junior professor.The ceremonial hall has n seats, one seat for each professor. Some places in this hall are meant for more senior professors than the others. More specifically, m pairs of seats are in "senior-junior" relation, and the tradition requires that for all m pairs of seats (ai,βbi) the professor seated in "senior" position ai should be more senior than the professor seated in "junior" position bi.GUC is very strict about its traditions, which have been carefully observed starting from year 2001. The tradition requires that: The seating of the professors changes every year. Year 2001 ceremony was using lexicographically first arrangement of professors in the ceremonial hall. Each consecutive year lexicographically next arrangement of the professors is used. The arrangement of the professors is the list of n integers, where the first integer is the seniority of the professor seated in position number one, the second integer is the seniority of the professor seated in position number two, etc.Given n, the number of professors, y, the current year and m pairs of restrictions, output the arrangement of the professors for this year.InputThe first line contains three integers n, y and m (1ββ€βnββ€β16,β2001ββ€βyββ€β1018,β0ββ€βmββ€β100) β the number of professors, the year for which the arrangement should be computed, and the number of pairs of seats for which the seniority relation should be kept, respectively.The next m lines contain one pair of integers each, "ai bi", indicating that professor on the ai-th seat is more senior than professor on the bi-th seat (1ββ€βai,βbiββ€βn,βaiββ βbi). Some pair may be listed more than once.Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin stream (you may also use the %I64d specificator).OutputPrint the order in which the professors should be seated in the requested year.If by this year the GUC would have ran out of arrangements, or the given "senior-junior" relation are contradictory, print "The times have changed" (without quotes).ExamplesInput3 2001 21 22 3Output1 2 3Input7 2020 61 21 32 42 53 63 7Output1 2 3 7 4 6 5Input10 3630801 0OutputThe times have changedInput3 2001 31 22 33 1OutputThe times have changedNoteIn the first example the lexicographically first order of seating is 1 2 3.In the third example the GUC will run out of arrangements after the year 3630800.In the fourth example there are no valid arrangements for the seating.The lexicographical comparison of arrangements is performed by the < operator in modern programming languages. The arrangement a is lexicographically less that the arrangement b, if there exists such i (1ββ€βiββ€βn), that aiβ<βbi, and for any j (1ββ€βjβ<βi) ajβ=βbj. | Input3 2001 21 22 3 | Output1 2 3 | 2 seconds | 256 megabytes | ['bitmasks', 'dp', '*2400'] |
B. Basketball Teamtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to different departments. There are m departments in GUC, numbered from 1 to m. Herr Wafa's department has number h. For each department i, Herr Wafa knows number si β how many students who play basketball belong to this department.Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department. Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.InputThe first line contains three integers n, m and h (1ββ€βnββ€β100,β1ββ€βmββ€β1000,β1ββ€βhββ€βm) β the number of players on the team, the number of departments in GUC and Herr Wafa's department, correspondingly. The second line contains a single-space-separated list of m integers si (1ββ€βsiββ€β100), denoting the number of students in the i-th department. Note that sh includes Herr Wafa.OutputPrint the probability that Herr Wafa will have at least one teammate from his department. If there is not enough basketball players in GUC to participate in ABC, print -1. The answer will be accepted if it has absolute or relative error not exceeding 10β-β6.ExamplesInput3 2 12 1Output1Input3 2 11 1Output-1Input3 2 12 2Output0.666667NoteIn the first example all 3 players (2 from department 1 and 1 from department 2) must be chosen for the team. Both players from Wafa's departments will be chosen, so he's guaranteed to have a teammate from his department.In the second example, there are not enough players.In the third example, there are three possibilities to compose the team containing Herr Wafa. In two of them the other player from Herr Wafa's department is part of the team. | Input3 2 12 1 | Output1 | 1 second | 256 megabytes | ['combinatorics', 'dp', 'math', 'probabilities', '*1600'] |
A. Dorm Water Supplytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe German University in Cairo (GUC) dorm houses are numbered from 1 to n. Underground water pipes connect these houses together. Each pipe has certain direction (water can flow only in this direction and not vice versa), and diameter (which characterizes the maximal amount of water it can handle).For each house, there is at most one pipe going into it and at most one pipe going out of it. With the new semester starting, GUC student and dorm resident, Lulu, wants to install tanks and taps at the dorms. For every house with an outgoing water pipe and without an incoming water pipe, Lulu should install a water tank at that house. For every house with an incoming water pipe and without an outgoing water pipe, Lulu should install a water tap at that house. Each tank house will convey water to all houses that have a sequence of pipes from the tank to it. Accordingly, each tap house will receive water originating from some tank house.In order to avoid pipes from bursting one week later (like what happened last semester), Lulu also has to consider the diameter of the pipes. The amount of water each tank conveys should not exceed the diameter of the pipes connecting a tank to its corresponding tap. Lulu wants to find the maximal amount of water that can be safely conveyed from each tank to its corresponding tap.InputThe first line contains two space-separated integers n and p (1ββ€βnββ€β1000,β0ββ€βpββ€βn) β the number of houses and the number of pipes correspondingly. Then p lines follow β the description of p pipes. The i-th line contains three integers ai bi di, indicating a pipe of diameter di going from house ai to house bi (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βdiββ€β106).It is guaranteed that for each house there is at most one pipe going into it and at most one pipe going out of it.OutputPrint integer t in the first line β the number of tank-tap pairs of houses.For the next t lines, print 3 integers per line, separated by spaces: tanki, tapi, and diameteri, where tankiββ βtapi (1ββ€βiββ€βt). Here tanki and tapi are indexes of tank and tap houses respectively, and diameteri is the maximum amount of water that can be conveyed. All the t lines should be ordered (increasingly) by tanki.ExamplesInput3 21 2 102 3 20Output11 3 10Input3 31 2 202 3 103 1 5Output0Input4 21 2 603 4 50Output21 2 603 4 50 | Input3 21 2 102 3 20 | Output11 3 10 | 1 second | 256 megabytes | ['dfs and similar', 'graphs', '*1400'] |
E. Space Rescuerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Galaxy contains n planets, there are many different living creatures inhabiting each planet. And each creature can get into troubles! Space rescuers know it perfectly well and they are always ready to help anyone who really needs help. All you need to do is call for them. Now the space rescuers plan to build the largest in the history of the Galaxy rescue station; however, the rescue station's location is yet to be determined. As some cases are real emergencies, the rescuers want to find such a point in the Galaxy from which it would be possible to get to the remotest planet in the minimum possible time. In other words, the rescuers need such point in the space that the distance between it and the planet remotest from it was minimal (if we compare this point with all other possible points in the space). Unfortunately, the rescuers can't sole this problem.As the planets are quite remote from each other, they can be considered as points in Euclidean three-dimensional space. The distance between points (xi,βyi,βzi) and (xj,βyj,βzj) can be calculated by the formula . The rescue station can be positioned in any point in the space. It can also coincide with some planet. Galaxy is in danger! Save the space rescuers and find the required point for them.InputThe first line of the input file contains integer n β the number of planets (1ββ€βNββ€β100). Each of the following n lines contains information about the planets. The i-th line contains three integers xi,βyi,βzi β the coordinates of the i-th planet (β-β104ββ€βxi,βyi,βziββ€β104, 1ββ€βiββ€βn). No two planets coincide.OutputPrint on the first line of the output file three space-separated real numbers x0,βy0,βz0 β the coordinates for the future base. If there are several solutions, you are allowed to print any of them. The answer will be accepted if the distance from this point to the remotest planet will differ from the juries' variant in no more than 10β-β6 in absolute or relative value.ExamplesInput55 0 0-5 0 00 3 44 -3 02 2 -2Output0.000 0.000 0.000 | Input55 0 0-5 0 00 3 44 -3 02 2 -2 | Output0.000 0.000 0.000 | 2 seconds | 256 megabytes | ['geometry', 'ternary search', '*2100'] |
D. Treasure Islandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOur brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map.The treasure map can be represented as a rectangle nβΓβm in size. Each cell stands for an islands' square (the square's side length equals to a mile). Some cells stand for the sea and they are impenetrable. All other cells are penetrable (i.e. available) and some of them contain local sights. For example, the large tree on the hills or the cave in the rocks.Besides, the map also has a set of k instructions. Each instruction is in the following form:"Walk n miles in the y direction"The possible directions are: north, south, east, and west. If you follow these instructions carefully (you should fulfill all of them, one by one) then you should reach exactly the place where treasures are buried. Unfortunately the captain doesn't know the place where to start fulfilling the instructions β as that very piece of the map was lost. But the captain very well remembers that the place contained some local sight. Besides, the captain knows that the whole way goes through the island's penetrable squares.The captain wants to know which sights are worth checking. He asks you to help him with that. InputThe first line contains two integers n and m (3ββ€βn,βmββ€β1000).Then follow n lines containing m integers each β the island map's description. "#" stands for the sea. It is guaranteed that all cells along the rectangle's perimeter are the sea. "." stands for a penetrable square without any sights and the sights are marked with uppercase Latin letters from "A" to "Z". Not all alphabet letters can be used. However, it is guaranteed that at least one of them is present on the map. All local sights are marked by different letters.The next line contains number k (1ββ€βkββ€β105), after which k lines follow. Each line describes an instruction. Each instruction possesses the form "dir len", where dir stands for the direction and len stands for the length of the way to walk. dir can take values "N", "S", "W" and "E" for North, South, West and East correspondingly. At that, north is to the top, South is to the bottom, west is to the left and east is to the right. len is an integer from 1 to 1000.OutputPrint all local sights that satisfy to the instructions as a string without any separators in the alphabetical order. If no sight fits, print "no solution" without the quotes.ExamplesInput6 10###########K#..######.#..##.###..L.#...####D###A.###########4N 2S 1E 1W 2OutputADInput3 4#####.A#####2W 1N 2Outputno solution | Input6 10###########K#..######.#..##.###..L.#...####D###A.###########4N 2S 1E 1W 2 | OutputAD | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1700'] |
C. Bunstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLavrenty, a baker, is going to make several buns with stuffings and sell them.Lavrenty has n grams of dough as well as m different stuffing types. The stuffing types are numerated from 1 to m. Lavrenty knows that he has ai grams left of the i-th stuffing. It takes exactly bi grams of stuffing i and ci grams of dough to cook a bun with the i-th stuffing. Such bun can be sold for di tugriks.Also he can make buns without stuffings. Each of such buns requires c0 grams of dough and it can be sold for d0 tugriks. So Lavrenty can cook any number of buns with different stuffings or without it unless he runs out of dough and the stuffings. Lavrenty throws away all excess material left after baking.Find the maximum number of tugriks Lavrenty can earn.InputThe first line contains 4 integers n, m, c0 and d0 (1ββ€βnββ€β1000, 1ββ€βmββ€β10, 1ββ€βc0,βd0ββ€β100). Each of the following m lines contains 4 integers. The i-th line contains numbers ai, bi, ci and di (1ββ€βai,βbi,βci,βdiββ€β100).OutputPrint the only number β the maximum number of tugriks Lavrenty can earn.ExamplesInput10 2 2 17 3 2 10012 3 1 10Output241Input100 1 25 5015 5 20 10Output200NoteTo get the maximum number of tugriks in the first sample, you need to cook 2 buns with stuffing 1, 4 buns with stuffing 2 and a bun without any stuffing.In the second sample Lavrenty should cook 4 buns without stuffings. | Input10 2 2 17 3 2 10012 3 1 10 | Output241 | 2 seconds | 256 megabytes | ['dp', '*1700'] |
B. Choosing Laptoptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is choosing a laptop. The shop has n laptops to all tastes.Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties.If all three properties of a laptop are strictly less than those properties of some other laptop, then the first laptop is considered outdated by Vasya. Among all laptops Vasya does not consider outdated, he chooses the cheapest one.There are very many laptops, which is why Vasya decided to write a program that chooses the suitable laptop. However, Vasya doesn't have his own laptop yet and he asks you to help him.InputThe first line contains number n (1ββ€βnββ€β100).Then follow n lines. Each describes a laptop as speed ram hdd cost. Besides, speed, ram, hdd and cost are integers 1000ββ€βspeedββ€β4200 is the processor's speed in megahertz 256ββ€βramββ€β4096 the RAM volume in megabytes 1ββ€βhddββ€β500 is the HDD in gigabytes 100ββ€βcostββ€β1000 is price in tugriks All laptops have different prices.OutputPrint a single number β the number of a laptop Vasya will choose. The laptops are numbered with positive integers from 1 to n in the order in which they are given in the input data.ExamplesInput52100 512 150 2002000 2048 240 3502300 1024 200 3202500 2048 80 3002000 512 180 150Output4NoteIn the third sample Vasya considers the first and fifth laptops outdated as all of their properties cannot match those of the third laptop. The fourth one is the cheapest among the laptops that are left. Thus, Vasya chooses the fourth laptop. | Input52100 512 150 2002000 2048 240 3502300 1024 200 3202500 2048 80 3002000 512 180 150 | Output4 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1000'] |
A. Card Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a card game called "Durak", which means "Fool" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly β you can find them later yourselves if you want.To play durak you need a pack of 36 cards. Each card has a suit ("S", "H", "D" and "C") and a rank (in the increasing order "6", "7", "8", "9", "T", "J", "Q", "K" and "A"). At the beginning of the game one suit is arbitrarily chosen as trump. The players move like that: one player puts one or several of his cards on the table and the other one should beat each of them with his cards.A card beats another one if both cards have similar suits and the first card has a higher rank then the second one. Besides, a trump card can beat any non-trump card whatever the cardsβ ranks are. In all other cases you can not beat the second card with the first one.You are given the trump suit and two different cards. Determine whether the first one beats the second one or not.InputThe first line contains the tramp suit. It is "S", "H", "D" or "C".The second line contains the description of the two different cards. Each card is described by one word consisting of two symbols. The first symbol stands for the rank ("6", "7", "8", "9", "T", "J", "Q", "K" and "A"), and the second one stands for the suit ("S", "H", "D" and "C").OutputPrint "YES" (without the quotes) if the first cards beats the second one. Otherwise, print "NO" (also without the quotes).ExamplesInputHQH 9SOutputYESInputS8D 6DOutputYESInputC7H ASOutputNO | InputHQH 9S | OutputYES | 2 seconds | 256 megabytes | ['implementation', '*1000'] |
E. Lift and Throwtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a straight half-line divided into segments of unit length, which we will call positions. The positions are numbered by positive integers that start with 1 from the end of half-line, i. e. 1, 2, 3 and so on. The distance between the positions is the absolute difference between the respective numbers. Laharl, Etna and Flonne occupy some positions on the half-line and they want to get to the position with the largest possible number. They are originally placed in different positions. Each of the characters can perform each of the following actions no more than once: Move a certain distance. Grab another character and lift him above the head. Throw the lifted character a certain distance. Each character has a movement range parameter. They can only move to free positions, assuming that distance between those positions doesn't exceed the movement range. One character can lift another character if the distance between the two characters equals 1, and no one already holds that another character. We can assume that the lifted character moves to the same position as the person who has lifted him, and the position in which he stood before becomes free. A lifted character cannot perform any actions and the character that holds him cannot walk. Also, each character has a throwing range parameter. It is the distance at which this character can throw the one lifted above his head. He can only throw a character to a free position, and only when there is a lifted character. We accept the situation when one person grabs another one who in his turn has the third character in his hands. This forms a "column" of three characters. For example, Laharl can hold Etna while Etna holds Flonne. In this case, Etna and the Flonne cannot perform any actions, and Laharl can only throw Etna (together with Flonne) at some distance. Laharl, Etna and Flonne perform actions in any order. They perform actions in turns, that is no two of them can do actions at the same time.Determine the maximum number of position at least one of the characters can reach. That is, such maximal number x so that one of the characters can reach position x.InputThe first line contains three integers: Laharl's position, his movement range and throwing range. The second and the third lines describe Etna's and Flonne's parameters correspondingly in the similar form. It is guaranteed that the three characters occupy distinct positions. All numbers in the input are between 1 and 10, inclusive.OutputPrint a single number β the maximum ordinal number of position which either Laharl, Etna or Flonne can reach.ExamplesInput9 3 34 3 12 3 3Output15NoteLet us explain how to reach position 15 in the sample.Initially Laharl occupies position 9, Etna β position 4 and Flonne β position 2.First Laharl moves to position 6.Then Flonne moves to position 5 and grabs Etna.Laharl grabs Flonne and throws to position 9.Flonne throws Etna to position 12.Etna moves to position 15. | Input9 3 34 3 12 3 3 | Output15 | 1.5 seconds | 256 megabytes | ['brute force', '*2500'] |
D. Entertaining Geodeticstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe maps in the game are divided into square cells called Geo Panels. Some of these panels are painted. We shall assume that the Geo Panels without color are painted the transparent color. Besides, the map has so-called Geo Symbols. They look like pyramids of different colors (including Geo Symbols of the transparent color). Each Geo Symbol is located on one Geo Panel, and each Geo Panel may contain no more than one Geo Symbol. Geo Symbols can be eliminated. To understand better what happens when a Geo Symbol is eliminated, let us introduce some queue to which we will put the recently eliminated Geo Symbols. Let's put at the head of the queue a Geo Symbol that was eliminated just now. Next, we will repeat the following operation: Extract the Geo Symbol from the queue. Look at the color of the panel containing the given Geo Symbol. If it differs from transparent and differs from the color of the Geo Symbol, then all Geo Panels of this color are repainted in the color of the given Geo Symbol (transparent Geo Symbols repaint the Geo Panels transparent). Repainting is executed in an infinite spiral strictly in the following order starting from the panel, which contained the Geo Symbol: In other words, we select all the panels that need to be repainted and find their numbers in the infinite spiral whose center is placed in the position of the given Geo Symbol. After that, we repaint them in the order of the number's increasing. If a panel contains another Geo Symbol and this panel is being repainted, then the Geo Symbol is removed from the field and placed at the tail of the queue. After repainting the Geo Symbol is completely eliminated and the next Geo Symbol is taken from the head of the queue (if there is any) and the process repeats. The process ends if the queue is empty. See the sample analysis for better understanding. You know the colors of all the Geo Panels and the location of all the Geo Symbols. Determine the number of repaintings, which will occur if you destroy one of the Geo Symbols.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β300) β the height and the width of the map (in cells).Then follow n line; each of them contains m numbers β the Geo Panels' colors.Then follow n more lines; each of them contains m numbers β the Geo Symbols' description. -1 means that the given position contains no Geo Symbol. Otherwise, the number represents the color of the Geo Symbol in the given position.All colors are integers from 0 to 109. 0 represents the transparent color.The last line contains two integers x and y (1ββ€βxββ€βn, 1ββ€βyββ€βm) β the row and the column where the Geo Symbol is placed that needs to be eliminated. The rows are numbered from top to bottom, the columns are numbered from left to right. Coordinates are 1-based. It is guaranteed that the position with coordinates (x,βy) contains a Geo Symbol.OutputPrint the single number β the total number of repaintings after the Geo Symbol is eliminated. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cout stream (you may also use the %I64d specificator).ExamplesInput5 59 0 1 1 00 0 3 2 01 1 1 3 01 1 1 3 00 1 2 0 3-1 1 -1 3 -1-1 -1 -1 0 -1-1 -1 -1 -1 -1-1 2 3 -1 -1-1 -1 -1 -1 24 2Output35NoteAll actions of the sample you can see on the following picture: If your browser does not support APNG and you see just static image, you can see GIF version of this image by the following link:http://assets.codeforces.com/images/geo_slow.gif | Input5 59 0 1 1 00 0 3 2 01 1 1 3 01 1 1 3 00 1 2 0 3-1 1 -1 3 -1-1 -1 -1 0 -1-1 -1 -1 -1 -1-1 2 3 -1 -1-1 -1 -1 -1 24 2 | Output35 | 1 second | 256 megabytes | ['brute force', 'dsu', 'implementation', '*2700'] |
C. Item Worldtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach item in the game has a level. The higher the level is, the higher basic parameters the item has. We shall consider only the following basic parameters: attack (atk), defense (def) and resistance to different types of impact (res).Each item belongs to one class. In this problem we will only consider three of such classes: weapon, armor, orb.Besides, there's a whole new world hidden inside each item. We can increase an item's level travelling to its world. We can also capture the so-called residents in the Item WorldResidents are the creatures that live inside items. Each resident gives some bonus to the item in which it is currently located. We will only consider residents of types: gladiator (who improves the item's atk), sentry (who improves def) and physician (who improves res).Each item has the size parameter. The parameter limits the maximum number of residents that can live inside an item. We can move residents between items. Within one moment of time we can take some resident from an item and move it to some other item if it has a free place for a new resident. We cannot remove a resident from the items and leave outside β any of them should be inside of some item at any moment of time.Laharl has a certain number of items. He wants to move the residents between items so as to equip himself with weapon, armor and a defensive orb. The weapon's atk should be largest possible in the end. Among all equipping patterns containing weapon's maximum atk parameter we should choose the ones where the armorβs def parameter is the largest possible. Among all such equipment patterns we should choose the one where the defensive orb would have the largest possible res parameter. Values of the parameters def and res of weapon, atk and res of armor and atk and def of orb are indifferent for Laharl.Find the optimal equipment pattern Laharl can get.InputThe first line contains number n (3ββ€βnββ€β100) β representing how many items Laharl has.Then follow n lines. Each line contains description of an item. The description has the following form: "name class atk def res size" β the item's name, class, basic attack, defense and resistance parameters and its size correspondingly. name and class are strings and atk, def, res and size are integers. name consists of lowercase Latin letters and its length can range from 1 to 10, inclusive. class can be "weapon", "armor" or "orb". 0ββ€βatk,βdef,βresββ€β1000. 1ββ€βsizeββ€β10. It is guaranteed that Laharl has at least one item of each class.The next line contains an integer k (1ββ€βkββ€β1000) β the number of residents.Then k lines follow. Each of them describes a resident. A resident description looks like: "name type bonus home" β the resident's name, his type, the number of points the resident adds to the item's corresponding parameter and the name of the item which currently contains the resident. name, type and home are strings and bonus is an integer. name consists of lowercase Latin letters and its length can range from 1 to 10, inclusive. type may be "gladiator", "sentry" or "physician". 1ββ€βbonusββ€β100. It is guaranteed that the number of residents in each item does not exceed the item's size.The names of all items and residents are pairwise different.All words and numbers in the input are separated by single spaces.OutputPrint on the first line the name of the weapon in the optimal equipping pattern; then print the number of residents the weapon contains; then print the residents' names.Print on the second and third lines in the same form the names of the armor and defensive orb as well as the residents they contain. Use single spaces for separation.If there are several possible solutions, print any of them.ExamplesInput4sword weapon 10 2 3 2pagstarmor armor 0 15 3 1iceorb orb 3 2 13 2longbow weapon 9 1 2 15mike gladiator 5 longbowbobby sentry 6 pagstarmorpetr gladiator 7 iceorbteddy physician 6 swordblackjack sentry 8 swordOutputsword 2 petr mike pagstarmor 1 blackjack iceorb 2 teddy bobby Input4sword weapon 10 2 3 2pagstarmor armor 0 15 3 1iceorb orb 3 2 13 2longbow weapon 9 1 2 16mike gladiator 5 longbowbobby sentry 6 pagstarmorpetr gladiator 7 iceorbteddy physician 6 swordblackjack sentry 8 swordjoe physician 6 iceorbOutputlongbow 1 mike pagstarmor 1 bobby iceorb 2 petr joe NoteIn the second sample we have no free space inside the items, therefore we cannot move the residents between them. | Input4sword weapon 10 2 3 2pagstarmor armor 0 15 3 1iceorb orb 3 2 13 2longbow weapon 9 1 2 15mike gladiator 5 longbowbobby sentry 6 pagstarmorpetr gladiator 7 iceorbteddy physician 6 swordblackjack sentry 8 sword | Outputsword 2 petr mike pagstarmor 1 blackjack iceorb 2 teddy bobby | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'sortings', '*2200'] |
B. Dark Assemblytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark Assembly is a governing body in the Netherworld. Here sit the senators who take the most important decisions for the player. For example, to expand the range of the shop or to improve certain characteristics of the character the Dark Assembly's approval is needed.The Dark Assembly consists of n senators. Each of them is characterized by his level and loyalty to the player. The level is a positive integer which reflects a senator's strength. Loyalty is the probability of a positive decision in the voting, which is measured as a percentage with precision of up to 10%. Senators make decisions by voting. Each of them makes a positive or negative decision in accordance with their loyalty. If strictly more than half of the senators take a positive decision, the player's proposal is approved. If the player's proposal is not approved after the voting, then the player may appeal against the decision of the Dark Assembly. To do that, player needs to kill all the senators that voted against (there's nothing wrong in killing senators, they will resurrect later and will treat the player even worse). The probability that a player will be able to kill a certain group of senators is equal to Aβ/β(Aβ+βB), where A is the sum of levels of all player's characters and B is the sum of levels of all senators in this group. If the player kills all undesired senators, then his proposal is approved.Senators are very fond of sweets. They can be bribed by giving them candies. For each received candy a senator increases his loyalty to the player by 10%. It's worth to mention that loyalty cannot exceed 100%. The player can take no more than k sweets to the courtroom. Candies should be given to the senators before the start of voting.Determine the probability that the Dark Assembly approves the player's proposal if the candies are distributed among the senators in the optimal way.InputThe first line contains three integers n, k and A (1ββ€βn,βkββ€β8, 1ββ€βAββ€β9999).Then n lines follow. The i-th of them contains two numbers β bi and li β the i-th senator's level and his loyalty.The levels of all senators are integers in range from 1 to 9999 (inclusive). The loyalties of all senators are integers in range from 0 to 100 (inclusive) and all of them are divisible by 10.OutputPrint one real number with precision 10β-β6 β the maximal possible probability that the Dark Assembly approves the player's proposal for the best possible distribution of candies among the senators.ExamplesInput5 6 10011 8014 9023 7080 30153 70Output1.0000000000Input5 3 10011 8014 9023 7080 30153 70Output0.9628442962Input1 3 2020 20Output0.7500000000NoteIn the first sample the best way of candies' distribution is giving them to first three of the senators. It ensures most of votes.It the second sample player should give all three candies to the fifth senator. | Input5 6 10011 8014 9023 7080 30153 70 | Output1.0000000000 | 2 seconds | 256 megabytes | ['brute force', 'probabilities', '*1800'] |
A. Transmigrationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the k coefficient (if the skill level was equal to x, then after transmigration it becomes equal to [kx], where [y] is the integral part of y). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be?InputThe first line contains three numbers n, m and k β the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; n and m are integers, and k is a real number with exactly two digits after decimal point (1ββ€βn,βmββ€β20, 0.01ββ€βkββ€β0.99).Then follow n lines, each of which describes a character's skill in the form "name exp" β the skill's name and the character's skill level: name is a string and exp is an integer in range from 0 to 9999, inclusive. Then follow m lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names.OutputPrint on the first line number z β the number of skills the character will have after the transmigration. Then print z lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order.ExamplesInput5 4 0.75axe 350impaler 300ionize 80megafire 120magicboost 220healmegafireshieldmagicboostOutput6axe 262heal 0impaler 225magicboost 165megafire 0shield 0 | Input5 4 0.75axe 350impaler 300ionize 80megafire 120magicboost 220healmegafireshieldmagicboost | Output6axe 262heal 0impaler 225magicboost 165megafire 0shield 0 | 2 seconds | 256 megabytes | ['implementation', '*1700'] |
A. Blackjacktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne rainy gloomy evening when all modules hid in the nearby cafes to drink hot energetic cocktails, the Hexadecimal virus decided to fly over the Mainframe to look for a Great Idea. And she has found one!Why not make her own Codeforces, with blackjack and other really cool stuff? Many people will surely be willing to visit this splendid shrine of high culture.In Mainframe a standard pack of 52 cards is used to play blackjack. The pack contains cards of 13 values: 2, 3, 4, 5, 6, 7, 8, 9, 10, jacks, queens, kings and aces. Each value also exists in one of four suits: hearts, diamonds, clubs and spades. Also, each card earns some value in points assigned to it: cards with value from two to ten earn from 2 to 10 points, correspondingly. An ace can either earn 1 or 11, whatever the player wishes. The picture cards (king, queen and jack) earn 10 points. The number of points a card earns does not depend on the suit. The rules of the game are very simple. The player gets two cards, if the sum of points of those cards equals n, then the player wins, otherwise the player loses.The player has already got the first card, it's the queen of spades. To evaluate chances for victory, you should determine how many ways there are to get the second card so that the sum of points exactly equals n.InputThe only line contains n (1ββ€βnββ€β25) β the required sum of points.OutputPrint the numbers of ways to get the second card in the required way if the first card is the queen of spades.ExamplesInput12Output4Input20Output15Input10Output0NoteIn the first sample only four two's of different suits can earn the required sum of points.In the second sample we can use all tens, jacks, queens and kings; overall it's 15 cards, as the queen of spades (as any other card) is only present once in the pack of cards and it's already in use.In the third sample there is no card, that would add a zero to the current ten points. | Input12 | Output4 | 2 seconds | 256 megabytes | ['implementation', '*800'] |
E. Buying Setstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Hexadecimal virus loves playing with number sets β intersecting them, uniting them. One beautiful day she was surprised to find out that Scuzzy, her spherical pet cat, united all sets in one and ate the result! Something had to be done quickly and Hexadecimal rushed to the market.The market has n sets of numbers on sale. The virus wants to buy the following collection of sets: the number of sets in the collection should be exactly the same as the number of numbers in the union of all bought sets. Moreover, Hexadecimal wants to buy the cheapest suitable collection of set.Yet nothing's so easy! As Mainframe is a kingdom of pure rivalry markets, we know that the union of any k sets contains no less than k distinct numbers (for every positive integer k).Help the virus choose the suitable collection of sets. The collection can be empty.InputThe first line contains the only number n (1ββ€βnββ€β300) β the number of sets available in the market.Next n lines describe the goods: first we are given mi (1ββ€βmiββ€βn) β the number of distinct numbers in the i-th set, then follow mi numbers β the set's elements. We know that the set's elements are distinct positive integers and they do not exceed n.The last line contains n integers whose absolute values do not exceed 106 β the price of each set.OutputPrint a single number β the minimum price the virus will have to pay for such a collection of k sets that union of the collection's sets would have exactly k distinct numbers ().ExamplesInput31 12 2 31 310 20 -3Output-3Input52 1 22 2 32 3 42 4 52 5 11 -1 1 -1 1Output0Input52 1 22 2 32 3 42 4 52 5 1-1 1 -1 1 -1Output-1 | Input31 12 2 31 310 20 -3 | Output-3 | 2 seconds | 256 megabytes | ['flows', 'graph matchings', '*2900'] |
D. Time to Raid Cowavanstime limit per test4 secondsmemory limit per test70 megabytesinputstandard inputoutputstandard outputAs you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space. Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row. If we number all cows in the cowavan with positive integers from 1 to n, then we can formalize the popular model of abduction, known as the (a,βb)-Cowavan Raid: first they steal a cow number a, then number aβ+βb, then β number aβ+β2Β·b, and so on, until the number of an abducted cow exceeds n. During one raid the cows are not renumbered. The aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made p scenarios of the (a,βb)-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen. InputThe first line contains the only positive integer n (1ββ€βnββ€β3Β·105) β the number of cows in the cowavan.The second number contains n positive integer wi, separated by spaces, where the i-th number describes the mass of the i-th cow in the cowavan (1ββ€βwiββ€β109).The third line contains the only positive integer p β the number of scenarios of (a,βb)-raids (1ββ€βpββ€β3Β·105).Each following line contains integer parameters a and b of the corresponding scenario (1ββ€βa,βbββ€βn).OutputPrint for each scenario of the (a,βb)-raid the total mass of cows, that can be stolen using only this scenario.Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams of the %I64d specificator.ExamplesInput31 2 321 11 2Output64Input42 3 5 731 32 32 2Output9310 | Input31 2 321 11 2 | Output64 | 4 seconds | 70 megabytes | ['brute force', 'data structures', 'sortings', '*2100'] |
C. Russian Roulettetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all. Sasha selects any k out of n slots he wishes and puts bullets there. Roma spins the cylinder so that every of n possible cylinder's shifts is equiprobable. Then the game starts, the players take turns, Sasha starts: he puts the gun to his head and shoots. If there was no bullet in front of the trigger, the cylinder shifts by one position and the weapon is given to Roma for make the same move. The game continues until someone is shot, the survivor is the winner. Sasha does not want to lose, so he must choose slots for bullets in such a way as to minimize the probability of its own loss. Of all the possible variant he wants to select the lexicographically minimal one, where an empty slot is lexicographically less than a charged one. More formally, the cylinder of n bullet slots able to contain k bullets can be represented as a string of n characters. Exactly k of them are "X" (charged slots) and the others are "." (uncharged slots). Let us describe the process of a shot. Suppose that the trigger is in front of the first character of the string (the first slot). If a shot doesn't kill anyone and the cylinder shifts, then the string shifts left. So the first character becomes the last one, the second character becomes the first one, and so on. But the trigger doesn't move. It will be in front of the first character of the resulting string.Among all the strings that give the minimal probability of loss, Sasha choose the lexicographically minimal one. According to this very string, he charges the gun. You have to help Sasha to charge the gun. For that, each xi query must be answered: is there a bullet in the positions xi?InputThe first line contains three integers n, k and p (1ββ€βnββ€β1018,β0ββ€βkββ€βn,β1ββ€βpββ€β1000) β the number of slots in the cylinder, the number of bullets and the number of queries. Then follow p lines; they are the queries. Each line contains one integer xi (1ββ€βxiββ€βn) the number of slot to describe.Please do not use the %lld specificator to read or write 64-bit numbers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.OutputFor each query print "." if the slot should be empty and "X" if the slot should be charged.ExamplesInput3 1 3123Output..XInput6 3 6123456Output.X.X.XInput5 2 512345Output...XXNoteThe lexicographical comparison of is performed by the < operator in modern programming languages. The a string is lexicographically less that the b string, if there exists such i (1ββ€βiββ€βn), that aiβ<βbi, and for any j (1ββ€βjβ<βi) ajβ=βbj. | Input3 1 3123 | Output..X | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*1900'] |
B. Cthulhutime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with n vertices and m edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not.To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle.It is guaranteed that the graph contains no multiple edges and self-loops. InputThe first line contains two integers β the number of vertices n and the number of edges m of the graph (1ββ€βnββ€β100, 0ββ€βmββ€β).Each of the following m lines contains a pair of integers x and y, that show that an edge exists between vertices x and y (1ββ€βx,βyββ€βn,βxββ βy). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.OutputPrint "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.ExamplesInput6 66 36 45 12 51 45 4OutputFHTAGN!Input6 55 64 63 15 11 2OutputNONoteLet us denote as a simple cycle a set of v vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., vβ-β1 and v, v and 1.A tree is a connected undirected graph consisting of n vertices and nβ-β1 edges (nβ>β0).A rooted tree is a tree where one vertex is selected to be the root. | Input6 66 36 45 12 51 45 4 | OutputFHTAGN! | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', '*1500'] |
A. Testing Pants for Sadnesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?InputThe first line contains a positive integer n (1ββ€βnββ€β100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1ββ€βaiββ€β109), the number of answer variants to question i.OutputPrint a single number β the minimal number of clicks needed to pass the test it the worst-case scenario. Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInput21 1Output2Input22 2Output5Input110Output10NoteNote to the second sample. In the worst-case scenario you will need five clicks: the first click selects the first variant to the first question, this answer turns out to be wrong. the second click selects the second variant to the first question, it proves correct and we move on to the second question; the third click selects the first variant to the second question, it is wrong and we go back to question 1; the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question; the fifth click selects the second variant to the second question, it proves correct, the test is finished. | Input21 1 | Output2 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', '*1100'] |
B. Sum of Digitstime limit per test2 secondsmemory limit per test265 megabytesinputstandard inputoutputstandard outputHaving watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?InputThe first line contains the only integer n (0ββ€βnββ€β10100000). It is guaranteed that n doesn't contain any leading zeroes.OutputPrint the number of times a number can be replaced by the sum of its digits until it only contains one digit.ExamplesInput0Output0Input10Output1Input991Output3NoteIn the first sample the number already is one-digit β Herald can't cast a spell.The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.The third test contains number 991. As one casts a spell the following transformations take place: 991βββ19βββ10βββ1. After three transformations the number becomes one-digit. | Input0 | Output0 | 2 seconds | 265 megabytes | ['implementation', '*1000'] |
A. Clothestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.InputThe first input file line contains integers n and m β the total number of clothing items in the shop and the total number of matching pairs of clothing items ().Next line contains n integers ai (1ββ€βaiββ€β106) β the prices of the clothing items in rubles.Next m lines each contain a pair of space-separated integers ui and vi (1ββ€βui,βviββ€βn,βuiββ βvi). Each such pair of numbers means that the ui-th and the vi-th clothing items match each other. It is guaranteed that in each pair ui and vi are distinct and all the unordered pairs (ui,βvi) are different.OutputPrint the only number β the least possible sum in rubles that Gerald will have to pay in the shop. If the shop has no three clothing items that would match each other, print "-1" (without the quotes).ExamplesInput3 31 2 31 22 33 1Output6Input3 22 3 42 32 1Output-1Input4 41 1 1 11 22 33 44 1Output-1NoteIn the first test there only are three pieces of clothing and they all match each other. Thus, there is only one way β to buy the 3 pieces of clothing; in this case he spends 6 roubles.The second test only has three pieces of clothing as well, yet Gerald can't buy them because the first piece of clothing does not match the third one. Thus, there are no three matching pieces of clothing. The answer is -1.In the third example there are 4 pieces of clothing, but Gerald can't buy any 3 of them simultaneously. The answer is -1. | Input3 31 2 31 22 33 1 | Output6 | 2 seconds | 256 megabytes | ['brute force', '*1200'] |
E. Candies and Stonestime limit per test7.5 secondsmemory limit per test45 megabytesinputstandard inputoutputstandard outputLittle Gerald and his coach Mike play an interesting game. At the beginning of the game there is a pile consisting of n candies and a pile consisting of m stones. Gerald and Mike move in turns, Mike goes first. During his move Mike checks how many candies and stones Gerald has eaten. Let Gerald eat a candies and b stones. Then Mike awards Gerald f(a,βb) prize points. Gerald during his move either eats a candy from the pile of candies or a stone from the pile of stones. As Mike sees that Gerald has eaten everything apart one candy and one stone, he awards points for the last time and the game ends. Gerald is not allowed to eat all the candies, and he is not allowed to eat all the stones too. Tell Gerald how to play to get the largest possible number of points: it is required to find one of the possible optimal playing strategies for Gerald.InputThe first line contains three integers n,βm,βp (1ββ€βn,βmββ€β20000, 1ββ€βpββ€β109). The second line contains n integers x0, x1, ..., xnβ-β1 (0ββ€βxiββ€β20000). The third line contains m integers y0, y1, ..., ymβ-β1 (0ββ€βyiββ€β20000). The value of f(a,βb) is calculated as a remainder of the division of the sum xaβ+βyb by number p.OutputPrint on the first line the only number: the maximal number of points Gerald can earn. Print on the second line a sting consisting of nβ+βmβ-β2 characters, each of which is either a "C" or "S", the i-th character should be "C" if Gerald's i-th move should be eating a candy and "S" if he should eat a stone.ExamplesInput2 2 100 00 1Output2SCInput3 3 100 2 00 0 2Output10CSSCInput3 3 20 1 11 1 0Output4SCSCNoteIn the first test if Gerald's first move is eating a stone, he will receive a point for it and if he eats a candy, he will get zero pints. In any way Gerald will get 0 points before his first move, and 1 after his second one. This, the maximum number of points Gerald can get equals to 2, and for that he should first eat a stone, then a candy. | Input2 2 100 00 1 | Output2SC | 7.5 seconds | 45 megabytes | ['divide and conquer', 'dp', '*2500'] |
D. Castletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald is positioned in an old castle which consists of n halls connected with nβ-β1 corridors. It is exactly one way to go from any hall to any other one. Thus, the graph is a tree. Initially, at the moment of time 0, Gerald is positioned in hall 1. Besides, some other hall of the castle contains the treasure Gerald is looking for. The treasure's position is not known; it can equiprobably be in any of other nβ-β1 halls. Gerald can only find out where the treasure is when he enters the hall with the treasure. That very moment Gerald sees the treasure and the moment is regarded is the moment of achieving his goal. The corridors have different lengths. At that, the corridors are considered long and the halls are considered small and well lit. Thus, it is possible not to take the time Gerald spends in the halls into consideration. The castle is very old, that's why a corridor collapses at the moment when somebody visits it two times, no matter in which direction. Gerald can move around the castle using the corridors; he will go until he finds the treasure. Naturally, Gerald wants to find it as quickly as possible. In other words, he wants to act in a manner that would make the average time of finding the treasure as small as possible. Each corridor can be used no more than two times. That's why Gerald chooses the strategy in such a way, so he can visit every hall for sure.More formally, if the treasure is located in the second hall, then Gerald will find it the moment he enters the second hall for the first time β let it be moment t2. If the treasure is in the third hall, then Gerald will find it the moment he enters the third hall for the first time. Let it be the moment of time t3. And so on. Thus, the average time of finding the treasure will be equal to .InputThe first line contains the only integer n (2ββ€βnββ€β105) β the number of halls in the castle. Next nβ-β1 lines each contain three integers. The i-th line contains numbers ai, bi and ti (1ββ€βai,βbiββ€βn, aiββ βbi, 1ββ€βtiββ€β1000) β the numbers of halls connected with the i-th corridor and the time needed to go along the corridor. Initially Gerald is in the hall number 1. It is guaranteed that one can get from any hall to any other one using corridors.OutputPrint the only real number: the sought expectation of time needed to find the treasure. The answer should differ from the right one in no less than 10β-β6.ExamplesInput21 2 1Output1.0Input41 3 24 2 13 2 3Output4.333333333333334Input51 2 11 3 11 4 11 5 1Output4.0NoteIn the first test the castle only has two halls which means that the treasure is located in the second hall. Gerald will only need one minute to go to the second hall from the first one.In the second test Gerald can only go from the first hall to the third one. He can get from the third room to the first one or to the second one, but he has already visited the first hall and can get nowhere from there. Thus, he needs to go to the second hall. He should go to hall 4 from there, because all other halls have already been visited. If the treasure is located in the third hall, Gerald will find it in a minute, if the treasure is located in the second hall, Gerald finds it in two minutes, if the treasure is in the fourth hall, Gerald will find it in three minutes. The average time makes 2 minutes.In the third test Gerald needs to visit 4 halls: the second, third, fourth and fifth ones. All of them are only reachable from the first hall. Thus, he needs to go to those 4 halls one by one and return. Gerald will enter the first of those halls in a minute, in the second one β in three minutes, in the third one - in 5 minutes, in the fourth one - in 7 minutes. The average time is 4 minutes. | Input21 2 1 | Output1.0 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'probabilities', 'sortings', 'trees', '*2300'] |
C. Vectorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt a geometry lesson Gerald was given a task: to get vector B out of vector A. Besides, the teacher permitted him to perform the following operations with vector Π: Turn the vector by 90 degrees clockwise. Add to the vector a certain vector C.Operations could be performed in any order any number of times.Can Gerald cope with the task?InputThe first line contains integers x1 ΠΈ y1 β the coordinates of the vector A (β-β108ββ€βx1,βy1ββ€β108). The second and the third line contain in the similar manner vectors B and C (their coordinates are integers; their absolute value does not exceed 108).OutputPrint "YES" (without the quotes) if it is possible to get vector B using the given operations. Otherwise print "NO" (without the quotes).ExamplesInput0 01 10 1OutputYESInput0 01 11 1OutputYESInput0 01 12 2OutputNO | Input0 01 10 1 | OutputYES | 1 second | 256 megabytes | ['implementation', 'math', '*2000'] |
B. Busestime limit per test2 secondsmemory limit per test265 megabytesinputstandard inputoutputstandard outputLittle boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly nβ+β1 bus stops. All of them are numbered with integers from 0 to n in the order in which they follow from Gerald's home. The bus stop by Gerald's home has number 0 and the bus stop by the school has number n.There are m buses running between the house and the school: the i-th bus goes from stop si to ti (siβ<βti), visiting all the intermediate stops in the order in which they follow on the segment. Besides, Gerald's no idiot and he wouldn't get off the bus until it is still possible to ride on it closer to the school (obviously, getting off would be completely pointless). In other words, Gerald can get on the i-th bus on any stop numbered from si to tiβ-β1 inclusive, but he can get off the i-th bus only on the bus stop ti.Gerald can't walk between the bus stops and he also can't move in the direction from the school to the house.Gerald wants to know how many ways he has to get from home to school. Tell him this number. Two ways are considered different if Gerald crosses some segment between the stops on different buses. As the number of ways can be too much, find the remainder of a division of this number by 1000000007 (109β+β7).InputThe first line contains two space-separated integers: n and m (1ββ€βnββ€β109,β0ββ€βmββ€β105). Then follow m lines each containing two integers si,βti. They are the numbers of starting stops and end stops of the buses (0ββ€βsiβ<βtiββ€βn).OutputPrint the only number β the number of ways to get to the school modulo 1000000007 (109β+β7).ExamplesInput2 20 11 2Output1Input3 20 11 2Output0Input5 50 10 20 30 40 5Output16NoteThe first test has the only variant to get to school: first on bus number one to the bus stop number one; then on bus number two to the bus stop number two.In the second test no bus goes to the third bus stop, where the school is positioned. Thus, the correct answer is 0.In the third test Gerald can either get or not on any of the first four buses to get closer to the school. Thus, the correct answer is 24β=β16. | Input2 20 11 2 | Output1 | 2 seconds | 265 megabytes | ['binary search', 'data structures', 'dp', '*1700'] |
A. Homeworktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than k characters, it will be very suspicious. Find the least number of distinct characters that can remain in the string after no more than k characters are deleted. You also have to find any possible way to delete the characters.InputThe first input data line contains a string whose length is equal to n (1ββ€βnββ€β105). The string consists of lowercase Latin letters. The second line contains the number k (0ββ€βkββ€β105).OutputPrint on the first line the only number m β the least possible number of different characters that could remain in the given string after it loses no more than k characters.Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly m distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly m distinct characters, print any of them.ExamplesInputaaaaa4Output1aaaaaInputabacaba4Output1aaaaInputabcdefgh10Output0NoteIn the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length.In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string.In the third sample you are given a line whose length is equal to 8, and kβ=β10, so that the whole line can be deleted. The correct answer is 0 and an empty string. | Inputaaaaa4 | Output1aaaaa | 2 seconds | 256 megabytes | ['greedy', '*1200'] |
J. Interval Coloringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAryo has got a lot of intervals for his 2418th birthday. He is really excited and decided to color all these intervals with some colors. He has a simple rule for himself. He calls a coloring nice if there exists no three intervals a,βb and c such that the following conditions are satisfied simultaneously: a,βb and c are colored with the same color, , , . Moreover he found out that for every intervals i and j, there is at least one point in i which isn't in j.Given some set of intervals. You have to find the minimum number k, such that Aryo can find a nice coloring with k colors.InputThe first line contains a single integer n (1ββ€βnββ€β103), number of intervals.The following n lines contain a interval description each. Each interval is described by two numbers si,βei which are the start and end points of it (β-β105β<βsi,βeiβ<β105, siββ€βei). See samples for clarity. A square bracket stands for including of the corresponding endpoint, while a round bracket stands for excluding.OutputWrite a single integer k β the minimum number of colors needed for a nice coloring.ExamplesInput2[1,2)(3,4]Output1Input3[1,3][2,6](5,7)Output2 | Input2[1,2)(3,4] | Output1 | 2 seconds | 256 megabytes | ['*special problem', 'greedy', 'math', '*2400'] |
I. Rotationtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputEhsan loves geometry! Especially he likes to rotate points!Given a point in the plane, Ehsan likes to rotate it by k degrees (counter-clockwise), around the origin. What is the result of this rotation?InputA single integer k (0ββ€βkβ<β360) is given in the first line. Two integer numbers x and y are given in the second line (β-β1390ββ€βx,βyββ€β1390).OutputWrite two numbers. The result of the rotation. Your answer must have a relative error less than 10β-β1.ExamplesInput901 1Output-1.00000000 1.00000000Input1801 1390Output-1.00000000 -1390.00000000 | Input901 1 | Output-1.00000000 1.00000000 | 2 seconds | 64 megabytes | ['*special problem', 'geometry', 'math', '*1500'] |
H. Battleshiptime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputDo you know the game Battleship? If no, look into Wikipedia article http://en.wikipedia.org/wiki/Battleship_(game). You are given the positions of ships on a 10βΓβ10 board for playing Battleship. According to the rules, the board should contain the following ships: one of size 4 (4βΓβ1 or 1βΓβ4 rectangle), two of size 3 (3βΓβ1 or 1βΓβ3 rectangles), three of size 2 (2βΓβ1 or 1βΓβ2 rectangles), four of size 1 (1βΓβ1 rectangles). The ships should not 'bend', touch each other or overlap in any way. Each ship can be oriented horizontaly or verticaly. Your task is to check whether the given set of boards meets the given conditions.InputThe first line contains number n (1ββ€βnββ€β10) β the number of boards. Each board is described by 10 lines containing 10 characters each. The symbol "0" stands for an empty square and the symbol "*" stands for a square occupied by a ship. The descriptions of boards are separated with empty lines.OutputPrint n lines YES or NO. Print the first word if the board meets the given conditions; otherwise print the second word.ExamplesInput2****0000000000000000***00***00000000000000000000**000**0000000000000**000*00000000000*00*00*00000000****0000000000000000***00***00000000000000000000**000**0000000000000**0000*0000000000*00*00*00000000OutputYESNO | Input2****0000000000000000***00***00000000000000000000**000**0000000000000**000*00000000000*00*00*00000000****0000000000000000***00***00000000000000000000**000**0000000000000**0000*0000000000*00*00*00000000 | OutputYESNO | 2 seconds | 64 megabytes | ['*special problem', 'dfs and similar', 'implementation', '*2100'] |
G. Name the albumtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThe famous singer, Aryo, is going to publish a new album of his great work!Unfortunately these days, there are many albums, Aryo wants to choose a new name for his album, a name that has not been used or at least has not been used recently.He has a list of all used album names together with the year the albums were published. He also has a list of suitable names for his album.If he finds a suitable name which has not been used before, he'll use it. Otherwise he will use the name which was used as long ago as possible. If two such names are found (that haven't been used or were used at the same year), he uses the name that is alphabetically latest.Help him name his album.InputThe first line contains a single integer n (0ββ€βnββ€β105), the number of used names. The following n lines each contain a string (the album name) and an integer (the year album was published). Album names are made of lowercase Latin letters and contain at most 14 letters. The year is in range [1900,β2011].The following line contains a single integer m (1ββ€βmββ€β104), the number of suitable album names.The following m lines each contain a string β a suitable name. It contains at most 14 lowercase Latin letters.All album names and suitable names are non-empty.OutputWrite a single string. The name of the new album.ExamplesInput3eyesonme 2008anewdayhascome 2002oneheart 20032oneheartbienbienOutputbienbienInput2nasimevasl 2003basetareha 20062nasimevaslbasetarehaOutputnasimevasl | Input3eyesonme 2008anewdayhascome 2002oneheart 20032oneheartbienbien | Outputbienbien | 2 seconds | 64 megabytes | ['*special problem', 'data structures', 'implementation', '*1800'] |
F. Polynomtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are given a polynom in form p(x)β=β(xβ+βa1)Β·(xβ+βa2)Β·... (xβ+βan). Write Pike program to print it in a standard form p(x)β=βxnβ+βb1xnβ-β1β+β...β+βbnβ-β1xβ+βbn. You should write each addend in form Β«C*X^KΒ» (for example, 5*X^8).Please, write the polynom in the shortest way, so you should skip unnecessary terms: some terms Β«C*X^KΒ» should be reduced or even omitted. Look for the samples for clarification.InputThe first line of the input contains n (1ββ€βnββ€β9). The following n lines contain integer ai (β-β10ββ€βaiββ€β10).OutputPrint the given polynom in a standard way. Note, that the answer in this problem response uniquely determined.ExamplesInput2-11OutputX^2-1Input211OutputX^2+2*X+1 | Input2-11 | OutputX^2-1 | 2 seconds | 64 megabytes | ['*special problem', 'implementation', '*1800'] |
E. Lamps in a Linetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n lamps in a line. The lamps are numbered 1 to n from left to right. There are also n keys. When key number i is pressed, all lamps number x such that i|x change their state.For two integer numbers a and b, we say a|b if and only if there exists an integer c such that aβΓβcβ=βb.Amirali likes to play with the keys. He randomly pressed k keys and wants to know the final state of the lamps. Help him by writing a Pike piece of code to solve this task.InputThe first line of input contains a single integer n, the number of lamps (1ββ€βnββ€β105).The following line contains n words. The i-th word describes the initial state of lamp number i (see samples for details).The following line contains a single integer k (1ββ€βkββ€β104), the number of times a key is pressed. Then in the next line come k integers in range [1,βn] which are the numbers of the pressed keys.OutputWrite n words to output. Describe the final state of the lamps. See samples for more details.ExamplesInput2off off21 2Outputon off Input3off off on61 1 1 1 2 2Outputoff off on | Input2off off21 2 | Outputon off | 1 second | 256 megabytes | ['*special problem', 'math', '*1600'] |
D. World of Mouthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are a lot of rumors in the media these days. One day Aida decided to find out how rumors are made.She asked n of her friends to help her. They all formed a circle and Aida told the person to her right a piece of news which was just a simple string. Then each person told the string to the person on his/her right. But they didn't tell the string exactly as they'd heard it. Each person made at most one of these two types of changes: Removing one character from the end of the heard string. Adding a character to the end of the heard string. Finally when the rumor passed exactly n moves (a complete cycle), Aida heard something quite different from what she expected from the person on her left. She thinks someone has cheated and made some changes other than those explained above. Now she wants you to write a Pike piece of code which gets the initial and final strings and tells Aida whether it's possible to get to the final string from the initial one, by the rules described above.InputThe first line contains a single integer n (2ββ€βnββ€β8βΓβ106), the number of Aida's friends. The following two lines contain a non-empty string each β initial and final strings. The lengths of strings are at most 107 and they only contain English alphabet letters.OutputWrite a single YES or NO. Write YES only if it's possible to get to the final string from the initial string.ExamplesInput100CodeforcesMMIODPCOutputYesInput5MMIODCFOutputNoNoteThe input is case-sensitive, while the output is not. | Input100CodeforcesMMIODPC | OutputYes | 5 seconds | 256 megabytes | ['*special problem', 'strings', '*1500'] |
C. A+Btime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputBijan is new to programming. He learned recently that programmers do not code every bit of their apps from scratch.For example they never write a code to sum two integers, because their languages have the ability to do the sum. But can they use it? Can an experienced coder who has attended more than 100 contests, sum two integers?Bijan is not sure about this. What's your opinion?InputYou are given two integers a and b, one per line (1ββ€βa,βbβ<β10500). These numbers will not have any leading zeros.OutputWrite sum of the two integers. Do not put any leading zeros.ExamplesInput23Output5Input13902011Output3401Input1234554321Output66666 | Input23 | Output5 | 2 seconds | 64 megabytes | ['*special problem', 'implementation', '*1400'] |
B. Friendly Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKiana thinks two integers are friends if and only if one of them divides the other one. For example, 12 and 4 are friends, also 6 and 6 are friends too, but 120 and 36 are not.A group of non-zero integers is called friendly, if each pair of its integers form a friend pair.You are given a group of non-zero integers. See if they're friendly.InputThe first line contains n (1ββ€βnββ€β1000), where n β the number of integers in the group.The next line contains the elements, sorted in the non-decreasing order. The numbers are comma separated, they have at most 7 digits in their decimal notation and do not have any leading zeros.OutputIf the group is friendly write "FRIENDS", else write "NOT FRIENDS".ExamplesInput41,3,6,12OutputFRIENDSInput31,2,9OutputNOT FRIENDS | Input41,3,6,12 | OutputFRIENDS | 2 seconds | 256 megabytes | ['*special problem', 'implementation', '*1500'] |
A. Carpeting the Roomtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputSoroush's room is a square with side length n. Before this contest he bought k fine Persian carpets to carpet his room for celebrating the 100th contest on his favorite site. Each Persian carpet is a square of side length n1.Soroush wants to cover all the area of his room. Carpets can be put over each other but it is not allowed to rotate the carpets. Can Soroush carpet his room completely?InputThe input consists of three integer numbers n, k and n1 (10ββ€βnββ€β12, 1ββ€βkββ€β10, ).OutputWrite a single YES or NO. Write YES if and only if Sorush can carpet his room completely.ExamplesInput10 4 6OutputYESInput10 2 5OutputNO | Input10 4 6 | OutputYES | 2 seconds | 64 megabytes | ['*special problem', 'implementation', '*1100'] |
B. Help Chef Gerasimtime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.InputThe first line contains integer n β the number of cups on the royal table (1ββ€βnββ€β1000). Next n lines contain volumes of juice in each cup β non-negative integers, not exceeding 104.OutputIf the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).ExamplesInput5270250250230250Output20 ml. from cup #4 to cup #1.Input5250250250250250OutputExemplary pages.Input5270250249230250OutputUnrecoverable configuration. | Input5270250250230250 | Output20 ml. from cup #4 to cup #1. | 0.5 second | 256 megabytes | ['implementation', 'sortings', '*1300'] |
A. Help Far Away Kingdomtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this: If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the numberβs integer part. If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the numberβs integer part. If the numberβs integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position. Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the Kingβs order?InputThe first line contains a single number to round up β the integer part (a non-empty set of decimal digits that do not start with 0 β with the exception of a case when the set consists of a single digit β in this case 0 can go first), then follows character Β«.Β» (a dot), and then follows the fractional part (any non-empty set of decimal digits). The number's length does not exceed 1000 characters, including the dot. There are no other characters in the input data.OutputIf the last number of the integer part is not equal to 9, print the rounded-up number without leading zeroes. Otherwise, print the message "GOTO Vasilisa." (without the quotes).ExamplesInput0.0Output0Input1.49Output1Input1.50Output2Input2.71828182845904523536Output3Input3.14159265358979323846Output3Input12345678901234567890.1Output12345678901234567890Input123456789123456789.999OutputGOTO Vasilisa. | Input0.0 | Output0 | 2 seconds | 256 megabytes | ['strings', '*800'] |
E. Help Shrek and Donkeytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputShrek and the Donkey (as you can guess, they also live in the far away kingdom) decided to play a card game called YAGame. The rules are very simple: initially Shrek holds m cards and the Donkey holds n cards (the players do not see each other's cards), and one more card lies on the table face down so that both players cannot see it as well. Thus, at the beginning of the game there are overall mβ+βnβ+β1 cards. Besides, the players know which cards the pack of cards consists of and their own cards (but they do not know which card lies on the table and which ones the other player has). The players move in turn and Shrek starts. During a move a player can: Try to guess which card is lying on the table. If he guesses correctly, the game ends and he wins. If his guess is wrong, the game also ends but this time the other player wins. Name any card from the pack. If the other player has such card, he must show it and put it aside (so that this card is no longer used in the game). If the other player doesn't have such card, he says about that. Recently Donkey started taking some yellow pills and winning over Shrek. Now Shrek wants to evaluate his chances to win if he too starts taking the pills.Help Shrek assuming the pills are good in quality and that both players using them start playing in the optimal manner.InputThe first line contains space-separated integers m and n (0ββ€βm,βnββ€β1000).OutputPrint space-separated probabilities that Shrek wins and Donkey wins correspondingly; the absolute error should not exceed 10β-β9.ExamplesInput0 3Output0.25 0.75Input1 0Output1 0Input1 1Output0.5 0.5 | Input0 3 | Output0.25 0.75 | 2 seconds | 256 megabytes | ['dp', 'games', 'math', 'probabilities', '*2700'] |
D. Help Monkstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a far away kingdom is the famous Lio Shan monastery. Gods constructed three diamond pillars on the monastery's lawn long ago. Gods also placed on one pillar n golden disks of different diameters (in the order of the diameters' decreasing from the bottom to the top). Besides, gods commanded to carry all the disks from the first pillar to the third one according to the following rules: you can carry only one disk in one move; you cannot put a larger disk on a smaller one. There was no universal opinion concerning what is to happen after the gods' will is done: some people promised world peace and eternal happiness to everyone, whereas others predicted that the kingdom will face communiβ¦ (gee, what am I rambling about?) the Armageddon. However, as everybody knew that it was impossible to solve the problem in less than 2nβ-β1 moves and the lazy Lio Shan monks never even started to solve it, everyone lives peacefully even though the problem was never solved and nobody was afraid of the Armageddon.However, the monastery wasn't doing so well lately and the wise prior Ku Sean Sun had to cut some disks at the edges and use the gold for the greater good. Wouldn't you think that the prior is entitled to have an air conditioning system? Besides, staying in the monastery all year is sooo dullβ¦ One has to have a go at something new now and then, go skiing, for exampleβ¦ Ku Sean Sun realize how big a mistake he had made only after a while: after he cut the edges, the diameters of some disks got the same; that means that some moves that used to be impossible to make, were at last possible (why, gods never prohibited to put a disk on a disk of the same diameter). Thus, the possible Armageddon can come earlier than was initially planned by gods. Much earlier. So much earlier, in fact, that Ku Sean Sun won't even have time to ski all he wants or relax under the air conditioner.The wise prior could never let that last thing happen and he asked one very old and very wise witch PikiWedia to help him. May be she can determine the least number of moves needed to solve the gods' problem. However, the witch laid out her cards and found no answer for the prior. Then he asked you to help him.Can you find the shortest solution of the problem, given the number of disks and their diameters? Keep in mind that it is allowed to place disks of the same diameter one on the other one, however, the order in which the disks are positioned on the third pillar in the end should match the initial order of the disks on the first pillar.InputThe first line contains an integer n β the number of disks (1ββ€βnββ€β20). The second line contains n integers di β the disks' diameters after Ku Sean Sun cut their edges. The diameters are given from the bottom to the top (1ββ€βdiββ€β20, besides, diββ₯βdiβ+β1 for any 1ββ€βiβ<βn).OutputPrint on the first line number m β the smallest number of moves to solve the gods' problem. Print on the next m lines the description of moves: two space-separated positive integers si and ti that determine the number of the pillar from which the disk is moved and the number of pillar where the disk is moved, correspondingly (1ββ€βsi,βtiββ€β3, siββ βti). ExamplesInput33 2 1Output71 31 23 21 32 12 31 3Input33 1 1Output51 21 21 32 32 3Input33 3 3Output51 21 21 32 32 3NotePay attention to the third test demonstrating that the order of disks should remain the same in the end, even despite the disks' same radius. If this condition was not necessary to fulfill, the gods' task could have been solved within a smaller number of moves (three β simply moving the three disks from the first pillar on the third one). | Input33 2 1 | Output71 31 23 21 32 12 31 3 | 2 seconds | 256 megabytes | ['constructive algorithms', '*2500'] |
C. Help Greg the Dwarftime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA very unusual citizen lives in a far away kingdom β Dwarf Gracula. However, his unusual name is not the weirdest thing (besides, everyone long ago got used to calling him simply Dwarf Greg). What is special about Dwarf Greg β he's been living for over 200 years; besides, he lives in a crypt on an abandoned cemetery and nobody has ever seen him out in daytime. Moreover, nobody has ever seen Greg buy himself any food. That's why nobody got particularly surprised when after the infernal dragon's tragic death cattle continued to disappear from fields. The people in the neighborhood were long sure that the harmless dragon was never responsible for disappearing cattle (considering that the dragon used to be sincere about his vegetarian views). But even that's not the worst part of the whole story.The worst part is that merely several minutes ago Dwarf Greg in some unintelligible way got inside your house and asked you to help him solve a problem. The point is that a short time ago Greg decided to order a new coffin (knowing his peculiar character, you are not surprised at all). But the problem is: a very long in both directions L-shaped corridor leads to Greg's crypt, and you can't drag just any coffin through that corridor. That's why he asked you to help. You've formalized the task on a plane like this: let the corridor's width before and after the turn be equal to a and b correspondingly (see the picture). The corridor turns directly at a right angle, the coffin is a rectangle whose length and width are equal to l and w (lββ₯βw) correspondingly. Dwarf Greg has already determined the coffin's length (l), which is based on his height; your task is to determine the coffin's maximally possible width (w), at which it can be brought to the crypt. Besides, due to its large mass (pure marble!) the coffin is equipped with rotating wheels; therefore it is impossible to lift it off the ground, however, arbitrary moves and rotations of the coffin in the plane become possible. The coffin may be rotated arbitrarily just before you drag it into crypt and move through the corridor.Greg promised that if you help him, he will grant you immortality (I wonder how?). And if you don't, well... trust me, you don't want to know what happens if you don't help him...InputThe first line contains three space-separated integers a, b and l from the problem's statement (1ββ€βa,βb,βlββ€β104).OutputPrint the maximally possible width of a coffin with absolute or relative error no more than 10β-β7. If a coffin with the given length and positive width (the coffin that would meet the conditions from the problem's statement) does not exist, print "My poor head =(" (without quotes).It is guaranteed that if the answer is positive, it will be not less than 10β-β7. All the hacks will also be checked to meet that condition.ExamplesInput2 2 1Output1.0000000Input2 2 2Output2.0000000Input2 2 3Output1.3284271Input2 2 6OutputMy poor head =(NoteIn the first example the answer is restricted by the coffin's length (remember β coffin's widths should not be larger than it's length).In the second example it is possible to drag the coffin through the corridor thanks to rotating wheels: firstly, drag it forward by one side while it will not be hampered by the wall, then move it forward by adjacent side perpendicularly to the initial movement direction (remember β arbitrary moves and rotations of the coffin are possible). | Input2 2 1 | Output1.0000000 | 2 seconds | 256 megabytes | ['geometry', 'ternary search', '*2500'] |
B. Help Kingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the modification of the problem used during the official round. Unfortunately, author's solution of the original problem appeared wrong, so the problem was changed specially for the archive.Once upon a time in a far away kingdom lived the King. The King had a beautiful daughter, Victoria. They lived happily, but not happily ever after: one day a vicious dragon attacked the kingdom and stole Victoria. The King was full of grief, yet he gathered his noble knights and promised half of his kingdom and Victoria's hand in marriage to the one who will save the girl from the infernal beast.Having travelled for some time, the knights found the dragon's lair and all of them rushed there to save Victoria. Each knight spat on the dragon once and, as the dragon had quite a fragile and frail heart, his heart broke and poor beast died. As for the noble knights, they got Victoria right to the King and started brawling as each one wanted the girl's hand in marriage.The problem was that all the noble knights were equally noble and equally handsome, and Victoria didn't want to marry any of them anyway. Then the King (and he was a very wise man and didn't want to hurt anybody's feelings) decided to find out who will get his daughter randomly, i.e. tossing a coin. However, there turned out to be n noble knights and the coin only has two sides. The good thing is that when a coin is tossed, the coin falls on each side with equal probability. The King got interested how to pick one noble knight using this coin so that all knights had equal probability of being chosen (the probability in that case should always be equal to 1β/βn). First the King wants to know the expected number of times he will need to toss a coin to determine the winner. Besides, while tossing the coin, the King should follow the optimal tossing strategy (i.e. the strategy that minimizes the expected number of tosses). Help the King in this challenging task.InputThe first line contains a single integer n from the problem's statement (1ββ€βnββ€β10000).OutputPrint the sought expected number of tosses as an irreducible fraction in the following form: "a/b" (without the quotes) without leading zeroes.ExamplesInput2Output1/1Input3Output8/3Input4Output2/1 | Input2 | Output1/1 | 2 seconds | 256 megabytes | ['implementation', 'probabilities', 'trees', '*2200'] |
A. Help Victoria the Wisetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that.The box's lock is constructed like that. The box itself is represented by an absolutely perfect black cube with the identical deepening on each face (those are some foreign nanotechnologies that the far away kingdom scientists haven't dreamt of). The box is accompanied by six gems whose form matches the deepenings in the box's faces. The box can only be opened after it is correctly decorated by the gems, that is, when each deepening contains exactly one gem. Two ways of decorating the box are considered the same if they can be obtained one from the other one by arbitrarily rotating the box (note that the box is represented by a perfect nanotechnological cube)Now Vasilisa the Wise wants to know by the given set of colors the following: in how many ways would she decorate the box in the worst case to open it? To answer this question it is useful to know that two gems of one color are indistinguishable from each other. Help Vasilisa to solve this challenging problem.InputThe first line contains exactly 6 characters without spaces from the set {R, O, Y, G, B, V} β they are the colors of gems with which the box should be decorated.OutputPrint the required number of different ways to decorate the box.ExamplesInputYYYYYYOutput1InputBOOOOBOutput2InputROYGBVOutput30 | InputYYYYYY | Output1 | 1 second | 256 megabytes | ['brute force', 'implementation', '*1700'] |
E. Leaderstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a revolution in Berland the new dictator faced an unexpected challenge: the country has to be somehow ruled. The dictator is a very efficient manager, yet he can't personally give orders to each and every citizen. That's why he decided to pick some set of leaders he would control. Those leaders will directly order the citizens. However, leadership efficiency turned out to vary from person to person (i.e. while person A makes an efficient leader, person B may not be that good at it). That's why the dictator asked world-famous berland scientists for help. The scientists suggested an innovatory technology β to make the leaders work in pairs.A relationship graph is some undirected graph whose vertices correspond to people. A simple path is a path with no repeated vertices. Long and frighteningly expensive research showed that a pair of people has maximum leadership qualities if a graph of relationships has a simple path between them with an odd number of edges. The scientists decided to call such pairs of different people leader pairs. Secret services provided the scientists with the relationship graph so that the task is simple β we have to learn to tell the dictator whether the given pairs are leader pairs or not. Help the scientists cope with the task.InputThe first line contains integers n and m (1ββ€βnββ€β105,β0ββ€βmββ€β105) β the number of vertices and edges in the relationship graph correspondingly. Next m lines contain pairs of integers a and b which mean that there is an edge between the a-th and the b-th vertices (the vertices are numbered starting from 1, 1ββ€βa,βbββ€βn). It is guaranteed that the graph has no loops or multiple edges.Next line contains number q (1ββ€βqββ€β105) β the number of pairs the scientists are interested in. Next q lines contain these pairs (in the same format as the edges, the queries can be repeated, a query can contain a pair of the identical vertices).OutputFor each query print on a single line "Yes" if there's a simple odd path between the pair of people; otherwise, print "No".ExamplesInput7 71 31 42 32 45 66 77 581 21 31 42 41 55 65 76 7OutputNoYesYesYesNoYesYesYesNoteNotes to the samples:1) Between vertices 1 and 2 there are 2 different simple paths in total: 1-3-2 and 1-4-2. Both of them consist of an even number of edges. 2) Vertices 1 and 3 are connected by an edge, that's why a simple odd path for them is 1-3.5) Vertices 1 and 5 are located in different connected components, there's no path between them. | Input7 71 31 42 32 45 66 77 581 21 31 42 41 55 65 76 7 | OutputNoYesYesYesNoYesYesYes | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', 'trees', '*2200'] |
D. Robot in Basementtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Professor has lost his home robot yet again. After some thinking Professor understood that he had left the robot in the basement.The basement in Professor's house is represented by a rectangle nβΓβm, split into 1βΓβ1 squares. Some squares are walls which are impassable; other squares are passable. You can get from any passable square to any other passable square moving through edge-adjacent passable squares. One passable square is the exit from the basement. The robot is placed exactly in one passable square. Also the robot may be placed in the exit square.Professor is scared of going to the dark basement looking for the robot at night. However, he has a basement plan and the robot's remote control. Using the remote, Professor can send signals to the robot to shift one square left, right, up or down. When the robot receives a signal, it moves in the required direction if the robot's neighboring square in the given direction is passable. Otherwise, the robot stays idle.Professor wrote a sequence of k commands on a piece of paper. He thinks that the sequence can lead the robot out of the basement, wherever it's initial position might be. Professor programmed another robot to press the required buttons on the remote according to the notes on the piece of paper. Professor was just about to run the program and go to bed, when he had an epiphany.Executing each command takes some energy and Professor doesn't want to get huge electricity bill at the end of the month. That's why he wants to find in the sequence he has written out the minimal possible prefix that would guarantee to lead the robot out to the exit after the prefix is fulfilled. And that's the problem Professor challenges you with at this late hour.InputThe first line contains three integers n, m and k (3ββ€βn,βmββ€β150, 1ββ€βkββ€β105). Next n lines contain m characters each β that is the Professor's basement's description: "#" stands for a wall, "." stands for a passable square and "E" stands for the exit from the basement (this square also is passable). It is possible to get from each passable square to the exit, all squares located by the nβΓβm rectangle's perimeter are the walls. Exactly one square is the exit from the basement. The last line contains k characters, the description of the sequence of commands that Professor has written out on a piece of paper. "L", "R", "U", "D" stand for commands left, right, up and down correspondingly.OutputPrint in the output file the length of the smallest possible prefix that will lead the robot to the exit square. In other words, wherever the robot had been positioned initially, it should be positioned in the exit square after all the commands from the prefix are fulfilled (during doing commands the robot can come and leave the exit square, but only the last position of the robot is interesting for us). If Professor is mistaken and no prefix (including the whole sequence) can bring the robot to the exit, print "-1" (without the quotes). If there is the only passable square and it is the exit, print "0" (without the quotes).ExamplesInput5 5 7######...##...##E..######UULLDDROutput6Input5 5 7######.#.##...##E..######UULLDDROutput-1Input5 3 2####.##.##E####DDOutput2 | Input5 5 7######...##...##E..######UULLDDR | Output6 | 4 seconds | 256 megabytes | ['bitmasks', 'brute force', 'implementation', '*2700'] |
C. Winning Strategytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne university has just found out about a sport programming contest called ACM ICPC v2.0. This contest doesn't differ much from the well-known ACM ICPC, for example, the participants are not allowed to take part in the finals more than two times. However, there is one notable difference: the teams in the contest should consist of exactly n participants.Having taken part in several ACM ICPC v2.0 finals and having not won any medals, the students and the university governors realized that it's high time they changed something about the preparation process. Specifically, as the first innovation it was decided to change the teams' formation process. Having spent considerable amount of time on studying the statistics of other universities' performance, they managed to receive some interesting information: the dependence between the probability of winning a medal and the number of team members that participated in the finals in the past. More formally, we know nβ+β1 real numbers p0ββ€βp1ββ€β...ββ€βpn, where pi is the probability of getting a medal on the finals if the team has i participants of previous finals, and other nβ-βi participants arrived to the finals for the first time.Despite such useful data, the university governors are unable to determine such team forming tactics that would provide the maximum probability of winning a medal at ACM ICPC v2.0 finals on average (we are supposed to want to provide such result to the far future and we are also supposed to have an endless supply of students). And how about you, can you offer such optimal tactic? At the first stage the university governors want to know the value of maximum average probability.More formally, suppose that the university sends a team to the k-th world finals. The team has ak participants of previous finals (0ββ€βakββ€βn). Since each person can participate in the finals no more than twice, the following condition must be true: . Your task is to choose sequence so that the limit Ξ¨ exists and it's value is maximal:As is an infinite sequence, you should only print the maximum value of the Ξ¨ limit.InputThe first line contains an integer n (3ββ€βnββ€β100), n is the number of team participants. The second line contains nβ+β1 real numbers with no more than 6 digits after decimal point pi (0ββ€βiββ€βn,β0ββ€βpiββ€β1) β the probability of that the team will win a medal if it contains i participants who has already been on the finals. Also the condition piββ€βpiβ+β1 should be fulfilled for all 0ββ€βiββ€βnβ-β1.OutputPrint the only real number β the expected average number of medals won per year if the optimal strategy is used. The result may have absolute or relative error 10β-β6.ExamplesInput30.115590 0.384031 0.443128 0.562356Output0.4286122500Input31 1 1 1Output0.9999999999NoteIn the second test, no matter what participants the team contains, it is doomed to be successful. | Input30.115590 0.384031 0.443128 0.562356 | Output0.4286122500 | 2 seconds | 256 megabytes | ['binary search', 'graphs', 'math', 'shortest paths', '*2400'] |
B. Supersettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA set of points on a plane is called good, if for any two points at least one of the three conditions is true: those two points lie on same horizontal line; those two points lie on same vertical line; the rectangle, with corners in these two points, contains inside or on its borders at least one point of the set, other than these two. We mean here a rectangle with sides parallel to coordinates' axes, the so-called bounding box of the two points.You are given a set consisting of n points on a plane. Find any good superset of the given set whose size would not exceed 2Β·105 points.InputThe first line contains an integer n (1ββ€βnββ€β104) β the number of points in the initial set. Next n lines describe the set's points. Each line contains two integers xi and yi (β-β109ββ€βxi,βyiββ€β109) β a corresponding point's coordinates. It is guaranteed that all the points are different.OutputPrint on the first line the number of points m (nββ€βmββ€β2Β·105) in a good superset, print on next m lines the points. The absolute value of the points' coordinates should not exceed 109. Note that you should not minimize m, it is enough to find any good superset of the given set, whose size does not exceed 2Β·105.All points in the superset should have integer coordinates.ExamplesInput21 12 2Output31 12 21 2 | Input21 12 2 | Output31 12 21 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'divide and conquer', '*2300'] |
A. Dominotime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2βΓβ1. Both halves of each domino contain one digit from 0 to 6. 0-0 0-1 0-2 0-3 0-4 0-5 0-61-1 1-2 1-3 1-4 1-5 1-62-2 2-3 2-4 2-5 2-63-3 3-4 3-5 3-64-4 4-5 4-65-5 5-66-6The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2βΓβ2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size nβΓβm and put there rectangular chips of sizes 1βΓβ2 and 2βΓβ1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round.InputThe first line contains two positive integers n and m (1ββ€βn,βmββ€β30). Each of the following n lines contains m characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct.It is also guaranteed that at least one solution exists.OutputPrint on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next n lines containing m characters each, should contain a field from dots and numbers from 0 to 6 β any of the possible solutions. All dominoes should be different.ExamplesInput8 8.aabbcc..defghi.kdefghijklmnopqj.lmnopq..rstuvw.xrstuvwyxzzAABByOutput10080.001122..001122.3344005533440055.225566..225566.6611334466113344 | Input8 8.aabbcc..defghi.kdefghijklmnopqj.lmnopq..rstuvw.xrstuvwyxzzAABBy | Output10080.001122..001122.3344005533440055.225566..225566.6611334466113344 | 0.5 second | 256 megabytes | ['brute force', 'implementation', '*2400'] |
B. Lucky Numbers (easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.InputThe only line contains a positive integer n (1ββ€βnββ€β109). This number doesn't have leading zeroes.OutputOutput the least super lucky number that is more than or equal to n.Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInput4500Output4747Input47Output47 | Input4500 | Output4747 | 2 seconds | 256 megabytes | ['binary search', 'bitmasks', 'brute force', '*1300'] |
A. Footballtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If there are at least 7 players of some team standing one after another, then the situation is considered dangerous. For example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.InputThe first input line contains a non-empty string consisting of characters "0" and "1", which represents players. The length of the string does not exceed 100 characters. There's at least one player from each team present on the field.OutputPrint "YES" if the situation is dangerous. Otherwise, print "NO".ExamplesInput001001OutputNOInput1000000001OutputYES | Input001001 | OutputNO | 2 seconds | 256 megabytes | ['implementation', 'strings', '*900'] |
E. Lucky Countrytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One night Petya was sleeping. He was dreaming of being the president of some island country. The country is represented by islands connected by two-way roads. Between some islands there is no road way, even through other islands, that's why the country is divided into several regions. More formally, each island belongs to exactly one region, there is a path between any two islands located in the same region; there is no path between any two islands from different regions. A region is lucky if the amount of islands in it is a lucky number.As a real president, Petya first decided to build a presidential palace. Being a lucky numbers' fan, Petya wants to position his palace in one of the lucky regions. However, it is possible that initially the country has no such regions. In this case Petya can build additional roads between different regions, thus joining them. Find the minimum number of roads needed to build to create a lucky region.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β105). They are the number of islands and the number of roads correspondingly. Next m lines contain road descriptions. Each road is defined by the numbers of islands that it connects: that is, by two integers u and v (1ββ€βu,βvββ€βn). Some roads can connect an island with itself; there can be more than one road between a pair of islands. Numbers in each line are separated by exactly one space character.OutputIf there's no solution, output the only number "-1" (without the quotes). Otherwise, output the minimum number of roads r that need to be built to get a lucky region.ExamplesInput4 31 22 31 3Output1Input5 41 23 44 53 5Output-1 | Input4 31 22 31 3 | Output1 | 1 second | 256 megabytes | ['dp', 'dsu', 'graphs', '*2500'] |
D. Horse Racestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya likes horse racing very much. Horses numbered from l to r take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A nearly lucky number is an integer number that has at least two lucky digits the distance between which does not exceed k. Petya learned from some of his mates from Lviv that lucky digits are digits 4 and 7. The distance between the digits is the absolute difference between their positions in the number of a horse. For example, if kβ=β2, then numbers 412395497, 404, 4070400000070004007 are nearly lucky and numbers 4, 4123954997, 4007000040070004007 are not.Petya prepared t intervals [li,βri] and invented number k, common for all of them. Your task is to find how many nearly happy numbers there are in each of these segments. Since the answers can be quite large, output them modulo 1000000007 (109β+β7).InputThe first line contains two integers t and k (1ββ€βt,βkββ€β1000) β the number of segments and the distance between the numbers correspondingly. Next t lines contain pairs of integers li and ri (1ββ€βlββ€βrββ€β101000). All numbers are given without the leading zeroes. Numbers in each line are separated by exactly one space character.OutputOutput t lines. In each line print one integer β the answer for the corresponding segment modulo 1000000007 (109β+β7).ExamplesInput1 21 100Output4Input1 270 77Output2Input2 11 2080 100Output00NoteIn the first sample, the four nearly lucky numbers are 44, 47, 74, 77.In the second sample, only 74 and 77 are in the given segment. | Input1 21 100 | Output4 | 2 seconds | 256 megabytes | ['dp', 'math', '*2500'] |
C. Volleyballtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths.Initially each junction has exactly one taxi standing there. The taxi driver from the i-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than ti meters. Also, the cost of the ride doesn't depend on the distance and is equal to ci bourles. Taxis can't stop in the middle of a road. Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially.At the moment Petya is located on the junction x and the volleyball stadium is on the junction y. Determine the minimum amount of money Petya will need to drive to the stadium.InputThe first line contains two integers n and m (1ββ€βnββ€β1000,β0ββ€βmββ€β1000). They are the number of junctions and roads in the city correspondingly. The junctions are numbered from 1 to n, inclusive. The next line contains two integers x and y (1ββ€βx,βyββ€βn). They are the numbers of the initial and final junctions correspondingly. Next m lines contain the roads' description. Each road is described by a group of three integers ui, vi, wi (1ββ€βui,βviββ€βn,β1ββ€βwiββ€β109) β they are the numbers of the junctions connected by the road and the length of the road, correspondingly. The next n lines contain n pairs of integers ti and ci (1ββ€βti,βciββ€β109), which describe the taxi driver that waits at the i-th junction β the maximum distance he can drive and the drive's cost. The road can't connect the junction with itself, but between a pair of junctions there can be more than one road. All consecutive numbers in each line are separated by exactly one space character.OutputIf taxis can't drive Petya to the destination point, print "-1" (without the quotes). Otherwise, print the drive's minimum cost.Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use cin, cout streams or the %I64d specificator.ExamplesInput4 41 31 2 31 4 12 4 12 3 52 77 21 27 7Output9NoteAn optimal way β ride from the junction 1 to 2 (via junction 4), then from 2 to 3. It costs 7+2=9 bourles. | Input4 41 31 2 31 4 12 4 12 3 52 77 21 27 7 | Output9 | 2 seconds | 256 megabytes | ['shortest paths', '*1900'] |
B. Lucky Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.InputThe only line contains a positive integer n (1ββ€βnββ€β10100000). This number doesn't have leading zeroes.OutputOutput the least super lucky number that is more than or equal to n.ExamplesInput4500Output4747Input47Output47 | Input4500 | Output4747 | 2 seconds | 256 megabytes | ['dp', 'greedy', '*1800'] |
A. Hockeytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1,βs2,β...,βsn. All those strings consist of uppercase and lowercase Latin letters. String w has the length of |w|, its characters are numbered from 1 to |w|.First Petya should find all the occurrences of forbidden substrings in the w string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal.After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position i should be replaced by any other one if for position i in string w there exist pair of indices l,βr (1ββ€βlββ€βiββ€βrββ€β|w|) such that substring w[lΒ ...Β r] is contained in the collection s1,βs2,β...,βsn, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.Letter letter (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the letter occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.InputThe first line contains the only integer n (1ββ€βnββ€β100) β the number of forbidden substrings in the collection. Next n lines contain these substrings. The next line contains string w. All those nβ+β1 lines are non-empty strings consisting of uppercase and lowercase Latin letters whose length does not exceed 100. The last line contains a lowercase letter letter.OutputOutput the only line β Petya's resulting string with the maximum number of letters letter. If there are several answers then output the one that comes first lexicographically.The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if a is a prefix of b, or there exists such an i (1ββ€βiββ€β|a|), that aiβ<βbi, and for any j (1ββ€βjβ<βi) ajβ=βbj. |a| stands for the length of string a.ExamplesInput3bersuckyeluPetrLoveLuckyNumberstOutputPetrLovtTttttNumttttInput4hellopartyabefglghjdhfgjIVanpetrsmatchwinaOutputpetrsmatchwinInput2aCacbaabAcabacOutputabCacba | Input3bersuckyeluPetrLoveLuckyNumberst | OutputPetrLovtTttttNumtttt | 2 seconds | 256 megabytes | ['implementation', 'strings', '*1600'] |
B. Friendstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Igor K. stopped programming and took up math. One late autumn evening he was sitting at a table reading a book and thinking about something. The following statement caught his attention: "Among any six people there are either three pairwise acquainted people or three pairwise unacquainted people"Igor just couldn't get why the required minimum is 6 people. "Well, that's the same for five people, too!" β he kept on repeating in his mind. β "Let's take, say, Max, Ilya, Vova β here, they all know each other! And now let's add Dima and Oleg to Vova β none of them is acquainted with each other! Now, that math is just rubbish!"Igor K. took 5 friends of his and wrote down who of them is friends with whom. Now he wants to check whether it is true for the five people that among them there are either three pairwise acquainted or three pairwise not acquainted people.InputThe first line contains an integer m (0ββ€βmββ€β10), which is the number of relations of acquaintances among the five friends of Igor's.Each of the following m lines contains two integers ai and bi (1ββ€βai,βbiββ€β5;aiββ βbi), where (ai,βbi) is a pair of acquainted people. It is guaranteed that each pair of the acquaintances is described exactly once. The acquaintance relation is symmetrical, i.e. if x is acquainted with y, then y is also acquainted with x.OutputPrint "FAIL", if among those five people there are no either three pairwise acquainted or three pairwise unacquainted people. Otherwise print "WIN".ExamplesInput41 32 31 45 3OutputWINInput51 22 33 44 55 1OutputFAIL | Input41 32 31 45 3 | OutputWIN | 1 second | 256 megabytes | ['graphs', 'implementation', 'math', '*1300'] |
A. Restoring Passwordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had downloaded. Immediately his QIP Infinium said: "invalid login/password".Igor K. entered the ISQ from his additional account and looked at the info of his main one. His name and surname changed to "H1N1" and "Infected" correspondingly, and the "Additional Information" field contained a strange-looking binary code 80 characters in length, consisting of zeroes and ones. "I've been hacked" β thought Igor K. and run the Internet Exploiter browser to quickly type his favourite search engine's address.Soon he learned that it really was a virus that changed ISQ users' passwords. Fortunately, he soon found out that the binary code was actually the encrypted password where each group of 10 characters stood for one decimal digit. Accordingly, the original password consisted of 8 decimal digits.Help Igor K. restore his ISQ account by the encrypted password and encryption specification.InputThe input data contains 11 lines. The first line represents the binary code 80 characters in length. That is the code written in Igor K.'s ISQ account's info. Next 10 lines contain pairwise distinct binary codes 10 characters in length, corresponding to numbers 0, 1, ..., 9.OutputPrint one line containing 8 characters β The password to Igor K.'s ISQ account. It is guaranteed that the solution exists.ExamplesInput010011001001011000000101100010010110010001011001100101101000010110101001011011000100110000010011001001011000000101100010010110010001011001100101101000010110101001011011000101101110Output12345678Input101011011110010000101001000110101011011100101101110110001000110111100101100010001001000010110111100110010001101010110111001011011111010011011011000001111001010110110110000110001000Output30234919 | Input010011001001011000000101100010010110010001011001100101101000010110101001011011000100110000010011001001011000000101100010010110010001011001100101101000010110101001011011000101101110 | Output12345678 | 2 seconds | 256 megabytes | ['implementation', 'strings', '*900'] |
E. Lostborntime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor K. very much likes a multiplayer role playing game WineAge II. Who knows, perhaps, that might be the reason for his poor performance at the university. As any person who plays the game, he is interested in equipping his hero with as good weapon and outfit as possible. One day, as he was reading the game's forum yet again, he discovered a very interesting fact. As it turns out, each weapon in the game is characterised with k different numbers: a1,β...,βak. They are called hit indicators and according to the game developers' plan they are pairwise coprime. The damage that is inflicted during a hit depends not only on the weapon's characteristics, but also on the hero's strength parameter. Thus, if the hero's strength equals n, than the inflicted damage will be calculated as the number of numbers on the segment , that aren't divisible by any hit indicator ai.Recently, having fulfilled another quest, Igor K. found a new Lostborn sword. He wants to know how much damage he will inflict upon his enemies if he uses it.InputThe first line contains two integers: n and k (1ββ€βnββ€β1013, 1ββ€βkββ€β100). They are the indicator of Igor K's hero's strength and the number of hit indicators.The next line contains space-separated k integers ai (1ββ€βaiββ€β1000). They are Lostborn sword's hit indicators. The given k numbers are pairwise coprime.OutputPrint the single number β the damage that will be inflicted by Igor K.'s hero when he uses his new weapon. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.ExamplesInput20 32 3 5Output6Input50 215 8Output41 | Input20 32 3 5 | Output6 | 2 seconds | 256 megabytes | ['dp', 'math', 'number theory', '*2600'] |
D. Flagstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Igor K. was a freshman, his professor strictly urged him, as well as all other freshmen, to solve programming Olympiads. One day a problem called "Flags" from a website called Timmy's Online Judge caught his attention. In the problem one had to find the number of three-colored flags that would satisfy the condition... actually, it doesn't matter. Igor K. quickly found the formula and got the so passionately desired Accepted.However, the professor wasn't very much impressed. He decided that the problem represented on Timmy's Online Judge was very dull and simple: it only had three possible colors of flag stripes and only two limitations. He suggested a complicated task to Igor K. and the fellow failed to solve it. Of course, we won't tell anybody that the professor couldn't solve it as well.And how about you? Can you solve the problem?The flags consist of one or several parallel stripes of similar width. The stripes can be one of the following colors: white, black, red or yellow. You should find the number of different flags with the number of stripes from L to R, if: a flag cannot have adjacent stripes of one color; a flag cannot have adjacent white and yellow stripes; a flag cannot have adjacent red and black stripes; a flag cannot have the combination of black, white and red stripes following one after another in this or reverse order; symmetrical flags (as, for example, a WB and a BW flag, where W and B stand for the white and black colors) are considered the same. InputThe only line contains two integers L and R (1ββ€βLββ€βRββ€β109). They are the lower and upper borders of the number of stripes on the flag.OutputPrint a single number β the number of different flags that would satisfy the condition of the problem and would have from L to R stripes, modulo 1000000007.ExamplesInput3 4Output23Input5 6Output64NoteIn the first test the following flags exist (they are listed in the lexicographical order, the letters B, R, W, Y stand for Black, Red, White and Yellow correspondingly):3 stripes: BWB, BYB, BYR, RWR, RYR, WBW, WBY, WRW, WRY, YBY, YRY (overall 11 flags).4 stripes: BWBW, BWBY, BYBW, BYBY, BYRW, BYRY, RWRW, RWRY, RYBW, RYBY, RYRW, RYRY (12 flags).That's why the answer to test 1 is equal to 11β+β12β=β23. | Input3 4 | Output23 | 2 seconds | 256 megabytes | ['dp', 'math', 'matrices', '*2500'] |
C. Azemblertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the Search Ultimate program that searched for strings in a text failed, Igor K. got to think: "Why on Earth does my program work so slowly?" As he double-checked his code, he said: "My code contains no errors, yet I know how we will improve Search Ultimate!" and took a large book from the shelves. The book read "Azembler. Principally New Approach".Having carefully thumbed through the book, Igor K. realised that, as it turns out, you can multiply the numbers dozens of times faster. "Search Ultimate will be faster than it has ever been!" β the fellow shouted happily and set to work.Let us now clarify what Igor's idea was. The thing is that the code that was generated by a compiler was far from perfect. Standard multiplying does work slower than with the trick the book mentioned.The Azembler language operates with 26 registers (eax, ebx, ..., ezx) and two commands: [x] β returns the value located in the address x. For example, [eax] returns the value that was located in the address, equal to the value in the register eax. lea x, y β assigns to the register x, indicated as the first operand, the second operand's address. Thus, for example, the "lea ebx, [eax]" command will write in the ebx register the content of the eax register: first the [eax] operation will be fulfilled, the result of it will be some value that lies in the address written in eax. But we do not need the value β the next operation will be lea, that will take the [eax] address, i.e., the value in the eax register, and will write it in ebx. On the first thought the second operation seems meaningless, but as it turns out, it is acceptable to write the operation as lea ecx, [eax + ebx],lea ecx, [k*eax]or evenlea ecx, [ebx + k*eax],where k = 1, 2, 4 or 8.As a result, the register ecx will be equal to the numbers eax + ebx, k*eax and ebx + k*eax correspondingly. However, such operation is fulfilled many times, dozens of times faster that the usual multiplying of numbers. And using several such operations, one can very quickly multiply some number by some other one. Of course, instead of eax, ebx and ecx you are allowed to use any registers.For example, let the eax register contain some number that we should multiply by 41. It takes us 2 lines:lea ebx, [eax + 4*eax] // now ebx = 5*eaxlea eax, [eax + 8*ebx] // now eax = eax + 8*ebx = 41*eaxIgor K. got interested in the following question: what is the minimum number of lea operations needed to multiply by the given number n and how to do it? Your task is to help him.Consider that at the initial moment of time eax contains a number that Igor K. was about to multiply by n, and the registers from ebx to ezx contain number 0. At the final moment of time the result can be located in any register.InputThe input data contain the only integer n (1ββ€βnββ€β255), which Igor K. is about to multiply.OutputOn the first line print number p, which represents the minimum number of lea operations, needed to do that. Then print the program consisting of p commands, performing the operations. It is guaranteed that such program exists for any n from 1 to 255.Use precisely the following format of commands (here k is equal to 1, 2, 4 or 8, and x, y and z are any, even coinciding registers):lea x, [y]lea x, [y + z]lea x, [k*y]lea x, [y + k*z]Please note that extra spaces at the end of a command are unacceptable.ExamplesInput41Output2lea ebx, [eax + 4*eax]lea ecx, [eax + 8*ebx]Input2Output1lea ebx, [eax + eax]Input4Output1lea ebx, [4*eax] | Input41 | Output2lea ebx, [eax + 4*eax]lea ecx, [eax + 8*ebx] | 5 seconds | 256 megabytes | ['brute force', 'implementation', '*2500'] |
B. End of Examstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudents love to celebrate their holidays. Especially if the holiday is the day of the end of exams!Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the m friends found n different kinds of milk on the menu, that's why they ordered n bottles β one bottle of each kind. We know that the volume of milk in each bottle equals w.When the bottles were brought in, they decided to pour all the milk evenly among the m cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem β and what is actually the way to do it?Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible!Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.InputThe only input data file contains three integers n, w and m (1ββ€βnββ€β50, 100ββ€βwββ€β1000, 2ββ€βmββ€β50), where n stands for the number of ordered bottles, w stands for the volume of each of them and m stands for the number of friends in the company.OutputPrint on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO".If there is a solution, then print m more lines, where the i-th of them describes the content of the i-th student's cup. The line should consist of one or more pairs that would look like "b v". Each such pair means that v (vβ>β0) units of milk were poured into the i-th cup from bottle b (1ββ€βbββ€βn). All numbers b on each line should be different.If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point.ExamplesInput2 500 3OutputYES1 333.3333332 333.3333332 166.666667 1 166.666667Input4 100 5OutputYES3 20.000000 4 60.0000001 80.0000004 40.000000 2 40.0000003 80.0000002 60.000000 1 20.000000Input4 100 7OutputNOInput5 500 2OutputYES4 250.000000 5 500.000000 2 500.0000003 500.000000 1 500.000000 4 250.000000 | Input2 500 3 | OutputYES1 333.3333332 333.3333332 166.666667 1 166.666667 | 1 second | 256 megabytes | ['greedy', '*1900'] |
A. Framestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThroughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.InputThe only line contains four integers n, m, a, b (1ββ€βn,βmββ€β109, 1ββ€βaββ€βbββ€βn). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.OutputPrint a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.ExamplesInput11 4 3 9Output3Input20 5 2 20Output2NoteThe images below illustrate statement tests.The first test:In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.The second test:In this test we can first select all folders in the first row (2, 3, 4, 5), then β all other ones. | Input11 4 3 9 | Output3 | 2 seconds | 256 megabytes | ['implementation', '*1700'] |
B. Binary Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.Fangy takes some positive integer x and wants to get a number one from it. While x is not equal to 1, Fangy repeats the following action: if x is odd, then he adds 1 to it, otherwise he divides x by 2. Fangy knows that for any positive integer number the process ends in finite time.How many actions should Fangy perform to get a number one from number x?InputThe first line contains a positive integer x in a binary system. It is guaranteed that the first digit of x is different from a zero and the number of its digits does not exceed 106.OutputPrint the required number of actions.ExamplesInput1Output0Input1001001Output12Input101110Output8NoteLet's consider the third sample. Number 101110 is even, which means that we should divide it by 2. After the dividing Fangy gets an odd number 10111 and adds one to it. Number 11000 can be divided by 2 three times in a row and get number 11. All that's left is to increase the number by one (we get 100), and then divide it by 2 two times in a row. As a result, we get 1. | Input1 | Output0 | 1 second | 256 megabytes | ['greedy', '*1300'] |
A. Chipstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.The presenter has m chips. The presenter stands in the middle of the circle and starts giving the chips to the walruses starting from walrus number 1 and moving clockwise. The walrus number i gets i chips. If the presenter can't give the current walrus the required number of chips, then the presenter takes the remaining chips and the process ends. Determine by the given n and m how many chips the presenter will get in the end.InputThe first line contains two integers n and m (1ββ€βnββ€β50, 1ββ€βmββ€β104) β the number of walruses and the number of chips correspondingly.OutputPrint the number of chips the presenter ended up with.ExamplesInput4 11Output0Input17 107Output2Input3 8Output1NoteIn the first sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, four chips to the walrus number 4, then again one chip to the walrus number 1. After that the presenter runs out of chips. He can't give anything to the walrus number 2 and the process finishes.In the third sample the presenter gives one chip to the walrus number 1, two chips to the walrus number 2, three chips to the walrus number 3, then again one chip to the walrus number 1. The presenter has one chip left and he can't give two chips to the walrus number 2, that's why the presenter takes the last chip. | Input4 11 | Output0 | 2 seconds | 256 megabytes | ['implementation', 'math', '*800'] |
E. Igloo Skyscrapertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday the North Pole hosts an Olympiad in a sport called... toy igloo skyscrapers' building!There are n walruses taking part in the contest. Each walrus is given a unique number from 1 to n. After start each walrus begins to build his own igloo skyscraper. Initially, at the moment of time equal to 0, the height of the skyscraper i-th walrus is equal to ai. Each minute the i-th walrus finishes building bi floors.The journalists that are reporting from the spot where the Olympiad is taking place, make q queries to the organizers. Each query is characterized by a group of three numbers li, ri, ti. The organizers respond to each query with a number x, such that:1. Number x lies on the interval from li to ri inclusive (liββ€βxββ€βri).2. The skyscraper of the walrus number x possesses the maximum height among the skyscrapers of all walruses from the interval [li,βri] at the moment of time ti.For each journalists' query print the number of the walrus x that meets the above-given criteria. If there are several possible answers, print any of them.InputThe first line contains numbers n and q (1ββ€βn,βqββ€β105). Next n lines contain pairs of numbers ai, bi (1ββ€βai,βbiββ€β109). Then follow q queries i the following format li, ri, ti, one per each line (1ββ€βliββ€βriββ€βn, 0ββ€βtiββ€β106). All input numbers are integers.OutputFor each journalists' query print the number of the walrus x that meets the criteria, given in the statement. Print one number per line.ExamplesInput5 44 13 56 23 56 51 5 21 3 51 1 01 5 0Output5215Input5 46 15 12 54 36 12 4 13 4 51 4 51 2 0Output3331 | Input5 44 13 56 23 56 51 5 21 3 51 1 01 5 0 | Output5215 | 3 seconds | 256 megabytes | ['data structures', 'geometry', '*2500'] |
D. Grocer's Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYesterday was a fair in a supermarket's grocery section. There were n jars with spices on the fair. Before the event the jars were numbered from 1 to n from the left to the right. After the event the jars were moved and the grocer had to sort them by the increasing of the numbers.The grocer has a special machine at his disposal. The machine can take any 5 or less jars and rearrange them in the way the grocer wants. Note that the jars do not have to stand consecutively. For example, from the permutation 2, 6, 5, 4, 3, 1 one can get permutation 1, 2, 3, 4, 5, 6, if pick the jars on the positions 1, 2, 3, 5 and 6. Which minimum number of such operations is needed to arrange all the jars in the order of their numbers' increasing?InputThe first line contains an integer n (1ββ€βnββ€β105). The second line contains n space-separated integers ai (1ββ€βaiββ€βn) β the i-th number represents the number of a jar that occupies the i-th position. It is guaranteed that all the numbers are distinct.OutputPrint on the first line the least number of operations needed to rearrange all the jars in the order of the numbers' increasing. Then print the description of all actions in the following format.On the first line of the description of one action indicate the number of jars that need to be taken (k), on the second line indicate from which positions the jars need to be taken (b1,βb2,β...,βbk), on the third line indicate the jar's new order (c1,βc2,β...,βck). After the operation is fulfilled the jar from position bi will occupy the position ci. The set (c1,βc2,β...,βck) should be the rearrangement of the set (b1,βb2,β...,βbk).If there are multiple solutions, output any.ExamplesInput63 5 6 1 2 4Output241 3 6 4 3 6 4 1 22 5 5 2 Input149 13 11 3 10 7 12 14 1 5 4 6 8 2Output342 13 8 14 13 8 14 2 56 7 12 5 10 7 12 6 10 5 53 11 4 1 9 11 4 3 9 1 NoteLet's consider the first sample. The jars can be sorted within two actions.During the first action we take the jars from positions 1, 3, 6 and 4 and put them so that the jar that used to occupy the position 1 will occupy the position 3 after the operation is completed. The jar from position 3 will end up in position 6, the jar from position 6 will end up in position 4 and the jar from position 4 will end up in position 1.After the first action the order will look like that: 1, 5, 3, 4, 2, 6. During the second operation the jars in positions 2 and 5 will change places. | Input63 5 6 1 2 4 | Output241 3 6 4 3 6 4 1 22 5 5 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'greedy', '*2600'] |
C. Ski Basetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way.In the constructing process m bidirectional ski roads will be built. The roads are built one after another: first the road number 1 will be built, then the road number 2, and so on. The i-th road connects the junctions with numbers ai and bi.Track is the route with the following properties: The route is closed, that is, it begins and ends in one and the same junction. The route contains at least one road. The route doesn't go on one road more than once, however it can visit any junction any number of times. Let's consider the ski base as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected.Two ski bases are considered different if they consist of different road sets.After building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem.InputThe first line contains two integers n and m (2ββ€βnββ€β105,β1ββ€βmββ€β105). They represent the number of junctions and the number of roads correspondingly. Then on m lines follows the description of the roads in the order in which they were built. Each road is described by a pair of integers ai and bi (1ββ€βai,βbiββ€βn,βaiββ βbi) β the numbers of the connected junctions. There could be more than one road between a pair of junctions.OutputPrint m lines: the i-th line should represent the number of ways to build a ski base after the end of construction of the road number i. The numbers should be printed modulo 1000000009 (109β+β9).ExamplesInput3 41 32 31 21 2Output0013NoteLet us have 3 junctions and 4 roads between the junctions have already been built (as after building all the roads in the sample): 1 and 3, 2 and 3, 2 roads between junctions 1 and 2. The land lot for the construction will look like this: The land lot for the construction will look in the following way: We can choose a subset of roads in three ways: In the first and the second ways you can choose one path, for example, 1 - 2 - 3 - 1. In the first case you can choose one path 1 - 2 - 1. | Input3 41 32 31 21 2 | Output0013 | 2 seconds | 256 megabytes | ['combinatorics', 'dsu', 'graphs', '*2300'] |
B. Queuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (iβ<βj), that aiβ>βaj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.The airport manager asked you to count for each of n walruses in the queue his displeasure.InputThe first line contains an integer n (2ββ€βnββ€β105) β the number of walruses in the queue. The second line contains integers ai (1ββ€βaiββ€β109).Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one.OutputPrint n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus.ExamplesInput610 8 5 3 50 45Output2 1 0 -1 0 -1 Input710 4 6 3 2 8 15Output4 2 1 0 -1 -1 -1 Input510 3 1 10 11Output1 0 -1 -1 -1 | Input610 8 5 3 50 45 | Output2 1 0 -1 0 -1 | 2 seconds | 256 megabytes | ['binary search', 'data structures', '*1500'] |
A. Newspaper Headlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2?InputThe input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1ββ€β|s1|ββ€β104,β1ββ€β|s2|ββ€β106).OutputIf it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2.ExamplesInputabcxyzOutput-1InputabcddabcOutput2 | Inputabcxyz | Output-1 | 2 seconds | 256 megabytes | ['greedy', 'strings', '*1500'] |
B. African Crosswordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn African crossword is a rectangular table nβΓβm in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a letter should only be crossed out if and only if the corresponding column or row contains at least one more letter that is exactly the same. Besides, all such letters are crossed out simultaneously.When all repeated letters have been crossed out, we should write the remaining letters in a string. The letters that occupy a higher position follow before the letters that occupy a lower position. If the letters are located in one row, then the letter to the left goes first. The resulting word is the answer to the problem.You are suggested to solve an African crossword and print the word encrypted there.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β100). Next n lines contain m lowercase Latin letters each. That is the crossword grid.OutputPrint the encrypted word on a single line. It is guaranteed that the answer consists of at least one letter.ExamplesInput3 3cbabcdcbcOutputabcdInput5 5fcofdooedoafaoardcdfeofsfOutputcodeforces | Input3 3cbabcdcbc | Outputabcd | 2 seconds | 256 megabytes | ['implementation', 'strings', '*1100'] |
A. Cablewaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.A cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations (the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.The number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, after each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, the cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top.All students are divided into three groups: r of them like to ascend only in the red cablecars, g of them prefer only the green ones and b of them prefer only the blue ones. A student never gets on a cablecar painted a color that he doesn't like,The first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top.InputThe first line contains three integers r, g and b (0ββ€βr,βg,βbββ€β100). It is guaranteed that rβ+βgβ+βbβ>β0, it means that the group consists of at least one student. OutputPrint a single number β the minimal time the students need for the whole group to ascend to the top of the mountain.ExamplesInput1 3 2Output34Input3 2 1Output33NoteLet's analyze the first sample.At the moment of time 0 a red cablecar comes and one student from the r group get on it and ascends to the top at the moment of time 30.At the moment of time 1 a green cablecar arrives and two students from the g group get on it; they get to the top at the moment of time 31.At the moment of time 2 comes the blue cablecar and two students from the b group get on it. They ascend to the top at the moment of time 32.At the moment of time 3 a red cablecar arrives but the only student who is left doesn't like red and the cablecar leaves empty.At the moment of time 4 a green cablecar arrives and one student from the g group gets on it. He ascends to top at the moment of time 34.Thus, all the students are on the top, overall the ascension took exactly 34 minutes. | Input1 3 2 | Output34 | 2 seconds | 256 megabytes | ['greedy', 'math', '*1000'] |
E. Fire and Icetime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Fire Lord attacked the Frost Kingdom. He has already got to the Ice Fortress, where the Snow Queen dwells. He arranged his army on a segment n in length not far from the city walls. And only the frost magician Solomon can save the Frost Kingdom. The n-long segment is located at a distance equal exactly to 1 from the castle walls. It can be imaginarily divided into unit segments. On some of the unit segments fire demons are located β no more than one demon per position. Each demon is characterised by his strength - by some positive integer. We can regard the fire demons being idle.Initially Solomon is positioned on the fortress wall. He can perform the following actions several times in a row: "L" β Solomon shifts one unit to the left. This movement cannot be performed on the castle wall. "R" β Solomon shifts one unit to the left. This movement cannot be performed if there's no ice block to the right. "A" β If there's nothing to the right of Solomon, then Solomon creates an ice block that immediately freezes to the block that Solomon is currently standing on. If there already is an ice block, then Solomon destroys it. At that the ice blocks to the right of the destroyed one can remain but they are left unsupported. Those ice blocks fall down.Solomon spends exactly a second on each of these actions.As the result of Solomon's actions, ice blocks' segments fall down. When an ice block falls on a fire demon, the block evaporates and the demon's strength is reduced by 1. When the demons' strength is equal to 0, the fire demon vanishes. The picture below shows how it happens. The ice block that falls on the position with no demon, breaks into lots of tiny pieces and vanishes without hurting anybody. Help Solomon destroy all the Fire Lord's army in minimum time.InputThe first line contains an integer n (1ββ€βnββ€β1000). The next line contains n numbers, the i-th of them represents the strength of the fire demon standing of the i-th position, an integer from 1 to 100. If there's no demon on the i-th position, then the i-th number equals to 0. It is guaranteed that the input data have at least one fire demon.OutputPrint a string of minimum length, containing characters "L", "R" and "A" β the succession of actions leading to the required result.If there are several possible answers, print any of them.ExamplesInput31 0 1OutputARARARALLLAInput30 2 0OutputARARALAARALA | Input31 0 1 | OutputARARARALLLA | 0.5 second | 256 megabytes | ['greedy', '*2900'] |
D. Space minestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time in the galaxy of far, far away...Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star.When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon β space mines. Let's describe a space mine's build.Each space mine is shaped like a ball (we'll call it the mine body) of a certain radius r with the center in the point O. Several spikes protrude from the center. Each spike can be represented as a segment, connecting the center of the mine with some point P, such that (transporting long-spiked mines is problematic), where |OP| is the length of the segment connecting O and P. It is convenient to describe the point P by a vector p such that Pβ=βOβ+βp.The Death Star is shaped like a ball with the radius of R (R exceeds any mine's radius). It moves at a constant speed along the v vector at the speed equal to |v|. At the moment the rebels noticed the Star of Death, it was located in the point A.The rebels located n space mines along the Death Star's way. You may regard the mines as being idle. The Death Star does not know about the mines' existence and cannot notice them, which is why it doesn't change the direction of its movement. As soon as the Star of Death touched the mine (its body or one of the spikes), the mine bursts and destroys the Star of Death. A touching is the situation when there is a point in space which belongs both to the mine and to the Death Star. It is considered that Death Star will not be destroyed if it can move infinitely long time without touching the mines.Help the rebels determine whether they will succeed in destroying the Death Star using space mines or not. If they will succeed, determine the moment of time when it will happen (starting from the moment the Death Star was noticed).InputThe first input data line contains 7 integers Ax,βAy,βAz,βvx,βvy,βvz,βR. They are the Death Star's initial position, the direction of its movement, and its radius (β-β10ββ€βvx,βvy,βvzββ€β10, |v|β>β0, 0β<βRββ€β100).The second line contains an integer n, which is the number of mines (1ββ€βnββ€β100). Then follow n data blocks, the i-th of them describes the i-th mine.The first line of each block contains 5 integers Oix,βOiy,βOiz,βri,βmi, which are the coordinates of the mine centre, the radius of its body and the number of spikes (0β<βriβ<β100,β0ββ€βmiββ€β10). Then follow mi lines, describing the spikes of the i-th mine, where the j-th of them describes the i-th spike and contains 3 integers pijx,βpijy,βpijz β the coordinates of the vector where the given spike is directed ().The coordinates of the mines' centers and the center of the Death Star are integers, their absolute value does not exceed 10000. It is guaranteed that Rβ>βri for any 1ββ€βiββ€βn. For any mines iββ βj the following inequality if fulfilled: . Initially the Death Star and the mines do not have common points.OutputIf the rebels will succeed in stopping the Death Star using space mines, print the time from the moment the Death Star was noticed to the blast.If the Death Star will not touch a mine, print "-1" (without quotes).For the answer the absolute or relative error of 10β-β6 is acceptable.ExamplesInput0 0 0 1 0 0 5210 8 0 2 20 -3 02 2 020 0 0 4 32 4 0-4 3 01 -5 0Output10.0000000000Input8 8 4 4 4 2 61-2 -2 -1 3 0Output-1Input30 30 2 1 2 1 2030 0 40 5 11 4 4-10 -40 -5 7 0100 200 95 8 1-10 0 0Output74.6757620881 | Input0 0 0 1 0 0 5210 8 0 2 20 -3 02 2 020 0 0 4 32 4 0-4 3 01 -5 0 | Output10.0000000000 | 2 seconds | 256 megabytes | ['geometry', '*2500'] |
C. Chip Playtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider the following game. We have a rectangular field nβΓβm in size. Some squares of the field contain chips.Each chip has an arrow painted on it. Thus, each chip on the field points in one of the following directions: up, down, left or right.The player may choose a chip and make a move with it.The move is the following sequence of actions. The chosen chip is marked as the current one. After that the player checks whether there are more chips in the same row (or in the same column) with the current one that are pointed by the arrow on the current chip. If there is at least one chip then the closest of them is marked as the new current chip and the former current chip is removed from the field. After that the check is repeated. This process can be repeated several times. If a new chip is not found, then the current chip is removed from the field and the player's move ends.By the end of a move the player receives several points equal to the number of the deleted chips.By the given initial chip arrangement determine the maximum number of points that a player can receive during one move. Also determine the number of such moves.InputThe first line contains two integers n and m (1ββ€βn,βm,βnβΓβmββ€β5000). Then follow n lines containing m characters each β that is the game field description. "." means that this square is empty. "L", "R", "U", "D" mean that this square contains a chip and an arrow on it says left, right, up or down correspondingly.It is guaranteed that a field has at least one chip.OutputPrint two numbers β the maximal number of points a player can get after a move and the number of moves that allow receiving this maximum number of points.ExamplesInput4 4DRLDU.UL.UURRDDLOutput10 1Input3 5.D...RRRLL.U...Output6 2NoteIn the first sample the maximum number of points is earned by the chip in the position (3,β3). You can see its progress at the following picture: All other chips earn fewer points. | Input4 4DRLDU.UL.UURRDDL | Output10 1 | 4 seconds | 256 megabytes | ['brute force', 'data structures', 'implementation', '*2300'] |
B. Widget Librarytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type. Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets β they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change. We shall assume that the widget a is packed in the widget b if there exists a chain of widgets aβ=βc1,βc2,β...,βckβ=βb, kββ₯β2, for which ci is packed directly to ciβ+β1 for any 1ββ€βiβ<βk. In Vasya's library the situation when the widget a is packed in the widget a (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error.Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0. The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox β vertically. The parameter spacing sets the distance between adjacent widgets, and border β a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0βΓβ0, regardless of the options border and spacing. The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data. For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript. InputThe first line contains an integer n β the number of instructions (1ββ€βnββ€β100). Next n lines contain instructions in the language VasyaScript β one instruction per line. There is a list of possible instructions below. "Widget [name]([x],[y])" β create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units. "HBox [name]" β create a new widget [name] of the type HBox. "VBox [name]" β create a new widget [name] of the type VBox. "[name1].pack([name2])" β pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox. "[name].set_border([x])" β set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox. "[name].set_spacing([x])" β set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox. All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them. The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data.All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusiveIt is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget. OutputFor each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator)ExamplesInput12Widget me(50,40)VBox grandpaHBox fathergrandpa.pack(father)father.pack(me)grandpa.set_border(10)grandpa.set_spacing(20)Widget brother(30,60)father.pack(brother)Widget friend(20,60)Widget uncle(100,20)grandpa.pack(uncle)Outputbrother 30 60father 80 60friend 20 60grandpa 120 120me 50 40uncle 100 20Input15Widget pack(10,10)HBox dummyHBox xVBox yy.pack(dummy)y.set_border(5)y.set_spacing(55)dummy.set_border(10)dummy.set_spacing(20)x.set_border(10)x.set_spacing(10)x.pack(pack)x.pack(dummy)x.pack(pack)x.set_border(0)Outputdummy 0 0pack 10 10x 40 10y 10 10NoteIn the first sample the widgets are arranged as follows: | Input12Widget me(50,40)VBox grandpaHBox fathergrandpa.pack(father)father.pack(me)grandpa.set_border(10)grandpa.set_spacing(20)Widget brother(30,60)father.pack(brother)Widget friend(20,60)Widget uncle(100,20)grandpa.pack(uncle) | Outputbrother 30 60father 80 60friend 20 60grandpa 120 120me 50 40uncle 100 20 | 2 seconds | 256 megabytes | ['dp', 'expression parsing', 'graphs', 'implementation', '*2300'] |
A. Robberytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has n cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to n from the left to the right.Unfortunately, Joe didn't switch the last security system off. On the plus side, he knows the way it works.Every minute the security system calculates the total amount of diamonds for each two adjacent cells (for the cells between whose numbers difference equals 1). As a result of this check we get an nβ-β1 sums. If at least one of the sums differs from the corresponding sum received during the previous check, then the security system is triggered.Joe can move the diamonds from one cell to another between the security system's checks. He manages to move them no more than m times between two checks. One of the three following operations is regarded as moving a diamond: moving a diamond from any cell to any other one, moving a diamond from any cell to Joe's pocket, moving a diamond from Joe's pocket to any cell. Initially Joe's pocket is empty, and it can carry an unlimited amount of diamonds. It is considered that before all Joe's actions the system performs at least one check.In the morning the bank employees will come, which is why Joe has to leave the bank before that moment. Joe has only k minutes left before morning, and on each of these k minutes he can perform no more than m operations. All that remains in Joe's pocket, is considered his loot.Calculate the largest amount of diamonds Joe can carry with him. Don't forget that the security system shouldn't be triggered (even after Joe leaves the bank) and Joe should leave before morning.InputThe first line contains integers n, m and k (1ββ€βnββ€β104, 1ββ€βm,βkββ€β109). The next line contains n numbers. The i-th number is equal to the amount of diamonds in the i-th cell β it is an integer from 0 to 105.OutputPrint a single number β the maximum number of diamonds Joe can steal.ExamplesInput2 3 12 3Output0Input3 2 24 1 3Output2NoteIn the second sample Joe can act like this:The diamonds' initial positions are 4 1 3.During the first period of time Joe moves a diamond from the 1-th cell to the 2-th one and a diamond from the 3-th cell to his pocket.By the end of the first period the diamonds' positions are 3 2 2. The check finds no difference and the security system doesn't go off.During the second period Joe moves a diamond from the 3-rd cell to the 2-nd one and puts a diamond from the 1-st cell to his pocket.By the end of the second period the diamonds' positions are 2 3 1. The check finds no difference again and the security system doesn't go off.Now Joe leaves with 2 diamonds in his pocket. | Input2 3 12 3 | Output0 | 1 second | 256 megabytes | ['greedy', '*1800'] |
B. Keyboardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.InputThe first line contains three integers n, m, x (1ββ€βn,βmββ€β30,β1ββ€βxββ€β50).Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol. Then follow the length of the text q (1ββ€βqββ€β5Β·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.OutputIf Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).ExamplesInput2 2 1abcd1AOutput-1Input2 2 1abcd1eOutput-1Input2 2 1abcS5abcBAOutput1Input3 9 4qwertyuioasdfghjklSzxcvbnmS35TheQuIcKbRoWnFOXjummsovertHeLazYDOGOutput2NoteIn the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2. | Input2 2 1abcd1A | Output-1 | 1 second | 256 megabytes | ['implementation', '*1500'] |
A. Chordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya studies music. He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note after the H similar and we will identify them with each other. The distance between the notes along the musical scale is measured in tones: between two consecutive notes there's exactly one semitone, that is, 0.5 tone. The distance is taken from the lowest tone to the uppest one, that is, the distance between C and E is 4 semitones and between E and C is 8 semitonesVasya also knows what a chord is. A chord is an unordered set of no less than three notes. However, for now Vasya only works with triads, that is with the chords that consist of exactly three notes. He can already distinguish between two types of triads β major and minor.Let's define a major triad. Let the triad consist of notes X, Y and Z. If we can order the notes so as the distance along the musical scale between X and Y equals 4 semitones and the distance between Y and Z is 3 semitones, then the triad is major. The distance between X and Z, accordingly, equals 7 semitones.A minor triad is different in that the distance between X and Y should be 3 semitones and between Y and Z β 4 semitones.For example, the triad "C E G" is major: between C and E are 4 semitones, and between E and G are 3 semitones. And the triplet "C# B F" is minor, because if we order the notes as "B C# F", than between B and C# will be 3 semitones, and between C# and F β 4 semitones.Help Vasya classify the triad the teacher has given to him.InputThe only line contains 3 space-separated notes in the above-given notation.OutputPrint "major" if the chord is major, "minor" if it is minor, and "strange" if the teacher gave Vasya some weird chord which is neither major nor minor. Vasya promises you that the answer will always be unambiguous. That is, there are no chords that are both major and minor simultaneously.ExamplesInputC E GOutputmajorInputC# B FOutputminorInputA B HOutputstrange | InputC E G | Outputmajor | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1200'] |
E. Mogohu-Rea Idoltime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA long time ago somewhere in the depths of America existed a powerful tribe governed by the great leader Pinnie-the-Wooh. Once the tribe conquered three Maya cities. Pinnie-the-Wooh grew concerned: there had to be some control over the conquered territories. That's why he appealed to the priests of the supreme god Mogohu-Rea for help.The priests conveyed the god's will to him: to control these three cities he should put an idol to Mogohu-Rea β that will create a religious field over the cities. However, the idol is so powerful that it can easily drive the people around it mad unless it is balanced by exactly three sacrifice altars, placed one in each city. To balance the idol the altars should be placed so that the center of mass of the system of these three points coincided with the idol. When counting the center of mass consider that all the altars have the same mass.Now Pinnie-the-Wooh is thinking where to put the idol. He has a list of hills, that are suitable to put an idol there. Help him to identify on which of them you can put an idol without risking to fry off the brains of the cities' population with the religious field.Each city has a shape of a convex polygon such that no three vertexes lie on a straight line. The cities can intersect. Each altar should be attached to the city through a special ceremony, besides, it must be situated on the city's territory (possibly at the border). Thus, there may be several altars on a city's territory, but exactly one of them will be attached to the city. The altars, the idol and the hills are points on the plane, some of them may coincide.The hills are taken into consideration independently from each other, the altars' location for different hills may also be different.InputFirst follow descriptions of the three cities, divided by empty lines. The descriptions are in the following format:The first line contains an integer n, which represent the number of the polygon's vertexes (3ββ€βnββ€β5Β·104). Next n lines contain two integers xi, yi each, they are the coordinates of the polygon's i-th vertex in the counterclockwise order.After the cities' description follows the integer m (1ββ€βmββ€β105), which represents the number of hills. Next m lines each contain two integers xj, yj, they are the coordinates of the j-th hill.All the coordinates in the input data do not exceed 5Β·108 in the absolute value.OutputFor each hill print on a single line "YES" (without the quotes) or "NO" (without the quotes), depending on whether the three sacrifice altars can be put to balance the idol or not.ExamplesInput30 01 01 148 85 56 48 43-1 -1-3 -1-2 -250 02 17 11 15 3OutputNOYESNOYESNONoteFor the hill at (2,β1) the altars can be placed at the points (1,β0),β(7,β5),β(β-β2,ββ-β2), for the hill at (1,β1) β at the points (0,β0),β(6,β4),β(β-β3,ββ-β1). Many other groups of three points can do the trick. There are no suitable points for other hills. | Input30 01 01 148 85 56 48 43-1 -1-3 -1-2 -250 02 17 11 15 3 | OutputNOYESNOYESNO | 3 seconds | 256 megabytes | ['geometry', '*2600'] |
D. Beautiful Roadtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA long time ago in some country in Asia were civil wars.Each of n cities wanted to seize power. That's why sometimes one city gathered an army and sent it to campaign against another city.Road making was difficult, so the country had few roads, exactly nβ-β1. Also you could reach any city from any other city going on those roads.Even during the war the Oriental people remain spiritually rich and appreciate the beauty of nature. And to keep the memory of this great crusade for the centuries to come, they planted one beautiful tree by the road on which the army spent most time. The Oriental people love nature, that's why if there were several such roads, then one tree was planted by each of them.Recently, when the records of the war were found, it became clear that each city attacked each other one exactly once. There were exactly n(nβ-β1) attacks in total. Everyone has been wondering what road after those wars became the most beautiful, that is, by which road they planted the largest number of beautiful trees.InputThe first line contains an integer n (2ββ€βnββ€β105), which represents the number of cities. Next nβ-β1 lines contain three integers each: the numbers of cities ai,βbi (1ββ€βai,βbiββ€βn), connected by the i-th road and the number of days di the army spends to go on it (1ββ€βdiββ€β109). The lengths of several roads may coincide.OutputPrint on the first line two integers β the number of beautiful trees on the most beautiful road and the number of the most beautiful roads. Print on the second line the list of the most beautiful roads in the sorted order by the numbers' increasing. The roads are numbered from 1 to nβ-β1 in the order in which they are given in the input data.Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use the cout stream (also you may use the %I64d specificator).ExamplesInput22 1 5Output2 11 Input61 2 11 3 53 4 23 5 33 6 4Output16 12 | Input22 1 5 | Output2 11 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'dsu', 'graphs', 'implementation', 'sortings', 'trees', '*2300'] |
C. Interesting Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo best friends Serozha and Gena play a game.Initially there is one pile consisting of n stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of a1β>βa2β>β...β>βakβ>β0 stones. The piles should meet the condition a1β-βa2β=βa2β-βa3β=β...β=βakβ-β1β-βakβ=β1. Naturally, the number of piles k should be no less than two.The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way?InputThe single line contains a single integer n (1ββ€βnββ€β105).OutputIf Serozha wins, print k, which represents the minimal number of piles into which he can split the initial one during the first move in order to win the game.If Gena wins, print "-1" (without the quotes).ExamplesInput3Output2Input6Output-1Input100Output8 | Input3 | Output2 | 2 seconds | 256 megabytes | ['dp', 'games', 'math', '*2000'] |
B. Vasya and Typestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputProgrammer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below carefully and follow it and not the similar rules in real programming languages.There is a very powerful system of pointers on &K* β you can add an asterisk to the right of the existing type X β that will result in new type Xβ*β. That is called pointer-definition operation. Also, there is the operation that does the opposite β to any type of X, which is a pointer, you can add an ampersand β that will result in a type &X, to which refers X. That is called a dereference operation.The &K* language has only two basic data types β void and errtype. Also, the language has operators typedef and typeof. The operator "typedef A B" defines a new data type B, which is equivalent to A. A can have asterisks and ampersands, and B cannot have them. For example, the operator typedef void** ptptvoid will create a new type ptptvoid, that can be used as void**. The operator "typeof A" returns type of A, brought to void, that is, returns the type void**...*, equivalent to it with the necessary number of asterisks (the number can possibly be zero). That is, having defined the ptptvoid type, as shown above, the typeof ptptvoid operator will return void**.An attempt of dereferencing of the void type will lead to an error: to a special data type errtype. For errtype the following equation holds true: errtype*β=β&errtypeβ=βerrtype. An attempt to use the data type that hasn't been defined before that will also lead to the errtype.Using typedef, we can define one type several times. Of all the definitions only the last one is valid. However, all the types that have been defined earlier using this type do not change.Let us also note that the dereference operation has the lower priority that the pointer operation, in other words &Tβ*β is always equal to T.Note, that the operators are executed consecutively one by one. If we have two operators "typedef &void a" and "typedef a* b", then at first a becomes errtype, and after that b becomes errtype* = errtype, but not &void* = void (see sample 2).Vasya does not yet fully understand this powerful technology, that's why he asked you to help him. Write a program that analyzes these operators. InputThe first line contains an integer n (1ββ€βnββ€β100) β the number of operators. Then follow n lines with operators. Each operator is of one of two types: either "typedef A B", or "typeof A". In the first case the B type differs from void and errtype types, and besides, doesn't have any asterisks and ampersands.All the data type names are non-empty lines of no more than 20 lowercase Latin letters. The number of asterisks and ampersands separately in one type in any operator does not exceed 10, however if we bring some types to void with several asterisks, their number may exceed 10.OutputFor every typeof operator print on the single line the answer to that operator β the type that the given operator returned.ExamplesInput5typedef void* ptvtypeof ptvtypedef &&ptv nodetypeof nodetypeof &ptvOutputvoid*errtypevoidInput17typedef void* btypedef b* ctypeof btypeof ctypedef &b btypeof btypeof ctypedef &&b* ctypeof ctypedef &b* ctypeof ctypedef &void btypeof btypedef b******* ctypeof ctypedef &&b* ctypeof cOutputvoid*void**voidvoid**errtypevoiderrtypeerrtypeerrtypeNoteLet's look at the second sample.After the first two queries typedef the b type is equivalent to void*, and c β to void**.The next query typedef redefines b β it is now equal to &b = &void* = void. At that, the c type doesn't change.After that the c type is defined as &&b* = &&void* = &void = errtype. It doesn't influence the b type, that's why the next typedef defines c as &void* = void.Then the b type is again redefined as &void = errtype. Please note that the c type in the next query is defined exactly as errtype******* = errtype, and not &void******* = void******. The same happens in the last typedef. | Input5typedef void* ptvtypeof ptvtypedef &&ptv nodetypeof nodetypeof &ptv | Outputvoid*errtypevoid | 1 second | 256 megabytes | ['implementation', 'strings', '*1800'] |
A. Trainstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time, waits the first train to come and rides on it to the end of the branch to the corresponding girl. However, the trains run with different frequencies: a train goes to Dasha's direction every a minutes, but a train goes to Masha's direction every b minutes. If two trains approach at the same time, Vasya goes toward the direction with the lower frequency of going trains, that is, to the girl, to whose directions the trains go less frequently (see the note to the third sample).We know that the trains begin to go simultaneously before Vasya appears. That is the train schedule is such that there exists a moment of time when the two trains arrive simultaneously.Help Vasya count to which girlfriend he will go more often.InputThe first line contains two integers a and b (aββ βb,β1ββ€βa,βbββ€β106).OutputPrint "Dasha" if Vasya will go to Dasha more frequently, "Masha" if he will go to Masha more frequently, or "Equal" if he will go to both girlfriends with the same frequency.ExamplesInput3 7OutputDashaInput5 3OutputMashaInput2 3OutputEqualNoteLet's take a look at the third sample. Let the trains start to go at the zero moment of time. It is clear that the moments of the trains' arrival will be periodic with period 6. That's why it is enough to show that if Vasya descends to the subway at a moment of time inside the interval (0,β6], he will go to both girls equally often. If he descends to the subway at a moment of time from 0 to 2, he leaves for Dasha on the train that arrives by the second minute.If he descends to the subway at a moment of time from 2 to 3, he leaves for Masha on the train that arrives by the third minute.If he descends to the subway at a moment of time from 3 to 4, he leaves for Dasha on the train that arrives by the fourth minute.If he descends to the subway at a moment of time from 4 to 6, he waits for both trains to arrive by the sixth minute and goes to Masha as trains go less often in Masha's direction.In sum Masha and Dasha get equal time β three minutes for each one, thus, Vasya will go to both girlfriends equally often. | Input3 7 | OutputDasha | 2 seconds | 256 megabytes | ['implementation', 'math', '*1500'] |
E. Long sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence a0,βa1,β... is called a recurrent binary sequence, if each term ai (iβ=β0,β1,β...) is equal to 0 or 1 and there exist coefficients such that anβ=βc1Β·anβ-β1β+βc2Β·anβ-β2β+β...β+βckΒ·anβ-βk (mod 2),β for all nββ₯βk. Assume that not all of ci are zeros.Note that such a sequence can be uniquely recovered from any k-tuple {as,βasβ+β1,β...,βasβ+βkβ-β1} and so it is periodic. Moreover, if a k-tuple contains only zeros, then the sequence contains only zeros, so this case is not very interesting. Otherwise the minimal period of the sequence is not greater than 2kβ-β1, as k-tuple determines next element, and there are 2kβ-β1 non-zero k-tuples. Let us call a sequence long if its minimal period is exactly 2kβ-β1. Your task is to find a long sequence for a given k, if there is any.InputInput contains a single integer k (2ββ€βkββ€β50).OutputIf there is no long sequence for a given k, output "-1" (without quotes). Otherwise the first line of the output should contain k integer numbers: c1,βc2,β...,βck (coefficients). The second line should contain first k elements of the sequence: a0,βa1,β...,βakβ-β1. All of them (elements and coefficients) should be equal to 0 or 1, and at least one ci has to be equal to 1.If there are several solutions, output any.ExamplesInput2Output1 11 0Input3Output0 1 11 1 1Note1. In the first sample: c1β=β1, c2β=β1, so anβ=βanβ-β1β+βanβ-β2 (mod 2). Thus the sequence will be:so its period equals 3β=β22β-β1.2. In the second sample: c1β=β0, c2β=β1, c3β=β1, so anβ=βanβ-β2β+βanβ-β3 (mod 2). Thus our sequence is:and its period equals 7β=β23β-β1.Periods are colored. | Input2 | Output1 11 0 | 2 seconds | 256 megabytes | ['brute force', 'math', 'matrices', '*2700'] |
D. Powerful arraytime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of positive integers a1,βa2,β...,βan is given. Let us consider its arbitrary subarray al,βalβ+β1...,βar, where 1ββ€βlββ€βrββ€βn. For every positive integer s denote by Ks the number of occurrences of s into the subarray. We call the power of the subarray the sum of products KsΒ·KsΒ·s for every positive integer s. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite.You should calculate the power of t given subarrays.InputFirst line contains two integers n and t (1ββ€βn,βtββ€β200000) β the array length and the number of queries correspondingly.Second line contains n positive integers ai (1ββ€βaiββ€β106) β the elements of the array.Next t lines contain two positive integers l, r (1ββ€βlββ€βrββ€βn) each β the indices of the left and the right ends of the corresponding subarray.OutputOutput t lines, the i-th line of the output should contain single positive integer β the power of the i-th query subarray.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d).ExamplesInput3 21 2 11 21 3Output36Input8 31 1 2 2 1 3 1 12 71 62 7Output202020NoteConsider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored): Then K1β=β3, K2β=β2, K3β=β1, so the power is equal to 32Β·1β+β22Β·2β+β12Β·3β=β20. | Input3 21 2 11 21 3 | Output36 | 5 seconds | 256 megabytes | ['data structures', 'implementation', 'math', 'two pointers', '*2200'] |
C. Genetic engineeringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output"Multidimensional spaces are completely out of style these days, unlike genetics problems" β thought physicist Woll and changed his subject of study to bioinformatics. Analysing results of sequencing he faced the following problem concerning DNA sequences. We will further think of a DNA sequence as an arbitrary string of uppercase letters "A", "C", "G" and "T" (of course, this is a simplified interpretation).Let w be a long DNA sequence and s1,βs2,β...,βsm β collection of short DNA sequences. Let us say that the collection filters w iff w can be covered with the sequences from the collection. Certainly, substrings corresponding to the different positions of the string may intersect or even cover each other. More formally: denote by |w| the length of w, let symbols of w be numbered from 1 to |w|. Then for each position i in w there exist pair of indices l,βr (1ββ€βlββ€βiββ€βrββ€β|w|) such that the substring w[lΒ ...Β r] equals one of the elements s1,βs2,β...,βsm of the collection.Woll wants to calculate the number of DNA sequences of a given length filtered by a given collection, but he doesn't know how to deal with it. Help him! Your task is to find the number of different DNA sequences of length n filtered by the collection {si}.Answer may appear very large, so output it modulo 1000000009.InputFirst line contains two integer numbers n and m (1ββ€βnββ€β1000,β1ββ€βmββ€β10) β the length of the string and the number of sequences in the collection correspondently. Next m lines contain the collection sequences si, one per line. Each si is a nonempty string of length not greater than 10. All the strings consist of uppercase letters "A", "C", "G", "T". The collection may contain identical strings.OutputOutput should contain a single integer β the number of strings filtered by the collection modulo 1000000009 (109β+β9).ExamplesInput2 1AOutput1Input6 2CATTACTOutput2NoteIn the first sample, a string has to be filtered by "A". Clearly, there is only one such string: "AA".In the second sample, there exist exactly two different strings satisfying the condition (see the pictures below). | Input2 1A | Output1 | 2 seconds | 256 megabytes | ['dp', 'string suffix structures', 'trees', '*2500'] |
B. Tetris revisitedtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPhysicist Woll likes to play one relaxing game in between his search of the theory of everything.Game interface consists of a rectangular nβΓβm playing field and a dashboard. Initially some cells of the playing field are filled while others are empty. Dashboard contains images of all various connected (we mean connectivity by side) figures of 2, 3, 4 and 5 cells, with all their rotations and reflections. Player can copy any figure from the dashboard and place it anywhere at the still empty cells of the playing field. Of course any figure can be used as many times as needed.Woll's aim is to fill the whole field in such a way that there are no empty cells left, and also... just have some fun.Every initially empty cell should be filled with exactly one cell of some figure. Every figure should be entirely inside the board. In the picture black cells stand for initially filled cells of the field, and one-colour regions represent the figures.InputFirst line contains integers n and m (1ββ€βn,βmββ€β1000) β the height and the width of the field correspondingly. Next n lines contain m symbols each. They represent the field in a natural way: j-th character of the i-th line is "#" if the corresponding cell is filled, and "." if it is empty.OutputIf there is no chance to win the game output the only number "-1" (without the quotes). Otherwise output any filling of the field by the figures in the following format: each figure should be represented by some digit and figures that touch each other by side should be represented by distinct digits. Every initially filled cell should be represented by "#".ExamplesInput2 3...#.#Output000#0#Input3 3.#......#Output5#151155#Input3 3....##.#.Output-1Input1 2##Output##NoteIn the third sample, there is no way to fill a cell with no empty neighbours.In the forth sample, Woll does not have to fill anything, so we should output the field from the input. | Input2 3...#.# | Output000#0# | 1 second | 256 megabytes | ['constructive algorithms', 'graph matchings', 'greedy', 'math', '*2200'] |
A. Reflectiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor each positive integer n consider the integer Ο(n) which is obtained from n by replacing every digit a in the decimal notation of n with the digit (9ββ-ββa). We say that Ο(n) is the reflection of n. For example, reflection of 192 equals 807. Note that leading zeros (if any) should be omitted. So reflection of 9 equals 0, reflection of 91 equals 8.Let us call the weight of the number the product of the number and its reflection. Thus, the weight of the number 10 is equal to 10Β·89β=β890.Your task is to find the maximum weight of the numbers in the given range [l,βr] (boundaries are included).InputInput contains two space-separated integers l and r (1ββ€βlββ€βrββ€β109) β bounds of the range.OutputOutput should contain single integer number: maximum value of the product nΒ·Ο(n), where lββ€βnββ€βr.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).ExamplesInput3 7Output20Input1 1Output8Input8 10Output890NoteIn the third sample weight of 8 equals 8Β·1β=β8, weight of 9 equals 9Β·0β=β0, weight of 10 equals 890.Thus, maximum value of the product is equal to 890. | Input3 7 | Output20 | 2 seconds | 256 megabytes | ['math', '*1600'] |
E. Guard Towerstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a far away kingdom lives a very greedy king. To defend his land, he built n guard towers. Apart from the towers the kingdom has two armies, each headed by a tyrannical and narcissistic general. The generals can't stand each other, specifically, they will never let soldiers of two armies be present in one tower.During defence operations to manage a guard tower a general has to send part of his army to that tower. Each general asks some fee from the king for managing towers. As they live in a really far away kingdom, each general evaluates his fee in the following weird manner: he finds two remotest (the most distant) towers, where the soldiers of his army are situated and asks for the fee equal to the distance. Each tower is represented by a point on the plane with coordinates (x,βy), and the distance between two points with coordinates (x1,βy1) and (x2,βy2) is determined in this kingdom as |x1β-βx2|β+β|y1β-βy2|.The greedy king was not exactly satisfied with such a requirement from the generals, that's why he only agreed to pay one fee for two generals, equal to the maximum of two demanded fees. However, the king is still green with greed, and among all the ways to arrange towers between armies, he wants to find the cheapest one. Each tower should be occupied by soldiers of exactly one army.He hired you for that. You should find the minimum amount of money that will be enough to pay the fees. And as the king is also very scrupulous, you should also count the number of arrangements that will cost the same amount of money. As their number can be quite large, it is enough for the king to know it as a remainder from dividing by 109β+β7.Two arrangements are distinct if the sets of towers occupied by soldiers of the first general are distinct.InputThe first line contains an integer n (2ββ€βnββ€β5000), n is the number of guard towers. Then follow n lines, each of which contains two integers x,βy β the coordinates of the i-th tower (0ββ€βx,βyββ€β5000). No two towers are present at one point.Pretest 6 is one of the maximal tests for this problem.OutputPrint on the first line the smallest possible amount of money that will be enough to pay fees to the generals. Print on the second line the number of arrangements that can be carried out using the smallest possible fee. This number should be calculated modulo 1000000007 (109β+β7).ExamplesInput20 01 1Output02Input40 00 11 01 1Output14Input30 01000 10005000 5000Output20002NoteIn the first example there are only two towers, the distance between which is equal to 2. If we give both towers to one general, then we well have to pay 2 units of money. If each general receives a tower to manage, to fee will be equal to 0. That is the smallest possible fee. As you can easily see, we can obtain it in two ways. | Input20 01 1 | Output02 | 1.5 seconds | 256 megabytes | ['binary search', 'dsu', 'geometry', 'graphs', 'sortings', '*2600'] |
D. Sum of Medianstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn one well-known algorithm of finding the k-th order statistics we should divide all elements into groups of five consecutive elements and find the median of each five. A median is called the middle element of a sorted array (it's the third largest element for a group of five). To increase the algorithm's performance speed on a modern video card, you should be able to find a sum of medians in each five of the array.A sum of medians of a sorted k-element set Sβ=β{a1,βa2,β...,βak}, where a1β<βa2β<βa3β<β...β<βak, will be understood by as The operator stands for taking the remainder, that is stands for the remainder of dividing x by y.To organize exercise testing quickly calculating the sum of medians for a changing set was needed.InputThe first line contains number n (1ββ€βnββ€β105), the number of operations performed.Then each of n lines contains the description of one of the three operations: add xΒ β add the element x to the set; del xΒ β delete the element x from the set; sumΒ β find the sum of medians of the set. For any add x operation it is true that the element x is not included in the set directly before the operation.For any del x operation it is true that the element x is included in the set directly before the operation.All the numbers in the input are positive integers, not exceeding 109.OutputFor each operation sum print on the single line the sum of medians of the current set. If the set is empty, print 0.Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams (also you may use the %I64d specificator).ExamplesInput6add 4add 5add 1add 2add 3sumOutput3Input14add 1add 7add 2add 5sumadd 6add 8add 9add 3add 4add 10sumdel 1sumOutput51113 | Input6add 4add 5add 1add 2add 3sum | Output3 | 3 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'implementation', '*2300'] |
C. Petya and Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths.InputThe first line contains an odd integer n (3ββ€βnβ<β105), which represents the number of tree nodes. Next n lines contain node descriptions. The (iβ+β1)-th line contains two space-separated integers. The first number is the number of parent of the i-st node and the second number is the key lying in the i-th node. The next line contains an integer k (1ββ€βkββ€β105), which represents the number of keys for which you should count the average value of search results containing one mistake. Next k lines contain the actual keys, one key per line.All node keys and all search keys are positive integers, not exceeding 109. All nβ+βk keys are distinct.All nodes are numbered from 1 to n. For the tree root "-1" (without the quote) will be given instead of the parent's node number. It is guaranteed that the correct binary search tree is given. For each node except for the root, it could be determined according to its key whether it is the left child or the right one.OutputPrint k real numbers which are the expectations of answers for the keys specified in the input. The answer should differ from the correct one with the measure of absolute or relative error not exceeding 10β-β9.ExamplesInput7-1 81 41 122 22 63 103 1411Output8.0000000000Input3-1 51 31 76124689Output7.00000000007.00000000007.00000000003.00000000003.00000000003.0000000000NoteIn the first sample the search of key 1 with one error results in two paths in the trees: (1, 2, 5) and (1, 3, 6), in parentheses are listed numbers of nodes from the root to a leaf. The keys in the leaves of those paths are equal to 6 and 10 correspondingly, that's why the answer is equal to 8. | Input7-1 81 41 122 22 63 103 1411 | Output8.0000000000 | 3 seconds | 256 megabytes | ['binary search', 'dfs and similar', 'probabilities', 'sortings', 'trees', '*2200'] |
B. Embassy Queuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn an embassy of a well-known kingdom an electronic queue is organised. Every person who comes to the embassy, needs to make the following three actions: show the ID, pay money to the cashier and be fingerprinted. Besides, the actions should be performed in the given order.For each action several separate windows are singled out: k1 separate windows for the first action (the first type windows), k2 windows for the second one (the second type windows), and k3 for the third one (the third type windows). The service time for one person in any of the first type window equals to t1. Similarly, it takes t2 time to serve a person in any of the second type windows. And it takes t3 to serve one person in any of the third type windows. Thus, the service time depends only on the window type and is independent from the person who is applying for visa.At some moment n people come to the embassy, the i-th person comes at the moment of time ci. The person is registered under some number. After that he sits in the hall and waits for his number to be shown on a special board. Besides the person's number the board shows the number of the window where one should go and the person goes there immediately. Let's consider that the time needed to approach the window is negligible. The table can show information for no more than one person at a time. The electronic queue works so as to immediately start working with the person who has approached the window, as there are no other people in front of the window.The Client Service Quality inspectors noticed that several people spend too much time in the embassy (this is particularly tiresome as the embassy has no mobile phone reception and 3G). It was decided to organise the system so that the largest time a person spends in the embassy were minimum. Help the inspectors organise the queue. Consider that all actions except for being served in at the window, happen instantly.InputThe first line contains three space-separated integers k1, k2, k3 (1ββ€βkiββ€β109), they are the number of windows of the first, second and third type correspondingly.The second line contains three space-separated integers t1, t2, t3 (1ββ€βtiββ€β105), they are the periods of time needed to serve one person in the window of the first, second and third type correspondingly. The third line contains an integer n (1ββ€βnββ€β105), it is the number of people.The fourth line contains n space-separated integers ci (1ββ€βciββ€β109) in the non-decreasing order; ci is the time when the person number i comes to the embassy.OutputPrint the single number, the maximum time a person will spend in the embassy if the queue is organized optimally.Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams (also you may use the %I64d specificator).ExamplesInput1 1 11 1 151 1 1 1 1Output7Input2 1 15 1 151 2 3 3 5Output13NoteIn the first test 5 people come simultaneously at the moment of time equal to 1. There is one window of every type, it takes 1 unit of time to be served at each window. That's why the maximal time a person spends in the embassy is the time needed to be served at the windows (3 units of time) plus the time the last person who comes to the first window waits (4 units of time). Windows in the second test work like this:The first window of the first type: [1,β6) β the first person, [6,β11) β third person, [11,β16) β fifth personThe second window of the first type: [2,β7) β the second person, [7,β12) β the fourth personThe only second type window: [6,β7) β first, [7,β8) β second, [11,β12) β third, [12,β13) β fourth, [16,β17) β fifthThe only third type window: [7,β8) β first, [8,β9) β second, [12,β13) β third, [13,β14) β fourth, [17,β18) β fifthWe can see that it takes most time to serve the fifth person. | Input1 1 11 1 151 1 1 1 1 | Output7 | 2 seconds | 256 megabytes | ['data structures', 'greedy', '*1800'] |
A. Dominotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe all know the problem about the number of ways one can tile a 2βΓβn field by 1βΓβ2 dominoes. You probably remember that it goes down to Fibonacci numbers. We will talk about some other problem below, there you also are going to deal with tiling a rectangular field with dominoes.You are given a 4βΓβn rectangular field, that is the field that contains four lines and n columns. You have to find for it any tiling by 1βΓβ2 dominoes such that each of the nβ-β1 potential vertical cuts along the grid lines intersects at least one domino, splitting it in two. No two dominoes in the sought tiling should overlap, each square of the field should be covered by exactly one domino. It is allowed to rotate the dominoes, that is, you can use 2βΓβ1 as well as 1βΓβ2 dominoes.Write a program that finds an arbitrary sought tiling. InputThe input contains one positive integer n (1ββ€βnββ€β100) β the number of the field's columns.OutputIf there's no solution, print "-1" (without the quotes). Otherwise, print four lines containing n characters each β that's the description of tiling, where each vertical cut intersects at least one domino. You should print the tiling, having painted the field in no more than 26 colors. Each domino should be painted a color. Different dominoes can be painted the same color, but dominoes of the same color should not be side-neighbouring. To indicate colors you should use lowercase Latin letters. Print any of the acceptable ways of tiling.ExamplesInput4Outputyyzzbccdbxxdyyaa | Input4 | Outputyyzzbccdbxxdyyaa | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1300'] |