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. Amr and Musictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.Amr has n instruments, it takes ai days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments.Amr asked for your help to distribute his free days between instruments so that he can achieve his goal.InputThe first line contains two numbers n, k (1ββ€βnββ€β100, 0ββ€βkββ€β10β000), the number of instruments and number of days respectively.The second line contains n integers ai (1ββ€βaiββ€β100), representing number of days required to learn the i-th instrument.OutputIn the first line output one integer m representing the maximum number of instruments Amr can learn.In the second line output m space-separated integers: the indices of instruments to be learnt. You may output indices in any order.if there are multiple optimal solutions output any. It is not necessary to use all days for studying.ExamplesInput4 104 3 1 2Output41 2 3 4Input5 64 3 1 1 2Output31 3 4Input1 34Output0NoteIn the first test Amr can learn all 4 instruments.In the second test other possible solutions are: {2,β3,β5} or {3,β4,β5}.In the third test Amr doesn't have enough time to learn the only presented instrument. | Input4 104 3 1 2 | Output41 2 3 4 | 1 second | 256 megabytes | ['greedy', 'implementation', 'sortings', '*1000'] |
E. Mr. Kitayuta's Gifttime limit per test6 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputMr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly n lowercase English letters into s to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.) You can choose any n lowercase English letters, and insert each of them to any position of s, possibly to the beginning or the end of s. You have to insert exactly n letters even if it is possible to turn s into a palindrome by inserting less than n letters.Find the number of the palindromes that can be obtained in this way, modulo 10007.InputThe first line contains a string s (1ββ€β|s|ββ€β200). Each character in s is a lowercase English letter.The second line contains an integer n (1ββ€βnββ€β109).OutputPrint the number of the palindromes that can be obtained, modulo 10007.ExamplesInputrevive1Output1Inputadd2Output28NoteFor the first sample, you can obtain the palindrome "reviver" by inserting 'r' to the end of "revive".For the second sample, the following 28 palindromes can be obtained: "adada", "adbda", ..., "adzda", "dadad" and "ddadd". | Inputrevive1 | Output1 | 6 seconds | 768 megabytes | ['combinatorics', 'dp', 'matrices', 'strings', '*3000'] |
D. Mr. Kitayuta's Colorful Graphtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.Mr. Kitayuta wants you to process the following q queries.In the i-th query, he gives you two integers - ui and vi.Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.InputThe first line of the input contains space-separated two integers - n and m(2ββ€βnββ€β105,β1ββ€βmββ€β105), denoting the number of the vertices and the number of the edges, respectively.The next m lines contain space-separated three integers - ai, bi(1ββ€βaiβ<βbiββ€βn) and ci(1ββ€βciββ€βm). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if iββ βj,β(ai,βbi,βci)ββ β(aj,βbj,βcj).The next line contains a integer- q(1ββ€βqββ€β105), denoting the number of the queries.Then follows q lines, containing space-separated two integers - ui and vi(1ββ€βui,βviββ€βn). It is guaranteed that uiββ βvi.OutputFor each query, print the answer in a separate line.ExamplesInput4 51 2 11 2 22 3 12 3 32 4 331 23 41 4Output210Input5 71 5 12 5 13 5 14 5 11 2 22 3 23 4 251 55 12 51 51 4Output11112NoteLet's consider the first sample. The figure above shows the first sample. Vertex 1 and vertex 2 are connected by color 1 and 2. Vertex 3 and vertex 4 are connected by color 3. Vertex 1 and vertex 4 are not connected by any single color. | Input4 51 2 11 2 22 3 12 3 32 4 331 23 41 4 | Output210 | 4 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'dsu', 'graphs', '*2400'] |
E. Mr. Kitayuta vs. Bamboostime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Kitayuta's garden is planted with n bamboos. (Bamboos are tall, fast-growing tropical plants with hollow stems.) At the moment, the height of the i-th bamboo is hi meters, and it grows ai meters at the end of each day. Actually, Mr. Kitayuta hates these bamboos. He once attempted to cut them down, but failed because their stems are too hard. Mr. Kitayuta have not given up, however. He has crafted Magical Hammer with his intelligence to drive them into the ground.He can use Magical Hammer at most k times during each day, due to his limited Magic Power. Each time he beat a bamboo with Magical Hammer, its height decreases by p meters. If the height would become negative by this change, it will become 0 meters instead (it does not disappear). In other words, if a bamboo whose height is h meters is beaten with Magical Hammer, its new height will be max(0,βhβ-βp) meters. It is possible to beat the same bamboo more than once in a day.Mr. Kitayuta will fight the bamboos for m days, starting today. His purpose is to minimize the height of the tallest bamboo after m days (that is, m iterations of "Mr. Kitayuta beats the bamboos and then they grow"). Find the lowest possible height of the tallest bamboo after m days.InputThe first line of the input contains four space-separated integers n, m, k and p (1ββ€βnββ€β105,β1ββ€βmββ€β5000,β1ββ€βkββ€β10,β1ββ€βpββ€β109). They represent the number of the bamboos in Mr. Kitayuta's garden, the duration of Mr. Kitayuta's fight in days, the maximum number of times that Mr. Kitayuta beat the bamboos during each day, and the power of Magic Hammer, respectively.The following n lines describe the properties of the bamboos. The i-th of them (1ββ€βiββ€βn) contains two space-separated integers hi and ai (0ββ€βhiββ€β109,β1ββ€βaiββ€β109), denoting the initial height and the growth rate of the i-th bamboo, respectively.OutputPrint the lowest possible height of the tallest bamboo after m days.ExamplesInput3 1 2 510 1010 1015 2Output17Input2 10 10 10000000000 100 10Output10Input5 3 3 109 59 24 79 103 8Output14 | Input3 1 2 510 1010 1015 2 | Output17 | 2 seconds | 256 megabytes | ['binary search', 'greedy', '*2900'] |
D. Mr. Kitayuta's Technologytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputShuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n.Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city x to city y cannot be used to travel from city y to city x. The transportation within each city is extremely developed, therefore if a pipe from city x to city y and a pipe from city y to city z are both constructed, people will be able to travel from city x to city z instantly.Mr. Kitayuta is also involved in national politics. He considers that the transportation between the m pairs of city (ai,βbi) (1ββ€βiββ€βm) is important. He is planning to construct teleportation pipes so that for each important pair (ai,βbi), it will be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.InputThe first line contains two space-separated integers n and m (2ββ€βnββ€β105,β1ββ€βmββ€β105), denoting the number of the cities in Shuseki Kingdom and the number of the important pairs, respectively.The following m lines describe the important pairs. The i-th of them (1ββ€βiββ€βm) contains two space-separated integers ai and bi (1ββ€βai,βbiββ€βn,βaiββ βbi), denoting that it must be possible to travel from city ai to city bi by using one or more teleportation pipes (but not necessarily from city bi to city ai). It is guaranteed that all pairs (ai,βbi) are distinct.OutputPrint the minimum required number of teleportation pipes to fulfill Mr. Kitayuta's purpose.ExamplesInput4 51 21 31 42 32 4Output3Input4 61 21 42 32 43 23 4Output4NoteFor the first sample, one of the optimal ways to construct pipes is shown in the image below: For the second sample, one of the optimal ways is shown below: | Input4 51 21 31 42 32 4 | Output3 | 1 second | 256 megabytes | ['dfs and similar', '*2200'] |
C. Mr. Kitayuta, the Treasure Huntertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Shuseki Islands are an archipelago of 30001 small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from 0 to 30000 from the west to the east. These islands are known to contain many treasures. There are n gems in the Shuseki Islands in total, and the i-th gem is located on island pi.Mr. Kitayuta has just arrived at island 0. With his great jumping ability, he will repeatedly perform jumps between islands to the east according to the following process: First, he will jump from island 0 to island d. After that, he will continue jumping according to the following rule. Let l be the length of the previous jump, that is, if his previous jump was from island prev to island cur, let lβ=βcurβ-βprev. He will perform a jump of length lβ-β1, l or lβ+β1 to the east. That is, he will jump to island (curβ+βlβ-β1), (curβ+βl) or (curβ+βlβ+β1) (if they exist). The length of a jump must be positive, that is, he cannot perform a jump of length 0 when lβ=β1. If there is no valid destination, he will stop jumping. Mr. Kitayuta will collect the gems on the islands visited during the process. Find the maximum number of gems that he can collect.InputThe first line of the input contains two space-separated integers n and d (1ββ€βn,βdββ€β30000), denoting the number of the gems in the Shuseki Islands and the length of the Mr. Kitayuta's first jump, respectively.The next n lines describe the location of the gems. The i-th of them (1ββ€βiββ€βn) contains a integer pi (dββ€βp1ββ€βp2ββ€β...ββ€βpnββ€β30000), denoting the number of the island that contains the i-th gem.OutputPrint the maximum number of gems that Mr. Kitayuta can collect.ExamplesInput4 1010212727Output3Input8 8919283645556678Output6Input13 788916171718212324242630Output4NoteIn the first sample, the optimal route is 0 βββ 10 (+1 gem) βββ 19 βββ 27 (+2 gems) βββ...In the second sample, the optimal route is 0 βββ 8 βββ 15 βββ 21βββ 28 (+1 gem) βββ 36 (+1 gem) βββ 45 (+1 gem) βββ 55 (+1 gem) βββ 66 (+1 gem) βββ 78 (+1 gem) βββ...In the third sample, the optimal route is 0 βββ 7 βββ 13 βββ 18 (+1 gem) βββ 24 (+2 gems) βββ 30 (+1 gem) βββ... | Input4 1010212727 | Output3 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'two pointers', '*1900'] |
B. Mr. Kitayuta's Colorful Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Kitayuta has just bought an undirected graph consisting of n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.Mr. Kitayuta wants you to process the following q queries.In the i-th query, he gives you two integers β ui and vi.Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.InputThe first line of the input contains space-separated two integers β n and m (2ββ€βnββ€β100,β1ββ€βmββ€β100), denoting the number of the vertices and the number of the edges, respectively.The next m lines contain space-separated three integers β ai, bi (1ββ€βaiβ<βbiββ€βn) and ci (1ββ€βciββ€βm). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, if iββ βj, (ai,βbi,βci)ββ β(aj,βbj,βcj).The next line contains a integer β q (1ββ€βqββ€β100), denoting the number of the queries.Then follows q lines, containing space-separated two integers β ui and vi (1ββ€βui,βviββ€βn). It is guaranteed that uiββ βvi.OutputFor each query, print the answer in a separate line.ExamplesInput4 51 2 11 2 22 3 12 3 32 4 331 23 41 4Output210Input5 71 5 12 5 13 5 14 5 11 2 22 3 23 4 251 55 12 51 51 4Output11112NoteLet's consider the first sample. The figure above shows the first sample. Vertex 1 and vertex 2 are connected by color 1 and 2. Vertex 3 and vertex 4 are connected by color 3. Vertex 1 and vertex 4 are not connected by any single color. | Input4 51 2 11 2 22 3 12 3 32 4 331 23 41 4 | Output210 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'dsu', 'graphs', '*1400'] |
A. Mr. Kitayuta's Gifttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Kitayuta has kindly given you a string s consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into s to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.You can choose any lowercase English letter, and insert it to any position of s, possibly to the beginning or the end of s. You have to insert a letter even if the given string is already a palindrome.If it is possible to insert one lowercase English letter into s so that the resulting string will be a palindrome, print the string after the insertion. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one palindrome that can be obtained, you are allowed to print any of them.InputThe only line of the input contains a string s (1ββ€β|s|ββ€β10). Each character in s is a lowercase English letter.OutputIf it is possible to turn s into a palindrome by inserting one lowercase English letter, print the resulting string in a single line. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one solution, any of them will be accepted. ExamplesInputreviveOutputreviverInputeeOutputeyeInputkitayutaOutputNANoteFor the first sample, insert 'r' to the end of "revive" to obtain a palindrome "reviver".For the second sample, there is more than one solution. For example, "eve" will also be accepted.For the third sample, it is not possible to turn "kitayuta" into a palindrome by just inserting one letter. | Inputrevive | Outputreviver | 1 second | 256 megabytes | ['brute force', 'implementation', 'strings', '*1100'] |
E. Misha and LCP on Treetime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMisha has a tree with characters written on the vertices. He can choose two vertices s and t of this tree and write down characters of vertices lying on a path from s to t. We'll say that such string corresponds to pair (s,βt).Misha has m queries of type: you are given 4 vertices a, b, c, d; you need to find the largest common prefix of the strings that correspond to pairs (a,βb) and (c,βd). Your task is to help him.InputThe first line contains integer n (1ββ€βnββ€β300β000) β the number of vertices in the tree.Next follows a line consisting of n small English letters. The i-th character of the string corresponds to the character written on the i-th vertex. Next nβ-β1 lines contain information about edges. An edge is defined by a pair of integers u, v (1ββ€βu,βvββ€βn, uββ βv), separated by spaces.The next line contains integer m (1ββ€βmββ€β1β000β000) β the number of queries.Next m lines contain information about queries. A query is defined by four integers a, b, c, d (1ββ€βa,βb,βc,βdββ€βn), separated by spaces.OutputFor each query print the length of the largest common prefix on a separate line.ExamplesInput6bbbabb2 13 24 35 26 562 5 3 11 5 2 35 6 5 66 3 4 16 2 3 42 2 4 5Output222010 | Input6bbbabb2 13 24 35 26 562 5 3 11 5 2 35 6 5 66 3 4 16 2 3 42 2 4 5 | Output222010 | 8 seconds | 512 megabytes | ['binary search', 'dfs and similar', 'hashing', 'string suffix structures', 'trees', '*3000'] |
D. Misha and XORtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number x to the basket, Misha should answer the question: is it possible to choose one or multiple numbers that already are in the basket, such that their XOR sum equals x? If the answer is positive, you also need to give the indexes of these numbers. If there are multiple options of choosing numbers, you are allowed to choose any correct option. After Misha's answer the robot puts the number to the basket.Initially the basket is empty. Each integer you put in the basket takes some number. The first integer you put into the basket take number 0, the second integer takes number 1 and so on.Misha needs to clean up the place as soon as possible but unfortunately, he isn't that good at mathematics. He asks you to help him.InputThe first line contains number m (1ββ€βmββ€β2000), showing how many numbers are scattered around the room.The next m lines contain the numbers in the order in which the robot puts them in the basket. Each number is a positive integer strictly less than 10600 that doesn't contain leading zeroes. OutputFor each number either print a 0 on the corresponding line, if the number cannot be represented as a XOR sum of numbers that are in the basket, or print integer k showing how many numbers are in the representation and the indexes of these numbers. Separate the numbers by spaces. Each number can occur in the representation at most once.ExamplesInput77654321Output0003 0 1 22 1 22 0 22 0 1Input255Output01 0NoteThe XOR sum of numbers is the result of bitwise sum of numbers modulo 2. | Input77654321 | Output0003 0 1 22 1 22 0 22 0 1 | 2 seconds | 256 megabytes | ['bitmasks', '*2700'] |
E. Misha and Palindrome Degreetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisha has an array of n integers indexed by integers from 1 to n. Let's define palindrome degree of array a as the number of such index pairs (l,βr)(1ββ€βlββ€βrββ€βn), that the elements from the l-th to the r-th one inclusive can be rearranged in such a way that the whole array will be a palindrome. In other words, pair (l,βr) should meet the condition that after some rearranging of numbers on positions from l to r, inclusive (it is allowed not to rearrange the numbers at all), for any 1ββ€βiββ€βn following condition holds: a[i]β=βa[nβ-βiβ+β1]. Your task is to find the palindrome degree of Misha's array.InputThe first line contains integer n (1ββ€βnββ€β105).The second line contains n positive integers a[i] (1ββ€βa[i]ββ€βn), separated by spaces β the elements of Misha's array.OutputIn a single line print the answer to the problem.ExamplesInput32 2 2Output6Input63 6 5 3 3 5Output0Input55 5 2 5 2Output4NoteIn the first sample test any possible pair (l,βr) meets the condition.In the third sample test following pairs (1,β3),β(1,β4),β(1,β5),β(2,β5) meet the condition. | Input32 2 2 | Output6 | 1 second | 256 megabytes | ['binary search', 'combinatorics', 'implementation', '*2500'] |
D. Misha and Permutations Summationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define the sum of two permutations p and q of numbers 0,β1,β...,β(nβ-β1) as permutation , where Perm(x) is the x-th lexicographically permutation of numbers 0,β1,β...,β(nβ-β1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order.For example, Perm(0)β=β(0,β1,β...,βnβ-β2,βnβ-β1), Perm(n!β-β1)β=β(nβ-β1,βnβ-β2,β...,β1,β0)Misha has two permutations, p and q. Your task is to find their sum.Permutation aβ=β(a0,βa1,β...,βanβ-β1) is called to be lexicographically smaller than permutation bβ=β(b0,βb1,β...,βbnβ-β1), if for some k following conditions hold: a0β=βb0,βa1β=βb1,β...,βakβ-β1β=βbkβ-β1,βakβ<βbk.InputThe first line contains an integer n (1ββ€βnββ€β200β000).The second line contains n distinct integers from 0 to nβ-β1, separated by a space, forming permutation p.The third line contains n distinct integers from 0 to nβ-β1, separated by spaces, forming permutation q.OutputPrint n distinct integers from 0 to nβ-β1, forming the sum of the given permutations. Separate the numbers by spaces.ExamplesInput20 10 1Output0 1Input20 11 0Output1 0Input31 2 02 1 0Output1 0 2NotePermutations of numbers from 0 to 1 in the lexicographical order: (0,β1),β(1,β0).In the first sample Ord(p)β=β0 and Ord(q)β=β0, so the answer is .In the second sample Ord(p)β=β0 and Ord(q)β=β1, so the answer is .Permutations of numbers from 0 to 2 in the lexicographical order: (0,β1,β2),β(0,β2,β1),β(1,β0,β2),β(1,β2,β0),β(2,β0,β1),β(2,β1,β0).In the third sample Ord(p)β=β3 and Ord(q)β=β5, so the answer is . | Input20 10 1 | Output0 1 | 2 seconds | 256 megabytes | ['data structures', '*2000'] |
C. Misha and Foresttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to nβ-β1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.InputThe first line contains integer n (1ββ€βnββ€β216), the number of vertices in the graph.The i-th of the next lines contains numbers degreei and si (0ββ€βdegreeiββ€βnβ-β1, 0ββ€βsiβ<β216), separated by a space.OutputIn the first line print number m, the number of edges of the graph.Next print m lines, each containing two distinct numbers, a and b (0ββ€βaββ€βnβ-β1, 0ββ€βbββ€βnβ-β1), corresponding to edge (a,βb).Edges can be printed in any order; vertices of the edge can also be printed in any order.ExamplesInput32 31 01 0Output21 02 0Input21 11 0Output10 1NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal β as "xor". | Input32 31 01 0 | Output21 02 0 | 1 second | 256 megabytes | ['constructive algorithms', 'data structures', 'greedy', 'sortings', 'trees', '*1500'] |
B. Misha and Changing Handlestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.InputThe first line contains integer q (1ββ€βqββ€β1000), the number of handle change requests.Next q lines contain the descriptions of the requests, one per line.Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20.The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.OutputIn the first line output the integer n β the number of users that changed their handles at least once.In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order.Each user who changes the handle must occur exactly once in this description.ExamplesInput5Misha ILoveCodeforcesVasya PetrovPetrov VasyaPetrov123ILoveCodeforces MikeMirzayanovPetya IvanovOutput3Petya IvanovMisha MikeMirzayanovVasya VasyaPetrov123 | Input5Misha ILoveCodeforcesVasya PetrovPetrov VasyaPetrov123ILoveCodeforces MikeMirzayanovPetya Ivanov | Output3Petya IvanovMisha MikeMirzayanovVasya VasyaPetrov123 | 1 second | 256 megabytes | ['data structures', 'dsu', 'strings', '*1100'] |
A. Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contest started and Vasya submitted the problem d minutes after the contest started. As you know, on Codeforces the cost of a problem reduces as a round continues. That is, if you submit a problem that costs p points t minutes after the contest started, you get points. Misha and Vasya are having an argument trying to find out who got more points. Help them to find out the truth.InputThe first line contains four integers a, b, c, d (250ββ€βa,βbββ€β3500, 0ββ€βc,βdββ€β180). It is guaranteed that numbers a and b are divisible by 250 (just like on any real Codeforces round).OutputOutput on a single line: "Misha" (without the quotes), if Misha got more points than Vasya."Vasya" (without the quotes), if Vasya got more points than Misha."Tie" (without the quotes), if both of them got the same number of points.ExamplesInput500 1000 20 30OutputVasyaInput1000 1000 1 1OutputTieInput1500 1000 176 177OutputMisha | Input500 1000 20 30 | OutputVasya | 1 second | 256 megabytes | ['implementation', '*900'] |
G. New Year Runningtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNew Year is coming in Tree Island! In this island, as the name implies, there are n cities connected by nβ-β1 roads, and for any two distinct cities there always exists exactly one path between them. For every person in Tree Island, it takes exactly one minute to pass by exactly one road.There is a weird New Year tradition for runnners in Tree Island, which is called "extreme run". This tradition can be done as follows.A runner chooses two distinct cities a and b. For simplicity, let's denote the shortest path from city a to city b as p1,βp2,β...,βpl (here, p1β=βa and plβ=βb holds). Then following happens: The runner starts at city a. The runner runs from city a to b, following the shortest path from city a to city b. When the runner arrives at city b, he turns his direction immediately (it takes no time), and runs towards city a, following the shortest path from city b to city a. When the runner arrives at city a, he turns his direction immediately (it takes no time), and runs towards city b, following the shortest path from city a to city b. Repeat step 3 and step 4 forever. In short, the course of the runner can be denoted as: Two runners JH and JY decided to run "extremely" in order to celebrate the New Year. JH has chosen two cities u and v, and JY has chosen two cities x and y. They decided to start running at the same moment, and run until they meet at the same city for the first time. Meeting on a road doesn't matter for them. Before running, they want to know the amount of time they will run.It is too hard for JH and JY to calculate this, so they ask you for help.InputThe first line contains a single positive integer n (5ββ€βnββ€β2βΓβ105) β the number of cities in Tree Island.Next nβ-β1 lines describe the roads of Tree Island. The i-th line (1ββ€βiββ€βnβ-β1) of them contains two space-separated integers ai and bi (1ββ€βai,βbiββ€βn,βaiββ βbi) β the vertices connected by a single road of the tree.The next line contains an integer t (1ββ€βtββ€β2βΓβ105) β the number of test cases.Next t lines describes the test cases. The j-th line (1ββ€βjββ€βt) of them contains four space-separated integers uj,βvj,βxj,βyj (1ββ€βuj,βvj,βxj,βyjββ€βn,βujββ βvj,βxjββ βyj). It means that in this test case, JH has chosen two cities uj and vj, JY has chosen two cities xj and yj. JH starts running at city uj, and JY starts running at city xj.OutputFor each test case, print an integer describing the amount of time they should run in minutes. If they have to run for an infinitely long time (in other words, if they never meet at the same city), print -1 instead. If they meet at the beginning of their run, print 0.ExamplesInput71 33 67 43 75 47 246 5 5 33 5 4 61 5 1 31 5 3 1Output210-1NoteThe example looks like: | Input71 33 67 43 75 47 246 5 5 33 5 4 61 5 1 31 5 3 1 | Output210-1 | 4 seconds | 256 megabytes | ['number theory', 'trees', '*3200'] |
F. New Year Shoppingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDohyun is running a grocery store. He sells n items numbered by integers from 1 to n. The i-th (1ββ€βiββ€βn) of them costs ci dollars, and if I buy it, my happiness increases by hi. Each item can be displayed only for p units of time because of freshness. As Dohyun displays the i-th item at time ti, the customers can buy the i-th item only from time ti to time tiβ+β(pβ-β1) inclusively. Also, each customer cannot buy the same item more than once.I'd like to visit Dohyun's grocery store and buy some items for the New Year Party, and maximize my happiness. Because I am a really busy person, I can visit the store only once, and for very short period of time. In other words, if I visit the store at time t, I can only buy the items available at time t. But I can buy as many items as possible, if the budget holds. I can't buy same item several times due to store rules. It is not necessary to use the whole budget.I made a list of q pairs of integers (aj,βbj), which means I may visit the store at time aj, and spend at most bj dollars at the store. For each pair, I'd like to know the maximum happiness I can obtain. But there are so many pairs that I can't handle them. Can you help me?InputThe first line contains two space-separated integers n and p (1ββ€βnββ€β4000, 1ββ€βpββ€β10β000) β the number of items, and the display time of each item.Next n lines describe the items. The i-th (1ββ€βiββ€βn) of them contains three space-separated integers ci, hi, ti (1ββ€βci,βhiββ€β4000, 1ββ€βtiββ€β10β000) β the cost of the i-th item, the happiness of the i-th item, and the time when the i-th item starts to be displayed.The next line contains an integer q (1ββ€βqββ€β20β000)β the number of candidates.Next q lines describe the candidates. The j-th (1ββ€βjββ€βq) of them contains two space-separated integers aj, bj (1ββ€βajββ€β20β000, 1ββ€βbjββ€β4000) β the visit time and the budget for j-th visit of store.OutputFor each candidate, print a single line containing the maximum happiness that I can obtain by buying some items.ExamplesInput4 42 3 23 5 14 7 211 15 541 32 52 65 14Output581018Input5 43 2 17 4 42 1 26 3 53 2 2101 52 54 84 94 105 85 95 108 47 9Output2355645604NoteConsider the first sample. At time 1, only the 2nd item is available. I can buy the 2nd item using 3 dollars and my happiness will increase by 5. At time 2, the 1st, 2nd, and 3rd item is available. I can buy the 1st item using 2 dollars, and the 2nd item using 3 dollars. My happiness will increase by 3 + 5 = 8. At time 2, the 1st, 2nd, and 3rd item is available. I can buy the 1st item using 2 dollars, and the 3nd item using 4 dollars. My happiness will increase by 3 + 7 = 10. At time 5, the 1st, 3rd, and 4th item is available. I can buy the 1st item using 2 dollars, and the 4th item using 11 dollars. My happiness will increase by 3 + 15 = 18. Note that I don't need to use the whole budget in this case. | Input4 42 3 23 5 14 7 211 15 541 32 52 65 14 | Output581018 | 2 seconds | 256 megabytes | ['divide and conquer', 'dp', '*2700'] |
E. New Year Dominotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCelebrating the new year, many people post videos of falling dominoes; Here's a list of them: https://www.youtube.com/results?search_query=New+Years+Dominos User ainta, who lives in a 2D world, is going to post a video as well.There are n dominoes on a 2D Cartesian plane. i-th domino (1ββ€βiββ€βn) can be represented as a line segment which is parallel to the y-axis and whose length is li. The lower point of the domino is on the x-axis. Let's denote the x-coordinate of the i-th domino as pi. Dominoes are placed one after another, so p1β<βp2β<β...β<βpnβ-β1β<βpn holds.User ainta wants to take a video of falling dominoes. To make dominoes fall, he can push a single domino to the right. Then, the domino will fall down drawing a circle-shaped orbit until the line segment totally overlaps with the x-axis. Also, if the s-th domino touches the t-th domino while falling down, the t-th domino will also fall down towards the right, following the same procedure above. Domino s touches domino t if and only if the segment representing s and t intersects. See the picture above. If he pushes the leftmost domino to the right, it falls down, touching dominoes (A), (B) and (C). As a result, dominoes (A), (B), (C) will also fall towards the right. However, domino (D) won't be affected by pushing the leftmost domino, but eventually it will fall because it is touched by domino (C) for the first time. The picture above is an example of falling dominoes. Each red circle denotes a touch of two dominoes.User ainta has q plans of posting the video. j-th of them starts with pushing the xj-th domino, and lasts until the yj-th domino falls. But sometimes, it could be impossible to achieve such plan, so he has to lengthen some dominoes. It costs one dollar to increase the length of a single domino by 1. User ainta wants to know, for each plan, the minimum cost needed to achieve it. Plans are processed independently, i. e. if domino's length is increased in some plan, it doesn't affect its length in other plans. Set of dominos that will fall except xj-th domino and yj-th domino doesn't matter, but the initial push should be on domino xj.InputThe first line contains an integer n (2ββ€βnββ€β2βΓβ105)β the number of dominoes.Next n lines describe the dominoes. The i-th line (1ββ€βiββ€βn) contains two space-separated integers pi, li (1ββ€βpi,βliββ€β109)β the x-coordinate and the length of the i-th domino. It is guaranteed that p1β<βp2β<β...β<βpnβ-β1β<βpn.The next line contains an integer q (1ββ€βqββ€β2βΓβ105) β the number of plans.Next q lines describe the plans. The j-th line (1ββ€βjββ€βq) contains two space-separated integers xj, yj (1ββ€βxjβ<βyjββ€βn). It means the j-th plan is, to push the xj-th domino, and shoot a video until the yj-th domino falls.OutputFor each plan, print a line containing the minimum cost needed to achieve it. If no cost is needed, print 0.ExamplesInput61 53 34 49 210 112 141 22 42 52 6Output0112NoteConsider the example. The dominoes are set like the picture below. Let's take a look at the 4th plan. To make the 6th domino fall by pushing the 2nd domino, the length of the 3rd domino (whose x-coordinate is 4) should be increased by 1, and the 5th domino (whose x-coordinate is 9) should be increased by 1 (other option is to increase 4th domino instead of 5th also by 1). Then, the dominoes will fall like in the picture below. Each cross denotes a touch between two dominoes. | Input61 53 34 49 210 112 141 22 42 52 6 | Output0112 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'dsu', '*2300'] |
D. New Year Santa Networktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNew Year is coming in Tree World! In this world, as the name implies, there are n cities connected by nβ-β1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to nβ-β1. Let's define d(u,βv) as total length of roads on the path between city u and city v.As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1.Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1ββ€βkββ€β3) Santa will take charge of the warehouse in city ck.It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1,βc2)β+βd(c2,βc3)β+βd(c3,βc1) dollars. Santas are too busy to find the best place, so they decided to choose c1,βc2,βc3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network.However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.InputThe first line contains an integer n (3ββ€βnββ€β105) β the number of cities in Tree World.Next nβ-β1 lines describe the roads. The i-th line of them (1ββ€βiββ€βnβ-β1) contains three space-separated integers ai, bi, li (1ββ€βai,βbiββ€βn, aiββ βbi, 1ββ€βliββ€β103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li.The next line contains an integer q (1ββ€βqββ€β105) β the number of road length changes.Next q lines describe the length changes. The j-th line of them (1ββ€βjββ€βq) contains two space-separated integers rj, wj (1ββ€βrjββ€βnβ-β1, 1ββ€βwjββ€β103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times.OutputOutput q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10β-β6.ExamplesInput32 3 51 3 351 42 21 22 11 1Output14.000000000012.00000000008.00000000006.00000000004.0000000000Input61 5 35 3 26 1 71 4 45 2 351 22 13 54 15 2Output19.600000000018.600000000016.600000000013.600000000012.6000000000NoteConsider the first sample. There are 6 triples: (1,β2,β3),β(1,β3,β2),β(2,β1,β3),β(2,β3,β1),β(3,β1,β2),β(3,β2,β1). Because nβ=β3, the cost needed to build the network is always d(1,β2)β+βd(2,β3)β+βd(3,β1) for all the triples. So, the expected cost equals to d(1,β2)β+βd(2,β3)β+βd(3,β1). | Input32 3 51 3 351 42 21 22 11 1 | Output14.000000000012.00000000008.00000000006.00000000004.0000000000 | 2 seconds | 256 megabytes | ['combinatorics', 'dfs and similar', 'graphs', 'trees', '*1900'] |
C. New Year Book Readingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNew Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1ββ€βiββ€βn) book is wi.As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below. He lifts all the books above book x. He pushes book x out of the stack. He puts down the lifted books without changing their order. After reading book x, he puts book x on the top of the stack. He decided to read books for m days. In the j-th (1ββ€βjββ€βm) day, he will read the book that is numbered with integer bj (1ββ€βbjββ€βn). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?InputThe first line contains two space-separated integers n (2ββ€βnββ€β500) and m (1ββ€βmββ€β1000) β the number of books, and the number of days for which Jaehyun would read books.The second line contains n space-separated integers w1,βw2,β...,βwn (1ββ€βwiββ€β100) β the weight of each book.The third line contains m space separated integers b1,βb2,β...,βbm (1ββ€βbjββ€βn) β the order of books that he would read. Note that he can read the same book more than once.OutputPrint the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.ExamplesInput3 51 2 31 3 2 3 1Output12NoteHere's a picture depicting the example. Each vertical column presents the stacked books. | Input3 51 2 31 3 2 3 1 | Output12 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'math', '*1600'] |
B. New Year Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUser ainta has a permutation p1,βp2,β...,βpn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1,βa2,β...,βan is prettier than permutation b1,βb2,β...,βbn, if and only if there exists an integer k (1ββ€βkββ€βn) where a1β=βb1,βa2β=βb2,β...,βakβ-β1β=βbkβ-β1 and akβ<βbk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an nβΓβn binary matrix A, user ainta can swap the values of pi and pj (1ββ€βi,βjββ€βn, iββ βj) if and only if Ai,βjβ=β1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.InputThe first line contains an integer n (1ββ€βnββ€β300) β the size of the permutation p.The second line contains n space-separated integers p1,βp2,β...,βpn β the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation.Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai,βj is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i,βj where 1ββ€βiβ<βjββ€βn, Ai,βjβ=βAj,βi holds. Also, for all integers i where 1ββ€βiββ€βn, Ai,βiβ=β0 holds.OutputIn the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.ExamplesInput75 2 4 3 6 7 10001001000000000000101000001000000000100001001000Output1 2 4 3 6 7 5Input54 2 1 5 30010000011100100110101010Output1 2 3 4 5NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1,βp7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1,βp3),β(p4,βp5),β(p3,βp4). A permutation p is a sequence of integers p1,βp2,β...,βpn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n. | Input75 2 4 3 6 7 10001001000000000000101000001000000000100001001000 | Output1 2 4 3 6 7 5 | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', 'greedy', 'math', 'sortings', '*1600'] |
A. New Year Transportationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNew Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1βΓβn board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of nβ-β1 positive integers a1,βa2,β...,βanβ-β1. For every integer i where 1ββ€βiββ€βnβ-β1 the condition 1ββ€βaiββ€βnβ-βi holds. Next, he made nβ-β1 portals, numbered by integers from 1 to nβ-β1. The i-th (1ββ€βiββ€βnβ-β1) portal connects cell i and cell (iβ+βai), and one can travel from cell i to cell (iβ+βai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (iβ+βai) to cell i using the i-th portal. It is easy to see that because of condition 1ββ€βaiββ€βnβ-βi one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.InputThe first line contains two space-separated integers n (3ββ€βnββ€β3βΓβ104) and t (2ββ€βtββ€βn) β the number of cells, and the index of the cell which I want to go to.The second line contains nβ-β1 space-separated integers a1,βa2,β...,βanβ-β1 (1ββ€βaiββ€βnβ-βi). It is guaranteed, that using the given transportation system, one cannot leave the Line World.OutputIf I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".ExamplesInput8 41 2 1 2 1 2 1OutputYESInput8 51 2 1 2 1 1 1OutputNONoteIn the first sample, the visited cells are: 1,β2,β4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1,β2,β4,β6,β7,β8; so we can't visit the cell 5, which we want to visit. | Input8 41 2 1 2 1 2 1 | OutputYES | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'implementation', '*1000'] |
B. Lecturetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.InputThe first line contains two integers, n and m (1ββ€βnββ€β3000, 1ββ€βmββ€β3000) β the number of words in the professor's lecture and the number of words in each of these languages.The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once.The next line contains n space-separated strings c1,βc2,β...,βcn β the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1,βa2,β... am}.All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.OutputOutput exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.ExamplesInput4 3codeforces codesecrofcontest roundletter messagecodeforces contest letter contestOutputcodeforces round letter roundInput5 3joll wuqrdeuzf unhbnyiyc rsoqqvehhbnyiyc joll joll euzf jollOutputhbnyiyc joll joll un joll | Input4 3codeforces codesecrofcontest roundletter messagecodeforces contest letter contest | Outputcodeforces round letter round | 1 second | 256 megabytes | ['implementation', 'strings', '*1000'] |
A. Watching a movietime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have decided to watch the best moments of some movie. There are two buttons on your player: Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. Skip exactly x minutes of the movie (x is some fixed positive integer). If the player is now at the t-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (tβ+βx). Initially the movie is turned on in the player on the first minute, and you want to watch exactly n best moments of the movie, the i-th best moment starts at the li-th minute and ends at the ri-th minute (more formally, the i-th best moment consists of minutes: li,βliβ+β1,β...,βri). Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?InputThe first line contains two space-separated integers n, x (1ββ€βnββ€β50, 1ββ€βxββ€β105) β the number of the best moments of the movie and the value of x for the second button.The following n lines contain the descriptions of the best moments of the movie, the i-th line of the description contains two integers separated by a space li, ri (1ββ€βliββ€βriββ€β105).It is guaranteed that for all integers i from 2 to n the following condition holds: riβ-β1β<βli.OutputOutput a single number β the answer to the problem.ExamplesInput2 35 610 12Output6Input1 11 100000Output100000NoteIn the first sample, the player was initially standing on the first minute. As the minutes from the 1-st to the 4-th one don't contain interesting moments, we press the second button. Now we can not press the second button and skip 3 more minutes, because some of them contain interesting moments. Therefore, we watch the movie from the 4-th to the 6-th minute, after that the current time is 7. Similarly, we again skip 3 minutes and then watch from the 10-th to the 12-th minute of the movie. In total, we watch 6 minutes of the movie.In the second sample, the movie is very interesting, so you'll have to watch all 100000 minutes of the movie. | Input2 35 610 12 | Output6 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1000'] |
E. Stairs and Linestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a figure on a grid representing stairs consisting of 7 steps. The width of the stair on height i is wi squares. Formally, the figure is created by consecutively joining rectangles of size wiβΓβi so that the wi sides lie on one straight line. Thus, for example, if all wiβ=β1, the figure will look like that (different colors represent different rectangles): And if wβ=β{5,β1,β0,β3,β0,β0,β1}, then it looks like that: Find the number of ways to color some borders of the figure's inner squares so that no square had all four borders colored. The borders of the squares lying on the border of the figure should be considered painted. The ways that differ with the figure's rotation should be considered distinct. InputThe single line of the input contains 7 numbers w1,βw2,β...,βw7 (0ββ€βwiββ€β105). It is guaranteed that at least one of the wi's isn't equal to zero.OutputIn the single line of the output display a single number β the answer to the problem modulo 109β+β7.ExamplesInput0 1 0 0 0 0 0Output1Input0 2 0 0 0 0 0Output7Input1 1 1 0 0 0 0Output9Input5 1 0 3 0 0 1Output411199181NoteAll the possible ways of painting the third sample are given below: | Input0 1 0 0 0 0 0 | Output1 | 2 seconds | 256 megabytes | ['dp', 'matrices', '*2700'] |
D. Traffic Jams in the Landtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome country consists of (nβ+β1) cities, located along a straight highway. Let's number the cities with consecutive integers from 1 to nβ+β1 in the order they occur along the highway. Thus, the cities are connected by n segments of the highway, the i-th segment connects cities number i and iβ+β1. Every segment of the highway is associated with a positive integer aiβ>β1 β the period of traffic jams appearance on it. In order to get from city x to city y (xβ<βy), some drivers use the following tactics. Initially the driver is in city x and the current time t equals zero. Until the driver arrives in city y, he perfors the following actions: if the current time t is a multiple of ax, then the segment of the highway number x is now having traffic problems and the driver stays in the current city for one unit of time (formally speaking, we assign tβ=βtβ+β1); if the current time t is not a multiple of ax, then the segment of the highway number x is now clear and that's why the driver uses one unit of time to move to city xβ+β1 (formally, we assign tβ=βtβ+β1 and xβ=βxβ+β1). You are developing a new traffic control system. You want to consecutively process q queries of two types: determine the final value of time t after the ride from city x to city y (xβ<βy) assuming that we apply the tactics that is described above. Note that for each query t is being reset to 0. replace the period of traffic jams appearing on the segment number x by value y (formally, assign axβ=βy). Write a code that will effectively process the queries given above.InputThe first line contains a single integer n (1ββ€βnββ€β105) β the number of highway segments that connect the nβ+β1 cities.The second line contains n integers a1,βa2,β...,βan (2ββ€βaiββ€β6) β the periods of traffic jams appearance on segments of the highway.The next line contains a single integer q (1ββ€βqββ€β105) β the number of queries to process.The next q lines contain the descriptions of the queries in the format c, x, y (c β the query type). If c is character 'A', then your task is to process a query of the first type. In this case the following constraints are satisfied: 1ββ€βxβ<βyββ€βnβ+β1.If c is character 'C', then you need to process a query of the second type. In such case, the following constraints are satisfied: 1ββ€βxββ€βn, 2ββ€βyββ€β6.OutputFor each query of the first type output a single integer β the final value of time t after driving from city x to city y. Process the queries in the order in which they are given in the input.ExamplesInput102 5 3 2 3 5 3 4 2 410C 10 6A 2 6A 1 3C 3 4A 3 11A 4 9A 5 6C 7 3A 8 10A 2 5Output53146244 | Input102 5 3 2 3 5 3 4 2 410C 10 6A 2 6A 1 3C 3 4A 3 11A 4 9A 5 6C 7 3A 8 10A 2 5 | Output53146244 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'number theory', '*2400'] |
C. Array and Operationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have written on a piece of paper an array of n positive integers a[1],βa[2],β...,βa[n] and m good pairs of integers (i1,βj1),β(i2,βj2),β...,β(im,βjm). Each good pair (ik,βjk) meets the following conditions: ikβ+βjk is an odd number and 1ββ€βikβ<βjkββ€βn.In one operation you can perform a sequence of actions: take one of the good pairs (ik,βjk) and some integer v (vβ>β1), which divides both numbers a[ik] and a[jk]; divide both numbers by v, i. e. perform the assignments: and . Determine the maximum number of operations you can sequentially perform on the given array. Note that one pair may be used several times in the described operations.InputThe first line contains two space-separated integers n, m (2ββ€βnββ€β100, 1ββ€βmββ€β100).The second line contains n space-separated integers a[1],βa[2],β...,βa[n] (1ββ€βa[i]ββ€β109) β the description of the array.The following m lines contain the description of good pairs. The k-th line contains two space-separated integers ik, jk (1ββ€βikβ<βjkββ€βn, ikβ+βjk is an odd number).It is guaranteed that all the good pairs are distinct.OutputOutput the answer for the problem.ExamplesInput3 28 3 81 22 3Output0Input3 28 12 81 22 3Output2 | Input3 28 3 81 22 3 | Output0 | 1 second | 256 megabytes | ['flows', 'graph matchings', 'number theory', '*2100'] |
B. Name That Tunetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt turns out that you are a great fan of rock band AC/PE. Peter learned that and started the following game: he plays the first song of the list of n songs of the group, and you have to find out the name of the song. After you tell the song name, Peter immediately plays the following song in order, and so on.The i-th song of AC/PE has its recognizability pi. This means that if the song has not yet been recognized by you, you listen to it for exactly one more second and with probability of pi percent you recognize it and tell it's name. Otherwise you continue listening it. Note that you can only try to guess it only when it is integer number of seconds after the moment the song starts playing.In all AC/PE songs the first words of chorus are the same as the title, so when you've heard the first ti seconds of i-th song and its chorus starts, you immediately guess its name for sure.For example, in the song Highway To Red the chorus sounds pretty late, but the song has high recognizability. In the song Back In Blue, on the other hand, the words from the title sound close to the beginning of the song, but it's hard to name it before hearing those words. You can name both of these songs during a few more first seconds.Determine the expected number songs of you will recognize if the game lasts for exactly T seconds (i. e. you can make the last guess on the second T, after that the game stops).If all songs are recognized faster than in T seconds, the game stops after the last song is recognized.InputThe first line of the input contains numbers n and T (1ββ€βnββ€β5000, 1ββ€βTββ€β5000), separated by a space. Next n lines contain pairs of numbers pi and ti (0ββ€βpiββ€β100, 1ββ€βtiββ€βT). The songs are given in the same order as in Petya's list.OutputOutput a single number β the expected number of the number of songs you will recognize in T seconds. Your answer will be considered correct if its absolute or relative error does not exceed 10β-β6.ExamplesInput2 250 210 1Output1.500000000Input2 20 2100 2Output1.000000000Input3 350 350 225 2Output1.687500000Input2 20 20 2Output1.000000000 | Input2 250 210 1 | Output1.500000000 | 1 second | 256 megabytes | ['dp', 'probabilities', 'two pointers', '*2400'] |
A. Crazy Towntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCrazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aixβ+βbiyβ+βciβ=β0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.InputThe first line contains two space-separated integers x1, y1 (β-β106ββ€βx1,βy1ββ€β106) β the coordinates of your home.The second line contains two integers separated by a space x2, y2 (β-β106ββ€βx2,βy2ββ€β106) β the coordinates of the university you are studying at.The third line contains an integer n (1ββ€βnββ€β300) β the number of roads in the city. The following n lines contain 3 space-separated integers (β-β106ββ€βai,βbi,βciββ€β106; |ai|β+β|bi|β>β0) β the coefficients of the line aixβ+βbiyβ+βciβ=β0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).OutputOutput the answer to the problem.ExamplesInput1 1-1 -120 1 01 0 0Output2Input1 1-1 -131 0 00 1 01 1 -3Output2NotePictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors): | Input1 1-1 -120 1 01 0 0 | Output2 | 1 second | 256 megabytes | ['geometry', '*1700'] |
E. Subsequences Returntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAssume that sk(n) equals the sum of digits of number n in the k-based notation. For example, s2(5)β=βs2(1012)β=β1β+β0β+β1β=β2, s3(14)β=βs3(1123)β=β1β+β1β+β2β=β4.The sequence of integers a0,β...,βanβ-β1 is defined as . Your task is to calculate the number of distinct subsequences of sequence a0,β...,βanβ-β1. Calculate the answer modulo 109β+β7.Sequence a1,β...,βak is called to be a subsequence of sequence b1,β...,βbl, if there is a sequence of indices 1ββ€βi1β<β...β<βikββ€βl, such that a1β=βbi1, ..., akβ=βbik. In particular, an empty sequence (i.e. the sequence consisting of zero elements) is a subsequence of any sequence.InputThe first line contains two space-separated numbers n and k (1ββ€βnββ€β1018, 2ββ€βkββ€β30).OutputIn a single line print the answer to the problem modulo 109β+β7.ExamplesInput4 2Output11Input7 7Output128NoteIn the first sample the sequence ai looks as follows: (0,β1,β1,β0). All the possible subsequences are: (),β(0),β(0,β0),β(0,β1),β(0,β1,β0),β(0,β1,β1),β(0,β1,β1,β0),β(1),β(1,β0),β(1,β1),β(1,β1,β0).In the second sample the sequence ai looks as follows: (0,β1,β2,β3,β4,β5,β6). The subsequences of this sequence are exactly all increasing sequences formed from numbers from 0 to 6. It is easy to see that there are 27β=β128 such sequences. | Input4 2 | Output11 | 1 second | 256 megabytes | ['dp', 'matrices', '*2900'] |
E. Distributing Parts time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are an assistant director in a new musical play. The play consists of n musical parts, each part must be performed by exactly one actor. After the casting the director chose m actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, ci and di (ciββ€βdi)Β β the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each partΒ β aj and bj (ajββ€βbj)Β β the pitch of the lowest and the highest notes that are present in the part. The i-th actor can perform the j-th part if and only if ciββ€βajββ€βbjββ€βdi, i.e. each note of the part is in the actor's voice range.According to the contract, the i-th actor can perform at most ki parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).The rehearsal starts in two hours and you need to do the assignment quickly!InputThe first line contains a single integer nΒ β the number of parts in the play (1ββ€βnββ€β105).Next n lines contain two space-separated integers each, aj and bjΒ β the range of notes for the j-th part (1ββ€βajββ€βbjββ€β109).The next line contains a single integer mΒ β the number of actors (1ββ€βmββ€β105).Next m lines contain three space-separated integers each, ci, di and kiΒ β the range of the i-th actor and the number of parts that he can perform (1ββ€βciββ€βdiββ€β109, 1ββ€βkiββ€β109).OutputIf there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line.In the next line print n space-separated integers. The i-th integer should be the number of the actor who should perform the i-th part. If there are multiple correct assignments, print any of them.If there is no correct assignment, print a single word "NO" (without the quotes).ExamplesInput31 32 43 521 4 22 5 1OutputYES1 1 2Input31 32 43 521 3 22 5 1OutputNO | Input31 32 43 521 4 22 5 1 | OutputYES1 1 2 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*2100'] |
D. Tennis Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?InputThe first line contains a single integer nΒ β the length of the sequence of games (1ββ€βnββ€β105).The second line contains n space-separated integers ai. If aiβ=β1, then the i-th serve was won by Petya, if aiβ=β2, then the i-th serve was won by Gena.It is not guaranteed that at least one option for numbers s and t corresponds to the given record.OutputIn the first line print a single number kΒ β the number of options for numbers s and t.In each of the following k lines print two integers si and tiΒ β the option for numbers s and t. Print the options in the order of increasing si, and for equal siΒ β in the order of increasing ti.ExamplesInput51 2 1 2 1Output21 33 1Input41 1 1 1Output31 42 24 1Input41 2 1 2Output0Input82 1 2 1 1 1 1 1Output31 62 36 1 | Input51 2 1 2 1 | Output21 33 1 | 2 seconds | 256 megabytes | ['binary search', '*1900'] |
C. Removing Columnstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an nβΓβm rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijkΒ we obtain the table:acdefghjkΒ A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.InputThe first line contains two integers Β β n and m (1ββ€βn,βmββ€β100).Next n lines contain m small English letters eachΒ β the characters of the table.OutputPrint a single numberΒ β the minimum number of columns that you need to remove in order to make the table good.ExamplesInput1 10codeforcesOutput0Input4 4casecaretestcodeOutput2Input5 4codeforcescodeforcesOutput4NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t. | Input1 10codeforces | Output0 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', '*1500'] |
B. Secret Combinationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.InputThe first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of digits on the display.The second line contains n digitsΒ β the initial state of the display.OutputPrint a single line containing n digitsΒ β the desired state of the display containing the smallest possible number.ExamplesInput3579Output024Input42014Output0142 | Input3579 | Output024 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', '*1500'] |
A. Minimum Difficultytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike is trying rock climbing but he is awful at it. There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, aiβ<βaiβ+β1 for all i from 1 to nβ-β1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty . In other words, difficulty equals the maximum distance between two holds that are adjacent in height.Today Mike decided to cover the track with holds hanging on heights a1, ..., an. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence (1,β2,β3,β4,β5) and remove the third element from it, we obtain the sequence (1,β2,β4,β5)). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds must stay at their positions.Help Mike determine the minimum difficulty of the track after removing one hold.InputThe first line contains a single integer n (3ββ€βnββ€β100)Β β the number of holds.The next line contains n space-separated integers ai (1ββ€βaiββ€β1000), where ai is the height where the hold number i hangs. The sequence ai is increasing (i.e. each element except for the first one is strictly larger than the previous one).OutputPrint a single number β the minimum difficulty of the track after removing a single hold.ExamplesInput31 4 6Output5Input51 2 3 4 5Output2Input51 2 3 7 8Output4NoteIn the first sample you can remove only the second hold, then the sequence looks like (1,β6), the maximum difference of the neighboring elements equals 5.In the second test after removing every hold the difficulty equals 2.In the third test you can obtain sequences (1,β3,β7,β8), (1,β2,β7,β8), (1,β2,β3,β8), for which the difficulty is 4, 5 and 5, respectively. Thus, after removing the second element we obtain the optimal answer β 4. | Input31 4 6 | Output5 | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'math', '*900'] |
B. Modular Equationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLast week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define i modulo j as the remainder of division of i by j and denote it by . A Modular Equation, as Hamed's teacher described, is an equation of the form in which a and b are two non-negative integers and x is a variable. We call a positive integer x for which a solution of our equation.Hamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations.Now he wants to write his math exercises but since he has no idea how to do that, he asked you for help. He has told you all he knows about Modular Equations and asked you to write a program which given two numbers a and b determines how many answers the Modular Equation has.InputIn the only line of the input two space-separated integers a and b (0ββ€βa,βbββ€β109) are given.OutputIf there is an infinite number of answers to our equation, print "infinity" (without the quotes). Otherwise print the number of solutions of the Modular Equation .ExamplesInput21 5Output2Input9435152 272Output282Input10 10OutputinfinityNoteIn the first sample the answers of the Modular Equation are 8 and 16 since | Input21 5 | Output2 | 1 second | 256 megabytes | ['math', 'number theory', '*1600'] |
A. Digital Countertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMalek lives in an apartment block with 100 floors numbered from 0 to 99. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with 7 light sticks by turning them on or off. The picture below shows how the elevator shows each digit.One day when Malek wanted to go from floor 88 to floor 0 using the elevator he noticed that the counter shows number 89 instead of 88. Then when the elevator started moving the number on the counter changed to 87. After a little thinking Malek came to the conclusion that there is only one explanation for this: One of the sticks of the counter was broken. Later that day Malek was thinking about the broken stick and suddenly he came up with the following problem.Suppose the digital counter is showing number n. Malek calls an integer x (0ββ€βxββ€β99) good if it's possible that the digital counter was supposed to show x but because of some(possibly none) broken sticks it's showing n instead. Malek wants to know number of good integers for a specific n. So you must write a program that calculates this number. Please note that the counter always shows two digits.InputThe only line of input contains exactly two digits representing number n (0ββ€βnββ€β99). Note that n may have a leading zero.OutputIn the only line of the output print the number of good integers.ExamplesInput89Output2Input00Output4Input73Output15NoteIn the first sample the counter may be supposed to show 88 or 89.In the second sample the good integers are 00, 08, 80 and 88.In the third sample the good integers are 03,β08,β09,β33,β38,β39,β73,β78,β79,β83,β88,β89,β93,β98,β99. | Input89 | Output2 | 1 second | 256 megabytes | ['implementation', '*1100'] |
E. Shartitime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the last 24 hours Hamed and Malek spent all their time playing "Sharti". Now they are too exhausted to finish the last round. So they asked you for help to determine the winner of this round. "Sharti" is played on a nβΓβn board with some of cells colored white and others colored black. The rows of the board are numbered from top to bottom using number 1 to n. Also the columns of the board are numbered from left to right using numbers 1 to n. The cell located at the intersection of i-th row and j-th column is denoted by (i,βj).The players alternatively take turns. In each turn the player must choose a square with side-length at most k with its lower-right cell painted white. Then the colors of all the cells in this square are inversed (white cells become black and vice-versa). The player who cannot perform a move in his turn loses. You know Hamed and Malek are very clever and they would have played their best moves at each turn. Knowing this and the fact that Hamed takes the first turn, given the initial board as described in the input, you must determine which one of them will be the winner.InputIn this problem the initial board is specified as a set of m rectangles. All cells that lie inside at least one of these rectangles are colored white and the rest are colored black.In the first line of input three space-spereated integers n,βm,βk (1ββ€βkββ€βnββ€β109, 1ββ€βmββ€β5Β·104) follow, denoting size of the board, number of rectangles and maximum size of the turn square during the game, respectively.In i-th line of the next m lines four space-seperated integers ai,βbi,βci,βdi (1ββ€βaiββ€βciββ€βn, 1ββ€βbiββ€βdiββ€βn) are given meaning that i-th rectangle determining the initial board is a rectangle with upper-left cell at (ai,βbi) and lower-right cell at (ci,βdi).OutputIf Hamed wins, print "Hamed", otherwise print "Malek" (without the quotes).ExamplesInput5 2 11 1 3 32 2 4 4OutputMalekInput12 5 73 4 5 61 2 1 24 5 9 98 6 12 1012 4 12 4OutputHamed | Input5 2 11 1 3 32 2 4 4 | OutputMalek | 5 seconds | 256 megabytes | ['data structures', 'games', '*3200'] |
D. Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAli is Hamed's little brother and tomorrow is his birthday. Hamed wants his brother to earn his gift so he gave him a hard programming problem and told him if he can successfully solve it, he'll get him a brand new laptop. Ali is not yet a very talented programmer like Hamed and although he usually doesn't cheat but this time is an exception. It's about a brand new laptop. So he decided to secretly seek help from you. Please solve this problem for Ali. An n-vertex weighted rooted tree is given. Vertex number 1 is a root of the tree. We define d(u,βv) as the sum of edges weights on the shortest path between vertices u and v. Specifically we define d(u,βu)β=β0. Also let's define S(v) for each vertex v as a set containing all vertices u such that d(1,βu)β=βd(1,βv)β+βd(v,βu). Function f(u,βv) is then defined using the following formula:The goal is to calculate f(u,βv) for each of the q given pair of vertices. As the answer can be rather large it's enough to print it modulo 109β+β7.InputIn the first line of input an integer n (1ββ€βnββ€β105), number of vertices of the tree is given.In each of the next nβ-β1 lines three space-separated integers ai,βbi,βci (1ββ€βai,βbiββ€βn, 1ββ€βciββ€β109) are given indicating an edge between ai and bi with weight equal to ci.In the next line an integer q (1ββ€βqββ€β105), number of vertex pairs, is given.In each of the next q lines two space-separated integers ui,βvi (1ββ€βui,βviββ€βn) are given meaning that you must calculate f(ui,βvi).It is guaranteed that the given edges form a tree.OutputOutput q lines. In the i-th line print the value of f(ui,βvi) modulo 109β+β7.ExamplesInput51 2 14 3 13 5 11 3 151 11 52 42 13 5Output1010000000051000000002231000000002Input81 2 1001 3 202 4 22 5 13 6 13 7 26 8 561 82 35 82 64 76 1Output9999687534979699996127199999123599995856945130 | Input51 2 14 3 13 5 11 3 151 11 52 42 13 5 | Output1010000000051000000002231000000002 | 2 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'dp', 'trees', '*2700'] |
C. Helping Peopletime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMalek is a rich man. He also is very generous. That's why he decided to split his money between poor people. A charity institute knows n poor people numbered from 1 to n. The institute gave Malek q recommendations. A recommendation is a segment of people like [l,βr] which means the institute recommended that Malek gives one dollar to every person whose number is in this segment.However this charity has very odd rules about the recommendations. Because of those rules the recommendations are given in such a way that for every two recommendation [a,βb] and [c,βd] one of the following conditions holds: The two segments are completely disjoint. More formally either aββ€βbβ<βcββ€βd or cββ€βdβ<βaββ€βb One of the two segments are inside another. More formally either aββ€βcββ€βdββ€βb or cββ€βaββ€βbββ€βd. The goodness of a charity is the value of maximum money a person has after Malek finishes giving his money. The institute knows for each recommendation what is the probability that Malek will accept it. They want to know the expected value of goodness of this charity. So they asked you for help.You have been given the list of recommendations and for each recommendation the probability of it being accepted by Malek. You have also been given how much money each person initially has. You must find the expected value of goodness.InputIn the first line two space-separated integers n,βq (1ββ€βnββ€β105, 1ββ€βqββ€β5000) are given.In the second line n space-separated integers a1,βa2,β...,βan (0ββ€βaiββ€β109) are given meaning that person number i initially has ai dollars. Each of the next q lines contains three space-separated numbers li,βri,βpi (1ββ€βliββ€βriββ€βn, 0ββ€βpββ€β1) where li and ri are two integers describing the segment of recommendation and pi is a real number given with exactly three digits after decimal point which is equal to probability of Malek accepting this recommendation.Note that a segment may appear several times in recommendations.OutputOutput the sought value. Your answer will be considered correct if its absolute or relative error is less than 10β-β6.ExamplesInput5 21 7 2 4 31 3 0.5002 2 0.500Output8.000000000Input5 2281 280 279 278 2821 4 1.0001 4 0.000Output282.000000000Input3 51 2 31 3 0.5002 2 0.2501 2 0.8001 1 0.1202 2 0.900Output4.465000000 | Input5 21 7 2 4 31 3 0.5002 2 0.500 | Output8.000000000 | 2 seconds | 512 megabytes | ['dp', 'probabilities', '*2600'] |
B. Obsessive Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract kββ₯β1 non-overlapping substrings from it such that each of them contains string t as a substring? More formally, you need to calculate the number of ways to choose two sequences a1,βa2,β...,βak and b1,βb2,β...,βbk satisfying the following requirements: kββ₯β1 Β Β t is a substring of string saisaiβ+β1... sbi (string s is considered as 1-indexed). As the number of ways can be rather large print it modulo 109β+β7.InputInput consists of two lines containing strings s and t (1ββ€β|s|,β|t|ββ€β105). Each string consists of lowercase Latin letters.OutputPrint the answer in a single line.ExamplesInputababaabaOutput5InputwelcometoroundtwohundredandeightytwodOutput274201InputddddOutput12 | Inputababaaba | Output5 | 2 seconds | 256 megabytes | ['dp', 'strings', '*2000'] |
A. Treasuretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMalek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1ββ€βiββ€β|s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.InputThe first line of the input contains a string s (1ββ€β|s|ββ€β105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.OutputIf there is no way of replacing '#' characters which leads to a beautiful string print β-β1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with.If there are several possible answers, you may output any of them.ExamplesInput(((#)((#)Output12Input()((#((#(#()Output221Input#Output-1Input(#)Output-1Note|s| denotes the length of the string s. | Input(((#)((#) | Output12 | 2 seconds | 256 megabytes | ['greedy', '*1500'] |
E. Vasya and Polynomialtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is studying in the last class of school and soon he will take exams. He decided to study polynomials. Polynomial is a function P(x)β=βa0β+βa1x1β+β...β+βanxn. Numbers ai are called coefficients of a polynomial, non-negative integer n is called a degree of a polynomial.Vasya has made a bet with his friends that he can solve any problem with polynomials. They suggested him the problem: "Determine how many polynomials P(x) exist with integer non-negative coefficients so that , and , where and b are given positive integers"? Vasya does not like losing bets, but he has no idea how to solve this task, so please help him to solve the problem.InputThe input contains three integer positive numbers no greater than 1018.OutputIf there is an infinite number of such polynomials, then print "inf" without quotes, otherwise print the reminder of an answer modulo 109β+β7.ExamplesInput2 2 2Output2Input2 3 3Output1 | Input2 2 2 | Output2 | 2 seconds | 256 megabytes | ['math', '*2800'] |
D. Vasya and Chesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell contains a piece of the enemy color, the queen is able to move to this square. After that the enemy's piece is removed from the board. The queen cannot move to a cell containing an enemy piece if there is some other piece between it and the queen. There is an nβΓβn chessboard. We'll denote a cell on the intersection of the r-th row and c-th column as (r,βc). The square (1,β1) contains the white queen and the square (1,βn) contains the black queen. All other squares contain green pawns that don't belong to anyone.The players move in turns. The player that moves first plays for the white queen, his opponent plays for the black queen.On each move the player has to capture some piece with his queen (that is, move to a square that contains either a green pawn or the enemy queen). The player loses if either he cannot capture any piece during his move or the opponent took his queen during the previous move. Help Vasya determine who wins if both players play with an optimal strategy on the board nβΓβn.InputThe input contains a single number n (2ββ€βnββ€β109) β the size of the board.OutputOn the first line print the answer to problem β string "white" or string "black", depending on who wins if the both players play optimally. If the answer is "white", then you should also print two integers r and c representing the cell (r,βc), where the first player should make his first move to win. If there are multiple such cells, print the one with the minimum r. If there are still multiple squares, print the one with the minimum c.ExamplesInput2Outputwhite1 2Input3OutputblackNoteIn the first sample test the white queen can capture the black queen at the first move, so the white player wins.In the second test from the statement if the white queen captures the green pawn located on the central vertical line, then it will be captured by the black queen during the next move. So the only move for the white player is to capture the green pawn located at (2,β1). Similarly, the black queen doesn't have any other options but to capture the green pawn located at (2,β3), otherwise if it goes to the middle vertical line, it will be captured by the white queen.During the next move the same thing happens β neither the white, nor the black queen has other options rather than to capture green pawns situated above them. Thus, the white queen ends up on square (3,β1), and the black queen ends up on square (3,β3). In this situation the white queen has to capture any of the green pawns located on the middle vertical line, after that it will be captured by the black queen. Thus, the player who plays for the black queen wins. | Input2 | Outputwhite1 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'games', 'math', '*1700'] |
C. Vasya and Basketballtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.InputThe first line contains integer n (1ββ€βnββ€β2Β·105) β the number of throws of the first team. Then follow n integer numbers β the distances of throws ai (1ββ€βaiββ€β2Β·109). Then follows number m (1ββ€βmββ€β2Β·105) β the number of the throws of the second team. Then follow m integer numbers β the distances of throws of bi (1ββ€βbiββ€β2Β·109).OutputPrint two numbers in the format a:b β the score that is possible considering the problem conditions where the result of subtraction aβ-βb is maximum. If there are several such scores, find the one in which number a is maximum.ExamplesInput31 2 325 6Output9:6Input56 7 8 9 1051 2 3 4 5Output15:10 | Input31 2 325 6 | Output9:6 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'implementation', 'sortings', 'two pointers', '*1600'] |
B. Vasya and Wrestlingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.InputThe first line contains number n β the number of techniques that the wrestlers have used (1ββ€βnββ€β2Β·105). The following n lines contain integer numbers ai (|ai|ββ€β109, aiββ β0). If ai is positive, that means that the first wrestler performed the technique that was awarded with ai points. And if ai is negative, that means that the second wrestler performed the technique that was awarded with (β-βai) points.The techniques are given in chronological order.OutputIf the first wrestler wins, print string "first", otherwise print "second"ExamplesInput512-3-43OutputsecondInput3-1-23OutputfirstInput24-4OutputsecondNoteSequence xββ=ββx1x2... x|x| is lexicographically larger than sequence yββ=ββy1y2... y|y|, if either |x|ββ>ββ|y| and x1ββ=ββy1,ββx2ββ=ββy2,β... ,ββx|y|ββ=ββy|y|, or there is such number r (rββ<ββ|x|,βrββ<ββ|y|), that x1ββ=ββy1,ββx2ββ=ββy2,ββ... ,ββxrββ=ββyr and xrββ+ββ1ββ>ββyrββ+ββ1.We use notation |a| to denote length of sequence a. | Input512-3-43 | Outputsecond | 2 seconds | 256 megabytes | ['implementation', '*1400'] |
A. Vasya and Footballtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya.InputThe first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct.Next follows number n (1ββ€βnββ€β90) β the number of fouls. Each of the following n lines contains information about a foul in the following form: first goes number t (1ββ€βtββ€β90) β the minute when the foul occurs; then goes letter "h" or letter "a" β if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player; then goes the player's number m (1ββ€βmββ€β99); then goes letter "y" or letter "r" β if the letter is "y", that means that the yellow card was given, otherwise the red card was given. The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute.OutputFor each event when a player received his first red card in a chronological order print a string containing the following information: The name of the team to which the player belongs; the player's number in his team; the minute when he received the card. If no player received a card, then you do not need to print anything.It is possible case that the program will not print anything to the output (if there were no red cards).ExamplesInputMCCSKA928 a 3 y62 h 25 y66 h 42 y70 h 25 y77 a 4 y79 a 25 y82 h 42 r89 h 16 y90 a 13 rOutputMC 25 70MC 42 82CSKA 13 90 | InputMCCSKA928 a 3 y62 h 25 y66 h 42 y70 h 25 y77 a 4 y79 a 25 y82 h 42 r89 h 16 y90 a 13 r | OutputMC 25 70MC 42 82CSKA 13 90 | 2 seconds | 256 megabytes | ['implementation', '*1300'] |
E. Vanya and Fieldtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya decided to walk in the field of size nβΓβn cells. The field contains m apple trees, the i-th apple tree is at the cell with coordinates (xi,βyi). Vanya moves towards vector (dx,βdy). That means that if Vanya is now at the cell (x,βy), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both a and b. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.InputThe first line contains integers n,βm,βdx,βdy(1ββ€βnββ€β106, 1ββ€βmββ€β105, 1ββ€βdx,βdyββ€βn) β the size of the field, the number of apple trees and the vector of Vanya's movement. Next m lines contain integers xi,βyi (0ββ€βxi,βyiββ€βnβ-β1) β the coordinates of apples. One cell may contain multiple apple trees.OutputPrint two space-separated numbers β the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.ExamplesInput5 5 2 30 01 21 32 43 1Output1 3Input2 3 1 10 00 11 1Output0 0NoteIn the first sample Vanya's path will look like: (1,β3)β-β(3,β1)β-β(0,β4)β-β(2,β2)β-β(4,β0)β-β(1,β3)In the second sample: (0,β0)β-β(1,β1)β-β(0,β0) | Input5 5 2 30 01 21 32 43 1 | Output1 3 | 2 seconds | 256 megabytes | ['math', '*2000'] |
D. Vanya and Computer Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya and his friend Vova play a computer game where they need to destroy n monsters to pass a level. Vanya's character performs attack with frequency x hits per second and Vova's character performs attack with frequency y hits per second. Each character spends fixed time to raise a weapon and then he hits (the time to raise the weapon is 1β/βx seconds for the first character and 1β/βy seconds for the second one). The i-th monster dies after he receives ai hits. Vanya and Vova wonder who makes the last hit on each monster. If Vanya and Vova make the last hit at the same time, we assume that both of them have made the last hit.InputThe first line contains three integers n,x,y (1ββ€βnββ€β105, 1ββ€βx,βyββ€β106) β the number of monsters, the frequency of Vanya's and Vova's attack, correspondingly.Next n lines contain integers ai (1ββ€βaiββ€β109)Β β the number of hits needed do destroy the i-th monster.OutputPrint n lines. In the i-th line print word "Vanya", if the last hit on the i-th monster was performed by Vanya, "Vova", if Vova performed the last hit, or "Both", if both boys performed it at the same time.ExamplesInput4 3 21234OutputVanyaVovaVanyaBothInput2 1 112OutputBothBothNoteIn the first sample Vanya makes the first hit at time 1β/β3, Vova makes the second hit at time 1β/β2, Vanya makes the third hit at time 2β/β3, and both boys make the fourth and fifth hit simultaneously at the time 1.In the second sample Vanya and Vova make the first and second hit simultaneously at time 1. | Input4 3 21234 | OutputVanyaVovaVanyaBoth | 2 seconds | 256 megabytes | ['binary search', 'implementation', 'math', 'sortings', '*1800'] |
C. Vanya and Examstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi essays. He can raise the exam grade multiple times.What is the minimum number of essays that Vanya needs to write to get scholarship?InputThe first line contains three integers n, r, avg (1ββ€βnββ€β105, 1ββ€βrββ€β109, 1ββ€βavgββ€βmin(r,β106))Β β the number of exams, the maximum grade and the required grade point average, respectively.Each of the following n lines contains space-separated integers ai and bi (1ββ€βaiββ€βr, 1ββ€βbiββ€β106).OutputIn the first line print the minimum number of essays.ExamplesInput5 5 45 24 73 13 22 5Output4Input2 5 45 25 2Output0NoteIn the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.In the second sample, Vanya doesn't need to write any essays as his general point average already is above average. | Input5 5 45 24 73 13 22 5 | Output4 | 1 second | 256 megabytes | ['greedy', 'sortings', '*1400'] |
B. Vanya and Lanternstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?InputThe first line contains two integers n, l (1ββ€βnββ€β1000, 1ββ€βlββ€β109)Β β the number of lanterns and the length of the street respectively. The next line contains n integers ai (0ββ€βaiββ€βl). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street.OutputPrint the minimum light radius d, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10β-β9.ExamplesInput7 1515 5 3 7 9 14 0Output2.5000000000Input2 52 5Output2.0000000000NoteConsider the second sample. At dβ=β2 the first lantern will light the segment [0,β4] of the street, and the second lantern will light segment [3,β5]. Thus, the whole street will be lit. | Input7 1515 5 3 7 9 14 0 | Output2.5000000000 | 1 second | 256 megabytes | ['binary search', 'implementation', 'math', 'sortings', '*1200'] |
A. Vanya and Cubestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1β+β2β=β3 cubes, the third level must have 1β+β2β+β3β=β6 cubes, and so on. Thus, the i-th level of the pyramid must have 1β+β2β+β...β+β(iβ-β1)β+βi cubes.Vanya wants to know what is the maximum height of the pyramid that he can make using the given cubes.InputThe first line contains integer n (1ββ€βnββ€β104) β the number of cubes given to Vanya.OutputPrint the maximum possible height of the pyramid in the single line.ExamplesInput1Output1Input25Output4NoteIllustration to the second sample: | Input1 | Output1 | 1 second | 256 megabytes | ['implementation', '*800'] |
C. Decipheringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Maria Ivanovna found a Sasha's piece of paper with a message dedicated to Olya. Maria Ivanovna wants to know what is there in a message, but unfortunately the message is ciphered. Maria Ivanovna knows that her students usually cipher their messages by replacing each letter of an original message by some another letter. Replacement works in such way that same letters are always replaced with some fixed letter, and different letters are always replaced by different letters. Maria Ivanovna supposed that the message contains answers to the final exam (since its length is equal to the number of final exam questions). On the other hand she knows that Sasha's answer are not necessary correct. There are K possible answers for each questions. Of course, Maria Ivanovna knows correct answers.Maria Ivanovna decided to decipher message in such way that the number of Sasha's correct answers is maximum possible. She is very busy now, so your task is to help her.InputFirst line contains length of both strings N (1ββ€βNββ€β2β000β000) and an integer KΒ β number of possible answers for each of the questions (1ββ€βKββ€β52). Answers to the questions are denoted as Latin letters abcde...xyzABCDE...XYZ in the order. For example for Kβ=β6, possible answers are abcdef and for Kβ=β30 possible answers are abcde...xyzABCD.Second line contains a ciphered message string consisting of Latin letters.Third line contains a correct answers string consisting of Latin letters.OutputIn the first line output maximum possible number of correct Sasha's answers.In the second line output cipher rule as the string of length K where for each letter from the students' cipher (starting from 'a' as mentioned above) there is specified which answer does it correspond to.If there are several ways to produce maximum answer, output any of them.ExamplesInput10 2aaabbbaaabbbbbabbbbbOutput7baInput10 2aaaaaaabbbbbbbaaabbbOutput6abInput9 4dacbdacbdacbdacbdaOutput9cdba | Input10 2aaabbbaaabbbbbabbbbb | Output7ba | 1 second | 256 megabytes | ['flows', 'graph matchings', '*2300'] |
B. New York Hoteltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThink of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street-avenue crossings. They also want that the maximum distance covered by one of them while traveling to the restaurant to be minimum possible. Help friends choose optimal restaurant for a celebration.Suppose that the distance between neighboring crossings are all the same equal to one kilometer.InputThe first line contains two integers N ΠΈ MΒ β size of the city (1ββ€βN,βMββ€β109). In the next line there is a single integer C (1ββ€βCββ€β105)Β β the number of hotels friends stayed at. Following C lines contain descriptions of hotels, each consisting of two coordinates x and y (1ββ€βxββ€βN, 1ββ€βyββ€βM). The next line contains an integer HΒ β the number of restaurants (1ββ€βHββ€β105). Following H lines contain descriptions of restaurants in the same format.Several restaurants and hotels may be located near the same crossing.OutputIn the first line output the optimal distance. In the next line output index of a restaurant that produces this optimal distance. If there are several possibilities, you are allowed to output any of them.ExamplesInput10 1021 13 321 104 4Output62 | Input10 1021 13 321 104 4 | Output62 | 2 seconds | 256 megabytes | ['greedy', 'math', '*2100'] |
A. Up the hilltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHiking club "Up the hill" just returned from a walk. Now they are trying to remember which hills they've just walked through.It is known that there were N stops, all on different integer heights between 1 and N kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the second stop, on the second day they've traveled from the second to the third and so on, and on the last day they've traveled from the stop Nβ-β1 to the stop N and successfully finished their expedition.They are trying to find out which heights were their stops located at. They have an entry in a travel journal specifying how many days did they travel up the hill, and how many days did they walk down the hill.Help them by suggesting some possible stop heights satisfying numbers from the travel journal.InputIn the first line there is an integer non-negative number A denoting the number of days of climbing up the hill. Second line contains an integer non-negative number BΒ β the number of days of walking down the hill (Aβ+βBβ+β1β=βN, 1ββ€βNββ€β100β000).OutputOutput N space-separated distinct integers from 1 to N inclusive, denoting possible heights of the stops in order of visiting.ExamplesInput01Output2 1 Input21Output1 3 4 2 | Input01 | Output2 1 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1000'] |
F. Treeland Tourtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe "Road Accident" band is planning an unprecedented tour around Treeland. The RA fans are looking forward to the event and making bets on how many concerts their favorite group will have.Treeland consists of n cities, some pairs of cities are connected by bidirectional roads. Overall the country has nβ-β1 roads. We know that it is possible to get to any city from any other one. The cities are numbered by integers from 1 to n. For every city we know its value ri β the number of people in it.We know that the band will travel along some path, having concerts in some cities along the path. The band's path will not pass one city twice, each time they move to the city that hasn't been previously visited. Thus, the musicians will travel along some path (without visiting any city twice) and in some (not necessarily all) cities along the way they will have concerts.The band plans to gather all the big stadiums and concert halls during the tour, so every time they will perform in a city which population is larger than the population of the previously visited with concert city. In other words, the sequence of population in the cities where the concerts will be held is strictly increasing.In a recent interview with the leader of the "road accident" band promised to the fans that the band will give concert in the largest possible number of cities! Thus the band will travel along some chain of cities of Treeland and have concerts in some of these cities, so that the population number will increase, and the number of concerts will be the largest possible.The fans of Treeland are frantically trying to figure out how many concerts the group will have in Treeland. Looks like they can't manage without some help from a real programmer! Help the fans find the sought number of concerts.InputThe first line of the input contains integer n (2ββ€βnββ€β6000) β the number of cities in Treeland. The next line contains n integers r1,βr2,β...,βrn (1ββ€βriββ€β106), where ri is the population of the i-th city. The next nβ-β1 lines contain the descriptions of the roads, one road per line. Each road is defined by a pair of integers aj, bj (1ββ€βaj,βbjββ€βn) β the pair of the numbers of the cities that are connected by the j-th road. All numbers in the lines are separated by spaces.OutputPrint the number of cities where the "Road Accident" band will have concerts.ExamplesInput61 2 3 4 5 11 22 33 43 53 6Output4Input51 2 3 4 51 21 32 43 5Output3 | Input61 2 3 4 5 11 22 33 43 53 6 | Output4 | 5 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'dp', 'trees', '*2200'] |
E. Restoring Increasing Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeter wrote on the board a strictly increasing sequence of positive integers a1,βa2,β...,βan. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit.Restore the the original sequence knowing digits remaining on the board.InputThe first line of the input contains integer n (1ββ€βnββ€β105) β the length of the sequence. Next n lines contain one element of the sequence each. Each element consists only of digits and question marks. No element starts from digit 0. Each element has length from 1 to 8 characters, inclusive.OutputIf the answer exists, print in the first line "YES" (without the quotes). Next n lines must contain the sequence of positive integers β a possible variant of Peter's sequence. The found sequence must be strictly increasing, it must be transformed from the given one by replacing each question mark by a single digit. All numbers on the resulting sequence must be written without leading zeroes. If there are multiple solutions, print any of them.If there is no answer, print a single line "NO" (without the quotes).ExamplesInput3?181?OutputYES11819Input2???OutputNOInput51222412??512226?0000?00000OutputYES12224122251222620000100000 | Input3?181? | OutputYES11819 | 1 second | 256 megabytes | ['binary search', 'brute force', 'greedy', 'implementation', '*2000'] |
D. Chocolatetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus likes giving presents to Paraskevi. He has bought two chocolate bars, each of them has the shape of a segmented rectangle. The first bar is a1βΓβb1 segments large and the second one is a2βΓβb2 segments large.Polycarpus wants to give Paraskevi one of the bars at the lunch break and eat the other one himself. Besides, he wants to show that Polycarpus's mind and Paraskevi's beauty are equally matched, so the two bars must have the same number of squares.To make the bars have the same number of squares, Polycarpus eats a little piece of chocolate each minute. Each minute he does the following: he either breaks one bar exactly in half (vertically or horizontally) and eats exactly a half of the bar, or he chips of exactly one third of a bar (vertically or horizontally) and eats exactly a third of the bar. In the first case he is left with a half, of the bar and in the second case he is left with two thirds of the bar.Both variants aren't always possible, and sometimes Polycarpus cannot chip off a half nor a third. For example, if the bar is 16βΓβ23, then Polycarpus can chip off a half, but not a third. If the bar is 20βΓβ18, then Polycarpus can chip off both a half and a third. If the bar is 5βΓβ7, then Polycarpus cannot chip off a half nor a third.What is the minimum number of minutes Polycarpus needs to make two bars consist of the same number of squares? Find not only the required minimum number of minutes, but also the possible sizes of the bars after the process.InputThe first line of the input contains integers a1,βb1 (1ββ€βa1,βb1ββ€β109) β the initial sizes of the first chocolate bar. The second line of the input contains integers a2,βb2 (1ββ€βa2,βb2ββ€β109) β the initial sizes of the second bar.You can use the data of type int64 (in Pascal), long long (in Π‘++), long (in Java) to process large integers (exceeding 231β-β1).OutputIn the first line print m β the sought minimum number of minutes. In the second and third line print the possible sizes of the bars after they are leveled in m minutes. Print the sizes using the format identical to the input format. Print the sizes (the numbers in the printed pairs) in any order. The second line must correspond to the first bar and the third line must correspond to the second bar. If there are multiple solutions, print any of them.If there is no solution, print a single line with integer -1.ExamplesInput2 62 3Output11 62 3Input36 510 16Output316 55 16Input3 52 1Output-1 | Input2 62 3 | Output11 62 3 | 1 second | 256 megabytes | ['brute force', 'dfs and similar', 'math', 'meet-in-the-middle', 'number theory', '*1900'] |
C. Hacking Cyphertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus participates in a competition for hacking into a new secure messenger. He's almost won.Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.Help Polycarpus and find any suitable method to cut the public key.InputThe first line of the input contains the public key of the messenger β an integer without leading zeroes, its length is in range from 1 to 106 digits. The second line contains a pair of space-separated positive integers a, b (1ββ€βa,βbββ€β108).OutputIn the first line print "YES" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines β the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them.If there is no answer, print in a single line "NO" (without the quotes).ExamplesInput11640102497 1024OutputYES116401024Input2842545891539281719112818110001009 1000OutputYES284254589153928171911281811000Input12012 1OutputNO | Input11640102497 1024 | OutputYES116401024 | 1 second | 256 megabytes | ['brute force', 'math', 'number theory', 'strings', '*1700'] |
B. Queuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the lunch break all n Berland State University students lined up in the food court. However, it turned out that the food court, too, has a lunch break and it temporarily stopped working.Standing in a queue that isn't being served is so boring! So, each of the students wrote down the number of the student ID of the student that stands in line directly in front of him, and the student that stands in line directly behind him. If no one stands before or after a student (that is, he is the first one or the last one), then he writes down number 0 instead (in Berland State University student IDs are numerated from 1).After that, all the students went about their business. When they returned, they found out that restoring the queue is not such an easy task.Help the students to restore the state of the queue by the numbers of the student ID's of their neighbors in the queue.InputThe first line contains integer n (2ββ€βnββ€β2Β·105) β the number of students in the queue. Then n lines follow, i-th line contains the pair of integers ai,βbi (0ββ€βai,βbiββ€β106), where ai is the ID number of a person in front of a student and bi is the ID number of a person behind a student. The lines are given in the arbitrary order. Value 0 is given instead of a neighbor's ID number if the neighbor doesn't exist.The ID numbers of all students are distinct. It is guaranteed that the records correspond too the queue where all the students stand in some order.OutputPrint a sequence of n integers x1,βx2,β...,βxn β the sequence of ID numbers of all the students in the order they go in the queue from the first student to the last one.ExamplesInput492 310 731 07 141Output92 7 31 141 NoteThe picture illustrates the queue for the first sample. | Input492 310 731 07 141 | Output92 7 31 141 | 2 seconds | 256 megabytes | ['dsu', 'implementation', '*1500'] |
A. Team Olympiadtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe School β0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: tiβ=β1, if the i-th child is good at programming, tiβ=β2, if the i-th child is good at maths, tiβ=β3, if the i-th child is good at PE Each child happens to be good at exactly one of these three subjects.The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?InputThe first line contains integer n (1ββ€βnββ€β5000) β the number of children in the school. The second line contains n integers t1,βt2,β...,βtn (1ββ€βtiββ€β3), where ti describes the skill of the i-th child.OutputIn the first line output integer w β the largest possible number of teams. Then print w lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to n in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them.If no teams can be compiled, print the only line with value w equal to 0.ExamplesInput71 3 1 3 2 1 2Output23 5 26 7 4Input42 1 1 2Output0 | Input71 3 1 3 2 1 2 | Output23 5 26 7 4 | 1 second | 256 megabytes | ['greedy', 'implementation', 'sortings', '*800'] |
F. Special Matricestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn nβΓβn square matrix is special, if: it is binary, that is, each cell contains either a 0, or a 1; the number of ones in each row and column equals 2. You are given n and the first m rows of the matrix. Print the number of special nβΓβn matrices, such that the first m rows coincide with the given ones.As the required value can be rather large, print the remainder after dividing the value by the given number mod.InputThe first line of the input contains three integers n, m, mod (2ββ€βnββ€β500, 0ββ€βmββ€βn, 2ββ€βmodββ€β109). Then m lines follow, each of them contains n characters β the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given mβΓβn table contains at most two numbers one.OutputPrint the remainder after dividing the required value by number mod.ExamplesInput3 1 1000011Output2Input4 4 1005000110101001011001Output1NoteFor the first test the required matrices are: 011101110011110101In the second test the required matrix is already fully given, so the answer is 1. | Input3 1 1000011 | Output2 | 1 second | 256 megabytes | ['combinatorics', 'dp', '*2100'] |
E. Hikingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA traveler is planning a water hike along the river. He noted the suitable rest points for the night and wrote out their distances from the starting point. Each of these locations is further characterized by its picturesqueness, so for the i-th rest point the distance from the start equals xi, and its picturesqueness equals bi. The traveler will move down the river in one direction, we can assume that he will start from point 0 on the coordinate axis and rest points are points with coordinates xi.Every day the traveler wants to cover the distance l. In practice, it turns out that this is not always possible, because he needs to end each day at one of the resting points. In addition, the traveler is choosing between two desires: cover distance l every day and visit the most picturesque places.Let's assume that if the traveler covers distance rj in a day, then he feels frustration , and his total frustration over the hike is calculated as the total frustration on all days.Help him plan the route so as to minimize the relative total frustration: the total frustration divided by the total picturesqueness of all the rest points he used.The traveler's path must end in the farthest rest point.InputThe first line of the input contains integers n,βl (1ββ€βnββ€β1000,β1ββ€βlββ€β105) β the number of rest points and the optimal length of one day path.Then n lines follow, each line describes one rest point as a pair of integers xi,βbi (1ββ€βxi,βbiββ€β106). No two rest points have the same xi, the lines are given in the order of strictly increasing xi.OutputPrint the traveler's path as a sequence of the numbers of the resting points he used in the order he used them. Number the points from 1 to n in the order of increasing xi. The last printed number must be equal to n.ExamplesInput5 910 1020 1030 131 540 10Output1 2 4 5 NoteIn the sample test the minimum value of relative total frustration approximately equals 0.097549. This value can be calculated as . | Input5 910 1020 1030 131 540 10 | Output1 2 4 5 | 1 second | 256 megabytes | ['binary search', 'dp', '*2300'] |
D. Unbearable Controversy of Beingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c β one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a,βb), (b,βc), (a,βd), (d,βc) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below: Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him.Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city.When rhombi are compared, the order of intersections b and d doesn't matter.InputThe first line of the input contains a pair of integers n, m (1ββ€βnββ€β3000,β0ββ€βmββ€β30000) β the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers ai,βbi (1ββ€βai,βbiββ€βn;aiββ βbi) β the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions.It is not guaranteed that you can get from any intersection to any other one.OutputPrint the required number of "damn rhombi".ExamplesInput5 41 22 31 44 3Output1Input4 121 21 31 42 12 32 43 13 23 44 14 24 3Output12 | Input5 41 22 31 44 3 | Output1 | 1 second | 256 megabytes | ['brute force', 'combinatorics', 'dfs and similar', 'graphs', '*1700'] |
C. Given Length and Sum of Digits...time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.InputThe single line of the input contains a pair of integers m, s (1ββ€βmββ€β100,β0ββ€βsββ€β900) β the length and the sum of the digits of the required numbers.OutputIn the output print the pair of the required non-negative integer numbers β first the minimum possible number, then β the maximum possible number. If no numbers satisfying conditions required exist, print the pair of numbers "-1 -1" (without the quotes).ExamplesInput2 15Output69 96Input3 0Output-1 -1 | Input2 15 | Output69 96 | 1 second | 256 megabytes | ['dp', 'greedy', 'implementation', '*1400'] |
B. BerSU Balltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.InputThe first line contains an integer n (1ββ€βnββ€β100) β the number of boys. The second line contains sequence a1,βa2,β...,βan (1ββ€βaiββ€β100), where ai is the i-th boy's dancing skill.Similarly, the third line contains an integer m (1ββ€βmββ€β100) β the number of girls. The fourth line contains sequence b1,βb2,β...,βbm (1ββ€βbjββ€β100), where bj is the j-th girl's dancing skill.OutputPrint a single number β the required maximum possible number of pairs.ExamplesInput41 4 6 255 1 5 7 9Output3Input41 2 3 4410 11 12 13Output0Input51 1 1 1 131 2 3Output2 | Input41 4 6 255 1 5 7 9 | Output3 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'graph matchings', 'greedy', 'sortings', 'two pointers', '*1200'] |
A. SwapSorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.Note that in this problem you do not have to minimize the number of swaps β your task is to find any sequence that is no longer than n.InputThe first line of the input contains integer n (1ββ€βnββ€β3000) β the number of array elements. The second line contains elements of array: a0,βa1,β...,βanβ-β1 (β-β109ββ€βaiββ€β109), where ai is the i-th element of the array. The elements are numerated from 0 to nβ-β1 from left to right. Some integers may appear in the array more than once.OutputIn the first line print k (0ββ€βkββ€βn) β the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0ββ€βi,βjββ€βnβ-β1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print iβ=βj and swap the same pair of elements multiple times.If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.ExamplesInput55 2 5 1 4Output20 34 2Input610 20 20 40 60 60Output0Input2101 100Output10 1 | Input55 2 5 1 4 | Output20 34 2 | 1 second | 256 megabytes | ['greedy', 'implementation', 'sortings', '*1200'] |
B. Candy Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an old tradition of keeping 4 boxes of candies in the house in Cyberland. The numbers of candies are special if their arithmetic mean, their median and their range are all equal. By definition, for a set {x1,βx2,βx3,βx4} (x1ββ€βx2ββ€βx3ββ€βx4) arithmetic mean is , median is and range is x4β-βx1. The arithmetic mean and median are not necessary integer. It is well-known that if those three numbers are same, boxes will create a "debugging field" and codes in the field will have no bugs.For example, 1,β1,β3,β3 is the example of 4 numbers meeting the condition because their mean, median and range are all equal to 2.Jeff has 4 special boxes of candies. However, something bad has happened! Some of the boxes could have been lost and now there are only n (0ββ€βnββ€β4) boxes remaining. The i-th remaining box contains ai candies.Now Jeff wants to know: is there a possible way to find the number of candies of the 4β-βn missing boxes, meeting the condition above (the mean, median and range are equal)?InputThe first line of input contains an only integer n (0ββ€βnββ€β4).The next n lines contain integers ai, denoting the number of candies in the i-th box (1ββ€βaiββ€β500).OutputIn the first output line, print "YES" if a solution exists, or print "NO" if there is no solution.If a solution exists, you should output 4β-βn more lines, each line containing an integer b, denoting the number of candies in a missing box.All your numbers b must satisfy inequality 1ββ€βbββ€β106. It is guaranteed that if there exists a positive integer solution, you can always find such b's meeting the condition. If there are multiple answers, you are allowed to print any of them.Given numbers ai may follow in any order in the input, not necessary in non-decreasing.ai may have stood at any positions in the original set, not necessary on lowest n first positions.ExamplesInput211OutputYES33Input3111OutputNOInput41223OutputYESNoteFor the first sample, the numbers of candies in 4 boxes can be 1,β1,β3,β3. The arithmetic mean, the median and the range of them are all 2.For the second sample, it's impossible to find the missing number of candies.In the third example no box has been lost and numbers satisfy the condition.You may output b in any order. | Input211 | OutputYES33 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'math', '*1900'] |
A. Giga Towertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiga Tower is the tallest and deepest building in Cyberland. There are 17β777β777β777 floors, numbered from β-β8β888β888β888 to 8β888β888β888. In particular, there is floor 0 between floor β-β1 and floor 1. Every day, thousands of tourists come to this place to enjoy the wonderful view. In Cyberland, it is believed that the number "8" is a lucky number (that's why Giga Tower has 8β888β888β888 floors above the ground), and, an integer is lucky, if and only if its decimal notation contains at least one digit "8". For example, 8,ββ-β180,β808 are all lucky while 42,ββ-β10 are not. In the Giga Tower, if you write code at a floor with lucky floor number, good luck will always be with you (Well, this round is #278, also lucky, huh?).Tourist Henry goes to the tower to seek good luck. Now he is at the floor numbered a. He wants to find the minimum positive integer b, such that, if he walks b floors higher, he will arrive at a floor with a lucky number. InputThe only line of input contains an integer a (β-β109ββ€βaββ€β109).OutputPrint the minimum b in a line.ExamplesInput179Output1Input-1Output9Input18Output10NoteFor the first sample, he has to arrive at the floor numbered 180.For the second sample, he will arrive at 8.Note that b should be positive, so the answer for the third sample is 10, not 0. | Input179 | Output1 | 1 second | 256 megabytes | ['brute force', '*1100'] |
E. Touriststime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Cyberland, numbered from 1 to n, connected by m bidirectional roads. The j-th road connects city aj and bj.For tourists, souvenirs are sold in every city of Cyberland. In particular, city i sell it at a price of wi.Now there are q queries for you to handle. There are two types of queries: "C a w": The price in city a is changed to w. "A a b": Now a tourist will travel from city a to b. He will choose a route, he also doesn't want to visit a city twice. He will buy souvenirs at the city where the souvenirs are the cheapest (possibly exactly at city a or b). You should output the minimum possible price that he can buy the souvenirs during his travel.More formally, we can define routes as follow: A route is a sequence of cities [x1,βx2,β...,βxk], where k is a certain positive integer. For any 1ββ€βiβ<βjββ€βk,βxiββ βxj. For any 1ββ€βiβ<βk, there is a road connecting xi and xiβ+β1. The minimum price of the route is min(wx1,βwx2,β...,βwxk). The required answer is the minimum value of the minimum prices of all valid routes from a to b.InputThe first line of input contains three integers n,βm,βq (1ββ€βn,βm,βqββ€β105), separated by a single space.Next n lines contain integers wi (1ββ€βwiββ€β109).Next m lines contain pairs of space-separated integers aj and bj (1ββ€βaj,βbjββ€βn,βajββ βbj).It is guaranteed that there is at most one road connecting the same pair of cities. There is always at least one valid route between any two cities.Next q lines each describe a query. The format is "C a w" or "A a b" (1ββ€βa,βbββ€βn,β1ββ€βwββ€β109).OutputFor each query of type "A", output the corresponding answer.ExamplesInput3 3 31231 22 31 3A 2 3C 1 5A 2 3Output12Input7 9 412345671 22 51 52 33 42 45 66 75 7A 2 3A 6 4A 6 7A 3 3Output2153NoteFor the second sample, an optimal routes are:From 2 to 3 it is [2,β3].From 6 to 4 it is [6,β5,β1,β2,β4].From 6 to 7 it is [6,β5,β7].From 3 to 3 it is [3]. | Input3 3 31231 22 31 3A 2 3C 1 5A 2 3 | Output12 | 2 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'graphs', 'trees', '*3200'] |
D. Conveyor Beltstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAutomatic Bakery of Cyberland (ABC) recently bought an nβΓβm rectangle table. To serve the diners, ABC placed seats around the table. The size of each seat is equal to a unit square, so there are 2(nβ+βm) seats in total.ABC placed conveyor belts on each unit square on the table. There are three types of conveyor belts: "^", "<" and ">". A "^" belt can bring things upwards. "<" can bring leftwards and ">" can bring rightwards.Let's number the rows with 1 to n from top to bottom, the columns with 1 to m from left to right. We consider the seats above and below the top of the table are rows 0 and nβ+β1 respectively. Also we define seats to the left of the table and to the right of the table to be column 0 and mβ+β1. Due to the conveyor belts direction restriction there are currently no way for a diner sitting in the row nβ+β1 to be served.Given the initial table, there will be q events in order. There are two types of events: "A x y" means, a piece of bread will appear at row x and column y (we will denote such position as (x,βy)). The bread will follow the conveyor belt, until arriving at a seat of a diner. It is possible that the bread gets stuck in an infinite loop. Your task is to simulate the process, and output the final position of the bread, or determine that there will be an infinite loop. "C x y c" means that the type of the conveyor belt at (x,βy) is changed to c. Queries are performed separately meaning that even if the bread got stuck in an infinite loop, it won't affect further queries.InputThe first line of input contains three integers n, m and q (1ββ€βnββ€β105,β1ββ€βmββ€β10,β1ββ€βqββ€β105), separated by a space.Next n lines, each line contains m characters, describing the table. The characters can only be one of "<^>".Next q lines, each line describes an event. The format is "C x y c" or "A x y" (Consecutive elements are separated by a space). It's guaranteed that 1ββ€βxββ€βn,β1ββ€βyββ€βm. c is a character from the set "<^>".There are at most 10000 queries of "C" type.OutputFor each event of type "A", output two integers tx, ty in a line, separated by a space, denoting the destination of (x,βy) is (tx,βty).If there is an infinite loop, you should output txβ=βtyβ=ββ-β1.ExamplesInput2 2 3>>^^A 2 1C 1 2 <A 2 1Output1 3-1 -1Input4 5 7><<^<^<^^>>>>^>>^>>^A 3 1A 2 2C 1 4 <A 3 1C 1 2 ^A 3 1A 2 2Output0 4-1 -1-1 -10 20 2NoteFor the first sample:If the bread goes from (2,β1), it will go out of the table at (1,β3).After changing the conveyor belt of (1,β2) to "<", when the bread goes from (2,β1) again, it will get stuck at "><", so output is (β-β1,ββ-β1). | Input2 2 3>>^^A 2 1C 1 2 <A 2 1 | Output1 3-1 -1 | 3 seconds | 256 megabytes | ['data structures', '*2700'] |
C. Prefix Product Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a sequence [a1,βa2,β... ,βan]. Define its prefix product sequence .Now given n, find a permutation of [1,β2,β...,βn], such that its prefix product sequence is a permutation of [0,β1,β...,βnβ-β1].InputThe only input line contains an integer n (1ββ€βnββ€β105).OutputIn the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists.If any solution exists, you should output n more lines. i-th line contains only an integer ai. The elements of the sequence should be different positive integers no larger than n.If there are multiple solutions, you are allowed to print any of them.ExamplesInput7OutputYES1436527Input6OutputNONoteFor the second sample, there are no valid sequences. | Input7 | OutputYES1436527 | 1 second | 256 megabytes | ['constructive algorithms', 'math', 'number theory', '*2300'] |
B. Striptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlexandra has a paper strip with n numbers on it. Let's call them ai from left to right.Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy: Each piece should contain at least l numbers. The difference between the maximal and the minimal number on the piece should be at most s.Please help Alexandra to find the minimal number of pieces meeting the condition above.InputThe first line contains three space-separated integers n,βs,βl (1ββ€βnββ€β105,β0ββ€βsββ€β109,β1ββ€βlββ€β105).The second line contains n integers ai separated by spaces (β-β109ββ€βaiββ€β109).OutputOutput the minimal number of strip pieces.If there are no ways to split the strip, output -1.ExamplesInput7 2 21 3 1 2 4 1 2Output3Input7 2 21 100 1 100 1 100 1Output-1NoteFor the first sample, we can split the strip into 3 pieces: [1,β3,β1],β[2,β4],β[1,β2].For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | Input7 2 21 3 1 2 4 1 2 | Output3 | 1 second | 256 megabytes | ['binary search', 'data structures', 'dp', 'two pointers', '*2000'] |
A. Fight the Monstertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA monster is attacking the Cyberland!Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (HP), offensive power (ATK) and defensive power (DEF).During the battle, every second the monster's HP decrease by max(0,βATKYβ-βDEFM), while Yang's HP decreases by max(0,βATKMβ-βDEFY), where index Y denotes Master Yang and index M denotes monster. Both decreases happen simultaneously Once monster's HPββ€β0 and the same time Master Yang's HPβ>β0, Master Yang wins.Master Yang can buy attributes from the magic shop of Cyberland: h bitcoins per HP, a bitcoins per ATK, and d bitcoins per DEF.Now Master Yang wants to know the minimum number of bitcoins he can spend in order to win.InputThe first line contains three integers HPY,βATKY,βDEFY, separated by a space, denoting the initial HP, ATK and DEF of Master Yang.The second line contains three integers HPM,βATKM,βDEFM, separated by a space, denoting the HP, ATK and DEF of the monster.The third line contains three integers h,βa,βd, separated by a space, denoting the price of 1Β HP, 1Β ATK and 1Β DEF.All numbers in input are integer and lie between 1 and 100 inclusively.OutputThe only output line should contain an integer, denoting the minimum bitcoins Master Yang should spend in order to win.ExamplesInput1 2 11 100 11 100 100Output99Input100 100 1001 1 11 1 1Output0NoteFor the first sample, prices for ATK and DEF are extremely high. Master Yang can buy 99 HP, then he can beat the monster with 1 HP left.For the second sample, Master Yang is strong enough to beat the monster, so he doesn't need to buy anything. | Input1 2 11 100 11 100 100 | Output99 | 1 second | 256 megabytes | ['binary search', 'brute force', 'implementation', '*1800'] |
E. LIS of Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next "Data Structures and Algorithms" lesson will be about Longest Increasing Subsequence (LIS for short) of a sequence. For better understanding, Nam decided to learn it a few days before the lesson.Nam created a sequence a consisting of n (1ββ€βnββ€β105) elements a1,βa2,β...,βan (1ββ€βaiββ€β105). A subsequence ai1,βai2,β...,βaik where 1ββ€βi1β<βi2β<β...β<βikββ€βn is called increasing if ai1β<βai2β<βai3β<β...β<βaik. An increasing subsequence is called longest if it has maximum length among all increasing subsequences. Nam realizes that a sequence may have several longest increasing subsequences. Hence, he divides all indexes i (1ββ€βiββ€βn), into three groups: group of all i such that ai belongs to no longest increasing subsequences. group of all i such that ai belongs to at least one but not every longest increasing subsequence. group of all i such that ai belongs to every longest increasing subsequence. Since the number of longest increasing subsequences of a may be very large, categorizing process is very difficult. Your task is to help him finish this job.InputThe first line contains the single integer n (1ββ€βnββ€β105) denoting the number of elements of sequence a.The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β105).OutputPrint a string consisting of n characters. i-th character should be '1', '2' or '3' depending on which group among listed above index i belongs to.ExamplesInput14Output3Input41 3 2 5Output3223Input41 5 2 3Output3133NoteIn the second sample, sequence a consists of 4 elements: {a1,βa2,βa3,βa4} = {1,β3,β2,β5}. Sequence a has exactly 2 longest increasing subsequences of length 3, they are {a1,βa2,βa4} = {1,β3,β5} and {a1,βa3,βa4} = {1,β2,β5}.In the third sample, sequence a consists of 4 elements: {a1,βa2,βa3,βa4} = {1,β5,β2,β3}. Sequence a have exactly 1 longest increasing subsequence of length 3, that is {a1,βa3,βa4} = {1,β2,β3}. | Input14 | Output3 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', 'hashing', 'math', '*2200'] |
D. Valid Setstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you know, an undirected connected graph with n nodes and nβ-β1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109β+β7).InputThe first line contains two space-separated integers d (0ββ€βdββ€β2000) and n (1ββ€βnββ€β2000).The second line contains n space-separated positive integers a1,βa2,β...,βan(1ββ€βaiββ€β2000).Then the next nβ-β1 line each contain pair of integers u and v (1ββ€βu,βvββ€βn) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.OutputPrint the number of valid sets modulo 1000000007.ExamplesInput1 42 1 3 21 21 33 4Output8Input0 31 2 31 22 3Output3Input4 87 8 7 5 4 6 4 101 61 25 81 33 56 73 4Output41NoteIn the first sample, there are exactly 8 valid sets: {1},β{2},β{3},β{4},β{1,β2},β{1,β3},β{3,β4} and {1,β3,β4}. Set {1,β2,β3,β4} is not valid, because the third condition isn't satisfied. Set {1,β4} satisfies the third condition, but conflicts with the second condition. | Input1 42 1 3 21 21 33 4 | Output8 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'math', 'trees', '*2100'] |
C. Palindrome Transformationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.There is a cursor pointing at some symbol of the string. Suppose that cursor is at position i (1ββ€βiββ€βn, the string uses 1-based indexing) now. Left and right arrow keys are used to move cursor around the string. The string is cyclic, that means that when Nam presses left arrow key, the cursor will move to position iβ-β1 if iβ>β1 or to the end of the string (i. e. position n) otherwise. The same holds when he presses the right arrow key (if iβ=βn, the cursor appears at the beginning of the string).When Nam presses up arrow key, the letter which the text cursor is pointing to will change to the next letter in English alphabet (assuming that alphabet is also cyclic, i. e. after 'z' follows 'a'). The same holds when he presses the down arrow key.Initially, the text cursor is at position p. Because Nam has a lot homework to do, he wants to complete this as fast as possible. Can you help him by calculating the minimum number of arrow keys presses to make the string to be a palindrome?InputThe first line contains two space-separated integers n (1ββ€βnββ€β105) and p (1ββ€βpββ€βn), the length of Nam's string and the initial position of the text cursor.The next line contains n lowercase characters of Nam's string.OutputPrint the minimum number of presses needed to change string into a palindrome.ExamplesInput8 3aeabcaezOutput6NoteA string is a palindrome if it reads the same forward or reversed.In the sample test, initial Nam's string is: (cursor position is shown bold).In optimal solution, Nam may do 6 following steps:The result, , is now a palindrome. | Input8 3aeabcaez | Output6 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', '*1700'] |
B. OR in Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define logical OR as an operation on two logical values (i. e. values that belong to the set {0,β1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner: where is equal to 1 if some aiβ=β1, otherwise it is equal to 0.Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1ββ€βiββ€βm) and column j (1ββ€βjββ€βn) is denoted as Aij. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula:.(Bij is OR of all elements in row i and column j of matrix A)Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large.InputThe first line contains two integer m and n (1ββ€βm,βnββ€β100), number of rows and number of columns of matrices respectively.The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1).OutputIn the first line, print "NO" if Nam has made a mistake when calculating B, otherwise print "YES". If the first line is "YES", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one.ExamplesInput2 21 00 0OutputNOInput2 31 1 11 1 1OutputYES1 1 11 1 1Input2 30 1 01 1 1OutputYES0 0 00 1 0 | Input2 21 00 0 | OutputNO | 1 second | 256 megabytes | ['greedy', 'hashing', 'implementation', '*1300'] |
A. Calculating Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a positive integer n let's define a function f:f(n)β=ββ-β1β+β2β-β3β+β..β+β(β-β1)nn Your task is to calculate f(n) for a given integer n.InputThe single line contains the positive integer n (1ββ€βnββ€β1015).OutputPrint f(n) in a single line.ExamplesInput4Output2Input5Output-3Notef(4)β=ββ-β1β+β2β-β3β+β4β=β2f(5)β=ββ-β1β+β2β-β3β+β4β-β5β=ββ-β3 | Input4 | Output2 | 1 second | 256 megabytes | ['implementation', 'math', '*800'] |
B. Valuable Resourcestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMany computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems. Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square. Building a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.InputThe first line of the input contains number nΒ β the number of mines on the map (2ββ€βnββ€β1000). Each of the next n lines contains a pair of integers xi and yiΒ β the coordinates of the corresponding mine (β-β109ββ€βxi,βyiββ€β109). All points are pairwise distinct.OutputPrint the minimum area of the city that can cover all the mines with valuable resources.ExamplesInput20 02 2Output4Input20 00 3Output9 | Input20 02 2 | Output4 | 1 second | 256 megabytes | ['brute force', 'greedy', '*1300'] |
A. Factorytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to produce (remainder after dividing x by m) more details. Unfortunately, no customer has ever bought any mythical detail, so all the details produced stay on the factory. The board of directors are worried that the production by the given plan may eventually stop (that means that there will be Π° moment when the current number of details on the factory is divisible by m). Given the number of details a on the first day and number m check if the production stops at some moment.InputThe first line contains two integers a and m (1ββ€βa,βmββ€β105).OutputPrint "Yes" (without quotes) if the production will eventually stop, otherwise print "No".ExamplesInput1 5OutputNoInput3 6OutputYes | Input1 5 | OutputNo | 1 second | 256 megabytes | ['implementation', 'math', 'matrices', '*1400'] |
E. Sign on Fencetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBizon the Champion has recently finished painting his wood fence. The fence consists of a sequence of n panels of 1 meter width and of arbitrary height. The i-th panel's height is hi meters. The adjacent planks follow without a gap between them.After Bizon painted the fence he decided to put a "for sale" sign on it. The sign will be drawn on a rectangular piece of paper and placed on the fence so that the sides of the sign are parallel to the fence panels and are also aligned with the edges of some panels. Bizon the Champion introduced the following constraints for the sign position: The width of the sign should be exactly w meters. The sign must fit into the segment of the fence from the l-th to the r-th panels, inclusive (also, it can't exceed the fence's bound in vertical direction). The sign will be really pretty, So Bizon the Champion wants the sign's height to be as large as possible.You are given the description of the fence and several queries for placing sign. For each query print the maximum possible height of the sign that can be placed on the corresponding segment of the fence with the given fixed width of the sign.InputThe first line of the input contains integer nΒ β the number of panels in the fence (1ββ€βnββ€β105). The second line contains n space-separated integers hi,Β β the heights of the panels (1ββ€βhiββ€β109). The third line contains an integer mΒ β the number of the queries (1ββ€βmββ€β105). The next m lines contain the descriptions of the queries, each query is represented by three integers l, r and w (1ββ€βlββ€βrββ€βn, 1ββ€βwββ€βrβ-βlβ+β1)Β β the segment of the fence and the width of the sign respectively.OutputFor each query print the answer on a separate lineΒ β the maximum height of the sign that can be put in the corresponding segment of the fence with all the conditions being satisfied.ExamplesInput51 2 2 3 332 5 32 5 21 5 5Output231NoteThe fence described in the sample looks as follows: The possible positions for the signs for all queries are given below. The optimal position of the sign for the first query. The optimal position of the sign for the second query. The optimal position of the sign for the third query. | Input51 2 2 3 332 5 32 5 21 5 5 | Output231 | 4 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', '*2500'] |
D. Kindergartentime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a kindergarten, the children are being divided into groups. The teacher put the children in a line and associated each child with his or her integer charisma value. Each child should go to exactly one group. Each group should be a nonempty segment of consecutive children of a line. A group's sociability is the maximum difference of charisma of two children in the group (in particular, if the group consists of one child, its sociability equals a zero). The teacher wants to divide the children into some number of groups in such way that the total sociability of the groups is maximum. Help him find this value.InputThe first line contains integer nΒ β the number of children in the line (1ββ€βnββ€β106).The second line contains n integers aiΒ β the charisma of the i-th child (β-β109ββ€βaiββ€β109).OutputPrint the maximum possible total sociability of all groups.ExamplesInput51 2 3 1 2Output3Input33 3 3Output0NoteIn the first test sample one of the possible variants of an division is following: the first three children form a group with sociability 2, and the two remaining children form a group with sociability 1.In the second test sample any division leads to the same result, the sociability will be equal to 0 in each group. | Input51 2 3 1 2 | Output3 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', '*2400'] |
C. Strange Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHow many specific orders do you know? Ascending order, descending order, order of ascending length, order of ascending polar angle... Let's have a look at another specific order: d-sorting. This sorting is applied to the strings of length at least d, where d is some positive integer. The characters of the string are sorted in following manner: first come all the 0-th characters of the initial string, then the 1-st ones, then the 2-nd ones and so on, in the end go all the (dβ-β1)-th characters of the initial string. By the i-th characters we mean all the character whose positions are exactly i modulo d. If two characters stand on the positions with the same remainder of integer division by d, their relative order after the sorting shouldn't be changed. The string is zero-indexed. For example, for string 'qwerty':Its 1-sorting is the string 'qwerty' (all characters stand on 0 positions),Its 2-sorting is the string 'qetwry' (characters 'q', 'e' and 't' stand on 0 positions and characters 'w', 'r' and 'y' are on 1 positions),Its 3-sorting is the string 'qrwtey' (characters 'q' and 'r' stand on 0 positions, characters 'w' and 't' stand on 1 positions and characters 'e' and 'y' stand on 2 positions),Its 4-sorting is the string 'qtwyer',Its 5-sorting is the string 'qywert'.You are given string S of length n and m shuffling operations of this string. Each shuffling operation accepts two integer arguments k and d and transforms string S as follows. For each i from 0 to nβ-βk in the increasing order we apply the operation of d-sorting to the substring S[i..iβ+βkβ-β1]. Here S[a..b] represents a substring that consists of characters on positions from a to b inclusive.After each shuffling operation you need to print string S.InputThe first line of the input contains a non-empty string S of length n, consisting of lowercase and uppercase English letters and digits from 0 to 9. The second line of the input contains integer mΒ β the number of shuffling operations (1ββ€βmΒ·nββ€β106). Following m lines contain the descriptions of the operations consisting of two integers k and d (1ββ€βdββ€βkββ€βn). OutputAfter each operation print the current state of string S.ExamplesInputqwerty34 26 35 2OutputqertwyqtewryqetyrwNoteHere is detailed explanation of the sample. The first modification is executed with arguments kβ=β4, dβ=β2. That means that you need to apply 2-sorting for each substring of length 4 one by one moving from the left to the right. The string will transform in the following manner:qwerty βββ qewrty βββ qerwty βββ qertwyThus, string S equals 'qertwy' at the end of first query.The second modification is executed with arguments kβ=β6, dβ=β3. As a result of this operation the whole string S is replaced by its 3-sorting: qertwy βββ qtewryThe third modification is executed with arguments kβ=β5, dβ=β2. qtewry βββ qertwy βββ qetyrw | Inputqwerty34 26 35 2 | Outputqertwyqtewryqetyrw | 2 seconds | 256 megabytes | ['implementation', 'math', '*2600'] |
B. Maximum Valuetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a consisting of n integers. Find the maximum possible value of (integer remainder of ai divided by aj), where 1ββ€βi,βjββ€βn and aiββ₯βaj.InputThe first line contains integer nΒ β the length of the sequence (1ββ€βnββ€β2Β·105). The second line contains n space-separated integers ai (1ββ€βaiββ€β106).OutputPrint the answer to the problem.ExamplesInput33 4 5Output2 | Input33 4 5 | Output2 | 1 second | 256 megabytes | ['binary search', 'math', 'sortings', 'two pointers', '*2100'] |
A. Bitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer x.You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that lββ€βxββ€βr, and is maximum possible. If there are multiple such numbers find the smallest of them.InputThe first line contains integer nΒ β the number of queries (1ββ€βnββ€β10000).Each of the following n lines contain two integers li,βriΒ β the arguments for the corresponding query (0ββ€βliββ€βriββ€β1018).OutputFor each query print the answer in a separate line.ExamplesInput31 22 41 10Output137NoteThe binary representations of numbers from 1 to 10 are listed below:110β=β12210β=β102310β=β112410β=β1002510β=β1012610β=β1102710β=β1112810β=β10002910β=β100121010β=β10102 | Input31 22 41 10 | Output137 | 1 second | 256 megabytes | ['bitmasks', 'constructive algorithms', '*1700'] |
B. Friends and Presentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have two friends. You want to present each of them several positive integers. You want to present cnt1 numbers to the first friend and cnt2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends.In addition, the first friend does not like the numbers that are divisible without remainder by prime number x. The second one does not like the numbers that are divisible without remainder by prime number y. Of course, you're not going to present your friends numbers they don't like.Your task is to find such minimum number v, that you can form presents using numbers from a set 1,β2,β...,βv. Of course you may choose not to present some numbers at all.A positive integer number greater than 1 is called prime if it has no positive divisors other than 1 and itself.InputThe only line contains four positive integers cnt1, cnt2, x, y (1ββ€βcnt1,βcnt2β<β109; cnt1β+βcnt2ββ€β109; 2ββ€βxβ<βyββ€β3Β·104)Β β the numbers that are described in the statement. It is guaranteed that numbers x, y are prime.OutputPrint a single integer β the answer to the problem.ExamplesInput3 1 2 3Output5Input1 3 2 3Output4NoteIn the first sample you give the set of numbers {1,β3,β5} to the first friend and the set of numbers {2} to the second friend. Note that if you give set {1,β3,β5} to the first friend, then we cannot give any of the numbers 1, 3, 5 to the second friend. In the second sample you give the set of numbers {3} to the first friend, and the set of numbers {1,β2,β4} to the second friend. Thus, the answer to the problem is 4. | Input3 1 2 3 | Output5 | 1 second | 256 megabytes | ['binary search', 'math', '*1800'] |
A. Counterexample time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend has recently learned about coprime numbers. A pair of numbers {a,βb} is called coprime if the maximum number that divides both a and b is equal to one. Your friend often comes up with different statements. He has recently supposed that if the pair (a,βb) is coprime and the pair (b,βc) is coprime, then the pair (a,βc) is coprime. You want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers (a,βb,βc), for which the statement is false, and the numbers meet the condition lββ€βaβ<βbβ<βcββ€βr. More specifically, you need to find three numbers (a,βb,βc), such that lββ€βaβ<βbβ<βcββ€βr, pairs (a,βb) and (b,βc) are coprime, and pair (a,βc) is not coprime.InputThe single line contains two positive space-separated integers l, r (1ββ€βlββ€βrββ€β1018; rβ-βlββ€β50).OutputPrint three positive space-separated integers a, b, cΒ β three distinct numbers (a,βb,βc) that form the counterexample. If there are several solutions, you are allowed to print any of them. The numbers must be printed in ascending order. If the counterexample does not exist, print the single number -1.ExamplesInput2 4Output2 3 4Input10 11Output-1Input900000000000000009 900000000000000029Output900000000000000009 900000000000000010 900000000000000021NoteIn the first sample pair (2,β4) is not coprime and pairs (2,β3) and (3,β4) are. In the second sample you cannot form a group of three distinct integers, so the answer is -1. In the third sample it is easy to see that numbers 900000000000000009 and 900000000000000021 are divisible by three. | Input2 4 | Output2 3 4 | 1 second | 256 megabytes | ['brute force', 'implementation', 'math', 'number theory', '*1100'] |
E. ELCAtime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a root tree containing n vertexes. Let's number the tree vertexes with integers from 1 to n. The tree root is in the vertex 1.Each vertex (except fot the tree root) v has a direct ancestor pv. Also each vertex v has its integer value sv. Your task is to perform following queries: P v u (uββ βv). If u isn't in subtree of v, you must perform the assignment pvβ=βu. Otherwise you must perform assignment puβ=βv. Note that after this query the graph continues to be a tree consisting of n vertexes. V v t. Perform assignment svβ=βt. Your task is following. Before starting performing queries and after each query you have to calculate expected value written on the lowest common ancestor of two equiprobably selected vertices i and j. Here lowest common ancestor of i and j is the deepest vertex that lies on the both of the path from the root to vertex i and the path from the root to vertex j. Please note that the vertices i and j can be the same (in this case their lowest common ancestor coincides with them).InputThe first line of the input contains integer n (2ββ€βnββ€β5Β·104) β the number of the tree vertexes. The second line contains nβ-β1 integer p2,βp3,β...,βpn (1ββ€βpiββ€βn) β the description of the tree edges. It is guaranteed that those numbers form a tree.The third line contains n integers β s1,βs2,β... sn (0ββ€βsiββ€β106) β the values written on each vertex of the tree.The next line contains integer q (1ββ€βqββ€β5Β·104) β the number of queries. Each of the following q lines contains the description of the query in the format described in the statement. It is guaranteed that query arguments u and v lie between 1 and n. It is guaranteed that argument t in the queries of type V meets limits 0ββ€βtββ€β106.OutputPrint qβ+β1 number β the corresponding expected values. Your answer will be considered correct if its absolute or relative error doesn't exceed 10β-β9.ExamplesInput51 2 2 11 2 3 4 55P 3 4P 4 5V 2 3P 5 2P 1 4Output1.6400000001.8000000002.2800000002.3200000002.8000000001.840000000NoteNote that in the query P v u if u lies in subtree of v you must perform assignment puβ=βv. An example of such case is the last query in the sample. | Input51 2 2 11 2 3 4 55P 3 4P 4 5V 2 3P 5 2P 1 4 | Output1.6400000001.8000000002.2800000002.3200000002.8000000001.840000000 | 8 seconds | 256 megabytes | ['data structures', 'trees', '*3200'] |
D. Random Function and Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a rooted tree consisting of n vertices. Let's number them with integers from 1 to n inclusive. The root of the tree is the vertex 1. For each iβ>β1 direct parent of the vertex i is pi. We say that vertex i is child for its direct parent pi.You have initially painted all the vertices with red color. You like to repaint some vertices of the tree. To perform painting you use the function paint that you call with the root of the tree as an argument. Here is the pseudocode of this function:count = 0 // global integer variable rnd() { // this function is used in paint code return 0 or 1 equiprobably}paint(s) { if (count is even) then paint s with white color else paint s with black color count = count + 1 if rnd() = 1 then children = [array of vertex s children in ascending order of their numbers] else children = [array of vertex s children in descending order of their numbers] for child in children { // iterating over children array if rnd() = 1 then paint(child) // calling paint recursively }}As a result of this function, some vertices may change their colors to white or black and some of them may remain red.Your task is to determine the number of distinct possible colorings of the vertices of the tree. We will assume that the coloring is possible if there is a nonzero probability to get this coloring with a single call of paint(1). We assume that the colorings are different if there is a pair of vertices that are painted with different colors in these colorings. Since the required number may be very large, find its remainder of division by 1000000007 (109β+β7).InputThe first line contains a single integer n (2ββ€βnββ€β105)Β β the number of vertexes in the tree.The second line contains nβ-β1 integers p2,βp3,β...,βpn (1ββ€βpiβ<βi). Number pi is the parent of vertex i.OutputPrint a single integerΒ β the answer to the problem modulo 1000000007 (109β+β7)ExamplesInput41 2 1Output8Input31 1Output5NoteAll possible coloring patterns of the first sample are given below. | Input41 2 1 | Output8 | 1 second | 256 megabytes | ['combinatorics', 'dp', 'trees', '*2700'] |
C. Game with Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou play the game with your friend. The description of this game is listed below. Your friend creates n distinct strings of the same length m and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the n strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: Β«What character stands on position pos in the string you have chosen?Β» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.InputThe first line contains a single integer n (1ββ€βnββ€β50)Β β the number of strings your friend came up with.The next n lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.OutputPrint the single number β the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10β-β9.ExamplesInput2aabaacOutput2.000000000000000Input3aaAaBaCaaOutput1.666666666666667Input3acavacwqqOutput1.000000000000000NoteIn the first sample the strings only differ in the character in the third position. So only the following situations are possible: you guess the string in one question. The event's probability is ; you guess the string in two questions. The event's probability is Β· = (as in this case the first question should ask about the position that is other than the third one); you guess the string in three questions. The event's probability is Β· Β· = ; Thus, the expected value is equal to In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is .In the third sample whatever position we ask about in the first question, we immediately identify the string. | Input2aabaac | Output2.000000000000000 | 1 second | 256 megabytes | ['bitmasks', 'dp', 'probabilities', '*2600'] |
B. Interesting Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe'll call an array of n non-negative integers a[1],βa[2],β...,βa[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1ββ€βliββ€βriββ€βn) meaning that value should be equal to qi. Your task is to find any interesting array of n elements or state that such array doesn't exist.Expression x&y means the bitwise AND of numbers x and y. In programming languages C++, Java and Python this operation is represented as "&", in Pascal β as "and".InputThe first line contains two integers n, m (1ββ€βnββ€β105, 1ββ€βmββ€β105)Β β the number of elements in the array and the number of limits.Each of the next m lines contains three integers li, ri, qi (1ββ€βliββ€βriββ€βn, 0ββ€βqiβ<β230) describing the i-th limit.OutputIf the interesting array exists, in the first line print "YES" (without the quotes) and in the second line print n integers a[1],βa[2],β...,βa[n] (0ββ€βa[i]β<β230)Β decribing the interesting array. If there are multiple answers, print any of them.If the interesting array doesn't exist, print "NO" (without the quotes) in the single line.ExamplesInput3 11 3 3OutputYES3 3 3Input3 21 3 31 3 2OutputNO | Input3 11 3 3 | OutputYES3 3 3 | 1 second | 256 megabytes | ['constructive algorithms', 'data structures', 'trees', '*1800'] |
A. Diverse Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPermutation p is an ordered set of integers p1,βββp2,βββ...,βββpn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,βββp2,βββ...,βββpn.Your task is to find such permutation p of length n, that the group of numbers |p1β-βp2|,β|p2β-βp3|,β...,β|pnβ-β1β-βpn| has exactly k distinct elements.InputThe single line of the input contains two space-separated positive integers n, k (1ββ€βkβ<βnββ€β105).OutputPrint n integers forming the permutation. If there are multiple answers, print any of them.ExamplesInput3 2Output1 3 2Input3 1Output1 2 3Input5 2Output1 3 2 4 5NoteBy |x| we denote the absolute value of number x. | Input3 2 | Output1 3 2 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1200'] |
E. Parking Lottime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya's been bored at work and he is killing the time by watching the parking lot at the office. The parking lot looks from above like an nβΓβm table (a cell of the table corresponds to a single parking spot). Some spots in the parking lot are taken, others are empty.Petya watches cars riding into the parking lot one by one. After a car settles down at the parking spot, Petya amuzes himself by counting what maximum square of empty spots (i.e. a square subtable) can be seen on the parking lot if we look at it from above. Also, he takes notes of the square's size (side length) in his notebook. You task is: given the state of the parking lot at the initial moment of time and the information about where the arriving cars park, restore what Petya wrote in his notebook. It is midday, so nobody leaves the lot.InputThe first line contains three integers n, m and k β the sizes of the parking lot and the number of arriving cars after Petya started his watch (1ββ€βn,βm,βkββ€β2000). Each of the following n lines contains m characters 'X' and '.', where 'X' means a taken spot and '.' means an empty spot. Each of the next k lines contains a pair of integers xi, yi β the number of row and column of the spot the corresponding car takes (1ββ€βxiββ€βn, 1ββ€βyiββ€βm). It is guaranteed that this place was empty. You can assume that a car enters a parking lot only after the previous car successfully finds a spot.OutputPrint k integers β the length of the side of the maximum square of empty spots after the corresponding car has entered the parking lot.ExamplesInput7 8 4........X.....X..................X......................1 56 43 54 6Output5443 | Input7 8 4........X.....X..................X......................1 56 43 54 6 | Output5443 | 3 seconds | 256 megabytes | ['data structures', 'divide and conquer', '*2800'] |
D. Parcelstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJaroslav owns a small courier service. He has recently got and introduced a new system of processing parcels. Each parcel is a box, the box has its weight and strength. The system works as follows. It originally has an empty platform where you can put boxes by the following rules: If the platform is empty, then the box is put directly on the platform, otherwise it is put on the topmost box on the platform. The total weight of all boxes on the platform cannot exceed the strength of platform S at any time. The strength of any box of the platform at any time must be no less than the total weight of the boxes that stand above. You can take only the topmost box from the platform.The system receives n parcels, the i-th parcel arrives exactly at time ini, its weight and strength are equal to wi and si, respectively. Each parcel has a value of vi bourles. However, to obtain this value, the system needs to give the parcel exactly at time outi, otherwise Jaroslav will get 0 bourles for it. Thus, Jaroslav can skip any parcel and not put on the platform, formally deliver it at time ini and not get anything for it. Any operation in the problem is performed instantly. This means that it is possible to make several operations of receiving and delivering parcels at the same time and in any order. Please note that the parcel that is delivered at time outi, immediately gets outside of the system, and the following activities taking place at the same time are made ββwithout taking it into consideration. Since the system is very complex, and there are a lot of received parcels, Jaroslav asks you to say what maximum amount of money he can get using his system.InputThe first line of the input contains two space-separated integers n and S (1ββ€βnββ€β500, 0ββ€βSββ€β1000). Then n lines follow, the i-th line contains five space-separated integers: ini, outi, wi, si and vi (0ββ€βiniβ<βoutiβ<β2n, 0ββ€βwi,βsiββ€β1000, 1ββ€βviββ€β106). It is guaranteed that for any i and j (iββ βj) either iniββ βinj, or outiββ βoutj.OutputPrint a single number β the maximum sum in bourles that Jaroslav can get.ExamplesInput3 20 1 1 1 11 2 1 1 10 2 1 1 1Output3Input5 50 6 1 2 11 2 1 1 11 3 1 1 13 6 2 1 24 5 1 1 1Output5NoteNote to the second sample (T is the moment in time): Tβ=β0: The first parcel arrives, we put in on the first platform. Tβ=β1: The second and third parcels arrive, we put the third one on the current top (i.e. first) parcel on the platform, then we put the secod one on the third one. Now the first parcel holds weight w2β+βw3β=β2 and the third parcel holds w2β=β1. Tβ=β2: We deliver the second parcel and get v2β=β1 bourle. Now the first parcel holds weight w3β=β1, the third one holds 0. Tβ=β3: The fourth parcel comes. First we give the third parcel and get v3β=β1 bourle. Now the first parcel holds weight 0. We put the fourth parcel on it β the first one holds w4β=β2. Tβ=β4: The fifth parcel comes. We cannot put it on the top parcel of the platform as in that case the first parcel will carry weight w4β+βw5β=β3, that exceed its strength s1β=β2, that's unacceptable. We skip the fifth parcel and get nothing for it. Tβ=β5: Nothing happens. Tβ=β6: We deliver the fourth, then the first parcel and get v1β+βv4β=β3 bourles for them. Note that you could have skipped the fourth parcel and got the fifth one instead, but in this case the final sum would be 4 bourles. | Input3 20 1 1 1 11 2 1 1 10 2 1 1 1 | Output3 | 2 seconds | 256 megabytes | ['dp', 'graphs', '*2600'] |
E. Riding in a Lifttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. However, you already are in the mood and decide to make k consecutive trips in the lift.Let us suppose that at the moment you are on the floor number x (initially, you were on floor a). For another trip between floors you choose some floor with number y (yββ βx) and the lift travels to this floor. As you cannot visit floor b with the secret lab, you decided that the distance from the current floor x to the chosen y must be strictly less than the distance from the current floor x to floor b with the secret lab. Formally, it means that the following inequation must fulfill: |xβ-βy|β<β|xβ-βb|. After the lift successfully transports you to floor y, you write down number y in your notepad.Your task is to find the number of distinct number sequences that you could have written in the notebook as the result of k trips in the lift. As the sought number of trips can be rather large, find the remainder after dividing the number by 1000000007 (109β+β7).InputThe first line of the input contains four space-separated integers n, a, b, k (2ββ€βnββ€β5000, 1ββ€βkββ€β5000, 1ββ€βa,βbββ€βn, aββ βb).OutputPrint a single integer β the remainder after dividing the sought number of sequences by 1000000007 (109β+β7).ExamplesInput5 2 4 1Output2Input5 2 4 2Output2Input5 3 4 1Output0NoteTwo sequences p1,βp2,β...,βpk and q1,βq2,β...,βqk are distinct, if there is such integer j (1ββ€βjββ€βk), that pjββ βqj.Notes to the samples: In the first sample after the first trip you are either on floor 1, or on floor 3, because |1β-β2|β<β|2β-β4| and |3β-β2|β<β|2β-β4|. In the second sample there are two possible sequences: (1,β2); (1,β3). You cannot choose floor 3 for the first trip because in this case no floor can be the floor for the second trip. In the third sample there are no sought sequences, because you cannot choose the floor for the first trip. | Input5 2 4 1 | Output2 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', '*1900'] |
D. Long Jumpstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputValery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1,βa2,β...,βan, where ai denotes the distance of the i-th mark from the origin (a1β=β0, anβ=βl).Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1ββ€βiββ€βjββ€βn), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, ajβ-βaiβ=βd). Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (xβ<βy) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y. Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.InputThe first line contains four positive space-separated integers n, l, x, y (2ββ€βnββ€β105, 2ββ€βlββ€β109, 1ββ€βxβ<βyββ€βl) β the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly.The second line contains a sequence of n integers a1,βa2,β...,βan (0β=βa1β<βa2β<β...β<βanβ=βl), where ai shows the distance from the i-th mark to the origin.OutputIn the first line print a single non-negative integer v β the minimum number of marks that you need to add on the ruler.In the second line print v space-separated integers p1,βp2,β...,βpv (0ββ€βpiββ€βl). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them.ExamplesInput3 250 185 2300 185 250Output1230Input4 250 185 2300 20 185 250Output0Input2 300 185 2300 300Output2185 230NoteIn the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark.In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks.In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills. | Input3 250 185 2300 185 250 | Output1230 | 1 second | 256 megabytes | ['binary search', 'greedy', 'implementation', '*1700'] |
C. Examstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudent Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (biβ<βai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai.Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.InputThe first line contains a single positive integer n (1ββ€βnββ€β5000) β the number of exams Valera will take.Each of the next n lines contains two positive space-separated integers ai and bi (1ββ€βbiβ<βaiββ€β109) β the date of the exam in the schedule and the early date of passing the i-th exam, correspondingly.OutputPrint a single integer β the minimum possible number of the day when Valera can take the last exam if he takes all the exams so that all the records in his record book go in the order of non-decreasing date.ExamplesInput35 23 14 2Output2Input36 15 24 3Output6NoteIn the first sample Valera first takes an exam in the second subject on the first day (the teacher writes down the schedule date that is 3). On the next day he takes an exam in the third subject (the teacher writes down the schedule date, 4), then he takes an exam in the first subject (the teacher writes down the mark with date 5). Thus, Valera takes the last exam on the second day and the dates will go in the non-decreasing order: 3, 4, 5.In the second sample Valera first takes an exam in the third subject on the fourth day. Then he takes an exam in the second subject on the fifth day. After that on the sixth day Valera takes an exam in the first subject. | Input35 23 14 2 | Output2 | 1 second | 256 megabytes | ['greedy', 'sortings', '*1400'] |
B. Towerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task.InputThe first line contains two space-separated positive integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β1000) β the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β104) β the towers' initial heights.OutputIn the first line print two space-separated non-negative integers s and m (mββ€βk). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that.In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (iββ βj). Note that in the process of performing operations the heights of some towers can become equal to zero.If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them.ExamplesInput3 25 8 5Output0 22 12 3Input3 42 2 4Output1 13 2Input5 38 3 2 6 3Output3 31 31 21 3NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6. | Input3 25 8 5 | Output0 22 12 3 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'implementation', 'sortings', '*1400'] |
A. Expressiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets: 1+2*3=7 1*(2+3)=5 1*2*3=6 (1+2)*3=9 Note that you can insert operation signs only between a and b, and between b and c, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2.It's easy to see that the maximum value that you can obtain is 9.Your task is: given a, b and c print the maximum value that you can get.InputThe input contains three integers a, b and c, each on a single line (1ββ€βa,βb,βcββ€β10).OutputPrint the maximum value of the expression that you can obtain.ExamplesInput123Output9Input2103Output60 | Input123 | Output9 | 1 second | 256 megabytes | ['brute force', 'math', '*1000'] |
Subsets and Splits