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
|
---|---|---|---|---|---|
H. Endless Roses Most Beautifultime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady decided to buy roses for his girlfriend.A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the same color. Arkady wants to buy exactly k roses. For each rose in the shop he knows its beauty and color: the beauty of the i-th rose is bi, and its color is ci ('W' for a white rose, 'O' for an orange rose and 'R' for a red rose). Compute the maximum possible total beauty of a bouquet of k roses satisfying the constraints above or determine that it is not possible to make such a bouquet.InputThe first line contains two integers n and k (1ββ€βkββ€βnββ€β200β000) β the number of roses in the show and the number of roses Arkady wants to buy.The second line contains a sequence of integers b1,βb2,β...,βbn (1ββ€βbiββ€β10β000), where bi equals the beauty of the i-th rose.The third line contains a string c of length n, consisting of uppercase English letters 'W', 'O' and 'R', where ci denotes the color of the i-th rose: 'W' denotes white, 'O' Β β orange, 'R' β red.OutputPrint the maximum possible total beauty of a bouquet of k roses that satisfies the constraints above. If it is not possible to make a single such bouquet, print -1.ExamplesInput5 34 3 4 1 6RROWWOutput11Input5 210 20 14 20 11RRRRROutput-1Input11 55 6 3 2 3 4 7 5 4 5 6RWOORWORROWOutput28NoteIn the first example Arkady wants to buy 3 roses. He can, for example, buy both red roses (their indices are 1 and 2, and their total beauty is 7) and the only orange rose (its index is 3, its beauty is 4). This way the total beauty of the bouquet is 11. In the second example Arkady can not buy a bouquet because all roses have the same color. | Input5 34 3 4 1 6RROWW | Output11 | 1 second | 256 megabytes | ['*2200'] |
G. Large Bouquetstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.Determine the maximum possible number of large bouquets Vasya can make. InputThe first line contains a single positive integer n (1ββ€βnββ€β105) β the number of initial bouquets.The second line contains a sequence of integers a1,βa2,β...,βan (1ββ€βaiββ€β106) β the number of flowers in each of the initial bouquets.OutputPrint the maximum number of large bouquets Vasya can make. ExamplesInput52 3 4 2 7Output2Input62 2 6 8 6 12Output0Input311 4 10Output1NoteIn the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme. In the second example it is not possible to form a single bouquet with odd number of flowers.In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11β+β4β+β10β=β25. | Input52 3 4 2 7 | Output2 | 1 second | 256 megabytes | ['*1500'] |
F. Mobile Communicationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sum of p rubles is charged from Arkady's mobile phone account every day in the morning. Among the following m days, there are n days when Arkady will top up the account: in the day di he will deposit ti rubles on his mobile phone account. Arkady will always top up the account before the daily payment will be done. There will be no other payments nor tops up in the following m days.Determine the number of days starting from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment (i.Β e. in evening). Initially the account's balance is zero rubles.InputThe first line contains three integers n, p and m (1ββ€βnββ€β100β000, 1ββ€βpββ€β109, 1ββ€βmββ€β109, nββ€βm) β the number of days Arkady will top up the account, the amount of the daily payment, and the number of days you should check.The i-th of the following n lines contains two integers di and ti (1ββ€βdiββ€βm, 1ββ€βtiββ€β109) β the index of the day when Arkady will make the i-th top up, and the amount he will deposit on this day. It is guaranteed that the indices of the days are distinct and are given in increasing order, i.Β e. diβ>βdiβ-β1 for all i from 2 to n.OutputPrint the number of days from the 1-st to the m-th such that the account will have a negative amount on it after the daily payment.ExamplesInput3 6 72 134 207 9Output3Input5 4 10010 7015 7621 1230 10067 85Output26NoteIn the first example the balance will change as following (remember, initially the balance is zero): in the first day 6 rubles will be charged, the balance in the evening will be equal to β-β6; in the second day Arkady will deposit 13 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 1; in the third day 6 rubles will be charged, the balance in the evening will be equal to β-β5; in the fourth day Arkady will deposit 20 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 9; in the fifth day 6 rubles will be charged, the balance in the evening will be equal to 3; in the sixth day 6 rubles will be charged, the balance in the evening will be equal to β-β3; in the seventh day Arkady will deposit 9 rubles, then 6 rubles will be charged, the balance in the evening will be equal to 0. Thus, in the end of the first, third and sixth days the balance will be negative in the end of the day. | Input3 6 72 134 207 9 | Output3 | 1 second | 256 megabytes | ['*2000'] |
E. Merge Equal Elementstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of positive integers a1,βa2,β...,βan. While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a single integer xβ+β1 on their place. This way the number of elements in the sequence is decreased by 1 on each step. You stop performing the operation when there is no pair of equal consecutive elements.For example, if the initial sequence is [5,β2,β1,β1,β2,β2], then after the first operation you get [5,β2,β2,β2,β2], after the second β [5,β3,β2,β2], after the third β [5,β3,β3], and finally after the fourth you get [5,β4]. After that there are no equal consecutive elements left in the sequence, so you stop the process.Determine the final sequence after you stop performing the operation.InputThe first line contains a single integer n (2ββ€βnββ€β2Β·105) β the number of elements in the sequence.The second line contains the sequence of integers a1,βa2,β...,βan (1ββ€βaiββ€β109).OutputIn the first line print a single integer k β the number of elements in the sequence after you stop performing the operation. In the second line print k integersΒ β the sequence after you stop performing the operation.ExamplesInput65 2 1 1 2 2Output25 4 Input41000000000 1000000000 1000000000 1000000000Output11000000002 Input74 10 22 11 12 5 6Output74 10 22 11 12 5 6 NoteThe first example is described in the statements.In the second example the initial sequence is [1000000000,β1000000000,β1000000000,β1000000000]. After the first operation the sequence is equal to [1000000001,β1000000000,β1000000000]. After the second operation the sequence is [1000000001,β1000000001]. After the third operation the sequence is [1000000002].In the third example there are no two equal consecutive elements initially, so the sequence does not change. | Input65 2 1 1 2 2 | Output25 4 | 1 second | 256 megabytes | ['constructive algorithms', 'data structures', '*1900'] |
D. Choose Placetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right. Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the places are shown on the picture: Here, the desks in the top row are the closest to the blackboard, while the desks in the bottom row are the furthest from the blackboard.You are given a plan of the class, where '*' denotes an occupied place, '.' denotes a vacant place, and the aisles are denoted by '-'. Find any of the most convenient vacant places for Petya.InputThe input consists of 6 lines. Each line describes one row of desks, starting from the closest to the blackboard. Each line is given in the following format: two characters, each is '*' or '.' β the description of the left desk in the current row; a character '-' β the aisle; two characters, each is '*' or '.' β the description of the center desk in the current row; a character '-' β the aisle; two characters, each is '*' or '.' β the description of the right desk in the current row. So, the length of each of the six lines is 8.It is guaranteed that there is at least one vacant place in the classroom.OutputPrint the plan of the classroom after Petya takes one of the most convenient for him places. Mark this place with the letter 'P'. There should be exactly one letter 'P' in the plan. Petya can only take a vacant place. In all other places the output should coincide with the input.If there are multiple answers, print any.ExamplesInput..-**-....-**-....-..-....-..-....-..-....-..-..Output..-**-....-**-....-..-....-P.-....-..-....-..-..Input**-**-****-**-**..-**-.***-**-**..-..-....-**-..Output**-**-****-**-**..-**-.***-**-**..-P.-....-**-..Input**-**-*.*.-*.-****-**-****-**-**..-..-....-**-..Output**-**-*.*.-*P-****-**-****-**-**..-..-....-**-..NoteIn the first example the maximum convenience is 3.In the second example the maximum convenience is 2.In the third example the maximum convenience is 4. | Input..-**-....-**-....-..-....-..-....-..-....-..-.. | Output..-**-....-**-....-..-....-P.-....-..-....-..-.. | 1 second | 256 megabytes | ['*1600'] |
C. Is This a Zebra?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means that the corresponding column is black.You think that this photo can contain a zebra. In this case the whole photo should consist of several (possibly, only one) alternating black and white stripes of equal width. For example, the photo [0,β0,β0,β1,β1,β1,β0,β0,β0] can be a photo of zebra, while the photo [0,β0,β0,β1,β1,β1,β1] can not, because the width of the black stripe is 3, while the width of the white stripe is 4. Can the given photo be a photo of zebra or not?InputThe first line contains a single integer n (1ββ€βnββ€β100β000) β the width of the photo.The second line contains a sequence of integers a1,βa2,β...,βan (0ββ€βaiββ€β1) β the description of the photo. If ai is zero, the i-th column is all black. If ai is one, then the i-th column is all white.OutputIf the photo can be a photo of zebra, print "YES" (without quotes). Otherwise, print "NO".You can print each letter in any case (upper or lower).ExamplesInput90 0 0 1 1 1 0 0 0OutputYESInput70 0 0 1 1 1 1OutputNOInput51 1 1 1 1OutputYESInput81 1 1 0 0 0 1 1OutputNOInput91 1 0 1 1 0 1 1 0OutputNONoteThe first two examples are described in the statements.In the third example all pixels are white, so the photo can be a photo of zebra.In the fourth example the width of the first stripe is equal to three (white color), the width of the second stripe is equal to three (black), and the width of the third stripe is equal to two (white). Thus, not all stripes have equal length, so this photo is not a photo of zebra. | Input90 0 0 1 1 1 0 0 0 | OutputYES | 1 second | 256 megabytes | ['implementation', '*1700'] |
B. Add Pointstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m β the smallest number of points you should add on the line to make the distances between all neighboring points equal. InputThe first line contains a single integer n (3ββ€βnββ€β100β000) β the number of points.The second line contains a sequence of integers x1,βx2,β...,βxn (β-β109ββ€βxiββ€β109) β the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.OutputPrint a single integer m β the smallest number of points you should add on the line to make the distances between all neighboring points equal. ExamplesInput3-5 10 5Output1Input6100 200 400 300 600 500Output0Input410 9 0 -1Output8NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything. | Input3-5 10 5 | Output1 | 1 second | 256 megabytes | ['*1800'] |
A. 2-3-numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA positive integer is called a 2-3-integer, if it is equal to 2xΒ·3y for some non-negative integers x and y. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 β are 2-3 integers, while 5, 10, 21 and 120 are not.Print the number of 2-3-integers on the given segment [l,βr], i.Β e. the number of sich 2-3-integers t that lββ€βtββ€βr.InputThe only line contains two integers l and r (1ββ€βlββ€βrββ€β2Β·109).OutputPrint a single integer the number of 2-3-integers on the segment [l,βr].ExamplesInput1 10Output7Input100 200Output5Input1 2000000000Output326NoteIn the first example the 2-3-integers are 1, 2, 3, 4, 6, 8 and 9.In the second example the 2-3-integers are 108, 128, 144, 162 and 192. | Input1 10 | Output7 | 1 second | 256 megabytes | ['implementation', 'math', '*1300'] |
F. Parametric Circulationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova has recently learned what a circulaton in a graph is. Recall the definition: let G = (V, E) be a directed graph. A circulation f is such a collection of non-negative real numbers f_e (e \in E), that for each vertex v \in V the following conservation condition holds:\sum\limits_{e \in \delta^{-}(v)} f_e = \sum\limits_{e \in \delta^{+}(v)} f_ewhere \delta^{+}(v) is the set of edges that end in the vertex v, and \delta^{-}(v) is the set of edges that start in the vertex v. In other words, for each vertex the total incoming flow should be equal to the total outcoming flow.Let a lr-circulation be such a circulation f that for each edge the condition l_e \leq f_e \leq r_e holds, where l_e and r_e for each edge e \in E are two non-negative real numbers denoting the lower and upper bounds on the value of the circulation on this edge e.Vova can't stop thinking about applications of a new topic. Right now he thinks about the following natural question: let the graph be fixed, and each value l_e and r_e be a linear function of a real variable t:l_e(t) = a_e t + b_e r_e(t) = c_e t + d_eNote that t is the same for all edges.Let t be chosen at random from uniform distribution on a segment [0, 1]. What is the probability of existence of lr-circulation in the graph?InputThe first line contains two integers n, m (1 \leq n \leq 1000, 1 \leq m \leq 2000).Each of the next m lines describes edges of the graph in the format u_e, v_e, a_e, b_e, c_e, d_e (1 \leq u_e, v_e \leq n, -10^4 \leq a_e, c_e \leq 10^4, 0 \leq b_e, d_e \leq 10^4), where u_e and v_e are the startpoint and the endpoint of the edge e, and the remaining 4 integers describe the linear functions for the upper and lower bound of circulation.It is guaranteed that for any t \in [0, 1] and for any edge e \in E the following condition holds 0 \leq l_e(t) \leq r_e(t) \leq 10^4.OutputPrint a single real integer β the probability of existence of lr-circulation in the graph, given that t is chosen uniformly at random from the segment [0, 1]. Your answer is considered correct if its absolute difference from jury's answer is not greater than 10^{-6}.ExampleInput3 31 2 0 3 -4 72 3 -2 5 1 63 1 0 4 0 4Output0.25NoteIn the first example the conservation condition allows only circulations with equal values f_e for all three edges. The value of circulation on the last edge should be 4 whatever t is chosen, so the probability isP(4 \in [3, -4t + 7]~~\&~~4 \in [-2t + 5, t + 6]) = 0.25 | Input3 31 2 0 3 -4 72 3 -2 5 1 63 1 0 4 0 4 | Output0.25 | 2 seconds | 256 megabytes | ['binary search', 'flows', '*3100'] |
E. May Holidaystime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's May in Flatland, and there are m days in this month. Despite the fact that May Holidays are canceled long time ago, employees of some software company still have a habit of taking short or long vacations in May.Of course, not all managers of the company like this. There are n employees in the company that form a tree-like structure of subordination: each employee has a unique integer id i between 1 and n, and each employee with id i (except the head manager whose id is 1) has exactly one direct manager with id p_i. The structure of subordination is not cyclic, i.e. if we start moving from any employee to his direct manager, then we will eventually reach the head manager. We define that an employee u is a subordinate of an employee v, if v is a direct manager of u, or the direct manager of u is a subordinate of v. Let s_i be the number of subordinates the i-th employee has (for example, s_1 = n - 1, because all employees except himself are subordinates of the head manager).Each employee i has a bearing limit of t_i, which is an integer between 0 and s_i. It denotes the maximum number of the subordinates of the i-th employee being on vacation at the same moment that he can bear. If at some moment strictly more than t_i subordinates of the i-th employee are on vacation, and the i-th employee himself is not on a vacation, he becomes displeased.In each of the m days of May exactly one event of the following two types happens: either one employee leaves on a vacation at the beginning of the day, or one employee returns from a vacation in the beginning of the day. You know the sequence of events in the following m days. Your task is to compute for each of the m days the number of displeased employees on that day.InputThe first line contains two integers n and m (2 \leq n, m \leq 10^5) β the number of employees in the company and the number of days in May.The second line contains n - 1 integers p_2, p_3, \ldots, p_n (1 \leq p_i \leq n), denoting the direct managers of employees.The third line contains n integers t_1, t_2, \ldots, t_n (0 \leq t_i \leq s_i), denoting the bearing limits of empoyees.The fourth line contains m integers q_1, q_2, \ldots, q_m (1 \leq |q_i| \leq n, q_i \ne 0), denoting the events. If q_i is positive, then the employee with id q_i leaves for a vacation starting from this day, if q_i is negative, then the employee -q_i returns from a vacation starting from this day. In the beginning of May no employee is on vacation. It is guaranteed that if some employee leaves for a vacation, he is not on a vacation at the moment and vice versa.OutputPrint a sequence of m integers a_1, a_2, \ldots, a_m, where a_i is the number of displeased employees on the i-th day.ExamplesInput7 84 5 1 1 5 50 0 0 1 2 0 02 6 3 7 -2 4 -3 1Output1 1 1 2 2 2 1 0Input5 61 2 3 44 0 0 1 01 5 2 3 -5 -1Output0 2 1 0 0 0NoteIn the first sample test after employee with id 2 leaves for a vacation at the first day, the head manager with id 1 becomes displeased as he does not want any of his subordinates to go for a vacation. At the fourth day employee with id 5 becomes displeased as his last remaining employee with id 7 leaves for a vacation. At the fifth day employee with id 2 returns from the vacation, but it does not affect the number of displeased employees as the employees 5 and 1 are still displeased. At the sixth day employee with id 3 returns back from the vacation, preventing the employee with id 5 from being displeased and at the last day the head manager with id 1 leaves for a vacation, leaving the company without the displeased people at all. | Input7 84 5 1 1 5 50 0 0 1 2 0 02 6 3 7 -2 4 -3 1 | Output1 1 1 2 2 2 1 0 | 5 seconds | 256 megabytes | ['data structures', 'trees', '*2900'] |
D. Aztec Catacombstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIndiana Jones found ancient Aztec catacombs containing a golden idol. The catacombs consists of n caves. Each pair of caves is connected with a two-way corridor that can be opened or closed. The entrance to the catacombs is in the cave 1, the idol and the exit are in the cave n.When Indiana goes from a cave x to a cave y using an open corridor, all corridors connected to the cave x change their state: all open corridors become closed, all closed corridors become open. Indiana wants to go from cave 1 to cave n going through as small number of corridors as possible. Help him find the optimal path, or determine that it is impossible to get out of catacombs.InputThe first line contains two integers n and m (2 \leq n \leq 3\cdot 10^5, 0 \leq m \leq 3 \cdot 10^5)Β β the number of caves and the number of open corridors at the initial moment.The next m lines describe the open corridors. The i-th of these lines contains two integers u_i and v_i (1 \leq u_i, v_i \leq n, u_i \neq v_i)Β β the caves connected by the i-th open corridor. It is guaranteed that each unordered pair of caves is presented at most once.OutputIf there is a path to exit, in the first line print a single integer kΒ β the minimum number of corridors Indians should pass through (1 \leq k \leq 10^6). In the second line print k+1 integers x_0, \ldots, x_kΒ β the number of caves in the order Indiana should visit them. The sequence x_0, \ldots, x_k should satisfy the following: x_0 = 1, x_k = n; for each i from 1 to k the corridor from x_{i - 1} to x_i should be open at the moment Indiana walks along this corridor.If there is no path, print a single integer -1.We can show that if there is a path, there is a path consisting of no more than 10^6 corridors.ExamplesInput4 41 22 31 33 4Output21 3 4 Input4 21 22 3Output41 2 3 1 4 | Input4 41 22 31 33 4 | Output21 3 4 | 2 seconds | 256 megabytes | ['constructive algorithms', '*2600'] |
C. Big Secrettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitya has learned that the answer for The Ultimate Question of Life, the Universe, and Everything is not the integer 54 42, but an increasing integer sequence a_1, \ldots, a_n. In order to not reveal the secret earlier than needed, Vitya encrypted the answer and obtained the sequence b_1, \ldots, b_n using the following rules: b_1 = a_1; b_i = a_i \oplus a_{i - 1} for all i from 2 to n, where x \oplus y is the bitwise XOR of x and y. It is easy to see that the original sequence can be obtained using the rule a_i = b_1 \oplus \ldots \oplus b_i.However, some time later Vitya discovered that the integers b_i in the cypher got shuffled, and it can happen that when decrypted using the rule mentioned above, it can produce a sequence that is not increasing. In order to save his reputation in the scientific community, Vasya decided to find some permutation of integers b_i so that the sequence a_i = b_1 \oplus \ldots \oplus b_i is strictly increasing. Help him find such a permutation or determine that it is impossible.InputThe first line contains a single integer n (1 \leq n \leq 10^5).The second line contains n integers b_1, \ldots, b_n (1 \leq b_i < 2^{60}).OutputIf there are no valid permutations, print a single line containing "No".Otherwise in the first line print the word "Yes", and in the second line print integers b'_1, \ldots, b'_nΒ β a valid permutation of integers b_i. The unordered multisets \{b_1, \ldots, b_n\} and \{b'_1, \ldots, b'_n\} should be equal, i.Β e. for each integer x the number of occurrences of x in the first multiset should be equal to the number of occurrences of x in the second multiset. Apart from this, the sequence a_i = b'_1 \oplus \ldots \oplus b'_i should be strictly increasing.If there are multiple answers, print any of them.ExamplesInput31 2 3OutputNoInput64 7 7 12 31 61OutputYes4 12 7 31 7 61 NoteIn the first example no permutation is valid.In the second example the given answer lead to the sequence a_1 = 4, a_2 = 8, a_3 = 15, a_4 = 16, a_5 = 23, a_6 = 42. | Input31 2 3 | OutputNo | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*2200'] |
B. Resource Distributiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne department of some software company has n servers of different specifications. Servers are indexed with consecutive integers from 1 to n. Suppose that the specifications of the j-th server may be expressed with a single integer number c_j of artificial resource units.In order for production to work, it is needed to deploy two services S_1 and S_2 to process incoming requests using the servers of the department. Processing of incoming requests of service S_i takes x_i resource units.The described situation happens in an advanced company, that is why each service may be deployed using not only one server, but several servers simultaneously. If service S_i is deployed using k_i servers, then the load is divided equally between these servers and each server requires only x_i / k_i (that may be a fractional number) resource units.Each server may be left unused at all, or be used for deploying exactly one of the services (but not for two of them simultaneously). The service should not use more resources than the server provides.Determine if it is possible to deploy both services using the given servers, and if yes, determine which servers should be used for deploying each of the services.InputThe first line contains three integers n, x_1, x_2 (2 \leq n \leq 300\,000, 1 \leq x_1, x_2 \leq 10^9)Β β the number of servers that the department may use, and resource units requirements for each of the services.The second line contains n space-separated integers c_1, c_2, \ldots, c_n (1 \leq c_i \leq 10^9)Β β the number of resource units provided by each of the servers.OutputIf it is impossible to deploy both services using the given servers, print the only word "No" (without the quotes).Otherwise print the word "Yes" (without the quotes). In the second line print two integers k_1 and k_2 (1 \leq k_1, k_2 \leq n)Β β the number of servers used for each of the services.In the third line print k_1 integers, the indices of the servers that will be used for the first service.In the fourth line print k_2 integers, the indices of the servers that will be used for the second service.No index may appear twice among the indices you print in the last two lines. If there are several possible answers, it is allowed to print any of them.ExamplesInput6 8 163 5 2 9 8 7OutputYes3 21 2 65 4Input4 20 3221 11 11 12OutputYes1 312 3 4Input4 11 325 5 16 16OutputNoInput5 12 207 8 4 11 9OutputNoNoteIn the first sample test each of the servers 1, 2 and 6 will will provide 8 / 3 = 2.(6) resource units and each of the servers 5, 4 will provide 16 / 2 = 8 resource units.In the second sample test the first server will provide 20 resource units and each of the remaining servers will provide 32 / 3 = 10.(6) resource units. | Input6 8 163 5 2 9 8 7 | OutputYes3 21 2 65 4 | 2 seconds | 256 megabytes | ['binary search', 'implementation', 'sortings', '*1700'] |
A. Stairs and Elevatorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height n and width m. We can denote sections with pairs of integers (i, j), where i is the floor, and j is the section number on the floor.The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections (1, x), (2, x), \ldots, (n, x) for some x between 1 and m. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to v floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.You are to process q queries. Each query is a question "what is the minimum time needed to go from a room in section (x_1, y_1) to a room in section (x_2, y_2)?"InputThe first line contains five integers n, m, c_l, c_e, v (2 \leq n, m \leq 10^8, 0 \leq c_l, c_e \leq 10^5, 1 \leq c_l + c_e \leq m - 1, 1 \leq v \leq n - 1)Β β the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively.The second line contains c_l integers l_1, \ldots, l_{c_l} in increasing order (1 \leq l_i \leq m), denoting the positions of the stairs. If c_l = 0, the second line is empty.The third line contains c_e integers e_1, \ldots, e_{c_e} in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers l_i and e_i are distinct.The fourth line contains a single integer q (1 \leq q \leq 10^5)Β β the number of queries.The next q lines describe queries. Each of these lines contains four integers x_1, y_1, x_2, y_2 (1 \leq x_1, x_2 \leq n, 1 \leq y_1, y_2 \leq m)Β β the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i.Β e. y_1 and y_2 are not among l_i and e_i.OutputPrint q integers, one per lineΒ β the answers for the queries.ExampleInput5 6 1 1 32531 1 5 61 3 5 43 3 5 3Output754NoteIn the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2. | Input5 6 1 1 32531 1 5 61 3 5 43 3 5 3 | Output754 | 2 seconds | 256 megabytes | ['binary search', '*1600'] |
F. Minimal Subset Differencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe call a positive integer x a k-beautiful integer if and only if it is possible to split the multiset of its digits in the decimal representation into two subsets such that the difference between the sum of digits in one subset and the sum of digits in the other subset is less than or equal to k. Each digit should belong to exactly one subset after the split.There are n queries for you. Each query is described with three integers l, r and k, which mean that you are asked how many integers x between l and r (inclusive) are k-beautiful.InputThe first line contains a single integer n (1ββ€βnββ€β5Β·104), indicating the number of queries.Each of the next n lines describes a query, containing three integers l, r and k (1ββ€βlββ€βrββ€β1018, 0ββ€βkββ€β9).OutputFor each query print a single numberΒ β the answer to the query.ExamplesInput101 100 01 100 11 100 21 100 31 100 41 100 51 100 61 100 71 100 81 100 9Output92844587080889498100Input101 1000 01 1000 11 1000 21 1000 31 1000 41 1000 51 1000 61 1000 71 1000 81 1000 9Output1353805737218309069559839961000NoteIf 1ββ€βxββ€β9, integer x is k-beautiful if and only if xββ€βk.If 10ββ€βxββ€β99, integer xβ=β10aβ+βb is k-beautiful if and only if |aβ-βb|ββ€βk, where a and b are integers between 0 and 9, inclusive.100 is k-beautiful if and only if kββ₯β1. | Input101 100 01 100 11 100 21 100 31 100 41 100 51 100 61 100 71 100 81 100 9 | Output92844587080889498100 | 3 seconds | 256 megabytes | ['dp', '*3200'] |
E. Wardrobetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOlya wants to buy a custom wardrobe. It should have n boxes with heights a1,βa2,β...,βan, stacked one on another in some order. In other words, we can represent each box as a vertical segment of length ai, and all these segments should form a single segment from 0 to without any overlaps.Some of the boxes are important (in this case biβ=β1), others are not (then biβ=β0). Olya defines the convenience of the wardrobe as the number of important boxes such that their bottom edge is located between the heights l and r, inclusive.You are given information about heights of the boxes and their importance. Compute the maximum possible convenience of the wardrobe if you can reorder the boxes arbitrarily.InputThe first line contains three integers n, l and r (1ββ€βnββ€β10β000, 0ββ€βlββ€βrββ€β10β000)Β β the number of boxes, the lowest and the highest heights for a bottom edge of an important box to be counted in convenience.The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β10β000)Β β the heights of the boxes. It is guaranteed that the sum of height of all boxes (i.Β e. the height of the wardrobe) does not exceed 10β000: Olya is not very tall and will not be able to reach any higher.The second line contains n integers b1,βb2,β...,βbn (0ββ€βbiββ€β1), where bi equals 1 if the i-th box is important, and 0 otherwise.OutputPrint a single integerΒ β the maximum possible convenience of the wardrobe.ExamplesInput5 3 63 2 5 1 21 1 0 1 0Output2Input2 2 53 61 1Output1NoteIn the first example you can, for example, first put an unimportant box of height 2, then put an important boxes of sizes 1, 3 and 2, in this order, and then the remaining unimportant boxes. The convenience is equal to 2, because the bottom edges of important boxes of sizes 3 and 2 fall into the range [3,β6].In the second example you have to put the short box under the tall box. | Input5 3 63 2 5 1 21 1 0 1 0 | Output2 | 1 second | 256 megabytes | ['dp', 'greedy', '*2700'] |
D. Contact ATCtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady the air traffic controller is now working with n planes in the air. All planes move along a straight coordinate axis with Arkady's station being at point 0 on it. The i-th plane, small enough to be represented by a point, currently has a coordinate of xi and is moving with speed vi. It's guaranteed that xiΒ·viβ<β0, i.e., all planes are moving towards the station.Occasionally, the planes are affected by winds. With a wind of speed vwind (not necessarily positive or integral), the speed of the i-th plane becomes viβ+βvwind.According to weather report, the current wind has a steady speed falling inside the range [β-βw,βw] (inclusive), but the exact value cannot be measured accurately since this value is rather small β smaller than the absolute value of speed of any plane.Each plane should contact Arkady at the exact moment it passes above his station. And you are to help Arkady count the number of pairs of planes (i,βj) (iβ<βj) there are such that there is a possible value of wind speed, under which planes i and j contact Arkady at the same moment. This value needn't be the same across different pairs.The wind speed is the same for all planes. You may assume that the wind has a steady speed and lasts arbitrarily long.InputThe first line contains two integers n and w (1ββ€βnββ€β100β000, 0ββ€βwβ<β105)Β β the number of planes and the maximum wind speed.The i-th of the next n lines contains two integers xi and vi (1ββ€β|xi|ββ€β105, wβ+β1ββ€β|vi|ββ€β105, xiΒ·viβ<β0)Β β the initial position and speed of the i-th plane.Planes are pairwise distinct, that is, no pair of (i,βj) (iβ<βj) exists such that both xiβ=βxj and viβ=βvj.OutputOutput a single integerΒ β the number of unordered pairs of planes that can contact Arkady at the same moment.ExamplesInput5 1-3 2-3 3-1 21 -33 -5Output3Input6 1-3 2-2 2-1 21 -22 -23 -2Output9NoteIn the first example, the following 3 pairs of planes satisfy the requirements: (2,β5) passes the station at time 3β/β4 with vwindβ=β1; (3,β4) passes the station at time 2β/β5 with vwindβ=β1β/β2; (3,β5) passes the station at time 4β/β7 with vwindβ=ββ-β1β/β4. In the second example, each of the 3 planes with negative coordinates can form a valid pair with each of the other 3, totaling 9 pairs. | Input5 1-3 2-3 3-1 21 -33 -5 | Output3 | 1 second | 256 megabytes | ['*2500'] |
C. Riverside Curiotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water does not wash the marks away. Arkady writes down the number of marks strictly above the water level each day, on the i-th day this value is equal to mi.Define di as the number of marks strictly under the water level on the i-th day. You are to find out the minimum possible sum of di over all days. There are no marks on the channel before the first day.InputThe first line contains a single positive integer n (1ββ€βnββ€β105)Β β the number of days.The second line contains n space-separated integers m1,βm2,β...,βmn (0ββ€βmiβ<βi)Β β the number of marks strictly above the water on each day.OutputOutput one single integerΒ β the minimum possible sum of the number of marks strictly below the water level among all days.ExamplesInput60 1 0 3 0 2Output6Input50 1 2 1 2Output1Input50 1 1 2 2Output0NoteIn the first example, the following figure shows an optimal case. Note that on day 3, a new mark should be created because if not, there cannot be 3 marks above water on day 4. The total number of marks underwater is 0β+β0β+β2β+β0β+β3β+β1β=β6.In the second example, the following figure shows an optimal case. | Input60 1 0 3 0 2 | Output6 | 1 second | 256 megabytes | ['data structures', 'dp', 'greedy', '*1700'] |
B. Three-level Lasertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn atom of element X can exist in n distinct states with energies E1β<βE2β<β...β<βEn. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where iβ<βjβ<βk. After that the following process happens: initially the atom is in the state i, we spend Ekβ-βEi energy to put the atom in the state k, the atom emits a photon with useful energy Ekβ-βEj and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ejβ-βEi, the process repeats from step 1. Let's define the energy conversion efficiency as , i.Β e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ekβ-βEiββ€βU.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.InputThe first line contains two integers n and U (3ββ€βnββ€β105, 1ββ€βUββ€β109) β the number of states and the maximum possible difference between Ek and Ei.The second line contains a sequence of integers E1,βE2,β...,βEn (1ββ€βE1β<βE2...β<βEnββ€β109). It is guaranteed that all Ei are given in increasing order.OutputIf it is not possible to choose three states that satisfy all constraints, print -1.Otherwise, print one real number Ξ·Β β the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10β-β9.Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .ExamplesInput4 41 3 5 7Output0.5Input10 810 13 15 16 17 19 20 22 24 25Output0.875Input3 12 5 10Output-1NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to . | Input4 41 3 5 7 | Output0.5 | 1 second | 256 megabytes | ['binary search', 'greedy', 'two pointers', '*1600'] |
A. Mystical Mosaictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a rectangular grid of n rows of m initially-white cells each.Arkady performed a certain number (possibly zero) of operations on it. In the i-th operation, a non-empty subset of rows Ri and a non-empty subset of columns Ci are chosen. For each row r in Ri and each column c in Ci, the intersection of row r and column c is coloured black.There's another constraint: a row or a column can only be chosen at most once among all operations. In other words, it means that no pair of (i,βj) (iβ<βj) exists such that or , where denotes intersection of sets, and denotes the empty set.You are to determine whether a valid sequence of operations exists that produces a given final grid.InputThe first line contains two space-separated integers n and m (1ββ€βn,βmββ€β50)Β β the number of rows and columns of the grid, respectively.Each of the following n lines contains a string of m characters, each being either '.' (denoting a white cell) or '#' (denoting a black cell), representing the desired setup.OutputIf the given grid can be achieved by any valid sequence of operations, output "Yes"; otherwise output "No" (both without quotes).You can print each character in any case (upper or lower).ExamplesInput5 8.#.#..#......#...#.#..#.#.#....#.....#..OutputYesInput5 5..#....#..#####..#....#..OutputNoInput5 9........##..........##.#..........#.....#.#.#OutputNoNoteFor the first example, the desired setup can be produced by 3 operations, as is shown below. For the second example, the desired setup cannot be produced, since in order to colour the center row, the third row and all columns must be selected in one operation, but after that no column can be selected again, hence it won't be possible to colour the other cells in the center column. | Input5 8.#.#..#......#...#.#..#.#.#....#.....#.. | OutputYes | 1 second | 256 megabytes | ['greedy', 'implementation', '*1300'] |
F. Public Servicetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are N cities in Bob's country connected by roads. Some pairs of cities are connected by public transport. There are two competing transport companiesΒ β Boblines operating buses and Bobrail running trains. When traveling from A to B, a passenger always first selects the mode of transport (either bus or train), and then embarks on a journey. For every pair of cities, there are exactly two ways of how to travel between them without visiting any city more than onceΒ β one using only bus routes, and the second using only train routes. Furthermore, there is no pair of cities that is directly connected by both a bus route and a train route.You obtained the plans of each of the networks. Unfortunately, each of the companies uses different names for the same cities. More precisely, the bus company numbers the cities using integers from 1 to N, while the train company uses integers between Nβ+β1 and 2N. Find one possible mapping between those two numbering schemes, such that no pair of cities is connected directly by both a bus route and a train route. Note that this mapping has to map different cities to different cities.InputThe first line contains an integer N (2ββ€βNββ€β10000), the number of cities.Nβ-β1 lines follow, representing the network plan of Boblines. Each contains two integers u and v (1ββ€βu,βvββ€βN), meaning that there is a bus route between cities u and v.Nβ-β1 lines follow, representing the network plan of Bobrail. Each contains two integers u and v (Nβ+β1ββ€βu,βvββ€β2N), meaning that there is a train route between cities u and v.OutputIf there is no solution, output a single line with the word "No".If a solution exists, output two lines. On the first line, there should be the word "Yes". On the second line, there should be N integers P1,βP2,β...,βPN (Nβ+β1ββ€βPiββ€β2N)Β β the mapping between the two numbering schemes. More precisely, for iββ βj it should be Piββ βPj, and for every direct bus route (i,βj), there is no direct train route between (Pi,βPj).If there are multiple solutions, you may print any of them.ExamplesInput41 22 33 45 66 77 8OutputYes6 8 5 7Input41 22 33 45 65 75 8OutputNoInput71 21 31 41 55 66 78 99 1010 1111 1212 1313 14OutputYes9 14 11 12 13 10 8NoteThe first sample (bus lines in red and rail lines in blue): | Input41 22 33 45 66 77 8 | OutputYes6 8 5 7 | 4 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'trees', '*3200'] |
E. Perpetual Subtractiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a number x initially written on a blackboard. You repeat the following action a fixed amount of times: take the number x currently written on a blackboard and erase it select an integer uniformly at random from the range [0,βx] inclusive, and write it on the blackboard Determine the distribution of final number given the distribution of initial number and the number of steps.InputThe first line contains two integers, N (1ββ€βNββ€β105)Β β the maximum number written on the blackboardΒ β and M (0ββ€βMββ€β1018)Β β the number of steps to perform.The second line contains Nβ+β1 integers P0,βP1,β...,βPN (0ββ€βPiβ<β998244353), where Pi describes the probability that the starting number is i. We can express this probability as irreducible fraction Pβ/βQ, then . It is guaranteed that the sum of all Pis equals 1 (modulo 998244353).OutputOutput a single line of Nβ+β1 integers, where Ri is the probability that the final number after M steps is i. It can be proven that the probability may always be expressed as an irreducible fraction Pβ/βQ. You are asked to output .ExamplesInput2 10 0 1Output332748118 332748118 332748118Input2 20 0 1Output942786334 610038216 443664157Input9 3503 31 314 3141 31415 314159 3141592 31415926 314159265 649178508Output822986014 12998613 84959018 728107923 939229297 935516344 27254497 413831286 583600448 442738326NoteIn the first case, we start with number 2. After one step, it will be 0, 1 or 2 with probability 1/3 each.In the second case, the number will remain 2 with probability 1/9. With probability 1/9 it stays 2 in the first round and changes to 1 in the next, and with probability 1/6 changes to 1 in the first round and stays in the second. In all other cases the final integer is 0. | Input2 10 0 1 | Output332748118 332748118 332748118 | 2 seconds | 256 megabytes | ['fft', 'math', 'matrices', '*3100'] |
D. Picking Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A BC B AC C AB AAA empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source.InputThe first line contains a string S (1ββ€β|S|ββ€β105). The second line contains a string T (1ββ€β|T|ββ€β105), each of these strings consists only of uppercase English letters 'A', 'B' and 'C'.The third line contains the number of queries Q (1ββ€βQββ€β105).The following Q lines describe queries. The i-th of these lines contains four space separated integers ai, bi, ci, di. These represent the i-th query: is it possible to create T[ci..di] from S[ai..bi] by applying the above transitions finite amount of times?Here, U[x..y] is a substring of U that begins at index x (indexed from 1) and ends at index y. In particular, U[1..|U|] is the whole string U.It is guaranteed that 1ββ€βaββ€βbββ€β|S| and 1ββ€βcββ€βdββ€β|T|.OutputPrint a string of Q characters, where the i-th character is '1' if the answer to the i-th query is positive, and '0' otherwise.ExampleInputAABCCBAABABCB51 3 1 22 2 2 47 9 1 13 4 2 34 5 1 3Output10011NoteIn the first query we can achieve the result, for instance, by using transitions .The third query asks for changing AAB to AΒ β but in this case we are not able to get rid of the character 'B'. | InputAABCCBAABABCB51 3 1 22 2 2 47 9 1 13 4 2 34 5 1 3 | Output10011 | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', 'strings', '*2500'] |
C. Perfect Securitytime limit per test3.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice has a very important message M consisting of some non-negative integers that she wants to keep secret from Eve. Alice knows that the only theoretically secure cipher is one-time pad. Alice generates a random key K of the length equal to the message's length. Alice computes the bitwise xor of each element of the message and the key (, where denotes the bitwise XOR operation) and stores this encrypted message A. Alice is smart. Be like Alice.For example, Alice may have wanted to store a message Mβ=β(0,β15,β9,β18). She generated a key Kβ=β(16,β7,β6,β3). The encrypted message is thus Aβ=β(16,β8,β15,β17).Alice realised that she cannot store the key with the encrypted message. Alice sent her key K to Bob and deleted her own copy. Alice is smart. Really, be like Alice.Bob realised that the encrypted message is only secure as long as the key is secret. Bob thus randomly permuted the key before storing it. Bob thinks that this way, even if Eve gets both the encrypted message and the key, she will not be able to read the message. Bob is not smart. Don't be like Bob.In the above example, Bob may have, for instance, selected a permutation (3,β4,β1,β2) and stored the permuted key Pβ=β(6,β3,β16,β7).One year has passed and Alice wants to decrypt her message. Only now Bob has realised that this is impossible. As he has permuted the key randomly, the message is lost forever. Did we mention that Bob isn't smart?Bob wants to salvage at least some information from the message. Since he is not so smart, he asks for your help. You know the encrypted message A and the permuted key P. What is the lexicographically smallest message that could have resulted in the given encrypted text?More precisely, for given A and P, find the lexicographically smallest message O, for which there exists a permutation Ο such that for every i.Note that the sequence S is lexicographically smaller than the sequence T, if there is an index i such that Siβ<βTi and for all jβ<βi the condition Sjβ=βTj holds. InputThe first line contains a single integer N (1ββ€βNββ€β300000), the length of the message. The second line contains N integers A1,βA2,β...,βAN (0ββ€βAiβ<β230) representing the encrypted message.The third line contains N integers P1,βP2,β...,βPN (0ββ€βPiβ<β230) representing the permuted encryption key.OutputOutput a single line with N integers, the lexicographically smallest possible message O. Note that all its elements should be non-negative.ExamplesInput38 4 1317 2 7Output10 3 28Input512 7 87 22 1118 39 9 12 16Output0 14 69 6 44Input10331415699 278745619 998190004 423175621 42983144 166555524 843586353 802130100 337889448 685310951226011312 266003835 342809544 504667531 529814910 684873393 817026985 844010788 993949858 1031395667Output128965467 243912600 4281110 112029883 223689619 76924724 429589 119397893 613490433 362863284NoteIn the first case, the solution is (10,β3,β28), since , and . Other possible permutations of key yield messages (25,β6,β10), (25,β3,β15), (10,β21,β10), (15,β21,β15) and (15,β6,β28), which are all lexicographically larger than the solution. | Input38 4 1317 2 7 | Output10 3 28 | 3.5 seconds | 512 megabytes | ['data structures', 'greedy', 'strings', 'trees', '*1800'] |
B. Producing Snowtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice likes snow a lot! Unfortunately, this year's winter is already over, and she can't expect to have any more of it. Bob has thus bought her a giftΒ β a large snow maker. He plans to make some amount of snow every day. On day i he will make a pile of snow of volume Vi and put it in her garden.Each day, every pile will shrink a little due to melting. More precisely, when the temperature on a given day is Ti, each pile will reduce its volume by Ti. If this would reduce the volume of a pile to or below zero, it disappears forever. All snow piles are independent of each other. Note that the pile made on day i already loses part of its volume on the same day. In an extreme case, this may mean that there are no piles left at the end of a particular day.You are given the initial pile sizes and the temperature on each day. Determine the total volume of snow melted on each day. InputThe first line contains a single integer N (1ββ€βNββ€β105)Β β the number of days. The second line contains N integers V1,βV2,β...,βVN (0ββ€βViββ€β109), where Vi is the initial size of a snow pile made on the day i.The third line contains N integers T1,βT2,β...,βTN (0ββ€βTiββ€β109), where Ti is the temperature on the day i.OutputOutput a single line with N integers, where the i-th integer represents the total volume of snow melted on day i.ExamplesInput310 10 55 7 2Output5 12 4Input530 25 20 15 109 10 12 4 13Output9 20 35 11 25NoteIn the first sample, Bob first makes a snow pile of volume 10, which melts to the size of 5 on the same day. On the second day, he makes another pile of size 10. Since it is a bit warmer than the day before, the first pile disappears completely while the second pile shrinks to 3. At the end of the second day, he has only a single pile of size 3. On the third day he makes a smaller pile than usual, but as the temperature dropped too, both piles survive till the end of the day. | Input310 10 55 7 2 | Output5 12 4 | 1 second | 256 megabytes | ['binary search', 'data structures', '*1600'] |
A. Primal Sporttime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob begin their day with a quick game. They first choose a starting number X0ββ₯β3 and try to reach one million by the process described below. Alice goes first and then they take alternating turns. In the i-th turn, the player whose turn it is selects a prime number smaller than the current number, and announces the smallest multiple of this prime number that is not smaller than the current number.Formally, he or she selects a prime pβ<βXiβ-β1 and then finds the minimum Xiββ₯βXiβ-β1 such that p divides Xi. Note that if the selected prime p already divides Xiβ-β1, then the number does not change.Eve has witnessed the state of the game after two turns. Given X2, help her determine what is the smallest possible starting number X0. Note that the players don't necessarily play optimally. You should consider all possible game evolutions.InputThe input contains a single integer X2 (4ββ€βX2ββ€β106). It is guaranteed that the integer X2 is composite, that is, is not prime.OutputOutput a single integerΒ β the minimum possible X0.ExamplesInput14Output6Input20Output15Input8192Output8191NoteIn the first test, the smallest possible starting number is X0β=β6. One possible course of the game is as follows: Alice picks prime 5 and announces X1β=β10 Bob picks prime 7 and announces X2β=β14. In the second case, let X0β=β15. Alice picks prime 2 and announces X1β=β16 Bob picks prime 5 and announces X2β=β20. | Input14 | Output6 | 1.5 seconds | 256 megabytes | ['math', 'number theory', '*1700'] |
F. Divisibilitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputImp is really pleased that you helped him. But it you solve the last problem, his gladness would raise even more. Let's define for some set of integers as the number of pairs a, b in , such that: a is strictly less than b; a divides b without a remainder. You are to find such a set , which is a subset of {1,β2,β...,βn} (the set that contains all positive integers not greater than n), that . InputThe only line contains two integers n and k .OutputIf there is no answer, print "No".Otherwise, in the first line print "Yes", in the secondΒ β an integer m that denotes the size of the set you have found, in the second line print m integersΒ β the elements of the set , in any order.If there are multiple answers, print any of them.ExamplesInput3 3OutputNoInput6 6OutputYes51 2 4 5 6 Input8 3OutputYes42 4 5 8NoteIn the second sample, the valid pairs in the output set are (1,β2), (1,β4), (1,β5), (1,β6), (2,β4), (2,β6). Thus, .In the third example, the valid pairs in the output set are (2,β4), (4,β8), (2,β8). Thus, . | Input3 3 | OutputNo | 1 second | 256 megabytes | ['constructive algorithms', 'dp', 'greedy', 'number theory', '*2400'] |
E. Birdstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputApart from plush toys, Imp is a huge fan of little yellow birds! To summon birds, Imp needs strong magic. There are n trees in a row on an alley in a park, there is a nest on each of the trees. In the i-th nest there are ci birds; to summon one bird from this nest Imp needs to stay under this tree and it costs him costi points of mana. However, for each bird summoned, Imp increases his mana capacity by B points. Imp summons birds one by one, he can summon any number from 0 to ci birds from the i-th nest. Initially Imp stands under the first tree and has W points of mana, and his mana capacity equals W as well. He can only go forward, and each time he moves from a tree to the next one, he restores X points of mana (but it can't exceed his current mana capacity). Moving only forward, what is the maximum number of birds Imp can summon?InputThe first line contains four integers n, W, B, X (1ββ€βnββ€β103,β0ββ€βW,βB,βXββ€β109)Β β the number of trees, the initial points of mana, the number of points the mana capacity increases after a bird is summoned, and the number of points restored when Imp moves from a tree to the next one.The second line contains n integers c1,βc2,β...,βcn (0ββ€βciββ€β104)Β β where ci is the number of birds living in the i-th nest. It is guaranteed that .The third line contains n integers cost1,βcost2,β...,βcostn (0ββ€βcostiββ€β109), where costi is the mana cost to summon a bird from the i-th nest.OutputPrint a single integerΒ β the maximum number of birds Imp can summon.ExamplesInput2 12 0 43 44 2Output6Input4 1000 10 351 2 4 51000 500 250 200Output5Input2 10 7 112 106 1Output11NoteIn the first sample base amount of Imp's mana is equal to 12 (with maximum capacity also equal to 12). After he summons two birds from the first nest, he loses 8 mana points, although his maximum capacity will not increase (since Bβ=β0). After this step his mana will be 4 of 12; during the move you will replenish 4 mana points, and hence own 8 mana out of 12 possible. Now it's optimal to take 4 birds from the second nest and spend 8 mana. The final answer will be β 6.In the second sample the base amount of mana is equal to 1000. The right choice will be to simply pick all birds from the last nest. Note that Imp's mana doesn't restore while moving because it's initially full. | Input2 12 0 43 44 2 | Output6 | 1 second | 256 megabytes | ['dp', '*2200'] |
D. Robot Vacuum Cleanertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPushok the dog has been chasing Imp for a few hours already. Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i,βj), that iβ<βj and and . The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.Help Imp to find the maximum noise he can achieve by changing the order of the strings.InputThe first line contains a single integer n (1ββ€βnββ€β105)Β β the number of strings in robot's memory.Next n lines contain the strings t1,βt2,β...,βtn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.OutputPrint a single integerΒ β the maxumum possible noise Imp can achieve by changing the order of the strings.ExamplesInput4sshhsshhhsOutput18Input2hsOutput1NoteThe optimal concatenation in the first sample is ssshhshhhs. | Input4sshhsshhhs | Output18 | 1 second | 256 megabytes | ['greedy', 'sortings', '*1800'] |
C. Cave Paintingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputImp is watching a documentary about cave painting. Some numbers, carved in chaotic order, immediately attracted his attention. Imp rapidly proposed a guess that they are the remainders of division of a number n by all integers i from 1 to k. Unfortunately, there are too many integers to analyze for Imp.Imp wants you to check whether all these remainders are distinct. Formally, he wants to check, if all , 1ββ€βiββ€βk, are distinct, i.Β e. there is no such pair (i,βj) that: 1ββ€βiβ<βjββ€βk, , where is the remainder of division x by y. InputThe only line contains two integers n, k (1ββ€βn,βkββ€β1018).OutputPrint "Yes", if all the remainders are distinct, and "No" otherwise.You can print each letter in arbitrary case (lower or upper).ExamplesInput4 4OutputNoInput5 3OutputYesNoteIn the first sample remainders modulo 1 and 4 coincide. | Input4 4 | OutputNo | 1 second | 256 megabytes | ['brute force', 'number theory', '*1600'] |
B. Magic Foresttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputImp is in a magic forest, where xorangles grow (wut?) A xorangle of order n is such a non-degenerate triangle, that lengths of its sides are integers not exceeding n, and the xor-sum of the lengths is equal to zero. Imp has to count the number of distinct xorangles of order n to get out of the forest. Formally, for a given integer n you have to find the number of such triples (a,βb,βc), that: 1ββ€βaββ€βbββ€βcββ€βn; , where denotes the bitwise xor of integers x and y. (a,βb,βc) form a non-degenerate (with strictly positive area) triangle. InputThe only line contains a single integer n (1ββ€βnββ€β2500).OutputPrint the number of xorangles of order n.ExamplesInput6Output1Input10Output2NoteThe only xorangle in the first sample is (3,β5,β6). | Input6 | Output1 | 1 second | 256 megabytes | ['brute force', '*1300'] |
A. Cloning Toystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputImp likes his plush toy a lot. Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.Initially, Imp has only one original toy. He wants to know if it is possible to use machine to get exactly x copied toys and y original toys? He can't throw toys away, and he can't apply the machine to a copy if he doesn't currently have any copies.InputThe only line contains two integers x and y (0ββ€βx,βyββ€β109)Β β the number of copies and the number of original toys Imp wants to get (including the initial one).OutputPrint "Yes", if the desired configuration is possible, and "No" otherwise.You can print each letter in arbitrary case (upper or lower).ExamplesInput6 3OutputYesInput4 2OutputNoInput1000 1001OutputYesNoteIn the first example, Imp has to apply the machine twice to original toys and then twice to copies. | Input6 3 | OutputYes | 1 second | 256 megabytes | ['implementation', '*1300'] |
01. Labyrinth-1time limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a robot in a two-dimensional labyrinth which consists of NβΓβM cells. Some pairs of cells adjacent by side are separated by a wall or a door. The labyrinth itself is separated from the outside with walls around it. Some labyrinth cells are the exits. In order to leave the labyrinth the robot should reach any exit. There are keys in some cells. Any key can open any door but after the door is opened the key stays in the lock. Thus every key can be used only once. There are no labyrinth cells that contain both a key and an exit. Also there can not be both a wall and a door between the pair of adjacent cells.Your need to write a program in abc language (see the language description below) that will lead the robot to one of the exits. Lets numerate the labyrinth rows from 0 to Nβ-β1 top to bottom and the columns β from 0 to Mβ-β1 left to right.In abc language the following primary commands are available: move-DIR β move to the adjacent cell in the direction. down increases the number of the row by 1, right increases the number of the column by 1. In case thereβs a wall or a closed door in this direction, nothingβs happening. open-DIR β open the door between the current cell and the adjacent one in DIR direction. In case there isnβt any door in this direction or itβs already been opened or the robot doesnβt have a key, nothingβs happening. take β take the key in the current cell. In case there isnβt any key or the robot has already picked it up, nothingβs happening. The robot is able to carry any number of keys. terminate β terminate the program. This command is not obligatory to use. In case itβs absent the command is added at the end of the program automatically. Also, there are the following control commands in abc language: for-N OPS end β repeat the sequence of the OPS commands N times, 0β<βNββ€β100000. Each loop counter check counts as a command fulfilled by the robot. if-ok OPS1 else OPS2 endif β carries out the sequence of the OPS1 commands, if the previous command of moving, taking the key or opening the door was successful, otherwise the sequence of the OPS2 commands is being carried out. Should there be no previous command run, the sequence OPS1 will be carried out. If-ok check counts as a command fulfilled by the robot. break β stops the current for loop. continue β finishes the current for loop iterations. Note that the control and the primary commands can be fit into each other arbitrarily.The robot will fulfill your commands sequentially until it exits the labyrinth, or it runs out of the commands, or the terminate command is run, or the quantity of the fulfilled commands exceeds the bound number 5Β·106.In abc language each command is a separate word and should be separated from other commands with at least one space symbol.You should write a program that prints the sequence of commands leading the robot out of the labyrinth. Of course, as you are a good programmer, you should optimize these sequence.The number of the non-space symbols in the sequence should not exceed 107. If you succeed in finding the way out of the labyrinth i youβll be granted the number of points equal to: where: Wi β labyrinthβs weight, some fixed constant. Gi β number of robots moves. Oi β number of fulfilled commands. Note that this number includes commands like take executed in the cells with no key, as well as opening commands applied to the already opened doors. Li β sequence length in symbols, excluding space symbols and line breaks. Qβ=β10Β·NΒ·M. In case your sequence doesnβt lead the robot to the exit youβll be granted 0 points. Your programs result will be the sum of all Si. You should maximize this total sum.All labyrinths will be known and available to you. You can download the archive with labyrinths by any of the given links, password to extract files is aimtechiscool: https://drive.google.com/file/d/1dkIBfW_Gy6c3FJtXjMXZPMsGKRyn3pzp https://www.dropbox.com/s/77jrplnjgmviiwt/aimmaze.zip?dl=0 https://yadi.sk/d/JNXDLeH63RzaCi In order to make local testing of your programs more convenient, the program calculating your results (checker) and the labyrinth visualizer will be available. This program is written in python3 programming language, thatβs why youβre going to need python3 interpreter, as well as pillow library, which you can install with the following command pip3 install pillow. pip3 is a utility program for python3 package (library) installation. It will be installed automatically with the python3 interpreter.Example command to run checker and visualizer: python3 aimmaze.py maze.in robot.abc --image maze.png. The checker can be run separately of visualization: python3 aimmaze.py maze.in robot.abc. Flag --output-log will let you see the information of robots each step: python3 aimmaze.py maze.in robot.abc --output-log. Note python3 can be installed as python on your computer.To adjust image settings, you can edit constants at the beginning of the program aimmaze.py.InputThe first line contains integers i,βΒ W,βΒ N,βΒ M,βΒ x0,βΒ y0,βΒ C,βΒ D,βΒ K,βΒ E. 1ββ€βiββ€β14 β labyrinthβs number, which is needed for a checking program. 1ββ€βWββ€β1018 β labyrinthβs weight, which is needed for a checking program. 2ββ€βN,βMββ€β1000 β labyrinthβs height and width. 0ββ€βx0ββ€βNβ-β1,βΒ 0ββ€βy0ββ€βMβ-β1 β robotβs starting position (x0,βy0). 0ββ€βCββ€β2Β·NM β number of walls. 0ββ€βDββ€β105 β number of doors. 0ββ€βKββ€β105 β number of keys. 1ββ€βEββ€β1000 β number of exits. The x coordinate corresponds to the row number, y β to the column number. (0,β0) cell is located on the left-up corner, so that down direction increases the x coordinate, while right direction increases the y coordinate.Each of the next C lines contains 4 integers each x1,βy1,βx2,βy2 β the coordinates of cells with a wall between them in a zero based indexing. It is guaranteed that |x1β-βx2|β+β|y1β-βy2|β=β1,βΒ 0ββ€βx1,βx2ββ€βNβ-β1,βΒ 0ββ€βy1,βy2ββ€βMβ-β1. Also there are always walls around the labyrinthβs borders, which are not given in the labyrinths description.Each of the next D lines contains door description in the same format as walls description. It is guaranteed that doors and walls donβt overlap.Each of the next K rows contains a pair of integer which are the key coordinates in a zero based indexing.Each of the next E rows contains a pair of integer which are the exit coordinates in a zero based indexing.It is guaranteed that the robots starting position as well as keys and exits are located in pairwise different cells.OutputPrint a program in abc language which passes the given labyrinth. Commands have to be separated by at least one space symbol. You can use arbitrary formatting for the program.ExampleInput1 1 30 30 1 1 1 1 1 11 1 1 22 2 2 31 49 0Outputfor-1111 take open-up open-left open-right open-down move-left if-ok for-11 move-left take open-up open-left open-right open-down end else move-right if-ok for-11 move-right take open-up open-left open-right open-down end else endif endif move-up if-ok for-11 move-up take open-up open-left open-right open-down end else move-down if-ok for-11 move-down take open-up open-left open-right open-down end else endif endifend | Input1 1 30 30 1 1 1 1 1 11 1 1 22 2 2 31 49 0 | Outputfor-1111 take open-up open-left open-right open-down move-left if-ok for-11 move-left take open-up open-left open-right open-down end else move-right if-ok for-11 move-right take open-up open-left open-right open-down end else endif endif move-up if-ok for-11 move-up take open-up open-left open-right open-down end else move-down if-ok for-11 move-down take open-up open-left open-right open-down end else endif endifend | 8 seconds | 512 megabytes | ['*3200'] |
G. List Of Integerstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote as L(x,βp) an infinite sequence of integers y such that gcd(p,βy)β=β1 and yβ>βx (where gcd is the greatest common divisor of two integer numbers), sorted in ascending order. The elements of L(x,βp) are 1-indexed; for example, 9, 13 and 15 are the first, the second and the third elements of L(7,β22), respectively.You have to process t queries. Each query is denoted by three integers x, p and k, and the answer to this query is k-th element of L(x,βp).InputThe first line contains one integer t (1ββ€βtββ€β30000) β the number of queries to process.Then t lines follow. i-th line contains three integers x, p and k for i-th query (1ββ€βx,βp,βkββ€β106).OutputPrint t integers, where i-th integer is the answer to i-th query.ExamplesInput37 22 17 22 27 22 3Output91315Input542 42 4243 43 4344 44 4445 45 4546 46 46Output18787139128141 | Input37 22 17 22 27 22 3 | Output91315 | 5 seconds | 256 megabytes | ['binary search', 'bitmasks', 'brute force', 'combinatorics', 'math', 'number theory', '*2200'] |
F. SUM and REPLACEtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet D(x) be the number of positive divisors of a positive integer x. For example, D(2)β=β2 (2 is divisible by 1 and 2), D(6)β=β4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β for every replace ai with D(ai); SUM l r β calculate . Print the answer for each SUM query.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β3Β·105) β the number of elements in the array and the number of queries to process, respectively.The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β106) β the elements of the array.Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If tiβ=β1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1ββ€βtiββ€β2, 1ββ€βliββ€βriββ€βn).There is at least one SUM query.OutputFor each SUM query print the answer to it.ExampleInput7 66 4 1 10 3 2 42 1 72 4 51 3 52 4 41 5 72 1 7Output3013422 | Input7 66 4 1 10 3 2 42 1 72 4 51 3 52 4 41 5 72 1 7 | Output3013422 | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'dsu', 'number theory', '*2000'] |
E. Connected Components?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph consisting of n vertices and edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x,βy) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices.You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule.InputThe first line contains two integers n and m (1ββ€βnββ€β200000, ).Then m lines follow, each containing a pair of integers x and y (1ββ€βx,βyββ€βn, xββ βy) denoting that there is no edge between x and y. Each pair is listed at most once; (x,βy) and (y,βx) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. OutputFirstly print k β the number of connected components in this graph.Then print k integers β the sizes of components. You should output these integers in non-descending order.ExampleInput5 51 23 43 24 22 5Output21 4 | Input5 51 23 43 24 22 5 | Output21 4 | 2 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'dsu', 'graphs', '*2100'] |
D. Tankstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya sometimes has to water his field. To water the field, Petya needs a tank with exactly V ml of water.Petya has got N tanks, i-th of them initially containing ai ml of water. The tanks are really large, any of them can contain any amount of water (no matter how large this amount is).Also Petya has got a scoop that can contain up to K ml of water (initially the scoop is empty). This scoop can be used to get some water from some tank, and after that pour it all into some tank (it is impossible to get water from multiple tanks without pouring it, or leave some water in the scoop when pouring it). When Petya tries to get some water from a tank, he gets min(v,βK) water, where v is the current volume of water in the tank.Is it possible to obtain a tank with exactly V ml of water using these operations? If it is possible, print a sequence of operations that allows to do it. If there are multiple ways to obtain needed amount of water in some tank, print any of them.InputThe first line contains 3 integers: N (2ββ€βNββ€β5000), K (1ββ€βKββ€β5000), and V (0ββ€βVββ€β109) β the number of tanks, the maximum volume of water the scoop can contain, and the required amount of water in some tank, respectively.The second line contains N integers ai (0ββ€βaiββ€β105), where ai is initial volume of water in i-th tank.OutputIf it is impossible to obtain a tank with exactly V ml of water, print NO. Otherwise print YES in the first line, and beginning from the second line, print the sequence of operations in the following format: Each line has to contain 3 numbers denoting a compressed operation: "cnt x y" (1ββ€βcntββ€β109,β1ββ€βx,βyββ€βN), where x is the index of the tank where we get water, y is the index of the tank where we pour water, and cnt is the number of times we transfer water from tank x to tank y. The number of these lines must not exceed Nβ+β5.ExamplesInput2 3 52 3OutputYES1 2 1Input2 3 42 3OutputNOInput5 2 01 3 5 7 9OutputYES2 2 13 3 14 4 15 5 1 | Input2 3 52 3 | OutputYES1 2 1 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'implementation', '*2400'] |
C. Swap Adjacent Elementstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this array.For some indices i (1ββ€βiββ€βnβ-β1) it is possible to swap i-th element with (iβ+β1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the number of times you swap i-th element with (iβ+β1)-th (if the position is not forbidden).Can you make this array sorted in ascending order performing some sequence of swapping operations?InputThe first line contains one integer n (2ββ€βnββ€β200000) β the number of elements in the array.The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β200000) β the elements of the array. Each integer from 1 to n appears exactly once.The third line contains a string of nβ-β1 characters, each character is either 0 or 1. If i-th character is 1, then you can swap i-th element with (iβ+β1)-th any number of times, otherwise it is forbidden to swap i-th element with (iβ+β1)-th.OutputIf it is possible to sort the array in ascending order using any sequence of swaps you are allowed to make, print YES. Otherwise, print NO.ExamplesInput61 2 5 3 4 601110OutputYESInput61 2 5 3 4 601010OutputNONoteIn the first example you may swap a3 and a4, and then swap a4 and a5. | Input61 2 5 3 4 601110 | OutputYES | 1 second | 256 megabytes | ['dfs and similar', 'greedy', 'math', 'sortings', 'two pointers', '*1400'] |
B. Tea Queuetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently n students from city S moved to city P to attend a programming camp.They moved there by train. In the evening, all students in the train decided that they want to drink some tea. Of course, no two people can use the same teapot simultaneously, so the students had to form a queue to get their tea.i-th student comes to the end of the queue at the beginning of li-th second. If there are multiple students coming to the queue in the same moment, then the student with greater index comes after the student with lesser index. Students in the queue behave as follows: if there is nobody in the queue before the student, then he uses the teapot for exactly one second and leaves the queue with his tea; otherwise the student waits for the people before him to get their tea. If at the beginning of ri-th second student i still cannot get his tea (there is someone before him in the queue), then he leaves the queue without getting any tea. For each student determine the second he will use the teapot and get his tea (if he actually gets it).InputThe first line contains one integer t β the number of test cases to solve (1ββ€βtββ€β1000).Then t test cases follow. The first line of each test case contains one integer n (1ββ€βnββ€β1000) β the number of students.Then n lines follow. Each line contains two integer li, ri (1ββ€βliββ€βriββ€β5000) β the second i-th student comes to the end of the queue, and the second he leaves the queue if he still cannot get his tea.It is guaranteed that for every condition liβ-β1ββ€βli holds.The sum of n over all test cases doesn't exceed 1000.Note that in hacks you have to set tβ=β1.OutputFor each test case print n integers. i-th of them must be equal to the second when i-th student gets his tea, or 0 if he leaves without tea.ExampleInput221 31 431 51 12 3Output1 2 1 0 2 NoteThe example contains 2 tests: During 1-st second, students 1 and 2 come to the queue, and student 1 gets his tea. Student 2 gets his tea during 2-nd second. During 1-st second, students 1 and 2 come to the queue, student 1 gets his tea, and student 2 leaves without tea. During 2-nd second, student 3 comes and gets his tea. | Input221 31 431 51 12 3 | Output1 2 1 0 2 | 1 second | 256 megabytes | ['implementation', '*1200'] |
A. Water The Gardentime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is winter now, and Max decided it's about time he watered the garden.The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed xi), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed xi is turned on, then after one second has passed, the bed xi will be watered; after two seconds have passed, the beds from the segment [xiβ-β1,βxiβ+β1] will be watered (if they exist); after j seconds have passed (j is an integer number), the beds from the segment [xiβ-β(jβ-β1),βxiβ+β(jβ-β1)] will be watered (if they exist). Nothing changes during the seconds, so, for example, we can't say that the segment [xiβ-β2.5,βxiβ+β2.5] will be watered after 2.5 seconds have passed; only the segment [xiβ-β2,βxiβ+β2] will be watered at that moment. The garden from test 1. White colour denotes a garden bed without a tap, red colour β a garden bed with a tap. The garden from test 1 after 2 seconds have passed after turning on the tap. White colour denotes an unwatered garden bed, blue colour β a watered bed. Max wants to turn on all the water taps at the same moment, and now he wonders, what is the minimum number of seconds that have to pass after he turns on some taps until the whole garden is watered. Help him to find the answer!InputThe first line contains one integer t β the number of test cases to solve (1ββ€βtββ€β200).Then t test cases follow. The first line of each test case contains two integers n and k (1ββ€βnββ€β200, 1ββ€βkββ€βn) β the number of garden beds and water taps, respectively.Next line contains k integers xi (1ββ€βxiββ€βn) β the location of i-th water tap. It is guaranteed that for each condition xiβ-β1β<βxi holds.It is guaranteed that the sum of n over all test cases doesn't exceed 200.Note that in hacks you have to set tβ=β1.OutputFor each test case print one integer β the minimum number of seconds that have to pass after Max turns on some of the water taps, until the whole garden is watered.ExampleInput35 133 31 2 34 11Output314NoteThe first example consists of 3 tests: There are 5 garden beds, and a water tap in the bed 3. If we turn it on, then after 1 second passes, only bed 3 will be watered; after 2 seconds pass, beds [1,β3] will be watered, and after 3 seconds pass, everything will be watered. There are 3 garden beds, and there is a water tap in each one. If we turn all of them on, then everything will be watered after 1 second passes. There are 4 garden beds, and only one tap in the bed 1. It will take 4 seconds to water, for example, bed 4. | Input35 133 31 2 34 11 | Output314 | 1 second | 256 megabytes | ['implementation', '*1000'] |
F. A Game With Numberstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputImagine that Alice is playing a card game with her friend Bob. They both have exactly 8 cards and there is an integer on each card, ranging from 0 to 4. In each round, Alice or Bob in turns choose two cards from different players, let them be a and b, where a is the number on the player's card, and b is the number on the opponent's card. It is necessary that a \cdot b \ne 0. Then they calculate c = (a + b) \bmod 5 and replace the number a with c. The player who ends up with numbers on all 8 cards being 0, wins.Now Alice wants to know who wins in some situations. She will give you her cards' numbers, Bob's cards' numbers and the person playing the first round. Your task is to determine who wins if both of them choose the best operation in their rounds.InputThe first line contains one positive integer T (1 \leq T \leq 100\,000), denoting the number of situations you need to consider.The following lines describe those T situations. For each situation: The first line contains a non-negative integer f (0 \leq f \leq 1), where f = 0 means that Alice plays first and f = 1 means Bob plays first. The second line contains 8 non-negative integers a_1, a_2, \ldots, a_8 (0 \leq a_i \leq 4), describing Alice's cards. The third line contains 8 non-negative integers b_1, b_2, \ldots, b_8 (0 \leq b_i \leq 4), describing Bob's cards. We guarantee that if f=0, we have \sum_{i=1}^{8}a_i \ne 0. Also when f=1, \sum_{i=1}^{8}b_i \ne 0 holds.OutputOutput T lines. For each situation, determine who wins. Output "Alice" (without quotes) if Alice wins. "Bob" (without quotes) if Bob wins. "Deal" (without quotes) if it gets into a deal, i.e. no one wins. ExampleInput410 0 0 0 0 0 0 01 2 3 4 1 2 3 410 0 0 1 0 0 0 00 0 0 0 4 0 0 001 0 0 0 0 0 0 00 0 0 4 0 0 2 011 1 1 1 1 1 1 11 1 1 1 1 1 1 1OutputAliceBobAliceDealNoteIn the first situation, Alice has all her numbers 0. So she wins immediately.In the second situation, Bob picks the numbers 4 and 1. Because we have (4 + 1) \bmod 5 = 0, Bob wins after this operation.In the third situation, Alice picks the numbers 1 and 4. She wins after this operation.In the fourth situation, we can prove that it falls into a loop. | Input410 0 0 0 0 0 0 01 2 3 4 1 2 3 410 0 0 1 0 0 0 00 0 0 0 4 0 0 001 0 0 0 0 0 0 00 0 0 4 0 0 2 011 1 1 1 1 1 1 11 1 1 1 1 1 1 1 | OutputAliceBobAliceDeal | 4 seconds | 512 megabytes | ['games', 'graphs', 'shortest paths', '*2600'] |
E. Congruence Equationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an integer x. Your task is to find out how many positive integers n (1 \leq n \leq x) satisfy n \cdot a^n \equiv b \quad (\textrm{mod}\;p), where a, b, p are all known constants.InputThe only line contains four integers a,b,p,x (2 \leq p \leq 10^6+3, 1 \leq a,b < p, 1 \leq x \leq 10^{12}). It is guaranteed that p is a prime.OutputPrint a single integer: the number of possible answers n.ExamplesInput2 3 5 8Output2Input4 6 7 13Output1Input233 233 10007 1Output1NoteIn the first sample, we can see that n=2 and n=8 are possible answers. | Input2 3 5 8 | Output2 | 3 seconds | 256 megabytes | ['chinese remainder theorem', 'math', 'number theory', '*2100'] |
D. Substringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a graph with n nodes and m directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is 3. Your task is find a path whose value is the largest.InputThe first line contains two positive integers n, m (1 \leq n, m \leq 300\,000), denoting that the graph has n nodes and m directed edges.The second line contains a string s with only lowercase English letters. The i-th character is the letter assigned to the i-th node.Then m lines follow. Each line contains two integers x, y (1 \leq x, y \leq n), describing a directed edge from x to y. Note that x can be equal to y and there can be multiple edges between x and y. Also the graph can be not connected.OutputOutput a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.ExamplesInput5 4abaca1 21 33 44 5Output3Input6 6xzyabc1 23 12 35 44 36 4Output-1Input10 14xzyzyzyzqx1 22 43 54 52 66 86 52 103 910 94 61 102 83 7Output4NoteIn the first sample, the path with largest value is 1 \to 3 \to 4 \to 5. The value is 3 because the letter 'a' appears 3 times. | Input5 4abaca1 21 33 44 5 | Output3 | 3 seconds | 256 megabytes | ['dfs and similar', 'dp', 'graphs', '*1700'] |
C. Seat Arrangementstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied.The classroom contains n rows of seats and there are m seats in each row. Then the classroom can be represented as an n \times m matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find k consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.InputThe first line contains three positive integers n,m,k (1 \leq n, m, k \leq 2\,000), where n,m represent the sizes of the classroom and k is the number of consecutive seats you need to find.Each of the next n lines contains m characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.OutputA single number, denoting the number of ways to find k empty seats in the same row or column.ExamplesInput2 3 2**....Output3Input1 2 2..Output1Input3 3 4.*.*.*.*.Output0NoteIn the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. (1,3), (2,3) (2,2), (2,3) (2,1), (2,2) | Input2 3 2**.... | Output3 | 1 second | 256 megabytes | ['brute force', 'implementation', '*1300'] |
B. Perfect Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe consider a positive integer perfect, if and only if the sum of its digits is exactly 10. Given a positive integer k, your task is to find the k-th smallest perfect positive integer.InputA single line with a positive integer k (1 \leq k \leq 10\,000).OutputA single number, denoting the k-th smallest perfect integer.ExamplesInput1Output19Input2Output28NoteThe first perfect integer is 19 and the second one is 28. | Input1 | Output19 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'dp', 'implementation', 'number theory', '*1100'] |
A. Supermarkettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that a yuan for b kilos (You don't need to care about what "yuan" is), the same as a/b yuan for a kilo.Now imagine you'd like to buy m kilos of apples. You've asked n supermarkets and got the prices. Find the minimum cost for those apples.You can assume that there are enough apples in all supermarkets.InputThe first line contains two positive integers n and m (1 \leq n \leq 5\,000, 1 \leq m \leq 100), denoting that there are n supermarkets and you want to buy m kilos of apples.The following n lines describe the information of the supermarkets. Each line contains two positive integers a, b (1 \leq a, b \leq 100), denoting that in this supermarket, you are supposed to pay a yuan for b kilos of apples.OutputThe only line, denoting the minimum cost for m kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed 10^{-6}.Formally, let your answer be x, and the jury's answer be y. Your answer is considered correct if \frac{|x - y|}{\max{(1, |y|)}} \le 10^{-6}.ExamplesInput3 51 23 41 3Output1.66666667Input2 199 10098 99Output0.98989899NoteIn the first sample, you are supposed to buy 5 kilos of apples in supermarket 3. The cost is 5/3 yuan.In the second sample, you are supposed to buy 1 kilo of apples in supermarket 2. The cost is 98/99 yuan. | Input3 51 23 41 3 | Output1.66666667 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'implementation', '*800'] |
B. Radio Stationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers. Each ip is of form "a.b.c.d" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip.Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.InputThe first line of input contains two integers n and m (1ββ€βn,βmββ€β1000).The next n lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1ββ€β|name|ββ€β10, name only consists of English lowercase letters). It is guaranteed that all ip are distinct.The next m lines contain the commands in the configuration file. Each line is of form "command ip;" (1ββ€β|command|ββ€β10, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the n school servers.OutputPrint m lines, the commands in the configuration file after Dustin did his task.ExamplesInput2 2main 192.168.0.2replica 192.168.0.1block 192.168.0.1;proxy 192.168.0.2;Outputblock 192.168.0.1; #replicaproxy 192.168.0.2; #mainInput3 5google 8.8.8.8codeforces 212.193.33.27server 138.197.64.57redirect 138.197.64.57;block 8.8.8.8;cf 212.193.33.27;unblock 8.8.8.8;check 138.197.64.57;Outputredirect 138.197.64.57; #serverblock 8.8.8.8; #googlecf 212.193.33.27; #codeforcesunblock 8.8.8.8; #googlecheck 138.197.64.57; #server | Input2 2main 192.168.0.2replica 192.168.0.1block 192.168.0.1;proxy 192.168.0.2; | Outputblock 192.168.0.1; #replicaproxy 192.168.0.2; #main | 2 seconds | 256 megabytes | ['implementation', 'strings', '*900'] |
A. Eleventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEleven wants to choose a new name for herself. As a bunch of geeks, her friends suggested an algorithm to choose a name for her. Eleven wants her name to have exactly n characters. Her friend suggested that her name should only consist of uppercase and lowercase letters 'O'. More precisely, they suggested that the i-th letter of her name should be 'O' (uppercase) if i is a member of Fibonacci sequence, and 'o' (lowercase) otherwise. The letters in the name are numbered from 1 to n. Fibonacci sequence is the sequence f where f1β=β1, f2β=β1, fnβ=βfnβ-β2β+βfnβ-β1 (nβ>β2). As her friends are too young to know what Fibonacci sequence is, they asked you to help Eleven determine her new name.InputThe first and only line of input contains an integer n (1ββ€βnββ€β1000).OutputPrint Eleven's new name on the first and only line of output.ExamplesInput8OutputOOOoOooOInput15OutputOOOoOooOooooOoo | Input8 | OutputOOOoOooO | 1 second | 256 megabytes | ['brute force', 'implementation', '*800'] |
E. Upside Downtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAs we all know, Eleven has special abilities. Thus, Hopper convinced her to close the gate to the Upside Down World with her mind. Upside down monsters like to move between the worlds, so they are going to attack Hopper and Eleven in order to make them stop. The monsters live in the vines. The vines form a tree with n vertices, numbered from 1 through n. There's a lowercase English letter written in each tunnel (edge). Upside down is a magical world. There are m types of monsters in upside down, numbered from 1 through m. Each type of monster has a special word that gives them powers. The special word of type i is si. There are q monsters in upside down. Each one is at a junction (vertex) and is going to some other junction. If monster of type k goes from junction i to junction j, the power it gains is the number of times it sees its special world (sk) consecutively in the tunnels. More formally: If f(i,βj) is the string we get when we concatenate the letters written in the tunnels on the shortest path from i to j, then the power the monster gains is the number of occurrences of sk in f(i,βj).Hopper and Eleven want to get prepared, so for each monster, they want to know the power the monster gains after moving. InputThe first line of input contains three integers, n,βm and q (2ββ€βnββ€β105, 1ββ€βm,βqββ€β105).The next nβ-β1 lines contain the tunnels (edges). Each line contains two integers v and u (1ββ€βv,βuββ€βn, vββ βu) and a lowercase English letter c, meaning there's a tunnel connecting junctions v and u written c in it. It is guaranteed that the given graph is a tree.The next m lines contain the special words. i-th line of them contains a single string si (1ββ€β|si|ββ€β105), consisting of lowercase English letters. It is guaranteed that |s1|β+β|s2|β+β...β+β|sm|ββ€β105).The next q lines contain the monsters. Each line contains three integers i, j and k (1ββ€βi,βjββ€βn, iββ βj, 1ββ€βkββ€βm), meaning a monster of type k is going from junction number i to junction number j.OutputPrint q lines. i-th line should contain a single integer, the power the i-th monster gains after moving.ExamplesInput6 4 51 6 b2 3 a1 2 b5 3 b4 5 babbbaa1 2 16 2 31 6 24 5 41 6 2Output01101Input10 6 71 3 s10 1 d2 6 s5 2 d7 4 l8 9 d8 10 l7 2 d8 7 ldldssldddlsl4 5 43 7 510 6 23 1 47 5 610 9 49 8 4Output2200011 | Input6 4 51 6 b2 3 a1 2 b5 3 b4 5 babbbaa1 2 16 2 31 6 24 5 41 6 2 | Output01101 | 3 seconds | 512 megabytes | ['data structures', 'string suffix structures', 'strings', 'trees', '*3400'] |
D. Stranger Treestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWill shares a psychic connection with the Upside Down Monster, so everything the monster knows, Will knows. Suddenly, he started drawing, page after page, non-stop. Joyce, his mom, and Chief Hopper put the drawings together, and they realized, it's a labeled tree! A tree is a connected acyclic graph. Will's tree has n vertices. Joyce and Hopper don't know what that means, so they're investigating this tree and similar trees. For each k such that 0ββ€βkββ€βnβ-β1, they're going to investigate all labeled trees with n vertices that share exactly k edges with Will's tree. Two labeled trees are different if and only if there's a pair of vertices (v,βu) such that there's an edge between v and u in one tree and not in the other one.Hopper and Joyce want to know how much work they have to do, so they asked you to tell them the number of labeled trees with n vertices that share exactly k edges with Will's tree, for each k. The answer could be very large, so they only asked you to tell them the answers modulo 1000000007β=β109β+β7.InputThe first line of input contains a single integer n (2ββ€βnββ€β100)Β β the size of the tree.The next nβ-β1 lines contain the edges of Will's tree. Each line contains two integers v and u (1ββ€βv,βuββ€βn, vββ βu), endpoints of an edge. It is guaranteed that the given graph is a tree.OutputPrint n integers in one line. i-th integer should be the number of the number of labeled trees with n vertices that share exactly iβ-β1 edges with Will's tree, modulo 1000β000β007β=β109β+β7.ExamplesInput31 21 3Output0 2 1 Input41 22 33 4Output1 7 7 1 Input41 21 31 4Output0 9 6 1 | Input31 21 3 | Output0 2 1 | 1 second | 256 megabytes | ['dp', 'math', 'matrices', 'trees', '*2600'] |
C. Pollywogtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs we all know, Dart is some kind of creature from Upside Down world. For simplicity, we call their kind pollywogs. Dart and xβ-β1 other pollywogs are playing a game. There are n stones in a row, numbered from 1 through n from left to right. At most 1 pollywog may be sitting on each stone at a time. Initially, the pollywogs are sitting on the first x stones (one pollywog on each stone). Dart and his friends want to end up on the last x stones. At each second, the leftmost pollywog should jump to the right. A pollywog can jump at most k stones; more specifically, a pollywog can jump from stone number i to stones iβ+β1,βiβ+β2,β... iβ+βk. A pollywog can't jump on an occupied stone. Jumping a distance i takes ci amounts of energy from the pollywog. Also, q stones are special Each time landing on a special stone p, takes wp amounts of energy (in addition to the energy for jump) from the pollywog. wp could be negative, in this case, it means the pollywog absorbs |wp| amounts of energy.Pollywogs want to spend as little energy as possible (this value could be negative). They're just pollywogs, so they asked for your help. Tell them the total change in their energy, in case they move optimally.InputThe first line of input contains four integers, x,βk,βn and q (1ββ€βxββ€βkββ€β8, kββ€βnββ€β108, 0ββ€βqββ€βmin(25,βnβ-βx))Β β the number of pollywogs, the maximum length of jump, the number of stones and the number of special stones.The next line contains k integers, c1,βc2,β... ck, separated by spaces (1ββ€βciββ€β109)Β β the energetic costs of jumps.The next q lines contain description of the special stones. Each line contains two integers p and wp (xβ+β1ββ€βpββ€βn, |wp|ββ€β109). All p are distinct.OutputPrint the minimum amount of energy they need, in the first and only line of output.ExamplesInput2 3 10 21 2 35 -106 1000Output6Input4 7 85 317 5 28 4 52 46 659 -7633 -6919 2018Output135 | Input2 3 10 21 2 35 -106 1000 | Output6 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'matrices', '*2900'] |
B. MADMAXtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter. Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round iβ-β1 (for iβ>β1). The rounds are numbered for both players together, i.Β e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?You have to determine the winner of the game for all initial positions of the marbles.InputThe first line of input contains two integers n and m (2ββ€βnββ€β100, ).The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1ββ€βv,βuββ€βn, vββ βu). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.OutputPrint n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise.ExamplesInput4 41 2 b1 3 a2 4 c3 4 bOutputBAAAABAABBBABBBBInput5 85 3 h1 2 c3 1 c3 2 r5 1 r4 3 z5 4 r5 2 hOutputBABBBBBBBBAABBBAAABAAAAABNoteHere's the graph in the first sample test case: Here's the graph in the second sample test case: | Input4 41 2 b1 3 a2 4 c3 4 b | OutputBAAAABAABBBABBBB | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'games', 'graphs', '*1700'] |
A. The Monstertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him. Thus, he came up with a puzzle to tell his mom his coordinates. His coordinates are the answer to the following problem.A string consisting only of parentheses ('(' and ')') is called a bracket sequence. Some bracket sequence are called correct bracket sequences. More formally: Empty string is a correct bracket sequence. if s is a correct bracket sequence, then (s) is also a correct bracket sequence. if s and t are correct bracket sequences, then st (concatenation of s and t) is also a correct bracket sequence. A string consisting of parentheses and question marks ('?') is called pretty if and only if there's a way to replace each question mark with either '(' or ')' such that the resulting string is a non-empty correct bracket sequence.Will gave his mom a string s consisting of parentheses and question marks (using Morse code through the lights) and his coordinates are the number of pairs of integers (l,βr) such that 1ββ€βlββ€βrββ€β|s| and the string slslβ+β1... sr is pretty, where si is i-th character of s.Joyce doesn't know anything about bracket sequences, so she asked for your help.InputThe first and only line of input contains string s, consisting only of characters '(', ')' and '?' (2ββ€β|s|ββ€β5000).OutputPrint the answer to Will's puzzle in the first and only line of output.ExamplesInput((?))Output4Input??()??Output7NoteFor the first sample testcase, the pretty substrings of s are: "(?" which can be transformed to "()". "?)" which can be transformed to "()". "((?)" which can be transformed to "(())". "(?))" which can be transformed to "(())". For the second sample testcase, the pretty substrings of s are: "??" which can be transformed to "()". "()". "??()" which can be transformed to "()()". "?()?" which can be transformed to "(())". "??" which can be transformed to "()". "()??" which can be transformed to "()()". "??()??" which can be transformed to "()()()". | Input((?)) | Output4 | 1 second | 256 megabytes | ['dp', 'greedy', 'implementation', 'math', '*1800'] |
E. Jamie and Treetime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo your surprise, Jamie is the final boss! Ehehehe.Jamie has given you a tree with n vertices, numbered from 1 to n. Initially, the root of the tree is the vertex with number 1. Also, each vertex has a value on it.Jamie also gives you three types of queries on the tree:1 vΒ β Change the tree's root to vertex with number v.2 u v xΒ β For each vertex in the subtree of smallest size that contains u and v, add x to its value.3 vΒ β Find sum of values of vertices in the subtree of vertex with number v.A subtree of vertex v is a set of vertices such that v lies on shortest path from this vertex to root of the tree. Pay attention that subtree of a vertex can change after changing the tree's root.Show your strength in programming to Jamie by performing the queries accurately!InputThe first line of input contains two space-separated integers n and q (1ββ€βnββ€β105,β1ββ€βqββ€β105)Β β the number of vertices in the tree and the number of queries to process respectively.The second line contains n space-separated integers a1,βa2,β...,βan (β-β108ββ€βaiββ€β108)Β β initial values of the vertices.Next nβ-β1 lines contains two space-separated integers ui,βvi (1ββ€βui,βviββ€βn) describing edge between vertices ui and vi in the tree.The following q lines describe the queries.Each query has one of following formats depending on its type:1 v (1ββ€βvββ€βn) for queries of the first type.2 u v x (1ββ€βu,βvββ€βn,ββ-β108ββ€βxββ€β108) for queries of the second type.3 v (1ββ€βvββ€βn) for queries of the third type.All numbers in queries' descriptions are integers.The queries must be carried out in the given order. It is guaranteed that the tree is valid.OutputFor each query of the third type, output the required answer. It is guaranteed that at least one query of the third type is given by Jamie.ExamplesInput6 71 4 2 8 5 71 23 14 34 53 63 12 4 6 33 41 62 2 4 -51 43 3Output27195Input4 64 3 5 61 22 33 43 11 32 2 4 31 12 2 4 -33 1Output1821NoteThe following picture shows how the tree varies after the queries in the first sample. | Input6 71 4 2 8 5 71 23 14 34 53 63 12 4 6 33 41 62 2 4 -51 43 3 | Output27195 | 2.5 seconds | 256 megabytes | ['data structures', 'trees', '*2400'] |
D. Jamie and To-do Listtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWhy I have to finish so many assignments???Jamie is getting very busy with his school life. He starts to forget the assignments that he has to do. He decided to write the things down on a to-do list. He assigns a value priority for each of his assignment (lower value means more important) so he can decide which he needs to spend more time on.After a few days, Jamie finds out the list is too large that he can't even manage the list by himself! As you are a good friend of Jamie, help him write a program to support the following operations on the to-do list: set ai xiΒ β Add assignment ai to the to-do list if it is not present, and set its priority to xi. If assignment ai is already in the to-do list, its priority is changed to xi. remove aiΒ β Remove assignment ai from the to-do list if it is present in it. query aiΒ β Output the number of assignments that are more important (have a smaller priority value) than assignment ai, so Jamie can decide a better schedule. Output β-β1 if ai is not in the to-do list. undo diΒ β Undo all changes that have been made in the previous di days (not including the day of this operation) At day 0, the to-do list is empty. In each of the following q days, Jamie will do exactly one out of the four operations. If the operation is a query, you should output the result of the query before proceeding to the next day, or poor Jamie cannot make appropriate decisions.InputThe first line consists of a single integer q (1ββ€βqββ€β105)Β β the number of operations.The following q lines consists of the description of the operations. The i-th line consists of the operation that Jamie has done in the i-th day. The query has the following format:The first word in the line indicates the type of operation. It must be one of the following four: set, remove, query, undo. If it is a set operation, a string ai and an integer xi follows (1ββ€βxiββ€β109). ai is the assignment that need to be set to priority xi. If it is a remove operation, a string ai follows. ai is the assignment that need to be removed. If it is a query operation, a string ai follows. ai is the assignment that needs to be queried. If it is a undo operation, an integer di follows (0ββ€βdiβ<βi). di is the number of days that changes needed to be undone. All assignment names ai only consists of lowercase English letters and have a length 1ββ€β|ai|ββ€β15.It is guaranteed that the last operation is a query operation.OutputFor each query operation, output a single integerΒ β the number of assignments that have a priority lower than assignment ai, or β-β1 if ai is not in the to-do list.InteractionIf the operation is a query, you should output the result of the query and flush the output stream before proceeding to the next operation. Otherwise, you may get the verdict Idleness Limit Exceed.For flushing the output stream, please refer to the documentation of your chosen programming language. The flush functions of some common programming languages are listed below: C: fflush(stdout); C++: cout Β« flush; Java: System.out.flush(); ExamplesInput8set chemlabreport 1set physicsexercise 2set chinesemockexam 3query physicsexercisequery chinesemockexamremove physicsexercisequery physicsexercisequery chinesemockexamOutput12-11Input8set physicsexercise 2set chinesemockexam 3set physicsexercise 1query physicsexercisequery chinesemockexamundo 4query physicsexercisequery chinesemockexamOutput010-1Input5query economicsessayremove economicsessayquery economicsessayundo 2query economicsessayOutput-1-1-1Input5set economicsessay 1remove economicsessayundo 1undo 1query economicsessayOutput-1 | Input8set chemlabreport 1set physicsexercise 2set chinesemockexam 3query physicsexercisequery chinesemockexamremove physicsexercisequery physicsexercisequery chinesemockexam | Output12-11 | 2 seconds | 512 megabytes | ['data structures', 'interactive', 'trees', '*2200'] |
C. Jamie and Interesting Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJamie has recently found undirected weighted graphs with the following properties very interesting: The graph is connected and contains exactly n vertices and m edges. All edge weights are integers and are in range [1,β109] inclusive. The length of shortest path from 1 to n is a prime number. The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number. The graph contains no loops or multi-edges. If you are not familiar with some terms from the statement you can find definitions of them in notes section. Help Jamie construct any graph with given number of vertices and edges that is interesting!InputFirst line of input contains 2 integers n, m Β β the required number of vertices and edges.OutputIn the first line output 2 integers sp, mstw (1ββ€βsp,βmstwββ€β1014)Β β the length of the shortest path and the sum of edges' weights in the minimum spanning tree.In the next m lines output the edges of the graph. In each line output 3 integers u, v, w (1ββ€βu,βvββ€βn,β1ββ€βwββ€β109) describing the edge connecting u and v and having weight w. ExamplesInput4 4Output7 71 2 32 3 23 4 22 4 4Input5 4Output7 131 2 21 3 41 4 34 5 4NoteThe graph of sample 1: Shortest path sequence: {1,β2,β3,β4}. MST edges are marked with an asterisk (*).Definition of terms used in the problem statement:A shortest path in an undirected graph is a sequence of vertices (v1,βv2,β... ,βvk) such that vi is adjacent to viβ+β1 1ββ€βiβ<βk and the sum of weight is minimized where w(i,βj) is the edge weight between i and j. (https://en.wikipedia.org/wiki/Shortest_path_problem)A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. (https://en.wikipedia.org/wiki/Prime_number)A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. (https://en.wikipedia.org/wiki/Minimum_spanning_tree)https://en.wikipedia.org/wiki/Multiple_edges | Input4 4 | Output7 71 2 32 3 23 4 22 4 4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'shortest paths', '*1600'] |
B. Jamie and Binary Sequence (changed after round)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one. To be more clear, consider all integer sequence with length k (a1,βa2,β...,βak) with . Give a value to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest.For definitions of powers and lexicographical order see notes.InputThe first line consists of two integers n and k (1ββ€βnββ€β1018,β1ββ€βkββ€β105)Β β the required sum and the length of the sequence.OutputOutput "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and k numbers separated by space in the second lineΒ β the required sequence.It is guaranteed that the integers in the answer sequence fit the range [β-β1018,β1018].ExamplesInput23 5OutputYes3 3 2 1 0 Input13 2OutputNoInput1 2OutputYes-1 -1 NoteSample 1:23β+β23β+β22β+β21β+β20β=β8β+β8β+β4β+β2β+β1β=β23Answers like (3,β3,β2,β0,β1) or (0,β1,β2,β3,β3) are not lexicographically largest.Answers like (4,β1,β1,β1,β0) do not have the minimum y value.Sample 2:It can be shown there does not exist a sequence with length 2.Sample 3:Powers of 2:If xβ>β0, then 2xβ=β2Β·2Β·2Β·...Β·2 (x times).If xβ=β0, then 2xβ=β1.If xβ<β0, then .Lexicographical order:Given two different sequences of the same length, (a1,βa2,β... ,βak) and (b1,βb2,β... ,βbk), the first one is smaller than the second one for the lexicographical order, if and only if aiβ<βbi, for the first i where ai and bi differ. | Input23 5 | OutputYes3 3 2 1 0 | 2 seconds | 256 megabytes | ['bitmasks', 'greedy', 'math', '*2000'] |
A. Jamie and Alarm Snoozetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJamie loves sleeping. One day, he decides that he needs to wake up at exactly hh:βmm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh:βmm is reached, and only then he will wake up. He wants to know what is the smallest number of times he needs to press the snooze button.A time is considered lucky if it contains a digit '7'. For example, 13:β07 and 17:β27 are lucky, while 00:β48 and 21:β34 are not lucky.Note that it is not necessary that the time set for the alarm and the wake-up time are on the same day. It is guaranteed that there is a lucky time Jamie can set so that he can wake at hh:βmm.Formally, find the smallest possible non-negative integer y such that the time representation of the time xΒ·y minutes before hh:βmm contains the digit '7'.Jamie uses 24-hours clock, so after 23:β59 comes 00:β00.InputThe first line contains a single integer x (1ββ€βxββ€β60).The second line contains two two-digit integers, hh and mm (00ββ€βhhββ€β23,β00ββ€βmmββ€β59).OutputPrint the minimum number of times he needs to press the button.ExamplesInput311 23Output2Input501 07Output0NoteIn the first sample, Jamie needs to wake up at 11:23. So, he can set his alarm at 11:17. He would press the snooze button when the alarm rings at 11:17 and at 11:20.In the second sample, Jamie can set his alarm at exactly at 01:07 which is lucky. | Input311 23 | Output2 | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'math', '*900'] |
G. Coprime Arraystime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an array a of size n coprime iff gcd(a1,βa2,β...,βan)β=β1, where gcd is the greatest common divisor of the arguments.You are given two numbers n and k. For each i (1ββ€βiββ€βk) you have to determine the number of coprime arrays a of size n such that for every j (1ββ€βjββ€βn) 1ββ€βajββ€βi. Since the answers can be very large, you have to calculate them modulo 109β+β7.InputThe first line contains two integers n and k (1ββ€βn,βkββ€β2Β·106) β the size of the desired arrays and the maximum upper bound on elements, respectively.OutputSince printing 2Β·106 numbers may take a lot of time, you have to output the answer in such a way:Let bi be the number of coprime arrays with elements in range [1,βi], taken modulo 109β+β7. You have to print , taken modulo 109β+β7. Here denotes bitwise xor operation (^ in C++ or Java, xor in Pascal).ExamplesInput3 4Output82Input2000000 8Output339310063NoteExplanation of the example:Since the number of coprime arrays is large, we will list the arrays that are non-coprime, but contain only elements in range [1,βi]:For iβ=β1, the only array is coprime. b1β=β1.For iβ=β2, array [2,β2,β2] is not coprime. b2β=β7.For iβ=β3, arrays [2,β2,β2] and [3,β3,β3] are not coprime. b3β=β25.For iβ=β4, arrays [2,β2,β2], [3,β3,β3], [2,β2,β4], [2,β4,β2], [2,β4,β4], [4,β2,β2], [4,β2,β4], [4,β4,β2] and [4,β4,β4] are not coprime. b4β=β55. | Input3 4 | Output82 | 3.5 seconds | 256 megabytes | ['math', 'number theory', '*2300'] |
F. Imbalance Value of a Treetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree T consisting of n vertices. A number is written on each vertex; the number written on vertex i is ai. Let's denote the function I(x,βy) as the difference between maximum and minimum value of ai on a simple path connecting vertices x and y.Your task is to calculate .InputThe first line contains one integer number n (1ββ€βnββ€β106) β the number of vertices in the tree.The second line contains n integer numbers a1, a2, ..., an (1ββ€βaiββ€β106) β the numbers written on the vertices.Then nβ-β1 lines follow. Each line contains two integers x and y denoting an edge connecting vertex x and vertex y (1ββ€βx,βyββ€βn, xββ βy). It is guaranteed that these edges denote a tree.OutputPrint one number equal to .ExampleInput42 2 3 11 21 31 4Output6 | Input42 2 3 11 21 31 4 | Output6 | 4 seconds | 256 megabytes | ['data structures', 'dsu', 'graphs', 'trees', '*2400'] |
E. Physical Education Lessonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis year Alex has finished school, and now he is a first-year student of Berland State University. For him it was a total surprise that even though he studies programming, he still has to attend physical education lessons. The end of the term is very soon, but, unfortunately, Alex still hasn't attended a single lesson!Since Alex doesn't want to get expelled, he wants to know the number of working days left until the end of the term, so he can attend physical education lessons during these days. But in BSU calculating the number of working days is a complicated matter:There are n days left before the end of the term (numbered from 1 to n), and initially all of them are working days. Then the university staff sequentially publishes q orders, one after another. Each order is characterised by three numbers l, r and k: If kβ=β1, then all days from l to r (inclusive) become non-working days. If some of these days are made working days by some previous order, then these days still become non-working days; If kβ=β2, then all days from l to r (inclusive) become working days. If some of these days are made non-working days by some previous order, then these days still become working days. Help Alex to determine the number of working days left after each order!InputThe first line contains one integer n, and the second line β one integer q (1ββ€βnββ€β109, 1ββ€βqββ€β3Β·105) β the number of days left before the end of the term, and the number of orders, respectively.Then q lines follow, i-th line containing three integers li, ri and ki representing i-th order (1ββ€βliββ€βriββ€βn, 1ββ€βkiββ€β2).OutputPrint q integers. i-th of them must be equal to the number of working days left until the end of the term after the first i orders are published.ExampleInput461 2 13 4 12 3 21 3 22 4 11 4 2Output202314 | Input461 2 13 4 12 3 21 3 22 4 11 4 2 | Output202314 | 1 second | 256 megabytes | ['data structures', 'implementation', 'sortings', '*2300'] |
D. Almost Acyclic Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed graph consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn't contain any cycle (a non-empty path that starts and ends in the same vertex).InputThe first line contains two integers n and m (2ββ€βnββ€β500, 1ββ€βmββ€βmin(n(nβ-β1),β100000)) β the number of vertices and the number of edges, respectively.Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1ββ€βu,βvββ€βn, uββ βv). Each ordered pair (u,βv) is listed at most once (there is at most one directed edge from u to v).OutputIf it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.ExamplesInput3 41 22 33 23 1OutputYESInput5 61 22 33 23 12 14 5OutputNONoteIn the first example you can remove edge , and the graph becomes acyclic.In the second example you have to remove at least two edges (for example, and ) in order to make the graph acyclic. | Input3 41 22 33 23 1 | OutputYES | 1 second | 256 megabytes | ['dfs and similar', 'graphs', '*2200'] |
C. Permute Digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.It is allowed to leave a as it is.InputThe first line contains integer a (1ββ€βaββ€β1018). The second line contains integer b (1ββ€βbββ€β1018). Numbers don't have leading zeroes. It is guaranteed that answer exists.OutputPrint the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists.The number in the output should have exactly the same length as number a. It should be a permutation of digits of a.ExamplesInput123222Output213Input392110000Output9321Input49405000Output4940 | Input123222 | Output213 | 1 second | 256 megabytes | ['dp', 'greedy', '*1700'] |
B. Browsertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this segment as fast as possible.Each second Luba can either try moving the cursor to the left or to the right (if the cursor is currently at the tab i, then she can move it to the tab max(iβ-β1,βa) or to the tab min(iβ+β1,βb)) or try closing all the tabs to the left or to the right of the cursor (if the cursor is currently at the tab i, she can close all the tabs with indices from segment [a,βiβ-β1] or from segment [iβ+β1,βb]). In the aforementioned expressions a and b denote the minimum and maximum index of an unclosed tab, respectively. For example, if there were 7 tabs initially and tabs 1, 2 and 7 are closed, then aβ=β3, bβ=β6.What is the minimum number of seconds Luba has to spend in order to leave only the tabs with initial indices from l to r inclusive opened?InputThe only line of input contains four integer numbers n, pos, l, r (1ββ€βnββ€β100, 1ββ€βposββ€βn, 1ββ€βlββ€βrββ€βn) β the number of the tabs, the cursor position and the segment which Luba needs to leave opened.OutputPrint one integer equal to the minimum number of seconds required to close all the tabs outside the segment [l,βr].ExamplesInput6 3 2 4Output5Input6 3 1 3Output1Input5 2 1 5Output0NoteIn the first test Luba can do the following operations: shift the mouse cursor to the tab 2, close all the tabs to the left of it, shift the mouse cursor to the tab 3, then to the tab 4, and then close all the tabs to the right of it.In the second test she only needs to close all the tabs to the right of the current position of the cursor.In the third test Luba doesn't need to do anything. | Input6 3 2 4 | Output5 | 1 second | 256 megabytes | ['implementation', '*1300'] |
A. Gardentime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuba thinks about watering her garden. The garden can be represented as a segment of length k. Luba has got n buckets, the i-th bucket allows her to water some continuous subsegment of garden of length exactly ai each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden.Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length ai if she chooses the i-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.See the examples for better understanding.InputThe first line of input contains two integer numbers n and k (1ββ€βn,βkββ€β100) β the number of buckets and the length of the garden, respectively.The second line of input contains n integer numbers ai (1ββ€βaiββ€β100) β the length of the segment that can be watered by the i-th bucket in one hour.It is guaranteed that there is at least one bucket such that it is possible to water the garden in integer number of hours using only this bucket.OutputPrint one integer number β the minimum number of hours required to water the garden.ExamplesInput3 62 3 5Output2Input6 71 2 3 4 5 6Output7NoteIn the first test the best option is to choose the bucket that allows to water the segment of length 3. We can't choose the bucket that allows to water the segment of length 5 because then we can't water the whole garden.In the second test we can choose only the bucket that allows us to water the segment of length 1. | Input3 62 3 5 | Output2 | 1 second | 256 megabytes | ['implementation', '*900'] |
H. Ember and Storm's Tree Gametime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEmber and Storm play a game. First, Ember picks a labelled tree T of n vertices, such that the degree of every vertex is at most d. Then, Storm picks two distinct vertices u and v in this tree and writes down the labels of the vertices in the path from u to v in a sequence a1,βa2... ak. Finally, Ember picks any index i (1ββ€βiβ<βk) in the array. Now he performs one of the following two operations exactly once: flip the subrange [iβ+β1,βk] and add ai to it. After this, the sequence becomes a1,β... ai,βakβ+βai,βakβ-β1β+βai,β... aiβ+β1β+βai negate the subrange [iβ+β1,βk] and add ai to it. i.e., the array becomes a1,β... ai,ββ-βaiβ+β1β+βai,ββ-βaiβ+β2β+βai,β...β-βakβ+βai Ember wins if the array is monotonically increasing or decreasing after this. Otherwise Storm wins.The game can be described by the tuple (T,βu,βv,βi,βop) where op is Β«flipΒ» or Β«negateΒ» depending on the action Ember chose in the last turn. Find the number of tuples that can occur if Ember and Storm play optimally. When they play optimally, if there are multiple moves by which they are guaranteed to win, then they may play any of the winning moves. Otherwise, if someone loses no matter what they play, then they may play any of the possible moves.Report the answer modulo m.InputThe input consists of a single line containing three integers n, d and m (2ββ€βnββ€β200,β1ββ€βdβ<βn,β1ββ€βmββ€β2Β·109).OutputPrint a single number Β β the number of possible tuples if Ember and Storm play as described, modulo m.ExamplesInput2 1 1000000007Output4Input3 1 250Output0Input3 2 100Output36NoteIn the first sample case, there is only one possible tree. There are two possible paths, 1 to 2 and 2 to 1. For both paths, i can only be 1, and op can take both possibilities. Therefore, the answer is 4.In the second sample, there are no possible trees.In the third sample, there are three possible trees. | Input2 1 1000000007 | Output4 | 3 seconds | 512 megabytes | ['combinatorics', 'dp', 'games', 'trees', '*3400'] |
G. Sum the Fibonaccitime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array s of n non-negative integers.A 5-tuple of integers (a,βb,βc,βd,βe) is said to be valid if it satisfies the following conditions: 1ββ€βa,βb,βc,βd,βeββ€βn (sa | sb) & sc & (sd ^ se)β=β2i for some integer i sa & sbβ=β0 Here, '|' is the bitwise OR, '&' is the bitwise AND and '^' is the bitwise XOR operation.Find the sum of f(sa|sb)β*βf(sc)β*βf(sd^se) over all valid 5-tuples (a,βb,βc,βd,βe), where f(i) is the i-th Fibonnaci number (f(0)β=β0,βf(1)β=β1,βf(i)β=βf(iβ-β1)β+βf(iβ-β2)).Since answer can be is huge output it modulo 109β+β7.InputThe first line of input contains an integer n (1ββ€βnββ€β106).The second line of input contains n integers si (0ββ€βsiβ<β217).OutputOutput the sum as described above, modulo 109β+β7ExamplesInput21 2Output32Input37 4 1Output3520Input101 3 0 7 3 7 6 5 7 5Output1235424Input1050 9 11 44 39 40 5 39 23 7Output113860062 | Input21 2 | Output32 | 4 seconds | 256 megabytes | ['bitmasks', 'divide and conquer', 'dp', 'fft', 'math', '*2600'] |
F. Substrings in a Stringtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a string s, process q queries, each having one of the following forms: 1βiβc β Change the i-th character in the string to c. 2βlβrβy β Consider the substring of s starting at position l and ending at position r. Output the number of times y occurs as a substring in it. InputThe first line of the input contains the string s (1ββ€β|s|ββ€β105) of lowercase English letters.The second line contains an integer q (1ββ€βqββ€β105) Β β the number of queries to process.The next q lines describe the queries and may have one of the following forms: 1βiβc (1ββ€βiββ€β|s|) 2βlβrβy (1ββ€βlββ€βrββ€β|s|) c is a lowercase English letter and y is a non-empty string consisting of only lowercase English letters.The sum of |y| over all queries of second type is at most 105.It is guaranteed that there is at least one query of second type.All strings are 1-indexed.|s| is the length of the string s.OutputFor each query of type 2, output the required answer in a separate line.ExamplesInputababababa32 1 7 aba1 5 c2 1 7 abaOutput31Inputabcdcbc52 1 7 bc1 4 b2 4 7 bc1 2 a2 1 4 aaOutput221NoteConsider the first sample case. Initially, the string aba occurs 3 times in the range [1,β7]. Note that two occurrences may overlap. After the update, the string becomes ababcbaba and now aba occurs only once in the range [1,β7]. | Inputababababa32 1 7 aba1 5 c2 1 7 aba | Output31 | 6 seconds | 256 megabytes | ['bitmasks', 'brute force', 'data structures', 'string suffix structures', 'strings', '*3000'] |
E. Palindromes in a Treetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t.A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome.For each vertex, output the number of palindromic paths passing through it. Note: The path from vertex u to vertex v is considered to be the same as the path from vertex v to vertex u, and this path will be counted only once for each of the vertices it passes through.InputThe first line contains an integer n (2ββ€βnββ€β2Β·105) Β β the number of vertices in the tree.The next nβ-β1 lines each contain two integers u and v (1βββ€ββu,βvβββ€ββn,βuββ βv) denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree.The next line contains a string consisting of n lowercase characters from a to t where the i-th (1ββ€βiββ€βn) character is the label of vertex i in the tree.OutputPrint n integers in a single line, the i-th of which is the number of palindromic paths passing through vertex i in the tree.ExamplesInput51 22 33 43 5abcbbOutput1 3 4 3 3 Input76 24 33 75 27 21 4afefdfsOutput1 4 1 1 2 4 2 NoteIn the first sample case, the following paths are palindromic:2β-β3β-β42β-β3β-β54β-β3β-β5Additionally, all paths containing only one vertex are palindromic. Listed below are a few paths in the first sample that are not palindromic:1β-β2β-β31β-β2β-β3β-β41β-β2β-β3β-β5 | Input51 22 33 43 5abcbb | Output1 3 4 3 3 | 4 seconds | 256 megabytes | ['bitmasks', 'data structures', 'divide and conquer', 'trees', '*2400'] |
D. Bash and a Tough Math Puzzletime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBash likes playing with arrays. He has an array a1,βa2,β... an of n integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.Suppose he guesses that the gcd of the elements in the range [l,βr] of a is x. He considers the guess to be almost correct if he can change at most one element in the segment such that the gcd of the segment is x after making the change. Note that when he guesses, he doesn't actually change the array β he just wonders if the gcd of the segment can be made x. Apart from this, he also sometimes makes changes to the array itself.Since he can't figure it out himself, Bash wants you to tell him which of his guesses are almost correct. Formally, you have to process q queries of one of the following forms: 1βlβrβx β Bash guesses that the gcd of the range [l,βr] is x. Report if this guess is almost correct. 2βiβy β Bash sets ai to y. Note: The array is 1-indexed.InputThe first line contains an integer n (1ββ€βnββ€β5Β·105) Β β the size of the array.The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109) Β β the elements of the array.The third line contains an integer q (1ββ€βqββ€β4Β·105) Β β the number of queries.The next q lines describe the queries and may have one of the following forms: 1βlβrβx (1ββ€βlββ€βrββ€βn,β1ββ€βxββ€β109). 2βiβy (1ββ€βiββ€βn,β1ββ€βyββ€β109). Guaranteed, that there is at least one query of first type.OutputFor each query of first type, output "YES" (without quotes) if Bash's guess is almost correct and "NO" (without quotes) otherwise.ExamplesInput32 6 341 1 2 21 1 3 32 1 91 1 3 2OutputYESYESNOInput51 2 3 4 561 1 4 22 3 61 1 4 21 1 5 22 5 101 1 5 2OutputNOYESNOYESNoteIn the first sample, the array initially is {2,β6,β3}. For query 1, the first two numbers already have their gcd as 2.For query 2, we can achieve a gcd of 3 by changing the first element of the array to 3. Note that the changes made during queries of type 1 are temporary and do not get reflected in the array. After query 3, the array is now {9,β6,β3}. For query 4, no matter which element you change, you cannot get the gcd of the range to be 2. | Input32 6 341 1 2 21 1 3 32 1 91 1 3 2 | OutputYESYESNO | 2.5 seconds | 256 megabytes | ['data structures', 'number theory', '*1900'] |
C. Travelling Salesman and Special Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer x and reduce it to the number of bits set to 1 in the binary representation of x. For example for number 13 it's true that 1310β=β11012, so it has 3 bits set and 13 will be reduced to 3 in one operation.He calls a number special if the minimum number of operations to reduce it to 1 is k.He wants to find out how many special numbers exist which are not greater than n. Please help the Travelling Salesman, as he is about to reach his destination!Since the answer can be large, output it modulo 109β+β7.InputThe first line contains integer n (1ββ€βnβ<β21000).The second line contains integer k (0ββ€βkββ€β1000).Note that n is given in its binary representation without any leading zeros.OutputOutput a single integerΒ β the number of special numbers not greater than n, modulo 109β+β7.ExamplesInput1102Output3Input1111110112Output169NoteIn the first sample, the three special numbers are 3, 5 and 6. They get reduced to 2 in one operation (since there are two set bits in each of 3, 5 and 6) and then to 1 in one more operation (since there is only one set bit in 2). | Input1102 | Output3 | 1 second | 256 megabytes | ['brute force', 'combinatorics', 'dp', '*1800'] |
B. Conan and Agasa play a Card Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEdogawa Conan got tired of solving cases, and invited his friend, Professor Agasa, over. They decided to play a game of cards. Conan has n cards, and the i-th card has a number ai written on it.They take turns playing, starting with Conan. In each turn, the player chooses a card and removes it. Also, he removes all cards having a number strictly lesser than the number on the chosen card. Formally, if the player chooses the i-th card, he removes that card and removes the j-th card for all j such that ajβ<βai.A player loses if he cannot make a move on his turn, that is, he loses if there are no cards left. Predict the outcome of the game, assuming both players play optimally.InputThe first line contains an integer n (1ββ€βnββ€β105)Β β the number of cards Conan has. The next line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β105), where ai is the number on the i-th card.OutputIf Conan wins, print "Conan" (without quotes), otherwise print "Agasa" (without quotes).ExamplesInput34 5 7OutputConanInput21 1OutputAgasaNoteIn the first example, Conan can just choose the card having number 7 on it and hence remove all the cards. After that, there are no cards left on Agasa's turn.In the second example, no matter which card Conan chooses, there will be one one card left, which Agasa can choose. After that, there are no cards left when it becomes Conan's turn again. | Input34 5 7 | OutputConan | 2 seconds | 256 megabytes | ['games', 'greedy', 'implementation', '*1200'] |
A. Perfect Squarestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a1,βa2,β...,βan of n integers, find the largest number in the array that is not a perfect square.A number x is said to be a perfect square if there exists an integer y such that xβ=βy2.InputThe first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of elements in the array.The second line contains n integers a1,βa2,β...,βan (β-β106ββ€βaiββ€β106)Β β the elements of the array.It is guaranteed that at least one element of the array is not a perfect square.OutputPrint the largest number in the array which is not a perfect square. It is guaranteed that an answer always exists.ExamplesInput24 2Output2Input81 2 4 8 16 32 64 576Output32NoteIn the first sample case, 4 is a perfect square, so the largest number in the array that is not a perfect square is 2. | Input24 2 | Output2 | 1 second | 256 megabytes | ['brute force', 'implementation', 'math', '*900'] |
H. Don't Exceedtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou generate real numbers s1,βs2,β...,βsn as follows: s0β=β0; siβ=βsiβ-β1β+βti, where ti is a real number chosen independently uniformly at random between 0 and 1, inclusive. You are given real numbers x1,βx2,β...,βxn. You are interested in the probability that siββ€βxi is true for all i simultaneously.It can be shown that this can be represented as , where P and Q are coprime integers, and . Print the value of PΒ·Qβ-β1 modulo 998244353.InputThe first line contains integer n (1ββ€βnββ€β30).The next n lines contain real numbers x1,βx2,β...,βxn, given with at most six digits after the decimal point (0β<βxiββ€βn).OutputPrint a single integer, the answer to the problem.ExamplesInput41.0023.0000004.0Output1Input10.50216Output342677322Input20.51.0Output623902721Input60.771.2345672.11.8902.99993.77Output859831967NoteIn the first example, the sought probability is 1 since the sum of i real numbers which don't exceed 1 doesn't exceed i.In the second example, the probability is x1 itself.In the third example, the sought probability is 3β/β8. | Input41.0023.0000004.0 | Output1 | 4 seconds | 256 megabytes | ['math', 'probabilities', '*3400'] |
G. Power Substringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n positive integers a1,βa2,β...,βan.For every ai you need to find a positive integer ki such that the decimal notation of 2ki contains the decimal notation of ai as a substring among its last min(100,βlength(2ki)) digits. Here length(m) is the length of the decimal notation of m.Note that you don't have to minimize ki. The decimal notations in this problem do not contain leading zeros.InputThe first line contains a single integer n (1ββ€βnββ€β2β000)Β β the number of integers ai.Each of the next n lines contains a positive integer ai (1ββ€βaiβ<β1011).OutputPrint n lines. The i-th of them should contain a positive integer ki such that the last min(100,βlength(2ki)) digits of 2ki contain the decimal notation of ai as a substring. Integers ki must satisfy 1ββ€βkiββ€β1050.It can be shown that the answer always exists under the given constraints. If there are multiple answers, print any of them.ExamplesInput282Output31Input234857Output520 | Input282 | Output31 | 2 seconds | 256 megabytes | ['math', 'number theory', '*3200'] |
F. Strongly Connected Tournamenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a chess tournament in All-Right-City. n players were invited to take part in the competition. The tournament is held by the following rules: Initially, each player plays one game with every other player. There are no ties; After that, the organizers build a complete directed graph with players as vertices. For every pair of players there is exactly one directed edge between them: the winner of their game is the startpoint of this edge and the loser is the endpoint; After that, the organizers build a condensation of this graph. The condensation of this graph is an acyclic complete graph, therefore it has the only Hamiltonian path which consists of strongly connected components of initial graph A1βββA2βββ...βββAk. The players from the first component A1 are placed on the first places, the players from the component A2 are placed on the next places, and so on. To determine exact place of each player in a strongly connected component, all the procedures from 1 to 5 are repeated recursively inside each component, i.e. for every iβ=β1,β2,β...,βk players from the component Ai play games with each other again, and so on; If a component consists of a single player, then he has no more rivals, his place is already determined and the process stops. The players are enumerated with integers from 1 to n. The enumeration was made using results of a previous tournament. It is known that player i wins player j (iβ<βj) with probability p.You need to help to organize the tournament. Find the expected value of total number of games played by all the players. It can be shown that the answer can be represented as , where P and Q are coprime integers and . Print the value of PΒ·Qβ-β1 modulo 998244353.If you are not familiar with any of the terms above, you can read about them here.InputThe first line of input contains a single integer n (2ββ€βnββ€β2000)Β β the number of players.The second line contains two integers a and b (1ββ€βaβ<βbββ€β100)Β β the numerator and the denominator of fraction .OutputIn the only line print the expected value of total number of games played by all the players. Print the answer using the format above.ExamplesInput31 2Output4Input34 6Output142606340Input41 2Output598946623NoteIn the first example the expected value is 4.In the second example the expected value is .In the third example the expected value is . | Input31 2 | Output4 | 2 seconds | 256 megabytes | ['dp', 'graphs', 'math', 'probabilities', '*2800'] |
E. Logical Expressiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of: Operation AND ('&', ASCII code 38) Operation OR ('|', ASCII code 124) Operation NOT ('!', ASCII code 33) Variables x, y and z (ASCII codes 120-122) Parentheses ('(', ASCII code 40, and ')', ASCII code 41) If more than one expression of minimum length exists, you should find the lexicographically smallest one.Operations have standard priority. NOT has the highest priority, then AND goes, and OR has the lowest priority. The expression should satisfy the following grammar:E ::= E '|' T | TT ::= T '&' F | FF ::= '!' F | '(' E ')' | 'x' | 'y' | 'z'InputThe first line contains one integer nΒ β the number of functions in the input (1ββ€βnββ€β10β000).The following n lines contain descriptions of functions, the i-th of them contains a string of length 8 that consists of digits 0 and 1Β β the truth table of the i-th function. The digit on position j (0ββ€βjβ<β8) equals to the value of the function in case of , and .OutputYou should output n lines, the i-th line should contain the expression of minimum length which equals to the i-th function. If there is more than one such expression, output the lexicographically smallest of them. Expressions should satisfy the given grammar and shouldn't contain white spaces.ExampleInput400110011000001111111000000011111Outputy(y|z)&x!xx|y&zNoteThe truth table for the second function: | Input400110011000001111111000000011111 | Outputy(y|z)&x!xx|y&z | 3 seconds | 256 megabytes | ['bitmasks', 'dp', 'shortest paths', '*2400'] |
D. Too Easy Problemstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are preparing for an exam on scheduling theory. The exam will last for exactly T milliseconds and will consist of n problems. You can either solve problem i in exactly ti milliseconds or ignore it and spend no time. You don't need time to rest after solving a problem, either.Unfortunately, your teacher considers some of the problems too easy for you. Thus, he assigned an integer ai to every problem i meaning that the problem i can bring you a point to the final score only in case you have solved no more than ai problems overall (including problem i).Formally, suppose you solve problems p1,βp2,β...,βpk during the exam. Then, your final score s will be equal to the number of values of j between 1 and k such that kββ€βapj.You have guessed that the real first problem of the exam is already in front of you. Therefore, you want to choose a set of problems to solve during the exam maximizing your final score in advance. Don't forget that the exam is limited in time, and you must have enough time to solve all chosen problems. If there exist different sets of problems leading to the maximum final score, any of them will do.InputThe first line contains two integers n and T (1ββ€βnββ€β2Β·105; 1ββ€βTββ€β109)Β β the number of problems in the exam and the length of the exam in milliseconds, respectively.Each of the next n lines contains two integers ai and ti (1ββ€βaiββ€βn; 1ββ€βtiββ€β104). The problems are numbered from 1 to n.OutputIn the first line, output a single integer sΒ β your maximum possible final score.In the second line, output a single integer k (0ββ€βkββ€βn)Β β the number of problems you should solve.In the third line, output k distinct integers p1,βp2,β...,βpk (1ββ€βpiββ€βn)Β β the indexes of problems you should solve, in any order.If there are several optimal sets of problems, you may output any of them.ExamplesInput5 3003 1004 1504 802 902 300Output233 1 4Input2 1001 7872 788Output00Input2 1002 422 58Output221 2NoteIn the first example, you should solve problems 3, 1, and 4. In this case you'll spend 80β+β100β+β90β=β270 milliseconds, falling within the length of the exam, 300 milliseconds (and even leaving yourself 30 milliseconds to have a rest). Problems 3 and 1 will bring you a point each, while problem 4 won't. You'll score two points.In the second example, the length of the exam is catastrophically not enough to solve even a single problem.In the third example, you have just enough time to solve both problems in 42β+β58β=β100 milliseconds and hand your solutions to the teacher with a smile. | Input5 3003 1004 1504 802 902 300 | Output233 1 4 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'greedy', 'sortings', '*1800'] |
C. Party Lemonadetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA New Year party is not a New Year party without lemonade! As usual, you are expecting a lot of guests, and buying lemonade has already become a pleasant necessity.Your favorite store sells lemonade in bottles of n different volumes at different costs. A single bottle of type i has volume 2iβ-β1 liters and costs ci roubles. The number of bottles of each type in the store can be considered infinite.You want to buy at least L liters of lemonade. How many roubles do you have to spend?InputThe first line contains two integers n and L (1ββ€βnββ€β30; 1ββ€βLββ€β109)Β β the number of types of bottles in the store and the required amount of lemonade in liters, respectively.The second line contains n integers c1,βc2,β...,βcn (1ββ€βciββ€β109)Β β the costs of bottles of different types.OutputOutput a single integerΒ β the smallest number of roubles you have to pay in order to buy at least L liters of lemonade.ExamplesInput4 1220 30 70 90Output150Input4 310000 1000 100 10Output10Input4 310 100 1000 10000Output30Input5 787787787123456789 234567890 345678901 456789012 987654321Output44981600785557577NoteIn the first example you should buy one 8-liter bottle for 90 roubles and two 2-liter bottles for 30 roubles each. In total you'll get 12 liters of lemonade for just 150 roubles.In the second example, even though you need only 3 liters, it's cheaper to buy a single 8-liter bottle for 10 roubles.In the third example it's best to buy three 1-liter bottles for 10 roubles each, getting three liters for 30 roubles. | Input4 1220 30 70 90 | Output150 | 1 second | 256 megabytes | ['bitmasks', 'dp', 'greedy', '*1600'] |
B. Christmas Sprucetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.InputThe first line contains one integer nΒ β the number of vertices in the tree (3ββ€βnββ€β1β000). Each of the next nβ-β1 lines contains one integer pi (1ββ€βiββ€βnβ-β1)Β β the index of the parent of the iβ+β1-th vertex (1ββ€βpiββ€βi).Vertex 1 is the root. It's guaranteed that the root has at least 2 children.OutputPrint "Yes" if the tree is a spruce and "No" otherwise.ExamplesInput4111OutputYesInput7111222OutputNoInput81111333OutputYesNoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example: | Input4111 | OutputYes | 1 second | 256 megabytes | ['implementation', 'trees', '*1200'] |
A. Modular Exponentiationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe following problem is well-known: given integers n and m, calculate , where 2nβ=β2Β·2Β·...Β·2 (n factors), and denotes the remainder of division of x by y.You are asked to solve the "reverse" problem. Given integers n and m, calculate . InputThe first line contains a single integer n (1ββ€βnββ€β108).The second line contains a single integer m (1ββ€βmββ€β108).OutputOutput a single integerΒ β the value of .ExamplesInput442Output10Input158Output0Input9876543223456789Output23456789NoteIn the first example, the remainder of division of 42 by 24β=β16 is equal to 10.In the second example, 58 is divisible by 21β=β2 without remainder, and the answer is 0. | Input442 | Output10 | 1 second | 256 megabytes | ['implementation', 'math', '*900'] |
E. Prime Gifttime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOpposite to Grisha's nice behavior, Oleg, though he has an entire year at his disposal, didn't manage to learn how to solve number theory problems in the past year. That's why instead of Ded Moroz he was visited by his teammate Andrew, who solemnly presented him with a set of n distinct prime numbers alongside with a simple task: Oleg is to find the k-th smallest integer, such that all its prime divisors are in this set. InputThe first line contains a single integer n (1ββ€βnββ€β16).The next line lists n distinct prime numbers p1,βp2,β...,βpn (2ββ€βpiββ€β100) in ascending order.The last line gives a single integer k (1ββ€βk). It is guaranteed that the k-th smallest integer such that all its prime divisors are in this set does not exceed 1018.OutputPrint a single line featuring the k-th smallest integer. It's guaranteed that the answer doesn't exceed 1018.ExamplesInput32 3 57Output8Input53 7 11 13 3117Output93NoteThe list of numbers with all prime divisors inside {2,β3,β5} begins as follows:(1,β2,β3,β4,β5,β6,β8,β...)The seventh number in this list (1-indexed) is eight. | Input32 3 57 | Output8 | 3.5 seconds | 256 megabytes | ['binary search', 'dfs and similar', 'math', 'meet-in-the-middle', 'number theory', 'two pointers', '*2400'] |
D. Fishestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size nβΓβm, divided into cells of size 1βΓβ1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!).The gift bundle also includes a square scoop of size rβΓβr, designed for fishing. If the lower-left corner of the scoop-net is located at cell (x,βy), all fishes inside the square (x,βy)...(xβ+βrβ-β1,βyβ+βrβ-β1) get caught. Note that the scoop-net should lie completely inside the pond when used.Unfortunately, Sasha is not that skilled in fishing and hence throws the scoop randomly. In order to not frustrate Sasha, Misha decided to release k fishes into the empty pond in such a way that the expected value of the number of caught fishes is as high as possible. Help Misha! In other words, put k fishes in the pond into distinct cells in such a way that when the scoop-net is placed into a random position among (nβ-βrβ+β1)Β·(mβ-βrβ+β1) possible positions, the average number of caught fishes is as high as possible.InputThe only line contains four integers n,βm,βr,βk (1ββ€βn,βmββ€β105, 1ββ€βrββ€βmin(n,βm), 1ββ€βkββ€βmin(nΒ·m,β105)).OutputPrint a single numberΒ β the maximum possible expected number of caught fishes.You answer is considered correct, is its absolute or relative error does not exceed 10β-β9. Namely, let your answer be a, and the jury's answer be b. Your answer is considered correct, if .ExamplesInput3 3 2 3Output2.0000000000Input12 17 9 40Output32.8333333333NoteIn the first example you can put the fishes in cells (2,β1), (2,β2), (2,β3). In this case, for any of four possible positions of the scoop-net (highlighted with light green), the number of fishes inside is equal to two, and so is the expected value. | Input3 3 2 3 | Output2.0000000000 | 1 second | 256 megabytes | ['data structures', 'graphs', 'greedy', 'probabilities', 'shortest paths', '*2100'] |
C. Perun, Ult!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA lot of students spend their winter holidays productively. Vlad has advanced very well in doing so! For three days already, fueled by salads and tangerinesΒ β the leftovers from New Year celebrationΒ β he has been calibrating his rating in his favorite MOBA game, playing as a hero named Perun.Perun has an ultimate ability called "Thunderwrath". At the instant of its activation, each enemy on the map (n of them in total) loses health points as a single-time effect. It also has a restriction: it can only activated when the moment of time is an integer. The initial bounty for killing an enemy is . Additionally, it increases by each second. Formally, if at some second t the ability is activated and the i-th enemy is killed as a result (i.e. his health drops to zero or lower), Vlad earns units of gold.Every enemy can receive damage, as well as be healed. There are multiple ways of doing so, but Vlad is not interested in details. For each of n enemies he knows: Β β maximum number of health points for the i-th enemy; Β β initial health of the enemy (on the 0-th second); Β β the amount of health the i-th enemy can regenerate per second. There also m health updates Vlad knows about: Β β time when the health was updated; Β β the enemy whose health was updated; Β β updated health points for enemyj. Obviously, Vlad wants to maximize his profit. If it's necessary, he could even wait for years to activate his ability at the right second. Help him determine the exact second (note that it must be an integer) from 0 (inclusively) to β+ββ so that a single activation of the ability would yield Vlad the maximum possible amount of gold, and print this amount.InputIn the first line, two integers are given (separated by spaces)Β β n and m (1ββ€βnββ€β105, 0ββ€βmββ€β105).In the second line, there are three integers: , and (, ).Each of the following n lines has three integersΒ β , , (, ).The next m lines contain three integers eachΒ β , , (, , ). It is guaranteed that there is no more than one hearth change per second for each enemy: more formally, for each a,βb so that 1ββ€βa,βbββ€βm,βaββ βb holds that if , then .OutputOutput the single integerΒ β the maximum amount of gold Vlad can obtain if he applies "Thunderwrath" exactly once, or -1 if this amount can be infinitely large.ExamplesInput3 21000 10 5070 5 590 70 1110 20 220 2 1030 3 10Output3000Input1 1500 50 1000750 750 2010 1 300Output-1NoteOn the pictures you can see health points of each enemy versus time in sample cases.Periods when Vlad can kill one enemy are marked with yellow color.Periods when Vlad can kill two enemies are marked with purple color. In the first sample case, Vlad can activate the ability at the 50-th second: the enemies 2 and 3 will die since they would have 40 and 50 health points correspondingly. Vlad will earn 2Β·(1000β+β50Β·10)β=β3000 gold. In the second sample case, the maximum amount of health for the enemy 1 is less than the damage dealt by the ability. Hence, the enemy could be killed anytime. As the bounty increases by 50 over the time, the maximum possible amount of gold is infinite. | Input3 21000 10 5070 5 590 70 1110 20 220 2 1030 3 10 | Output3000 | 1 second | 256 megabytes | ['brute force', 'greedy', 'sortings', '*2500'] |
B. New Year's Evetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSince Grisha behaved well last year, at New Year's Eve he was visited by Ded Moroz who brought an enormous bag of gifts with him! The bag contains n sweet candies from the good ol' bakery, each labeled from 1 to n corresponding to its tastiness. No two candies have the same tastiness.The choice of candies has a direct effect on Grisha's happiness. One can assume that he should take the tastiest onesΒ β but no, the holiday magic turns things upside down. It is the xor-sum of tastinesses that matters, not the ordinary sum!A xor-sum of a sequence of integers a1,βa2,β...,βam is defined as the bitwise XOR of all its elements: , here denotes the bitwise XOR operation; more about bitwise XOR can be found here.Ded Moroz warned Grisha he has more houses to visit, so Grisha can take no more than k candies from the bag. Help Grisha determine the largest xor-sum (largest xor-sum means maximum happiness!) he can obtain.InputThe sole string contains two integers n and k (1ββ€βkββ€βnββ€β1018).OutputOutput one numberΒ β the largest possible xor-sum.ExamplesInput4 3Output7Input6 6Output7NoteIn the first sample case, one optimal answer is 1, 2 and 4, giving the xor-sum of 7.In the second sample case, one can, for example, take all six candies and obtain the xor-sum of 7. | Input4 3 | Output7 | 1 second | 256 megabytes | ['bitmasks', 'constructive algorithms', 'number theory', '*1300'] |
A. Tricky Alchemytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the winter holidays, the demand for Christmas balls is exceptionally high. Since it's already 2018, the advances in alchemy allow easy and efficient ball creation by utilizing magic crystals.Grisha needs to obtain some yellow, green and blue balls. It's known that to produce a yellow ball one needs two yellow crystals, greenΒ β one yellow and one blue, and for a blue ball, three blue crystals are enough.Right now there are A yellow and B blue crystals in Grisha's disposal. Find out how many additional crystals he should acquire in order to produce the required number of balls.InputThe first line features two integers A and B (0ββ€βA,βBββ€β109), denoting the number of yellow and blue crystals respectively at Grisha's disposal.The next line contains three integers x, y and z (0ββ€βx,βy,βzββ€β109)Β β the respective amounts of yellow, green and blue balls to be obtained.OutputPrint a single integerΒ β the minimum number of crystals that Grisha should acquire in addition.ExamplesInput4 32 1 1Output2Input3 91 1 3Output1Input12345678 8765432143043751 1000000000 53798715Output2147483648NoteIn the first sample case, Grisha needs five yellow and four blue crystals to create two yellow balls, one green ball, and one blue ball. To do that, Grisha needs to obtain two additional crystals: one yellow and one blue. | Input4 32 1 1 | Output2 | 1 second | 256 megabytes | ['implementation', '*800'] |
G. Mass Change Queriestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. You have to process q queries to this array; each query is given as four numbers l, r, x and y, denoting that for every i such that lββ€βiββ€βr and aiβ=βx you have to set ai equal to y.Print the array after all queries are processed.InputThe first line contains one integer n (1ββ€βnββ€β200000) β the size of array a.The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β100) β the elements of array a.The third line contains one integer q (1ββ€βqββ€β200000) β the number of queries you have to process.Then q lines follow. i-th line contains four integers l, r, x and y denoting i-th query (1ββ€βlββ€βrββ€βn, 1ββ€βx,βyββ€β100).OutputPrint n integers β elements of array a after all changes are made.ExampleInput51 2 3 4 533 5 3 51 5 5 11 5 1 5Output5 2 5 4 5 | Input51 2 3 4 533 5 3 51 5 5 11 5 1 5 | Output5 2 5 4 5 | 3 seconds | 512 megabytes | ['data structures', '*2500'] |
F. Tree Destructiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with n vertices. Then nβ-β1 following operations are applied to the tree. A single operation consists of the following steps: choose two leaves; add the length of the simple path between them to the answer; remove one of the chosen leaves from the tree. Initial answer (before applying operations) is 0. Obviously after nβ-β1 such operations the tree will consist of a single vertex. Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer!InputThe first line contains one integer number n (2ββ€βnββ€β2Β·105) β the number of vertices in the tree. Next nβ-β1 lines describe the edges of the tree in form ai,βbi (1ββ€βai, biββ€βn, aiββ βbi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer number β maximal possible answer. In the next nβ-β1 lines print the operations in order of their applying in format ai,βbi,βci, where ai,βbi β pair of the leaves that are chosen in the current operation (1ββ€βai, biββ€βn), ci (1ββ€βciββ€βn, ciβ=βai or ciβ=βbi) β choosen leaf that is removed from the tree in the current operation. See the examples for better understanding.ExamplesInput31 21 3Output32 3 32 1 1Input51 21 32 42 5Output93 5 54 3 34 1 14 2 2 | Input31 21 3 | Output32 3 32 1 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', 'trees', '*2400'] |
E. Stack Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's suppose you have an array a, a stack s (initially empty) and an array b (also initially empty).You may perform the following operations until both a and s are empty: Take the first element of a, push it into s and remove it from a (if a is not empty); Take the top element from s, append it to the end of array b and remove it from s (if s is not empty). You can perform these operations in arbitrary order.If there exists a way to perform the operations such that array b is sorted in non-descending order in the end, then array a is called stack-sortable.For example, [3,β1,β2] is stack-sortable, because b will be sorted if we perform the following operations: Remove 3 from a and push it into s; Remove 1 from a and push it into s; Remove 1 from s and append it to the end of b; Remove 2 from a and push it into s; Remove 2 from s and append it to the end of b; Remove 3 from s and append it to the end of b. After all these operations bβ=β[1,β2,β3], so [3,β1,β2] is stack-sortable. [2,β3,β1] is not stack-sortable.You are given k first elements of some permutation p of size n (recall that a permutation of size n is an array of size n where each integer from 1 to n occurs exactly once). You have to restore the remaining nβ-βk elements of this permutation so it is stack-sortable. If there are multiple answers, choose the answer such that p is lexicographically maximal (an array q is lexicographically greater than an array p iff there exists some integer k such that for every iβ<βk qiβ=βpi, and qkβ>βpk). You may not swap or change any of first k elements of the permutation.Print the lexicographically maximal permutation p you can obtain.If there exists no answer then output -1.InputThe first line contains two integers n and k (2ββ€βnββ€β200000, 1ββ€βkβ<βn) β the size of a desired permutation, and the number of elements you are given, respectively.The second line contains k integers p1, p2, ..., pk (1ββ€βpiββ€βn) β the first k elements of p. These integers are pairwise distinct.OutputIf it is possible to restore a stack-sortable permutation p of size n such that the first k elements of p are equal to elements given in the input, print lexicographically maximal such permutation.Otherwise print -1.ExamplesInput5 33 2 1Output3 2 1 5 4 Input5 32 3 1Output-1Input5 13Output3 2 1 5 4 Input5 23 4Output-1 | Input5 33 2 1 | Output3 2 1 5 4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'greedy', 'implementation', '*2000'] |
D. Inversion Countingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i,βj) such that iβ>βj and aiβ<βaj. For example, a permutation [4,β1,β3,β2] contains 4 inversions: (2,β1), (3,β1), (4,β1), (4,β3).You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l,βr] of the permutation. For example, if aβ=β[1,β2,β3,β4] and a query lβ=β2, rβ=β4 is applied, then the resulting permutation is [1,β4,β3,β2].After each query you have to determine whether the number of inversions is odd or even.InputThe first line contains one integer n (1ββ€βnββ€β1500) β the size of the permutation. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€βn) β the elements of the permutation. These integers are pairwise distinct.The third line contains one integer m (1ββ€βmββ€β2Β·105) β the number of queries to process.Then m lines follow, i-th line containing two integers li, ri (1ββ€βliββ€βriββ€βn) denoting that i-th query is to reverse a segment [li,βri] of the permutation. All queries are performed one after another.OutputPrint m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.ExamplesInput31 2 321 22 3OutputoddevenInput41 2 4 341 11 41 42 3OutputoddoddoddevenNoteThe first example: after the first query aβ=β[2,β1,β3], inversion: (2,β1); after the second query aβ=β[2,β3,β1], inversions: (3,β1), (3,β2). The second example: aβ=β[1,β2,β4,β3], inversion: (4,β3); aβ=β[3,β4,β2,β1], inversions: (3,β1), (4,β1), (3,β2), (4,β2), (4,β3); aβ=β[1,β2,β4,β3], inversion: (4,β3); aβ=β[1,β4,β2,β3], inversions: (3,β2), (4,β2). | Input31 2 321 22 3 | Outputoddeven | 2 seconds | 256 megabytes | ['brute force', 'math', '*1800'] |
C. Three Garlandstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka is decorating the Christmas tree. He has got three garlands, and all of them will be put on the tree. After that Mishka will switch these garlands on.When a garland is switched on, it periodically changes its state β sometimes it is lit, sometimes not. Formally, if i-th garland is switched on during x-th second, then it is lit only during seconds x, xβ+βki, xβ+β2ki, xβ+β3ki and so on.Mishka wants to switch on the garlands in such a way that during each second after switching the garlands on there would be at least one lit garland. Formally, Mishka wants to choose three integers x1, x2 and x3 (not necessarily distinct) so that he will switch on the first garland during x1-th second, the second one β during x2-th second, and the third one β during x3-th second, respectively, and during each second starting from max(x1,βx2,βx3) at least one garland will be lit.Help Mishka by telling him if it is possible to do this!InputThe first line contains three integers k1, k2 and k3 (1ββ€βkiββ€β1500) β time intervals of the garlands.OutputIf Mishka can choose moments of time to switch on the garlands in such a way that each second after switching the garlands on at least one garland will be lit, print YES.Otherwise, print NO.ExamplesInput2 2 3OutputYESInput4 2 3OutputNONoteIn the first example Mishka can choose x1β=β1, x2β=β2, x3β=β1. The first garland will be lit during seconds 1,β3,β5,β7,β..., the second β 2,β4,β6,β8,β..., which already cover all the seconds after the 2-nd one. It doesn't even matter what x3 is chosen. Our choice will lead third to be lit during seconds 1,β4,β7,β10,β..., though.In the second example there is no way to choose such moments of time, there always be some seconds when no garland is lit. | Input2 2 3 | OutputYES | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', '*1400'] |
B. Two Cakestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's New Year's Eve soon, so Ivan decided it's high time he started setting the table. Ivan has bought two cakes and cut them into pieces: the first cake has been cut into a pieces, and the second one β into b pieces.Ivan knows that there will be n people at the celebration (including himself), so Ivan has set n plates for the cakes. Now he is thinking about how to distribute the cakes between the plates. Ivan wants to do it in such a way that all following conditions are met: Each piece of each cake is put on some plate; Each plate contains at least one piece of cake; No plate contains pieces of both cakes. To make his guests happy, Ivan wants to distribute the cakes in such a way that the minimum number of pieces on the plate is maximized. Formally, Ivan wants to know the maximum possible number x such that he can distribute the cakes according to the aforementioned conditions, and each plate will contain at least x pieces of cake.Help Ivan to calculate this number x!InputThe first line contains three integers n, a and b (1ββ€βa,βbββ€β100, 2ββ€βnββ€βaβ+βb) β the number of plates, the number of pieces of the first cake, and the number of pieces of the second cake, respectively.OutputPrint the maximum possible number x such that Ivan can distribute the cake in such a way that each plate will contain at least x pieces of cake.ExamplesInput5 2 3Output1Input4 7 10Output3NoteIn the first example there is only one way to distribute cakes to plates, all of them will have 1 cake on it.In the second example you can have two plates with 3 and 4 pieces of the first cake and two plates both with 5 pieces of the second cake. Minimal number of pieces is 3. | Input5 2 3 | Output1 | 1 second | 256 megabytes | ['binary search', 'brute force', 'implementation', '*1200'] |
A. Nearest Minimumstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integer numbers a0,βa1,β...,βanβ-β1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.InputThe first line contains positive integer n (2ββ€βnββ€β105) β size of the given array. The second line contains n integers a0,βa1,β...,βanβ-β1 (1ββ€βaiββ€β109) β elements of the array. It is guaranteed that in the array a minimum occurs at least two times.OutputPrint the only number β distance between two nearest minimums in the array.ExamplesInput23 3Output1Input35 6 5Output2Input92 1 3 5 4 1 2 3 1Output3 | Input23 3 | Output1 | 2 seconds | 256 megabytes | ['implementation', '*1100'] |
C. Minimum Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has n positive integers a1,βa2,β...,βan. His friend Vasya decided to joke and replaced all digits in Petya's numbers with a letters. He used the lowercase letters of the Latin alphabet from 'a' to 'j' and replaced all digits 0 with one letter, all digits 1 with another letter and so on. For any two different digits Vasya used distinct letters from 'a' to 'j'.Your task is to restore Petya's numbers. The restored numbers should be positive integers without leading zeros. Since there can be multiple ways to do it, determine the minimum possible sum of all Petya's numbers after the restoration. It is guaranteed that before Vasya's joke all Petya's numbers did not have leading zeros.InputThe first line contains a single integer n (1ββ€βnββ€β1β000) β the number of Petya's numbers.Each of the following lines contains non-empty string si consisting of lowercase Latin letters from 'a' to 'j' β the Petya's numbers after Vasya's joke. The length of each string does not exceed six characters.OutputDetermine the minimum sum of all Petya's numbers after the restoration. The restored numbers should be positive integers without leading zeros. It is guaranteed that the correct restore (without leading zeros) exists for all given tests.ExamplesInput3abdeajOutput47Input5abcdefghijbdefaccbdgOutput136542Input3aajjaaOutput44NoteIn the first example, you need to replace the letter 'a' with the digit 1, the letter 'b' with the digit 0, the letter 'd' with the digit 2, the letter 'e' with the digit 3, and the letter 'j' with the digit 4. So after the restoration numbers will look like [10,β23,β14]. The sum of them is equal to 47, which is the minimum possible sum of the numbers after the correct restoration.In the second example the numbers after the restoration can look like: [120468,β3579,β2468,β10024,β3]. In the second example the numbers after the restoration can look like: [11,β22,β11]. | Input3abdeaj | Output47 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1700'] |
B. Door Framestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has equal wooden bars of length n. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length a and one top side of length b. A solid (i.e. continuous without breaks) piece of bar is needed for each side.Determine a minimal number of wooden bars which are needed to make the frames for two doors. Petya can cut the wooden bars into any parts, but each side of each door should be a solid piece of a wooden bar (or a whole wooden bar).InputThe first line contains a single integer n (1ββ€βnββ€β1β000) β the length of each wooden bar.The second line contains a single integer a (1ββ€βaββ€βn) β the length of the vertical (left and right) sides of a door frame.The third line contains a single integer b (1ββ€βbββ€βn) β the length of the upper side of a door frame.OutputPrint the minimal number of wooden bars with length n which are needed to make the frames for two doors.ExamplesInput812Output1Input534Output6Input642Output4Input2056Output2NoteIn the first example one wooden bar is enough, since the total length of all six sides of the frames for two doors is 8.In the second example 6 wooden bars is enough, because for each side of the frames the new wooden bar is needed. | Input812 | Output1 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1600'] |
A. The Way to Hometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point xβ+βa, where a is an integer from 1 to d.For each point from 1 to n is known if there is a lily flower in it. The frog can jump only in points with a lilies. Guaranteed that there are lilies in the points 1 and n.Determine the minimal number of jumps that the frog needs to reach home which is in the point n from the point 1. Consider that initially the frog is in the point 1. If the frog can not reach home, print -1.InputThe first line contains two integers n and d (2ββ€βnββ€β100, 1ββ€βdββ€βnβ-β1) β the point, which the frog wants to reach, and the maximal length of the frog jump.The second line contains a string s of length n, consisting of zeros and ones. If a character of the string s equals to zero, then in the corresponding point there is no lily flower. In the other case, in the corresponding point there is a lily flower. Guaranteed that the first and the last characters of the string s equal to one.OutputIf the frog can not reach the home, print -1.In the other case, print the minimal number of jumps that the frog needs to reach the home which is in the point n from the point 1.ExamplesInput8 410010101Output2Input4 21001Output-1Input8 411100101Output3Input12 3101111100101Output4NoteIn the first example the from can reach home in two jumps: the first jump from the point 1 to the point 4 (the length of the jump is three), and the second jump from the point 4 to the point 8 (the length of the jump is four).In the second example the frog can not reach home, because to make it she need to jump on a distance three, but the maximum length of her jump equals to two. | Input8 410010101 | Output2 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'greedy', 'implementation', '*800'] |
F. AND-permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation.InputThe input consists of one line containing a single integer N (1ββ€βNββ€β105).OutputFor each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them.ExamplesInput3OutputNONOInput6OutputYES6 5 4 3 2 1 YES3 6 2 5 1 4 | Input3 | OutputNONO | 2 seconds | 256 megabytes | ['constructive algorithms', '*2500'] |
E. Coprocessortime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depends on have already completed.Some of the tasks in the graph can only be executed on a coprocessor, and the rest can only be executed on the main processor. In one coprocessor call you can send it a set of tasks which can only be executed on it. For each task of the set, all tasks on which it depends must be either already completed or be included in the set. The main processor starts the program execution and gets the results of tasks executed on the coprocessor automatically.Find the minimal number of coprocessor calls which are necessary to execute the given program.InputThe first line contains two space-separated integers N (1ββ€βNββ€β105) β the total number of tasks given, and M (0ββ€βMββ€β105) β the total number of dependencies between tasks.The next line contains N space-separated integers . If Eiβ=β0, task i can only be executed on the main processor, otherwise it can only be executed on the coprocessor.The next M lines describe the dependencies between tasks. Each line contains two space-separated integers T1 and T2 and means that task T1 depends on task T2 (T1ββ βT2). Tasks are indexed from 0 to Nβ-β1. All M pairs (T1,βT2) are distinct. It is guaranteed that there are no circular dependencies between tasks.OutputOutput one line containing an integer β the minimal number of coprocessor calls necessary to execute the program.ExamplesInput4 30 1 0 10 11 22 3Output2Input4 31 1 1 00 10 23 0Output1NoteIn the first test, tasks 1 and 3 can only be executed on the coprocessor. The dependency graph is linear, so the tasks must be executed in order 3 -> 2 -> 1 -> 0. You have to call coprocessor twice: first you call it for task 3, then you execute task 2 on the main processor, then you call it for for task 1, and finally you execute task 0 on the main processor.In the second test, tasks 0, 1 and 2 can only be executed on the coprocessor. Tasks 1 and 2 have no dependencies, and task 0 depends on tasks 1 and 2, so all three tasks 0, 1 and 2 can be sent in one coprocessor call. After that task 3 is executed on the main processor. | Input4 30 1 0 10 11 22 3 | Output2 | 1.5 seconds | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'greedy', '*1900'] |
D. Colorful Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right.You perform a sequence of operations on this set of points. In one operation, you delete all points which have a neighbor point of a different color than the point itself. Points are deleted simultaneously, i.e. first you decide which points have to be deleted and then delete them. After that you can perform the next operation etc. If an operation would not delete any points, you can't perform it.How many operations will you need to perform until the next operation does not have any points to delete?InputInput contains a single string of lowercase English letters 'a'-'z'. The letters give the points' colors in the order in which they are arranged on the line: the first letter gives the color of the leftmost point, the second gives the color of the second point from the left etc.The number of the points is between 1 and 106.OutputOutput one line containing an integer - the number of operations which can be performed on the given set of points until there are no more points to delete.ExamplesInputaabbOutput2InputaabcaaOutput1NoteIn the first test case, the first operation will delete two middle points and leave points "ab", which will be deleted with the second operation. There will be no points left to apply the third operation to.In the second test case, the first operation will delete the four points in the middle, leaving points "aa". None of them have neighbors of other colors, so the second operation can't be applied. | Inputaabb | Output2 | 2 seconds | 256 megabytes | ['data structures', 'greedy', 'implementation', '*2100'] |
C. Python Indentationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Python, code blocks don't have explicit begin/end or curly braces to mark beginning and end of the block. Instead, code blocks are defined by indentation.We will consider an extremely simplified subset of Python with only two types of statements.Simple statements are written in a single line, one per line. An example of a simple statement is assignment.For statements are compound statements: they contain one or several other statements. For statement consists of a header written in a separate line which starts with "for" prefix, and loop body. Loop body is a block of statements indented one level further than the header of the loop. Loop body can contain both types of statements. Loop body can't be empty.You are given a sequence of statements without indentation. Find the number of ways in which the statements can be indented to form a valid Python program.InputThe first line contains a single integer N (1ββ€βNββ€β5000)Β β the number of commands in the program. N lines of the program follow, each line describing a single command. Each command is either "f" (denoting "for statement") or "s" ("simple statement"). It is guaranteed that the last line is a simple statement.OutputOutput one line containing an integer - the number of ways the given sequence of statements can be indented modulo 109β+β7. ExamplesInput4sffsOutput1Input4fsfsOutput2NoteIn the first test case, there is only one way to indent the program: the second for statement must be part of the body of the first one.simple statementfor statement for statement simple statementIn the second test case, there are two ways to indent the program: the second for statement can either be part of the first one's body or a separate statement following the first one.for statement simple statement for statement simple statementorfor statement simple statementfor statement simple statement | Input4sffs | Output1 | 2 seconds | 256 megabytes | ['dp', '*1800'] |
Subsets and Splits