problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
β | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
A. Case of Matryoshkastime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art.The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be nested in a matryoshka with a higher number, two matryoshkas can not be directly nested in the same doll, but there may be chain nestings, for example, 1βββ2βββ4βββ5. In one second, you can perform one of the two following operations: Having a matryoshka a that isn't nested in any other matryoshka and a matryoshka b, such that b doesn't contain any other matryoshka and is not nested in any other matryoshka, you may put a in b; Having a matryoshka a directly contained in matryoshka b, such that b is not nested in any other matryoshka, you may get a out of b. According to the modern aesthetic norms the matryoshka dolls on display were assembled in a specific configuration, i.e. as several separate chains of nested matryoshkas, but the criminal, following the mysterious plan, took out all the dolls and assembled them into a single large chain (1βββ2βββ...βββn). In order to continue the investigation Andrewid needs to know in what minimum time it is possible to perform this action.InputThe first line contains integers n (1ββ€βnββ€β105) and k (1ββ€βkββ€β105) β the number of matryoshkas and matryoshka chains in the initial configuration.The next k lines contain the descriptions of the chains: the i-th line first contains number mi (1ββ€βmiββ€βn), and then mi numbers ai1,βai2,β...,βaimi β the numbers of matryoshkas in the chain (matryoshka ai1 is nested into matryoshka ai2, that is nested into matryoshka ai3, and so on till the matryoshka aimi that isn't nested into any other matryoshka).It is guaranteed that m1β+βm2β+β...β+βmkβ=βn, the numbers of matryoshkas in all the chains are distinct, in each chain the numbers of matryoshkas follow in the ascending order.OutputIn the single line print the minimum number of seconds needed to assemble one large chain from the initial configuration.ExamplesInput3 22 1 21 3Output1Input7 33 1 3 72 2 52 4 6Output10NoteIn the first sample test there are two chains: 1βββ2 and 3. In one second you can nest the first chain into the second one and get 1βββ2βββ3.In the second sample test you need to disassemble all the three chains into individual matryoshkas in 2 + 1 + 1 = 4 seconds and then assemble one big chain in 6 seconds. | Input3 22 1 21 3 | Output1 | 2 seconds | 256 megabytes | ['implementation', '*1500'] |
B. Ohana Cleans Uptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOhana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.Return the maximum number of rows that she can make completely clean.InputThe first line of input will be a single integer n (1ββ€βnββ€β100).The next n lines will describe the state of the room. The i-th line will contain a binary string with n characters denoting the state of the i-th row of the room. The j-th character on this line is '1' if the j-th square in the i-th row is clean, and '0' if it is dirty.OutputThe output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.ExamplesInput40101100011110101Output2Input3111111111Output3NoteIn the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.In the second sample, everything is already clean, so Ohana doesn't need to do anything. | Input40101100011110101 | Output2 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'strings', '*1200'] |
A. Kyoya and Photobookstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the photos in the booklet in order. He now wants to sell some "special edition" photobooks, each with one extra photo inserted anywhere in the book. He wants to make as many distinct photobooks as possible, so he can make more money. He asks Haruhi, how many distinct photobooks can he make by inserting one extra photo into the photobook he already has?Please help Haruhi solve this problem.InputThe first line of input will be a single string s (1ββ€β|s|ββ€β20). String s consists only of lowercase English letters. OutputOutput a single integer equal to the number of distinct photobooks Kyoya Ootori can make.ExamplesInputaOutput51InputhiOutput76NoteIn the first case, we can make 'ab','ac',...,'az','ba','ca',...,'za', and 'aa', producing a total of 51 distinct photo booklets. | Inputa | Output51 | 2 seconds | 256 megabytes | ['brute force', 'math', 'strings', '*900'] |
E. Kyoya and Traintime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKyoya Ootori wants to take the train to get to school. There are n train stations and m one-way train lines going between various stations. Kyoya is currently at train station 1, and the school is at station n. To take a train, he must pay for a ticket, and the train also takes a certain amount of time. However, the trains are not perfect and take random amounts of time to arrive at their destination. If Kyoya arrives at school strictly after t time units, he will have to pay a fine of x.Each train line is described by a ticket price, and a probability distribution on the time the train takes. More formally, train line i has ticket cost ci, and a probability distribution pi,βk which denotes the probability that this train will take k time units for all 1ββ€βkββ€βt. Amounts of time that each of the trains used by Kyouya takes are mutually independent random values (moreover, if Kyoya travels along the same train more than once, it is possible for the train to take different amounts of time and those amounts are also independent one from another). Kyoya wants to get to school by spending the least amount of money in expectation (for the ticket price plus possible fine for being late). Of course, Kyoya has an optimal plan for how to get to school, and every time he arrives at a train station, he may recalculate his plan based on how much time he has remaining. What is the expected cost that Kyoya will pay to get to school if he moves optimally?InputThe first line of input contains four integers n,βm,βt,βx (2βββ€ββnβββ€β50, 1ββ€βmββ€β100, 1ββ€βtββ€β20β000, 0ββ€βxββ€β106).The next 2m lines contain the description of the trains. The 2i-th line will have 3 integers ai,βbi,βci, representing a one way train from station ai to bi with ticket cost ci (1ββ€βai,βbiββ€βn, aiββ βbi, 0ββ€βciββ€β106). There will always be at least one path from any station to the school. The (2iβ+β1)-th line will contain t integers, pi,β1,βpi,β2,β...,βpi,βt where pi,βkβ/β100000 is the probability that this train will take k units of time to traverse (0ββ€βpi,βkββ€β100β000 for 1ββ€βkββ€βt, ). It is guaranteed that there is no more than one train between each pair of platforms in each of the directions.OutputPrint a single real number that is equal to an optimal expected cost of getting to school. The answer will be considered correct if its relative or absolute error doesn't exceed 10β-β6.ExamplesInput4 4 5 11 2 050000 0 50000 0 02 3 010000 0 0 0 900003 4 0100000 0 0 0 02 4 00 0 0 50000 50000Output0.7000000000Input4 4 5 11 2 10050000 0 50000 0 02 3 10010000 0 0 0 900003 4 100100000 0 0 0 02 4 1000 0 0 50000 50000Output200.7500000000NoteThe optimal strategy in the first case is as follows:First, travel along first train line. With probability 1β/β2 Kyoya will take 1 time unit. Otherwise, Kyoya will take 3 time units.If the train takes 1 time unit, travel along the 4th train line. Kyoya will make it to school in time with probability 1β/β2. Otherwise, if the train takes 3 time units, travel along the 2nd train line. Kyoya will make it to school in time with probability 1β/β10.Since the cost of all train lines are zero, we can just look at the probability that Kyoya will incur the penalty. The probability that Kyoya will have to pay the penalty is 1β/β2βΓβ1β/β2β+β1β/β2βΓβ9β/β10β=β7β/β10. We can show that no other strategy is strictly better.The optimal strategy in the second case is to travel along 1βββ2βββ4 no matter what. Kyoya will incur the penalty with probability 3β/β4, and the cost of the trains is 200, thus the expected cost is 200.75. | Input4 4 5 11 2 050000 0 50000 0 02 3 010000 0 0 0 900003 4 0100000 0 0 0 02 4 00 0 0 50000 50000 | Output0.7000000000 | 8 seconds | 512 megabytes | ['dp', 'fft', 'graphs', 'math', 'probabilities', '*3200'] |
D. Nudist Beachtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNudist Beach is planning a military operation to attack the Life Fibers. In this operation, they will attack and capture several cities which are currently under the control of the Life Fibers.There are n cities, labeled from 1 to n, and m bidirectional roads between them. Currently, there are Life Fibers in every city. In addition, there are k cities that are fortresses of the Life Fibers that cannot be captured under any circumstances. So, the Nudist Beach can capture an arbitrary non-empty subset of cities with no fortresses.After the operation, Nudist Beach will have to defend the captured cities from counterattack. If they capture a city and it is connected to many Life Fiber controlled cities, it will be easily defeated. So, Nudist Beach would like to capture a set of cities such that for each captured city the ratio of Nudist Beach controlled neighbors among all neighbors of that city is as high as possible. More formally, they would like to capture a non-empty set of cities S with no fortresses of Life Fibers. The strength of a city is defined as (number of neighbors of x in S) / (total number of neighbors of x). Here, two cities are called neighbors if they are connnected with a road. The goal is to maximize the strength of the weakest city in S.Given a description of the graph, and the cities with fortresses, find a non-empty subset that maximizes the strength of the weakest city. InputThe first line of input contains three integers n,βm,βk (2βββ€ββnβββ€β100β000, 1ββ€βmββ€β100β000, 1ββ€βkββ€βnβ-β1).The second line of input contains k integers, representing the cities with fortresses. These cities will all be distinct. The next m lines contain the roads. The i-th of these lines will have 2 integers ai,βbi (1ββ€βai,βbiββ€βn, aiββ βbi). Every city will have at least one road adjacent to it.There is no more than one road between each pair of the cities.OutputThe first line should contain an integer r, denoting the size of an optimum set (1ββ€βrββ€βnβ-βk). The second line should contain r integers, denoting the cities in the set. Cities may follow in an arbitrary order. This line should not contain any of the cities with fortresses.If there are multiple possible answers, print any of them.ExamplesInput9 8 43 9 6 81 21 31 41 52 62 72 82 9Output31 4 5Input10 8 22 91 32 94 55 66 77 88 1010 4Output81 5 4 8 10 6 3 7NoteThe first example case achieves a strength of 1/2. No other subset is strictly better.The second example case achieves a strength of 1. Note that the subset doesn't necessarily have to be connected. | Input9 8 43 9 6 81 21 31 41 52 62 72 82 9 | Output31 4 5 | 2 seconds | 256 megabytes | ['binary search', 'graphs', 'greedy', '*2300'] |
C. Love Trianglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1β000β000β007.InputThe first line of input will contain two integers n,βm (3ββ€βnββ€β100β000, 0ββ€βmββ€β100β000).The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai,βbi,βci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1ββ€βai,βbiββ€βn, aiββ βbi, ).Each pair of people will be described no more than once.OutputPrint a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1β000β000β007. ExamplesInput3 0Output4Input4 41 2 12 3 13 4 04 1 0Output1Input4 41 2 12 3 13 4 04 1 1Output0NoteIn the first sample, the four ways are to: Make everyone love each other Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other. | Input3 0 | Output4 | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', '*2200'] |
B. Kyoya and Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define the permutation of length n as an array pβ=β[p1,βp2,β...,βpn] consisting of n distinct integers from range from 1 to n. We say that this permutation maps value 1 into the value p1, value 2 into the value p2 and so on.Kyota Ootori has just learned about cyclic representation of a permutation. A cycle is a sequence of numbers such that each element of this sequence is being mapped into the next element of this sequence (and the last element of the cycle is being mapped into the first element of the cycle). The cyclic representation is a representation of p as a collection of cycles forming p. For example, permutation pβ=β[4,β1,β6,β2,β5,β3] has a cyclic representation that looks like (142)(36)(5) because 1 is replaced by 4, 4 is replaced by 2, 2 is replaced by 1, 3 and 6 are swapped, and 5 remains in place. Permutation may have several cyclic representations, so Kyoya defines the standard cyclic representation of a permutation as follows. First, reorder the elements within each cycle so the largest element is first. Then, reorder all of the cycles so they are sorted by their first element. For our example above, the standard cyclic representation of [4,β1,β6,β2,β5,β3] is (421)(5)(63).Now, Kyoya notices that if we drop the parenthesis in the standard cyclic representation, we get another permutation! For instance, [4,β1,β6,β2,β5,β3] will become [4,β2,β1,β5,β6,β3].Kyoya notices that some permutations don't change after applying operation described above at all. He wrote all permutations of length n that do not change in a list in lexicographic order. Unfortunately, his friend Tamaki Suoh lost this list. Kyoya wishes to reproduce the list and he needs your help. Given the integers n and k, print the permutation that was k-th on Kyoya's list.InputThe first line will contain two integers n, k (1ββ€βnββ€β50, 1ββ€βkββ€βmin{1018,βl} where l is the length of the Kyoya's list).OutputPrint n space-separated integers, representing the permutation that is the answer for the question. ExamplesInput4 3Output1 3 2 4Input10 1Output1 2 3 4 5 6 7 8 9 10NoteThe standard cycle representation is (1)(32)(4), which after removing parenthesis gives us the original permutation. The first permutation on the list would be [1,β2,β3,β4], while the second permutation would be [1,β2,β4,β3]. | Input4 3 | Output1 3 2 4 | 2 seconds | 256 megabytes | ['binary search', 'combinatorics', 'constructive algorithms', 'greedy', 'implementation', 'math', '*1900'] |
A. Kyoya and Colored Ballstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color iβ+β1 for all i from 1 to kβ-β1. Now he wonders how many different ways this can happen. InputThe first line of input will have one integer k (1ββ€βkββ€β1000) the number of colors.Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1ββ€βciββ€β1000).The total number of balls doesn't exceed 1000.OutputA single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1β000β000β007. ExamplesInput3221Output3Input41234Output1680NoteIn the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are: 1 2 1 2 31 1 2 2 32 1 1 2 3 | Input3221 | Output3 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', '*1500'] |
E. Vanya and Bracketstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya is doing his maths homework. He has an expression of form , where x1,βx2,β...,βxn are digits from 1 to 9, and sign represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.InputThe first line contains expression s (1ββ€β|s|ββ€β5001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs β+β and β*β. The number of signs β*β doesn't exceed 15.OutputIn the first line print the maximum possible value of an expression.ExamplesInput3+5*7+8*4Output303Input2+3*5Output25Input3*4*5Output60NoteNote to the first sample test. 3β+β5β*β(7β+β8)β*β4β=β303.Note to the second sample test. (2β+β3)β*β5β=β25.Note to the third sample test. (3β*β4)β*β5β=β60 (also many other variants are valid, for instance, (3)β*β4β*β5β=β60). | Input3+5*7+8*4 | Output303 | 1 second | 256 megabytes | ['brute force', 'dp', 'expression parsing', 'greedy', 'implementation', 'strings', '*2100'] |
D. Vanya and Trianglestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.InputThe first line contains integer n (1ββ€βnββ€β2000) β the number of the points painted on the plane. Next n lines contain two integers each xi,βyi (β-β100ββ€βxi,βyiββ€β100) β the coordinates of the i-th point. It is guaranteed that no two given points coincide.OutputIn the first line print an integer β the number of triangles with the non-zero area among the painted points.ExamplesInput40 01 12 02 2Output3Input30 01 12 0Output1Input11 1Output0NoteNote to the first sample test. There are 3 triangles formed: (0,β0)β-β(1,β1)β-β(2,β0); (0,β0)β-β(2,β2)β-β(2,β0); (1,β1)β-β(2,β2)β-β(2,β0).Note to the second sample test. There is 1 triangle formed: (0,β0)β-β(1,β1)β-β(2,β0).Note to the third sample test. A single point doesn't form a single triangle. | Input40 01 12 02 2 | Output3 | 4 seconds | 512 megabytes | ['brute force', 'combinatorics', 'data structures', 'geometry', 'math', 'sortings', '*1900'] |
C. Vanya and Scalestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya has a scales for weighing loads and weights of masses w0,βw1,βw2,β...,βw100 grams where w is some integer not less than 2 (exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using the given weights, if the weights can be put on both pans of the scales. Formally speaking, your task is to determine whether it is possible to place an item of mass m and some weights on the left pan of the scales, and some weights on the right pan of the scales so that the pans of the scales were in balance.InputThe first line contains two integers w,βm (2ββ€βwββ€β109, 1ββ€βmββ€β109) β the number defining the masses of the weights and the mass of the item.OutputPrint word 'YES' if the item can be weighted and 'NO' if it cannot.ExamplesInput3 7OutputYESInput100 99OutputYESInput100 50OutputNONoteNote to the first sample test. One pan can have an item of mass 7 and a weight of mass 3, and the second pan can have two weights of masses 9 and 1, correspondingly. Then 7β+β3β=β9β+β1.Note to the second sample test. One pan of the scales can have an item of mass 99 and the weight of mass 1, and the second pan can have the weight of mass 100.Note to the third sample test. It is impossible to measure the weight of the item in the manner described in the input. | Input3 7 | OutputYES | 1 second | 256 megabytes | ['brute force', 'dp', 'greedy', 'math', 'meet-in-the-middle', 'number theory', '*1900'] |
B. Vanya and Bookstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya got an important task β he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.Vanya wants to know how many digits he will have to write down as he labels the books.InputThe first line contains integer n (1ββ€βnββ€β109) β the number of books in the library.OutputPrint the number of digits needed to number all the books.ExamplesInput13Output17Input4Output4NoteNote to the first test. The books get numbers 1,β2,β3,β4,β5,β6,β7,β8,β9,β10,β11,β12,β13, which totals to 17 digits.Note to the second sample. The books get numbers 1,β2,β3,β4, which totals to 4 digits. | Input13 | Output17 | 1 second | 256 megabytes | ['implementation', 'math', '*1200'] |
A. Vanya and Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.InputThe first line contains integer n (1ββ€βnββ€β100) β the number of rectangles.Each of the following n lines contains four integers x1,βy1,βx2,βy2 (1ββ€βx1ββ€βx2ββ€β100, 1ββ€βy1ββ€βy2ββ€β100), where x1 and y1 are the number of the column and row of the lower left cell and x2 and y2 are the number of the column and row of the upper right cell of a rectangle.OutputIn a single line print the sum of all values in the cells of the table.ExamplesInput21 1 2 32 2 3 3Output10Input21 1 3 31 1 3 3Output18NoteNote to the first sample test:Values of the table in the first three rows and columns will be as follows:121121110So, the sum of values will be equal to 10.Note to the second sample test:Values of the table in the first three rows and columns will be as follows:222222222So, the sum of values will be equal to 18. | Input21 1 2 32 2 3 3 | Output10 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1000'] |
E. GukiZ and GukiZianatime limit per test10 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor GukiZ was playing with arrays again and accidentally discovered new function, which he called GukiZiana. For given array a, indexed with integers from 1 to n, and number y, GukiZiana(a,βy) represents maximum value of jβ-βi, such that ajβ=βaiβ=βy. If there is no y as an element in a, then GukiZiana(a,βy) is equal to β-β1. GukiZ also prepared a problem for you. This time, you have two types of queries: First type has form 1 l r x and asks you to increase values of all ai such that lββ€βiββ€βr by the non-negative integer x. Second type has form 2 y and asks you to find value of GukiZiana(a,βy). For each query of type 2, print the answer and make GukiZ happy!InputThe first line contains two integers n, q (1ββ€βnββ€β5β*β105,β1ββ€βqββ€β5β*β104), size of array a, and the number of queries. The second line contains n integers a1,βa2,β... an (1ββ€βaiββ€β109), forming an array a. Each of next q lines contain either four or two numbers, as described in statement:If line starts with 1, then the query looks like 1 l r x (1ββ€βlββ€βrββ€βn, 0ββ€βxββ€β109), first type query.If line starts with 2, then th query looks like 2 y (1ββ€βyββ€β109), second type query.OutputFor each query of type 2, print the value of GukiZiana(a,βy), for y value for that query.ExamplesInput4 31 2 3 41 1 2 11 1 1 12 3Output2Input2 31 21 2 2 12 32 4Output0-1 | Input4 31 2 3 41 1 2 11 1 1 12 3 | Output2 | 10 seconds | 256 megabytes | ['binary search', 'data structures', 'implementation', '*2500'] |
D. GukiZ and Binary Operationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe all know that GukiZ often plays with arrays. Now he is thinking about this problem: how many arrays a, of length n, with non-negative elements strictly less then 2l meet the following condition: ? Here operation means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equivalent to &), operation means bitwise OR (in Pascal it is equivalent to , in C/C++/Java/Python it is equivalent to |). Because the answer can be quite large, calculate it modulo m. This time GukiZ hasn't come up with solution, and needs you to help him!InputFirst and the only line of input contains four integers n, k, l, m (2ββ€βnββ€β1018, 0ββ€βkββ€β1018, 0ββ€βlββ€β64, 1ββ€βmββ€β109β+β7).OutputIn the single line print the number of arrays satisfying the condition above modulo m.ExamplesInput2 1 2 10Output3Input2 1 1 3Output1Input3 3 2 10Output9NoteIn the first sample, satisfying arrays are {1,β1},β{3,β1},β{1,β3}.In the second sample, only satisfying array is {1,β1}.In the third sample, satisfying arrays are {0,β3,β3},β{1,β3,β2},β{1,β3,β3},β{2,β3,β1},β{2,β3,β3},β{3,β3,β0},β{3,β3,β1},β{3,β3,β2},β{3,β3,β3}. | Input2 1 2 10 | Output3 | 1 second | 256 megabytes | ['combinatorics', 'implementation', 'math', 'matrices', 'number theory', '*2100'] |
C. GukiZ hates Boxestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1ββ€βiββ€βn) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way. Students are working simultaneously. At time 0, all students are located left of the first pile. It takes one second for every student to move from this position to the first pile, and after that, every student must start performing sequence of two possible operations, each taking one second to complete. Possible operations are: If iββ βn, move from pile i to pile iβ+β1; If pile located at the position of student is not empty, remove one box from it.GukiZ's students aren't smart at all, so they need you to tell them how to remove boxes before professor comes (he is very impatient man, and doesn't want to wait). They ask you to calculate minumum time t in seconds for which they can remove all the boxes from GukiZ's way. Note that students can be positioned in any manner after t seconds, but all the boxes must be removed.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β105), the number of piles of boxes and the number of GukiZ's students. The second line contains n integers a1,βa2,β... an (0ββ€βaiββ€β109) where ai represents the number of boxes on i-th pile. It's guaranteed that at least one pile of is non-empty.OutputIn a single line, print one number, minimum time needed to remove all the boxes in seconds.ExamplesInput2 11 1Output4Input3 21 0 2Output5Input4 1003 4 5 4Output5NoteFirst sample: Student will first move to the first pile (1 second), then remove box from first pile (1 second), then move to the second pile (1 second) and finally remove the box from second pile (1 second).Second sample: One of optimal solutions is to send one student to remove a box from the first pile and a box from the third pile, and send another student to remove a box from the third pile. Overall, 5 seconds.Third sample: With a lot of available students, send three of them to remove boxes from the first pile, four of them to remove boxes from the second pile, five of them to remove boxes from the third pile, and four of them to remove boxes from the fourth pile. Process will be over in 5 seconds, when removing the boxes from the last pile is finished. | Input2 11 1 | Output4 | 2 seconds | 256 megabytes | ['binary search', 'greedy', '*2200'] |
B. ZgukistringZtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?InputThe first line contains string a, the second line contains string b, and the third line contains string c (1ββ€β|a|,β|b|,β|c|ββ€β105, where |s| denotes the length of string s).All three strings consist only of lowercase English letters. It is possible that b and c coincide.OutputFind one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.ExamplesInputaaaabOutputaaaInputpozdravstaklenidodirinistedobriOutputnisteaadddiiklooprrvzInputabbbaacccaabacaOutputababacabccNoteIn the third sample, this optimal solutions has three non-overlaping substrings equal to either b or c on positions 1βββ2 (ab), 3βββ4 (ab), 5βββ7 (aca). In this sample, there exist many other optimal solutions, one of them would be acaababbcc. | Inputaaaab | Outputaaa | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', 'strings', '*1800'] |
A. GukiZ and Contesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. He thinks that each student will take place equal to . In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position. GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.InputThe first line contains integer n (1ββ€βnββ€β2000), number of GukiZ's students. The second line contains n numbers a1,βa2,β... an (1ββ€βaiββ€β2000) where ai is the rating of i-th student (1ββ€βiββ€βn).OutputIn a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.ExamplesInput31 3 3Output3 1 1Input11Output1Input53 5 3 4 5Output4 1 4 3 1NoteIn the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.In the second sample, first student is the only one on the contest.In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position. | Input31 3 3 | Output3 1 1 | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'sortings', '*800'] |
E. Brackets in Implicationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImplication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false. Implication is written by using character '', and the arguments and the result of the implication are written as '0' (false) and '1' (true). According to the definition of the implication: When a logical expression contains multiple implications, then when there are no brackets, it will be calculated from left to fight. For example,. When there are brackets, we first calculate the expression in brackets. For example,.For the given logical expression determine if it is possible to place there brackets so that the value of a logical expression is false. If it is possible, your task is to find such an arrangement of brackets.InputThe first line contains integer n (1ββ€βnββ€β100β000) β the number of arguments in a logical expression.The second line contains n numbers a1,βa2,β...,βan (), which means the values of arguments in the expression in the order they occur.OutputPrint "NO" (without the quotes), if it is impossible to place brackets in the expression so that its value was equal to 0.Otherwise, print "YES" in the first line and the logical expression with the required arrangement of brackets in the second line.The expression should only contain characters '0', '1', '-' (character with ASCII code 45), '>' (character with ASCII code 62), '(' and ')'. Characters '-' and '>' can occur in an expression only paired like that: ("->") and represent implication. The total number of logical arguments (i.e. digits '0' and '1') in the expression must be equal to n. The order in which the digits follow in the expression from left to right must coincide with a1,βa2,β...,βan.The expression should be correct. More formally, a correct expression is determined as follows: Expressions "0", "1" (without the quotes) are correct. If v1, v2 are correct, then v1->v2 is a correct expression. If v is a correct expression, then (v) is a correct expression. The total number of characters in the resulting expression mustn't exceed 106.If there are multiple possible answers, you are allowed to print any of them.ExamplesInput40 1 1 0OutputYES(((0)->1)->(1->0))Input21 1OutputNOInput10OutputYES0 | Input40 1 1 0 | OutputYES(((0)->1)->(1->0)) | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'math', '*2200'] |
D. Regular Bridgetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.InputThe single line of the input contains integer k (1ββ€βkββ€β100) β the required degree of the vertices of the regular graph.OutputPrint "NO" (without quotes), if such graph doesn't exist. Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines.The description of the made graph must start with numbers n and m β the number of vertices and edges respectively. Each of the next m lines must contain two integers, a and b (1ββ€βa,βbββ€βn, aββ βb), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order.The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges). ExamplesInput1OutputYES2 11 2NoteIn the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge. | Input1 | OutputYES2 11 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'implementation', '*1900'] |
C. Divisibility by Eighttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes.Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-negative integer, doesn't have leading zeroes and is divisible by 8. After the removing, it is forbidden to rearrange the digits.If a solution exists, you should print it.InputThe single line of the input contains a non-negative integer n. The representation of number n doesn't contain any leading zeroes and its length doesn't exceed 100 digits. OutputPrint "NO" (without quotes), if there is no such way to remove some digits from number n. Otherwise, print "YES" in the first line and the resulting number after removing digits from number n in the second line. The printed number must be divisible by 8.If there are multiple possible answers, you may print any of them.ExamplesInput3454OutputYES344Input10OutputYES0Input111111OutputNO | Input3454 | OutputYES344 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'math', '*1500'] |
B. Preparing Olympiadtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made.A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must be at least l and at most r. Also, you think that the difference between difficulties of the easiest and the hardest of the chosen problems must be at least x.Find the number of ways to choose a problemset for the contest.InputThe first line contains four integers n, l, r, x (1ββ€βnββ€β15, 1ββ€βlββ€βrββ€β109, 1ββ€βxββ€β106) β the number of problems you have, the minimum and maximum value of total difficulty of the problemset and the minimum difference in difficulty between the hardest problem in the pack and the easiest one, respectively.The second line contains n integers c1,βc2,β...,βcn (1ββ€βciββ€β106) β the difficulty of each problem.OutputPrint the number of ways to choose a suitable problemset for the contest. ExamplesInput3 5 6 11 2 3Output2Input4 40 50 1010 20 30 25Output2Input5 25 35 1010 10 20 10 20Output6NoteIn the first example two sets are suitable, one consisting of the second and third problem, another one consisting of all three problems.In the second example, two sets of problems are suitable β the set of problems with difficulties 10 and 30 as well as the set of problems with difficulties 20 and 30.In the third example any set consisting of one problem of difficulty 10 and one problem of difficulty 20 is suitable. | Input3 5 6 11 2 3 | Output2 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', '*1400'] |
A. Two Substringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).InputThe only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.OutputPrint "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.ExamplesInputABAOutputNOInputBACFABOutputYESInputAXBYBXAOutputNONoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA". | InputABA | OutputNO | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', 'implementation', 'strings', '*1500'] |
H. Degenerate Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe determinant of a matrix 2βΓβ2 is defined as follows:A matrix is called degenerate if its determinant is equal to zero. The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements.You are given a matrix . Consider any degenerate matrix B such that norm ||Aβ-βB|| is minimum possible. Determine ||Aβ-βB||.InputThe first line contains two integers a and b (|a|,β|b|ββ€β109), the elements of the first row of matrix A. The second line contains two integers c and d (|c|,β|d|ββ€β109) the elements of the second row of matrix A.OutputOutput a single real number, the minimum possible value of ||Aβ-βB||. Your answer is considered to be correct if its absolute or relative error does not exceed 10β-β9.ExamplesInput1 23 4Output0.2000000000Input1 00 1Output0.5000000000NoteIn the first sample matrix B is In the second sample matrix B is | Input1 23 4 | Output0.2000000000 | 1 second | 256 megabytes | ['binary search', 'math', '*2100'] |
G. Happy Linetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDo you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of n Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person a stands just behind person b, then person a can pay person b 1 dollar, then a and b get swapped. Of course, if person a has zero dollars, he can not swap places with person b.Residents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them.Can you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.InputThe first line contains integer n (1ββ€βnββ€β200β000) β the number of residents who stand in the line.The second line contains n space-separated integers ai (0ββ€βaiββ€β109), where ai is the number of Berland dollars of a man standing on the i-th position in the line. The positions are numbered starting from the end of the line. OutputIf it is impossible to make all the residents happy, print ":(" without the quotes. Otherwise, print in the single line n space-separated integers, the i-th of them must be equal to the number of money of the person on position i in the new line. If there are multiple answers, print any of them.ExamplesInput211 8Output9 10 Input510 9 7 10 6Output:(Input312 3 3Output4 4 10 NoteIn the first sample two residents should swap places, after that the first resident has 10 dollars and he is at the head of the line and the second resident will have 9 coins and he will be at the end of the line. In the second sample it is impossible to achieve the desired result.In the third sample the first person can swap with the second one, then they will have the following numbers of dollars: 4 11 3, then the second person (in the new line) swaps with the third one, and the resulting numbers of dollars will equal to: 4 4 10. In this line everybody will be happy. | Input211 8 | Output9 10 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'sortings', '*2200'] |
F. Yura and Developerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYura has a team of k developers and a list of n tasks numbered from 1 to n. Yura is going to choose some tasks to be done this week. Due to strange Looksery habits the numbers of chosen tasks should be a segment of consecutive integers containing no less than 2 numbers, i. e. a sequence of form l,βlβ+β1,β...,βr for some 1ββ€βlβ<βrββ€βn. Every task i has an integer number ai associated with it denoting how many man-hours are required to complete the i-th task. Developers are not self-confident at all, and they are actually afraid of difficult tasks. Knowing that, Yura decided to pick up a hardest task (the one that takes the biggest number of man-hours to be completed, among several hardest tasks with same difficulty level he chooses arbitrary one) and complete it on his own. So, if tasks with numbers [l,βr] are chosen then the developers are left with rβ-βl tasks to be done by themselves. Every developer can spend any integer amount of hours over any task, but when they are done with the whole assignment there should be exactly ai man-hours spent over the i-th task. The last, but not the least problem with developers is that one gets angry if he works more than another developer. A set of tasks [l,βr] is considered good if it is possible to find such a distribution of work that allows to complete all the tasks and to have every developer working for the same amount of time (amount of work performed by Yura doesn't matter for other workers as well as for him).For example, let's suppose that Yura have chosen tasks with following difficulties: aβ=β[1,β2,β3,β4], and he has three developers in his disposal. He takes the hardest fourth task to finish by himself, and the developers are left with tasks with difficulties [1,β2,β3]. If the first one spends an hour on the first task and an hour on the third one, the second developer spends two hours on the second task and the third developer spends two hours on the third task, then they are done, since every developer worked exactly for two hours and every task has been worked over for the required amount of time. As another example, if the first task required two hours instead of one to be completed then it would be impossible to assign the tasks in a way described above. Besides work, Yura is fond of problem solving. He wonders how many pairs (l,βr) (1ββ€βlβ<βrββ€βn) exists such that a segment [l,βr] is good? Yura has already solved this problem, but he has no time to write the code. Please, help Yura and implement the solution for this problem. InputThe first line of input contains two positive integers: n and k (1ββ€βnββ€β300β000,β1ββ€βkββ€β1β000β000), the number of tasks in the list and the number of developers in Yura's disposal. The second line contains n integers ai (1ββ€βaiββ€β109). OutputOutput a single integer β the number of pairs (l,βr) satisfying the conditions from the statement.ExamplesInput4 31 2 3 4Output3Input4 24 4 7 4Output6NoteIn the first sample there are three good segments: [1;3] β the hardest task requires 3 man-hours, so there are tasks left that require 1 and 2 man-hours. A solution is to make first developer work on the first task for an hour, while second and third developers work on the second task. Each developer works exactly one hour. [1;4] β the hardest task requires 4 man-hours, so there are tasks left that require 1, 2 and 3 man-hours. If the first developer spends an hour on the first task and an hour on the third one, the second developer spends two hours on the second task and the third developer spends two hours on the third task, then they are done, since every developer worked exactly for two hours. [3;4] β the hardest task requires 4 man-hours, so there is only one task left that requires 3 man-hours. A solution is to make each developer work for an hour. | Input4 31 2 3 4 | Output3 | 1 second | 256 megabytes | ['data structures', 'divide and conquer', '*2800'] |
E. Sasha Circletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerlanders like to eat cones after a hard day. Misha Square and Sasha Circle are local authorities of Berland. Each of them controls its points of cone trade. Misha has n points, Sasha β m. Since their subordinates constantly had conflicts with each other, they decided to build a fence in the form of a circle, so that the points of trade of one businessman are strictly inside a circle, and points of the other one are strictly outside. It doesn't matter which of the two gentlemen will have his trade points inside the circle.Determine whether they can build a fence or not.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β10000), numbers of Misha's and Sasha's trade points respectively.The next n lines contains pairs of space-separated integers Mx,βMy (β-β104ββ€βMx,βMyββ€β104), coordinates of Misha's trade points.The next m lines contains pairs of space-separated integers Sx,βSy (β-β104ββ€βSx,βSyββ€β104), coordinates of Sasha's trade points.It is guaranteed that all nβ+βm points are distinct.OutputThe only output line should contain either word "YES" without quotes in case it is possible to build a such fence or word "NO" in the other case.ExamplesInput2 2-1 01 00 -10 1OutputNOInput4 41 00 1-1 00 -11 1-1 1-1 -11 -1OutputYESNoteIn the first sample there is no possibility to separate points, because any circle that contains both points (β-β1,β0),β(1,β0) also contains at least one point from the set (0,ββ-β1),β(0,β1), and vice-versa: any circle that contains both points (0,ββ-β1),β(0,β1) also contains at least one point from the set (β-β1,β0),β(1,β0)In the second sample one of the possible solution is shown below. Misha's points are marked with red colour and Sasha's are marked with blue. | Input2 2-1 01 00 -10 1 | OutputNO | 2 seconds | 256 megabytes | ['geometry', 'math', '*2700'] |
D. Haar Featurestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.Let's consider a rectangular image that is represented with a table of size nβΓβm. The table elements are integers that specify the brightness of each pixel in the image.A feature also is a rectangular table of size nβΓβm. Each cell of a feature is painted black or white.To calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of Wβ-βB, where W is the total brightness of the pixels in the image, covered with white feature cells, and B is the total brightness of the pixels covered with black feature cells.Some examples of the most popular Haar features are given below. Your task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.A prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.You have a variable value, whose value is initially zero. In one operation you can count the sum of pixel values ββat any prefix rectangle, multiply it by any integer and add to variable value.You are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.InputThe first line contains two space-separated integers n and m (1ββ€βn,βmββ€β100) β the number of rows and columns in the feature.Next n lines contain the description of the feature. Each line consists of m characters, the j-th character of the i-th line equals to "W", if this element of the feature is white and "B" if it is black.OutputPrint a single number β the minimum number of operations that you need to make to calculate the value of the feature.ExamplesInput6 8BBBBBBBBBBBBBBBBBBBBBBBBWWWWWWWWWWWWWWWWWWWWWWWWOutput2Input3 3WBWBWWWWWOutput4Input3 6WWBBWWWWBBWWWWBBWWOutput3Input4 4BBBBBBBBBBBBBBBWOutput4NoteThe first sample corresponds to feature B, the one shown in the picture. The value of this feature in an image of size 6βΓβ8 equals to the difference of the total brightness of the pixels in the lower and upper half of the image. To calculate its value, perform the following two operations: add the sum of pixels in the prefix rectangle with the lower right corner in the 6-th row and 8-th column with coefficient 1 to the variable value (the rectangle is indicated by a red frame); add the number of pixels in the prefix rectangle with the lower right corner in the 3-rd row and 8-th column with coefficient β-β2 and variable value. Thus, all the pixels in the lower three rows of the image will be included with factor 1, and all pixels in the upper three rows of the image will be included with factor 1β-β2β=ββ-β1, as required. | Input6 8BBBBBBBBBBBBBBBBBBBBBBBBWWWWWWWWWWWWWWWWWWWWWWWW | Output2 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1900'] |
C. The Game Of Paritytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.InputThe first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros.OutputPrint string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.ExamplesInput3 11 2 1OutputStannisInput3 12 2 1OutputDaenerysInput6 35 20 12 7 14 101OutputStannisNoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Input3 11 2 1 | OutputStannis | 1 second | 256 megabytes | ['games', '*2200'] |
B. Looksery Partytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated.InputThe first line contains a single integer n (1ββ€βnββ€β100) β the number of employees of company Looksery.Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1.The last line contains n space-separated integers: a1,βa2,β...,βan (0ββ€βaiββ€βn), where ai represents the number of messages that the i-th employee should get according to Igor.OutputIn the first line print a single integer m β the number of employees who should come to the party so that Igor loses the dispute.In the second line print m space-separated integers β the numbers of these employees in an arbitrary order.If Igor wins the dispute in any case, print -1.If there are multiple possible solutions, print any of them.ExamplesInput31010100010 1 2Output11 Input111Output0Input411110101111000011 0 1 0Output41 2 3 4 NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second β 3, the third β 2, the fourth β 3. | Input31010100010 1 2 | Output11 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', '*2300'] |
A. Face Detectiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2βΓβ2 square, such that from the four letters of this square you can make word "face". You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.InputThe first line contains two space-separated integers, n and m (1ββ€βn,βmββ€β50) β the height and the width of the image, respectively.Next n lines define the image. Each line contains m lowercase Latin letters.OutputIn the single line print the number of faces on the image.ExamplesInput4 4xxxxxfaxxcexxxxxOutput1Input4 2xxcfaexxOutput1Input2 3faccefOutput2Input1 4faceOutput0NoteIn the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column: In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.In the third sample two faces are shown: In the fourth sample the image has no faces on it. | Input4 4xxxxxfaxxcexxxxx | Output1 | 1 second | 256 megabytes | ['implementation', 'strings', '*900'] |
B. Mike and Funtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an nβΓβm grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i,βj). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes. They play for q rounds. In each round, Mike chooses a bear (i,βj) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round. InputThe first line of input contains three integers n, m and q (1ββ€βn,βmββ€β500 and 1ββ€βqββ€β5000).The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes).The next q lines contain the information about the rounds. Each of them contains two integers i and j (1ββ€βiββ€βn and 1ββ€βjββ€βm), the row number and the column number of the bear changing his state.OutputAfter each round, print the current score of the bears.ExamplesInput5 4 50 1 1 01 0 0 10 1 1 01 0 0 10 0 0 01 11 41 14 24 3Output34334 | Input5 4 50 1 1 01 0 0 10 1 1 01 0 0 10 0 0 01 11 41 14 24 3 | Output34334 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', 'implementation', '*1400'] |
A. Mike and Faxtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s. He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length.He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length.InputThe first line of input contains string s containing lowercase English letters (1ββ€β|s|ββ€β1000).The second line contains integer k (1ββ€βkββ€β1000).OutputPrint "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise.ExamplesInputsaba2OutputNOInputsaddastavvat2OutputYESNotePalindrome is a string reading the same forward and backward.In the second sample, the faxes in his back-bag can be "saddas" and "tavvat". | Inputsaba2 | OutputNO | 1 second | 256 megabytes | ['brute force', 'implementation', 'strings', '*1100'] |
E. Mike and Friendstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhat-The-Fatherland is a strange country! All phone numbers there are strings consisting of lowercase English letters. What is double strange that a phone number can be associated with several bears!In that country there is a rock band called CF consisting of n bears (including Mike) numbered from 1 to n. Phone number of i-th member of CF is si. May 17th is a holiday named Phone Calls day. In the last Phone Calls day, everyone called all the numbers that are substrings of his/her number (one may call some number several times). In particular, everyone called himself (that was really strange country).Denote as call(i,βj) the number of times that i-th member of CF called the j-th member of CF. The geek Mike has q questions that he wants to ask you. In each question he gives you numbers l,βr and k and you should tell him the number InputThe first line of input contains integers n and q (1ββ€βnββ€β2βΓβ105 and 1ββ€βqββ€β5βΓβ105).The next n lines contain the phone numbers, i-th line contains a string si consisting of lowercase English letters ().The next q lines contain the information about the questions, each of them contains integers l,βr and k (1ββ€βlββ€βrββ€βn and 1ββ€βkββ€βn).OutputPrint the answer for each question in a separate line.ExamplesInput5 5aababababababb1 5 13 5 11 5 21 5 31 4 5Output75636 | Input5 5aababababababb1 5 13 5 11 5 21 5 31 4 5 | Output75636 | 3 seconds | 256 megabytes | ['data structures', 'string suffix structures', 'strings', 'trees', '*2800'] |
D. Mike and Fishtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish. He has marked n distinct points in the plane. i-th point is point (xi,βyi). He wants to put exactly one fish in each of these points such that the difference between the number of red fish and the blue fish on each horizontal or vertical line is at most 1.He can't find a way to perform that! Please help him.InputThe first line of input contains integer n (1ββ€βnββ€β2βΓβ105).The next n lines contain the information about the points, i-th line contains two integers xi and yi (1ββ€βxi,βyiββ€β2βΓβ105), the i-th point coordinates.It is guaranteed that there is at least one valid answer.OutputPrint the answer as a sequence of n characters 'r' (for red) or 'b' (for blue) where i-th character denotes the color of the fish in the i-th point.ExamplesInput41 11 22 12 2OutputbrrbInput31 11 22 1Outputbrr | Input41 11 22 12 2 | Outputbrrb | 3 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', '*2600'] |
C. Mike and Foamtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike is a bartender at Rico's bar. At Rico's, they put beer glasses in a special shelf. There are n kinds of beer at Rico's numbered from 1 to n. i-th kind of beer has ai milliliters of foam on it. Maxim is Mike's boss. Today he told Mike to perform q queries. Initially the shelf is empty. In each request, Maxim gives him a number x. If beer number x is already in the shelf, then Mike should remove it from the shelf, otherwise he should put it in the shelf.After each query, Mike should tell him the score of the shelf. Bears are geeks. So they think that the score of a shelf is the number of pairs (i,βj) of glasses in the shelf such that iβ<βj and where is the greatest common divisor of numbers a and b.Mike is tired. So he asked you to help him in performing these requests.InputThe first line of input contains numbers n and q (1ββ€βn,βqββ€β2βΓβ105), the number of different kinds of beer and number of queries.The next line contains n space separated integers, a1,βa2,β... ,βan (1ββ€βaiββ€β5βΓβ105), the height of foam in top of each kind of beer.The next q lines contain the queries. Each query consists of a single integer integer x (1ββ€βxββ€βn), the index of a beer that should be added or removed from the shelf.OutputFor each query, print the answer for that query in one line.ExamplesInput5 61 2 3 4 6123451Output013562 | Input5 61 2 3 4 6123451 | Output013562 | 2 seconds | 256 megabytes | ['bitmasks', 'combinatorics', 'dp', 'math', 'number theory', '*2300'] |
B. Mike and Feettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high. A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1ββ€βxββ€βn the maximum strength among all groups of size x.InputThe first line of input contains integer n (1ββ€βnββ€β2βΓβ105), the number of bears.The second line contains n integers separated by space, a1,βa2,β...,βan (1ββ€βaiββ€β109), heights of bears.OutputPrint n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.ExamplesInput101 2 3 4 5 4 3 2 1 6Output6 4 4 3 3 2 2 1 1 1 | Input101 2 3 4 5 4 3 2 1 6 | Output6 4 4 3 3 2 2 1 1 1 | 1 second | 256 megabytes | ['binary search', 'data structures', 'dp', 'dsu', '*1900'] |
A. Mike and Frogtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar. So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become and height of Abol will become where x1,βy1,βx2 and y2 are some integer numbers and denotes the remainder of a modulo b.Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.Mike has asked you for your help. Calculate the minimum time or say it will never happen.InputThe first line of input contains integer m (2ββ€βmββ€β106).The second line of input contains integers h1 and a1 (0ββ€βh1,βa1β<βm).The third line of input contains integers x1 and y1 (0ββ€βx1,βy1β<βm).The fourth line of input contains integers h2 and a2 (0ββ€βh2,βa2β<βm).The fifth line of input contains integers x2 and y2 (0ββ€βx2,βy2β<βm).It is guaranteed that h1ββ βa1 and h2ββ βa2.OutputPrint the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.ExamplesInput54 21 10 12 3Output3Input10231 21 01 21 1Output-1NoteIn the first sample, heights sequences are following:Xaniar: Abol: | Input54 21 10 12 3 | Output3 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', 'math', '*2200'] |
E. Soldier and Travelingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of ai soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road.Check if is it possible that after roaming there will be exactly bi soldiers in the i-th city.InputFirst line of input consists of two integers n and m (1ββ€βnββ€β100, 0ββ€βmββ€β200).Next line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β100).Next line contains n integers b1,βb2,β...,βbn (0ββ€βbiββ€β100).Then m lines follow, each of them consists of two integers p and q (1ββ€βp,βqββ€βn, pββ βq) denoting that there is an undirected road between cities p and q. It is guaranteed that there is at most one road between each pair of cities.OutputIf the conditions can not be met output single word "NO".Otherwise output word "YES" and then n lines, each of them consisting of n integers. Number in the i-th line in the j-th column should denote how many soldiers should road from city i to city j (if iββ βj) or how many soldiers should stay in city i (if iβ=βj).If there are several possible answers you may output any of them.ExamplesInput4 41 2 6 33 5 3 11 22 33 44 2OutputYES1 0 0 0 2 0 0 0 0 5 1 0 0 0 2 1 Input2 01 22 1OutputNO | Input4 41 2 6 33 5 3 11 22 33 44 2 | OutputYES1 0 0 0 2 0 0 0 0 5 1 0 0 0 2 1 | 1 second | 256 megabytes | ['flows', 'graphs', 'math', '*2100'] |
D. Soldier and Number Gametime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer xβ>β1, such that n is divisible by x and replacing n with nβ/βx. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a!β/βb! for some positive integer a and b (aββ₯βb). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?InputFirst line of input consists of single integer t (1ββ€βtββ€β1β000β000) denoting number of games soldiers play.Then follow t lines, each contains pair of integers a and b (1ββ€βbββ€βaββ€β5β000β000) defining the value of n for a game.OutputFor each game output a maximum score that the second soldier can get.ExamplesInput23 16 3Output25 | Input23 16 3 | Output25 | 3 seconds | 256 megabytes | ['constructive algorithms', 'dp', 'math', 'number theory', '*1700'] |
C. Soldier and Cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game. The rules are following. On each turn a fight happens. Each of them picks card from the top of his stack and puts on the table. The one whose card value is bigger wins this fight and takes both cards from the table to the bottom of his stack. More precisely, he first takes his opponent's card and puts to the bottom of his stack, and then he puts his card to the bottom of his stack. If after some turn one of the player's stack becomes empty, he loses and the other one wins. You have to calculate how many fights will happen and who will win the game, or state that game won't end.InputFirst line contains a single integer n (2ββ€βnββ€β10), the number of cards.Second line contains integer k1 (1ββ€βk1ββ€βnβ-β1), the number of the first soldier's cards. Then follow k1 integers that are the values on the first soldier's cards, from top to bottom of his stack.Third line contains integer k2 (k1β+βk2β=βn), the number of the second soldier's cards. Then follow k2 integers that are the values on the second soldier's cards, from top to bottom of his stack.All card values are different.OutputIf somebody wins in this game, print 2 integers where the first one stands for the number of fights before end of game and the second one is 1 or 2 showing which player has won.If the game won't end and will continue forever output β-β1.ExamplesInput42 1 32 4 2Output6 2Input31 22 1 3Output-1NoteFirst sample: Second sample: | Input42 1 32 4 2 | Output6 2 | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'games', '*1400'] |
B. Soldier and Badgestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputColonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors. Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.InputFirst line of input consists of one integer n (1ββ€βnββ€β3000).Next line consists of n integers ai (1ββ€βaiββ€βn), which stand for coolness factor of each badge.OutputOutput single integer β minimum amount of coins the colonel has to pay.ExamplesInput41 3 1 4Output1Input51 2 3 2 5Output2NoteIn first sample test we can increase factor of first badge by 1.In second sample test we can increase factors of the second and the third badge by 1. | Input41 3 1 4 | Output1 | 3 seconds | 256 megabytes | ['brute force', 'greedy', 'implementation', 'sortings', '*1200'] |
A. Soldier and Bananastime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?InputThe first line contains three positive integers k,βn,βw (1βββ€ββk,βwβββ€ββ1000, 0ββ€βnββ€β109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants. OutputOutput one integer β the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.ExamplesInput3 17 4Output13 | Input3 17 4 | Output13 | 1 second | 256 megabytes | ['brute force', 'implementation', 'math', '*800'] |
E. Paths and Treestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.Let's assume that we are given a connected weighted undirected graph Gβ=β(V,βE) (here V is the set of vertices, E is the set of edges). The shortest-path tree from vertex u is such graph G1β=β(V,βE1) that is a tree with the set of edges E1 that is the subset of the set of edges of the initial graph E, and the lengths of the shortest paths from u to any vertex to G and to G1 are the same. You are given a connected weighted undirected graph G and vertex u. Your task is to find the shortest-path tree of the given graph from vertex u, the total weight of whose edges is minimum possible.InputThe first line contains two numbers, n and m (1ββ€βnββ€β3Β·105, 0ββ€βmββ€β3Β·105) β the number of vertices and edges of the graph, respectively.Next m lines contain three integers each, representing an edge β ui,βvi,βwi β the numbers of vertices connected by an edge and the weight of the edge (uiββ βvi,β1ββ€βwiββ€β109). It is guaranteed that graph is connected and that there is no more than one edge between any pair of vertices.The last line of the input contains integer u (1ββ€βuββ€βn) β the number of the start vertex.OutputIn the first line print the minimum total weight of the edges of the tree.In the next line print the indices of the edges that are included in the tree, separated by spaces. The edges are numbered starting from 1 in the order they follow in the input. You may print the numbers of the edges in any order.If there are multiple answers, print any of them.ExamplesInput3 31 2 12 3 11 3 23Output21 2 Input4 41 2 12 3 13 4 14 1 24Output42 3 4 NoteIn the first sample there are two possible shortest path trees: with edges 1βββ3 and 2βββ3 (the total weight is 3); with edges 1βββ2 and 2βββ3 (the total weight is 2); And, for example, a tree with edges 1βββ2 and 1βββ3 won't be a shortest path tree for vertex 3, because the distance from vertex 3 to vertex 2 in this tree equals 3, and in the original graph it is 1. | Input3 31 2 12 3 11 3 23 | Output21 2 | 3 seconds | 256 megabytes | ['graphs', 'greedy', 'shortest paths', '*2000'] |
D. Queuetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.InputThe first line contains integer n (1ββ€βnββ€β105).The next line contains n integers ti (1ββ€βtiββ€β109), separated by spaces.OutputPrint a single number β the maximum number of not disappointed people in the queue.ExamplesInput515 2 1 5 3Output4NoteValue 4 is achieved at such an arrangement, for example: 1,β2,β3,β5,β15. Thus, you can make everything feel not disappointed except for the person with time 5. | Input515 2 1 5 3 | Output4 | 1 second | 256 megabytes | ['greedy', 'implementation', 'sortings', '*1300'] |
C. Woodcutterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1,βx2,β...,βxn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xiβ-βhi,βxi] or [xi;xiβ+βhi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell. InputThe first line contains integer n (1ββ€βnββ€β105) β the number of trees.Next n lines contain pairs of integers xi,βhi (1ββ€βxi,βhiββ€β109) β the coordinate and the height of the Ρ-th tree.The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.OutputPrint a single number β the maximum number of trees that you can cut down by the given rules.ExamplesInput51 22 15 1010 919 1Output3Input51 22 15 1010 920 1Output4NoteIn the first sample you can fell the trees like that: fell the 1-st tree to the left β now it occupies segment [β-β1;1] fell the 2-nd tree to the right β now it occupies segment [2;3] leave the 3-rd tree β it occupies point 5 leave the 4-th tree β it occupies point 10 fell the 5-th tree to the right β now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19]. | Input51 22 15 1010 919 1 | Output3 | 1 second | 256 megabytes | ['dp', 'greedy', '*1500'] |
B. Equidistant Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti. As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.It's time for Susie to go to bed, help her find such string p or state that it is impossible.InputThe first line contains string s of length n. The second line contains string t of length n.The length of string n is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.OutputPrint a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line "impossible" (without the quotes).If there are multiple possible answers, print any of them.ExamplesInput00011011Output0011Input000111OutputimpossibleNoteIn the first sample different answers are possible, namely β 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101. | Input00011011 | Output0011 | 1 second | 256 megabytes | ['greedy', '*1100'] |
A. Toy Carstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an nβΓβn matrix Π: there is a number on the intersection of the Ρ-th row and j-th column that describes the result of the collision of the Ρ-th and the j-th car: β-β1: if this pair of cars never collided. β-β1 occurs only on the main diagonal of the matrix. 0: if no car turned over during the collision. 1: if only the i-th car turned over during the collision. 2: if only the j-th car turned over during the collision. 3: if both cars turned over during the collision. Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?InputThe first line contains integer n (1ββ€βnββ€β100) β the number of cars.Each of the next n lines contains n space-separated integers that determine matrix A. It is guaranteed that on the main diagonal there are β-β1, and β-β1 doesn't appear anywhere else in the matrix.It is guaranteed that the input is correct, that is, if Aijβ=β1, then Ajiβ=β2, if Aijβ=β3, then Ajiβ=β3, and if Aijβ=β0, then Ajiβ=β0.OutputPrint the number of good cars and in the next line print their space-separated indices in the increasing order.ExamplesInput3-1 0 00 -1 10 2 -1Output21 3 Input4-1 3 3 33 -1 3 33 3 -1 33 3 3 -1Output0 | Input3-1 0 00 -1 10 2 -1 | Output21 3 | 1 second | 256 megabytes | ['implementation', '*900'] |
B. Sea and Islandstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).Find a way to cover some cells with sand so that exactly k islands appear on the nβΓβn map, or determine that no such way exists. InputThe single line contains two positive integers n, k (1ββ€βnββ€β100, 0ββ€βkββ€βn2) β the size of the map and the number of islands you should form.OutputIf the answer doesn't exist, print "NO" (without the quotes) in a single line.Otherwise, print "YES" in the first line. In the next n lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal n.If there are multiple answers, you may print any of them.You should not maximize the sizes of islands.ExamplesInput5 2OutputYESSSSSSLLLLLSSSSSLLLLLSSSSSInput5 25OutputNO | Input5 2 | OutputYESSSSSSLLLLLSSSSSLLLLLSSSSS | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1400'] |
A. Set of Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string q. A sequence of k strings s1,βs2,β...,βsk is called beautiful, if the concatenation of these strings is string q (formally, s1β+βs2β+β...β+βskβ=βq) and the first characters of these strings are distinct.Find any beautiful sequence of strings or determine that the beautiful sequence doesn't exist.InputThe first line contains a positive integer k (1ββ€βkββ€β26) β the number of strings that should be in a beautiful sequence. The second line contains string q, consisting of lowercase Latin letters. The length of the string is within range from 1 to 100, inclusive.OutputIf such sequence doesn't exist, then print in a single line "NO" (without the quotes). Otherwise, print in the first line "YES" (without the quotes) and in the next k lines print the beautiful sequence of strings s1,βs2,β...,βsk.If there are multiple possible answers, print any of them.ExamplesInput1abcaOutputYESabcaInput2aaacasOutputYESaaacasInput4abcOutputNONoteIn the second sample there are two possible answers: {"aaaca",β"s"} and {"aaa",β"cas"}. | Input1abca | OutputYESabca | 1 second | 256 megabytes | ['implementation', 'strings', '*1100'] |
E. Listening to Musictime limit per test7 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputPlease note that the memory limit differs from the standard.You really love to listen to music. During the each of next s days you will listen to exactly m songs from the playlist that consists of exactly n songs. Let's number the songs from the playlist with numbers from 1 to n, inclusive. The quality of song number i is ai.On the i-th day you choose some integer v (liββ€βvββ€βri) and listen to songs number v,βvβ+β1,β...,βvβ+βmβ-β1. On the i-th day listening to one song with quality less than qi increases your displeasure by exactly one.Determine what minimum displeasure you can get on each of the s next days. InputThe first line contains two positive integers n, m (1ββ€βmββ€βnββ€β2Β·105). The second line contains n positive integers a1,βa2,β...,βan (0ββ€βaiβ<β230) β the description of songs from the playlist. The next line contains a single number s (1ββ€βsββ€β2Β·105) β the number of days that you consider.The next s lines contain three integers each li,βri,βxi (1ββ€βliββ€βriββ€βnβ-βmβ+β1; 0ββ€βxiβ<β230) β the description of the parameters for the i-th day. In order to calculate value qi, you need to use formula: , where ansi is the answer to the problem for day i. Assume that ans0β=β0. OutputPrint exactly s integers ans1,βans2,β...,βanss, where ansi is the minimum displeasure that you can get on day i.ExamplesInput5 31 2 1 2 351 1 21 3 21 3 31 3 51 3 1Output20231 | Input5 31 2 1 2 351 1 21 3 21 3 31 3 51 3 1 | Output20231 | 7 seconds | 64 megabytes | ['constructive algorithms', 'data structures', '*3200'] |
D. Road Improvementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe country has n cities and nβ-β1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive.All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road.Your task is β for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1β000β000β007 (109β+β7).InputThe first line of the input contains a single integer n (2ββ€βnββ€β2Β·105) β the number of cities in the country. Next line contains nβ-β1 positive integers p2,βp3,βp4,β...,βpn (1ββ€βpiββ€βiβ-β1) β the description of the roads in the country. Number pi means that the country has a road connecting city pi and city i. OutputPrint n integers a1,βa2,β...,βan, where ai is the sought number of ways to improve the quality of the roads modulo 1β000β000β007 (109β+β7), if the capital of the country is at city number i.ExamplesInput31 1Output4 3 3Input51 2 3 4Output5 8 9 8 5 | Input31 1 | Output4 3 3 | 2 seconds | 256 megabytes | ['dp', 'trees', '*2300'] |
C. Remembering Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have multiset of n strings of the same length, consisting of lowercase English letters. We will say that those strings are easy to remember if for each string there is some position i and some letter c of the English alphabet, such that this string is the only string in the multiset that has letter c in position i.For example, a multiset of strings {"abc", "aba", "adc", "ada"} are not easy to remember. And multiset {"abc", "ada", "ssa"} is easy to remember because: the first string is the only string that has character c in position 3; the second string is the only string that has character d in position 2; the third string is the only string that has character s in position 2. You want to change your multiset a little so that it is easy to remember. For aij coins, you can change character in the j-th position of the i-th string into any other lowercase letter of the English alphabet. Find what is the minimum sum you should pay in order to make the multiset of strings easy to remember.InputThe first line contains two integers n, m (1ββ€βn,βmββ€β20)Β β the number of strings in the multiset and the length of the strings respectively. Next n lines contain the strings of the multiset, consisting only of lowercase English letters, each string's length is m.Next n lines contain m integers each, the i-th of them contains integers ai1,βai2,β...,βaim (0ββ€βaijββ€β106).OutputPrint a single number β the answer to the problem.ExamplesInput4 5abcdeabcdeabcdeabcde1 1 1 1 11 1 1 1 11 1 1 1 11 1 1 1 1Output3Input4 3abcabaadcada10 10 1010 1 1010 10 1010 1 10Output2Input3 3abcadassa1 1 11 1 11 1 1Output0 | Input4 5abcdeabcdeabcdeabcde1 1 1 1 11 1 1 1 11 1 1 1 11 1 1 1 1 | Output3 | 2 seconds | 256 megabytes | ['bitmasks', 'dp', '*2500'] |
B. Destroying Roadstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours.Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.InputThe first line contains two integers n, m (1ββ€βnββ€β3000, )Β β the number of cities and roads in the country, respectively. Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1ββ€βai,βbiββ€βn, aiββ βbi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them.The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1ββ€βsi,βtiββ€βn, 0ββ€βliββ€βn).OutputPrint a single number β the answer to the problem. If the it is impossible to meet the conditions, print -1.ExamplesInput5 41 22 33 44 51 3 23 5 2Output0Input5 41 22 33 44 51 3 22 4 2Output1Input5 41 22 33 44 51 3 23 5 1Output-1 | Input5 41 22 33 44 51 3 23 5 2 | Output0 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'shortest paths', '*2100'] |
A. Writing Codetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProgrammers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes. Let's call a sequence of non-negative integers v1,βv2,β...,βvn a plan, if v1β+βv2β+β...β+βvnβ=βm. The programmers follow the plan like that: in the beginning the first programmer writes the first v1 lines of the given task, then the second programmer writes v2 more lines of the given task, and so on. In the end, the last programmer writes the remaining lines of the code. Let's call a plan good, if all the written lines of the task contain at most b bugs in total.Your task is to determine how many distinct good plans are there. As the number of plans can be large, print the remainder of this number modulo given positive integer mod.InputThe first line contains four integers n, m, b, mod (1ββ€βn,βmββ€β500, 0ββ€βbββ€β500; 1ββ€βmodββ€β109β+β7)Β β the number of programmers, the number of lines of code in the task, the maximum total number of bugs respectively and the modulo you should use when printing the answer.The next line contains n space-separated integers a1,βa2,β...,βan (0ββ€βaiββ€β500)Β β the number of bugs per line for each programmer.OutputPrint a single integer β the answer to the problem modulo mod.ExamplesInput3 3 3 1001 1 1Output10Input3 6 5 10000000071 2 3Output0Input3 5 6 111 2 1Output0 | Input3 3 3 1001 1 1 | Output10 | 3 seconds | 256 megabytes | ['dp', '*1800'] |
F. Questtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is making a quest for his friends. He has already made n tasks, for each task the boy evaluated how interesting it is as an integer qi, and the time ti in minutes needed to complete the task. An interesting feature of his quest is: each participant should get the task that is best suited for him, depending on his preferences. The task is chosen based on an interactive quiz that consists of some questions. The player should answer these questions with "yes" or "no". Depending on the answer to the question, the participant either moves to another question or goes to one of the tasks that are in the quest. In other words, the quest is a binary tree, its nodes contain questions and its leaves contain tasks. We know that answering any of the questions that are asked before getting a task takes exactly one minute from the quest player. Polycarp knows that his friends are busy people and they can't participate in the quest for more than T minutes. Polycarp wants to choose some of the n tasks he made, invent the corresponding set of questions for them and use them to form an interactive quiz as a binary tree so that no matter how the player answers quiz questions, he spends at most T minutes on completing the whole quest (that is, answering all the questions and completing the task). Specifically, the quest can contain zero questions and go straight to the task. Each task can only be used once (i.e., the people who give different answers to questions should get different tasks).Polycarp wants the total "interest" value of the tasks involved in the quest to be as large as possible. Help him determine the maximum possible total interest value of the task considering that the quest should be completed in T minutes at any variant of answering questions.InputThe first line contains two integers n and T (1ββ€βnββ€β1000, 1ββ€βTββ€β100) β the number of tasks made by Polycarp and the maximum time a quest player should fit into.Next n lines contain two integers ti,βqi (1ββ€βtiββ€βT, 1ββ€βqiββ€β1000) each β the time in minutes needed to complete the i-th task and its interest value.OutputPrint a single integer β the maximum possible total interest value of all the tasks in the quest.ExamplesInput5 51 11 12 23 34 4Output11Input5 54 14 24 34 44 5Output9Input2 21 12 10Output10NoteIn the first sample test all the five tasks can be complemented with four questions and joined into one quest.In the second sample test it is impossible to use all the five tasks, but you can take two of them, the most interesting ones.In the third sample test the optimal strategy is to include only the second task into the quest.Here is the picture that illustrates the answers to the sample tests. The blue circles represent the questions, the two arrows that go from every circle represent where a person goes depending on his answer to that question. The tasks are the red ovals. | Input5 51 11 12 23 34 4 | Output11 | 1 second | 256 megabytes | ['dp', 'greedy', '*2100'] |
E. Playing on Graphtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova and Marina love offering puzzles to each other. Today Marina offered Vova to cope with the following task.Vova has a non-directed graph consisting of n vertices and m edges without loops and multiple edges. Let's define the operation of contraction two vertices a and b that are not connected by an edge. As a result of this operation vertices a and b are deleted and instead of them a new vertex x is added into the graph, and also edges are drawn from it to all vertices that were connected with a or with b (specifically, if the vertex was connected with both a and b, then also exactly one edge is added from x to it). Thus, as a result of contraction again a non-directed graph is formed, it contains no loops nor multiple edges, and it contains (nβ-β1) vertices.Vova must perform the contraction an arbitrary number of times to transform the given graph into a chain of the maximum length. A chain of length k (kββ₯β0) is a connected graph whose vertices can be numbered with integers from 1 to kβ+β1 so that the edges of the graph connect all pairs of vertices (i,βiβ+β1) (1ββ€βiββ€βk) and only them. Specifically, the graph that consists of one vertex is a chain of length 0. The vertices that are formed as a result of the contraction are allowed to be used in the following operations of contraction. The picture illustrates the contraction of two vertices marked by red. Help Vova cope with his girlfriend's task. Find the maximum length of the chain that can be obtained from the resulting graph or else determine that it is impossible to obtain the chain.InputThe first line contains two integers n,βm (1ββ€βnββ€β1000, 0ββ€βmββ€β100β000) β the number of vertices and the number of edges in the original graph.Next m lines contain the descriptions of edges in the format ai,βbi (1ββ€βai,βbiββ€βn, aiββ βbi), which means that there is an edge between vertices ai and bi. It is guaranteed that there is at most one edge between each pair of vertexes.OutputIf it is impossible to obtain a chain from the given graph, print β-β1. Otherwise, print the maximum possible number of edges in the resulting chain.ExamplesInput5 41 22 33 43 5Output3Input4 61 22 31 33 42 41 4Output-1Input4 21 32 4Output2NoteIn the first sample test you can contract vertices 4 and 5 and obtain a chain of length 3.In the second sample test it is initially impossible to contract any pair of vertexes, so it is impossible to achieve the desired result.In the third sample test you can contract vertices 1 and 2 and obtain a chain of length 2. | Input5 41 22 33 43 5 | Output3 | 3 seconds | 256 megabytes | ['graphs', 'shortest paths', '*2600'] |
D. Superhero's Jobtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's tough to be a superhero. And it's twice as tough to resist the supervillain who is cool at math. Suppose that you're an ordinary Batman in an ordinary city of Gotham. Your enemy Joker mined the building of the city administration and you only have several minutes to neutralize the charge. To do that you should enter the cancel code on the bomb control panel.However, that mad man decided to give you a hint. This morning the mayor found a playing card under his pillow. There was a line written on the card:The bomb has a note saying "J(x)β=βA", where A is some positive integer. You suspect that the cancel code is some integer x that meets the equation J(x)β=βA. Now in order to decide whether you should neutralize the bomb or run for your life, you've got to count how many distinct positive integers x meet this equation.InputThe single line of the input contains a single integer A (1ββ€βAββ€β1012).OutputPrint the number of solutions of the equation J(x)β=βA.ExamplesInput3Output1Input24Output3NoteRecord x|n means that number n divides number x. is defined as the largest positive integer that divides both a and b.In the first sample test the only suitable value of x is 2. Then J(2)β=β1β+β2.In the second sample test the following values of x match: xβ=β14, J(14)β=β1β+β2β+β7β+β14β=β24 xβ=β15, J(15)β=β1β+β3β+β5β+β15β=β24 xβ=β23, J(23)β=β1β+β23β=β24 | Input3 | Output1 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'hashing', 'math', 'number theory', '*2600'] |
C. Idempotent functionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1,β2,β...,βn} is such function , that for any the formula g(g(x))β=βg(x) holds.Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x)β=βf(x), f(k)(x)β=βf(f(kβ-β1)(x)) for each kβ>β1.You are given some function . Your task is to find minimum positive integer k such that function f(k)(x) is idempotent.InputIn the first line of the input there is a single integer n (1ββ€βnββ€β200) β the size of function f domain.In the second line follow f(1),βf(2),β...,βf(n) (1ββ€βf(i)ββ€βn for each 1ββ€βiββ€βn), the values of a function.OutputOutput minimum k such that function f(k)(x) is idempotent.ExamplesInput41 2 2 4Output1Input32 3 3Output2Input32 3 1Output3NoteIn the first sample test function f(x)β=βf(1)(x) is already idempotent since f(f(1))β=βf(1)β=β1, f(f(2))β=βf(2)β=β2, f(f(3))β=βf(3)β=β2, f(f(4))β=βf(4)β=β4.In the second sample test: function f(x)β=βf(1)(x) isn't idempotent because f(f(1))β=β3 but f(1)β=β2; function f(x)β=βf(2)(x) is idempotent since for any x it is true that f(2)(x)β=β3, so it is also true that f(2)(f(2)(x))β=β3. In the third sample test: function f(x)β=βf(1)(x) isn't idempotent because f(f(1))β=β3 but f(1)β=β2; function f(f(x))β=βf(2)(x) isn't idempotent because f(2)(f(2)(1))β=β2 but f(2)(1)β=β3; function f(f(f(x)))β=βf(3)(x) is idempotent since it is identity function: f(3)(x)β=βx for any meaning that the formula f(3)(f(3)(x))β=βf(3)(x) also holds. | Input41 2 2 4 | Output1 | 1 second | 256 megabytes | ['constructive algorithms', 'graphs', 'math', '*2000'] |
B. Duck Hunttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA duck hunter is doing his favorite thing, hunting. He lives in a two dimensional world and is located at point (0,β0). As he doesn't like walking for his prey, he prefers to shoot only vertically up (because in this case, the ducks fall straight into his hands). The hunter doesn't reload the gun immediately β r or more seconds must pass between the shots. When the hunter shoots up, the bullet immediately hits all the ducks who are directly above the hunter.In a two dimensional world each duck is a horizontal segment that moves horizontally in the negative direction of the Ox axis at the speed 1 length unit per second. For each duck we know the values hi and ti β the x-coordinates of its head (the left end of the segment) and its tail (the right end of the segment) at time 0. The height where the duck is flying isn't important as the gun shoots vertically up to the infinite height and hits all the ducks on its way. The figure to the first sample. What maximum number of ducks can the hunter shoot? The duck is considered shot by the hunter if at the moment of the shot at least one of its point intersects the Oy axis. After the hunter shoots the duck, it falls and it can't be shot anymore. The hunter cannot make shots before the moment of time 0.InputThe first line of the input contains integers n, r (1ββ€βnββ€β200β000, 1ββ€βrββ€β109) β the number of ducks and the minimum time in seconds between the shots. Then n lines follow, each of them contains two integers hi,βti (β-β109ββ€βhiβ<βtiββ€β109)Β β the x-coordinate of the head and tail of the i-th duck at the moment 0.OutputPrint a single integer β the maximum number of ducks that can be shot by the hunter.ExamplesInput3 3-3 01 3-1 2Output3Input4 5-1 12 45 96 8Output3NoteIn the first sample the hunter must shoot at time 0, this shot kills ducks 1 and 3. Then the hunter needs to reload the gun and shoot again at time 3. His second shot hits the tail of duck 2.In the second sample the hunter can make shots at times 0 and 6 to hit three ducks. | Input3 3-3 01 3-1 2 | Output3 | 3 seconds | 256 megabytes | ['data structures', '*3100'] |
A. Place Your Ad Heretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan Anatolyevich's agency is starting to become famous in the town. They have already ordered and made n TV commercial videos. Each video is made in a special way: the colors and the soundtrack are adjusted to the time of the day and the viewers' mood. That's why the i-th video can only be shown within the time range of [li,βri] (it is not necessary to use the whole segment but the broadcast time should be within this segment).Now it's time to choose a TV channel to broadcast the commercial. Overall, there are m TV channels broadcasting in the city, the j-th one has cj viewers, and is ready to sell time [aj,βbj] to broadcast the commercial.Ivan Anatolyevich is facing a hard choice: he has to choose exactly one video i and exactly one TV channel j to broadcast this video and also a time range to broadcast [x,βy]. At that the time range should be chosen so that it is both within range [li,βri] and within range [aj,βbj].Let's define the efficiency of the broadcast as value (yβ-βx)Β·cj β the total sum of time that all the viewers of the TV channel are going to spend watching the commercial. Help Ivan Anatolyevich choose the broadcast with the maximum efficiency!InputThe first line contains two integers n and m (1ββ€βn,βmββ€β2Β·105)Β β the number of commercial videos and channels, respectively.Each of the following n lines contains two integers li, ri (0ββ€βliββ€βriββ€β109)Β β the segment of time when it is possible to show the corresponding video.Each of the following m lines contains three integers aj, bj, cj (0ββ€βajββ€βbjββ€β109, 1ββ€βcjββ€β109), characterizing the TV channel.OutputIn the first line print an integer β the maximum possible efficiency of the broadcast. If there is no correct way to get a strictly positive efficiency, print a zero.If the maximum efficiency is strictly positive, in the second line also print the number of the video i (1ββ€βiββ€βn) and the number of the TV channel j (1ββ€βjββ€βm) in the most effective broadcast.If there are multiple optimal answers, you can print any of them.ExamplesInput2 37 91 42 8 20 4 18 9 3Output42 1Input1 10 01 1 10Output0NoteIn the first sample test the most optimal solution is to show the second commercial using the first TV channel at time [2,β4]. The efficiency of such solution is equal to (4β-β2)Β·2β=β4.In the second sample test Ivan Anatolievich's wish does not meet the options of the TV channel, the segments do not intersect, so the answer is zero. | Input2 37 91 42 8 20 4 18 9 3 | Output42 1 | 2 seconds | 256 megabytes | ['data structures', 'sortings', '*2400'] |
E. Infinite Inversionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an infinite sequence consisting of all positive integers in the increasing order: pβ=β{1,β2,β3,β...}. We performed n swap operations with this sequence. A swap(a,βb) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i,βj), that iβ<βj and piβ>βpj.InputThe first line contains a single integer n (1ββ€βnββ€β105)Β β the number of swap operations applied to the sequence.Each of the next n lines contains two integers ai and bi (1ββ€βai,βbiββ€β109, aiββ βbi)Β β the arguments of the swap operation.OutputPrint a single integer β the number of inversions in the resulting sequence.ExamplesInput24 21 4Output4Input31 63 42 5Output15NoteIn the first sample the sequence is being modified as follows: . It has 4 inversions formed by index pairs (1,β4), (2,β3), (2,β4) and (3,β4). | Input24 21 4 | Output4 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'implementation', 'sortings', 'trees', '*2100'] |
D. Bad Luck Islandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.InputThe single line contains three integers r, s and p (1ββ€βr,βs,βpββ€β100)Β β the original number of individuals in the species of rock, scissors and paper, respectively.OutputPrint three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10β-β9.ExamplesInput2 2 2Output0.333333333333 0.333333333333 0.333333333333Input2 1 2Output0.150000000000 0.300000000000 0.550000000000Input1 1 3Output0.057142857143 0.657142857143 0.285714285714 | Input2 2 2 | Output0.333333333333 0.333333333333 0.333333333333 | 2 seconds | 256 megabytes | ['dp', 'probabilities', '*1900'] |
C. Ice Cavetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou play a computer game. Your character stands on some level of a multilevel ice cave. In order to move on forward, you need to descend one level lower and the only way to do this is to fall through the ice.The level of the cave where you are is a rectangular square grid of n rows and m columns. Each cell consists either from intact or from cracked ice. From each cell you can move to cells that are side-adjacent with yours (due to some limitations of the game engine you cannot make jumps on the same place, i.e. jump from a cell to itself). If you move to the cell with cracked ice, then your character falls down through it and if you move to the cell with intact ice, then the ice on this cell becomes cracked.Let's number the rows with integers from 1 to n from top to bottom and the columns with integers from 1 to m from left to right. Let's denote a cell on the intersection of the r-th row and the c-th column as (r,βc). You are staying in the cell (r1,βc1) and this cell is cracked because you've just fallen here from a higher level. You need to fall down through the cell (r2,βc2) since the exit to the next level is there. Can you do this?InputThe first line contains two integers, n and m (1ββ€βn,βmββ€β500)Β β the number of rows and columns in the cave description.Each of the next n lines describes the initial state of the level of the cave, each line consists of m characters "." (that is, intact ice) and "X" (cracked ice).The next line contains two integers, r1 and c1 (1ββ€βr1ββ€βn,β1ββ€βc1ββ€βm)Β β your initial coordinates. It is guaranteed that the description of the cave contains character 'X' in cell (r1,βc1), that is, the ice on the starting cell is initially cracked.The next line contains two integers r2 and c2 (1ββ€βr2ββ€βn,β1ββ€βc2ββ€βm)Β β the coordinates of the cell through which you need to fall. The final cell may coincide with the starting one.OutputIf you can reach the destination, print 'YES', otherwise print 'NO'.ExamplesInput4 6X...XX...XX..X..X.......1 62 2OutputYESInput5 4.X.....XX.X......XX.5 31 1OutputNOInput4 7..X.XX..XX..X.X...X..X......2 21 6OutputYESNoteIn the first sample test one possible path is:After the first visit of cell (2,β2) the ice on it cracks and when you step there for the second time, your character falls through the ice as intended. | Input4 6X...XX...XX..X..X.......1 62 2 | OutputYES | 2 seconds | 256 megabytes | ['dfs and similar', '*2000'] |
B. School Markstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1,β...,βak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.InputThe first line contains 5 space-separated integers: n, k, p, x and y (1ββ€βnββ€β999, n is odd, 0ββ€βkβ<βn, 1ββ€βpββ€β1000, nββ€βxββ€βnΒ·p, 1ββ€βyββ€βp). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games.The second line contains k space-separated integers: a1,β...,βak (1ββ€βaiββ€βp)Β β the marks that Vova got for the tests he has already written.OutputIf Vova cannot achieve the desired result, print "-1".Otherwise, print nβ-βk space-separated integersΒ β the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.ExamplesInput5 3 5 18 43 5 4Output4 1Input5 3 5 16 45 5 5Output-1NoteThe median of sequence a1,Β ...,Β an where n is odd (in this problem n is always odd) is the element staying on (nβ+β1)β/β2 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: "4Β 2", "2Β 4", "5Β 1", "1Β 5", "4Β 1", "1Β 4" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is "-1". | Input5 3 5 18 43 5 4 | Output4 1 | 2 seconds | 256 megabytes | ['greedy', 'implementation', '*1700'] |
A. Combination Locktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputScrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock. The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?InputThe first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of disks on the combination lock.The second line contains a string of n digitsΒ β the original state of the disks.The third line contains a string of n digitsΒ β Scrooge McDuck's combination that opens the lock.OutputPrint a single integerΒ β the minimum number of moves Scrooge McDuck needs to open the lock.ExamplesInput58219564723Output13NoteIn the sample he needs 13 moves: 1 disk: 2 disk: 3 disk: 4 disk: 5 disk: | Input58219564723 | Output13 | 2 seconds | 256 megabytes | ['implementation', '*800'] |
H. Summer Dichotomytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputT students applied into the ZPP class of Summer Irrelevant School. The organizing committee of the school may enroll any number of them, but at least t students must be enrolled. The enrolled students should be divided into two groups in any manner (it is possible that one of the groups will be empty!)During a shift the students from the ZPP grade are tutored by n teachers. Due to the nature of the educational process, each of the teachers should be assigned to exactly one of two groups (it is possible that no teacher will be assigned to some of the groups!). The i-th teacher is willing to work in a group as long as the group will have at least li and at most ri students (otherwise it would be either too boring or too hard). Besides, some pairs of the teachers don't like each other other and therefore can not work in the same group; in total there are m pairs of conflicting teachers.You, as the head teacher of Summer Irrelevant School, have got a difficult task: to determine how many students to enroll in each of the groups and in which group each teacher will teach.InputThe first line contains two space-separated integers, t and T (1ββ€βtββ€βTββ€β109).The second line contains two space-separated integers n and m (1ββ€βnββ€β105, 0ββ€βmββ€β105).The i-th of the next n lines contain integers li and ri (0ββ€βliββ€βriββ€β109).The next m lines describe the pairs of conflicting teachers. Each of these lines contain two space-separated integers β the indices of teachers in the pair. The teachers are indexed starting from one. It is guaranteed that no teacher has a conflict with himself and no pair of conflicting teachers occurs in the list more than once.OutputIf the distribution is possible, print in the first line a single word 'POSSIBLE' (without the quotes). In the second line print two space-separated integers n1 and n2Β β the number of students in the first and second group, correspondingly, the contstraint tββ€βn1β+βn2ββ€βT should be met. In the third line print n characters, the i-th of which should be 1 or 2, if the i-th teacher should be assigned to the first or second group, correspondingly. If there are multiple possible distributions of students and teachers in groups, you can print any of them.If the sought distribution doesn't exist, print a single word 'IMPOSSIBLE' (without the quotes).ExamplesInput10 203 03 64 916 25OutputPOSSIBLE4 16112Input1 103 30 100 100 101 21 32 3OutputIMPOSSIBLE | Input10 203 03 64 916 25 | OutputPOSSIBLE4 16112 | 2 seconds | 256 megabytes | ['2-sat', 'data structures', 'dfs and similar', 'greedy', '*3200'] |
G. Berserk Robot time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHelp! A robot escaped our lab and we need help finding it. The lab is at the point (0,β0) of the coordinate plane, at time 0 the robot was there. The robot's movements are defined by a programΒ β a string of length l, consisting of characters U, L, D, R. Each second the robot executes the next command in his program: if the current coordinates of the robot are (x,βy), then commands U, L, D, R move it to cells (x,βyβ+β1), (xβ-β1,βy), (x,βyβ-β1), (xβ+β1,βy) respectively. The execution of the program started at time 0. The program is looped, i.e. each l seconds of executing the program start again from the first character. Unfortunately, we don't know what program was loaded into the robot when he left the lab.Our radars managed to find out the position of the robot at n moments of time: we know that at the moment of time ti the robot is at the point (xi,βyi). Given this data, either help to determine what program could be loaded into the robot, or determine that no possible program meets the data and the robot must have broken down.InputThe first line of the input contains two space-separated integers n and l (1ββ€βnββ€β2Β·105, 1ββ€βlββ€β2Β·106).Next n lines contain three space-separated integersΒ β ti, xi, yi (1ββ€βtiββ€β1018, β-β1018ββ€βxi,βyiββ€β1018). The radar data is given chronologically, i.e. tiβ<βtiβ+β1 for all i from 1 to nβ-β1.OutputPrint any of the possible programs that meet the data. If no program meets the data, print a single word 'NO' (without the quotes).ExamplesInput3 31 1 02 1 -13 0 -1OutputRDLInput2 21 1 0999 1 0OutputRLInput2 510 10 020 0 0OutputNO | Input3 31 1 02 1 -13 0 -1 | OutputRDL | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', 'sortings', '*3100'] |
F. A Heap of Heapstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAndrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.The teacher gave Andrew an array of n numbers a1, ..., an. After that he asked Andrew for each k from 1 to nβ-β1 to build a k-ary heap on the array and count the number of elements for which the property of the minimum-rooted heap is violated, i.e. the value of an element is less than the value of its parent.Andrew looked up on the Wikipedia that a k-ary heap is a rooted tree with vertices in elements of the array. If the elements of the array are indexed from 1 to n, then the children of element v are elements with indices k(vβ-β1)β+β2, ..., kvβ+β1 (if some of these elements lie outside the borders of the array, the corresponding children are absent). In any k-ary heap every element except for the first one has exactly one parent; for the element 1 the parent is absent (this element is the root of the heap). Denote p(v) as the number of the parent of the element with the number v. Let's say that for a non-root element v the property of the heap is violated if avβ<βap(v).Help Andrew cope with the task!InputThe first line contains a single integer n (2ββ€βnββ€β2Β·105).The second line contains n space-separated integers a1, ..., an (β-β109ββ€βaiββ€β109).Outputin a single line print nβ-β1 integers, separate the consecutive numbers with a single space β the number of elements for which the property of the k-ary heap is violated, for kβ=β1, 2, ..., nβ-β1.ExamplesInput51 5 4 3 2Output3 2 1 0Input62 2 2 2 2 2Output0 0 0 0 0NotePictures with the heaps for the first sample are given below; elements for which the property of the heap is violated are marked with red. In the second sample all elements are equal, so the property holds for all pairs. | Input51 5 4 3 2 | Output3 2 1 0 | 3 seconds | 512 megabytes | ['brute force', 'data structures', 'math', 'sortings', '*2200'] |
E. Demiurges Play Againtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDemiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to m are placed in such a way that each number appears exactly in one leaf.Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.InputThe first line contains a single integer nΒ β the number of nodes in the tree (1ββ€βnββ€β2Β·105).Each of the next nβ-β1 lines contains two integers ui and vi (1ββ€βui,βviββ€βn)Β β the ends of the edge of the tree; the edge leads from node ui to node vi. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.OutputPrint two space-separated integers β the maximum possible and the minimum possible result of the game.ExamplesInput51 21 32 42 5Output3 2Input61 21 33 41 55 6Output3 3NoteConsider the first sample. The tree contains three leaves: 3, 4 and 5. If we put the maximum number 3 at node 3, then the first player moves there and the result will be 3. On the other hand, it is easy to see that for any rearrangement the first player can guarantee the result of at least 2.In the second sample no matter what the arragment is the first player can go along the path that ends with a leaf with number 3. | Input51 21 32 42 5 | Output3 2 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'math', 'trees', '*2200'] |
D. Weird Chesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous.Igor's chessboard is a square of size nβΓβn cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves.Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x,βy)Β β the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx,βdy); using this move, the piece moves from the field (x,βy) to the field (xβ+βdx,βyβ+βdy). You can perform the move if the cell (xβ+βdx,βyβ+βdy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x,βy) and (xβ+βdx,βyβ+βdy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess).Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors.InputThe first line contains a single integer n (1ββ€βnββ€β50).The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values: o β in this case the field (i,βj) is occupied by a piece and the field may or may not be attacked by some other piece; x β in this case field (i,βj) is attacked by some piece; . β in this case field (i,βj) isn't attacked by any piece.It is guaranteed that there is at least one piece on the board.OutputIf there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2nβ-β1)βΓβ(2nβ-β1) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them.If a valid set of moves does not exist, print a single word 'NO'.ExamplesInput5oxxxxx...xx...xx...xxxxxoOutputYES....x........x........x........x....xxxxoxxxx....x........x........x........x....Input6.x.x..x.x.x..xo..xx..ox..x.x.x..x.x.OutputYES.....................................x.x.......x...x........o........x...x.......x.x.....................................Input3o.xoxxo.xOutputNONoteIn the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight. | Input5oxxxxx...xx...xx...xxxxxo | OutputYES....x........x........x........x....xxxxoxxxx....x........x........x........x.... | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', '*1800'] |
C. Tourist's Notestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to nβ-β1 the inequality |hiβ-βhiβ+β1|ββ€β1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hiβ-βhiβ+β1|ββ€β1.InputThe first line contains two space-separated numbers, n and m (1ββ€βnββ€β108, 1ββ€βmββ€β105)Β β the number of days of the hike and the number of notes left in the journal.Next m lines contain two space-separated integers di and hdi (1ββ€βdiββ€βn, 0ββ€βhdiββ€β108)Β β the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to mβ-β1 the following condition holds: diβ<βdiβ+β1.OutputIf the notes aren't contradictory, print a single integer β the maximum possible height value throughout the whole route.If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).ExamplesInput8 22 07 0Output2Input8 32 07 08 3OutputIMPOSSIBLENoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0,β0,β1,β2,β1,β1,β0,β1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent. | Input8 22 07 0 | Output2 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'greedy', 'implementation', 'math', '*1600'] |
B. Quasi Binarytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011Β β are quasibinary and numbers 2, 12, 900 are not.You are given a positive integer n. Represent it as a sum of minimum number of quasibinary numbers.InputThe first line contains a single integer n (1ββ€βnββ€β106).OutputIn the first line print a single integer kΒ β the minimum number of numbers in the representation of number n as a sum of quasibinary numbers.In the second line print k numbers β the elements of the sum. All these numbers should be quasibinary according to the definition above, their sum should equal n. Do not have to print the leading zeroes in the numbers. The order of numbers doesn't matter. If there are multiple possible representations, you are allowed to print any of them.ExamplesInput9Output91 1 1 1 1 1 1 1 1 Input32Output310 11 11 | Input9 | Output91 1 1 1 1 1 1 1 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dp', 'greedy', 'implementation', '*1400'] |
A. Cutting Bannertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA large banner with word CODEFORCES was ordered for the 1000-th onsite round of CodeforcesΟ that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case English letters.There is very little time to correct the mistake. All that we can manage to do is to cut out some substring from the banner, i.e. several consecutive letters. After that all the resulting parts of the banner will be glued into a single piece (if the beginning or the end of the original banner was cut out, only one part remains); it is not allowed change the relative order of parts of the banner (i.e. after a substring is cut, several first and last letters are left, it is allowed only to glue the last letters to the right of the first letters). Thus, for example, for example, you can cut a substring out from string 'TEMPLATE' and get string 'TEMPLE' (if you cut out string AT), 'PLATE' (if you cut out TEM), 'T' (if you cut out EMPLATE), etc.Help the organizers of the round determine whether it is possible to cut out of the banner some substring in such a way that the remaining parts formed word CODEFORCES.InputThe single line of the input contains the word written on the banner. The word only consists of upper-case English letters. The word is non-empty and its length doesn't exceed 100 characters. It is guaranteed that the word isn't word CODEFORCES.OutputPrint 'YES', if there exists a way to cut out the substring, and 'NO' otherwise (without the quotes).ExamplesInputCODEWAITFORITFORCESOutputYESInputBOTTOMCODEROutputNOInputDECODEFORCESOutputYESInputDOGEFORCESOutputNO | InputCODEWAITFORITFORCES | OutputYES | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1400'] |
E. Tavas on the Pathtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTavas lives in Tavaspolis. Tavaspolis has n cities numbered from 1 to n connected by nβ-β1 bidirectional roads. There exists a path between any two cities. Also each road has a length. Tavas' favorite strings are binary strings (they contain only 0 and 1). For any binary string like sβ=βs1s2... sk, T(s) is its Goodness. T(s) can be calculated as follows:Consider there are exactly m blocks of 1s in this string (a block of 1s in s is a maximal consecutive substring of s that only contains 1) with lengths x1,βx2,β...,βxm.Define where f is a given sequence (if mβ=β0, then T(s)β=β0).Tavas loves queries. He asks you to answer q queries. In each query he gives you numbers v,βu,βl and you should print following number:Consider the roads on the path from city v to city u: e1,βe2,β...,βex.Build the binary string b of length x such that: biβ=β1 if and only if lββ€βw(ei) where w(e) is the length of road e.You should print T(b) for this query.InputThe first line of input contains integers n and q (2ββ€βnββ€β105 and 1ββ€βqββ€β105).The next line contains nβ-β1 space separated integers f1,βf2,β...,βfnβ-β1 (|fi|ββ€β1000).The next nβ-β1 lines contain the details of the roads. Each line contains integers v,βu and w and it means that there's a road between cities v and u of length w (1ββ€βv,βuββ€βn and 1ββ€βwββ€β109).The next q lines contain the details of the queries. Each line contains integers v,βu,βl (1ββ€βv,βuββ€βn, vββ βu and 1ββ€βlββ€β109).OutputPrint the answer of each query in a single line.ExamplesInput2 3101 2 31 2 21 2 31 2 4Output10100Input6 6-5 0 0 2 101 2 12 3 23 4 54 5 15 6 51 6 11 6 21 6 53 6 54 6 41 4 2Output10-5-10-10-50 | Input2 3101 2 31 2 21 2 31 2 4 | Output10100 | 3 seconds | 256 megabytes | ['data structures', 'divide and conquer', 'trees', '*3100'] |
D. Tavas in Kansastime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputTavas lives in Kansas. Kansas has n cities numbered from 1 to n connected with m bidirectional roads. We can travel from any city to any other city via these roads. Kansas is as strange as Tavas. So there may be a road between a city and itself or more than one road between two cities.Tavas invented a game and called it "Dashti". He wants to play Dashti with his girlfriends, Nafas.In this game, they assign an arbitrary integer value to each city of Kansas. The value of i-th city equals to pi.During the game, Tavas is in city s and Nafas is in city t. They play in turn and Tavas goes first. A player in his/her turn, must choose a non-negative integer x and his/her score increases by the sum of values of all cities with (shortest) distance no more than x from his/her city. Each city may be used once, or in the other words, after first time a player gets score from a city, city score becomes zero.There is an additional rule: the player must choose x such that he/she gets the point of at least one city that was not used before. Note that city may initially have value 0, such city isn't considered as been used at the beginning of the game, i. e. each player may use it to fullfill this rule.The game ends when nobody can make a move.A player's score is the sum of the points he/she earned during the game. The winner is the player with greater score, or there is a draw if players score the same value. Both players start game with zero points. If Tavas wins, he'll break his girlfriend's heart, and if Nafas wins, Tavas will cry. But if their scores are equal, they'll be happy and Tavas will give Nafas flowers.They're not too emotional after all, so they'll play optimally. Your task is to tell Tavas what's going to happen after the game ends.InputThe first line of input contains two integers n and m (2ββ€βnββ€β2000, nβ-β1ββ€βmββ€β105).The second line of input contains two integers s and t (1ββ€βs,βtββ€βn, sββ βt).The next line contains n integers p1,βp2,β...,βpn separated by spaces (|pi|ββ€β109).The next m lines contain the roads. Each line contains three integers v,βu,βw and it means that there's an road with length w between cities v and u (1ββ€βu,βvββ€βn and 0ββ€βwββ€β109). The road may lead from the city to itself, there may be several roads between each pair of cities.OutputIf Tavas wins, print "Break a heart". If Nafas wins print "Cry" and if nobody wins (i. e. the game ended with draw) print "Flowers".ExamplesInput4 41 23 2 5 -111 4 23 4 23 1 53 2 1OutputCryInput5 41 22 2 -5 -4 61 2 42 3 52 4 24 5 2OutputBreak a heartInput2 11 2-5 -51 2 10OutputFlowers | Input4 41 23 2 5 -111 4 23 4 23 1 53 2 1 | OutputCry | 2 seconds | 512 megabytes | ['dp', 'games', '*2900'] |
E. Tavas and Pashmakstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him.InputThe first line of input contains a single integer n (1ββ€βnββ€β2βΓβ105).The next n lines contain the details of competitors. i-th line contains two integers si and ri (1ββ€βsi,βriββ€β104).OutputIn the first and the only line of output, print a sequence of numbers of possible winners in increasing order.ExamplesInput31 32 23 1Output1 2 3 Input31 21 12 1Output1 3 | Input31 32 23 1 | Output1 2 3 | 1 second | 256 megabytes | ['geometry', 'math', '*2600'] |
D. Tavas and Malekastime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead. Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions x1β<βx2β<β...β<βxk where p matches s. More formally, for each xi (1ββ€βiββ€βk) he condition sxisxiβ+β1... sxiβ+β|p|β-β1β=βp is fullfilled.Then Malekas wrote down one of subsequences of x1,βx2,β... xk (possibly, he didn't write anything) on a piece of paper. Here a sequence b is a subsequence of sequence a if and only if we can turn a into b by removing some of its elements (maybe no one of them or all).After Tavas woke up, Malekas told him everything. He couldn't remember string s, but he knew that both p and s only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.Tavas wonders, what is the number of possible values of s? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.Answer can be very large, so Tavas wants you to print the answer modulo 109β+β7.InputThe first line contains two integers n and m, the length of s and the length of the subsequence Malekas wrote down (1ββ€βnββ€β106 and 0ββ€βmββ€βnβ-β|p|β+β1).The second line contains string p (1ββ€β|p|ββ€βn).The next line contains m space separated integers y1,βy2,β...,βym, Malekas' subsequence (1ββ€βy1β<βy2β<β...β<βymββ€βnβ-β|p|β+β1).OutputIn a single line print the answer modulo 1000β000β007.ExamplesInput6 2ioi1 3Output26Input5 2ioi1 2Output0NoteIn the first sample test all strings of form "ioioi?" where the question mark replaces arbitrary English letter satisfy.Here |x| denotes the length of string x.Please note that it's possible that there is no such string (answer is 0). | Input6 2ioi1 3 | Output26 | 2 seconds | 256 megabytes | ['greedy', 'hashing', 'string suffix structures', 'strings', '*1900'] |
C. Tavas and Karafstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKarafs is some kind of vegetable in shape of an 1βΓβh rectangle. Tavaspolis people love Karafs and they use Karafs in almost any kind of food. Tavas, himself, is crazy about Karafs. Each Karafs has a positive integer height. Tavas has an infinite 1-based sequence of Karafses. The height of the i-th Karafs is siβ=βAβ+β(iβ-β1)βΓβB.For a given m, let's define an m-bite operation as decreasing the height of at most m distinct not eaten Karafses by 1. Karafs is considered as eaten when its height becomes zero.Now SaDDas asks you n queries. In each query he gives you numbers l, t and m and you should find the largest number r such that lββ€βr and sequence sl,βslβ+β1,β...,βsr can be eaten by performing m-bite no more than t times or print -1 if there is no such number r.InputThe first line of input contains three integers A, B and n (1ββ€βA,βBββ€β106, 1ββ€βnββ€β105).Next n lines contain information about queries. i-th line contains integers l,βt,βm (1ββ€βl,βt,βmββ€β106) for i-th query.OutputFor each query, print its answer in a single line.ExamplesInput2 1 41 5 33 3 107 10 26 4 8Output4-18-1Input1 5 21 5 102 7 4Output12 | Input2 1 41 5 33 3 107 10 26 4 8 | Output4-18-1 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'math', '*1900'] |
B. Tavas and SaDDastime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you." The problem is: You are given a lucky number n. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.If we sort all lucky numbers in increasing order, what's the 1-based index of n? Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.InputThe first and only line of input contains a lucky number n (1ββ€βnββ€β109).OutputPrint the index of n among all lucky numbers.ExamplesInput4Output1Input7Output2Input77Output6 | Input4 | Output1 | 1 second | 256 megabytes | ['bitmasks', 'brute force', 'combinatorics', 'implementation', '*1100'] |
A. Tavas and Nafastime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words. He ate coffee mix without water again, so right now he's really messed up and can't think.Your task is to help him by telling him what to type.InputThe first and only line of input contains an integer s (0ββ€βsββ€β99), Tavas's score. OutputIn the first and only line of output, print a single string consisting only from English lowercase letters and hyphens ('-'). Do not use spaces.ExamplesInput6OutputsixInput99Outputninety-nineInput20OutputtwentyNoteYou can find all you need to know about English numerals in http://en.wikipedia.org/wiki/English_numerals . | Input6 | Outputsix | 1 second | 256 megabytes | ['brute force', 'implementation', '*1000'] |
F. Simplified Nonogramtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this task you have to write a program dealing with nonograms on fields no larger than 5βΓβ20.Simplified nonogram is a task where you have to build such field (each cell is either white or black) that satisfies the given information about rows and columns. For each row and each column the number of contiguous black segments is specified. For example if size of the field is nβ=β3,βmβ=β5, Π°nd numbers of contiguous black segments in rows are: [2,β3,β2] and in columns are: [1,β0,β1,β2,β1] then the solution may look like: It is guaranteed that on each test in the testset there exists at least one solution.InputIn the first line there follow two integers n, m (1ββ€βnββ€β5,β1ββ€βmββ€β20) β number of rows and number of columns respectively.Second line contains n integers a1,βa2,β...,βan where ai is the number of contiguous black segments in i-th row of the field. Similarly, third line contains m integers b1,βb2,β...,βbm where bi is the number of contiguous black segments in the i-th column of the field.It is guaranteed that there exists at least one solution.OutputOutput any possible solution. Output should consist of n lines each containing m characters. Denote white cell as "." and black cell as "*".ExamplesInput3 52 3 21 0 1 2 1Output*.**.*.*.**..**Input3 32 1 22 1 2Output*.*.*.*.*Input3 31 0 12 2 2Output***...*** | Input3 52 3 21 0 1 2 1 | Output*.**.*.*.**..** | 2 seconds | 256 megabytes | ['bitmasks', 'dp', 'hashing', 'meet-in-the-middle', '*2400'] |
E. Berland Local Positioning Systemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are n bus stops located along the street, the i-th of them is located at the distance ai from the central square, all distances are distinct, the stops are numbered in the order of increasing distance from the square, that is, aiβ<βaiβ+β1 for all i from 1 to nβ-β1. The bus starts its journey from the first stop, it passes stops 2, 3 and so on. It reaches the stop number n, turns around and goes in the opposite direction to stop 1, passing all the intermediate stops in the reverse order. After that, it again starts to move towards stop n. During the day, the bus runs non-stop on this route.The bus is equipped with the Berland local positioning system. When the bus passes a stop, the system notes down its number.One of the key features of the system is that it can respond to the queries about the distance covered by the bus for the parts of its path between some pair of stops. A special module of the system takes the input with the information about a set of stops on a segment of the path, a stop number occurs in the set as many times as the bus drove past it. This module returns the length of the traveled segment of the path (or -1 if it is impossible to determine the length uniquely). The operation of the module is complicated by the fact that stop numbers occur in the request not in the order they were visited but in the non-decreasing order.For example, if the number of stops is 6, and the part of the bus path starts at the bus stop number 5, ends at the stop number 3 and passes the stops as follows: , then the request about this segment of the path will have form: 3,β4,β5,β5,β6. If the bus on the segment of the path from stop 5 to stop 3 has time to drive past the 1-th stop (i.e., if we consider a segment that ends with the second visit to stop 3 on the way from 5), then the request will have form: 1,β2,β2,β3,β3,β4,β5,β5,β6.You will have to repeat the Berland programmers achievement and implement this function.InputThe first line contains integer n (2ββ€βnββ€β2Β·105) β the number of stops.The second line contains n integers (1ββ€βaiββ€β109) β the distance from the i-th stop to the central square. The numbers in the second line go in the increasing order.The third line contains integer m (1ββ€βmββ€β4Β·105) β the number of stops the bus visited on some segment of the path.The fourth line contains m integers (1ββ€βbiββ€βn) β the sorted list of numbers of the stops visited by the bus on the segment of the path. The number of a stop occurs as many times as it was visited by a bus.It is guaranteed that the query corresponds to some segment of the path.OutputIn the single line please print the distance covered by a bus. If it is impossible to determine it unambiguously, print β-β1.ExamplesInput62 3 5 7 11 1353 4 5 5 6Output10Input62 3 5 7 11 1391 2 2 3 3 4 5 5 6Output16Input310 200 30041 2 2 3Output-1Input31 2 341 2 2 3Output3NoteThe first test from the statement demonstrates the first example shown in the statement of the problem.The second test from the statement demonstrates the second example shown in the statement of the problem.In the third sample there are two possible paths that have distinct lengths, consequently, the sought length of the segment isn't defined uniquely.In the fourth sample, even though two distinct paths correspond to the query, they have the same lengths, so the sought length of the segment is defined uniquely. | Input62 3 5 7 11 1353 4 5 5 6 | Output10 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'hashing', 'implementation', '*2400'] |
D. Handshakestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn February, 30th n students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in stayed in CTOP until the end of the day and never left.At any time any three students could join together and start participating in a team contest, which lasted until the end of the day. The team did not distract from the contest for a minute, so when another student came in and greeted those who were present, he did not shake hands with the members of the contest writing team. Each team consisted of exactly three students, and each student could not become a member of more than one team. Different teams could start writing contest at different times.Given how many present people shook the hands of each student, get a possible order in which the students could have come to CTOP. If such an order does not exist, then print that this is impossible.Please note that some students could work independently until the end of the day, without participating in a team contest.InputThe first line contains integer n (1ββ€βnββ€β2Β·105) β the number of students who came to CTOP. The next line contains n integers a1,βa2,β...,βan (0ββ€βaiβ<βn), where ai is the number of students with who the i-th student shook hands.OutputIf the sought order of students exists, print in the first line "Possible" and in the second line print the permutation of the students' numbers defining the order in which the students entered the center. Number i that stands to the left of number j in this permutation means that the i-th student came earlier than the j-th student. If there are multiple answers, print any of them.If the sought order of students doesn't exist, in a single line print "Impossible".ExamplesInput52 1 3 0 1OutputPossible4 5 1 3 2 Input90 2 3 4 1 1 0 2 2OutputPossible7 5 2 1 6 8 3 4 9Input40 2 1 1OutputImpossibleNoteIn the first sample from the statement the order of events could be as follows: student 4 comes in (a4β=β0), he has no one to greet; student 5 comes in (a5β=β1), he shakes hands with student 4; student 1 comes in (a1β=β2), he shakes hands with two students (students 4, 5); student 3 comes in (a3β=β3), he shakes hands with three students (students 4, 5, 1); students 4, 5, 3 form a team and start writing a contest; student 2 comes in (a2β=β1), he shakes hands with one student (number 1). In the second sample from the statement the order of events could be as follows: student 7 comes in (a7β=β0), he has nobody to greet; student 5 comes in (a5β=β1), he shakes hands with student 7; student 2 comes in (a2β=β2), he shakes hands with two students (students 7, 5); students 7, 5, 2 form a team and start writing a contest; student 1 comes in(a1β=β0), he has no one to greet (everyone is busy with the contest); student 6 comes in (a6β=β1), he shakes hands with student 1; student 8 comes in (a8β=β2), he shakes hands with two students (students 1, 6); student 3 comes in (a3β=β3), he shakes hands with three students (students 1, 6, 8); student 4 comes in (a4β=β4), he shakes hands with four students (students 1, 6, 8, 3); students 8, 3, 4 form a team and start writing a contest; student 9 comes in (a9β=β2), he shakes hands with two students (students 1, 6). In the third sample from the statement the order of events is restored unambiguously: student 1 comes in (a1β=β0), he has no one to greet; student 3 comes in (or student 4) (a3β=βa4β=β1), he shakes hands with student 1; student 2 comes in (a2β=β2), he shakes hands with two students (students 1, 3 (or 4)); the remaining student 4 (or student 3), must shake one student's hand (a3β=βa4β=β1) but it is impossible as there are only two scenarios: either a team formed and he doesn't greet anyone, or he greets all the three present people who work individually. | Input52 1 3 0 1 | OutputPossible4 5 1 3 2 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', 'greedy', '*1900'] |
C. Polycarpus' Dicetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has n dice d1,βd2,β...,βdn. The i-th dice shows numbers from 1 to di. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d1,βd2,β...,βdn. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is Aβ=β11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.InputThe first line contains two integers n,βA (1ββ€βnββ€β2Β·105,βnββ€βAββ€βs) β the number of dice and the sum of shown values where sβ=βd1β+βd2β+β...β+βdn.The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β106), where di is the maximum value that the i-th dice can show.OutputPrint n integers b1,βb2,β...,βbn, where bi is the number of values for which it is guaranteed that the i-th dice couldn't show them.ExamplesInput2 84 4Output3 3 Input1 35Output4 Input2 32 3Output0 1 NoteIn the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3. | Input2 84 4 | Output3 3 | 1 second | 256 megabytes | ['math', '*1600'] |
B. Covered Pathtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe on-board computer on Polycarp's car measured that the car speed at the beginning of some section of the path equals v1 meters per second, and in the end it is v2 meters per second. We know that this section of the route took exactly t seconds to pass.Assuming that at each of the seconds the speed is constant, and between seconds the speed can change at most by d meters per second in absolute value (i.e., the difference in the speed of any two adjacent seconds does not exceed d in absolute value), find the maximum possible length of the path section in meters.InputThe first line contains two integers v1 and v2 (1ββ€βv1,βv2ββ€β100) β the speeds in meters per second at the beginning of the segment and at the end of the segment, respectively.The second line contains two integers t (2ββ€βtββ€β100) β the time when the car moves along the segment in seconds, d (0ββ€βdββ€β10) β the maximum value of the speed change between adjacent seconds.It is guaranteed that there is a way to complete the segment so that: the speed in the first second equals v1, the speed in the last second equals v2, the absolute value of difference of speeds between any two adjacent seconds doesn't exceed d. OutputPrint the maximum possible length of the path segment in meters. ExamplesInput5 64 2Output26Input10 1010 0Output100NoteIn the first sample the sequence of speeds of Polycarpus' car can look as follows: 5, 7, 8, 6. Thus, the total path is 5β+β7β+β8β+β6β=β26 meters.In the second sample, as dβ=β0, the car covers the whole segment at constant speed vβ=β10. In tβ=β10 seconds it covers the distance of 100 meters. | Input5 64 2 | Output26 | 1 second | 256 megabytes | ['dp', 'greedy', 'math', '*1400'] |
A. Examtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and iβ+β1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sure.Your task is to choose the maximum number of students and make such an arrangement of students in the room that no two students with adjacent numbers sit side by side.InputA single line contains integer n (1ββ€βnββ€β5000) β the number of students at an exam.OutputIn the first line print integer k β the maximum number of students who can be seated so that no two students with adjacent numbers sit next to each other.In the second line print k distinct integers a1,βa2,β...,βak (1ββ€βaiββ€βn), where ai is the number of the student on the i-th position. The students on adjacent positions mustn't have adjacent numbers. Formally, the following should be true: |aiβ-βaiβ+β1|ββ β1 for all i from 1 to kβ-β1.If there are several possible answers, output any of them.ExamplesInput6Output61 5 3 6 2 4Input3Output21 3 | Input6 | Output61 5 3 6 2 4 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', 'math', '*1100'] |
F. Encodingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp invented a new way to encode strings. Let's assume that we have string T, consisting of lowercase English letters. Let's choose several pairs of letters of the English alphabet in such a way that each letter occurs in at most one pair. Then let's replace each letter in T with its pair letter if there is a pair letter for it. For example, if you chose pairs (l, r), (p, q) and (a, o), then word "parallelogram" according to the given encoding principle transforms to word "qolorreraglom".Polycarpus already has two strings, S and T. He suspects that string T was obtained after applying the given encoding method from some substring of string S. Find all positions mi in S (1ββ€βmiββ€β|S|β-β|T|β+β1), such that T can be obtained fro substring SmiSmiβ+β1... Smiβ+β|T|β-β1 by applying the described encoding operation by using some set of pairs of English alphabet lettersInputThe first line of the input contains two integers, |S| and |T| (1ββ€β|T|ββ€β|S|ββ€β2Β·105) β the lengths of string S and string T, respectively.The second and third line of the input contain strings S and T, respectively. Both strings consist only of lowercase English letters.OutputPrint number k β the number of suitable positions in string S.In the next line print k integers m1,βm2,β...,βmk β the numbers of the suitable positions in the increasing order.ExamplesInput11 5abacabadabaacabaOutput31 3 7Input21 13paraparallelogramgramqolorreraglomOutput15 | Input11 5abacabadabaacaba | Output31 3 7 | 3 seconds | 256 megabytes | ['hashing', 'string suffix structures', 'strings', '*2400'] |
E. Correcting Mistakestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnalyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.Implement a program that can, given two distinct words S and T of the same length n determine how many words W of length nβ+β1 are there with such property that you can transform W into both S, and T by deleting exactly one character. Words S and T consist of lowercase English letters. Word W also should consist of lowercase English letters.InputThe first line contains integer n (1ββ€βnββ€β100β000) β the length of words S and T.The second line contains word S.The third line contains word T.Words S and T consist of lowercase English letters. It is guaranteed that S and T are distinct words.OutputPrint a single integer β the number of distinct words W that can be transformed to S and T due to a typo.ExamplesInput7readingtradingOutput1Input5sweetsheepOutput0Input3toytryOutput2NoteIn the first sample test the two given words could be obtained only from word "treading" (the deleted letters are marked in bold).In the second sample test the two given words couldn't be obtained from the same word by removing one letter.In the third sample test the two given words could be obtained from either word "tory" or word "troy". | Input7readingtrading | Output1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dp', 'greedy', 'hashing', 'strings', 'two pointers', '*1800'] |
D. Landmarkstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe have an old building with nβ+β2 columns in a row. These columns support the ceiling. These columns are located in points with coordinates 0β=βx0β<βx1β<β...β<βxnβ<βxnβ+β1. The leftmost and the rightmost columns are special, we will call them bearing, the other columns are ordinary. For each column we know its durability di. Let's consider an ordinary column with coordinate x. Let's assume that the coordinate of the closest to it column to the left (bearing or ordinary) is a and the coordinate of the closest to it column to the right (also, bearing or ordinary) is b. In this task let's assume that this column supports the segment of the ceiling from point to point (here both fractions are considered as real division). If the length of the segment of the ceiling supported by the column exceeds di, then the column cannot support it and it crashes after a while, and after that the load is being redistributeed between the neighbouring columns according to the same principle. Thus, ordinary columns will be crashing for some time until the process stops at some state. One can prove that the set of the remaining columns doesn't depend on the order in which columns crash. If there are only two bearing columns left in the end, then we assume that the whole construction crashes under the weight of the roof. But if at least one ordinary column stays in addition to the bearing ones, then the building doesn't crash.To make the building stronger, we can add one extra ordinary column of arbitrary durability d' at any (not necessarily integer) point 0β<βx'β<βxnβ+β1. If point x' is already occupied by an ordinary column, it is replaced by a new one.Your task is to find out: what minimal durability can the added column have so that the building doesn't crash?InputThe first line contains integer n (1ββ€βnββ€β105) β the number of ordinary columns.The second line contains nβ+β2 integers x0,βx1,β...,βxn,βxnβ+β1 (x0β=β0, xiβ<βxiβ+β1 for 0ββ€βiββ€βn, xnβ+β1ββ€β109) β the coordinates of the columns.The third line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β109).OutputPrint a single number β the minimum possible durability of the column that you need to add in order to make the building stay. If you do not have to add the column, please print 0. Your answer will be checked with the relative or absolute error 10β-β4.ExamplesInput20 20 40 10015 40Output10Input30 4 10 28 309 13 5Output0 | Input20 20 40 10015 40 | Output10 | 2 seconds | 256 megabytes | ['data structures', 'dp', '*3000'] |
C. Board Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp and Vasiliy love simple logical games. Today they play a game with infinite chessboard and one pawn for each player. Polycarp and Vasiliy move in turns, Polycarp starts. In each turn Polycarp can move his pawn from cell (x,βy) to (xβ-β1,βy) or (x,βyβ-β1). Vasiliy can move his pawn from (x,βy) to one of cells: (xβ-β1,βy),β(xβ-β1,βyβ-β1) and (x,βyβ-β1). Both players are also allowed to skip move. There are some additional restrictions β a player is forbidden to move his pawn to a cell with negative x-coordinate or y-coordinate or to the cell containing opponent's pawn The winner is the first person to reach cell (0,β0). You are given the starting coordinates of both pawns. Determine who will win if both of them play optimally well.InputThe first line contains four integers: xp,βyp,βxv,βyv (0ββ€βxp,βyp,βxv,βyvββ€β105) β Polycarp's and Vasiliy's starting coordinates.It is guaranteed that in the beginning the pawns are in different cells and none of them is in the cell (0,β0).OutputOutput the name of the winner: "Polycarp" or "Vasiliy".ExamplesInput2 1 2 2OutputPolycarpInput4 7 7 4OutputVasiliyNoteIn the first sample test Polycarp starts in (2,β1) and will move to (1,β1) in the first turn. No matter what his opponent is doing, in the second turn Polycarp can move to (1,β0) and finally to (0,β0) in the third turn. | Input2 1 2 2 | OutputPolycarp | 1 second | 256 megabytes | ['games', 'greedy', 'implementation', 'math', '*1700'] |
B. Work Grouptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior.We will call person a a subordinates of another person b, if either b is an immediate supervisor of a, or the immediate supervisor of a is a subordinate to person b. In particular, subordinates of the head are all other employees of the company.To solve achieve an Important Goal we need to form a workgroup. Every person has some efficiency, expressed by a positive integer ai, where i is the person's number. The efficiency of the workgroup is defined as the total efficiency of all the people included in it.The employees of the big software company are obsessed with modern ways of work process organization. Today pair programming is at the peak of popularity, so the workgroup should be formed with the following condition. Each person entering the workgroup should be able to sort all of his subordinates who are also in the workgroup into pairs. In other words, for each of the members of the workgroup the number of his subordinates within the workgroup should be even.Your task is to determine the maximum possible efficiency of the workgroup formed at observing the given condition. Any person including the director of company can enter the workgroup.InputThe first line contains integer n (1ββ€βnββ€β2Β·105) β the number of workers of the Big Software Company. Then n lines follow, describing the company employees. The i-th line contains two integers pi,βai (1ββ€βaiββ€β105) β the number of the person who is the i-th employee's immediate superior and i-th employee's efficiency. For the director p1β=ββ-β1, for all other people the condition 1ββ€βpiβ<βi is fulfilled.OutputPrint a single integer β the maximum possible efficiency of the workgroup.ExamplesInput7-1 31 21 11 44 54 35 2Output17NoteIn the sample test the most effective way is to make a workgroup from employees number 1,β2,β4,β5,β6. | Input7-1 31 21 11 44 54 35 2 | Output17 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'strings', 'trees', '*2000'] |
A. Berland Minerstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe biggest gold mine in Berland consists of n caves, connected by nβ-β1 transitions. The entrance to the mine leads to the cave number 1, it is possible to go from it to any remaining cave of the mine by moving along the transitions. The mine is being developed by the InMine Inc., k miners work for it. Each day the corporation sorts miners into caves so that each cave has at most one miner working there. For each cave we know the height of its ceiling hi in meters, and for each miner we know his height sj, also in meters. If a miner's height doesn't exceed the height of the cave ceiling where he is, then he can stand there comfortably, otherwise, he has to stoop and that makes him unhappy.Unfortunately, miners typically go on strike in Berland, so InMine makes all the possible effort to make miners happy about their work conditions. To ensure that no miner goes on strike, you need make sure that no miner has to stoop at any moment on his way from the entrance to the mine to his cave (in particular, he must be able to stand comfortably in the cave where he works). To reach this goal, you can choose exactly one cave and increase the height of its ceiling by several meters. However enlarging a cave is an expensive and complex procedure. That's why InMine Inc. asks you either to determine the minimum number of meters you should raise the ceiling of some cave so that it is be possible to sort the miners into the caves and keep all miners happy with their working conditions or to determine that it is impossible to achieve by raising ceiling in exactly one cave.InputThe first line contains integer n (1ββ€βnββ€β5Β·105) β the number of caves in the mine.Then follows a line consisting of n positive integers h1,βh2,β...,βhn (1ββ€βhiββ€β109), where hi is the height of the ceiling in the i-th cave.Next nβ-β1 lines contain the descriptions of transitions between the caves. Each line has the form ai,βbi (1ββ€βai,βbiββ€βn, aiββ βbi), where ai and bi are the numbers of the caves connected by a path.The next line contains integer k (1ββ€βkββ€βn).The last line contains k integers s1,βs2,β...,βsk (1ββ€βsjββ€β109), where sj is the j-th miner's height.OutputIn the single line print the minimum number of meters that you need to raise the ceiling by in some cave so that all miners could be sorted into caves and be happy about the work conditions. If it is impossible to do, print β-β1. If it is initially possible and there's no need to raise any ceiling, print 0. ExamplesInput65 8 4 6 3 121 21 34 22 56 367 4 2 5 3 11Output6Input710 14 7 12 4 50 11 22 32 45 16 51 767 3 4 8 8 10Output0Input34 2 81 21 3217 15Output-1NoteIn the first sample test we should increase ceiling height in the first cave from 5 to 11. After that we can distribute miners as following (first goes index of a miner, then index of a cave): .In the second sample test there is no need to do anything since it is already possible to distribute miners as following: .In the third sample test it is impossible. | Input65 8 4 6 3 121 21 34 22 56 367 4 2 5 3 11 | Output6 | 3 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', 'greedy', 'trees', '*3000'] |
I. Different variablestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputN variables X1,β...,βXN can have positive integer values. You are given K constraints for these value that look like "the values of variables Xi1,βXi2,β...,βXiM are different". Among all possible lists of values of these variables that satisfy these constraints select the ones which have minimum possible max(Xi). Output lexicographically least of these lists.InputThe first line of input contains two integers n and k (2ββ€βNββ€β10, 1ββ€βKββ€β100) β the number of variables and the number of constraints.The following K lines contain the constraints, formatted as follows: the first number in the line M (2ββ€βMββ€βN) gives the number of variables in the constraint. After it follow M space-separated integers i1,β...,βiM β the indices of the variables used in the constraint (1ββ€βijββ€βN). All ij in one constraint are different.OutputOutput the values of X1,βX2,β...,βXN in a single line, separated with single spaces.ExamplesInput2 12 1 2Output1 2Input3 22 1 22 2 3Output1 2 1 | Input2 12 1 2 | Output1 2 | 2 seconds | 256 megabytes | ['*special problem', '*2500'] |
H. Points in triangletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of points on a plane with positive integer coordinates. Find a triangle of minimum area with vertices in points (0,β0), (A,β0) and (0,βB) (A and B are unknown positive integers) that contains all the given points inside it (points on the edges count towards being inside).InputThe first line of the input contains an integer N (1ββ€βNββ€β100) β the number of points. The following N lines contain pairs of numbers X and Y (1ββ€βX,βYββ€β100) - the coordinates of the points. All points are distinct.OutputOutput one floating-point number β the minimal area of the triangle. The answer is considered to be correct if its absolute or relative error does not exceed 10β-β4.ExamplesInput21 11 3Output6.0Input22 11 2Output4.5 | Input21 11 3 | Output6.0 | 2 seconds | 256 megabytes | ['*special problem', 'geometry', '*2100'] |
G. Levenshtein distancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLevenshtein distance between two strings of letters is calculated as the minimal total cost of a sequence of edit actions that converts one of the strings into the other one. The allowed edit actions are: substitution: the cost of substituting one letter with another is equal to the difference of index numbers of these letters in English alphabet. insertion/deletion: the cost of inserting a letter into a string or deleting a letter from a string is equal to the index number of this letter in English alphabet (see examples).You are given two strings. Find the Levenshtein distance between them.InputThe input data consists of two lines, each line contains a string of lowercase Latin letters. Each string is between 1 and 100 letters long, inclusive.OutputOutput a single integer β the Levenshtein distance between the strings.ExamplesInputarcbugOutput8InputdomedroneOutput19NoteIn the first example you should replace a with b (cost 1), r with u (cost 3) and c with g (cost 4).In the second example you should insert r (cost 18) are replace m with n (cost 1). | Inputarcbug | Output8 | 2 seconds | 256 megabytes | ['*special problem', '*2100'] |
F. Jumping frogstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA rectangular swamp is inhabited by 10 species of frogs. Frogs of species i can jump from hillocks to hillock exactly i units along X-axis or Y-axis. Initially frogs of all types sit at the hillock at coordinates (0, 0). You are given coordinates of all other hillocks in the swamp. Find the largest Manhattan distance from (0, 0) to any hillock to which one of the frogs can travel by jumping between hillocks.Manhattan distance between (x1,βy1) and (x2,βy2) is |x1β-βx2|β+β|y1β-βy2|.InputThe first line of the input contains an integer N (1ββ€βNββ€β100) - the number of hillocks. The following N lines contain the coordinates of the hillocks, formatted as "X Y" (β-β20ββ€βX,βYββ€β20). All hillocks are distinct, and none of them is located at (0, 0).OutputOutput a single integer β the largest Manhattan distance to any hillock reachable by one of the frogs by jumping between hillocks.ExamplesInput30 10 -20 3Output3Input50 10 20 32 22 4Output6Input118 0Output0NoteIn the first example frogs of species 1, 2 and 3 can jump as far as the first, the second and the third hillocks, respectively.In the second example frog of species 2 can jump to the second hillock, then to the fourth and finally to the fifth.In the third example no frog can reach the hillock. | Input30 10 -20 3 | Output3 | 2 seconds | 256 megabytes | ['*special problem', '*2100'] |
E. Sum and producttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given integers N and D. Find N positive integers x1...xN such that the difference of their product and their sum equals D.InputThe only line of input contains integers N (2ββ€βNββ€β1000) and D (0ββ€βDββ€β1000).OutputOutput N integers that satisfy the given condition in non-decreasing order (in a single line, separated with spaces). Note that some numbers can be equal. Numbers printed by you must not exceed 106.ExamplesInput2 1Output2 3Input3 5Output1 2 8 | Input2 1 | Output2 3 | 2 seconds | 256 megabytes | ['*special problem', '*1700'] |
D. Set subtractiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a starting set consisting of all integers from 1 to 1000, inclusive. You are also given several sets which need to be subtracted from the starting set (i.e., each number which is in at least one of these sets needs to be removed from the starting set). Each subtracted set is represented as an interval of integers from A to B, inclusive. Output the result after all subtractions.InputThe first line of input contains an integer N (0ββ€βNββ€β100) β the number of intervals to be subtracted. The following N lines contain pairs of integers A and B (1ββ€βAββ€βBββ€β1000) β lower and upper bounds of the intervals. Intervals can intersect. An interval can consist of a single number.OutputOutput the result of subtractions in the following format: in one line output first the number of integers in the resulting set and then the integers of the set, sorted in increasing order, separated by single space.ExamplesInput21 900902 999Output2 901 1000Input31 500200 746150 1000Output0 | Input21 900902 999 | Output2 901 1000 | 2 seconds | 256 megabytes | ['*special problem', '*1600'] |
C. Diophantine equationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an equation Aβ*βXβ+βBβ*βYβ=βC, A,βB,βC are positive integer coefficients, X and Y are variables which can have positive integer values only. Output the number of solutions of this equation and the solutions themselves.InputThe only line of input contains integers A,βB and C (1ββ€βA,βB,βCββ€β1000), separated with spaces.OutputIn the first line of the output print the number of the solutions N. In the next N lines print the solutions, formatted as "XY", sorted in ascending order of X, one solution per line.ExamplesInput3 5 35Output25 410 1Input3 35 5Output0 | Input3 5 35 | Output25 410 1 | 2 seconds | 256 megabytes | ['*special problem', '*1500'] |
Subsets and Splits