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. Civilizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrew plays a game called "Civilization". Dima helps him.The game has n cities and m bidirectional roads. The cities are numbered from 1 to n. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities v1,βv2,β...,βvk, that there is a road between any contiguous cities vi and viβ+β1 (1ββ€βiβ<βk). The length of the described path equals to (kβ-β1). We assume that two cities lie in the same region if and only if, there is a path connecting these two cities.During the game events of two types take place: Andrew asks Dima about the length of the longest path in the region where city x lies. Andrew asks Dima to merge the region where city x lies with the region where city y lies. If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them. Dima finds it hard to execute Andrew's queries, so he asks you to help him. Help Dima.InputThe first line contains three integers n, m, q (1ββ€βnββ€β3Β·105; 0ββ€βmβ<βn; 1ββ€βqββ€β3Β·105) β the number of cities, the number of the roads we already have and the number of queries, correspondingly.Each of the following m lines contains two integers, ai and bi (aiββ βbi; 1ββ€βai,βbiββ€βn). These numbers represent the road between cities ai and bi. There can be at most one road between two cities.Each of the following q lines contains one of the two events in the following format: 1 xi. It is the request Andrew gives to Dima to find the length of the maximum path in the region that contains city xi (1ββ€βxiββ€βn). 2 xi yi. It is the request Andrew gives to Dima to merge the region that contains city xi and the region that contains city yi (1ββ€βxi,βyiββ€βn). Note, that xi can be equal to yi. OutputFor each event of the first type print the answer on a separate line.ExamplesInput6 0 62 1 22 3 42 5 62 3 22 5 31 1Output4 | Input6 0 62 1 22 3 42 5 62 3 22 5 31 1 | Output4 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'dsu', 'ternary search', 'trees', '*2100'] |
B. A Lot of Gamestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (iβ+β1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.InputThe first line contains two integers, n and k (1ββ€βnββ€β105; 1ββ€βkββ€β109).Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.OutputIf the player who moves first wins, print "First", otherwise print "Second" (without the quotes).ExamplesInput2 3abOutputFirstInput3 1abcOutputFirstInput1 2abOutputSecond | Input2 3ab | OutputFirst | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'games', 'implementation', 'strings', 'trees', '*1900'] |
A. Boredomtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.InputThe first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105).OutputPrint a single integer β the maximum number of points that Alex can earn.ExamplesInput21 2Output2Input31 2 3Output4Input91 2 1 3 2 2 2 2 3Output10NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Input21 2 | Output2 | 1 second | 256 megabytes | ['dp', '*1500'] |
B. Little Pony and Sort by Shifttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, Twilight Sparkle is interested in how to sort a sequence of integers a1,βa2,β...,βan in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1,βa2,β...,βanβββan,βa1,βa2,β...,βanβ-β1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?InputThe first line contains an integer n (2ββ€βnββ€β105). The second line contains n integer numbers a1,βa2,β...,βan (1ββ€βaiββ€β105).OutputIf it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.ExamplesInput22 1Output1Input31 3 2Output-1Input21 2Output0 | Input22 1 | Output1 | 1 second | 256 megabytes | ['implementation', '*1200'] |
A. Little Pony and Crystal Minetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; nβ>β1) is an nβΓβn matrix with a diamond inscribed into it.You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.InputThe only line contains an integer n (3ββ€βnββ€β101; n is odd). OutputOutput a crystal of size n.ExamplesInput3Output*D*DDD*D*Input5Output**D***DDD*DDDDD*DDD***D**Input7Output***D*****DDD***DDDDD*DDDDDDD*DDDDD***DDD*****D*** | Input3 | Output*D*DDD*D* | 1 second | 256 megabytes | ['implementation', '*800'] |
E. Little Pony and Lord Tirektime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLord Tirek is a centaur and the main antagonist in the season four finale episodes in the series "My Little Pony: Friendship Is Magic". In "Twilight's Kingdom" (Part 1), Tirek escapes from Tartarus and drains magic from ponies to grow stronger. The core skill of Tirek is called Absorb Mana. It takes all mana from a magic creature and gives them to the caster.Now to simplify the problem, assume you have n ponies (numbered from 1 to n). Each pony has three attributes: si : amount of mana that the pony has at time 0; mi : maximum mana that the pony can have; ri : mana regeneration per unit time. Lord Tirek will do m instructions, each of them can be described with three integers: ti,βli,βri. The instruction means that at time ti, Tirek will use Absorb Mana on ponies with numbers from li to ri (both borders inclusive). We'll give you all the m instructions in order, count how much mana Tirek absorbs for each instruction.InputThe first line contains an integer n (1ββ€βnββ€β105) β the number of ponies. Each of the next n lines contains three integers si,βmi,βri (0ββ€βsiββ€βmiββ€β105;Β 0ββ€βriββ€β105), describing a pony. The next line contains an integer m (1ββ€βmββ€β105) β the number of instructions. Each of the next m lines contains three integers ti,βli,βri (0ββ€βtiββ€β109;Β 1ββ€βliββ€βriββ€βn), describing an instruction of Lord Tirek. The instructions are given in strictly increasing order of ti (all ti are distinct).OutputFor each instruction, output a single line which contains a single integer, the total mana absorbed in this instruction.ExamplesInput50 10 10 12 10 20 10 12 10 10 125 1 519 1 5Output2558NoteEvery pony starts with zero mana. For the first instruction, each pony has 5 mana, so you get 25 mana in total and each pony has 0 mana after the first instruction.For the second instruction, pony 3 has 14 mana and other ponies have mana equal to their mi. | Input50 10 10 12 10 20 10 12 10 10 125 1 519 1 5 | Output2558 | 3 seconds | 256 megabytes | ['data structures', '*3100'] |
D. Little Pony and Elements of Harmonytime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Elements of Harmony are six supernatural artifacts representing subjective aspects of harmony. They are arguably the most powerful force in Equestria. The inside of Elements of Harmony can be seen as a complete graph with n vertices labeled from 0 to nβ-β1, where n is a power of two, equal to 2m. The energy in Elements of Harmony is in constant movement. According to the ancient book, the energy of vertex u in time i (ei[u]) equals to: Here b[] is the transformation coefficient β an array of mβ+β1 integers and f(u,βv) is the number of ones in the binary representation of number (uΒ xorΒ v).Given the transformation coefficient and the energy distribution at time 0 (e0[]). Help Twilight Sparkle predict the energy distribution at time t (et[]). The answer can be quite large, so output it modulo p.InputThe first line contains three integers m, t and p (1ββ€βmββ€β20;Β 0ββ€βtββ€β1018;Β 2ββ€βpββ€β109). The following line contains n (nβ=β2m) integers e0[i] (1ββ€βe0[i]ββ€β109;Β 0ββ€βiβ<βn). The next line contains mβ+β1 integers b[i] (0ββ€βb[i]ββ€β109;Β 0ββ€βiββ€βm).OutputOutput n lines, the i-th line must contain a single integer et[i] modulo p.ExamplesInput2 2 100004 1 2 30 1 0Output146614 | Input2 2 100004 1 2 30 1 0 | Output146614 | 6 seconds | 256 megabytes | ['dp', 'matrices', '*3000'] |
C. Little Pony and Summer Sun Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwilight Sparkle learnt that the evil Nightmare Moon would return during the upcoming Summer Sun Celebration after one thousand years of imprisonment on the moon. She tried to warn her mentor Princess Celestia, but the princess ignored her and sent her to Ponyville to check on the preparations for the celebration. Twilight Sparkle wanted to track the path of Nightmare Moon. Unfortunately, she didn't know the exact path. What she knew is the parity of the number of times that each place Nightmare Moon visited. Can you help Twilight Sparkle to restore any path that is consistent with this information?Ponyville can be represented as an undirected graph (vertices are places, edges are roads between places) without self-loops and multi-edges. The path can start and end at any place (also it can be empty). Each place can be visited multiple times. The path must not visit more than 4n places.InputThe first line contains two integers n and m (2ββ€βnββ€β105;Β 0ββ€βmββ€β105) β the number of places and the number of roads in Ponyville. Each of the following m lines contains two integers ui,βvi (1ββ€βui,βviββ€βn;Β uiββ βvi), these integers describe a road between places ui and vi.The next line contains n integers: x1,βx2,β...,βxn (0ββ€βxiββ€β1) β the parity of the number of times that each place must be visited. If xiβ=β0, then the i-th place must be visited even number of times, else it must be visited odd number of times.OutputOutput the number of visited places k in the first line (0ββ€βkββ€β4n). Then output k integers β the numbers of places in the order of path. If xiβ=β0, then the i-th place must appear in the path even number of times, else i-th place must appear in the path odd number of times. Note, that given road system has no self-loops, therefore any two neighbouring places in the path must be distinct.If there is no required path, output -1. If there multiple possible paths, you can output any of them.ExamplesInput3 21 22 31 1 1Output31 2 3Input5 71 21 31 41 53 43 54 50 1 0 1 0Output102 1 3 4 5 4 5 4 3 1 Input2 00 0Output0 | Input3 21 22 31 1 1 | Output31 2 3 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', '*2200'] |
B. Little Pony and Harmony Chesttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPrincess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony. A sequence of positive integers bi is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmony sequence bi which minimizes the following expression:You are given sequence ai, help Princess Twilight to find the key.InputThe first line contains an integer n (1ββ€βnββ€β100) β the number of elements of the sequences a and b. The next line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β30).OutputOutput the key β sequence bi that minimizes the sum described above. If there are multiple optimal sequences, you can output any of them.ExamplesInput51 1 1 1 1Output1 1 1 1 1 Input51 6 4 2 8Output1 5 3 1 8 | Input51 1 1 1 1 | Output1 1 1 1 1 | 4 seconds | 256 megabytes | ['bitmasks', 'brute force', 'dp', '*2000'] |
A. Little Pony and Expected Maximumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times.InputA single line contains two integers m and n (1ββ€βm,βnββ€β105).OutputOutput a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10ββ-β4.ExamplesInput6 1Output3.500000000000Input6 3Output4.958333333333Input2 2Output1.750000000000NoteConsider the third test example. If you've made two tosses: You can get 1 in the first toss, and 2 in the second. Maximum equals to 2. You can get 1 in the first toss, and 1 in the second. Maximum equals to 1. You can get 2 in the first toss, and 1 in the second. Maximum equals to 2. You can get 2 in the first toss, and 2 in the second. Maximum equals to 2. The probability of each outcome is 0.25, that is expectation equals to: You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value | Input6 1 | Output3.500000000000 | 1 second | 256 megabytes | ['probabilities', '*1600'] |
F. Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation of numbers from 1 to n. Determine whether there's a pair of integers a,βb (1ββ€βa,βbββ€βn;Β aββ βb) such that the element (note, that it is usual division, not integer one) is between a and b in this permutation.InputFirst line consists of a single integer n (1ββ€βnββ€β300000) β the size of permutation.Second line contains n integers β the permutation itself.OutputPrint "YES", if such a pair exists, "NO" otherwise (in both cases without quotes, the answer is case insensitive).ExamplesInput41 3 4 2OutputNOInput51 5 2 4 3OutputYESNoteIn the second example 2 is between 1 and 3. Additionally 4 is between 3 and 5. | Input41 3 4 2 | OutputNO | 1 second | 256 megabytes | ['data structures', 'divide and conquer', 'hashing', '*2700'] |
E. Three stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings (s1,βs2,βs3). For each integer l (1ββ€βlββ€βmin(|s1|,β|s2|,β|s3|) you need to find how many triples (i1,βi2,βi3) exist such that three strings sk[ik... ikβ+βlβ-β1] (kβ=β1,β2,β3) are pairwise equal. Print all found numbers modulo 1000000007Β (109β+β7).See notes if you are not sure about some of the denotions used in the statement.InputFirst three lines contain three non-empty input strings. The sum of lengths of all strings is no more than 3Β·105. All strings consist only of lowercase English letters.OutputYou need to output min(|s1|,β|s2|,β|s3|) numbers separated by spaces β answers for the problem modulo 1000000007Β (109β+β7).ExamplesInputabcbccbcOutput3 1 InputabacabaabacabcdOutput11 2 0 0 NoteConsider a string tβ=βt1t2... t|t|, where ti denotes the i-th character of the string, and |t| denotes the length of the string.Then t[i... j] (1ββ€βiββ€βjββ€β|t|) represents the string titiβ+β1... tj (substring of t from position i to position j inclusive). | Inputabcbccbc | Output3 1 | 2 seconds | 256 megabytes | ['data structures', 'dsu', 'string suffix structures', 'strings', '*2400'] |
D. Washer, Dryer, Foldertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have k pieces of laundry, each of which you want to wash, dry and fold. You are at a laundromat that has n1 washing machines, n2 drying machines and n3 folding machines. Each machine can process only one piece of laundry at a time. You can't dry a piece of laundry before it is washed, and you can't fold it before it is dried. Moreover, after a piece of laundry is washed, it needs to be immediately moved into a drying machine, and after it is dried, it needs to be immediately moved into a folding machine.It takes t1 minutes to wash one piece of laundry in a washing machine, t2 minutes to dry it in a drying machine, and t3 minutes to fold it in a folding machine. Find the smallest number of minutes that is enough to wash, dry and fold all the laundry you have.InputThe only line of the input contains seven integers: k,βn1,βn2,βn3,βt1,βt2,βt3 (1ββ€βkββ€β104;Β 1ββ€βn1,βn2,βn3,βt1,βt2,βt3ββ€β1000).OutputPrint one integer β smallest number of minutes to do all your laundry.ExamplesInput1 1 1 1 5 5 5Output15Input8 4 3 2 10 5 2Output32NoteIn the first example there's one instance of each machine, each taking 5 minutes to complete. You have only one piece of laundry, so it takes 15 minutes to process it.In the second example you start washing first two pieces at moment 0. If you start the third piece of laundry immediately, then by the time it is dried, there will be no folding machine available, so you have to wait, and start washing third piece at moment 2. Similarly, you can't start washing next piece until moment 5, since otherwise there will be no dryer available, when it is washed. Start time for each of the eight pieces of laundry is 0,β0,β2,β5,β10,β10,β12 and 15 minutes respectively. The last piece of laundry will be ready after 15β+β10β+β5β+β2β=β32 minutes. | Input1 1 1 1 5 5 5 | Output15 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1900'] |
C. Magic Tricktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but may have duplicates of some cards.The trick itself is performed as follows: first Alex allows you to choose a random card from the deck. You memorize the card and put it back in the deck. Then Alex shuffles the deck, and pulls out a card. If the card matches the one you memorized, the trick is successful.You don't think Alex is a very good magician, and that he just pulls a card randomly from the deck. Determine the probability of the trick being successful if this is the case.InputFirst line of the input consists of two integers n and m (1ββ€βn,βmββ€β1000), separated by space β number of cards in each deck, and number of decks.OutputOn the only line of the output print one floating point number β probability of Alex successfully performing the trick. Relative or absolute error of your answer should not be higher than 10β-β6.ExamplesInput2 2Output0.6666666666666666Input4 4Output0.4000000000000000Input1 2Output1.0000000000000000NoteIn the first sample, with probability Alex will perform the trick with two cards with the same value from two different decks. In this case the trick is guaranteed to succeed.With the remaining probability he took two different cards, and the probability of pulling off the trick is .The resulting probability is | Input2 2 | Output0.6666666666666666 | 1 second | 256 megabytes | ['combinatorics', 'math', 'probabilities', '*2100'] |
B. 4-point polylinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular grid of lattice points from (0,β0) to (n,βm) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.A polyline defined by points p1,βp2,βp3,βp4 consists of the line segments p1βp2,βp2βp3,βp3βp4, and its length is the sum of the lengths of the individual line segments.InputThe only line of the input contains two integers n and m (0ββ€βn,βmββ€β1000). It is guaranteed that grid contains at least 4 different points.OutputPrint 4 lines with two integers per line separated by space β coordinates of points p1,βp2,βp3,βp4 in order which represent the longest possible polyline.Judge program compares your answer and jury's answer with 10β-β6 precision.ExamplesInput1 1Output1 10 01 00 1Input0 10Output0 10 100 00 9 | Input1 1 | Output1 10 01 00 1 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'geometry', 'trees', '*1800'] |
A. Eeveetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are solving the crossword problem K from IPSC 2014. You solved all the clues except for one: who does Eevee evolve into? You are not very into pokemons, but quick googling helped you find out, that Eevee can evolve into eight different pokemons: Vaporeon, Jolteon, Flareon, Espeon, Umbreon, Leafeon, Glaceon, and Sylveon.You know the length of the word in the crossword, and you already know some letters. Designers of the crossword made sure that the answer is unambiguous, so you can assume that exactly one pokemon out of the 8 that Eevee evolves into fits the length and the letters given. Your task is to find it.InputFirst line contains an integer n (6ββ€βnββ€β8) β the length of the string.Next line contains a string consisting of n characters, each of which is either a lower case english letter (indicating a known letter) or a dot character (indicating an empty cell in the crossword).OutputPrint a name of the pokemon that Eevee can evolve into that matches the pattern in the input. Use lower case letters only to print the name (in particular, do not capitalize the first letter).ExamplesInput7j......OutputjolteonInput7...feonOutputleafeonInput7.l.r.o.OutputflareonNoteHere's a set of names in a form you can paste into your solution:["vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"]{"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"} | Input7j...... | Outputjolteon | 1 second | 256 megabytes | ['brute force', 'implementation', 'strings', '*1000'] |
E. Devu and Flowerstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDevu wants to decorate his garden with flowers. He has purchased n boxes, where the i-th box contains fi flowers. All flowers in a single box are of the same color (hence they are indistinguishable). Also, no two boxes have flowers of the same color.Now Devu wants to select exactly s flowers from the boxes to decorate his garden. Devu would like to know, in how many different ways can he select the flowers from each box? Since this number may be very large, he asks you to find the number modulo (109β+β7). Devu considers two ways different if there is at least one box from which different number of flowers are selected in these two ways.InputThe first line of input contains two space-separated integers n and s (1ββ€βnββ€β20, 0ββ€βsββ€β1014).The second line contains n space-separated integers f1,βf2,β... fn (0ββ€βfiββ€β1012).OutputOutput a single integer β the number of ways in which Devu can select the flowers modulo (109β+β7).ExamplesInput2 31 3Output2Input2 42 2Output1Input3 51 3 2Output3NoteSample 1. There are two ways of selecting 3 flowers: {1,β2} and {0,β3}.Sample 2. There is only one way of selecting 4 flowers: {2,β2}.Sample 3. There are three ways of selecting 5 flowers: {1,β2,β2}, {0,β3,β2}, and {1,β3,β1}. | Input2 31 3 | Output2 | 4 seconds | 256 megabytes | ['bitmasks', 'combinatorics', 'number theory', '*2300'] |
D. Count Good Substringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".Given a string, you have to find two values: the number of good substrings of even length; the number of good substrings of odd length. InputThe first line of the input contains a single string of length n (1ββ€βnββ€β105). Each character of the string will be either 'a' or 'b'.OutputPrint two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.ExamplesInputbbOutput1 2InputbaabOutput2 4InputbabbOutput2 5InputbabaaOutput2 7NoteIn example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.DefinitionsA substring s[l,βr] (1ββ€βlββ€βrββ€βn) of string sβ=βs1s2... sn is string slslβ+β1... sr.A string sβ=βs1s2... sn is a palindrome if it is equal to string snsnβ-β1... s1. | Inputbb | Output1 2 | 2 seconds | 256 megabytes | ['math', '*2000'] |
C. Predict Outcome of the Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n games in a football tournament. Three teams are participating in it. Currently k games had already been played. You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each team, instead he thought that absolute difference between number of wins of first and second team will be d1 and that of between second and third team will be d2.You don't want any of team win the tournament, that is each team should have the same number of wins after n games. That's why you want to know: does there exist a valid tournament satisfying the friend's guess such that no team will win this tournament?Note that outcome of a match can not be a draw, it has to be either win or loss.InputThe first line of the input contains a single integer corresponding to number of test cases t (1ββ€βtββ€β105).Each of the next t lines will contain four space-separated integers n,βk,βd1,βd2 (1ββ€βnββ€β1012;Β 0ββ€βkββ€βn;Β 0ββ€βd1,βd2ββ€βk) β data for the current test case.OutputFor each test case, output a single line containing either "yes" if it is possible to have no winner of tournament, or "no" otherwise (without quotes).ExamplesInput53 0 0 03 3 0 06 4 1 06 3 3 03 3 3 2OutputyesyesyesnonoNoteSample 1. There has not been any match up to now (kβ=β0,βd1β=β0,βd2β=β0). If there will be three matches (1-2, 2-3, 3-1) and each team wins once, then at the end each team will have 1 win.Sample 2. You missed all the games (kβ=β3). As d1β=β0 and d2β=β0, and there is a way to play three games with no winner of tournament (described in the previous sample), the answer is "yes".Sample 3. You missed 4 matches, and d1β=β1,βd2β=β0. These four matches can be: 1-2 (win 2), 1-3 (win 3), 1-2 (win 1), 1-3 (win 1). Currently the first team has 2 wins, the second team has 1 win, the third team has 1 win. Two remaining matches can be: 1-2 (win 2), 1-3 (win 3). In the end all the teams have equal number of wins (2 wins). | Input53 0 0 03 3 0 06 4 1 06 3 3 03 3 3 2 | Outputyesyesyesnono | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'math', '*1700'] |
B. Sort the Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.InputThe first line of the input contains an integer n (1ββ€βnββ€β105) β the size of array a.The second line contains n distinct space-separated integers: a[1],βa[2],β...,βa[n] (1ββ€βa[i]ββ€β109).OutputPrint "yes" or "no" (without quotes), depending on the answer.If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them.ExamplesInput33 2 1Outputyes1 3Input42 1 3 4Outputyes1 2Input43 1 2 4OutputnoInput21 2Outputyes1 1NoteSample 1. You can reverse the entire array to get [1,β2,β3], which is sorted.Sample 3. No segment can be reversed such that the array will be sorted.DefinitionsA segment [l,βr] of array a is the sequence a[l],βa[lβ+β1],β...,βa[r].If you have an array a of size n and you reverse its segment [l,βr], the array will become:a[1],βa[2],β...,βa[lβ-β2],βa[lβ-β1],βa[r],βa[rβ-β1],β...,βa[lβ+β1],βa[l],βa[rβ+β1],βa[rβ+β2],β...,βa[nβ-β1],βa[n]. | Input33 2 1 | Outputyes1 3 | 1 second | 256 megabytes | ['implementation', 'sortings', '*1300'] |
A. Game With Stickstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks.An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.In the grid shown below, nβ=β3 and mβ=β3. There are nβ+βmβ=β6 sticks in total (horizontal sticks are shown in red and vertical sticks are shown in green). There are nΒ·mβ=β9 intersection points, numbered from 1 to 9. The rules of the game are very simple. The players move in turns. Akshat won gold, so he makes the first move. During his/her move, a player must choose any remaining intersection point and remove from the grid all sticks which pass through this point. A player will lose the game if he/she cannot make a move (i.e. there are no intersection points remaining on the grid at his/her move).Assume that both players play optimally. Who will win the game?InputThe first line of input contains two space-separated integers, n and m (1ββ€βn,βmββ€β100).OutputPrint a single line containing "Akshat" or "Malvika" (without the quotes), depending on the winner of the game.ExamplesInput2 2OutputMalvikaInput2 3OutputMalvikaInput3 3OutputAkshatNoteExplanation of the first sample:The grid has four intersection points, numbered from 1 to 4. If Akshat chooses intersection point 1, then he will remove two sticks (1β-β2 and 1β-β3). The resulting grid will look like this. Now there is only one remaining intersection point (i.e. 4). Malvika must choose it and remove both remaining sticks. After her move the grid will be empty.In the empty grid, Akshat cannot make any move, hence he will lose.Since all 4 intersection points of the grid are equivalent, Akshat will lose no matter which one he picks. | Input2 2 | OutputMalvika | 1 second | 256 megabytes | ['implementation', '*900'] |
B. Jzzhu and Sequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJzzhu has invented a kind of sequences, they meet the following property:You are given x and y, please calculate fn modulo 1000000007 (109β+β7).InputThe first line contains two integers x and y (|x|,β|y|ββ€β109). The second line contains a single integer n (1ββ€βnββ€β2Β·109).OutputOutput a single integer representing fn modulo 1000000007 (109β+β7).ExamplesInput2 33Output1Input0 -12Output1000000006NoteIn the first sample, f2β=βf1β+βf3, 3β=β2β+βf3, f3β=β1.In the second sample, f2β=ββ-β1; β-β1 modulo (109β+β7) equals (109β+β6). | Input2 33 | Output1 | 1 second | 256 megabytes | ['implementation', 'math', '*1300'] |
A. Jzzhu and Childrentime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies.Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm: Give m candies to the first child of the line. If this child still haven't got enough candies, then the child goes to the end of the line, else the child go home. Repeat the first two steps while the line is not empty. Consider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?InputThe first line contains two integers n,βm (1ββ€βnββ€β100;Β 1ββ€βmββ€β100). The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β100).OutputOutput a single integer, representing the number of the last child.ExamplesInput5 21 3 1 4 2Output4Input6 41 1 2 2 3 3Output6NoteLet's consider the first sample. Firstly child 1 gets 2 candies and go home. Then child 2 gets 2 candies and go to the end of the line. Currently the line looks like [3, 4, 5, 2] (indices of the children in order of the line). Then child 3 gets 2 candies and go home, and then child 4 gets 2 candies and goes to the end of the line. Currently the line looks like [5, 2, 4]. Then child 5 gets 2 candies and goes home. Then child 2 gets two candies and goes home, and finally child 4 gets 2 candies and goes home.Child 4 is the last one who goes home. | Input5 21 3 1 4 2 | Output4 | 1 second | 256 megabytes | ['implementation', '*1000'] |
E. Jzzhu and Squarestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJzzhu has two integers, n and m. He calls an integer point (x,βy) of a plane special if 0ββ€βxββ€βn and 0ββ€βyββ€βm. Jzzhu defines a unit square as a square with corners at points (x,βy), (xβ+β1,βy), (xβ+β1,βyβ+β1), (x,βyβ+β1), where x and y are some integers.Let's look at all the squares (their sides not necessarily parallel to the coordinate axes) with corners at the special points. For each such square Jzzhu paints a dot in every unit square that is fully inside it. After that some unit squares can contain several dots. Now Jzzhu wonders, how many dots he has painted on the plane. Find this number modulo 1000000007 (109β+β7).InputThe first line contains a single integer t (1ββ€βtββ€β105) β the number of tests.Each of the next t lines contains the description of the test: two integers n and m (1ββ€βn,βmββ€β106) β the value of variables for the current test.OutputFor each test output the total number of dots modulo 1000000007 (109β+β7).ExamplesInput41 32 22 53 4Output382658 | Input41 32 22 53 4 | Output382658 | 3 seconds | 256 megabytes | ['dp', 'math', 'number theory', '*2900'] |
D. Jzzhu and Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers.InputThe first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106).OutputOutput a single integer representing the number of required groups modulo 1000000007 (109β+β7).ExamplesInput32 3 3Output0Input40 1 2 3Output10Input65 2 0 5 2 1Output53 | Input32 3 3 | Output0 | 2 seconds | 256 megabytes | ['bitmasks', 'combinatorics', 'dp', '*2400'] |
C. Jzzhu and Applestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater than 1. Of course, each apple can be part of at most one group.Jzzhu wonders how to get the maximum possible number of groups. Can you help him?InputA single integer n (1ββ€βnββ€β105), the number of the apples.OutputThe first line must contain a single integer m, representing the maximum number of groups he can get. Each of the next m lines must contain two integers β the numbers of apples in the current group.If there are several optimal answers you can print any of them.ExamplesInput6Output26 32 4Input9Output39 32 46 8Input2Output0 | Input6 | Output26 32 4 | 1 second | 256 megabytes | ['constructive algorithms', 'number theory', '*2500'] |
B. Jzzhu and Citiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.InputThe first line contains three integers n,βm,βk (2ββ€βnββ€β105;Β 1ββ€βmββ€β3Β·105;Β 1ββ€βkββ€β105).Each of the next m lines contains three integers ui,βvi,βxi (1ββ€βui,βviββ€βn;Β uiββ βvi;Β 1ββ€βxiββ€β109).Each of the next k lines contains two integers si and yi (2ββ€βsiββ€βn;Β 1ββ€βyiββ€β109).It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.OutputOutput a single integer representing the maximum number of the train routes which can be closed.ExamplesInput5 5 31 2 12 3 21 3 33 4 41 5 53 54 55 5Output2Input2 2 31 2 22 1 32 12 22 3Output2 | Input5 5 31 2 12 3 21 3 33 4 41 5 53 54 55 5 | Output2 | 2 seconds | 256 megabytes | ['graphs', 'greedy', 'shortest paths', '*2000'] |
A. Jzzhu and Chocolatetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJzzhu has a big rectangular chocolate bar that consists of nβΓβm unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements: each cut should be straight (horizontal or vertical); each cut should go along edges of unit squares (it is prohibited to divide any unit chocolate square with cut); each cut should go inside the whole chocolate bar, and all cuts must be distinct. The picture below shows a possible way to cut a 5βΓβ6 chocolate for 5 times. Imagine Jzzhu have made k cuts and the big chocolate is splitted into several pieces. Consider the smallest (by area) piece of the chocolate, Jzzhu wants this piece to be as large as possible. What is the maximum possible area of smallest piece he can get with exactly k cuts? The area of a chocolate piece is the number of unit squares in it.InputA single line contains three integers n,βm,βk (1ββ€βn,βmββ€β109;Β 1ββ€βkββ€β2Β·109).OutputOutput a single integer representing the answer. If it is impossible to cut the big chocolate k times, print -1.ExamplesInput3 4 1Output6Input6 4 2Output8Input2 3 4Output-1NoteIn the first sample, Jzzhu can cut the chocolate following the picture below: In the second sample the optimal division looks like this: In the third sample, it's impossible to cut a 2βΓβ3 chocolate 4 times. | Input3 4 1 | Output6 | 1 second | 256 megabytes | ['greedy', 'math', '*1700'] |
E. Divisorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBizon the Champion isn't just friendly, he also is a rigorous coder.Let's define function f(a), where a is a sequence of integers. Function f(a) returns the following sequence: first all divisors of a1 go in the increasing order, then all divisors of a2 go in the increasing order, and so on till the last element of sequence a. For example, f([2,β9,β1])β=β[1,β2,β1,β3,β9,β1].Let's determine the sequence Xi, for integer i (iββ₯β0): X0β=β[X] ([X] is a sequence consisting of a single number X), Xiβ=βf(Xiβ-β1) (iβ>β0). For example, at Xβ=β6 we get X0β=β[6], X1β=β[1,β2,β3,β6], X2β=β[1,β1,β2,β1,β3,β1,β2,β3,β6].Given the numbers X and k, find the sequence Xk. As the answer can be rather large, find only the first 105 elements of this sequence.InputA single line contains two space-separated integers β X (1ββ€βXββ€β1012) and k (0ββ€βkββ€β1018).OutputPrint the elements of the sequence Xk in a single line, separated by a space. If the number of elements exceeds 105, then print only the first 105 elements.ExamplesInput6 1Output1 2 3 6 Input4 2Output1 1 2 1 2 4 Input10 3Output1 1 1 2 1 1 5 1 1 2 1 5 1 2 5 10 | Input6 1 | Output1 2 3 6 | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'implementation', 'number theory', '*2200'] |
D. Multiplication Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBizon the Champion isn't just charming, he also is very smart.While some of us were learning the multiplication table, Bizon the Champion had fun in his own manner. Bizon the Champion painted an nβΓβm multiplication table, where the element on the intersection of the i-th row and j-th column equals iΒ·j (the rows and columns of the table are numbered starting from 1). Then he was asked: what number in the table is the k-th largest number? Bizon the Champion always answered correctly and immediately. Can you repeat his success?Consider the given multiplication table. If you write out all nΒ·m numbers from the table in the non-decreasing order, then the k-th number you write out is called the k-th largest number.InputThe single line contains integers n, m and k (1ββ€βn,βmββ€β5Β·105;Β 1ββ€βkββ€βnΒ·m).OutputPrint the k-th largest number in a nβΓβm multiplication table.ExamplesInput2 2 2Output2Input2 3 4Output3Input1 10 5Output5NoteA 2βΓβ3 multiplication table looks like this:1 2 32 4 6 | Input2 2 2 | Output2 | 1 second | 256 megabytes | ['binary search', 'brute force', '*1800'] |
C. Painting Fencetime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputBizon the Champion isn't just attentive, he also is very hardworking.Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.InputThe first line contains integer n (1ββ€βnββ€β5000) β the number of fence planks. The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109).OutputPrint a single integer β the minimum number of strokes needed to paint the whole fence.ExamplesInput52 2 1 2 1Output3Input22 2Output2Input15Output1NoteIn the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.In the third sample there is only one plank that can be painted using a single vertical stroke. | Input52 2 1 2 1 | Output3 | 1 second | 512 megabytes | ['divide and conquer', 'dp', 'greedy', '*1900'] |
B. Suffix Structurestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team.At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), s and t. You need to transform word s into word t". The task looked simple to the guys because they know the suffix data structures well. Bizon Senior loves suffix automaton. By applying it once to a string, he can remove from this string any single character. Bizon Middle knows suffix array well. By applying it once to a string, he can swap any two characters of this string. The guys do not know anything about the suffix tree, but it can help them do much more. Bizon the Champion wonders whether the "Bizons" can solve the problem. Perhaps, the solution do not require both data structures. Find out whether the guys can solve the problem and if they can, how do they do it? Can they solve it either only with use of suffix automaton or only with use of suffix array or they need both structures? Note that any structure may be used an unlimited number of times, the structures may be used in any order.InputThe first line contains a non-empty word s. The second line contains a non-empty word t. Words s and t are different. Each word consists only of lowercase English letters. Each word contains at most 100 letters.OutputIn the single line print the answer to the problem. Print "need tree" (without the quotes) if word s cannot be transformed into word t even with use of both suffix array and suffix automaton. Print "automaton" (without the quotes) if you need only the suffix automaton to solve the problem. Print "array" (without the quotes) if you need only the suffix array to solve the problem. Print "both" (without the quotes), if you need both data structures to solve the problem.It's guaranteed that if you can solve the problem only with use of suffix array, then it is impossible to solve it only with use of suffix automaton. This is also true for suffix automaton.ExamplesInputautomatontomatOutputautomatonInputarrayararyOutputarrayInputbothhotOutputbothInputneedtreeOutputneed treeNoteIn the third sample you can act like that: first transform "both" into "oth" by removing the first character using the suffix automaton and then make two swaps of the string using the suffix array and get "hot". | Inputautomatontomat | Outputautomaton | 1 second | 256 megabytes | ['implementation', 'strings', '*1400'] |
A. Rewardstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBizon the Champion is called the Champion for a reason. Bizon the Champion has recently got a present β a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups and a3 third prize cups. Besides, he has b1 first prize medals, b2 second prize medals and b3 third prize medals. Naturally, the rewards in the cupboard must look good, that's why Bizon the Champion decided to follow the rules: any shelf cannot contain both cups and medals at the same time; no shelf can contain more than five cups; no shelf can have more than ten medals. Help Bizon the Champion find out if we can put all the rewards so that all the conditions are fulfilled.InputThe first line contains integers a1, a2 and a3 (0ββ€βa1,βa2,βa3ββ€β100). The second line contains integers b1, b2 and b3 (0ββ€βb1,βb2,βb3ββ€β100). The third line contains integer n (1ββ€βnββ€β100).The numbers in the lines are separated by single spaces.OutputPrint "YES" (without the quotes) if all the rewards can be put on the shelves in the described manner. Otherwise, print "NO" (without the quotes).ExamplesInput1 1 11 1 14OutputYESInput1 1 32 3 42OutputYESInput1 0 01 0 01OutputNO | Input1 1 11 1 14 | OutputYES | 1 second | 256 megabytes | ['implementation', '*800'] |
B. DZY Loves Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string sβ=βs1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get? InputThe first line contains a single string sΒ (1ββ€β|s|ββ€β103).The second line contains a single integer kΒ (0ββ€βkββ€β103).The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.OutputPrint a single integer β the largest possible value of the resulting string DZY could get.ExamplesInputabc31 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1Output41NoteIn the test sample DZY can obtain "abcbbc", valueβ=β1Β·1β+β2Β·2β+β3Β·2β+β4Β·2β+β5Β·2β+β6Β·2β=β41. | Inputabc31 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | Output41 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1000'] |
A. DZY Loves Hashtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY has a hash table with p buckets, numbered from 0 to pβ-β1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x)β=βxΒ modΒ p. Operation aΒ modΒ b denotes taking a remainder after division a by b.However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.InputThe first line contains two integers, p and n (2ββ€βp,βnββ€β300). Then n lines follow. The i-th of them contains an integer xi (0ββ€βxiββ€β109).OutputOutput a single integer β the answer to the problem.ExamplesInput10 5021534153Output4Input5 501234Output-1 | Input10 5021534153 | Output4 | 1 second | 256 megabytes | ['implementation', '*800'] |
E. DZY Loves Bridgestime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDZY owns 2m islands near his home, numbered from 1 to 2m. He loves building bridges to connect the islands. Every bridge he builds takes one day's time to walk across.DZY has a strange rule of building the bridges. For every pair of islands u,βvΒ (uββ βv), he has built 2k different bridges connecting them, where (a|b means b is divisible by a). These bridges are bidirectional.Also, DZY has built some bridges connecting his home with the islands. Specifically, there are ai different bridges from his home to the i-th island. These are one-way bridges, so after he leaves his home he will never come back.DZY decides to go to the islands for sightseeing. At first he is at home. He chooses and walks across one of the bridges connecting with his home, and arrives at some island. After that, he will spend t day(s) on the islands. Each day, he can choose to stay and rest, or to walk to another island across the bridge. It is allowed to stay at an island for more than one day. It's also allowed to cross one bridge more than once.Suppose that right after the t-th day DZY stands at the i-th island. Let ans[i] be the number of ways for DZY to reach the i-th island after t-th day. Your task is to calculate ans[i] for each i modulo 1051131.InputTo avoid huge input, we use the following way to generate the array a. You are given the first s elements of array: a1,βa2,β...,βas. All the other elements should be calculated by formula: aiβ=β(101Β·aiβ-βsβ+β10007)Β modΒ 1051131 (sβ<βiββ€β2m).The first line contains three integers m,βt,βs (1ββ€βmββ€β25;Β 1ββ€βtββ€β1018;Β 1ββ€βsββ€βmin(2m,β105)).The second line contains s integers a1,βa2,β...,βasΒ (1ββ€βaiββ€β106).OutputTo avoid huge output, you only need to output xor-sum of all the answers for all i modulo 1051131 (1ββ€βiββ€β2m), i.e. (ans[1]Β modΒ 1051131)Β xorΒ (ans[2]Β modΒ 1051131)Β xor... xorΒ (ans[n]Β modΒ 1051131).ExamplesInput2 1 41 1 1 2Output1Input3 5 6389094 705719 547193 653800 947499 17024Output556970NoteIn the first sample, ansβ=β[6,β7,β6,β6].If he wants to be at island 1 after one day, he has 6 different ways: home β> 1 -(stay)-> 1 home β> 2 β> 1 home β> 3 β> 1 home β> 3 β> 1 (note that there are two different bridges between 1 and 3) home β> 4 β> 1 home β> 4 β> 1 (note that there are two different bridges from home to 4) In the second sample, (a1,βa2,βa3,βa4,βa5,βa6,βa7,βa8)β=β(389094,β705719,β547193,β653800,β947499,β17024,β416654,β861849), ansβ=β[235771,β712729,β433182,β745954,β139255,β935785,β620229,β644335]. | Input2 1 41 1 1 2 | Output1 | 5 seconds | 512 megabytes | ['math', 'matrices', '*3100'] |
D. DZY Loves Gamestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday DZY begins to play an old game. In this game, he is in a big maze with n rooms connected by m corridors (each corridor allows to move in both directions). You can assume that all the rooms are connected with corridors directly or indirectly.DZY has got lost in the maze. Currently he is in the first room and has k lives. He will act like the follows: Firstly he will randomly pick one of the corridors going from his current room. Each outgoing corridor has the same probability to be picked. Then he will go through the corridor and then the process repeats. There are some rooms which have traps in them. The first room definitely has no trap, the n-th room definitely has a trap. Each time DZY enters one of these rooms, he will lost one life. Now, DZY knows that if he enters the n-th room with exactly 2 lives, firstly he will lost one live, but then he will open a bonus round. He wants to know the probability for him to open the bonus round. Please, help him.InputThe first line contains three integers n,βm,βkΒ (2ββ€βnββ€β500;Β 1ββ€βmββ€β105;Β 2ββ€βkββ€β109).The second line contains n integers, each of them is either 0 or 1. If the i-th number is 1, then the i-th room has a trap, otherwise it has not a trap. Please note, that the number of rooms with a trap is no more than 101. It is guaranteed that the first room has no trap, and the n-th room has a trap.Then m lines follows. Each of them contains two integers ui,βviΒ (1ββ€βui,βviββ€βn;Β uiββ βvi), meaning that current corridor connects two rooms ui and vi. It is guaranteed that the corridor system is connected.OutputPrint the only real number β the probability for DZY to open the bonus round. The answer will be considered correct if its relative or absolute error doesn't exceed 10β-β4.ExamplesInput5 5 30 0 1 0 11 22 33 44 51 2Output0.25000000Input3 2 20 1 11 22 3Output-0.00000000Input2 1 30 11 2Output1.00000000 | Input5 5 30 0 1 0 11 22 33 44 51 2 | Output0.25000000 | 2 seconds | 256 megabytes | ['math', 'matrices', 'probabilities', '*2800'] |
C. DZY Loves Fibonacci Numberstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries.InputThe first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a.Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds.OutputFor each query of the second type, print the value of the sum on a single line.ExamplesInput4 41 2 3 41 1 42 1 41 2 42 1 3Output1712NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Input4 41 2 3 41 1 42 1 41 2 42 1 3 | Output1712 | 4 seconds | 256 megabytes | ['data structures', 'math', 'number theory', '*2400'] |
B. DZY Loves Modificationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs we know, DZY loves playing games. One day DZY decided to play with a nβΓβm matrix. To be more precise, he decided to modify the matrix with exactly k operations.Each modification is one of the following: Pick some row of the matrix and decrease each element of the row by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the row before the decreasing. Pick some column of the matrix and decrease each element of the column by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the column before the decreasing. DZY wants to know: what is the largest total value of pleasure he could get after performing exactly k modifications? Please, help him to calculate this value.InputThe first line contains four space-separated integers n,βm,βk and p (1ββ€βn,βmββ€β103;Β 1ββ€βkββ€β106;Β 1ββ€βpββ€β100).Then n lines follow. Each of them contains m integers representing aijΒ (1ββ€βaijββ€β103) β the elements of the current row of the matrix.OutputOutput a single integer β the maximum possible total pleasure value DZY could get.ExamplesInput2 2 2 21 32 4Output11Input2 2 5 21 32 4Output11NoteFor the first sample test, we can modify: column 2, row 2. After that the matrix becomes:1 10 0For the second sample test, we can modify: column 2, row 2, row 1, column 1, column 2. After that the matrix becomes:-3 -3-2 -2 | Input2 2 2 21 32 4 | Output11 | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'greedy', '*2000'] |
A. DZY Loves Sequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY has a sequence a, consisting of n integers.We'll call a sequence ai,βaiβ+β1,β...,βaj (1ββ€βiββ€βjββ€βn) a subsegment of the sequence a. The value (jβ-βiβ+β1) denotes the length of the subsegment.Your task is to find the longest subsegment of a, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.You only need to output the length of the subsegment you find.InputThe first line contains integer nΒ (1ββ€βnββ€β105). The next line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109).OutputIn a single line print the answer to the problem β the maximum length of the required subsegment.ExamplesInput67 2 3 1 5 6Output5NoteYou can choose subsegment a2,βa3,βa4,βa5,βa6 and change its 3rd element (that is a4) to 4. | Input67 2 3 1 5 6 | Output5 | 1 second | 256 megabytes | ['dp', 'implementation', 'two pointers', '*1600'] |
B. DZY Loves Chemistrytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY loves chemistry, and he enjoys mixing chemicals.DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.Find the maximum possible danger after pouring all the chemicals one by one in optimal order.InputThe first line contains two space-separated integers n and m .Each of the next m lines contains two space-separated integers xi and yi (1ββ€βxiβ<βyiββ€βn). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input.Consider all the chemicals numbered from 1 to n in some order.OutputPrint a single integer β the maximum possible danger.ExamplesInput1 0Output1Input2 11 2Output2Input3 21 22 3Output4NoteIn the first sample, there's only one way to pour, and the danger won't increase.In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring). | Input1 0 | Output1 | 1 second | 256 megabytes | ['dfs and similar', 'dsu', 'greedy', '*1400'] |
A. DZY Loves Chessboardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY loves chessboard, and he enjoys playing with it.He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the same color are on two adjacent cells. Two cells are adjacent if and only if they share a common edge.You task is to find any suitable placement of chessmen on the given chessboard.InputThe first line contains two space-separated integers n and m (1ββ€βn,βmββ€β100).Each of the next n lines contains a string of m characters: the j-th character of the i-th string is either "." or "-". A "." means that the corresponding cell (in the i-th row and the j-th column) is good, while a "-" means it is bad.OutputOutput must contain n lines, each line must contain a string of m characters. The j-th character of the i-th string should be either "W", "B" or "-". Character "W" means the chessman on the cell is white, "B" means it is black, "-" means the cell is a bad cell.If multiple answers exist, print any of them. It is guaranteed that at least one answer exists.ExamplesInput1 1.OutputBInput2 2....OutputBWWBInput3 3.-.-----.OutputB-B-----BNoteIn the first sample, DZY puts a single black chessman. Of course putting a white one is also OK.In the second sample, all 4 cells are good. No two same chessmen share an edge in the sample output.In the third sample, no good cells are adjacent. So you can just put 3 chessmen, no matter what their colors are. | Input1 1. | OutputB | 1 second | 256 megabytes | ['dfs and similar', 'implementation', '*1200'] |
E. DZY Loves Plantingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY loves planting, and he enjoys solving tree problems.DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x,βy) (1ββ€βx,βyββ€βn) as the longest edge in the shortest path between nodes x and y. Specially g(z,βz)β=β0 for every z.For every integer sequence p1,βp2,β...,βpn (1ββ€βpiββ€βn), DZY defines f(p) as . DZY wants to find such a sequence p that f(p) has maximum possible value. But there is one more restriction: the element j can appear in p at most xj times.Please, find the maximum possible f(p) under the described restrictions.InputThe first line contains an integer nΒ (1ββ€βnββ€β3000).Each of the next nβ-β1 lines contains three integers ai,βbi,βciΒ (1ββ€βai,βbiββ€βn;Β 1ββ€βciββ€β10000), denoting an edge between ai and bi with length ci. It is guaranteed that these edges form a tree.Each of the next n lines describes an element of sequence x. The j-th line contains an integer xjΒ (1ββ€βxjββ€βn).OutputPrint a single integer representing the answer.ExamplesInput41 2 12 3 23 4 31111Output2Input41 2 12 3 23 4 34444Output3NoteIn the first sample, one of the optimal p is [4,β3,β2,β1]. | Input41 2 12 3 23 4 31111 | Output2 | 3 seconds | 256 megabytes | ['binary search', 'dsu', 'trees', '*2700'] |
D. DZY Loves Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY loves strings, and he enjoys collecting them.In China, many people like to use strings containing their names' initials, for example: xyz, jcvb, dzy, dyh.Once DZY found a lucky string s. A lot of pairs of good friends came to DZY when they heard about the news. The first member of the i-th pair has name ai, the second one has name bi. Each pair wondered if there is a substring of the lucky string containing both of their names. If so, they want to find the one with minimum length, which can give them good luck and make their friendship last forever.Please help DZY for each pair find the minimum length of the substring of s that contains both ai and bi, or point out that such substring doesn't exist.A substring of s is a string slslβ+β1... sr for some integers l,βr (1ββ€βlββ€βrββ€β|s|). The length of such the substring is (rβ-βlβ+β1).A string p contains some another string q if there is a substring of p equal to q.InputThe first line contains a string s (1ββ€β|s|ββ€β50000).The second line contains a non-negative integer q (0ββ€βqββ€β100000) β the number of pairs. Each of the next q lines describes a pair, the line contains two space-separated strings ai and bi (1ββ€β|ai|,β|bi|ββ€β4).It is guaranteed that all the strings only consist of lowercase English letters.OutputFor each pair, print a line containing a single integer β the minimum length of the required substring. If there is no such substring, output -1.ExamplesInputxudyhduxyz3xyz xyzdyh xyzdzy xyzOutput38-1Inputabcabd3a cab abcab dOutput233Inputbaabcabaaa2abca baaaa abaOutput64NoteThe shortest substrings in the first sample are: xyz, dyhduxyz.The shortest substrings in the second sample are: ca, abc and abd.The shortest substrings in the third sample are: baabca and abaa. | Inputxudyhduxyz3xyz xyzdyh xyzdzy xyz | Output38-1 | 3 seconds | 256 megabytes | ['binary search', 'hashing', 'strings', 'two pointers', '*2500'] |
C. DZY Loves Colorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY loves colors, and he enjoys painting.On a colorful day, DZY gets a colorful ribbon, which consists of n units (they are numbered from 1 to n from left to right). The color of the i-th unit of the ribbon is i at first. It is colorful enough, but we still consider that the colorfulness of each unit is 0 at first.DZY loves painting, we know. He takes up a paintbrush with color x and uses it to draw a line on the ribbon. In such a case some contiguous units are painted. Imagine that the color of unit i currently is y. When it is painted by this paintbrush, the color of the unit becomes x, and the colorfulness of the unit increases by |xβ-βy|.DZY wants to perform m operations, each operation can be one of the following: Paint all the units with numbers between l and r (both inclusive) with color x. Ask the sum of colorfulness of the units between l and r (both inclusive). Can you help DZY?InputThe first line contains two space-separated integers n,βmΒ (1ββ€βn,βmββ€β105).Each of the next m lines begins with a integer typeΒ (1ββ€βtypeββ€β2), which represents the type of this operation.If typeβ=β1, there will be 3 more integers l,βr,βxΒ (1ββ€βlββ€βrββ€βn;Β 1ββ€βxββ€β108) in this line, describing an operation 1.If typeβ=β2, there will be 2 more integers l,βrΒ (1ββ€βlββ€βrββ€βn) in this line, describing an operation 2.OutputFor each operation 2, print a line containing the answer β sum of colorfulness.ExamplesInput3 31 1 2 41 2 3 52 1 3Output8Input3 41 1 3 42 1 12 2 22 3 3Output321Input10 61 1 5 31 2 7 91 10 10 111 3 8 121 1 10 32 1 10Output129NoteIn the first sample, the color of each unit is initially [1,β2,β3], and the colorfulness is [0,β0,β0].After the first operation, colors become [4,β4,β3], colorfulness become [3,β2,β0].After the second operation, colors become [4,β5,β5], colorfulness become [3,β3,β2].So the answer to the only operation of type 2 is 8. | Input3 31 1 2 41 2 3 52 1 3 | Output8 | 2 seconds | 256 megabytes | ['data structures', '*2400'] |
B. DZY Loves FFTtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY loves Fast Fourier Transformation, and he enjoys using it.Fast Fourier Transformation is an algorithm used to calculate convolution. Specifically, if a, b and c are sequences with length n, which are indexed from 0 to nβ-β1, andWe can calculate c fast using Fast Fourier Transformation.DZY made a little change on this formula. NowTo make things easier, a is a permutation of integers from 1 to n, and b is a sequence only containing 0 and 1. Given a and b, DZY needs your help to calculate c.Because he is naughty, DZY provides a special way to get a and b. What you need is only three integers n, d, x. After getting them, use the code below to generate a and b.//x is 64-bit variable;function getNextX() { x = (x * 37 + 10007) % 1000000007; return x;}function initAB() { for(i = 0; i < n; i = i + 1){ a[i] = i + 1; } for(i = 0; i < n; i = i + 1){ swap(a[i], a[getNextX() % (i + 1)]); } for(i = 0; i < n; i = i + 1){ if (i < d) b[i] = 1; else b[i] = 0; } for(i = 0; i < n; i = i + 1){ swap(b[i], b[getNextX() % (i + 1)]); }}Operation x % y denotes remainder after division x by y. Function swap(x, y) swaps two values x and y.InputThe only line of input contains three space-separated integers n,βd,βxΒ (1ββ€βdββ€βnββ€β100000;Β 0ββ€βxββ€β1000000006). Because DZY is naughty, x can't be equal to 27777500.OutputOutput n lines, the i-th line should contain an integer ciβ-β1.ExamplesInput3 1 1Output132Input5 4 2Output22455Input5 4 3Output55554NoteIn the first sample, a is [1 3 2], b is [1 0 0], so c0β=βmax(1Β·1)β=β1, c1β=βmax(1Β·0,β3Β·1)β=β3, c2β=βmax(1Β·0,β3Β·0,β2Β·1)β=β2.In the second sample, a is [2 1 4 5 3], b is [1 1 1 0 1].In the third sample, a is [5 2 1 4 3], b is [1 1 1 1 0]. | Input3 1 1 | Output132 | 1 second | 256 megabytes | ['probabilities', '*2300'] |
A. DZY Loves Physicstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. InputThe first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges.The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n.Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.OutputOutput a real number denoting the answer, with an absolute or relative error of at most 10β-β9.ExamplesInput1 01Output0.000000000000000Input2 11 21 2 1Output3.000000000000000Input5 613 56 73 98 171 2 561 3 291 4 422 3 952 4 883 4 63Output2.965517241379311NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Input1 01 | Output0.000000000000000 | 1 second | 256 megabytes | ['greedy', 'math', '*1600'] |
B. Kolya and Tandem Repeattime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string.Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be?See notes for definition of a tandem repeat.InputThe first line contains s (1ββ€β|s|ββ€β200). This string contains only small English letters. The second line contains number k (1ββ€βkββ€β200) β the number of the added characters.OutputPrint a single number β the maximum length of the tandem repeat that could have occurred in the new string.ExamplesInputaaba2Output6Inputaaabbbb2Output6Inputabracadabra10Output20NoteA tandem repeat of length 2n is string s, where for any position i (1ββ€βiββ€βn) the following condition fulfills: siβ=βsiβ+βn.In the first sample Kolya could obtain a string aabaab, in the second β aaabbbbbb, in the third β abracadabrabracadabra. | Inputaaba2 | Output6 | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'strings', '*1500'] |
A. Anton and Letterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.InputThe first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.OutputPrint a single number β the number of distinct letters in Anton's set.ExamplesInput{a, b, c}Output3Input{b, a, b, a}Output2Input{}Output0 | Input{a, b, c} | Output3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', '*800'] |
E. Gena and Second Distancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGena doesn't like geometry, so he asks you to solve this problem for him.A rectangle with sides parallel to coordinate axes contains n dots. Let's consider some point of the plane. Let's count the distances from this point to the given n points. Let's sort these numbers in the non-decreasing order. We'll call the beauty of the point the second element of this array. If there are two mimimum elements in this array, the beaty will be equal to this minimum.Find the maximum beauty of a point inside the given rectangle.InputThe first line contains three integers w,βh,βn (1ββ€βw,βhββ€β106,β2ββ€βnββ€β1000) β the lengths of the rectangle sides and the number of points. Next n lines contain two integers xi,βyi (0ββ€βxiββ€βw,β0ββ€βyiββ€βh) each β the coordinates of a point. It is possible that it will be coincident points.OutputPrint a single number β the maximum beauty of a point with the absolute or relative error of at most 10β-β9.ExamplesInput5 5 40 05 00 55 5Output4.99999999941792340Input5 5 34 02 54 1Output5.65685424744772010NoteThe point which beauty we need to find must have coordinates (x,βy), where 0ββ€βxββ€βw,β0ββ€βyββ€βh. Some of the n points can coincide. | Input5 5 40 05 00 55 5 | Output4.99999999941792340 | 2 seconds | 256 megabytes | ['geometry', '*3100'] |
D. Adam and Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions: There is no vertex that has more than two incident edges painted the same color. For any two vertexes that have incident edges painted the same color (say, c), the path between them consists of the edges of the color c. Not all tree paintings are equally good for Adam. Let's consider the path from some vertex to the root. Let's call the number of distinct colors on this path the cost of the vertex. The cost of the tree's coloring will be the maximum cost among all the vertexes. Help Adam determine the minimum possible cost of painting the tree. Initially, Adam's tree consists of a single vertex that has number one and is the root. In one move Adam adds a new vertex to the already existing one, the new vertex gets the number equal to the minimum positive available integer. After each operation you need to calculate the minimum cost of coloring the resulting tree.InputThe first line contains integer n (1ββ€βnββ€β106) β the number of times a new vertex is added. The second line contains n numbers pi (1ββ€βpiββ€βi) β the numbers of the vertexes to which we add another vertex. OutputPrint n integers β the minimum costs of the tree painting after each addition. ExamplesInput111 1 1 3 4 4 7 3 7 6 6Output1 1 1 1 1 2 2 2 2 2 3 NoteThe figure below shows one of the possible variants to paint a tree from the sample at the last moment. The cost of the vertexes with numbers 11 and 12 equals 3. | Input111 1 1 3 4 4 7 3 7 6 6 | Output1 1 1 1 1 2 2 2 2 2 3 | 2 seconds | 256 megabytes | ['data structures', 'trees', '*2600'] |
C. Artem and Array time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArtem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a,βb) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points. After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.InputThe first line contains a single integer n (1ββ€βnββ€β5Β·105) β the number of elements in the array. The next line contains n integers ai (1ββ€βaiββ€β106) β the values of the array elements.OutputIn a single line print a single integer β the maximum number of points Artem can get.ExamplesInput53 1 5 2 6Output11Input51 2 3 4 5Output6Input51 100 101 100 1Output102 | Input53 1 5 2 6 | Output11 | 2 seconds | 256 megabytes | ['data structures', 'greedy', '*2500'] |
B. Andrey and Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends β the probability that this friend will come up with a problem if Andrey asks him.Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.InputThe first line contains a single integer n (1ββ€βnββ€β100) β the number of Andrey's friends. The second line contains n real numbers pi (0.0ββ€βpiββ€β1.0) β the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point.OutputPrint a single real number β the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10β-β9.ExamplesInput40.1 0.2 0.3 0.8Output0.800000000000Input20.1 0.2Output0.260000000000NoteIn the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one.In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1Β·0.8β+β0.9Β·0.2β=β0.26. | Input40.1 0.2 0.3 0.8 | Output0.800000000000 | 2 seconds | 256 megabytes | ['greedy', 'math', 'probabilities', '*1800'] |
A. Borya and Hanabitime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHave you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has).The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints. A color hint goes like that: a player names some color and points at all the cards of this color. Similarly goes the value hint. A player names some value and points at all the cards that contain the value.Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value.InputThe first line contains integer n (1ββ€βnββ€β100) β the number of Borya's cards. The next line contains the descriptions of n cards. The description of each card consists of exactly two characters. The first character shows the color (overall this position can contain five distinct letters β R, G, B, Y, W). The second character shows the card's value (a digit from 1 to 5). Borya doesn't know exact order of the cards they lie in.OutputPrint a single integer β the minimum number of hints that the other players should make.ExamplesInput2G3 G3Output0Input4G4 R4 R3 B3Output2Input5B1 Y1 W1 G1 R1Output4NoteIn the first sample Borya already knows for each card that it is a green three.In the second sample we can show all fours and all red cards.In the third sample you need to make hints about any four colors. | Input2G3 G3 | Output0 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'implementation', '*1700'] |
E. Valera and Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera is a coder. Recently he wrote a funny program. The pseudo code for this program is given below://input: integers x, k, pa = x;for(step = 1; step <= k; step = step + 1){ rnd = [random integer from 1 to 100]; if(rnd <= p) a = a * 2; else a = a + 1;}s = 0;while(remainder after dividing a by 2 equals 0){ a = a / 2; s = s + 1;}Now Valera wonders: given the values x, k and p, what is the expected value of the resulting number s?InputThe first line of the input contains three integers x,βk,βp (1ββ€βxββ€β109;Β 1ββ€βkββ€β200;Β 0ββ€βpββ€β100).OutputPrint the required expected value. Your answer will be considered correct if the absolute or relative error doesn't exceed 10β-β6.ExamplesInput1 1 50Output1.0000000000000Input5 3 0Output3.0000000000000Input5 3 25Output1.9218750000000NoteIf the concept of expected value is new to you, you can read about it by the link: http://en.wikipedia.org/wiki/Expected_value | Input1 1 50 | Output1.0000000000000 | 2 seconds | 256 megabytes | ['bitmasks', 'dp', 'math', 'probabilities', '*2400'] |
D. Valera and Swapstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation p of length n is a sequence of distinct integers p1,βp2,β...,βpn (1ββ€βpiββ€βn). A permutation is an identity permutation, if for any i the following equation holds piβ=βi. A swap (i,βj) is the operation that swaps elements pi and pj in the permutation. Let's assume that f(p) is the minimum number of swaps that you need to make the permutation p an identity permutation. Valera wonders, how he can transform permutation p into any permutation q, such that f(q)β=βm, using the minimum number of swaps. Help him do that.InputThe first line contains integer n (1ββ€βnββ€β3000) β the length of permutation p. The second line contains n distinct integers p1,βp2,β...,βpn (1ββ€βpiββ€βn) β Valera's initial permutation. The last line contains integer m (0ββ€βmβ<βn).OutputIn the first line, print integer k β the minimum number of swaps.In the second line, print 2k integers x1,βx2,β...,βx2k β the description of the swap sequence. The printed numbers show that you need to consecutively make swaps (x1,βx2), (x3,βx4), ..., (x2kβ-β1,βx2k). If there are multiple sequence swaps of the minimum length, print the lexicographically minimum one.ExamplesInput51 2 3 4 52Output21 2 1 3 Input52 1 4 5 32Output11 2 NoteSequence x1,βx2,β...,βxs is lexicographically smaller than sequence y1,βy2,β...,βys, if there is such integer r (1ββ€βrββ€βs), that x1β=βy1,βx2β=βy2,β...,βxrβ-β1β=βyrβ-β1 and xrβ<βyr. | Input51 2 3 4 52 | Output21 2 1 3 | 1 second | 256 megabytes | ['constructive algorithms', 'dsu', 'graphs', 'implementation', 'math', 'string suffix structures', '*2100'] |
C. Valera and Tubes time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns β starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x,βy).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1,βy1), (x2,βy2), ..., (xr,βyr), that: rββ₯β2; for any integer i (1ββ€βiββ€βrβ-β1) the following equation |xiβ-βxiβ+β1|β+β|yiβ-βyiβ+β1|β=β1 holds; each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled: no pair of tubes has common cells; each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.InputThe first line contains three space-separated integers n,βm,βk (2ββ€βn,βmββ€β300; 2ββ€β2kββ€βnΒ·m) β the number of rows, the number of columns and the number of tubes, correspondingly. OutputPrint k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1,βyi1,βxi2,βyi2,β...,βxiri,βyiri (the sequence of table cells).If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists. ExamplesInput3 3 3Output3 1 1 1 2 1 33 2 1 2 2 2 33 3 1 3 2 3 3Input2 3 1Output6 1 1 1 2 1 3 2 3 2 2 2 1NotePicture for the first sample: Picture for the second sample: | Input3 3 3 | Output3 1 1 1 2 1 33 2 1 2 2 2 33 3 1 3 2 3 3 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'implementation', '*1500'] |
B. Valera and Fruitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day aiβ+β1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?InputThe first line contains two space-separated integers n and v (1ββ€βn,βvββ€β3000) β the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1ββ€βai,βbiββ€β3000) β the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree.OutputPrint a single integer β the maximum number of fruit that Valera can collect. ExamplesInput2 31 52 3Output8Input5 103 202 201 204 205 20Output60NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither. | Input2 31 52 3 | Output8 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1400'] |
A. Valera and Antique Itemstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValera is a collector. Once he wanted to expand his collection with exactly one antique item.Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.InputThe first line contains two space-separated integers n,βv (1ββ€βnββ€β50;Β 104ββ€βvββ€β106) β the number of sellers and the units of money the Valera has.Then n lines follow. The i-th line first contains integer ki (1ββ€βkiββ€β50) the number of items of the i-th seller. Then go ki space-separated integers si1,βsi2,β...,βsiki (104ββ€βsijββ€β106) β the current prices of the items of the i-th seller. OutputIn the first line, print integer p β the number of sellers with who Valera can make a deal.In the second line print p space-separated integers q1,βq2,β...,βqp (1ββ€βqiββ€βn) β the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order. ExamplesInput3 500001 400002 20000 600003 10000 70000 190000Output31 2 3Input3 500001 500003 100000 120000 1100003 120000 110000 120000Output0NoteIn the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller.In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him. | Input3 500001 400002 20000 600003 10000 70000 190000 | Output31 2 3 | 1 second | 256 megabytes | ['implementation', '*1000'] |
D. Berland Federalizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Berland faces federalization requests more and more often. The proponents propose to divide the country into separate states. Moreover, they demand that there is a state which includes exactly k towns.Currently, Berland has n towns, some pairs of them are connected by bilateral roads. Berland has only nβ-β1 roads. You can reach any city from the capital, that is, the road network forms a tree.The Ministry of Roads fears that after the reform those roads that will connect the towns of different states will bring a lot of trouble.Your task is to come up with a plan to divide the country into states such that: each state is connected, i.e. for each state it is possible to get from any town to any other using its roads (that is, the roads that connect the state towns), there is a state that consisted of exactly k cities, the number of roads that connect different states is minimum. InputThe first line contains integers n, k (1ββ€βkββ€βnββ€β400). Then follow nβ-β1 lines, each of them describes a road in Berland. The roads are given as pairs of integers xi,βyi (1ββ€βxi,βyiββ€βn;Β xiββ βyi) β the numbers of towns connected by the road. Assume that the towns are numbered from 1 to n.OutputThe the first line print the required minimum number of "problem" roads t. Then print a sequence of t integers β their indices in the found division. The roads are numbered starting from 1 in the order they follow in the input. If there are multiple possible solutions, print any of them.If the solution shows that there are no "problem" roads at all, print a single integer 0 and either leave the second line empty or do not print it at all.ExamplesInput5 21 22 33 44 5Output12Input5 31 21 31 41 5Output23 4Input1 1Output0 | Input5 21 22 33 44 5 | Output12 | 1 second | 256 megabytes | ['dp', 'trees', '*2200'] |
C. One-Based Arithmetictime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProf. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+β1. Help him to find the least number of digits 1 in such sum.InputThe first line of the input contains integer n (1ββ€βnβ<β1015).OutputPrint expected minimal number of digits 1.ExamplesInput121Output6 | Input121 | Output6 | 0.5 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'divide and conquer', '*1800'] |
B. Balancertime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configuration?InputThe first line contains integer n (1ββ€βnββ€β50000). The second line contains n non-negative numbers that do not exceed 109, the i-th written number is the number of matches in the i-th matchbox. It is guaranteed that the total number of matches is divisible by n.OutputPrint the total minimum number of moves.ExamplesInput61 6 2 5 3 7Output12 | Input61 6 2 5 3 7 | Output12 | 0.5 seconds | 256 megabytes | ['greedy', 'implementation', '*1600'] |
A. Forgotten Episodetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n.Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which episode has Polycaprus forgotten to watch?InputThe first line of the input contains integer n (2ββ€βnββ€β100000)Β β the number of episodes in a season. Assume that the episodes are numbered by integers from 1 to n.The second line contains nβ-β1 integer a1,βa2,β...,βan (1ββ€βaiββ€βn)Β β the numbers of episodes that Polycarpus has watched. All values of ai are distinct.OutputPrint the number of the episode that Polycarpus hasn't watched.ExamplesInput103 8 10 1 7 9 6 5 2Output4 | Input103 8 10 1 7 9 6 5 2 | Output4 | 1 second | 256 megabytes | ['implementation', '*800'] |
E. Devu and Birthday Celebrationtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday is Devu's birthday. For celebrating the occasion, he bought n sweets from the nearby market. He has invited his f friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to each friend. He wants to celebrate it in a unique style, so he would like to ensure following condition for the distribution of sweets. Assume that he has distributed n sweets to his friends such that ith friend is given ai sweets. He wants to make sure that there should not be any positive integer xβ>β1, which divides every ai.Please find the number of ways he can distribute sweets to his friends in the required way. Note that the order of distribution is important, for example [1, 2] and [2, 1] are distinct distributions. As the answer could be very large, output answer modulo 1000000007 (109β+β7).To make the problem more interesting, you are given q queries. Each query contains an n, f pair. For each query please output the required number of ways modulo 1000000007 (109β+β7).InputThe first line contains an integer q representing the number of queries (1ββ€βqββ€β105). Each of the next q lines contains two space space-separated integers n, f (1ββ€βfββ€βnββ€β105).OutputFor each query, output a single integer in a line corresponding to the answer of each query.ExamplesInput56 27 26 36 47 4Output2691020NoteFor first query: nβ=β6,βfβ=β2. Possible partitions are [1, 5] and [5, 1].For second query: nβ=β7,βfβ=β2. Possible partitions are [1, 6] and [2, 5] and [3, 4] and [4, 3] and [5, 3] and [6, 1]. So in total there are 6 possible ways of partitioning. | Input56 27 26 36 47 4 | Output2691020 | 5 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', '*2100'] |
D. Devu and his Brothertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDevu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting. InputThe first line contains two space-separated integers n, m (1ββ€βn,βmββ€β105). The second line will contain n space-separated integers representing content of the array a (1ββ€βaiββ€β109). The third line will contain m space-separated integers representing content of the array b (1ββ€βbiββ€β109).OutputYou need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.ExamplesInput2 22 33 5Output3Input3 21 2 33 4Output4Input3 24 5 61 2Output0NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied. | Input2 22 33 5 | Output3 | 1 second | 256 megabytes | ['binary search', 'sortings', 'ternary search', 'two pointers', '*1700'] |
C. Devu and Partitioning of the Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDevu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous).If it is possible to partition the array, also give any possible way of valid partitioning.InputThe first line will contain three space separated integers n, k, p (1ββ€βkββ€βnββ€β105;Β 0ββ€βpββ€βk). The next line will contain n space-separated distinct integers representing the content of array a: a1,βa2,β...,βan (1ββ€βaiββ€β109).OutputIn the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes).If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum.As there can be multiple partitions, you are allowed to print any valid partition.ExamplesInput5 5 32 6 10 5 9OutputYES1 91 51 101 61 2Input5 5 37 14 2 9 5OutputNOInput5 3 11 2 3 7 5OutputYES3 5 1 31 71 2 | Input5 5 32 6 10 5 9 | OutputYES1 91 51 101 61 2 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', 'number theory', '*1700'] |
B. Devu, the Dumb Guytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDevu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.Please be careful that answer might not fit in 32 bit data type.InputThe first line will contain two space separated integers n, x (1ββ€βn,βxββ€β105). The next line will contain n space separated integers: c1,βc2,β...,βcn (1ββ€βciββ€β105).OutputOutput a single integer representing the answer to the problem.ExamplesInput2 34 1Output11Input4 25 1 2 1Output10Input3 31 1 1Output6NoteLook at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2βΓβ1β=β2 hours. Hence you will need to spend 12β+β2β=β14 hours.Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3βΓβ1β=β3 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2βΓβ4β=β8 hours. Hence you will need to spend 11 hours.So overall, minimum of both the cases is 11 hours.Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours. | Input2 34 1 | Output11 | 1 second | 256 megabytes | ['implementation', 'sortings', '*1200'] |
A. Devu, the Singer and Churu, the Jokertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDevu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited.Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song will take ti minutes exactly. The Comedian, Churu will crack jokes. All his jokes are of 5 minutes exactly.People have mainly come to listen Devu. But you know that he needs rest of 10 minutes after each song. On the other hand, Churu being a very active person, doesn't need any rest.You as one of the organizers should make an optimal sΡhedule for the event. For some reasons you must follow the conditions: The duration of the event must be no more than d minutes; Devu must complete all his songs; With satisfying the two previous conditions the number of jokes cracked by Churu should be as many as possible. If it is not possible to find a way to conduct all the songs of the Devu, output -1. Otherwise find out maximum number of jokes that Churu can crack in the grand event.InputThe first line contains two space separated integers n, d (1ββ€βnββ€β100;Β 1ββ€βdββ€β10000). The second line contains n space-separated integers: t1,βt2,β...,βtn (1ββ€βtiββ€β100).OutputIf there is no way to conduct all the songs of Devu, output -1. Otherwise output the maximum number of jokes that Churu can crack in the grand event.ExamplesInput3 302 2 1Output5Input3 202 1 1Output-1NoteConsider the first example. The duration of the event is 30 minutes. There could be maximum 5 jokes in the following way: First Churu cracks a joke in 5 minutes. Then Devu performs the first song for 2 minutes. Then Churu cracks 2 jokes in 10 minutes. Now Devu performs second song for 2 minutes. Then Churu cracks 2 jokes in 10 minutes. Now finally Devu will perform his last song in 1 minutes. Total time spent is 5β+β2β+β10β+β2β+β10β+β1β=β30 minutes.Consider the second example. There is no way of organizing Devu's all songs. Hence the answer is -1. | Input3 302 2 1 | Output5 | 1 second | 256 megabytes | ['greedy', 'implementation', '*900'] |
E. The Child and Binary Treetime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOur child likes computer science very much, especially he likes binary trees.Consider the sequence of n distinct positive integers: c1,βc2,β...,βcn. The child calls a vertex-weighted rooted binary tree good if and only if for every vertex v, the weight of v is in the set {c1,βc2,β...,βcn}. Also our child thinks that the weight of a vertex-weighted tree is the sum of all vertices' weights.Given an integer m, can you for all s (1ββ€βsββ€βm) calculate the number of good vertex-weighted rooted binary trees with weight s? Please, check the samples for better understanding what trees are considered different.We only want to know the answer modulo 998244353 (7βΓβ17βΓβ223β+β1, a prime number).InputThe first line contains two integers n,βm (1ββ€βnββ€β105;Β 1ββ€βmββ€β105). The second line contains n space-separated pairwise distinct integers c1,βc2,β...,βcn. (1ββ€βciββ€β105).OutputPrint m lines, each line containing a single integer. The i-th line must contain the number of good vertex-weighted rooted binary trees whose weight exactly equal to i. Print the answers modulo 998244353 (7βΓβ17βΓβ223β+β1, a prime number).ExamplesInput2 31 2Output139Input3 109 4 3Output00110242615Input5 1013 10 6 4 15Output0001010205NoteIn the first example, there are 9 good vertex-weighted rooted binary trees whose weight exactly equal to 3: | Input2 31 2 | Output139 | 7 seconds | 256 megabytes | ['combinatorics', 'divide and conquer', 'fft', 'number theory', '*3100'] |
D. The Child and Sequencetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array a[1],βa[2],β...,βa[n]. Then he should perform a sequence of m operations. An operation can be one of the following: Print operation l,βr. Picks should write down the value of . Modulo operation l,βr,βx. Picks should perform assignment a[i]β=βa[i]Β modΒ x for each i (lββ€βiββ€βr). Set operation k,βx. Picks should set the value of a[k] to x (in other words perform an assignment a[k]β=βx). Can you help Picks to perform the whole sequence of operations?InputThe first line of input contains two integer: n,βm (1ββ€βn,βmββ€β105). The second line contains n integers, separated by space: a[1],βa[2],β...,βa[n]Β (1ββ€βa[i]ββ€β109) β initial value of array elements.Each of the next m lines begins with a number type . If typeβ=β1, there will be two integers more in the line: l,βrΒ (1ββ€βlββ€βrββ€βn), which correspond the operation 1. If typeβ=β2, there will be three integers more in the line: l,βr,βxΒ (1ββ€βlββ€βrββ€βn;Β 1ββ€βxββ€β109), which correspond the operation 2. If typeβ=β3, there will be two integers more in the line: k,βxΒ (1ββ€βkββ€βn;Β 1ββ€βxββ€β109), which correspond the operation 3. OutputFor each operation 1, please print a line containing the answer. Notice that the answer may exceed the 32-bit integer.ExamplesInput5 51 2 3 4 52 3 5 43 3 51 2 52 1 3 31 1 3Output85Input10 106 9 6 7 6 1 10 10 9 51 3 92 7 10 92 5 10 81 4 73 3 72 7 9 91 2 41 6 61 5 93 1 10Output49152319NoteConsider the first testcase: At first, aβ=β{1,β2,β3,β4,β5}. After operation 1, aβ=β{1,β2,β3,β0,β1}. After operation 2, aβ=β{1,β2,β5,β0,β1}. At operation 3, 2β+β5β+β0β+β1β=β8. After operation 4, aβ=β{1,β2,β2,β0,β1}. At operation 5, 1β+β2β+β2β=β5. | Input5 51 2 3 4 52 3 5 43 3 51 2 52 1 3 31 1 3 | Output85 | 4 seconds | 256 megabytes | ['data structures', 'math', '*2300'] |
E. The Child and Polygontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis time our child has a simple polygon. He has to find the number of ways to split the polygon into non-degenerate triangles, each way must satisfy the following requirements: each vertex of each triangle is one of the polygon vertex; each side of the polygon must be the side of exactly one triangle; the area of intersection of every two triangles equals to zero, and the sum of all areas of triangles equals to the area of the polygon; each triangle must be completely inside the polygon; each side of each triangle must contain exactly two vertices of the polygon. The picture below depicts an example of a correct splitting. Please, help the child. Calculate the described number of ways modulo 1000000007 (109ββ+ββ7) for him.InputThe first line contains one integer n (3ββ€βnββ€β200) β the number of vertices of the polygon. Then follow n lines, each line containing two integers. The i-th line contains xi,βyi (|xi|,β|yi|ββ€β107) β the i-th vertex of the polygon in clockwise or counterclockwise order.It's guaranteed that the polygon is simple.OutputOutput the number of ways modulo 1000000007 (109ββ+ββ7).ExamplesInput40 00 11 11 0Output2Input40 01 00 1-1 0Output1Input50 01 01 10 1-2 -1Output3NoteIn the first sample, there are two possible splittings: In the second sample, there are only one possible splitting: | Input40 00 11 11 0 | Output2 | 2 seconds | 256 megabytes | ['dp', 'geometry', '*2500'] |
D. The Child and Zootime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOf course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p,βq). Finally, the child chooses one of the routes for which he writes down the value f(p,βq).After the child has visited the zoo, he thinks about the question: what is the average value of f(p,βq) for all pairs p,βq (pββ βq)? Can you answer his question?InputThe first line contains two integers n and m (2ββ€βnββ€β105; 0ββ€βmββ€β105). The second line contains n integers: a1,βa2,β...,βan (0ββ€βaiββ€β105). Then follow m lines, each line contains two integers xi and yi (1ββ€βxi,βyiββ€βn; xiββ βyi), denoting the road between areas xi and yi.All roads are bidirectional, each pair of areas is connected by at most one road.OutputOutput a real number β the value of .The answer will be considered correct if its relative or absolute error doesn't exceed 10β-β4.ExamplesInput4 310 20 30 401 32 34 3Output16.666667Input3 310 20 301 22 33 1Output13.333333Input7 840 20 10 30 20 50 401 22 33 44 55 66 71 45 7Output18.571429NoteConsider the first sample. There are 12 possible situations: pβ=β1,βqβ=β3,βf(p,βq)β=β10. pβ=β2,βqβ=β3,βf(p,βq)β=β20. pβ=β4,βqβ=β3,βf(p,βq)β=β30. pβ=β1,βqβ=β2,βf(p,βq)β=β10. pβ=β2,βqβ=β4,βf(p,βq)β=β20. pβ=β4,βqβ=β1,βf(p,βq)β=β10. Another 6 cases are symmetrical to the above. The average is .Consider the second sample. There are 6 possible situations: pβ=β1,βqβ=β2,βf(p,βq)β=β10. pβ=β2,βqβ=β3,βf(p,βq)β=β20. pβ=β1,βqβ=β3,βf(p,βq)β=β10. Another 3 cases are symmetrical to the above. The average is . | Input4 310 20 30 401 32 34 3 | Output16.666667 | 2 seconds | 256 megabytes | ['dsu', 'sortings', '*1900'] |
C. The Child and Toytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1β+βvf2β+β...β+βvfk energy for removing part i where f1,βf2,β...,βfk are the parts that are directly connected to the i-th and haven't been removed.Help the child to find out, what is the minimum total energy he should spend to remove all n parts.InputThe first line contains two integers n and m (1ββ€βnββ€β1000; 0ββ€βmββ€β2000). The second line contains n integers: v1,βv2,β...,βvn (0ββ€βviββ€β105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1ββ€βxi,βyiββ€βn;Β xiββ βyi).Consider all the parts are numbered from 1 to n.OutputOutput the minimum total energy the child should spend to remove all n parts of the toy.ExamplesInput4 310 20 30 401 41 22 3Output40Input4 4100 100 100 1001 22 32 43 4Output400Input7 1040 10 20 10 20 80 401 54 74 55 25 76 41 61 34 31 4Output160NoteOne of the optimal sequence of actions in the first sample is: First, remove part 3, cost of the action is 20. Then, remove part 2, cost of the action is 10. Next, remove part 4, cost of the action is 10. At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20β+β10β+β10β+β0β=β40, which is the minimum.In the second sample, the child will spend 400 no matter in what order he will remove the parts. | Input4 310 20 30 401 41 22 3 | Output40 | 1 second | 256 megabytes | ['graphs', 'greedy', 'sortings', '*1400'] |
B. The Child and Settime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.Fortunately, Picks remembers something about his set S: its elements were distinct integers from 1 to limit; the value of was equal to sum; here lowbit(x) equals 2k where k is the position of the first one in the binary representation of x. For example, lowbit(100102)β=β102,βlowbit(100012)β=β12,βlowbit(100002)β=β100002 (binary representation). Can you help Picks and find any set S, that satisfies all the above conditions?InputThe first line contains two integers: sum,βlimit (1ββ€βsum,βlimitββ€β105).OutputIn the first line print an integer n (1ββ€βnββ€β105), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them.If it's impossible to find a suitable set, print -1.ExamplesInput5 5Output24 5Input4 3Output32 3 1Input5 1Output-1NoteIn sample test 1: lowbit(4)β=β4,βlowbit(5)β=β1,β4β+β1β=β5.In sample test 2: lowbit(1)β=β1,βlowbit(2)β=β2,βlowbit(3)β=β1,β1β+β2β+β1β=β4. | Input5 5 | Output24 5 | 1 second | 256 megabytes | ['bitmasks', 'greedy', 'implementation', 'sortings', '*1500'] |
A. The Child and Homeworktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct.Fortunately the child knows how to solve such complicated test. The child will follow the algorithm: If there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, then the child thinks the choice is great. If there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice). You are given a multiple-choice questions, can you predict child's choose?InputThe first line starts with "A." (without quotes), then followed the description of choice A. The next three lines contains the descriptions of the other choices in the same format. They are given in order: B, C, D. Please note, that the description goes after prefix "X.", so the prefix mustn't be counted in description's length.Each description is non-empty and consists of at most 100 characters. Each character can be either uppercase English letter or lowercase English letter, or "_". OutputPrint a single line with the child's choice: "A", "B", "C" or "D" (without quotes).ExamplesInputA.VFleaKing_is_the_author_of_this_problemB.Picks_is_the_author_of_this_problemC.Picking_is_the_author_of_this_problemD.Ftiasch_is_cuteOutputDInputA.abB.abcdeC.abD.abcOutputCInputA.cB.ccC.cD.cOutputBNoteIn the first sample, the first choice has length 39, the second one has length 35, the third one has length 37, and the last one has length 15. The choice D (length 15) is twice shorter than all other choices', so it is great choice. There is no other great choices so the child will choose D.In the second sample, no choice is great, so the child will choose the luckiest choice C.In the third sample, the choice B (length 2) is twice longer than all other choices', so it is great choice. There is no other great choices so the child will choose B. | InputA.VFleaKing_is_the_author_of_this_problemB.Picks_is_the_author_of_this_problemC.Picking_is_the_author_of_this_problemD.Ftiasch_is_cute | OutputD | 1 second | 256 megabytes | ['implementation', '*1300'] |
F. Bannerstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAll modern mobile applications are divided into free and paid. Even a single application developers often release two versions: a paid version without ads and a free version with ads. Suppose that a paid version of the app costs p (p is an integer) rubles, and the free version of the application contains c ad banners. Each user can be described by two integers: ai β the number of rubles this user is willing to pay for the paid version of the application, and bi β the number of banners he is willing to tolerate in the free version.The behavior of each member shall be considered strictly deterministic: if for user i, value bi is at least c, then he uses the free version, otherwise, if value ai is at least p, then he buys the paid version without advertising, otherwise the user simply does not use the application. Each user of the free version brings the profit of cβΓβw rubles. Each user of the paid version brings the profit of p rubles.Your task is to help the application developers to select the optimal parameters p and c. Namely, knowing all the characteristics of users, for each value of c from 0 to (maxΒ bi)β+β1 you need to determine the maximum profit from the application and the corresponding parameter p.InputThe first line contains two integers n and w (1ββ€βnββ€β105;Β 1ββ€βwββ€β105) β the number of users and the profit from a single banner. Each of the next n lines contains two integers ai and bi (0ββ€βai,βbiββ€β105) β the characteristics of the i-th user.OutputPrint (maxΒ bi)β+β2 lines, in the i-th line print two integers: pay β the maximum gained profit at cβ=βiβ-β1, p (0ββ€βpββ€β109) β the corresponding optimal app cost. If there are multiple optimal solutions, print any of them.ExamplesInput2 12 00 2Output0 33 24 22 2Input3 13 12 21 3Output0 43 47 37 24 2 | Input2 12 00 2 | Output0 33 24 22 2 | 5 seconds | 512 megabytes | ['brute force', 'data structures', 'dp', '*3000'] |
E. Cardboard Boxtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEveryone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: ai β how long it takes to complete the level for one star, bi β how long it takes to complete the level for two stars (aiβ<βbi).You want to open the next box as quickly as possible. So, you need to earn at least w stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels.InputThe first line contains two integers n and w (1ββ€βnββ€β3Β·105;Β 1ββ€βwββ€β2n) β the number of levels in the first box and the number of stars you need to open another box. Each of the following n lines contains two integers ai and bi (1ββ€βaiβ<βbiββ€β109) β the attributes of the i-th level.OutputIn the first line print integer t β the minimum time you need to open the next box. In the next line, print n digits without spaces β the description of the optimal scenario: if you need to pass the i-th level for one star, the i-th digit should equal 1; if you need to pass the i-th level for two stars, the i-th digit should equal 2; if you do not need to pass the i-th level at all, the i-th digit should equal 0. ExamplesInput2 31 21 2Output312Input5 310 205 1010 206 925 30Output1401020NoteIn the first test sample, answer 21 is also assumed correct. | Input2 31 21 2 | Output312 | 5 seconds | 256 megabytes | ['data structures', 'greedy', '*2600'] |
D. Pudding Monsterstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHave you ever played Pudding Monsters? In this task, a simplified one-dimensional model of this game is used. Imagine an infinite checkered stripe, the cells of which are numbered sequentially with integers. Some cells of the strip have monsters, other cells of the strip are empty. All monsters are made of pudding, so if there are two monsters in the neighboring cells, they stick to each other (literally). Similarly, if several monsters are on consecutive cells, they all stick together in one block of monsters. We will call the stuck together monsters a block of monsters. A detached monster, not stuck to anyone else, is also considered a block.In one move, the player can take any block of monsters and with a movement of his hand throw it to the left or to the right. The selected monsters will slide on until they hit some other monster (or a block of monsters).For example, if a strip has three monsters in cells 1, 4 and 5, then there are only four possible moves: to send a monster in cell 1 to minus infinity, send the block of monsters in cells 4 and 5 to plus infinity, throw monster 1 to the right (it will stop in cell 3), throw a block of monsters in cells 4 and 5 to the left (they will stop in cells 2 and 3).Some cells on the strip are marked with stars. These are the special cells. The goal of the game is to make the largest possible number of special cells have monsters on them.You are given the numbers of the special cells on a strip as well as the initial position of all monsters. What is the maximum number of special cells that will contain monsters in the optimal game?InputThe first line contains two integers n and m (1ββ€βnββ€β105;Β 1ββ€βmββ€β2000) β the number of monsters on the strip and the number of special cells.The second line contains n distinct integers β the numbers of the cells with monsters, then the third line contains m distinct integers β the numbers of the special cells. It is guaranteed that all the numbers of the cells are positive integers not exceeding 2Β·105.OutputPrint a single integer β the maximum number of special cells that will contain monsters in the optimal game.ExamplesInput3 21 3 52 4Output2Input4 21 3 4 62 5Output2Input4 21 8 4 57 2Output1 | Input3 21 3 52 4 | Output2 | 5 seconds | 256 megabytes | ['dp', '*2800'] |
C. Dungeons and Candiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an nβΓβm checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same. When you transmit information via a network, you want to minimize traffic β the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A: You can transmit the whole level A. Then you need to transmit nΒ·m bytes via the network. You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA,βBΒ·w bytes, where dA,βB is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA,βB. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic.InputThe first line contains four integers n,βm,βk,βw (1ββ€βn,βmββ€β10;Β 1ββ€βk,βwββ€β1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters.OutputIn the first line print the required minimum number of transferred bytes.Then print k pairs of integers x1,βy1,βx2,βy2,β...,βxk,βyk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input.If there are multiple optimal solutions, you can print any of them.ExamplesInput2 3 3 2A.A...A.a..CX.Y...Output141 02 13 1Input1 1 4 1A.B.Output31 02 04 23 0Input1 3 5 2ABABBBBBABABABBOutput111 03 12 34 25 1 | Input2 3 3 2A.A...A.a..CX.Y... | Output141 02 13 1 | 2 seconds | 256 megabytes | ['dsu', 'graphs', 'greedy', 'trees', '*1800'] |
B. Om Nom and Spiderstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOm Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. The park can be represented as a rectangular nβΓβm field. The park has k spiders, each spider at time 0 is at some cell of the field. The spiders move all the time, and each spider always moves in one of the four directions (left, right, down, up). In a unit of time, a spider crawls from his cell to the side-adjacent cell in the corresponding direction. If there is no cell in the given direction, then the spider leaves the park. The spiders do not interfere with each other as they move. Specifically, one cell can have multiple spiders at the same time.Om Nom isn't yet sure where to start his walk from but he definitely wants: to start walking at time 0 at an upper row cell of the field (it is guaranteed that the cells in this row do not contain any spiders); to walk by moving down the field towards the lowest row (the walk ends when Om Nom leaves the boundaries of the park). We know that Om Nom moves by jumping. One jump takes one time unit and transports the little monster from his cell to either a side-adjacent cell on the lower row or outside the park boundaries.Each time Om Nom lands in a cell he sees all the spiders that have come to that cell at this moment of time. Om Nom wants to choose the optimal cell to start the walk from. That's why he wonders: for each possible starting cell, how many spiders will he see during the walk if he starts from this cell? Help him and calculate the required value for each possible starting cell.InputThe first line contains three integers n,βm,βk (2ββ€βn,βmββ€β2000;Β 0ββ€βkββ€βm(nβ-β1)). Each of the next n lines contains m characters β the description of the park. The characters in the i-th line describe the i-th row of the park field. If the character in the line equals ".", that means that the corresponding cell of the field is empty; otherwise, the character in the line will equal one of the four characters: "L" (meaning that this cell has a spider at time 0, moving left), "R" (a spider moving right), "U" (a spider moving up), "D" (a spider moving down). It is guaranteed that the first row doesn't contain any spiders. It is guaranteed that the description of the field contains no extra characters. It is guaranteed that at time 0 the field contains exactly k spiders.OutputPrint m integers: the j-th integer must show the number of spiders Om Nom will see if he starts his walk from the j-th cell of the first row. The cells in any row of the field are numbered from left to right.ExamplesInput3 3 4...R.LR.UOutput0 2 2 Input2 2 2..RLOutput1 1 Input2 2 2..LROutput0 0 Input3 4 8....RRLLUUUUOutput1 3 3 1 Input2 2 2..UUOutput0 0 NoteConsider the first sample. The notes below show how the spider arrangement changes on the field over time:... ... ..U ...R.L -> .*U -> L.R -> ...R.U .R. ..R ...Character "*" represents a cell that contains two spiders at the same time. If Om Nom starts from the first cell of the first row, he won't see any spiders. If he starts from the second cell, he will see two spiders at time 1. If he starts from the third cell, he will see two spiders: one at time 1, the other one at time 2. | Input3 3 4...R.LR.U | Output0 2 2 | 3 seconds | 256 megabytes | ['implementation', 'math', '*1400'] |
A. Feed with Candytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem. One day, Om Nom visited his friend Evan. Evan has n candies of two types (fruit drops and caramel drops), the i-th candy hangs at the height of hi centimeters above the floor of the house, its mass is mi. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most x centimeter high jumps. When Om Nom eats a candy of mass y, he gets stronger and the height of his jump increases by y centimeters.What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?InputThe first line contains two integers, n and x (1ββ€βn,βxββ€β2000) β the number of sweets Evan has and the initial height of Om Nom's jump. Each of the following n lines contains three integers ti,βhi,βmi (0ββ€βtiββ€β1;Β 1ββ€βhi,βmiββ€β2000) β the type, height and the mass of the i-th candy. If number ti equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.OutputPrint a single integer β the maximum number of candies Om Nom can eat.ExamplesInput5 30 2 41 3 10 8 30 20 101 5 5Output4NoteOne of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario: Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3β+β4β=β7. Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7β+β5β=β12. At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12β+β3β=β15. Om Nom eats candy 2, the height of his jump is 15β+β1β=β16. He cannot reach candy 4. | Input5 30 2 41 3 10 8 30 20 101 5 5 | Output4 | 2 seconds | 256 megabytes | ['greedy', '*1500'] |
E. Special Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you will need to deal with an nβΓβm grid graph. The graph's vertices are the nodes of the nβΓβm grid. The graph's edges are all the sides and diagonals of the grid's unit squares.The figure below shows a 3βΓβ5 graph. The black lines are the graph's edges, the colored circles are the graph's vertices. The vertices of the graph are painted on the picture for a reason: the coloring is a correct vertex coloring of the 3βΓβ5 graph into four colors. A graph coloring is correct if and only if each vertex is painted and no two vertices connected by an edge are painted the same color. You are given the size of the grid graph nβΓβm and the colors of some of its vertices. Find any way how to paint the unpainted vertices of the graph in 4 colors to make the final coloring a correct vertex graph coloring. If there is no such correct vertex coloring, say that the answer doesn't exist.InputThe first line contains two integers n and m (2ββ€βn,βmββ€β1000). Each of the next n lines consists of m characters β the given graph. Each character is either Β«0Β», Β«1Β», Β«2Β», Β«3Β», Β«4Β». Character Β«0Β» means that the corresponding vertex is unpainted, otherwise the character means the color of the vertex.Assume that all the available colors are numbered from 1 to 4.OutputIf there is no way to get correct vertex coloring of the graph, print 0 in a single line. Otherwise print the colored nβΓβm graph. Print the graph in the same format as in the input.If multiple answers exist, print any of them.ExamplesInput3 5101010002001000Output131314242431313Input2 20000Output1234Input2 21100Output0NoteThe answer to the first sample is shown on the picture (1 β green color, 2 β blue, 3 β dark blue, 4 β pink).In the second sample there exists 4! answers, each of them is considered correct.In the third sample two vertices with equal colors are connected. So the correct vertex coloring couldn't be obtained. | Input3 5101010002001000 | Output131314242431313 | 2 seconds | 256 megabytes | ['*2500'] |
D. Special Gridtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an nβΓβm grid, some of its nodes are black, the others are white. Moreover, it's not an ordinary grid β each unit square of the grid has painted diagonals.The figure below is an example of such grid of size 3βΓβ5. Four nodes of this grid are black, the other 11 nodes are white. Your task is to count the number of such triangles on the given grid that: the corners match the white nodes, and the area is positive; all sides go along the grid lines (horizontal, vertical or diagonal); no side contains black nodes. InputThe first line contains two integers n and m (2ββ€βn,βmββ€β400). Each of the following n lines contain m characters (zeros and ones) β the description of the grid. If the j-th character in the i-th line equals zero, then the node on the i-th horizontal line and on the j-th vertical line is painted white. Otherwise, the node is painted black.The horizontal lines are numbered starting from one from top to bottom, the vertical lines are numbered starting from one from left to right. OutputPrint a single integer β the number of required triangles.ExamplesInput3 5100001001000001Output20Input2 20000Output4Input2 21111Output0NoteThe figure below shows red and blue triangles. They are the examples of the required triangles in the first sample. One of the invalid triangles is painted green. It is invalid because not all sides go along the grid lines. | Input3 5100001001000001 | Output20 | 4 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', '*2000'] |
C. Cardiogramtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners:That is, a cardiogram is fully defined by a sequence of positive integers a1,βa2,β...,βan.Your task is to paint a cardiogram by given sequence ai.InputThe first line contains integer n (2ββ€βnββ€β1000). The next line contains the sequence of integers a1,βa2,β...,βan (1ββ€βaiββ€β1000). It is guaranteed that the sum of all ai doesn't exceed 1000.OutputPrint maxΒ |yiβ-βyj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print characters. Each character must equal either Β«β/βΒ» (slash), Β« \ Β» (backslash), Β« Β» (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram.Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.ExamplesInput53 1 2 5 1Output β/β\ β/β\β/β \ β/β \ β/β \ \β/βInput31 5 1Outputβ/β\ \ \ \ \β/βNoteDue to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.http://assets.codeforces.com/rounds/435/1.txthttp://assets.codeforces.com/rounds/435/2.txt | Input53 1 2 5 1 | Output β/β\ β/β\β/β \ β/β \ β/β \ \β/β | 1 second | 256 megabytes | ['implementation', '*1600'] |
B. Pasha Maximizestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha has a positive integer a without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer.Help Pasha count the maximum number he can get if he has the time to make at most k swaps.InputThe single line contains two integers a and k (1ββ€βaββ€β1018;Β 0ββ€βkββ€β100).OutputPrint the maximum number that Pasha can get if he makes at most k swaps.ExamplesInput1990 1Output9190Input300 0Output300Input1034 2Output3104Input9090000078001234 6Output9907000008001234 | Input1990 1 | Output9190 | 1 second | 256 megabytes | ['greedy', '*1400'] |
A. Queue on Bus Stoptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups.The bus stop queue has n groups of people. The i-th group from the beginning has ai people. Every 30 minutes an empty bus arrives at the bus stop, it can carry at most m people. Naturally, the people from the first group enter the bus first. Then go the people from the second group and so on. Note that the order of groups in the queue never changes. Moreover, if some group cannot fit all of its members into the current bus, it waits for the next bus together with other groups standing after it in the queue.Your task is to determine how many buses is needed to transport all n groups to the dacha countryside.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β100). The next line contains n integers: a1,βa2,β...,βan (1ββ€βaiββ€βm).OutputPrint a single integer β the number of buses that is needed to transport all n groups to the dacha countryside.ExamplesInput4 32 3 2 1Output3Input3 41 2 1Output1 | Input4 32 3 2 1 | Output3 | 1 second | 256 megabytes | ['implementation', '*1000'] |
E. Furukawa Nagisa's Treetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOne day, Okazaki Tomoya has bought a tree for Furukawa Nagisa's birthday. The tree is so strange that every node of the tree has a value. The value of the i-th node is vi. Now Furukawa Nagisa and Okazaki Tomoya want to play a game on the tree.Let (s,βe) be the path from node s to node e, we can write down the sequence of the values of nodes on path (s,βe), and denote this sequence as S(s,βe). We define the value of the sequence G(S(s,βe)) as follows. Suppose that the sequence is z0,βz1...zlβ-β1, where l is the length of the sequence. We define G(S(s,βe))β=βz0βΓβk0β+βz1βΓβk1β+β...β+βzlβ-β1βΓβklβ-β1. If the path (s,βe) satisfies , then the path (s,βe) belongs to Furukawa Nagisa, otherwise it belongs to Okazaki Tomoya.Calculating who has more paths is too easy, so they want to play something more difficult. Furukawa Nagisa thinks that if paths (p1,βp2) and (p2,βp3) belong to her, then path (p1,βp3) belongs to her as well. Also, she thinks that if paths (p1,βp2) and (p2,βp3) belong to Okazaki Tomoya, then path (p1,βp3) belongs to Okazaki Tomoya as well. But in fact, this conclusion isn't always right. So now Furukawa Nagisa wants to know how many triplets (p1,βp2,βp3) are correct for the conclusion, and this is your task.InputThe first line contains four integers n, y, k and xΒ (1ββ€βnββ€β105;Β 2ββ€βyββ€β109;Β 1ββ€βkβ<βy;Β 0ββ€βxβ<βy) β n being the number of nodes on the tree. It is guaranteed that y is a prime number.The second line contains n integers, the i-th integer is viΒ (0ββ€βviβ<βy).Then follow nβ-β1 lines, each line contains two integers, denoting an edge of the tree. The nodes of the tree are numbered from 1 to n.OutputOutput a single integer β the number of triplets that are correct for Furukawa Nagisa's conclusion.ExamplesInput1 2 1 01Output1Input3 5 2 14 3 11 22 3Output14Input8 13 8 120 12 7 4 12 0 8 121 88 44 66 22 38 52 7Output341 | Input1 2 1 01 | Output1 | 2 seconds | 512 megabytes | ['binary search', 'divide and conquer', 'sortings', 'trees', '*3000'] |
D. Nanami's Power Planttime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputNanami likes playing games, and is also really good at it. This day she was playing a new game which involved operating a power plant. Nanami's job is to control the generators in the plant and produce maximum output.There are n generators in the plant. Each generator should be set to a generating level. Generating level is an integer (possibly zero or negative), the generating level of the i-th generator should be between li and ri (both inclusive). The output of a generator can be calculated using a certain quadratic function f(x), where x is the generating level of the generator. Each generator has its own function, the function of the i-th generator is denoted as fi(x).However, there are m further restrictions to the generators. Let the generating level of the i-th generator be xi. Each restriction is of the form xuββ€βxvβ+βd, where u and v are IDs of two different generators and d is an integer.Nanami found the game tedious but giving up is against her creed. So she decided to have a program written to calculate the answer for her (the maximum total output of generators). Somehow, this became your job.InputThe first line contains two integers n and mΒ (1ββ€βnββ€β50;Β 0ββ€βmββ€β100) β the number of generators and the number of restrictions.Then follow n lines, each line contains three integers ai, bi, and ciΒ (|ai|ββ€β10;Β |bi|,β|ci|ββ€β1000) β the coefficients of the function fi(x). That is, fi(x)β=βaix2β+βbixβ+βci.Then follow another n lines, each line contains two integers li and riΒ (β-β100ββ€βliββ€βriββ€β100).Then follow m lines, each line contains three integers ui, vi, and diΒ (1ββ€βui,βviββ€βn;Β uiββ βvi;Β |di|ββ€β200), describing a restriction. The i-th restriction is xuiββ€βxviβ+βdi.OutputPrint a single line containing a single integer β the maximum output of all the generators. It is guaranteed that there exists at least one valid configuration.ExamplesInput3 30 1 00 1 10 1 20 31 2-100 1001 2 02 3 03 1 0Output9Input5 81 -8 202 -4 0-1 10 -100 1 00 -1 11 91 40 103 117 92 1 31 2 32 3 33 2 33 4 34 3 34 5 35 4 3Output46NoteIn the first sample, f1(x)β=βx, f2(x)β=βxβ+β1, and f3(x)β=βxβ+β2, so we are to maximize the sum of the generating levels. The restrictions are x1ββ€βx2, x2ββ€βx3, and x3ββ€βx1, which gives us x1β=βx2β=βx3. The optimal configuration is x1β=βx2β=βx3β=β2, which produces an output of 9.In the second sample, restrictions are equal to |xiβ-βxiβ+β1|ββ€β3 for 1ββ€βiβ<βn. One of the optimal configurations is x1β=β1, x2β=β4, x3β=β5, x4β=β8 and x5β=β7. | Input3 30 1 00 1 10 1 20 31 2-100 1001 2 02 3 03 1 0 | Output9 | 5 seconds | 512 megabytes | ['flows', '*2900'] |
E. Tachibana Kanade's Tofutime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputTachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu.Each piece of tofu in the canteen is given a m-based number, all numbers are in the range [l,βr] (l and r being m-based numbers), and for every m-based integer in the range [l,βr], there exists a piece of tofu with that number.To judge what tofu is Mapo Tofu, Tachibana Kanade chose n m-based number strings, and assigned a value to each string. If a string appears in the number of a tofu, the value of the string will be added to the value of that tofu. If a string appears multiple times, then the value is also added that many times. Initially the value of each tofu is zero.Tachibana Kanade considers tofu with values no more than k to be Mapo Tofu. So now Tachibana Kanade wants to know, how many pieces of tofu are Mapo Tofu?InputThe first line contains three integers n, m and kΒ (1ββ€βnββ€β200;Β 2ββ€βmββ€β20;Β 1ββ€βkββ€β500). Where n denotes the number of strings, m denotes the base used, and k denotes the limit of the value for Mapo Tofu.The second line represents the number l. The first integer in the line is len (1ββ€βlenββ€β200), describing the length (number of digits in base m) of l. Then follow len integers a1,βa2,β...,βalenΒ (0ββ€βaiβ<βm;Β a1β>β0) separated by spaces, representing the digits of l, with a1 being the highest digit and alen being the lowest digit.The third line represents the number r in the same format as l. It is guaranteed that 1ββ€βlββ€βr.Then follow n lines, each line describing a number string. The i-th line contains the i-th number string and vi β the value of the i-th string (1ββ€βviββ€β200). All number strings are described in almost the same format as l, the only difference is number strings may contain necessary leading zeros (see the first example). The sum of the lengths of all number strings does not exceed 200.OutputOutput the number of pieces of Mapo Tofu modulo 1000000007 (109β+β7). The answer should be a decimal integer.ExamplesInput2 10 11 13 1 0 01 1 11 0 1Output97Input2 10 122 5 96 6 3 5 4 9 72 0 6 13 6 7 2 1Output635439Input4 2 66 1 0 1 1 1 06 1 1 0 1 0 01 1 23 0 1 0 54 0 1 1 0 43 1 0 1 2Output2NoteIn the first sample, 10, 11 and 100 are the only three decimal numbers in [1,β100] with a value greater than 1. Here the value of 1 is 1 but not 2, since numbers cannot contain leading zeros and thus cannot be written as "01".In the second sample, no numbers in the given interval have a value greater than 12.In the third sample, 110000 and 110001 are the only two binary numbers in the given interval with a value no greater than 6. | Input2 10 11 13 1 0 01 1 11 0 1 | Output97 | 5 seconds | 512 megabytes | ['dp', '*2500'] |
D. Nanami's Digital Boardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium.The digital board is n pixels in height and m pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The j-th pixel of the i-th line is pixel (i,βj). The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light.Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel (i,βj) belongs to a side of sub-rectangle with (x1,βy1) and (x2,βy2) as its upper-left and lower-right vertex if and only if it satisfies the logical condition: ((iβ=βx1 or iβ=βx2) and (y1ββ€βjββ€βy2)) or ((jβ=βy1 or jβ=βy2) and (x1ββ€βiββ€βx2)).Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them?InputThe first line contains three space-separated integers n, m and qΒ (1ββ€βn,βm,βqββ€β1000) β the height and width of the digital board, and the number of operations.Then follow n lines, each line containing m space-separated integers. The j-th integer of the i-th line is ai,βj β the initial state of pixel (i,βj). If ai,βjβ=β0, pixel (i,βj) is initially dark. If ai,βjβ=β1, pixel (i,βj) is initially light. Then follow q lines, each line containing three space-separated integers op, x, and yΒ (1ββ€βopββ€β2;Β 1ββ€βxββ€βn;Β 1ββ€βyββ€βm), describing an operation. If opβ=β1, the pixel at (x,βy) changes its state (from light to dark or from dark to light). If opβ=β2, Nanami queries the biggest light block with pixel (x,βy) on its side. OutputFor each query, print a single line containing one integer β the answer to Nanami's query.ExamplesInput3 4 50 1 1 01 0 0 10 1 1 02 2 22 1 21 2 21 2 32 2 2Output026Input3 3 41 1 11 1 11 1 12 2 21 2 22 1 12 2 1Output633NoteConsider the first sample.The first query specifies pixel (2,β2), which is dark itself, so there are no valid light blocks, thus the answer is 0.The second query specifies pixel (1,β2). The biggest light block is the block with (1,β2) as its upper-left vertex and (1,β3) as its lower-right vertex.The last query specifies pixel (2,β2), which became light in the third operation. The biggest light block is the block with (1,β2) as its upper-left vertex and (3,β3) as its lower-right vertex. | Input3 4 50 1 1 01 0 0 10 1 1 02 2 22 1 21 2 21 2 32 2 2 | Output026 | 1 second | 256 megabytes | ['dsu', 'implementation', '*2000'] |
C. Ryouko's Memory Notetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRyouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory.Though Ryouko is forgetful, she is also born with superb analyzing abilities. However, analyzing depends greatly on gathered information, in other words, memory. So she has to shuffle through her notebook whenever she needs to analyze, which is tough work.Ryouko's notebook consists of n pages, numbered from 1 to n. To make life (and this problem) easier, we consider that to turn from page x to page y, |xβ-βy| pages should be turned. During analyzing, Ryouko needs m pieces of information, the i-th piece of information is on page ai. Information must be read from the notebook in order, so the total number of pages that Ryouko needs to turn is .Ryouko wants to decrease the number of pages that need to be turned. In order to achieve this, she can merge two pages of her notebook. If Ryouko merges page x to page y, she would copy all the information on page x to yΒ (1ββ€βx,βyββ€βn), and consequently, all elements in sequence a that was x would become y. Note that x can be equal to y, in which case no changes take place.Please tell Ryouko the minimum number of pages that she needs to turn. Note she can apply the described operation at most once before the reading. Note that the answer can exceed 32-bit integers.InputThe first line of input contains two integers n and mΒ (1ββ€βn,βmββ€β105).The next line contains m integers separated by spaces: a1,βa2,β...,βam (1ββ€βaiββ€βn).OutputPrint a single integer β the minimum number of pages Ryouko needs to turn.ExamplesInput4 61 2 3 4 3 2Output3Input10 59 4 3 8 8Output6NoteIn the first sample, the optimal solution is to merge page 4 to 3, after merging sequence a becomes {1,β2,β3,β3,β3,β2}, so the number of pages Ryouko needs to turn is |1β-β2|β+β|2β-β3|β+β|3β-β3|β+β|3β-β3|β+β|3β-β2|β=β3.In the second sample, optimal solution is achieved by merging page 9 to 4. | Input4 61 2 3 4 3 2 | Output3 | 1 second | 256 megabytes | ['implementation', 'math', 'sortings', '*1800'] |
B. Kuriyama Mirai's Stonestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: She will tell you two numbers, l and rΒ (1ββ€βlββ€βrββ€βn), and you should tell her . Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and rΒ (1ββ€βlββ€βrββ€βn), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.InputThe first line contains an integer nΒ (1ββ€βnββ€β105). The second line contains n integers: v1,βv2,β...,βvnΒ (1ββ€βviββ€β109) β costs of the stones. The third line contains an integer mΒ (1ββ€βmββ€β105) β the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and rΒ (1ββ€βlββ€βrββ€βn;Β 1ββ€βtypeββ€β2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.OutputPrint m lines. Each line must contain an integer β the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.ExamplesInput66 4 2 7 2 732 3 61 3 41 1 6Output24928Input45 5 2 3101 2 42 1 41 1 12 1 42 1 21 1 11 3 31 1 31 4 41 2 2Output10155155521235NotePlease note that the answers to the questions may overflow 32-bit integer type. | Input66 4 2 7 2 732 3 61 3 41 1 6 | Output24928 | 2 seconds | 256 megabytes | ['dp', 'implementation', 'sortings', '*1200'] |
A. Kitahara Haruki's Gifttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.But unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. Please, tell him: is it possible to divide all the apples in a fair way between his friends?InputThe first line contains an integer n (1ββ€βnββ€β100) β the number of apples. The second line contains n integers w1,βw2,β...,βwn (wiβ=β100 or wiβ=β200), where wi is the weight of the i-th apple.OutputIn a single line print "YES" (without the quotes) if it is possible to divide all the apples between his friends. Otherwise print "NO" (without the quotes).ExamplesInput3100 200 100OutputYESInput4100 100 100 200OutputNONoteIn the first test sample Kitahara Haruki can give the first and the last apple to Ogiso Setsuna and the middle apple to Touma Kazusa. | Input3100 200 100 | OutputYES | 1 second | 256 megabytes | ['brute force', 'implementation', '*1100'] |
E. Square Tilingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an nβΓβm rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally: each cell must be painted some color (the colors are marked by uppercase Latin letters); we will assume that two cells of the table are connected if they are of the same color and share a side; each connected region of the table must form a square. Given n and m, find lexicographically minimum coloring of the table that meets the described properties.InputThe first line contains two integers, n and m (1ββ€βn,βmββ€β100).OutputPrint lexicographically minimum coloring of the table that meets the described conditions. One coloring (let's call it X) is considered lexicographically less than the other one (let's call it Y), if: consider all the table cells from left to right and from top to bottom (first, the first cell in the first row, then the second cell in the first row and so on); let's find in this order the first cell that has distinct colors in two colorings; the letter that marks the color of the cell in X, goes alphabetically before the letter that marks the color of the cell in Y. ExamplesInput1 3OutputABAInput2 2OutputAAAAInput3 4OutputAAABAAACAAAB | Input1 3 | OutputABA | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*2300'] |
D. Prefixes and Suffixestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string sβ=βs1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: A substring s[i..j] (1ββ€βiββ€βjββ€β|s|) of string s is string sisiβ+β1...sj. The prefix of string s of length l (1ββ€βlββ€β|s|) is string s[1..l]. The suffix of string s of length l (1ββ€βlββ€β|s|) is string s[|s|β-βlβ+β1..|s|]. Your task is, for any prefix of string s which matches a suffix of string s, print the number of times it occurs in string s as a substring.InputThe single line contains a sequence of characters s1s2...s|s| (1ββ€β|s|ββ€β105) β string s. The string only consists of uppercase English letters.OutputIn the first line, print integer k (0ββ€βkββ€β|s|) β the number of prefixes that match a suffix of string s. Next print k lines, in each line print two integers li ci. Numbers li ci mean that the prefix of the length li matches the suffix of length li and occurs in string s as a substring ci times. Print pairs li ci in the order of increasing li.ExamplesInputABACABAOutput31 43 27 1InputAAAOutput31 32 23 1 | InputABACABA | Output31 43 27 1 | 1 second | 256 megabytes | ['dp', 'string suffix structures', 'strings', 'two pointers', '*2000'] |
C. Prime Swapstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a[1],βa[2],β...,βa[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times): choose two indexes, i and j (1ββ€βiβ<βjββ€βn; (jβ-βiβ+β1) is a prime number); swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmpβ=βa[i],βa[i]β=βa[j],βa[j]β=βtmp (tmp is a temporary variable). You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.InputThe first line contains integer n (1ββ€βnββ€β105). The next line contains n distinct integers a[1],βa[2],β...,βa[n] (1ββ€βa[i]ββ€βn).OutputIn the first line, print integer k (0ββ€βkββ€β5n) β the number of used operations. Next, print the operations. Each operation must be printed as "i j" (1ββ€βiβ<βjββ€βn; (jβ-βiβ+β1) is a prime).If there are multiple answers, you can print any of them.ExamplesInput33 2 1Output11 3Input21 2Output0Input44 2 3 1Output32 41 22 4 | Input33 2 1 | Output11 3 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1800'] |
B. Football Kittime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a football tournament where n teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the i-th team has color xi and the kit for away games of this team has color yi (xiββ βyi).In the tournament, each team plays exactly one home game and exactly one away game with each other team (n(nβ-β1) games in total). The team, that plays the home game, traditionally plays in its home kit. The team that plays an away game plays in its away kit. However, if two teams has the kits of the same color, they cannot be distinguished. In this case the away team plays in its home kit.Calculate how many games in the described tournament each team plays in its home kit and how many games it plays in its away kit.InputThe first line contains a single integer n (2ββ€βnββ€β105) β the number of teams. Next n lines contain the description of the teams. The i-th line contains two space-separated numbers xi, yi (1ββ€βxi,βyiββ€β105;Β xiββ βyi) β the color numbers for the home and away kits of the i-th team.OutputFor each team, print on a single line two space-separated integers β the number of games this team is going to play in home and away kits, correspondingly. Print the answers for the teams in the order they appeared in the input.ExamplesInput21 22 1Output2 02 0Input31 22 11 3Output3 14 02 2 | Input21 22 1 | Output2 02 0 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', '*1200'] |
A. Choosing Teamstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?InputThe first line contains two integers, n and k (1ββ€βnββ€β2000;Β 1ββ€βkββ€β5). The next line contains n integers: y1,βy2,β...,βyn (0ββ€βyiββ€β5), where yi shows the number of times the i-th person participated in the ACM ICPC world championship.OutputPrint a single number β the answer to the problem.ExamplesInput5 20 4 5 1 0Output1Input6 40 1 2 3 4 5Output0Input6 50 0 0 0 0 0Output2NoteIn the first sample only one team could be made: the first, the fourth and the fifth participants.In the second sample no teams could be created.In the third sample two teams could be created. Any partition into two teams fits. | Input5 20 4 5 1 0 | Output1 | 1 second | 256 megabytes | ['greedy', 'implementation', 'sortings', '*800'] |
E. Chemistry Experimenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day two students, Grisha and Diana, found themselves in the university chemistry lab. In the lab the students found n test tubes with mercury numbered from 1 to n and decided to conduct an experiment.The experiment consists of q steps. On each step, one of the following actions occurs: Diana pours all the contents from tube number pi and then pours there exactly xi liters of mercury. Let's consider all the ways to add vi liters of water into the tubes; for each way let's count the volume of liquid (water and mercury) in the tube with water with maximum amount of liquid; finally let's find the minimum among counted maximums. That is the number the students want to count. At that, the students don't actually pour the mercury. They perform calculations without changing the contents of the tubes. Unfortunately, the calculations proved to be too complex and the students asked you to help them. Help them conduct the described experiment.InputThe first line contains two integers n and q (1ββ€βn,βqββ€β105) β the number of tubes ans the number of experiment steps. The next line contains n space-separated integers: h1,βh2,β...,βhn (0ββ€βhiββ€β109), where hi is the volume of mercury in the Ρ-th tube at the beginning of the experiment.The next q lines contain the game actions in the following format: A line of form "1 pi xi" means an action of the first type (1ββ€βpiββ€βn;Β 0ββ€βxiββ€β109). A line of form "2 vi" means an action of the second type (1ββ€βviββ€β1015). It is guaranteed that there is at least one action of the second type. It is guaranteed that all numbers that describe the experiment are integers.OutputFor each action of the second type print the calculated value. The answer will be considered correct if its relative or absolute error doesn't exceed 10β-β4.ExamplesInput3 31 2 02 21 2 12 3Output1.500001.66667Input4 51 3 0 12 32 11 3 22 32 4Output1.666671.000002.333332.66667 | Input3 31 2 02 21 2 12 3 | Output1.500001.66667 | 4 seconds | 256 megabytes | ['binary search', 'data structures', 'ternary search', '*2200'] |
D. Random Tasktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers nβ+β1, nβ+β2, ..., 2Β·n there are exactly m numbers which binary representation contains exactly k digits one".The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.InputThe first line contains two space-separated integers, m and k (0ββ€βmββ€β1018; 1ββ€βkββ€β64).OutputPrint the required number n (1ββ€βnββ€β1018). If there are multiple answers, print any of them.ExamplesInput1 1Output1Input3 2Output5 | Input1 1 | Output1 | 1 second | 256 megabytes | ['binary search', 'bitmasks', 'combinatorics', 'dp', 'math', '*2100'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.