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
D. Airplane Arrangementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an airplane which has n rows from front to back. There will be m people boarding this airplane.This airplane has an entrance at the very front and very back of the plane.Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109 + 7.InputThe first line of input will contain two integers n, m (1 ≀ m ≀ n ≀ 1 000 000), the number of seats, and the number of passengers, respectively.OutputPrint a single number, the number of ways, modulo 109 + 7.ExampleInput3 3Output128NoteHere, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat.
Input3 3
Output128
2 seconds
256 megabytes
['math', 'number theory', '*2700']
C. Future Failuretime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game with a string of characters, with Alice going first. The string consists n characters, each of which is one of the first k letters of the alphabet. On a player’s turn, they can either arbitrarily permute the characters in the words, or delete exactly one character in the word (if there is at least one character). In addition, their resulting word cannot have appeared before throughout the entire game. The player unable to make a valid move loses the game.Given n, k, p, find the number of words with exactly n characters consisting of the first k letters of the alphabet such that Alice will win if both Alice and Bob play optimally. Return this number modulo the prime number p.InputThe first line of input will contain three integers n, k, p (1 ≀ n ≀ 250 000, 1 ≀ k ≀ 26, 108 ≀ p ≀ 109 + 100, p will be prime).OutputPrint a single integer, the number of winning words for Alice, modulo p.ExampleInput4 2 100000007Output14NoteThere are 14 strings that that Alice can win with. For example, some strings are "bbaa" and "baaa". Alice will lose on strings like "aaaa" or "bbbb".
Input4 2 100000007
Output14
3 seconds
256 megabytes
['dp', 'games', '*2800']
B. Diverging Directionstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed weighted graph with n nodes and 2n - 2 edges. The nodes are labeled from 1 to n, while the edges are labeled from 1 to 2n - 2. The graph's edges can be split into two parts. The first n - 1 edges will form a rooted spanning tree, with node 1 as the root. All these edges will point away from the root. The last n - 1 edges will be from node i to node 1, for all 2 ≀ i ≀ n. You are given q queries. There are two types of queries 1 i w: Change the weight of the i-th edge to w 2 u v: Print the length of the shortest path between nodes u to v Given these queries, print the shortest path lengths.InputThe first line of input will contain two integers n, q (2 ≀ n, q ≀ 200 000), the number of nodes, and the number of queries, respectively.The next 2n - 2 integers will contain 3 integers ai, bi, ci, denoting a directed edge from node ai to node bi with weight ci.The first n - 1 of these lines will describe a rooted spanning tree pointing away from node 1, while the last n - 1 of these lines will have bi = 1.More specifically, The edges (a1, b1), (a2, b2), ... (an - 1, bn - 1) will describe a rooted spanning tree pointing away from node 1. bj = 1 for n ≀ j ≀ 2n - 2. an, an + 1, ..., a2n - 2 will be distinct and between 2 and n. The next q lines will contain 3 integers, describing a query in the format described in the statement.All edge weights will be between 1 and 106.OutputFor each type 2 query, print the length of the shortest path in its own line.ExampleInput5 91 3 13 2 21 4 33 5 45 1 53 1 62 1 74 1 82 1 12 1 32 3 52 5 21 1 1002 1 31 8 302 4 22 2 4Output014810013210
Input5 91 3 13 2 21 4 33 5 45 1 53 1 62 1 74 1 82 1 12 1 32 3 52 5 21 1 1002 1 31 8 302 4 22 2 4
Output014810013210
3 seconds
256 megabytes
['data structures', 'dfs and similar', 'trees', '*2100']
A. Binary Blockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisible by k, the image is padded with only zeros on the right and bottom so that they are divisible by k. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some k. More specifically, the steps are to first choose k, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this k. The image must be compressible in that state.InputThe first line of input will contain two integers n, m (2 ≀ n, m ≀ 2 500), the dimensions of the image.The next n lines of input will contain a binary string with exactly m characters, representing the image.OutputPrint a single integer, the minimum number of pixels needed to toggle to make the image compressible.ExampleInput3 5001001011011001Output5NoteWe first choose k = 2.The image is padded as follows: 001000101100110010000000We can toggle the image to look as follows: 001100001100000000000000We can see that this image is compressible for k = 2.
Input3 5001001011011001
Output5
2 seconds
256 megabytes
['brute force', '*1400']
G. Functions On The Segmentstime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou have an array f of n functions.The function fi(x) (1 ≀ i ≀ n) is characterized by parameters: x1, x2, y1, a, b, y2 and take values: y1, if x ≀ x1. aΒ·x + b, if x1 < x ≀ x2. y2, if x > x2. There are m queries. Each query is determined by numbers l, r and x. For a query with number i (1 ≀ i ≀ m), you need to calculate the sum of all fj(xi) where l ≀ j ≀ r. The value of xi is calculated as follows: xi = (x + last) mod 109, where last is the answer to the query with number i - 1. The value of last equals 0 if i = 1.InputFirst line contains one integer number n (1 ≀ n ≀ 75000).Each of the next n lines contains six integer numbers: x1, x2, y1, a, b, y2 (0 ≀ x1 < x2 ≀ 2Β·105, 0 ≀ y1, y2 ≀ 109, 0 ≀ a, b ≀ 104).Next line contains one integer number m (1 ≀ m ≀ 500000).Each of the next m lines contains three integer numbers: l, r and x (1 ≀ l ≀ r ≀ n, 0 ≀ x ≀ 109).ExamplesInput11 2 1 4 5 1011 1 2Output13Input32 5 1 1 1 43 6 8 2 5 71 3 5 1 4 1031 3 32 3 21 2 5Output191711
Input11 2 1 4 5 1011 1 2
Output13
5 seconds
1024 megabytes
['data structures', '*2500']
F. Prefix Sumstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that yi is equal to the sum of first i elements of array x (0 ≀ i ≀ m).You have an infinite sequence of arrays A0, A1, A2..., where A0 is given in the input, and for each i β‰₯ 1 Ai = p(Ai - 1). Also you have a positive integer k. You have to find minimum possible i such that Ai contains a number which is larger or equal than k.InputThe first line contains two integers n and k (2 ≀ n ≀ 200000, 1 ≀ k ≀ 1018). n is the size of array A0.The second line contains n integers A00, A01... A0n - 1 β€” the elements of A0 (0 ≀ A0i ≀ 109). At least two elements of A0 are positive.OutputPrint the minimum i such that Ai contains a number which is larger or equal than k.ExamplesInput2 21 1Output1Input3 61 1 1Output2Input3 11 0 1Output0
Input2 21 1
Output1
1 second
256 megabytes
['binary search', 'brute force', 'combinatorics', 'math', 'matrices', '*2400']
E. Vasya's Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is studying number theory. He has denoted a function f(a, b) such that: f(a, 0) = 0; f(a, b) = 1 + f(a, b - gcd(a, b)), where gcd(a, b) is the greatest common divisor of a and b. Vasya has two numbers x and y, and he wants to calculate f(x, y). He tried to do it by himself, but found out that calculating this function the way he wants to do that might take very long time. So he decided to ask you to implement a program that will calculate this function swiftly.InputThe first line contains two integer numbers x and y (1 ≀ x, y ≀ 1012).OutputPrint f(x, y).ExamplesInput3 5Output3Input6 3Output1
Input3 5
Output3
1 second
256 megabytes
['binary search', 'implementation', 'math', '*2100']
D. Round Subsettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call the roundness of the number the number of zeros to which it ends.You have an array of n numbers. You need to choose a subset of exactly k numbers so that the roundness of the product of the selected numbers will be maximum possible.InputThe first line contains two integer numbers n and k (1 ≀ n ≀ 200, 1 ≀ k ≀ n).The second line contains n space-separated integer numbers a1, a2, ..., an (1 ≀ ai ≀ 1018).OutputPrint maximal roundness of product of the chosen subset of length k.ExamplesInput3 250 4 20Output3Input5 315 16 3 25 9Output3Input3 39 77 13Output0NoteIn the first example there are 3 subsets of 2 numbers. [50, 4] has product 200 with roundness 2, [4, 20] β€” product 80, roundness 1, [50, 20] β€” product 1000, roundness 3.In the second example subset [15, 16, 25] has product 6000, roundness 3.In the third example all subsets has product with roundness 0.
Input3 250 4 20
Output3
2 seconds
256 megabytes
['dp', 'math', '*2100']
C. Two Sealstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne very important person has a piece of paper in the form of a rectangle a × b.Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi × yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?InputThe first line contains three integer numbers n, a and b (1 ≀ n, a, b ≀ 100).Each of the next n lines contain two numbers xi, yi (1 ≀ xi, yi ≀ 100).OutputPrint the largest total area that can be occupied by two seals. If you can not select two seals, print 0.ExamplesInput2 2 21 22 1Output4Input4 10 92 31 15 109 11Output56Input3 10 106 67 720 5Output0NoteIn the first example you can rotate the second seal by 90 degrees. Then put impression of it right under the impression of the first seal. This will occupy all the piece of paper.In the second example you can't choose the last seal because it doesn't fit. By choosing the first and the third seals you occupy the largest area.In the third example there is no such pair of seals that they both can fit on a piece of paper.
Input2 2 21 22 1
Output4
1 second
256 megabytes
['brute force', 'implementation', '*1500']
B. Flag of Berlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe flag of Berland is such rectangular field n × m that satisfies following conditions: Flag consists of three colors which correspond to letters 'R', 'G' and 'B'. Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color. Each color should be used in exactly one stripe. You are given a field n × m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).InputThe first line contains two integer numbers n and m (1 ≀ n, m ≀ 100) β€” the sizes of the field.Each of the following n lines consisting of m characters 'R', 'G' and 'B' β€” the description of the field.OutputPrint "YES" (without quotes) if the given field corresponds to correct flag of Berland . Otherwise, print "NO" (without quotes).ExamplesInput6 5RRRRRRRRRRBBBBBBBBBBGGGGGGGGGGOutputYESInput4 3BRGBRGBRGBRGOutputYESInput6 7RRRGGGGRRRGGGGRRRGGGGRRRBBBBRRRBBBBRRRBBBBOutputNOInput4 4RRRRRRRRBBBBGGGGOutputNONoteThe field in the third example doesn't have three parralel stripes.Rows of the field in the fourth example are parralel to each other and to borders. But they have different heights β€” 2, 1 and 1.
Input6 5RRRRRRRRRRBBBBBBBBBBGGGGGGGGGG
OutputYES
1 second
256 megabytes
['brute force', 'implementation', '*1600']
A. Text Volumetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a text of single-space separated words, consisting of small and capital Latin letters.Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.Calculate the volume of the given text.InputThe first line contains one integer number n (1 ≀ n ≀ 200) β€” length of the text.The second line contains text of single-space separated words s1, s2, ..., si, consisting only of small and capital Latin letters.OutputPrint one integer number β€” volume of text.ExamplesInput7NonZEROOutput5Input24this is zero answer textOutput0Input24Harbour Space UniversityOutput1NoteIn the first example there is only one word, there are 5 capital letters in it.In the second example all of the words contain 0 capital letters.
Input7NonZERO
Output5
1 second
256 megabytes
['implementation', '*800']
F. Roads in the Kingdomtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the Kingdom K., there are n towns numbered with integers from 1 to n. The towns are connected by n bi-directional roads numbered with integers from 1 to n. The i-th road connects the towns ui and vi and its length is li. There is no more than one road between two towns. Also, there are no roads that connect the towns with itself.Let's call the inconvenience of the roads the maximum of the shortest distances between all pairs of towns.Because of lack of money, it was decided to close down one of the roads so that after its removal it is still possible to reach any town from any other. You have to find the minimum possible inconvenience of the roads after closing down one of the roads.InputThe first line contains the integer n (3 ≀ n ≀ 2Β·105)Β β€” the number of towns and roads.The next n lines contain the roads description. The i-th from these lines contains three integers ui, vi, li (1 ≀ ui, vi ≀ n, 1 ≀ li ≀ 109)Β β€” the numbers of towns connected by the i-th road and the length of the i-th road. No road connects a town to itself, no two roads connect the same towns.It's guaranteed that it's always possible to close down one of the roads so that all the towns are still reachable from each other.OutputPrint a single integerΒ β€” the minimum possible inconvenience of the roads after the refusal from one of the roads.ExamplesInput31 2 42 3 51 3 1Output5Input52 3 73 1 94 1 83 5 44 5 5Output18
Input31 2 42 3 51 3 1
Output5
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'trees', '*2500']
E. The penguin's gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPay attention: this problem is interactive.Penguin Xoriy came up with a new game recently. He has n icicles numbered from 1 to n. Each icicle has a temperatureΒ β€” an integer from 1 to 109. Exactly two of these icicles are special: their temperature is y, while a temperature of all the others is x ≠ y. You have to find those special icicles. You can choose a non-empty subset of icicles and ask the penguin what is the bitwise exclusive OR (XOR) of the temperatures of the icicles in this subset. Note that you can't ask more than 19 questions.You are to find the special icicles.InputThe first line contains three integers n, x, y (2 ≀ n ≀ 1000, 1 ≀ x, y ≀ 109, x ≠ y)Β β€” the number of icicles, the temperature of non-special icicles and the temperature of the special icicles.OutputTo give your answer to the penguin you have to print character "!" (without quotes), then print two integers p1, p2 (p1 < p2)Β β€” the indexes of the special icicles in ascending order. Note that "!" and p1 should be separated by a space; the indexes should be separated by a space too. After you gave the answer your program should terminate immediately.InteractionTo ask a question print character "?" (without quotes), an integer c (1 ≀ c ≀ n), and c distinct integers p1, p2, ..., pc (1 ≀ pi ≀ n)Β β€” the indexes of icicles that you want to know about. Note that "?" and c should be separated by a space; the indexes should be separated by a space too.After you asked the question, read a single integerΒ β€” the answer.Note that you can't ask more than 19 questions. If you ask more than 19 questions or at least one incorrect question, your solution will get "Wrong answer".If at some moment your program reads  - 1 as an answer, it should immediately exit (for example, by calling exit(0)). You will get "Wrong answer" in this case, it means that you asked more than 19 questions, or asked an invalid question. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.Your solution will get "Idleness Limit Exceeded", if you don't print anything or forget to flush the output, including for the final answer .To flush you can use (just after printing): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; For other languages see the documentation. HackingFor hacking use the following format:n x y p1 p2Here 1 ≀ p1 < p2 ≀ n are the indexes of the special icicles.Contestant programs will not be able to see this input.ExampleInput4 2 1211Output? 3 1 2 3? 1 1? 1 3! 1 3NoteThe answer for the first question is .The answer for the second and the third questions is 1, therefore, special icicles are indexes 1 and 3.You can read more about bitwise XOR operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.
Input4 2 1211
Output? 3 1 2 3? 1 1? 1 3! 1 3
1 second
256 megabytes
['binary search', 'constructive algorithms', 'interactive', '*2400']
D. Palindromic characteristicstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPalindromic characteristics of string s with length |s| is a sequence of |s| integers, where k-th number is the total number of non-empty substrings of s which are k-palindromes.A string is 1-palindrome if and only if it reads the same backward as forward.A string is k-palindrome (k > 1) if and only if: Its left half equals to its right half. Its left and right halfs are non-empty (k - 1)-palindromes. The left half of string t is its prefix of length ⌊|t| / 2βŒ‹, and right halfΒ β€” the suffix of the same length. ⌊|t| / 2βŒ‹ denotes the length of string t divided by 2, rounded down.Note that each substring is counted as many times as it appears in the string. For example, in the string "aaa" the substring "a" appears 3 times.InputThe first line contains the string s (1 ≀ |s| ≀ 5000) consisting of lowercase English letters.OutputPrint |s| integersΒ β€” palindromic characteristics of string s.ExamplesInputabbaOutput6 1 0 0 InputabacabaOutput12 4 1 0 0 0 0 NoteIn the first example 1-palindromes are substring Β«aΒ», Β«bΒ», Β«bΒ», Β«aΒ», Β«bbΒ», Β«abbaΒ», the substring Β«bbΒ» is 2-palindrome. There are no 3- and 4-palindromes here.
Inputabba
Output6 1 0 0
3 seconds
256 megabytes
['brute force', 'dp', 'hashing', 'strings', '*1900']
C. Star skytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 ≀ si ≀ c).Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 ≀ c, and 0, otherwise.You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper rightΒ β€” (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.A star lies in a rectangle if it lies on its border or lies strictly inside it.InputThe first line contains three integers n, q, c (1 ≀ n, q ≀ 105, 1 ≀ c ≀ 10)Β β€” the number of the stars, the number of the views and the maximum brightness of the stars.The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 ≀ xi, yi ≀ 100, 0 ≀ si ≀ c ≀ 10)Β β€” the coordinates of i-th star and its initial brightness.The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 ≀ ti ≀ 109, 1 ≀ x1i < x2i ≀ 100, 1 ≀ y1i < y2i ≀ 100)Β β€” the moment of the i-th view and the coordinates of the viewed rectangle.OutputFor each view print the total brightness of the viewed stars.ExamplesInput2 3 31 1 13 2 02 1 1 2 20 2 1 4 55 1 1 5 5Output303Input3 4 51 1 22 3 03 3 10 1 1 100 1001 2 2 4 42 2 1 4 71 50 50 51 51Output3350NoteLet's consider the first example.At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
Input2 3 31 1 13 2 02 1 1 2 20 2 1 4 55 1 1 5 5
Output303
2 seconds
256 megabytes
['dp', 'implementation', '*1600']
B. The number on the boardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.InputThe first line contains integer k (1 ≀ k ≀ 109).The second line contains integer n (1 ≀ n < 10100000).There are no leading zeros in n. It's guaranteed that this situation is possible.OutputPrint the minimum number of digits in which the initial number and n can differ.ExamplesInput311Output1Input399Output0NoteIn the first example, the initial number could be 12.In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.
Input311
Output1
2 seconds
256 megabytes
['greedy', '*1100']
A. Key racestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 milliseconds.If connection ping (delay) is t milliseconds, the competition passes for a participant as follows: Exactly after t milliseconds after the start of the competition the participant receives the text to be entered. Right after that he starts to type it. Exactly t milliseconds after he ends typing all the text, the site receives information about it. The winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, it is considered that there is a draw.Given the length of the text and the information about participants, determine the result of the game.InputThe first line contains five integers s, v1, v2, t1, t2 (1 ≀ s, v1, v2, t1, t2 ≀ 1000)Β β€” the number of characters in the text, the time of typing one character for the first participant, the time of typing one character for the the second participant, the ping of the first participant and the ping of the second participant.OutputIf the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw print "Friendship".ExamplesInput5 1 2 1 2OutputFirstInput3 3 1 1 1OutputSecondInput4 5 3 1 5OutputFriendshipNoteIn the first example, information on the success of the first participant comes in 7 milliseconds, of the second participantΒ β€” in 14 milliseconds. So, the first wins.In the second example, information on the success of the first participant comes in 11 milliseconds, of the second participantΒ β€” in 5 milliseconds. So, the second wins.In the third example, information on the success of the first participant comes in 22 milliseconds, of the second participantΒ β€” in 22 milliseconds. So, it is be a draw.
Input5 1 2 1 2
OutputFirst
1 second
256 megabytes
['math', '*800']
B. The Festive Eveningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in.There are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. Because of security measures, each guest is known to be assigned an entrance he should enter the castle through. The door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest that should enter the castle through this entrance. No two guests can enter the castle simultaneously.For an entrance to be protected from possible intrusion, a candy guard should be assigned to it. There are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! Notice that a guard can't leave his post until the door he is assigned to is closed.Slastyona had a suspicion that there could be uninvited guests at the evening. She knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened.InputTwo integers are given in the first string: the number of guests n and the number of guards k (1 ≀ n ≀ 106, 1 ≀ k ≀ 26).In the second string, n uppercase English letters s1s2... sn are given, where si is the entrance used by the i-th guest.OutputOutput Β«YESΒ» if at least one door was unguarded during some time, and Β«NOΒ» otherwise.You can output each letter in arbitrary case (upper or lower).ExamplesInput5 1AABBBOutputNOInput5 1ABABBOutputYESNoteIn the first sample case, the door A is opened right before the first guest's arrival and closed when the second guest enters the castle. The door B is opened right before the arrival of the third guest, and closed after the fifth one arrives. One guard can handle both doors, as the first one is closed before the second one is opened.In the second sample case, the door B is opened before the second guest's arrival, but the only guard can't leave the door A unattended, as there is still one more guest that should enter the castle through this door.
Input5 1AABBB
OutputNO
1 second
256 megabytes
['data structures', 'implementation', '*1100']
A. The Useless Toytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption.Spinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one): After the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in.Slastyona managed to have spinner rotating for exactly n seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.InputThere are two characters in the first string – the starting and the ending position of a spinner. The position is encoded with one of the following characters: v (ASCII code 118, lowercase v), < (ASCII code 60), ^ (ASCII code 94) or > (ASCII code 62) (see the picture above for reference). Characters are separated by a single space.In the second strings, a single number n is given (0 ≀ n ≀ 109) – the duration of the rotation.It is guaranteed that the ending position of a spinner is a result of a n second spin in any of the directions, assuming the given starting position.OutputOutput cw, if the direction is clockwise, ccw – if counter-clockwise, and undefined otherwise.ExamplesInput^ >1OutputcwInput< ^3OutputccwInput^ v6Outputundefined
Input^ >1
Outputcw
1 second
256 megabytes
['implementation', '*900']
E. Caramel Cloudstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output It is well-known that the best decoration for a flower bed in Sweetland are vanilla muffins. Seedlings of this plant need sun to grow up. Slastyona has m seedlings, and the j-th seedling needs at least kj minutes of sunlight to grow up.Most of the time it's sunny in Sweetland, but sometimes some caramel clouds come, the i-th of which will appear at time moment (minute) li and disappear at time moment ri. Of course, the clouds make shadows, and the seedlings can't grow when there is at least one cloud veiling the sun.Slastyona wants to grow up her muffins as fast as possible. She has exactly C candies, which is the main currency in Sweetland. One can dispel any cloud by paying ci candies. However, in order to comply with Sweetland's Department of Meteorology regulations, one can't dispel more than two clouds.Slastyona hasn't decided yet which of the m seedlings will be planted at the princess' garden, so she needs your help. For each seedling determine the earliest moment it can grow up if Slastyona won't break the law and won't spend more candies than she has. Note that each of the seedlings is considered independently.The seedlings start to grow at time moment 0.InputThe first line contains two integers n and C (0 ≀ n ≀ 3Β·105, 0 ≀ C ≀ 109) – the number of caramel clouds and the number of candies Slastyona has.The next n lines contain three integers each: li, ri, ci (0 ≀ li < ri ≀ 109, 0 ≀ ci ≀ 109), describing one caramel cloud.The next line contains single integer m (1 ≀ m ≀ 3Β·105) – the number of seedlings. Each of the seedlings is described with one integer kj (1 ≀ kj ≀ 109) – the required number of sunny minutes.OutputFor each seedling print one integer – the minimum minute Slastyona can grow it up.ExamplesInput3 51 7 11 6 21 7 13725Output12710Input3 151 4 172 8 64 8 9251Output81Input2 103 7 910 90 10210100Output10104NoteConsider the first example. For each k it is optimal to dispel clouds 1 and 3. Then the remaining cloud will give shadow on time segment [1..6]. So, intervals [0..1] and [6..inf) are sunny. In the second example for k = 1 it is not necessary to dispel anything, and for k = 5 the best strategy is to dispel clouds 2 and 3. This adds an additional sunny segment [4..8], which together with [0..1] allows to grow up the muffin at the eight minute. If the third example the two seedlings are completely different. For the first one it is necessary to dispel cloud 1 and obtain a sunny segment [0..10]. However, the same strategy gives answer 180 for the second seedling. Instead, we can dispel cloud 2, to make segments [0..3] and [7..inf) sunny, and this allows up to shorten the time to 104.
Input3 51 7 11 6 21 7 13725
Output12710
3 seconds
256 megabytes
['data structures', 'dp', 'sortings', '*3400']
D. Red-Black Cobwebtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Slastyona likes to watch life of nearby grove's dwellers. This time she watches a strange red-black spider sitting at the center of a huge cobweb.The cobweb is a set of n nodes connected by threads, each of the treads is either red of black. Using these threads, the spider can move between nodes. No thread connects a node to itself, and between any two nodes there is a unique sequence of threads connecting them.Slastyona decided to study some special qualities of the cobweb. She noticed that each of the threads has a value of clamminess x.However, Slastyona is mostly interested in jelliness of the cobweb. Consider those of the shortest paths between each pair of nodes on which the numbers of red and black threads differ at most twice. For each such path compute the product of the clamminess of threads on the path.The jelliness of the cobweb is the product of all obtained values among all paths. Those paths that differ by direction only are counted only once.Of course, this number can be huge, so Slastyona asks you to compute the jelliness of the given cobweb and print the answer modulo 109 + 7.InputThe first line contains the number of nodes n (2 ≀ n ≀ 105).The next n - 1 lines contain four integers each, denoting the i-th thread of the cobweb: the nodes it connects ui, vi (1 ≀ ui ≀ n, 1 ≀ vi ≀ n), the clamminess of the thread xi (1 ≀ x ≀ 109 + 6), and the color of the thread ci (). The red color is denoted by 0, and the black color is denoted by 1. OutputPrint single integer the jelliness of the cobweb modulo 109 + 7. If there are no paths such that the numbers of red and black threads differ at most twice, print 1.ExamplesInput51 2 9 02 3 5 12 4 5 02 5 5 1Output1265625Input81 2 7 12 3 4 13 4 19 15 1 2 06 2 3 07 3 3 08 4 4 0Output452841614NoteIn the first example there are 4 pairs of nodes such that the numbers of threads of both colors on them differ at most twice. There pairs are (1, 3) with product of clamminess equal to 45, (1, 5) with product of clamminess equal to 45, (3, 4) with product of clamminess equal to 25 and (4, 5) with product of clamminess equal to 25. The jelliness of the cobweb is equal to 1265625.
Input51 2 9 02 3 5 12 4 5 02 5 5 1
Output1265625
6 seconds
256 megabytes
['data structures', 'divide and conquer', 'implementation', 'trees', '*2800']
C. Ever-Hungry Krakozyabratime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output Recently, a wild Krakozyabra appeared at Jelly Castle. It is, truth to be said, always eager to have something for dinner.Its favorite meal is natural numbers (typically served with honey sauce), or, to be more precise, the zeros in their corresponding decimal representations. As for other digits, Krakozyabra dislikes them; moreover, they often cause it indigestion! So, as a necessary precaution, Krakozyabra prefers to sort the digits of a number in non-descending order before proceeding to feast. Then, the leading zeros of the resulting number are eaten and the remaining part is discarded as an inedible tail.For example, if Krakozyabra is to have the number 57040 for dinner, its inedible tail would be the number 457.Slastyona is not really fond of the idea of Krakozyabra living in her castle. Hovewer, her natural hospitality prevents her from leaving her guest without food. Slastyona has a range of natural numbers from L to R, which she is going to feed the guest with. Help her determine how many distinct inedible tails are going to be discarded by Krakozyabra by the end of the dinner.InputIn the first and only string, the numbers L and R are given – the boundaries of the range (1 ≀ L ≀ R ≀ 1018).OutputOutput the sole number – the answer for the problem.ExamplesInput1 10Output9Input40 57Output17Input157 165Output9NoteIn the first sample case, the inedible tails are the numbers from 1 to 9. Note that 10 and 1 have the same inedible tail – the number 1.In the second sample case, each number has a unique inedible tail, except for the pair 45, 54. The answer to this sample case is going to be (57 - 40 + 1) - 1 = 17.
Input1 10
Output9
1 second
256 megabytes
['brute force', 'combinatorics', 'greedy', 'math', '*2700']
B. The Bakerytime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it's profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let's denote this number as the value of the box), the higher price it has.She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can't affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.InputThe first line contains two integers n and k (1 ≀ n ≀ 35000, 1 ≀ k ≀ min(n, 50)) – the number of cakes and the number of boxes, respectively.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ n) – the types of cakes in the order the oven bakes them.OutputPrint the only integer – the maximum total value of all boxes with cakes.ExamplesInput4 11 2 2 1Output2Input7 21 3 3 1 4 4 4Output5Input8 37 7 8 7 7 8 1 7Output6NoteIn the first example Slastyona has only one box. She has to put all cakes in it, so that there are two types of cakes in the box, so the value is equal to 2.In the second example it is profitable to put the first two cakes in the first box, and all the rest in the second. There are two distinct types in the first box, and three in the second box then, so the total value is 5.
Input4 11 2 2 1
Output2
2.5 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'dp', 'two pointers', '*2200']
A. The Meaningless Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.InputIn the first string, the number of games n (1 ≀ n ≀ 350000) is given.Each game is represented by a pair of scores a, b (1 ≀ a, b ≀ 109) – the results of Slastyona and Pushok, correspondingly.OutputFor each pair of scores, answer "Yes" if it's possible for a game to finish with given score, and "No" otherwise.You can output each letter in arbitrary case (upper or lower).ExampleInput62 475 458 816 16247 9941000000000 1000000OutputYesYesYesNoNoYesNoteFirst game might have been consisted of one round, in which the number 2 would have been chosen and Pushok would have won.The second game needs exactly two rounds to finish with such result: in the first one, Slastyona would have said the number 5, and in the second one, Pushok would have barked the number 3.
Input62 475 458 816 16247 9941000000000 1000000
OutputYesYesYesNoNoYes
1 second
256 megabytes
['math', 'number theory', '*1700']
E. Vasya and Shiftstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a set of 4n strings of equal length, consisting of lowercase English letters "a", "b", "c", "d" and "e". Moreover, the set is split into n groups of 4 equal strings each. Vasya also has one special string a of the same length, consisting of letters "a" only.Vasya wants to obtain from string a some fixed string b, in order to do this, he can use the strings from his set in any order. When he uses some string x, each of the letters in string a replaces with the next letter in alphabet as many times as the alphabet position, counting from zero, of the corresponding letter in string x. Within this process the next letter in alphabet after "e" is "a".For example, if some letter in a equals "b", and the letter on the same position in x equals "c", then the letter in a becomes equal "d", because "c" is the second alphabet letter, counting from zero. If some letter in a equals "e", and on the same position in x is "d", then the letter in a becomes "c". For example, if the string a equals "abcde", and string x equals "baddc", then a becomes "bbabb".A used string disappears, but Vasya can use equal strings several times.Vasya wants to know for q given strings b, how many ways there are to obtain from the string a string b using the given set of 4n strings? Two ways are different if the number of strings used from some group of 4 strings is different. Help Vasya compute the answers for these questions modulo 109 + 7.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 500)Β β€” the number of groups of four strings in the set, and the length of all strings.Each of the next n lines contains a string s of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e". This means that there is a group of four strings equal to s.The next line contains single integer q (1 ≀ q ≀ 300)Β β€” the number of strings b Vasya is interested in.Each of the next q strings contains a string b of length m, consisting of lowercase English letters "a", "b", "c", "d" and "e"Β β€” a string Vasya is interested in.OutputFor each string Vasya is interested in print the number of ways to obtain it from string a, modulo 109 + 7.ExamplesInput1 1b2aeOutput11Input2 4aaaabbbb1ccccOutput5NoteIn the first example, we have 4 strings "b". Then we have the only way for each string b: select 0 strings "b" to get "a" and select 4 strings "b" to get "e", respectively. So, we have 1 way for each request.In the second example, note that the choice of the string "aaaa" does not change anything, that is we can choose any amount of it (from 0 to 4, it's 5 different ways) and we have to select the line "bbbb" 2 times, since other variants do not fit. We get that we have 5 ways for the request.
Input1 1b2ae
Output11
2 seconds
256 megabytes
['matrices', '*2600']
D. Misha, Grisha and Undergroundtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisha and Grisha are funny boys, so they like to use new underground. The underground has n stations connected with n - 1 routes so that each route connects two stations, and it is possible to reach every station from any other.The boys decided to have fun and came up with a plan. Namely, in some day in the morning Misha will ride the underground from station s to station f by the shortest path, and will draw with aerosol an ugly text "Misha was here" on every station he will pass through (including s and f). After that on the same day at evening Grisha will ride from station t to station f by the shortest path and will count stations with Misha's text. After that at night the underground workers will wash the texts out, because the underground should be clean. The boys have already chosen three stations a, b and c for each of several following days, one of them should be station s on that day, another should be station f, and the remaining should be station t. They became interested how they should choose these stations s, f, t so that the number Grisha will count is as large as possible. They asked you for help.InputThe first line contains two integers n and q (2 ≀ n ≀ 105, 1 ≀ q ≀ 105)Β β€” the number of stations and the number of days.The second line contains n - 1 integers p2, p3, ..., pn (1 ≀ pi ≀ n). The integer pi means that there is a route between stations pi and i. It is guaranteed that it's possible to reach every station from any other.The next q lines contains three integers a, b and c each (1 ≀ a, b, c ≀ n)Β β€” the ids of stations chosen by boys for some day. Note that some of these ids could be same.OutputPrint q lines. In the i-th of these lines print the maximum possible number Grisha can get counting when the stations s, t and f are chosen optimally from the three stations on the i-th day.ExamplesInput3 21 11 2 32 3 3Output23Input4 11 2 31 2 3Output2NoteIn the first example on the first day if s = 1, f = 2, t = 3, Misha would go on the route 1 2, and Grisha would go on the route 3 1 2. He would see the text at the stations 1 and 2. On the second day, if s = 3, f = 2, t = 3, both boys would go on the route 3 1 2. Grisha would see the text at 3 stations.In the second examle if s = 1, f = 3, t = 2, Misha would go on the route 1 2 3, and Grisha would go on the route 2 3 and would see the text at both stations.
Input3 21 11 2 32 3 3
Output23
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*1900']
C. Strange Radiationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed.You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people will start running with their maximum speed in the direction they are facing. Also, two strange rays will start propagating from the bomb with speed s: one to the right, and one to the left. Of course, the speed s is strictly greater than people's maximum speed.The rays are strange because if at any moment the position and the direction of movement of some ray and some person coincide, then the speed of the person immediately increases by the speed of the ray.You need to place the bomb is such a point that the minimum time moment in which there is a person that has run through point 0, and there is a person that has run through point 106, is as small as possible. In other words, find the minimum time moment t such that there is a point you can place the bomb to so that at time moment t some person has run through 0, and some person has run through point 106.InputThe first line contains two integers n and s (2 ≀ n ≀ 105, 2 ≀ s ≀ 106)Β β€” the number of people and the rays' speed.The next n lines contain the description of people. The i-th of these lines contains three integers xi, vi and ti (0 < xi < 106, 1 ≀ vi < s, 1 ≀ ti ≀ 2)Β β€” the coordinate of the i-th person on the line, his maximum speed and the direction he will run to (1 is to the left, i.e. in the direction of coordinate decrease, 2 is to the right, i.e. in the direction of coordinate increase), respectively.It is guaranteed that the points 0 and 106 will be reached independently of the bomb's position.OutputPrint the minimum time needed for both points 0 and 106 to be reached.Your answer is considered correct if its absolute or relative error doesn't exceed 10 - 6. Namely, if your answer is a, and the jury's answer is b, then your answer is accepted, if .ExamplesInput2 999400000 1 2500000 1 1Output500000.000000000000000000000000000000Input2 1000400000 500 1600000 500 2Output400.000000000000000000000000000000NoteIn the first example, it is optimal to place the bomb at a point with a coordinate of 400000. Then at time 0, the speed of the first person becomes 1000 and he reaches the point 106 at the time 600. The bomb will not affect on the second person, and he will reach the 0 point at the time 500000.In the second example, it is optimal to place the bomb at the point 500000. The rays will catch up with both people at the time 200. At this time moment, the first is at the point with a coordinate of 300000, and the second is at the point with a coordinate of 700000. Their speed will become 1500 and at the time 400 they will simultaneously run through points 0 and 106.
Input2 999400000 1 2500000 1 1
Output500000.000000000000000000000000000000
3 seconds
256 megabytes
['binary search', 'implementation', 'math', '*2500']
B. Petya and Examtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's hard times now. Today Petya needs to score 100 points on Informatics exam. The tasks seem easy to Petya, but he thinks he lacks time to finish them all, so he asks you to help with one..There is a glob pattern in the statements (a string consisting of lowercase English letters, characters "?" and "*"). It is known that character "*" occurs no more than once in the pattern.Also, n query strings are given, it is required to determine for each of them if the pattern matches it or not.Everything seemed easy to Petya, but then he discovered that the special pattern characters differ from their usual meaning.A pattern matches a string if it is possible to replace each character "?" with one good lowercase English letter, and the character "*" (if there is one) with any, including empty, string of bad lowercase English letters, so that the resulting string is the same as the given string.The good letters are given to Petya. All the others are bad.InputThe first line contains a string with length from 1 to 26 consisting of distinct lowercase English letters. These letters are good letters, all the others are bad.The second line contains the patternΒ β€” a string s of lowercase English letters, characters "?" and "*" (1 ≀ |s| ≀ 105). It is guaranteed that character "*" occurs in s no more than once.The third line contains integer n (1 ≀ n ≀ 105)Β β€” the number of query strings.n lines follow, each of them contains single non-empty string consisting of lowercase English lettersΒ β€” a query string.It is guaranteed that the total length of all query strings is not greater than 105.OutputPrint n lines: in the i-th of them print "YES" if the pattern matches the i-th query string, and "NO" otherwise.You can choose the case (lower or upper) for each letter arbitrary.ExamplesInputaba?a2aaaaabOutputYESNOInputabca?a?a*4abacabaabacaapapaaaaaaxOutputNOYESNOYESNoteIn the first example we can replace "?" with good letters "a" and "b", so we can see that the answer for the first query is "YES", and the answer for the second query is "NO", because we can't match the third letter.Explanation of the second example. The first query: "NO", because character "*" can be replaced with a string of bad letters only, but the only way to match the query string is to replace it with the string "ba", in which both letters are good. The second query: "YES", because characters "?" can be replaced with corresponding good letters, and character "*" can be replaced with empty string, and the strings will coincide. The third query: "NO", because characters "?" can't be replaced with bad letters. The fourth query: "YES", because characters "?" can be replaced with good letters "a", and character "*" can be replaced with a string of bad letters "x".
Inputaba?a2aaaaab
OutputYESNO
2 seconds
256 megabytes
['implementation', 'strings', '*1600']
A. Sasha and Stickstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. After that the players take turns crossing out exactly k sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than k sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.InputThe first line contains two integers n and k (1 ≀ n, k ≀ 1018, k ≀ n)Β β€” the number of sticks drawn by Sasha and the number kΒ β€” the number of sticks to be crossed out on each turn.OutputIf Sasha wins, print "YES" (without quotes), otherwise print "NO" (without quotes).You can print each letter in arbitrary case (upper of lower).ExamplesInput1 1OutputYESInput10 4OutputNONoteIn the first example Sasha crosses out 1 stick, and then there are no sticks. So Lena can't make a move, and Sasha wins.In the second example Sasha crosses out 4 sticks, then Lena crosses out 4 sticks, and after that there are only 2 sticks left. Sasha can't make a move. The players make equal number of moves, so Sasha doesn't win.
Input1 1
OutputYES
2 seconds
256 megabytes
['games', 'math', '*800']
C. Jury Markstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i.Β e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n ≀ k) values b1, b2, ..., bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i.Β e. n < k. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant.InputThe first line contains two integers k and n (1 ≀ n ≀ k ≀ 2 000) β€” the number of jury members and the number of scores Polycarp remembers.The second line contains k integers a1, a2, ..., ak ( - 2 000 ≀ ai ≀ 2 000) β€” jury's marks in chronological order.The third line contains n distinct integers b1, b2, ..., bn ( - 4 000 000 ≀ bj ≀ 4 000 000) β€” the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.OutputPrint the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes).ExamplesInput4 1-5 5 0 2010Output3Input2 2-2000 -20003998000 4000000Output1NoteThe answer for the first example is 3 because initially the participant could have  - 10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4 002 000.
Input4 1-5 5 0 2010
Output3
2 seconds
256 megabytes
['brute force', 'constructive algorithms', '*1700']
B. Keyboard Layoutstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order. You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.InputThe first line contains a string of length 26 consisting of distinct lowercase English letters. This is the first layout.The second line contains a string of length 26 consisting of distinct lowercase English letters. This is the second layout.The third line contains a non-empty string s consisting of lowercase and uppercase English letters and digits. This is the text typed in the first layout. The length of s does not exceed 1000.OutputPrint the text if the same keys were pressed in the second layout.ExamplesInputqwertyuiopasdfghjklzxcvbnmveamhjsgqocnrbfxdtwkylupziTwccpQZAvb2017OutputHelloVKCup2017Inputmnbvcxzlkjhgfdsapoiuytrewqasdfghjklqwertyuiopzxcvbnm7abaCABAABAcaba7Output7uduGUDUUDUgudu7
InputqwertyuiopasdfghjklzxcvbnmveamhjsgqocnrbfxdtwkylupziTwccpQZAvb2017
OutputHelloVKCup2017
1 second
256 megabytes
['implementation', 'strings', '*800']
A. Unimodal Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArray of integers is unimodal, if: it is strictly increasing in the beginning; after that it is constant; after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent.For example, the following three arrays are unimodal: [5, 7, 11, 11, 2, 1], [4, 4, 2], [7], but the following three are not unimodal: [5, 5, 6, 6, 1], [1, 2, 1, 2], [4, 5, 5, 6].Write a program that checks if an array is unimodal.InputThe first line contains integer n (1 ≀ n ≀ 100) β€” the number of elements in the array.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 1 000) β€” the elements of the array.OutputPrint "YES" if the given array is unimodal. Otherwise, print "NO".You can output each letter in any case (upper or lower).ExamplesInput61 5 5 5 4 2OutputYESInput510 20 30 20 10OutputYESInput41 2 1 2OutputNOInput73 3 3 3 3 3 3OutputYESNoteIn the first example the array is unimodal, because it is strictly increasing in the beginning (from position 1 to position 2, inclusively), that it is constant (from position 2 to position 4, inclusively) and then it is strictly decreasing (from position 4 to position 6, inclusively).
Input61 5 5 5 4 2
OutputYES
1 second
256 megabytes
['implementation', '*1000']
E. Perpetual Motion Machinetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDeveloper Petr thinks that he invented a perpetual motion machine. Namely, he has a lot of elements, which work in the following way.Each element has one controller that can be set to any non-negative real value. If a controller is set on some value x, then the controller consumes x2 energy units per second. At the same time, any two elements connected by a wire produce yΒ·z energy units per second, where y and z are the values set on their controllers.Petr has only a limited number of wires, so he has already built some scheme of elements and wires, and is now interested if it's possible to set the controllers in such a way that the system produces at least as much power as it consumes, and at least one controller is set on the value different from 0. Help him check this, and if it's possible, find the required integer values that should be set.It is guaranteed that if there exist controllers' settings satisfying the above conditions, then there exist required integer values not greater than 106.InputThere are several (at least one) test cases in the input. The first line contains single integerΒ β€” the number of test cases.There is an empty line before each test case. The first line of test case contains two integers n and m (1 ≀ n ≀ 105, 0 ≀ m ≀ 105)Β β€” the number of elements in the scheme and the number of wires.After that, m lines follow, each of them contains two integers a and b (1 ≀ a, b ≀ n)Β β€” two elements connected by a wire. No element is connected with itself, no two elements are connected by more than one wire.It is guaranteed that the sum of n and the sum of m over all test cases do not exceed 105.For hacks you can only use tests with one test case.OutputPrint answer for each test case.For each test case print "YES" if it's possible to set the controllers in such a way that the consumed power is not greater than the power produced, and the required values on the next line. The settings should be integers from 0 to 106, inclusive, and at least one value should be different from 0. If there are multiple answers, print any of them.If it's not possible to set the controllers in the required way, print one line "NO".ExampleInput4Β 4 41 22 33 44 2Β 3 22 33 1Β 4 61 23 44 21 41 33 2Β 10 92 13 25 26 22 72 82 92 104 2OutputYES1 2 2 1NOYES1 1 1 1YES1 5 1 1 1 1 1 1 1 1NoteIn the first example it's possible to set the controllers in the required way, for example, in the following way: set 1 on the first element, set 2 on the second and on the third, set 1 on the fourth. The consumed power is then equal to 12 + 22 + 22 + 12 = 10 energy units per second, the produced power is equal to 1Β·2 + 2Β·2 + 2Β·1 + 2Β·1 = 10 energy units per second. Thus the answer is "YES".In the second test case it's not possible to set the controllers in the required way. For example, if we set all controllers to 0.5, then the consumed powers equals 0.75 energy units per second, while produced power equals 0.5 energy units per second.
Input4Β 4 41 22 33 44 2Β 3 22 33 1Β 4 61 23 44 21 41 33 2Β 10 92 13 25 26 22 72 82 92 104 2
OutputYES1 2 2 1NOYES1 1 1 1YES1 5 1 1 1 1 1 1 1 1
2 seconds
512 megabytes
['constructive algorithms', 'dp', 'graphs', 'implementation', 'math', 'trees', '*3100']
D. Singer Housetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt is known that passages in Singer house are complex and intertwined. Let's define a Singer k-house as a graph built by the following process: take complete binary tree of height k and add edges from each vertex to all its successors, if they are not yet present. Singer 4-house Count the number of non-empty paths in Singer k-house which do not pass the same vertex twice. Two paths are distinct if the sets or the orders of visited vertices are different. Since the answer can be large, output it modulo 109 + 7.InputThe only line contains single integer k (1 ≀ k ≀ 400).OutputPrint single integerΒ β€” the answer for the task modulo 109 + 7.ExamplesInput2Output9Input3Output245Input20Output550384565NoteThere are 9 paths in the first example (the vertices are numbered on the picture below): 1, 2, 3, 1-2, 2-1, 1-3, 3-1, 2-1-3, 3-1-2. Singer 2-house
Input2
Output9
2 seconds
512 megabytes
['combinatorics', 'dp', 'graphs', 'trees', '*2800']
C. Bamboo Partitiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVladimir wants to modernize partitions in his office. To make the office more comfortable he decided to remove a partition and plant several bamboos in a row. He thinks it would be nice if there are n bamboos in a row, and the i-th from the left is ai meters high. Vladimir has just planted n bamboos in a row, each of which has height 0 meters right now, but they grow 1 meter each day. In order to make the partition nice Vladimir can cut each bamboo once at any height (no greater that the height of the bamboo), and then the bamboo will stop growing.Vladimir wants to check the bamboos each d days (i.e. d days after he planted, then after 2d days and so on), and cut the bamboos that reached the required height. Vladimir wants the total length of bamboo parts he will cut off to be no greater than k meters.What is the maximum value d he can choose so that he can achieve what he wants without cutting off more than k meters of bamboo?InputThe first line contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1011)Β β€” the number of bamboos and the maximum total length of cut parts, in meters.The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109)Β β€” the required heights of bamboos, in meters.OutputPrint a single integerΒ β€” the maximum value of d such that Vladimir can reach his goal.ExamplesInput3 41 3 5Output3Input3 4010 30 50Output32NoteIn the first example Vladimir can check bamboos each 3 days. Then he will cut the first and the second bamboos after 3 days, and the third bamboo after 6 days. The total length of cut parts is 2 + 0 + 1 = 3 meters.
Input3 41 3 5
Output3
2 seconds
512 megabytes
['brute force', 'data structures', 'implementation', 'math', 'number theory', 'sortings', 'two pointers', '*2300']
B. Cards Sortingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.You are to determine the total number of times Vasily takes the top card from the deck.InputThe first line contains single integer n (1 ≀ n ≀ 100 000) β€” the number of cards in the deck.The second line contains a sequence of n integers a1, a2, ..., an (1 ≀ ai ≀ 100 000), where ai is the number written on the i-th from top card in the deck.OutputPrint the total number of times Vasily takes the top card from the deck.ExamplesInput46 3 1 2Output7Input11000Output1Input73 3 3 3 3 3 3Output7NoteIn the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards.
Input46 3 1 2
Output7
1 second
256 megabytes
['data structures', 'implementation', 'sortings', '*1600']
A. Office Keystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else.You are to determine the minimum time needed for all n people to get to the office with keys. Assume that people move a unit distance per 1 second. If two people reach a key at the same time, only one of them can take the key. A person can pass through a point with a key without taking it.InputThe first line contains three integers n, k and p (1 ≀ n ≀ 1 000, n ≀ k ≀ 2 000, 1 ≀ p ≀ 109) β€” the number of people, the number of keys and the office location.The second line contains n distinct integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” positions in which people are located initially. The positions are given in arbitrary order.The third line contains k distinct integers b1, b2, ..., bk (1 ≀ bj ≀ 109) β€” positions of the keys. The positions are given in arbitrary order.Note that there can't be more than one person or more than one key in the same point. A person and a key can be located in the same point.OutputPrint the minimum time (in seconds) needed for all n to reach the office with keys.ExamplesInput2 4 5020 10060 10 40 80Output50Input1 2 101115 7Output7NoteIn the first example the person located at point 20 should take the key located at point 40 and go with it to the office located at point 50. He spends 30 seconds. The person located at point 100 can take the key located at point 80 and go to the office with it. He spends 50 seconds. Thus, after 50 seconds everybody is in office with keys.
Input2 4 5020 10060 10 40 80
Output50
2 seconds
256 megabytes
['binary search', 'brute force', 'dp', 'greedy', 'sortings', '*1800']
B. Black Squaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 100) β€” the sizes of the sheet.The next n lines contain m letters 'B' or 'W' each β€” the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white.OutputPrint the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1.ExamplesInput5 4WWWWWWWBWWWBWWBBWWWWOutput5Input1 2BBOutput-1Input3 3WWWWWWWWWOutput1NoteIn the first example it is needed to paint 5 cells β€” (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black.
Input5 4WWWWWWWBWWWBWWBBWWWW
Output5
1 second
256 megabytes
['implementation', '*1300']
A. Restaurant Tablestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a small restaurant there are a tables for one person and b tables for two persons. It it known that n groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person. If there are still none of them, the restaurant denies service to this group.If a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.You are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.InputThe first line contains three integers n, a and b (1 ≀ n ≀ 2Β·105, 1 ≀ a, b ≀ 2Β·105) β€” the number of groups coming to the restaurant, the number of one-seater and the number of two-seater tables.The second line contains a sequence of integers t1, t2, ..., tn (1 ≀ ti ≀ 2) β€” the description of clients in chronological order. If ti is equal to one, then the i-th group consists of one person, otherwise the i-th group consists of two people.OutputPrint the total number of people the restaurant denies service to.ExamplesInput4 1 21 2 1 1Output0Input4 1 11 1 2 1Output2NoteIn the first example the first group consists of one person, it is seated at a vacant one-seater table. The next group occupies a whole two-seater table. The third group consists of one person, it occupies one place at the remaining two-seater table. The fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, all clients are served.In the second example the first group consists of one person, it is seated at the vacant one-seater table. The next group consists of one person, it occupies one place at the two-seater table. It's impossible to seat the next group of two people, so the restaurant denies service to them. The fourth group consists of one person, he is seated at the remaining seat at the two-seater table. Thus, the restaurant denies service to 2 clients.
Input4 1 21 2 1 1
Output0
1 second
256 megabytes
['implementation', '*1200']
F. Dirty Arkady's Kitchentime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputArkady likes to walk around his kitchen. His labyrinthine kitchen consists of several important places connected with passages. Unfortunately it happens that these passages are flooded with milk so that it's impossible to pass through them. Namely, it's possible to pass through each passage in any direction only during some time interval.The lengths of all passages are equal and Arkady makes through them in one second. For security reasons, Arkady can never stop, also, he can't change direction while going through a passage. In other words, if he starts walking in some passage, he should reach its end and immediately leave the end.Today Arkady needs to quickly reach important place n from place 1. He plans to exit the place 1 at time moment 0 and reach the place n as early as he can. Please find the minimum time he should spend on his way.InputThe first line contains two integers n and m (1 ≀ n ≀ 5Β·105, 0 ≀ m ≀ 5Β·105)Β β€” the number of important places and the number of passages, respectively.After that, m lines follow, each of them describe one passage. Each line contains four integers a, b, l and r (1 ≀ a, b ≀ n, a ≠ b, 0 ≀ l < r ≀ 109)Β β€” the places the passage connects and the time segment during which it's possible to use this passage.OutputPrint one integerΒ β€” minimum time Arkady should spend to reach the destination. If he can't reach the place n, print -1.ExamplesInput5 61 2 0 12 5 2 32 5 0 11 3 0 13 4 1 24 5 2 3Output3Input2 11 2 1 100Output-1NoteIn the first example Arkady should go through important places 1 → 3 → 4 → 5.In the second example Arkady can't start his walk because at time moment 0 it's impossible to use the only passage.
Input5 61 2 0 12 5 2 32 5 0 11 3 0 13 4 1 24 5 2 3
Output3
6 seconds
512 megabytes
['data structures', 'dp', 'graphs', 'shortest paths', '*3200']
E. Rusty Stringtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGrigory loves strings. Recently he found a metal strip on a loft. The strip had length n and consisted of letters "V" and "K". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written.Grigory couldn't understand for a long time what these letters remind him of, so he became interested in the following question: if we put a letter "V" or "K" on each unreadable position, which values can the period of the resulting string be equal to?A period of a string is such an integer d from 1 to the length of the string that if we put the string shifted by d positions to the right on itself, then all overlapping letters coincide. For example, 3 and 5 are periods of "VKKVK".InputThere are several (at least one) test cases in the input. The first line contains single integerΒ β€” the number of test cases.There is an empty line before each test case. Each test case is described in two lines: the first line contains single integer n (1 ≀ n ≀ 5Β·105)Β β€” the length of the string, the second line contains the string of length n, consisting of letters "V", "K" and characters "?". The latter means the letter on its position is unreadable.It is guaranteed that the sum of lengths among all test cases doesn't exceed 5Β·105.For hacks you can only use tests with one test case.OutputFor each test case print two lines. In the first line print the number of possible periods after we replace each unreadable letter with "V" or "K". In the next line print all these values in increasing order.ExampleInput3Β 5V??VKΒ 6??????Β 4?VK?Output23 561 2 3 4 5 632 3 4NoteIn the first test case from example we can obtain, for example, "VKKVK", which has periods 3 and 5.In the second test case we can obtain "VVVVVV" which has all periods from 1 to 6.In the third test case string "KVKV" has periods 2 and 4, and string "KVKK" has periods 3 and 4.
Input3Β 5V??VKΒ 6??????Β 4?VK?
Output23 561 2 3 4 5 632 3 4
3 seconds
512 megabytes
['fft', 'math', 'strings', '*2700']
D. Best Edge Weighttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a connected weighted graph with n vertices and m edges. The graph doesn't contain loops nor multiple edges. Consider some edge with id i. Let's determine for this edge the maximum integer weight we can give to it so that it is contained in all minimum spanning trees of the graph if we don't change the other weights.You are to determine this maximum weight described above for each edge. You should calculate the answer for each edge independently, it means there can't be two edges with changed weights at the same time.InputThe first line contains two integers n and m (2 ≀ n ≀ 2Β·105, n - 1 ≀ m ≀ 2Β·105), where n and m are the number of vertices and the number of edges in the graph, respectively.Each of the next m lines contains three integers u, v and c (1 ≀ v, u ≀ n, v ≠ u, 1 ≀ c ≀ 109) meaning that there is an edge between vertices u and v with weight c. OutputPrint the answer for each edge in the order the edges are given in the input. If an edge is contained in every minimum spanning tree with any weight, print -1 as the answer.ExamplesInput4 41 2 22 3 23 4 24 1 3Output2 2 2 1 Input4 31 2 22 3 23 4 2Output-1 -1 -1
Input4 41 2 22 3 23 4 24 1 3
Output2 2 2 1
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'trees', '*2700']
C. DNA Evolutiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEveryone knows that DNA strands consist of nucleotides. There are four types of nucleotides: "A", "T", "G", "C". A DNA strand is a sequence of nucleotides. Scientists decided to track evolution of a rare species, which DNA strand was string s initially. Evolution of the species is described as a sequence of changes in the DNA. Every change is a change of some nucleotide, for example, the following change can happen in DNA strand "AAGC": the second nucleotide can change to "T" so that the resulting DNA strand is "ATGC".Scientists know that some segments of the DNA strand can be affected by some unknown infections. They can represent an infection as a sequence of nucleotides. Scientists are interested if there are any changes caused by some infections. Thus they sometimes want to know the value of impact of some infection to some segment of the DNA. This value is computed as follows: Let the infection be represented as a string e, and let scientists be interested in DNA strand segment starting from position l to position r, inclusive. Prefix of the string eee... (i.e. the string that consists of infinitely many repeats of string e) is written under the string s from position l to position r, inclusive. The value of impact is the number of positions where letter of string s coincided with the letter written under it. Being a developer, Innokenty is interested in bioinformatics also, so the scientists asked him for help. Innokenty is busy preparing VK Cup, so he decided to delegate the problem to the competitors. Help the scientists!InputThe first line contains the string s (1 ≀ |s| ≀ 105) that describes the initial DNA strand. It consists only of capital English letters "A", "T", "G" and "C".The next line contains single integer q (1 ≀ q ≀ 105)Β β€” the number of events.After that, q lines follow, each describes one event. Each of the lines has one of two formats: 1Β xΒ c, where x is an integer (1 ≀ x ≀ |s|), and c is a letter "A", "T", "G" or "C", which means that there is a change in the DNA: the nucleotide at position x is now c. 2Β lΒ rΒ e, where l, r are integers (1 ≀ l ≀ r ≀ |s|), and e is a string of letters "A", "T", "G" and "C" (1 ≀ |e| ≀ 10), which means that scientists are interested in the value of impact of infection e to the segment of DNA strand from position l to position r, inclusive. OutputFor each scientists' query (second type query) print a single integer in a new lineΒ β€” the value of impact of the infection on the DNA.ExamplesInputATGCATGC42 1 8 ATGC2 2 6 TTT1 4 T2 2 6 TAOutput824InputGAGTTGTTAA62 3 4 TATGGTG1 1 T1 6 G2 5 9 AGTAATA1 10 G2 2 6 TTGTOutput031NoteConsider the first example. In the first query of second type all characters coincide, so the answer is 8. In the second query we compare string "TTTTT..." and the substring "TGCAT". There are two matches. In the third query, after the DNA change, we compare string "TATAT..."' with substring "TGTAT". There are 4 matches.
InputATGCATGC42 1 8 ATGC2 2 6 TTT1 4 T2 2 6 TA
Output824
2 seconds
512 megabytes
['data structures', 'strings', '*2100']
B. High Loadtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputArkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be connected to exactly one other node of the network, while all other nodes should be connected to at least two nodes in order to increase the system stability.Arkady wants to make the system as fast as possible, so he wants to minimize the maximum distance between two exit-nodes. The distance between two nodes is the number of wires a package needs to go through between those two nodes.Help Arkady to find such a way to build the network that the distance between the two most distant exit-nodes is as small as possible.InputThe first line contains two integers n and k (3 ≀ n ≀ 2Β·105, 2 ≀ k ≀ n - 1)Β β€” the total number of nodes and the number of exit-nodes.Note that it is always possible to build at least one network with n nodes and k exit-nodes within the given constraints.OutputIn the first line print the minimum possible distance between the two most distant exit-nodes. In each of the next n - 1 lines print two integers: the ids of the nodes connected by a wire. The description of each wire should be printed exactly once. You can print wires and wires' ends in arbitrary order. The nodes should be numbered from 1 to n. Exit-nodes can have any ids.If there are multiple answers, print any of them.ExamplesInput3 2Output21 22 3Input5 3Output31 22 33 43 5NoteIn the first example the only network is shown on the left picture.In the second example one of optimal networks is shown on the right picture.Exit-nodes are highlighted.
Input3 2
Output21 22 3
2 seconds
512 megabytes
['constructive algorithms', 'greedy', 'implementation', 'trees', '*1800']
A. String Reconstructiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi, 1, xi, 2, ..., xi, ki. He remembers n such strings ti.You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only.InputThe first line contains single integer n (1 ≀ n ≀ 105) β€” the number of strings Ivan remembers.The next n lines contain information about the strings. The i-th of these lines contains non-empty string ti, then positive integer ki, which equal to the number of times the string ti occurs in string s, and then ki distinct positive integers xi, 1, xi, 2, ..., xi, ki in increasing order β€” positions, in which occurrences of the string ti in the string s start. It is guaranteed that the sum of lengths of strings ti doesn't exceed 106, 1 ≀ xi, j ≀ 106, 1 ≀ ki ≀ 106, and the sum of all ki doesn't exceed 106. The strings ti can coincide.It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists.OutputPrint lexicographically minimal string that fits all the information Ivan remembers. ExamplesInput3a 4 1 3 5 7ab 2 1 5ca 1 4OutputabacabaInput1a 1 3OutputaaaInput3ab 1 1aba 1 3ab 2 3 5Outputababab
Input3a 4 1 3 5 7ab 2 1 5ca 1 4
Outputabacaba
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', 'strings', '*1700']
G. Tree Queriestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices (numbered from 1 to n). Initially all vertices are white. You have to process q queries of two different types: 1 x β€” change the color of vertex x to black. It is guaranteed that the first query will be of this type. 2 x β€” for the vertex x, find the minimum index y such that the vertex with index y belongs to the simple path from x to some black vertex (a simple path never visits any vertex more than once). For each query of type 2 print the answer to it.Note that the queries are given in modified way.InputThe first line contains two numbers n and q (3 ≀ n, q ≀ 106).Then n - 1 lines follow, each line containing two numbers xi and yi (1 ≀ xi < yi ≀ n) and representing the edge between vertices xi and yi.It is guaranteed that these edges form a tree.Then q lines follow. Each line contains two integers ti and zi, where ti is the type of ith query, and zi can be used to restore xi for this query in this way: you have to keep track of the answer to the last query of type 2 (let's call this answer last, and initially last = 0); then xi = (zi + last) mod n + 1.It is guaranteed that the first query is of type 1, and there is at least one query of type 2.OutputFor each query of type 2 output the answer to it.ExampleInput4 61 22 33 41 21 22 21 32 22 2Output321
Input4 61 22 33 41 21 22 21 32 22 2
Output321
3 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*2500']
F. String Compressiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIvan wants to write a letter to his friend. The letter is a string s consisting of lowercase Latin letters.Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string s instead of the string itself.The compressed version of string s is a sequence of strings c1, s1, c2, s2, ..., ck, sk, where ci is the decimal representation of number ai (without any leading zeroes) and si is some string consisting of lowercase Latin letters. If Ivan writes string s1 exactly a1 times, then string s2 exactly a2 times, and so on, the result will be string s.The length of a compressed version is |c1| + |s1| + |c2| + |s2|... |ck| + |sk|. Among all compressed versions Ivan wants to choose a version such that its length is minimum possible. Help Ivan to determine minimum possible length.InputThe only line of input contains one string s consisting of lowercase Latin letters (1 ≀ |s| ≀ 8000).OutputOutput one integer number β€” the minimum possible length of a compressed version of s.ExamplesInputaaaaaaaaaaOutput3InputabcabOutput6InputcczababababOutput7NoteIn the first example Ivan will choose this compressed version: c1 is 10, s1 is a.In the second example Ivan will choose this compressed version: c1 is 1, s1 is abcab.In the third example Ivan will choose this compressed version: c1 is 2, s1 is c, c2 is 1, s2 is z, c3 is 4, s3 is ab.
Inputaaaaaaaaaa
Output3
2 seconds
512 megabytes
['dp', 'hashing', 'string suffix structures', 'strings', '*2400']
E. Minimal Labelstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed acyclic graph with n vertices and m edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.You should assign labels to all vertices in such a way that: Labels form a valid permutation of length n β€” an integer sequence such that each integer from 1 to n appears exactly once in it. If there exists an edge from vertex v to vertex u then labelv should be smaller than labelu. Permutation should be lexicographically smallest among all suitable. Find such sequence of labels to satisfy all the conditions.InputThe first line contains two integer numbers n, m (2 ≀ n ≀ 105, 1 ≀ m ≀ 105).Next m lines contain two integer numbers v and u (1 ≀ v, u ≀ n, v ≠ u) β€” edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges.OutputPrint n numbers β€” lexicographically smallest correct permutation of labels of vertices.ExamplesInput3 31 21 33 2Output1 3 2 Input4 53 14 12 33 42 4Output4 1 2 3 Input5 43 12 12 34 5Output3 1 2 4 5
Input3 31 21 33 2
Output1 3 2
1 second
256 megabytes
['data structures', 'dfs and similar', 'graphs', 'greedy', '*2300']
D. Suitable Replacementtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t consisting of small Latin letters, string s can also contain '?' characters. Suitability of string s is calculated by following metric:Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings s, you choose the one with the largest number of non-intersecting occurrences of string t. Suitability is this number of occurrences.You should replace all '?' characters with small Latin letters in such a way that the suitability of string s is maximal.InputThe first line contains string s (1 ≀ |s| ≀ 106).The second line contains string t (1 ≀ |t| ≀ 106).OutputPrint string s with '?' replaced with small Latin letters in such a way that suitability of that string is maximal.If there are multiple strings with maximal suitability then print any of them.ExamplesInput?aa?abOutputbaabInput??b?zaOutputazbzInputabcdabacabaOutputabcdNoteIn the first example string "baab" can be transformed to "abab" with swaps, this one has suitability of 2. That means that string "baab" also has suitability of 2.In the second example maximal suitability you can achieve is 1 and there are several dozens of such strings, "azbz" is just one of them.In the third example there are no '?' characters and the suitability of the string is 0.
Input?aa?ab
Outputbaab
1 second
256 megabytes
['binary search', 'greedy', 'implementation', '*1500']
C. Multi-judge Solvingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMakes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty β€” a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge). Makes has chosen n problems to solve on Decoforces with difficulties a1, a2, ..., an. He can solve these problems in arbitrary order. Though he can solve problem i with difficulty ai only if he had already solved some problem with difficulty (no matter on what online judge was it).Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty k.With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list. For every positive integer y there exist some problem with difficulty y on at least one judge besides Decoforces.Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another.Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.InputThe first line contains two integer numbers n, k (1 ≀ n ≀ 103, 1 ≀ k ≀ 109).The second line contains n space-separated integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109).OutputPrint minimum number of problems Makes should solve on other judges in order to solve all chosen problems on Decoforces.ExamplesInput3 32 1 9Output1Input4 2010 3 6 3Output0NoteIn the first example Makes at first solves problems 1 and 2. Then in order to solve the problem with difficulty 9, he should solve problem with difficulty no less than 5. The only available are difficulties 5 and 6 on some other judge. Solving any of these will give Makes opportunity to solve problem 3.In the second example he can solve every problem right from the start.
Input3 32 1 9
Output1
1 second
256 megabytes
['greedy', 'implementation', '*1600']
B. Five-In-a-Rowtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob play 5-in-a-row game. They have a playing field of size 10 × 10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts.In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately.Alice wins if some crosses in the field form line of length not smaller than 5. This line can be horizontal, vertical and diagonal.InputYou are given matrix 10 × 10 (10 lines of 10 characters each) with capital Latin letters 'X' being a cross, letters 'O' being a nought and '.' being an empty cell. The number of 'X' cells is equal to the number of 'O' cells and there is at least one of each type. There is at least one empty cell.It is guaranteed that in the current arrangement nobody has still won.OutputPrint 'YES' if it's possible for Alice to win in one turn by putting cross in some empty cell. Otherwise print 'NO'.ExamplesInputXX.XX..........OOOO.................................................................................OutputYESInputXXOXX.....OO.O......................................................................................OutputNO
InputXX.XX..........OOOO.................................................................................
OutputYES
1 second
256 megabytes
['brute force', 'implementation', '*1600']
A. Binary Protocoltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm: Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). Digits are written one by one in order corresponding to number and separated by single '0' character. Though Polycarp learnt how to encode the numbers, he has no idea how to decode them back. Help him calculate the decoded number.InputThe first line contains one integer number n (1 ≀ n ≀ 89) β€” length of the string s.The second line contains string s β€” sequence of '0' and '1' characters, number in its encoded format. It is guaranteed that the number corresponding to the string is positive and doesn't exceed 109. The string always starts with '1'.OutputPrint the decoded number.ExamplesInput3111Output3Input9110011101Output2031
Input3111
Output3
1 second
256 megabytes
['implementation', '*1100']
F. Madnesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe second semester starts at the University of Pavlopolis. After vacation in Vičkopolis Noora needs to return to Pavlopolis and continue her study.Sometimes (or quite often) there are teachers who do not like you. Incidentally Noora also has one such teacher. His name is Yury Dmitrievich and he teaches graph theory. Yury Dmitrievich doesn't like Noora, so he always gives the girl the most difficult tasks. So it happened this time.The teacher gives Noora a tree with n vertices. Vertices are numbered with integers from 1 to n. The length of all the edges of this tree is 1. Noora chooses a set of simple paths that pairwise don't intersect in edges. However each vertex should belong to at least one of the selected path.For each of the selected paths, the following is done: We choose exactly one edge (u, v) that belongs to the path. On the selected edge (u, v) there is a point at some selected distance x from the vertex u and at distance 1 - x from vertex v. But the distance x chosen by Noora arbitrarily, i. e. it can be different for different edges. One of the vertices u or v is selected. The point will start moving to the selected vertex. Let us explain how the point moves by example. Suppose that the path consists of two edges (v1, v2) and (v2, v3), the point initially stands on the edge (v1, v2) and begins its movement to the vertex v1. Then the point will reach v1, then "turn around", because the end of the path was reached, further it will move in another direction to vertex v2, then to vertex v3, then "turn around" again, then move to v2 and so on. The speed of the points is 1 edge per second. For example, for 0.5 second the point moves to the length of the half of an edge.A stopwatch is placed at each vertex of the tree. The time that the stopwatches indicate at start time is 0 seconds. Then at the starting moment of time, all points simultaneously start moving from the selected positions to selected directions along the selected paths, and stopwatches are simultaneously started. When one of the points reaches the vertex v, the stopwatch at the vertex v is automatically reset, i.e. it starts counting the time from zero.Denote by resv the maximal time that the stopwatch at the vertex v will show if the point movement continues infinitely. Noora is asked to select paths and points on them so that res1 is as minimal as possible. If there are several solutions to do this, it is necessary to minimize res2, then res3, res4, ..., resn.Help Noora complete the teacher's task.For the better understanding of the statement, see the explanation for the example.InputThe first line contains single integer n (2 ≀ n ≀ 100) β€” number of vertices in the given tree.Each of next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u ≠ v) β€” vertices connected by an edge.Guaranteed that input defines a valid tree.OutputIn the first line print single integer paths β€” number of paths you want to choose.In the next paths lines print path's descriptions: Single integer len β€” number of edges in the current path. len integers β€” indices of the edges in the path. The edges are numbered from 1 to n - 1 in order they are given in input. Two integers u and v β€” means that you put point on the edge between vertices u and v (obviously the edge should belong to the path) and a point will start moving to the vertex v. Note that order of printing of the edge's ends is important. For example if you print "1 2" (without quotes), then point will start moving to vertex 2; but if you print "2 1" (without quotes), then point will start moving to vertex 1. Single real number x (0 ≀ x ≀ 1) β€” distance between point and vertex u (the same vertex that you print first in the third paragraph). ScoringJudge system will generate array res using the output data provided by the participant. Also system will generate array resOptimal by the jury answer. Your answer will be accepted if only for each i (1 ≀ i ≀ n) the following is satisfied: .ExampleInput31 22 3Output21 1 1 2 0.66666666661 2 2 3 0.6666666666NoteConsider an example.In starting moment of time points are located as following:The first path is highlighted in red, the second in blue, green circles represent chosen points, and brown numbers inside vertices β€” current time at stopwatch. Purple arrows represent direction in which points will move.In 0.(3) seconds points will be located in following way (before stopwatch reset):After stopwatch reset:In 1.0 second after the start of moving:In 1.(3) seconds after the start of moving (after stopwatch reset):Finally, in 2 seconds after the start of moving points return to their initial positions.This process will continue infinitely.
Input31 22 3
Output21 1 1 2 0.66666666661 2 2 3 0.6666666666
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'trees', '*2500']
E. Liartime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe first semester ended. You know, after the end of the first semester the holidays begin. On holidays Noora decided to return to Vičkopolis. As a modest souvenir for Leha, she brought a sausage of length m from Pavlopolis. Everyone knows that any sausage can be represented as a string of lowercase English letters, the length of which is equal to the length of the sausage.Leha was very pleased with the gift and immediately ate the sausage. But then he realized that it was a quite tactless act, because the sausage was a souvenir! So the hacker immediately went to the butcher shop. Unfortunately, there was only another sausage of length n in the shop. However Leha was not upset and bought this sausage. After coming home, he decided to cut the purchased sausage into several pieces and number the pieces starting from 1 from left to right. Then he wants to select several pieces and glue them together so that the obtained sausage is equal to the sausage that Noora gave. But the hacker can glue two pieces together only when the number of the left piece is less than the number of the right piece. Besides he knows that if he glues more than x pieces, Noora will notice that he has falsified souvenir sausage and will be very upset. Of course Leha doesn’t want to upset the girl. The hacker asks you to find out whether he is able to cut the sausage he bought, and then glue some of the pieces so that Noora doesn't notice anything.Formally, you are given two strings s and t. The length of the string s is n, the length of the string t is m. It is required to select several pairwise non-intersecting substrings from s, so that their concatenation in the same order as these substrings appear in s, is equal to the string t. Denote by f(s, t) the minimal number of substrings to be chosen so that their concatenation is equal to the string t. If it is impossible to choose such substrings, then f(s, t) =β€‰βˆž. Leha really wants to know whether it’s true that f(s, t) ≀ x.InputThe first line contains single integer n (1 ≀ n ≀ 105) β€” length of sausage bought by Leha, i.e. the length of the string s.The second line contains string s of the length n consisting of lowercase English letters.The third line contains single integer m (1 ≀ m ≀ n) β€” length of sausage bought by Noora, i.e. the length of the string t.The fourth line contains string t of the length m consisting of lowercase English letters.The fifth line contains single integer x (1 ≀ x ≀ 30) β€” the maximum number of pieces of sausage that Leha can glue so that Noora doesn’t notice anything.OutputIn the only line print "YES" (without quotes), if Leha is able to succeed in creating new sausage so that Noora doesn't notice anything. Otherwise print "NO" (without quotes).ExamplesInput9hloyaygrt6loyyrt3OutputYESInput9hloyaygrt6loyyrt2OutputNONoteLet's consider the first sample.In the optimal answer, Leha should cut the sausage he bought in the following way: hloyaygrt = h + loy + a + y + g + rt. Then he numbers received parts from 1 to 6: h β€” number 1 loy β€” number 2 a β€” number 3 y β€” number 4 g β€” number 5 rt β€” number 6 Hereupon the hacker should glue the parts with numbers 2, 4 and 6 and get sausage loyygrt equal to one that is given by Noora. Thus, he will have to glue three pieces. Since x = 3 you should print "YES" (without quotes).In the second sample both sausages coincide with sausages from the first sample. However since x = 2 you should print "NO" (without quotes).
Input9hloyaygrt6loyyrt3
OutputYES
4 seconds
256 megabytes
['binary search', 'dp', 'hashing', 'string suffix structures', '*2400']
D. My pretty girl Nooratime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Pavlopolis University where Noora studies it was decided to hold beauty contest "Miss Pavlopolis University". Let's describe the process of choosing the most beautiful girl in the university in more detail.The contest is held in several stages. Suppose that exactly n girls participate in the competition initially. All the participants are divided into equal groups, x participants in each group. Furthermore the number x is chosen arbitrarily, i. e. on every stage number x can be different. Within each group the jury of the contest compares beauty of the girls in the format "each with each". In this way, if group consists of x girls, then comparisons occur. Then, from each group, the most beautiful participant is selected. Selected girls enter the next stage of the competition. Thus if n girls were divided into groups, x participants in each group, then exactly participants will enter the next stage. The contest continues until there is exactly one girl left who will be "Miss Pavlopolis University"But for the jury this contest is a very tedious task. They would like to divide the girls into groups in each stage so that the total number of pairwise comparisons of the girls is as few as possible. Let f(n) be the minimal total number of comparisons that should be made to select the most beautiful participant, if we admit n girls to the first stage.The organizers of the competition are insane. They give Noora three integers t, l and r and ask the poor girl to calculate the value of the following expression: t0Β·f(l) + t1Β·f(l + 1) + ... + tr - lΒ·f(r). However, since the value of this expression can be quite large the organizers ask her to calculate it modulo 109 + 7. If Noora can calculate the value of this expression the organizers promise her to help during the beauty contest. But the poor girl is not strong in mathematics, so she turned for help to Leha and he turned to you.InputThe first and single line contains three integers t, l and r (1 ≀ t < 109 + 7, 2 ≀ l ≀ r ≀ 5Β·106).OutputIn the first line print single integer β€” the value of the expression modulo 109 + 7.ExampleInput2 2 4Output19NoteConsider the sample.It is necessary to find the value of .f(2) = 1. From two girls you can form only one group of two people, in which there will be one comparison.f(3) = 3. From three girls you can form only one group of three people, in which there will be three comparisons.f(4) = 3. From four girls you can form two groups of two girls each. Then at the first stage there will be two comparisons, one in each of the two groups. In the second stage there will be two girls and there will be one comparison between them. Total 2 + 1 = 3 comparisons. You can also leave all girls in same group in the first stage. Then comparisons will occur. Obviously, it's better to split girls into groups in the first way.Then the value of the expression is .
Input2 2 4
Output19
1.5 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'math', 'number theory', '*1800']
C. Hacker, pack your bags!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's well known that the best way to distract from something is to do one's favourite thing. Job is such a thing for Leha.So the hacker began to work hard in order to get rid of boredom. It means that Leha began to hack computers all over the world. For such zeal boss gave the hacker a vacation of exactly x days. You know the majority of people prefer to go somewhere for a vacation, so Leha immediately went to the travel agency. There he found out that n vouchers left. i-th voucher is characterized by three integers li, ri, costi β€” day of departure from Vičkopolis, day of arriving back in Vičkopolis and cost of the voucher correspondingly. The duration of the i-th voucher is a value ri - li + 1.At the same time Leha wants to split his own vocation into two parts. Besides he wants to spend as little money as possible. Formally Leha wants to choose exactly two vouchers i and j (i ≠ j) so that they don't intersect, sum of their durations is exactly x and their total cost is as minimal as possible. Two vouchers i and j don't intersect if only at least one of the following conditions is fulfilled: ri < lj or rj < li.Help Leha to choose the necessary vouchers!InputThe first line contains two integers n and x (2 ≀ n, x ≀ 2Β·105) β€” the number of vouchers in the travel agency and the duration of Leha's vacation correspondingly.Each of the next n lines contains three integers li, ri and costi (1 ≀ li ≀ ri ≀ 2Β·105, 1 ≀ costi ≀ 109) β€” description of the voucher.OutputPrint a single integer β€” a minimal amount of money that Leha will spend, or print  - 1 if it's impossible to choose two disjoint vouchers with the total duration exactly x.ExamplesInput4 51 3 41 2 55 6 11 2 4Output5Input3 24 6 32 4 13 5 4Output-1NoteIn the first sample Leha should choose first and third vouchers. Hereupon the total duration will be equal to (3 - 1 + 1) + (6 - 5 + 1) = 5 and the total cost will be 4 + 1 = 5.In the second sample the duration of each voucher is 3 therefore it's impossible to choose two vouchers with the total duration equal to 2.
Input4 51 3 41 2 55 6 11 2 4
Output5
2 seconds
256 megabytes
['binary search', 'greedy', 'implementation', 'sortings', '*1600']
B. Crossword solvingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputErelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol.InputThe first line contains two integers n and m (1 ≀ n ≀ m ≀ 1000) β€” the length of the string s and the length of the string t correspondingly.The second line contains n lowercase English letters β€” string s.The third line contains m lowercase English letters β€” string t.OutputIn the first line print single integer k β€” the minimal number of symbols that need to be replaced.In the second line print k distinct integers denoting the positions of symbols in the string s which need to be replaced. Print the positions in any order. If there are several solutions print any of them. The numbering of the positions begins from one.ExamplesInput3 5abcxaybzOutput22 3 Input4 10abcdebceabazcdOutput12
Input3 5abcxaybz
Output22 3
1 second
256 megabytes
['brute force', 'implementation', 'strings', '*1000']
A. I'm bored with lifetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHolidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopolis. Thus Leha was left completely alone in a quiet town Vičkopolis. He almost even fell into a depression from boredom!Leha came up with a task for himself to relax a little. He chooses two integers A and B and then calculates the greatest common divisor of integers "A factorial" and "B factorial". Formally the hacker wants to find out GCD(A!, B!). It's well known that the factorial of an integer x is a product of all positive integers less than or equal to x. Thus x! = 1Β·2Β·3Β·...Β·(x - 1)Β·x. For example 4! = 1Β·2Β·3Β·4 = 24. Recall that GCD(x, y) is the largest positive integer q that divides (without a remainder) both x and y.Leha has learned how to solve this task very effective. You are able to cope with it not worse, aren't you?InputThe first and single line contains two integers A and B (1 ≀ A, B ≀ 109, min(A, B) ≀ 12).OutputPrint a single integer denoting the greatest common divisor of integers A! and B!.ExampleInput4 3Output6NoteConsider the sample.4! = 1Β·2Β·3Β·4 = 24. 3! = 1Β·2Β·3 = 6. The greatest common divisor of integers 24 and 6 is exactly 6.
Input4 3
Output6
1 second
256 megabytes
['implementation', 'math', 'number theory', '*800']
E. Okabe and El Psy Kongrootime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOkabe likes to take walks but knows that spies from the Organization could be anywhere; that's why he wants to know how many different walks he can take in his city safely. Okabe's city can be represented as all points (x, y) such that x and y are non-negative. Okabe starts at the origin (point (0, 0)), and needs to reach the point (k, 0). If Okabe is currently at the point (x, y), in one step he can go to (x + 1, y + 1), (x + 1, y), or (x + 1, y - 1).Additionally, there are n horizontal line segments, the i-th of which goes from x = ai to x = bi inclusive, and is at y = ci. It is guaranteed that a1 = 0, an ≀ k ≀ bn, and ai = bi - 1 for 2 ≀ i ≀ n. The i-th line segment forces Okabe to walk with y-value in the range 0 ≀ y ≀ ci when his x value satisfies ai ≀ x ≀ bi, or else he might be spied on. This also means he is required to be under two line segments when one segment ends and another begins.Okabe now wants to know how many walks there are from the origin to the point (k, 0) satisfying these conditions, modulo 109 + 7.InputThe first line of input contains the integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 1018)Β β€” the number of segments and the destination x coordinate.The next n lines contain three space-separated integers ai, bi, and ci (0 ≀ ai < bi ≀ 1018, 0 ≀ ci ≀ 15)Β β€” the left and right ends of a segment, and its y coordinate.It is guaranteed that a1 = 0, an ≀ k ≀ bn, and ai = bi - 1 for 2 ≀ i ≀ n.OutputPrint the number of walks satisfying the conditions, modulo 1000000007 (109 + 7).ExamplesInput1 30 3 3Output4Input2 60 3 03 10 2Output4Note The graph above corresponds to sample 1. The possible walks are: The graph above corresponds to sample 2. There is only one walk for Okabe to reach (3, 0). After this, the possible walks are:
Input1 30 3 3
Output4
2 seconds
256 megabytes
['dp', 'matrices', '*2100']
D. Okabe and Citytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOkabe likes to be able to walk through his city on a path lit by street lamps. That way, he doesn't get beaten up by schoolchildren.Okabe's city is represented by a 2D grid of cells. Rows are numbered from 1 to n from top to bottom, and columns are numbered 1 to m from left to right. Exactly k cells in the city are lit by a street lamp. It's guaranteed that the top-left cell is lit.Okabe starts his walk from the top-left cell, and wants to reach the bottom-right cell. Of course, Okabe will only walk on lit cells, and he can only move to adjacent cells in the up, down, left, and right directions. However, Okabe can also temporarily light all the cells in any single row or column at a time if he pays 1 coin, allowing him to walk through some cells not lit initially. Note that Okabe can only light a single row or column at a time, and has to pay a coin every time he lights a new row or column. To change the row or column that is temporarily lit, he must stand at a cell that is lit initially. Also, once he removes his temporary light from a row or column, all cells in that row/column not initially lit are now not lit.Help Okabe find the minimum number of coins he needs to pay to complete his walk!InputThe first line of input contains three space-separated integers n, m, and k (2 ≀ n, m, k ≀ 104).Each of the next k lines contains two space-separated integers ri and ci (1 ≀ ri ≀ n, 1 ≀ ci ≀ m)Β β€” the row and the column of the i-th lit cell.It is guaranteed that all k lit cells are distinct. It is guaranteed that the top-left cell is lit.OutputPrint the minimum number of coins Okabe needs to pay to complete his walk, or -1 if it's not possible.ExamplesInput4 4 51 12 12 33 34 3Output2Input5 5 41 12 13 13 2Output-1Input2 2 41 11 22 12 2Output0Input5 5 41 12 23 34 4Output3NoteIn the first sample test, Okabe can take the path , paying only when moving to (2, 3) and (4, 4).In the fourth sample, Okabe can take the path , paying when moving to (1, 2), (3, 4), and (5, 4).
Input4 4 51 12 12 33 34 3
Output2
4 seconds
256 megabytes
['dfs and similar', 'graphs', 'shortest paths', '*2200']
C. Okabe and Boxestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOkabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.InputThe first line of input contains the integer n (1 ≀ n ≀ 3Β·105)Β β€” the number of boxes.Each of the next 2n lines of input starts with a string "add" or "remove". If the line starts with the "add", an integer x (1 ≀ x ≀ n) follows, indicating that Daru should add the box with number x to the top of the stack. It is guaranteed that exactly n lines contain "add" operations, all the boxes added are distinct, and n lines contain "remove" operations. It is also guaranteed that a box is always added before it is required to be removed.OutputPrint the minimum number of times Daru needs to reorder the boxes to successfully complete all of Okabe's commands.ExamplesInput3add 1removeadd 2add 3removeremoveOutput1Input7add 3add 2add 1removeadd 4removeremoveremoveadd 6add 7add 5removeremoveremoveOutput2NoteIn the first sample, Daru should reorder the boxes after adding box 3 to the stack.In the second sample, Daru should reorder the boxes after adding box 4 and box 7 to the stack.
Input3add 1removeadd 2add 3removeremove
Output1
3 seconds
256 megabytes
['data structures', 'greedy', 'trees', '*1500']
B. Okabe and Banana Treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOkabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.Consider the point (x, y) in the 2D plane such that x and y are integers and 0 ≀ x, y. There is a tree in such a point, and it has x + y bananas. There are no trees nor bananas in other points. Now, Okabe draws a line with equation . Okabe can select a single rectangle with axis aligned sides with all points on or under the line and cut all the trees in all points that are inside or on the border of this rectangle and take their bananas. Okabe's rectangle can be degenerate; that is, it can be a line segment or even a point.Help Okabe and find the maximum number of bananas he can get if he chooses the rectangle wisely.Okabe is sure that the answer does not exceed 1018. You can trust him.InputThe first line of input contains two space-separated integers m and b (1 ≀ m ≀ 1000, 1 ≀ b ≀ 10000).OutputPrint the maximum number of bananas Okabe can get from the trees he cuts.ExamplesInput1 5Output30Input2 3Output25Note The graph above corresponds to sample test 1. The optimal rectangle is shown in red and has 30 bananas.
Input1 5
Output30
2 seconds
256 megabytes
['brute force', 'math', '*1300']
A. Okabe and Future Gadget Laboratorytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOkabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an n by n square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every x, y such that 1 ≀ x, y ≀ n and ax, y ≠ 1, there should exist two indices s and t so that ax, y = ax, s + at, y, where ai, j denotes the integer in i-th row and j-th column.Help Okabe determine whether a given lab is good!InputThe first line of input contains the integer n (1 ≀ n ≀ 50)Β β€” the size of the lab. The next n lines contain n space-separated integers denoting a row of the grid. The j-th integer in the i-th row is ai, j (1 ≀ ai, j ≀ 105).OutputPrint "Yes" if the given lab is good and "No" otherwise.You can output each letter in upper or lower case.ExamplesInput31 1 22 3 16 4 1OutputYesInput31 5 21 1 11 2 3OutputNoNoteIn the first sample test, the 6 in the bottom left corner is valid because it is the sum of the 2 above it and the 4 on the right. The same holds for every number not equal to 1 in this table, so the answer is "Yes".In the second sample test, the 5 cannot be formed as the sum of an integer in the same row and an integer in the same column. Thus the answer is "No".
Input31 1 22 3 16 4 1
OutputYes
2 seconds
256 megabytes
['implementation', '*800']
B. Mister B and Angle in Polygontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides).That's why Mister B decided to use this polygon. Now Mister B must find three distinct vertices v1, v2, v3 such that the angle (where v2 is the vertex of the angle, and v1 and v3 lie on its sides) is as close as possible to a. In other words, the value should be minimum possible.If there are many optimal solutions, Mister B should be satisfied with any of them.InputFirst and only line contains two space-separated integers n and a (3 ≀ n ≀ 105, 1 ≀ a ≀ 180)Β β€” the number of vertices in the polygon and the needed angle, in degrees.OutputPrint three space-separated integers: the vertices v1, v2, v3, which form . If there are multiple optimal solutions, print any of them. The vertices are numbered from 1 to n in clockwise order.ExamplesInput3 15Output1 2 3Input4 67Output2 1 3Input4 68Output4 1 2NoteIn first sample test vertices of regular triangle can create only angle of 60 degrees, that's why every possible angle is correct.Vertices of square can create 45 or 90 degrees angles only. That's why in second sample test the angle of 45 degrees was chosen, since |45 - 67| < |90 - 67|. Other correct answers are: "3 1 2", "3 2 4", "4 2 3", "4 3 1", "1 3 4", "1 4 2", "2 4 1", "4 1 3", "3 1 4", "3 4 2", "2 4 3", "2 3 1", "1 3 2", "1 2 4", "4 2 1".In third sample test, on the contrary, the angle of 90 degrees was chosen, since |90 - 68| < |45 - 68|. Other correct answers are: "2 1 4", "3 2 1", "1 2 3", "4 3 2", "2 3 4", "1 4 3", "3 4 1".
Input3 15
Output1 2 3
2 seconds
256 megabytes
['constructive algorithms', 'geometry', 'math', '*1300']
A. Mister B and Book Readingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMister B once received a gift: it was a book about aliens, which he started read immediately. This book had c pages.At first day Mister B read v0 pages, but after that he started to speed up. Every day, starting from the second, he read a pages more than on the previous day (at first day he read v0 pages, at secondΒ β€” v0 + a pages, at thirdΒ β€” v0 + 2a pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than v1 pages per day.Also, to refresh his memory, every day, starting from the second, Mister B had to reread last l pages he read on the previous day. Mister B finished the book when he read the last page for the first time.Help Mister B to calculate how many days he needed to finish the book.InputFirst and only line contains five space-separated integers: c, v0, v1, a and l (1 ≀ c ≀ 1000, 0 ≀ l < v0 ≀ v1 ≀ 1000, 0 ≀ a ≀ 1000) β€” the length of the book in pages, the initial reading speed, the maximum reading speed, the acceleration in reading speed and the number of pages for rereading.OutputPrint one integer β€” the number of days Mister B needed to finish the book.ExamplesInput5 5 10 5 4Output1Input12 4 12 4 1Output3Input15 1 100 0 0Output15NoteIn the first sample test the book contains 5 pages, so Mister B read it right at the first day.In the second sample test at first day Mister B read pages number 1 - 4, at second dayΒ β€” 4 - 11, at third dayΒ β€” 11 - 12 and finished the book.In third sample test every day Mister B read 1 page of the book, so he finished in 15 days.
Input5 5 10 5 4
Output1
2 seconds
256 megabytes
['implementation', '*900']
E. Mister B and Flight to the Moontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn order to fly to the Moon Mister B just needs to solve the following problem.There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles.We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?InputThe only line contains single integer n (3 ≀ n ≀ 300).OutputIf there is no answer, print -1.Otherwise, in the first line print k (1 ≀ k ≀ n2)Β β€” the number of cycles in your solution.In each of the next k lines print description of one cycle in the following format: first print integer m (3 ≀ m ≀ 4)Β β€” the length of the cycle, then print m integers v1, v2, ..., vm (1 ≀ vi ≀ n)Β β€” the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles.ExamplesInput3Output23 1 2 33 1 2 3Input5Output63 5 4 23 3 1 54 4 5 2 34 4 3 2 13 4 2 13 3 1 5
Input3
Output23 1 2 33 1 2 3
2 seconds
256 megabytes
['constructive algorithms', 'graphs', '*2800']
D. Mister B and Astronomerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter studying the beacons Mister B decided to visit alien's planet, because he learned that they live in a system of flickering star Moon. Moreover, Mister B learned that the star shines once in exactly T seconds. The problem is that the star is yet to be discovered by scientists.There are n astronomers numerated from 1 to n trying to detect the star. They try to detect the star by sending requests to record the sky for 1 second. The astronomers send requests in cycle: the i-th astronomer sends a request exactly ai second after the (i - 1)-th (i.e. if the previous request was sent at moment t, then the next request is sent at moment t + ai); the 1-st astronomer sends requests a1 seconds later than the n-th. The first astronomer sends his first request at moment 0.Mister B doesn't know the first moment the star is going to shine, but it's obvious that all moments at which the star will shine are determined by the time of its shine moment in the interval [0, T). Moreover, this interval can be split into T parts of 1 second length each of form [t, t + 1), where t = 0, 1, 2, ..., (T - 1).Mister B wants to know how lucky each astronomer can be in discovering the star first.For each astronomer compute how many segments of form [t, t + 1) (t = 0, 1, 2, ..., (T - 1)) there are in the interval [0, T) so that this astronomer is the first to discover the star if the first shine of the star happens in this time interval.InputThe first line contains two integers T and n (1 ≀ T ≀ 109, 2 ≀ n ≀ 2Β·105).The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109).OutputPrint n integers: for each astronomer print the number of time segments describer earlier.ExamplesInput4 22 3Output3 1 Input5 41 1 1 1Output2 1 1 1 NoteIn the first sample test the first astronomer will send requests at moments t1 = 0, 5, 10, ..., the second β€” at moments t2 = 3, 8, 13, .... That's why interval [0, 1) the first astronomer will discover first at moment t1 = 0, [1, 2) β€” the first astronomer at moment t1 = 5, [2, 3) β€” the first astronomer at moment t1 = 10, and [3, 4) β€” the second astronomer at moment t2 = 3.In the second sample test interval [0, 1) β€” the first astronomer will discover first, [1, 2) β€” the second astronomer, [2, 3) β€” the third astronomer, [3, 4) β€” the fourth astronomer, [4, 5) β€” the first astronomer.
Input4 22 3
Output3 1
2 seconds
256 megabytes
['number theory', '*2900']
C. Mister B and Beacons on Fieldtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMister B has a house in the middle of a giant plain field, which attracted aliens life. For convenience, aliens specified the Cartesian coordinate system on the field in such a way that Mister B's house has coordinates (0, 0). After that they sent three beacons to the field, but something went wrong. One beacon was completely destroyed, while the other two landed in positions with coordinates (m, 0) and (0, n), respectively, but shut down.Mister B was interested in this devices, so he decided to take them home. He came to the first beacon, placed at (m, 0), lifted it up and carried the beacon home choosing the shortest path. After that he came to the other beacon, placed at (0, n), and also carried it home choosing the shortest path. When first beacon was lifted up, the navigation system of the beacons was activated.Partially destroyed navigation system started to work in following way.At time moments when both survived beacons are at points with integer coordinates the system tries to find a location for the third beacon. It succeeds if and only if there is a point with integer coordinates such that the area of the triangle formed by the two survived beacons and this point is equal to s. In this case the system sends a packet of information with beacon positions to aliens, otherwise it doesn't.Compute how many packets of information system sent while Mister B was moving the beacons.InputThe first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The next 3Β·t lines describe t test cases. Every test case is described in three lines as follows. Note that each parameter is given as a product of three factors.The first line of a test case contains three space-separated integers: n1, n2, n3 (1 ≀ ni ≀ 106) such that n = n1Β·n2Β·n3.The second line contains three space-separated integers: m1, m2, m3 (1 ≀ mi ≀ 106) such that m = m1Β·m2Β·m3.The third line contains three space-separated integers: s1, s2, s3 (1 ≀ si ≀ 106) such that s = s1Β·s2Β·s3.Note that for hacks only tests with t = 1 allowed.OutputPrint t integers one per line β€” the answers for each test.ExampleInput32 1 12 1 11 1 31 5 12 2 11 1 210 6 182 103 213 1 13Output47171NoteFirst test case contains the following beacon positions: (2, 0) and (0, 2), s = 3. The following packets could be sent: ((2, 0), (0, 2), ( - 1, 0)), ((1, 0), (0, 2), (4, 0)), ((0, 0), (0, 2), (3, 1)), ((0, 0), (0, 1), ( - 6, 0)), where (b1, b2, p) has next description: b1 β€” first beacon position, b2 β€” second beacon position, p β€” some generated point.Second test case contains the following beacon initial positions: (4, 0) and (0, 5), s = 2. The following packets could be sent: ((4, 0), (0, 5), (0, 4)), ((3, 0), (0, 5), (2, 3)), ((2, 0), (0, 5), (2, 2)), ((1, 0), (0, 5), (1, 4)), ((0, 0), (0, 4), (0,  - 1)), ((0, 0), (0, 2), (2, 0)), ((0, 0), (0, 1), (4, 0)).
Input32 1 12 1 11 1 31 5 12 2 11 1 210 6 182 103 213 1 13
Output47171
5 seconds
256 megabytes
['number theory', '*2900']
B. Mister B and PR Shiftstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome time ago Mister B detected a strange signal from the space, which he started to study.After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.Let's define the deviation of a permutation p as .Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them.Let's denote id k (0 ≀ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example: k = 0: shift p1, p2, ... pn, k = 1: shift pn, p1, ... pn - 1, ..., k = n - 1: shift p2, p3, ... pn, p1. InputFirst line contains single integer n (2 ≀ n ≀ 106) β€” the length of the permutation.The second line contains n space-separated integers p1, p2, ..., pn (1 ≀ pi ≀ n)Β β€” the elements of the permutation. It is guaranteed that all elements are distinct.OutputPrint two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them.ExamplesInput31 2 3Output0 0Input32 3 1Output0 1Input33 2 1Output2 1NoteIn the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well.In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift.In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts.
Input31 2 3
Output0 0
2 seconds
256 megabytes
['data structures', 'implementation', 'math', '*1900']
A. Mister B and Boring Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSometimes Mister B has free evenings when he doesn't know what to do. Fortunately, Mister B found a new game, where the player can play against aliens.All characters in this game are lowercase English letters. There are two players: Mister B and his competitor.Initially the players have a string s consisting of the first a English letters in alphabetical order (for example, if a = 5, then s equals to "abcde").The players take turns appending letters to string s. Mister B moves first.Mister B must append exactly b letters on each his move. He can arbitrary choose these letters. His opponent adds exactly a letters on each move.Mister B quickly understood that his opponent was just a computer that used a simple algorithm. The computer on each turn considers the suffix of string s of length a and generates a string t of length a such that all letters in the string t are distinct and don't appear in the considered suffix. From multiple variants of t lexicographically minimal is chosen (if a = 4 and the suffix is "bfdd", the computer chooses string t equal to "aceg"). After that the chosen string t is appended to the end of s.Mister B soon found the game boring and came up with the following question: what can be the minimum possible number of different letters in string s on the segment between positions l and r, inclusive. Letters of string s are numerated starting from 1.InputFirst and only line contains four space-separated integers: a, b, l and r (1 ≀ a, b ≀ 12, 1 ≀ l ≀ r ≀ 109) β€” the numbers of letters each player appends and the bounds of the segment.OutputPrint one integer β€” the minimum possible number of different letters in the segment from position l to position r, inclusive, in string s.ExamplesInput1 1 1 8Output2Input4 2 2 6Output3Input3 7 4 6Output1NoteIn the first sample test one of optimal strategies generate string s = "abababab...", that's why answer is 2.In the second sample test string s = "abcdbcaefg..." can be obtained, chosen segment will look like "bcdbc", that's why answer is 3.In the third sample test string s = "abczzzacad..." can be obtained, chosen, segment will look like "zzz", that's why answer is 1.
Input1 1 1 8
Output2
2 seconds
256 megabytes
['games', 'greedy', '*2200']
G. Four Melodiestime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputAuthor note: I think some of you might remember the problem "Two Melodies" from Eductational Codeforces Round 22. Now it's time to make it a bit more difficult!Alice is a composer, and recently she had recorded two tracks that became very popular. Now she has got a lot of fans who are waiting for new tracks. This time Alice wants to form four melodies for her tracks.Alice has a sheet with n notes written on it. She wants to take four such non-empty non-intersecting subsequences that all of them form a melody and sum of their lengths is maximal.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.Subsequence forms a melody when each two adjacent notes either differ by 1 or are congruent modulo 7.You should write a program which will calculate maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody.InputThe first line contains one integer number n (4 ≀ n ≀ 3000).The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” notes written on a sheet.OutputPrint maximum sum of lengths of such four non-empty non-intersecting subsequences that all of them form a melody.ExamplesInput51 3 5 7 9Output4Input51 3 5 7 2Output5NoteIn the first example it is possible to compose 4 melodies by choosing any 4 notes (and each melody will consist of only one note).In the second example it is possible to compose one melody with 2 notes β€” {1, 2}. Remaining notes are used in other three melodies (one note per each melody).
Input51 3 5 7 9
Output4
5 seconds
1024 megabytes
['flows', 'graphs', '*2600']
F. Level Generationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices u and v is called a bridge if this edge belongs to every path between u and v (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.So the task Ivan gave you is: given q numbers n1, n2, ..., nq, for each i tell the maximum number of edges in a graph with ni vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.InputThe first line of input file contains a positive integer q (1 ≀ q ≀ 100 000) β€” the number of graphs Ivan needs to construct.Then q lines follow, i-th line contains one positive integer ni (1 ≀ ni ≀ 2Β·109) β€” the number of vertices in i-th graph.Note that in hacks you have to use q = 1.OutputOutput q numbers, i-th of them must be equal to the maximum number of edges in i-th graph.ExampleInput3346Output236NoteIn the first example it is possible to construct these graphs: 1 - 2, 1 - 3; 1 - 2, 1 - 3, 2 - 4; 1 - 2, 1 - 3, 2 - 3, 1 - 4, 2 - 5, 3 - 6.
Input3346
Output236
1 second
256 megabytes
['binary search', 'math', 'ternary search', '*2100']
E. Card Game Againtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova again tries to play some computer card game.The rules of deck creation in this game are simple. Vova is given an existing deck of n cards and a magic number k. The order of the cards in the deck is fixed. Each card has a number written on it; number ai is written on the i-th card in the deck.After receiving the deck and the magic number, Vova removes x (possibly x = 0) cards from the top of the deck, y (possibly y = 0) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards x + 1, x + 2, ... n - y - 1, n - y from the original deck.Vova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by k. So Vova received a deck (possibly not a valid one) and a number k, and now he wonders, how many ways are there to choose x and y so the deck he will get after removing x cards from the top and y cards from the bottom is valid?InputThe first line contains two integers n and k (1 ≀ n ≀ 100 000, 1 ≀ k ≀ 109).The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the numbers written on the cards.OutputPrint the number of ways to choose x and y so the resulting deck is valid.ExamplesInput3 46 2 8Output4Input3 69 1 14Output1NoteIn the first example the possible values of x and y are: x = 0, y = 0; x = 1, y = 0; x = 2, y = 0; x = 0, y = 1.
Input3 46 2 8
Output4
2 seconds
256 megabytes
['binary search', 'data structures', 'number theory', 'two pointers', '*1900']
D. Multicolored Carstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob got very bored during a long car trip so they decided to play a game. From the window they can see cars of different colors running past them. Cars are going one after another.The game rules are like this. Firstly Alice chooses some color A, then Bob chooses some color B (A ≠ B). After each car they update the number of cars of their chosen color that have run past them. Let's define this numbers after i-th car cntA(i) and cntB(i). If cntA(i) > cntB(i) for every i then the winner is Alice. If cntB(i) β‰₯ cntA(i) for every i then the winner is Bob. Otherwise it's a draw. Bob knows all the colors of cars that they will encounter and order of their appearance. Alice have already chosen her color A and Bob now wants to choose such color B that he will win the game (draw is not a win). Help him find this color.If there are multiple solutions, print any of them. If there is no such color then print -1.InputThe first line contains two integer numbers n and A (1 ≀ n ≀ 105, 1 ≀ A ≀ 106) – number of cars and the color chosen by Alice.The second line contains n integer numbers c1, c2, ..., cn (1 ≀ ci ≀ 106) β€” colors of the cars that Alice and Bob will encounter in the order of their appearance.OutputOutput such color B (1 ≀ B ≀ 106) that if Bob chooses it then he will win the game. If there are multiple solutions, print any of them. If there is no such color then print -1.It is guaranteed that if there exists any solution then there exists solution with (1 ≀ B ≀ 106).ExamplesInput4 12 1 4 2Output2Input5 22 2 4 5 3Output-1Input3 101 2 3Output4NoteLet's consider availability of colors in the first example: cnt2(i) β‰₯ cnt1(i) for every i, and color 2 can be the answer. cnt4(2) < cnt1(2), so color 4 isn't the winning one for Bob. All the other colors also have cntj(2) < cnt1(2), thus they are not available. In the third example every color is acceptable except for 10.
Input4 12 1 4 2
Output2
2 seconds
256 megabytes
['data structures', 'implementation', '*1700']
C. Sofa Thieftime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs to him as they all looked the same!The storehouse is represented as matrix n × m. Every sofa takes two neighbouring by some side cells. No cell is covered by more than one sofa. There can be empty cells.Sofa A is standing to the left of sofa B if there exist two such cells a and b that xa < xb, a is covered by A and b is covered by B. Sofa A is standing to the top of sofa B if there exist two such cells a and b that ya < yb, a is covered by A and b is covered by B. Right and bottom conditions are declared the same way. Note that in all conditions A ≠ B. Also some sofa A can be both to the top of another sofa B and to the bottom of it. The same is for left and right conditions.The note also stated that there are cntl sofas to the left of Grandpa Maks's sofa, cntr β€” to the right, cntt β€” to the top and cntb β€” to the bottom.Grandpa Maks asks you to help him to identify his sofa. It is guaranteed that there is no more than one sofa of given conditions.Output the number of Grandpa Maks's sofa. If there is no such sofa that all the conditions are met for it then output -1.InputThe first line contains one integer number d (1 ≀ d ≀ 105) β€” the number of sofas in the storehouse.The second line contains two integer numbers n, m (1 ≀ n, m ≀ 105) β€” the size of the storehouse.Next d lines contains four integer numbers x1, y1, x2, y2 (1 ≀ x1, x2 ≀ n, 1 ≀ y1, y2 ≀ m) β€” coordinates of the i-th sofa. It is guaranteed that cells (x1, y1) and (x2, y2) have common side, (x1, y1)  ≠  (x2, y2) and no cell is covered by more than one sofa.The last line contains four integer numbers cntl, cntr, cntt, cntb (0 ≀ cntl, cntr, cntt, cntb ≀ d - 1).OutputPrint the number of the sofa for which all the conditions are met. Sofas are numbered 1 through d as given in input. If there is no such sofa then print -1.ExamplesInput23 23 1 3 21 2 2 21 0 0 1Output1Input310 101 2 1 15 5 6 56 4 5 42 1 2 0Output2Input22 22 1 1 11 2 2 21 0 0 0Output-1NoteLet's consider the second example. The first sofa has 0 to its left, 2 sofas to its right ((1, 1) is to the left of both (5, 5) and (5, 4)), 0 to its top and 2 to its bottom (both 2nd and 3rd sofas are below). The second sofa has cntl = 2, cntr = 1, cntt = 2 and cntb = 0. The third sofa has cntl = 2, cntr = 1, cntt = 1 and cntb = 1. So the second one corresponds to the given conditions.In the third example The first sofa has cntl = 1, cntr = 1, cntt = 0 and cntb = 1. The second sofa has cntl = 1, cntr = 1, cntt = 1 and cntb = 0. And there is no sofa with the set (1, 0, 0, 0) so the answer is -1.
Input23 23 1 3 21 2 2 21 0 0 1
Output1
1 second
256 megabytes
['brute force', 'implementation', '*2000']
B. Permutation Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.The game consists of m steps. On each step the current leader with index i counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.You are given numbers l1, l2, ..., lm β€” indices of leaders in the beginning of each step. Child with number l1 is the first leader in the game. Write a program which will restore a possible permutation a1, a2, ..., an. If there are multiple solutions then print any of them. If there is no solution then print -1.InputThe first line contains two integer numbers n, m (1 ≀ n, m ≀ 100).The second line contains m integer numbers l1, l2, ..., lm (1 ≀ li ≀ n) β€” indices of leaders in the beginning of each step.OutputPrint such permutation of n numbers a1, a2, ..., an that leaders in the game will be exactly l1, l2, ..., lm if all the rules are followed. If there are multiple solutions print any of them. If there is no permutation which satisfies all described conditions print -1.ExamplesInput4 52 3 1 4 4Output3 1 2 4 Input3 33 1 2Output-1NoteLet's follow leadership in the first example: Child 2 starts. Leadership goes from 2 to 2 + a2 = 3. Leadership goes from 3 to 3 + a3 = 5. As it's greater than 4, it's going in a circle to 1. Leadership goes from 1 to 1 + a1 = 4. Leadership goes from 4 to 4 + a4 = 8. Thus in circle it still remains at 4.
Input4 52 3 1 4 4
Output3 1 2 4
1 second
256 megabytes
['implementation', '*1600']
A. Diplomas and Certificatestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students who have taken part in an olympiad. Now it's time to award the students.Some of them will receive diplomas, some wiil get certificates, and others won't receive anything. Students with diplomas and certificates are called winners. But there are some rules of counting the number of diplomas and certificates. The number of certificates must be exactly k times greater than the number of diplomas. The number of winners must not be greater than half of the number of all students (i.e. not be greater than half of n). It's possible that there are no winners.You have to identify the maximum possible number of winners, according to these rules. Also for this case you have to calculate the number of students with diplomas, the number of students with certificates and the number of students who are not winners.InputThe first (and the only) line of input contains two integers n and k (1 ≀ n, k ≀ 1012), where n is the number of students and k is the ratio between the number of certificates and the number of diplomas.OutputOutput three numbers: the number of students with diplomas, the number of students with certificates and the number of students who are not winners in case when the number of winners is maximum possible.It's possible that there are no winners.ExamplesInput18 2Output3 6 9Input9 10Output0 0 9Input1000000000000 5Output83333333333 416666666665 500000000002Input1000000000000 499999999999Output1 499999999999 500000000000
Input18 2
Output3 6 9
1 second
256 megabytes
['implementation', 'math', '*800']
F. MEX Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of integer numbers, initially it is empty. You should perform n queries.There are three different types of queries: 1 l r β€” Add all missing numbers from the interval [l, r] 2 l r β€” Remove all present numbers from the interval [l, r] 3 l r β€” Invert the interval [l, r] β€” add all missing and remove all present numbers from the interval [l, r] After each query you should output MEX of the set β€” the smallest positive (MEX  β‰₯ 1) integer number which is not presented in the set.InputThe first line contains one integer number n (1 ≀ n ≀ 105).Next n lines contain three integer numbers t, l, r (1 ≀ t ≀ 3, 1 ≀ l ≀ r ≀ 1018) β€” type of the query, left and right bounds.OutputPrint MEX of the set after each query.ExamplesInput31 3 43 1 62 1 3Output131Input41 1 33 5 62 4 43 1 6Output4441NoteHere are contents of the set after each query in the first example: {3, 4} β€” the interval [3, 4] is added {1, 2, 5, 6} β€” numbers {3, 4} from the interval [1, 6] got deleted and all the others are added {5, 6} β€” numbers {1, 2} got deleted
Input31 3 43 1 62 1 3
Output131
2 seconds
256 megabytes
['binary search', 'data structures', 'trees', '*2300']
E. Choosing The Commandertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires.Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors.Each warrior is represented by his personality β€” an integer number pi. Each commander has two characteristics β€” his personality pj and leadership lj (both are integer numbers). Warrior i respects commander j only if ( is the bitwise excluding OR of x and y).Initially Vova's army is empty. There are three different types of events that can happen with the army: 1Β pi β€” one warrior with personality pi joins Vova's army; 2Β pi β€” one warrior with personality pi leaves Vova's army; 3Β piΒ li β€” Vova tries to hire a commander with personality pi and leadership li. For each event of the third type Vova wants to know how many warriors (counting only those who joined the army and haven't left yet) respect the commander he tries to hire.InputThe first line contains one integer q (1 ≀ q ≀ 100000) β€” the number of events.Then q lines follow. Each line describes the event: 1Β pi (1 ≀ pi ≀ 108) β€” one warrior with personality pi joins Vova's army; 2Β pi (1 ≀ pi ≀ 108) β€” one warrior with personality pi leaves Vova's army (it is guaranteed that there is at least one such warrior in Vova's army by this moment); 3Β piΒ li (1 ≀ pi, li ≀ 108) β€” Vova tries to hire a commander with personality pi and leadership li. There is at least one event of this type. OutputFor each event of the third type print one integer β€” the number of warriors who respect the commander Vova tries to hire in the event.ExampleInput51 31 43 6 32 43 6 3Output10NoteIn the example the army consists of two warriors with personalities 3 and 4 after first two events. Then Vova tries to hire a commander with personality 6 and leadership 3, and only one warrior respects him (, and 2 < 3, but , and 5 β‰₯ 3). Then warrior with personality 4 leaves, and when Vova tries to hire that commander again, there are no warriors who respect him.
Input51 31 43 6 32 43 6 3
Output10
2 seconds
256 megabytes
['bitmasks', 'data structures', 'trees', '*2000']
D. Imbalanced Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.For example, the imbalance value of array [1, 4, 1] is 9, because there are 6 different subsegments of this array: [1] (from index 1 to index 1), imbalance value is 0; [1, 4] (from index 1 to index 2), imbalance value is 3; [1, 4, 1] (from index 1 to index 3), imbalance value is 3; [4] (from index 2 to index 2), imbalance value is 0; [4, 1] (from index 2 to index 3), imbalance value is 3; [1] (from index 3 to index 3), imbalance value is 0; You have to determine the imbalance value of the array a.InputThe first line contains one integer n (1 ≀ n ≀ 106) β€” size of the array a.The second line contains n integers a1, a2... an (1 ≀ ai ≀ 106) β€” elements of the array.OutputPrint one integer β€” the imbalance value of a.ExampleInput31 4 1Output9
Input31 4 1
Output9
2 seconds
256 megabytes
['data structures', 'divide and conquer', 'dsu', 'sortings', '*1900']
C. Really Big Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan likes to learn different things about numbers, but he is especially interested in really big numbers. Ivan thinks that a positive integer number x is really big if the difference between x and the sum of its digits (in decimal representation) is not less than s. To prove that these numbers may have different special properties, he wants to know how rare (or not rare) they are β€” in fact, he needs to calculate the quantity of really big numbers that are not greater than n.Ivan tried to do the calculations himself, but soon realized that it's too difficult for him. So he asked you to help him in calculations.InputThe first (and the only) line contains two integers n and s (1 ≀ n, s ≀ 1018).OutputPrint one integer β€” the quantity of really big numbers that are not greater than n.ExamplesInput12 1Output3Input25 20Output0Input10 9Output1NoteIn the first example numbers 10, 11 and 12 are really big.In the second example there are no really big numbers that are not greater than 25 (in fact, the first really big number is 30: 30 - 3 β‰₯ 20).In the third example 10 is the only really big number (10 - 1 β‰₯ 9).
Input12 1
Output3
1 second
256 megabytes
['binary search', 'brute force', 'dp', 'math', '*1600']
B. Makes And The Producttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter returning from the army Makes received a gift β€” an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i,  j,  k) (i < j < k), such that aiΒ·ajΒ·ak is minimum possible, are there in the array? Help him with it!InputThe first line of input contains a positive integer number nΒ (3 ≀ n ≀ 105) β€” the number of elements in array a. The second line contains n positive integer numbers aiΒ (1 ≀ ai ≀ 109) β€” the elements of a given array.OutputPrint one number β€” the quantity of triples (i,  j,  k) such that i,  j and k are pairwise distinct and aiΒ·ajΒ·ak is minimum possible.ExamplesInput41 1 1 1Output4Input51 3 2 3 4Output2Input61 3 3 1 3 2Output1NoteIn the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
Input41 1 1 1
Output4
2 seconds
256 megabytes
['combinatorics', 'implementation', 'math', 'sortings', '*1500']
A. Treasure Hunttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCaptain Bill the Hummingbird and his crew recieved an interesting challenge offer. Some stranger gave them a map, potion of teleportation and said that only this potion might help them to reach the treasure. Bottle with potion has two values x and y written on it. These values define four moves which can be performed using the potion: Map shows that the position of Captain Bill the Hummingbird is (x1, y1) and the position of the treasure is (x2, y2).You task is to tell Captain Bill the Hummingbird whether he should accept this challenge or decline. If it is possible for Captain to reach the treasure using the potion then output "YES", otherwise "NO" (without quotes).The potion can be used infinite amount of times.InputThe first line contains four integer numbers x1, y1, x2, y2 ( - 105 ≀ x1, y1, x2, y2 ≀ 105) β€” positions of Captain Bill the Hummingbird and treasure respectively.The second line contains two integer numbers x, y (1 ≀ x, y ≀ 105) β€” values on the potion bottle.OutputPrint "YES" if it is possible for Captain to reach the treasure using the potion, otherwise print "NO" (without quotes).ExamplesInput0 0 0 62 3OutputYESInput1 1 3 61 5OutputNONoteIn the first example there exists such sequence of moves: β€” the first type of move β€” the third type of move
Input0 0 0 62 3
OutputYES
1 second
256 megabytes
['implementation', 'math', 'number theory', '*1200']
B. Karen and Coffeetime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputTo stay woke and attentive during classes, Karen needs some coffee! Karen, a coffee aficionado, wants to know the optimal temperature for brewing the perfect cup of coffee. Indeed, she has spent some time reading several recipe books, including the universally acclaimed "The Art of the Covfefe".She knows n coffee recipes. The i-th recipe suggests that coffee should be brewed between li and ri degrees, inclusive, to achieve the optimal taste.Karen thinks that a temperature is admissible if at least k recipes recommend it.Karen has a rather fickle mind, and so she asks q questions. In each question, given that she only wants to prepare coffee with a temperature between a and b, inclusive, can you tell her how many admissible integer temperatures fall within the range?InputThe first line of input contains three integers, n, k (1 ≀ k ≀ n ≀ 200000), and q (1 ≀ q ≀ 200000), the number of recipes, the minimum number of recipes a certain temperature must be recommended by to be admissible, and the number of questions Karen has, respectively.The next n lines describe the recipes. Specifically, the i-th line among these contains two integers li and ri (1 ≀ li ≀ ri ≀ 200000), describing that the i-th recipe suggests that the coffee be brewed between li and ri degrees, inclusive.The next q lines describe the questions. Each of these lines contains a and b, (1 ≀ a ≀ b ≀ 200000), describing that she wants to know the number of admissible integer temperatures between a and b degrees, inclusive.OutputFor each question, output a single integer on a line by itself, the number of admissible integer temperatures between a and b degrees, inclusive.ExamplesInput3 2 491 9492 9797 9992 9493 9795 9690 100Output3304Input2 1 11 1200000 20000090 100Output0NoteIn the first test case, Karen knows 3 recipes. The first one recommends brewing the coffee between 91 and 94 degrees, inclusive. The second one recommends brewing the coffee between 92 and 97 degrees, inclusive. The third one recommends brewing the coffee between 97 and 99 degrees, inclusive. A temperature is admissible if at least 2 recipes recommend it.She asks 4 questions.In her first question, she wants to know the number of admissible integer temperatures between 92 and 94 degrees, inclusive. There are 3: 92, 93 and 94 degrees are all admissible.In her second question, she wants to know the number of admissible integer temperatures between 93 and 97 degrees, inclusive. There are 3: 93, 94 and 97 degrees are all admissible.In her third question, she wants to know the number of admissible integer temperatures between 95 and 96 degrees, inclusive. There are none.In her final question, she wants to know the number of admissible integer temperatures between 90 and 100 degrees, inclusive. There are 4: 92, 93, 94 and 97 degrees are all admissible.In the second test case, Karen knows 2 recipes. The first one, "wikiHow to make Cold Brew Coffee", recommends brewing the coffee at exactly 1 degree. The second one, "What good is coffee that isn't brewed at at least 36.3306 times the temperature of the surface of the sun?", recommends brewing the coffee at exactly 200000 degrees. A temperature is admissible if at least 1 recipe recommends it.In her first and only question, she wants to know the number of admissible integer temperatures that are actually reasonable. There are none.
Input3 2 491 9492 9797 9992 9493 9795 9690 100
Output3304
2.5 seconds
512 megabytes
['binary search', 'data structures', 'implementation', '*1400']
A. Karen and Morningtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKaren is getting ready for a new school day! It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.What is the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome?Remember that a palindrome is a string that reads the same forwards and backwards. For instance, 05:39 is not a palindrome, because 05:39 backwards is 93:50. On the other hand, 05:50 is a palindrome, because 05:50 backwards is 05:50.InputThe first and only line of input contains a single string in the format hh:mm (00 ≀  hh  ≀ 23, 00 ≀  mm  ≀ 59).OutputOutput a single integer on a line by itself, the minimum number of minutes she should sleep, such that, when she wakes up, the time is a palindrome.ExamplesInput05:39Output11Input13:31Output0Input23:59Output1NoteIn the first test case, the minimum number of minutes Karen should sleep for is 11. She can wake up at 05:50, when the time is a palindrome.In the second test case, Karen can wake up immediately, as the current time, 13:31, is already a palindrome.In the third test case, the minimum number of minutes Karen should sleep for is 1 minute. She can wake up at 00:00, when the time is a palindrome.
Input05:39
Output11
2 seconds
512 megabytes
['brute force', 'implementation', '*1000']
E. Karen and Neighborhoodtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt's been long after the events of the previous problems, and Karen has now moved on from student life and is looking to relocate to a new neighborhood. The neighborhood consists of n houses in a straight line, labelled 1 to n from left to right, all an equal distance apart.Everyone in this neighborhood loves peace and quiet. Because of this, whenever a new person moves into the neighborhood, he or she always chooses the house whose minimum distance to any occupied house is maximized. If there are multiple houses with the maximum possible minimum distance, he or she chooses the leftmost one.Note that the first person to arrive always moves into house 1.Karen is the k-th person to enter this neighborhood. If everyone, including herself, follows this rule, which house will she move into?InputThe first and only line of input contains two integers, n and k (1 ≀ k ≀ n ≀ 1018), describing the number of houses in the neighborhood, and that Karen was the k-th person to move in, respectively.OutputOutput a single integer on a line by itself, the label of the house Karen will move into.ExamplesInput6 4Output2Input39 3Output20NoteIn the first test case, there are 6 houses in the neighborhood, and Karen is the fourth person to move in: The first person moves into house 1. The second person moves into house 6. The third person moves into house 3. The fourth person moves into house 2. In the second test case, there are 39 houses in the neighborhood, and Karen is the third person to move in: The first person moves into house 1. The second person moves into house 39. The third person moves into house 20.
Input6 4
Output2
2 seconds
512 megabytes
['binary search', 'constructive algorithms', 'implementation', '*2900']
D. Karen and Cardstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKaren just got home from the supermarket, and is getting ready to go to sleep. After taking a shower and changing into her pajamas, she looked at her shelf and saw an album. Curious, she opened it and saw a trading card collection.She recalled that she used to play with those cards as a child, and, although she is now grown-up, she still wonders a few things about it.Each card has three characteristics: strength, defense and speed. The values of all characteristics of all cards are positive integers. The maximum possible strength any card can have is p, the maximum possible defense is q and the maximum possible speed is r.There are n cards in her collection. The i-th card has a strength ai, defense bi and speed ci, respectively.A card beats another card if at least two of its characteristics are strictly greater than the corresponding characteristics of the other card.She now wonders how many different cards can beat all the cards in her collection. Two cards are considered different if at least one of their characteristics have different values.InputThe first line of input contains four integers, n, p, q and r (1 ≀ n, p, q, r ≀ 500000), the number of cards in the collection, the maximum possible strength, the maximum possible defense, and the maximum possible speed, respectively.The next n lines each contain three integers. In particular, the i-th line contains ai, bi and ci (1 ≀ ai ≀ p, 1 ≀ bi ≀ q, 1 ≀ ci ≀ r), the strength, defense and speed of the i-th collection card, respectively.OutputOutput a single integer on a line by itself, the number of different cards that can beat all the cards in her collection.ExamplesInput3 4 4 52 2 51 3 44 1 1Output10Input5 10 10 101 1 11 1 11 1 11 1 11 1 1Output972NoteIn the first test case, the maximum possible strength is 4, the maximum possible defense is 4 and the maximum possible speed is 5. Karen has three cards: The first card has strength 2, defense 2 and speed 5. The second card has strength 1, defense 3 and speed 4. The third card has strength 4, defense 1 and speed 1. There are 10 cards that beat all the cards here: The card with strength 3, defense 3 and speed 5. The card with strength 3, defense 4 and speed 2. The card with strength 3, defense 4 and speed 3. The card with strength 3, defense 4 and speed 4. The card with strength 3, defense 4 and speed 5. The card with strength 4, defense 3 and speed 5. The card with strength 4, defense 4 and speed 2. The card with strength 4, defense 4 and speed 3. The card with strength 4, defense 4 and speed 4. The card with strength 4, defense 4 and speed 5. In the second test case, the maximum possible strength is 10, the maximum possible defense is 10 and the maximum possible speed is 10. Karen has five cards, all with strength 1, defense 1 and speed 1.Any of the 972 cards which have at least two characteristics greater than 1 can beat all of the cards in her collection.
Input3 4 4 52 2 51 3 44 1 1
Output10
2 seconds
512 megabytes
['binary search', 'combinatorics', 'data structures', 'geometry', '*2800']
C. Karen and Supermarkettime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOn the way home, Karen decided to stop by the supermarket to buy some groceries. She needs to buy a lot of goods, but since she is a student her budget is still quite limited. In fact, she can only spend up to b dollars.The supermarket sells n goods. The i-th good can be bought for ci dollars. Of course, each good can only be bought once.Lately, the supermarket has been trying to increase its business. Karen, being a loyal customer, was given n coupons. If Karen purchases the i-th good, she can use the i-th coupon to decrease its price by di. Of course, a coupon cannot be used without buying the corresponding good.There is, however, a constraint with the coupons. For all i β‰₯ 2, in order to use the i-th coupon, Karen must also use the xi-th coupon (which may mean using even more coupons to satisfy the requirement for that coupon).Karen wants to know the following. What is the maximum number of goods she can buy, without exceeding her budget b?InputThe first line of input contains two integers n and b (1 ≀ n ≀ 5000, 1 ≀ b ≀ 109), the number of goods in the store and the amount of money Karen has, respectively.The next n lines describe the items. Specifically: The i-th line among these starts with two integers, ci and di (1 ≀ di < ci ≀ 109), the price of the i-th good and the discount when using the coupon for the i-th good, respectively. If i β‰₯ 2, this is followed by another integer, xi (1 ≀ xi < i), denoting that the xi-th coupon must also be used before this coupon can be used. OutputOutput a single integer on a line by itself, the number of different goods Karen can buy, without exceeding her budget.ExamplesInput6 1610 910 5 112 2 120 18 310 2 32 1 5Output4Input5 103 13 1 13 1 23 1 33 1 4Output5NoteIn the first test case, Karen can purchase the following 4 items: Use the first coupon to buy the first item for 10 - 9 = 1 dollar. Use the third coupon to buy the third item for 12 - 2 = 10 dollars. Use the fourth coupon to buy the fourth item for 20 - 18 = 2 dollars. Buy the sixth item for 2 dollars. The total cost of these goods is 15, which falls within her budget. Note, for example, that she cannot use the coupon on the sixth item, because then she should have also used the fifth coupon to buy the fifth item, which she did not do here.In the second test case, Karen has enough money to use all the coupons and purchase everything.
Input6 1610 910 5 112 2 120 18 310 2 32 1 5
Output4
2 seconds
512 megabytes
['brute force', 'dp', 'trees', '*2400']
B. Karen and Testtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKaren has just arrived at school, and she has a math test today! The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?Since this number can be quite large, output only the non-negative remainder after dividing it by 109 + 7.InputThe first line of input contains a single integer n (1 ≀ n ≀ 200000), the number of numbers written on the first row.The next line contains n integers. Specifically, the i-th one among these is ai (1 ≀ ai ≀ 109), the i-th number on the first row.OutputOutput a single integer on a line by itself, the number on the final row after performing the process above.Since this number can be quite large, print only the non-negative remainder after dividing it by 109 + 7.ExamplesInput53 6 9 12 15Output36Input43 7 5 2Output1000000006NoteIn the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15.Karen performs the operations as follows: The non-negative remainder after dividing the final number by 109 + 7 is still 36, so this is the correct output.In the second test case, the numbers written on the first row are 3, 7, 5 and 2.Karen performs the operations as follows: The non-negative remainder after dividing the final number by 109 + 7 is 109 + 6, so this is the correct output.
Input53 6 9 12 15
Output36
2 seconds
512 megabytes
['brute force', 'combinatorics', 'constructive algorithms', 'math', '*2200']
A. Karen and Gametime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOn the way to school, Karen became fixated on the puzzle game on her phone! The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!InputThe first line of input contains two integers, n and m (1 ≀ n, m ≀ 100), the number of rows and the number of columns in the grid, respectively.The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≀ gi, j ≀ 500).OutputIf there is an error and it is actually not possible to beat the level, output a single integer -1.Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level.The next k lines should each contain one of the following, describing the moves in the order they must be done: row x, (1 ≀ x ≀ n) describing a move of the form "choose the x-th row". col x, (1 ≀ x ≀ m) describing a move of the form "choose the x-th column". If there are multiple optimal solutions, output any one of them.ExamplesInput3 52 2 2 3 20 0 0 1 01 1 1 2 1Output4row 1row 1col 4row 3Input3 30 0 00 1 00 0 0Output-1Input3 31 1 11 1 11 1 1Output3row 1row 2row 3NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level: In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level: Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3.
Input3 52 2 2 3 20 0 0 1 01 1 1 2 1
Output4row 1row 1col 4row 3
2 seconds
512 megabytes
['brute force', 'greedy', 'implementation', '*1700']
E. An unavoidable detour for hometime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThose unwilling to return home from a long journey, will be affected by the oddity of the snail and lose their way. Mayoi, the oddity's carrier, wouldn't like this to happen, but there's nothing to do with this before a cure is figured out. For now, she would only like to know the enormous number of possibilities to be faced with if someone gets lost.There are n towns in the region, numbered from 1 to n. The town numbered 1 is called the capital. The traffic network is formed by bidirectional roads connecting pairs of towns. No two roads connect the same pair of towns, and no road connects a town with itself. The time needed to travel through each of the roads is the same. Lost travelers will not be able to find out how the towns are connected, but the residents can help them by providing the following facts: Starting from each town other than the capital, the shortest path (i.e. the path passing through the minimum number of roads) to the capital exists, and is unique; Let li be the number of roads on the shortest path from town i to the capital, then li β‰₯ li - 1 holds for all 2 ≀ i ≀ n; For town i, the number of roads connected to it is denoted by di, which equals either 2 or 3. You are to count the number of different ways in which the towns are connected, and give the answer modulo 109 + 7. Two ways of connecting towns are considered different if a pair (u, v) (1 ≀ u, v ≀ n) exists such there is a road between towns u and v in one of them but not in the other.InputThe first line of input contains a positive integer n (3 ≀ n ≀ 50) β€” the number of towns.The second line contains n space-separated integers d1, d2, ..., dn (2 ≀ di ≀ 3) β€” the number of roads connected to towns 1, 2, ..., n, respectively. It is guaranteed that the sum of di over all i is even.OutputOutput one integer β€” the total number of different possible ways in which the towns are connected, modulo 109 + 7.ExamplesInput43 2 3 2Output1Input52 3 3 2 2Output2Input52 2 2 2 2Output2Input202 2 2 2 3 2 3 2 2 2 2 2 2 2 2 2 2 3 3 2Output82944NoteIn the first example, the following structure is the only one to satisfy the constraints, the distances from towns 2, 3, 4 to the capital are all 1. In the second example, the following two structures satisfy the constraints.
Input43 2 3 2
Output1
3 seconds
256 megabytes
['combinatorics', 'dp', 'graphs', 'shortest paths', '*2600']
D. An overnight dance in discothequetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it?The discotheque can be seen as an infinite xy-plane, in which there are a total of n dancers. Once someone starts moving around, they will move only inside their own movement range, which is a circular area Ci described by a center (xi, yi) and a radius ri. No two ranges' borders have more than one common point, that is for every pair (i, j) (1 ≀ i < j ≀ n) either ranges Ci and Cj are disjoint, or one of them is a subset of the other. Note that it's possible that two ranges' borders share a single common point, but no two dancers have exactly the same ranges.Tsukihi, being one of them, defines the spaciousness to be the area covered by an odd number of movement ranges of dancers who are moving. An example is shown below, with shaded regions representing the spaciousness if everyone moves at the same time. But no one keeps moving for the whole night after all, so the whole night's time is divided into two halves β€” before midnight and after midnight. Every dancer moves around in one half, while sitting down with friends in the other. The spaciousness of two halves are calculated separately and their sum should, of course, be as large as possible. The following figure shows an optimal solution to the example above. By different plans of who dances in the first half and who does in the other, different sums of spaciousness over two halves are achieved. You are to find the largest achievable value of this sum.InputThe first line of input contains a positive integer n (1 ≀ n ≀ 1 000) β€” the number of dancers.The following n lines each describes a dancer: the i-th line among them contains three space-separated integers xi, yi and ri ( - 106 ≀ xi, yi ≀ 106, 1 ≀ ri ≀ 106), describing a circular movement range centered at (xi, yi) with radius ri.OutputOutput one decimal number β€” the largest achievable sum of spaciousness over two halves of the night.The output is considered correct if it has a relative or absolute error of at most 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .ExamplesInput52 1 60 4 12 -1 31 -2 14 -1 1Output138.23007676Input80 0 10 0 20 0 30 0 40 0 50 0 60 0 70 0 8Output289.02652413NoteThe first sample corresponds to the illustrations in the legend.
Input52 1 60 4 12 -1 31 -2 14 -1 1
Output138.23007676
2 seconds
256 megabytes
['dfs and similar', 'dp', 'geometry', 'greedy', 'trees', '*2000']
C. An impassioned circulation of affectiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c β€” Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.InputThe first line of input contains a positive integer n (1 ≀ n ≀ 1 500) β€” the length of the garland.The second line contains n lowercase English letters s1s2... sn as a string β€” the initial colours of paper pieces on the garland.The third line contains a positive integer q (1 ≀ q ≀ 200 000) β€” the number of plans Nadeko has.The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≀ mi ≀ n) β€” the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci β€” Koyomi's possible favourite colour.OutputOutput q lines: for each work plan, output one line containing an integer β€” the largest Koyomity achievable after repainting the garland according to it.ExamplesInput6koyomi31 o4 o4 mOutput365Input15yamatonadeshiko101 a2 a3 a4 a5 a1 b2 b3 b4 b5 bOutput3457812345Input10aaaaaaaaaa210 b10 zOutput1010NoteIn the first sample, there are three plans: In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable; In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6; In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.
Input6koyomi31 o4 o4 m
Output365
2 seconds
256 megabytes
['brute force', 'dp', 'strings', 'two pointers', '*1600']
B. An express train to reveriestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.On that night, Sengoku constructed a permutation p1, p2, ..., pn of integers from 1 to n inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with n meteorids, colours of which being integer sequences a1, a2, ..., an and b1, b2, ..., bn respectively. Meteoroids' colours were also between 1 and n inclusive, and the two sequences were not identical, that is, at least one i (1 ≀ i ≀ n) exists, such that ai ≠ bi holds.Well, she almost had it all β€” each of the sequences a and b matched exactly n - 1 elements in Sengoku's permutation. In other words, there is exactly one i (1 ≀ i ≀ n) such that ai ≠ pi, and exactly one j (1 ≀ j ≀ n) such that bj ≠ pj.For now, Sengoku is able to recover the actual colour sequences a and b through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.InputThe first line of input contains a positive integer n (2 ≀ n ≀ 1 000) β€” the length of Sengoku's permutation, being the length of both meteor outbursts at the same time.The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ n) β€” the sequence of colours in the first meteor outburst.The third line contains n space-separated integers b1, b2, ..., bn (1 ≀ bi ≀ n) β€” the sequence of colours in the second meteor outburst. At least one i (1 ≀ i ≀ n) exists, such that ai ≠ bi holds.OutputOutput n space-separated integers p1, p2, ..., pn, denoting a possible permutation Sengoku could have had. If there are more than one possible answer, output any one of them.Input guarantees that such permutation exists.ExamplesInput51 2 3 4 31 2 5 4 5Output1 2 5 4 3Input54 4 2 3 15 4 5 3 1Output5 4 2 3 1Input41 1 3 41 4 3 4Output1 2 3 4NoteIn the first sample, both 1, 2, 5, 4, 3 and 1, 2, 3, 4, 5 are acceptable outputs.In the second sample, 5, 4, 2, 3, 1 is the only permutation to satisfy the constraints.
Input51 2 3 4 31 2 5 4 5
Output1 2 5 4 3
1 second
256 megabytes
['constructive algorithms', '*1300']
A. An abandoned sentiment from pasttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. Ever since, she tried to avoid contact with others, for fear that this secret might be noticed.To get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long time, but now Kaiki provides an opportunity.Hitagi's sequence a has a length of n. Lost elements in it are denoted by zeros. Kaiki provides another sequence b, whose length k equals the number of lost elements in a (i.e. the number of zeros). Hitagi is to replace each zero in a with an element from b so that each element in b should be used exactly once. Hitagi knows, however, that, apart from 0, no integer occurs in a and b more than once in total.If the resulting sequence is not an increasing sequence, then it has the power to recover Hitagi from the oddity. You are to determine whether this is possible, or Kaiki's sequence is just another fake. In other words, you should detect whether it is possible to replace each zero in a with an integer from b so that each integer from b is used exactly once, and the resulting sequence is not increasing.InputThe first line of input contains two space-separated positive integers n (2 ≀ n ≀ 100) and k (1 ≀ k ≀ n) β€” the lengths of sequence a and b respectively.The second line contains n space-separated integers a1, a2, ..., an (0 ≀ ai ≀ 200) β€” Hitagi's broken sequence with exactly k zero elements.The third line contains k space-separated integers b1, b2, ..., bk (1 ≀ bi ≀ 200) β€” the elements to fill into Hitagi's sequence.Input guarantees that apart from 0, no integer occurs in a and b more than once in total.OutputOutput "Yes" if it's possible to replace zeros in a with elements in b and make the resulting sequence not increasing, and "No" otherwise.ExamplesInput4 211 0 0 145 4OutputYesInput6 12 3 0 8 9 105OutputNoInput4 18 94 0 489OutputYesInput7 70 0 0 0 0 0 01 2 3 4 5 6 7OutputYesNoteIn the first sample: Sequence a is 11, 0, 0, 14. Two of the elements are lost, and the candidates in b are 5 and 4. There are two possible resulting sequences: 11, 5, 4, 14 and 11, 4, 5, 14, both of which fulfill the requirements. Thus the answer is "Yes". In the second sample, the only possible resulting sequence is 2, 3, 5, 8, 9, 10, which is an increasing sequence and therefore invalid.
Input4 211 0 0 145 4
OutputYes
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'sortings', '*900']
F. Bipartite Checkingtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph consisting of n vertices. Initially there are no edges in the graph. Also you are given q queries, each query either adds one undirected edge to the graph or removes it. After each query you have to check if the resulting graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color).InputThe first line contains two integers n and q (2 ≀ n, q ≀ 100000).Then q lines follow. ith line contains two numbers xi and yi (1 ≀ xi < yi ≀ n). These numbers describe ith query: if there is an edge between vertices xi and yi, then remove it, otherwise add it.OutputPrint q lines. ith line must contain YES if the graph is bipartite after ith query, and NO otherwise.ExampleInput3 52 31 31 21 21 2OutputYESYESNOYESNO
Input3 52 31 31 21 21 2
OutputYESYESNOYESNO
6 seconds
256 megabytes
['data structures', 'dsu', 'graphs', '*2500']
E. Army Creationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you might remember from our previous rounds, Vova really likes computer games. Now he is playing a strategy game known as Rage of Empires.In the game Vova can hire n different warriors; ith warrior has the type ai. Vova wants to create a balanced army hiring some subset of warriors. An army is called balanced if for each type of warrior present in the game there are not more than k warriors of this type in the army. Of course, Vova wants his army to be as large as possible.To make things more complicated, Vova has to consider q different plans of creating his army. ith plan allows him to hire only warriors whose numbers are not less than li and not greater than ri.Help Vova to determine the largest size of a balanced army for each plan.Be aware that the plans are given in a modified way. See input section for details.InputThe first line contains two integers n and k (1 ≀ n, k ≀ 100000).The second line contains n integers a1, a2, ... an (1 ≀ ai ≀ 100000).The third line contains one integer q (1 ≀ q ≀ 100000).Then q lines follow. ith line contains two numbers xi and yi which represent ith plan (1 ≀ xi, yi ≀ n).You have to keep track of the answer to the last plan (let's call it last). In the beginning last = 0. Then to restore values of li and ri for the ith plan, you have to do the following: li = ((xi + last)Β modΒ n) + 1; ri = ((yi + last)Β modΒ n) + 1; If li > ri, swap li and ri. OutputPrint q numbers. ith number must be equal to the maximum size of a balanced army when considering ith plan.ExampleInput6 21 1 1 2 2 251 64 31 12 62 6Output24132NoteIn the first example the real plans are: 1Β 2 1Β 6 6Β 6 2Β 4 4Β 6
Input6 21 1 1 2 2 251 64 31 12 62 6
Output24132
2 seconds
256 megabytes
['binary search', 'data structures', '*2200']
D. Two Melodiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice is a beginner composer and now she is ready to create another masterpiece. And not even the single one but two at the same time! Alice has a sheet with n notes written on it. She wants to take two such non-empty non-intersecting subsequences that both of them form a melody and sum of their lengths is maximal.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.Subsequence forms a melody when each two adjacent notes either differs by 1 or are congruent modulo 7.You should write a program which will calculate maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.InputThe first line contains one integer number n (2 ≀ n ≀ 5000).The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 105) β€” notes written on a sheet.OutputPrint maximum sum of lengths of such two non-empty non-intersecting subsequences that both of them form a melody.ExamplesInput41 2 4 5Output4Input662 22 60 61 48 49Output5NoteIn the first example subsequences [1, 2] and [4, 5] give length 4 in total.In the second example subsequences [62, 48, 49] and [60, 61] give length 5 in total. If you choose subsequence [62, 61] in the first place then the second melody will have maximum length 2, that gives the result of 4, which is not maximal.
Input41 2 4 5
Output4
2 seconds
256 megabytes
['dp', 'flows', '*2600']
C. The Tag Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last.InputThe first line contains two integer numbers n and x (2 ≀ n ≀ 2Β·105, 2 ≀ x ≀ n).Each of the next n - 1 lines contains two integer numbers a and b (1 ≀ a, b ≀ n) β€” edges of the tree. It is guaranteed that the edges form a valid tree.OutputPrint the total number of moves Alice and Bob will make.ExamplesInput4 31 22 32 4Output4Input5 21 22 33 42 5Output6NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4
Input4 31 22 32 4
Output4
1 second
256 megabytes
['dfs and similar', 'graphs', '*1700']
B. The Golden Agetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputUnlucky year in Berland is such a year that its number n can be represented as n = xa + yb, where a and b are non-negative integer numbers. For example, if x = 2 and y = 3 then the years 4 and 17 are unlucky (4 = 20 + 31, 17 = 23 + 32 = 24 + 30) and year 18 isn't unlucky as there is no such representation for it.Such interval of years that there are no unlucky years in it is called The Golden Age.You should write a program which will find maximum length of The Golden Age which starts no earlier than the year l and ends no later than the year r. If all years in the interval [l, r] are unlucky then the answer is 0.InputThe first line contains four integer numbers x, y, l and r (2 ≀ x, y ≀ 1018, 1 ≀ l ≀ r ≀ 1018).OutputPrint the maximum length of The Golden Age within the interval [l, r].If all years in the interval [l, r] are unlucky then print 0.ExamplesInput2 3 1 10Output1Input3 5 10 22Output8Input2 3 3 5Output0NoteIn the first example the unlucky years are 2, 3, 4, 5, 7, 9 and 10. So maximum length of The Golden Age is achived in the intervals [1, 1], [6, 6] and [8, 8].In the second example the longest Golden Age is the interval [15, 22].
Input2 3 1 10
Output1
1 second
256 megabytes
['brute force', 'math', '*1800']