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
G. Another Meme Problemtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's call a fraction \frac{x}{y} good if there exists at least one another fraction \frac{x'}{y'} such that \frac{x}{y} = \frac{x'}{y'}, 1 \le x', y' \le 9, the digit denoting x' is contained in the decimal representation of x, and the digit denoting y' is contained in the decimal representation of y. For example, \frac{26}{13} is a good fraction, because \frac{26}{13} = \frac{2}{1}.You are given an integer number n. Please calculate the number of good fractions \frac{x}{y} such that 1 \le x \le n and 1 \le y \le n. The answer may be really large, so print it modulo 998244353.InputThe only line of the input contains one integer n (1 \le n < 10^{100}).OutputPrint the number of good fractions \frac{x}{y} such that 1 \le x \le n and 1 \le y \le n. The answer may be really large, so print it modulo 998244353.ExamplesInput 42 Output 150 Input 3141592653589793238462643383279 Output 459925407
42
150
4 seconds
512 megabytes
['dp', '*2700']
F. Crossword Experttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming. Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability \frac{1}{2} he solves the crossword in exactly t_i seconds, and with probability \frac{1}{2} he has to spend an additional second to finish the crossword). All these events are independent.After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E — the expected number of crosswords he will be able to solve completely. Can you calculate it? Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values — in this problem it means that the expected value of the number of solved crosswords can be calculated as E = \sum \limits_{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords. We can represent E as rational fraction \frac{P}{Q} with Q > 0. To give the answer, you should print P \cdot Q^{-1} \bmod (10^9 + 7).InputThe first line contains two integers n and T (1 \le n \le 2 \cdot 10^5, 1 \le T \le 2 \cdot 10^{14}) — the number of crosswords and the time Adilbek has to spend, respectively.The second line contains n integers t_1, t_2, \dots, t_n (1 \le t_i \le 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword.Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.OutputPrint one integer — the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P \cdot Q^{-1} \bmod (10^9 + 7).ExamplesInput 3 5 2 2 2 Output 750000007 Input 3 5 2 1 2 Output 125000003 NoteThe answer for the first sample is equal to \frac{14}{8}.The answer for the second sample is equal to \frac{17}{8}.
3 5 2 2 2
750000007
2 seconds
256 megabytes
['combinatorics', 'dp', 'number theory', 'probabilities', 'two pointers', '*2400']
E. Count The Rectanglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n segments drawn on a plane; the i-th segment connects two points (x_{i, 1}, y_{i, 1}) and (x_{i, 2}, y_{i, 2}). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every i \in [1, n] either x_{i, 1} = x_{i, 2} or y_{i, 1} = y_{i, 2} (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices h_1, h_2, v_1 and v_2 such that h_1 < h_2 and v_1 < v_2 form a rectangle if the following conditions hold: segments h_1 and h_2 are horizontal; segments v_1 and v_2 are vertical; segment h_1 intersects with segment v_1; segment h_2 intersects with segment v_1; segment h_1 intersects with segment v_2; segment h_2 intersects with segment v_2. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions h_1 < h_2 and v_1 < v_2 should hold.InputThe first line contains one integer n (1 \le n \le 5000) — the number of segments.Then n lines follow. The i-th line contains four integers x_{i, 1}, y_{i, 1}, x_{i, 2} and y_{i, 2} denoting the endpoints of the i-th segment. All coordinates of the endpoints are in the range [-5000, 5000].It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.OutputPrint one integer — the number of ways to choose four segments so they form a rectangle.ExamplesInput 7 -1 4 -1 -2 6 -1 -2 -1 -2 3 6 3 2 -2 2 4 4 -1 4 3 5 3 5 1 5 2 1 2 Output 7 Input 5 1 5 1 0 0 1 5 1 5 4 0 4 4 2 4 0 4 3 4 5 Output 0 NoteThe following pictures represent sample cases:
7 -1 4 -1 -2 6 -1 -2 -1 -2 3 6 3 2 -2 2 4 4 -1 4 3 5 3 5 1 5 2 1 2
7
2 seconds
256 megabytes
['bitmasks', 'brute force', 'data structures', 'geometry', 'sortings', '*2200']
D. 1-2-K Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob play a game. There is a paper strip which is divided into n + 1 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one).Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the chip is currently in the cell i, the player can move it into cell i - 1, i - 2 or i - k). The chip should not leave the borders of the paper strip: it is impossible, for example, to move it k cells to the left if the current cell has number i < k. The player who can't make a move loses the game.Who wins if both participants play optimally?Alice and Bob would like to play several games, so you should determine the winner in each game.InputThe first line contains the single integer T (1 ≤ T ≤ 100) — the number of games. Next T lines contain one game per line. All games are independent.Each of the next T lines contains two integers n and k (0 ≤ n ≤ 109, 3 ≤ k ≤ 109) — the length of the strip and the constant denoting the third move, respectively.OutputFor each game, print Alice if Alice wins this game and Bob otherwise.ExampleInput40 33 33 44 4OutputBobAliceBobAlice
Input40 33 33 44 4
OutputBobAliceBobAlice
2 seconds
256 megabytes
['games', 'math', '*1700']
C. From S To Ttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings s, t and p consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.During each operation you choose any character from p, erase it from p and insert it into string s (you may insert this character anywhere you want: in the beginning of s, in the end or between any two consecutive characters). For example, if p is aba, and s is de, then the following outcomes are possible (the character we erase from p and insert into s is highlighted): aba \rightarrow ba, de \rightarrow ade; aba \rightarrow ba, de \rightarrow dae; aba \rightarrow ba, de \rightarrow dea; aba \rightarrow aa, de \rightarrow bde; aba \rightarrow aa, de \rightarrow dbe; aba \rightarrow aa, de \rightarrow deb; aba \rightarrow ab, de \rightarrow ade; aba \rightarrow ab, de \rightarrow dae; aba \rightarrow ab, de \rightarrow dea; Your goal is to perform several (maybe zero) operations so that s becomes equal to t. Please determine whether it is possible.Note that you have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 100) — the number of queries. Each query is represented by three consecutive lines.The first line of each query contains the string s (1 \le |s| \le 100) consisting of lowercase Latin letters.The second line of each query contains the string t (1 \le |t| \le 100) consisting of lowercase Latin letters.The third line of each query contains the string p (1 \le |p| \le 100) consisting of lowercase Latin letters.OutputFor each query print YES if it is possible to make s equal to t, and NO otherwise.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).ExampleInput 4 ab acxb cax a aaaa aaabbcc a aaaa aabbcc ab baaa aaaaa Output YES YES NO NO NoteIn the first test case there is the following sequence of operation: s = ab, t = acxb, p = cax; s = acb, t = acxb, p = ax; s = acxb, t = acxb, p = a. In the second test case there is the following sequence of operation: s = a, t = aaaa, p = aaabbcc; s = aa, t = aaaa, p = aabbcc; s = aaa, t = aaaa, p = abbcc; s = aaaa, t = aaaa, p = bbcc.
4 ab acxb cax a aaaa aaabbcc a aaaa aabbcc ab baaa aaaaa
YES YES NO NO
1 second
256 megabytes
['implementation', 'strings', '*1300']
B. Yet Another Crosses Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a picture consisting of n rows and m columns. Rows are numbered from 1 to n from the top to the bottom, columns are numbered from 1 to m from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers x and y, where 1 \le x \le n and 1 \le y \le m, such that all cells in row x and all cells in column y are painted black.For examples, each of these pictures contain crosses: The fourth picture contains 4 crosses: at (1, 3), (1, 5), (3, 3) and (3, 5).Following images don't contain crosses: You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?You are also asked to answer multiple independent queries.InputThe first line contains an integer q (1 \le q \le 5 \cdot 10^4) — the number of queries.The first line of each query contains two integers n and m (1 \le n, m \le 5 \cdot 10^4, n \cdot m \le 4 \cdot 10^5) — the number of rows and the number of columns in the picture.Each of the next n lines contains m characters — '.' if the cell is painted white and '*' if the cell is painted black.It is guaranteed that \sum n \le 5 \cdot 10^4 and \sum n \cdot m \le 4 \cdot 10^5.OutputPrint q lines, the i-th line should contain a single integer — the answer to the i-th query, which is the minimum number of minutes you have to spend so the resulting picture contains at least one cross.ExampleInput 9 5 5 ..*.. ..*.. ***** ..*.. ..*.. 3 4 **** .*.. .*.. 4 3 *** *.. *.. *.. 5 5 ***** *.*.* ***** ..*.* ..*** 1 4 **** 5 5 ..... ..*.. .***. ..*.. ..... 5 3 ... .*. .*. *** .*. 3 3 .*. *.* .*. 4 4 *.** .... *.** *.** Output 0 0 0 0 0 4 1 1 2 NoteThe example contains all the pictures from above in the same order.The first 5 pictures already contain a cross, thus you don't have to paint anything.You can paint (1, 3), (3, 1), (5, 3) and (3, 5) on the 6-th picture to get a cross in (3, 3). That'll take you 4 minutes.You can paint (1, 2) on the 7-th picture to get a cross in (4, 2).You can paint (2, 2) on the 8-th picture to get a cross in (2, 2). You can, for example, paint (1, 3), (3, 1) and (3, 3) to get a cross in (3, 3) but that will take you 3 minutes instead of 1.There are 9 possible crosses you can get in minimum time on the 9-th picture. One of them is in (1, 1): paint (1, 2) and (2, 1).
9 5 5 ..*.. ..*.. ***** ..*.. ..*.. 3 4 **** .*.. .*.. 4 3 *** *.. *.. *.. 5 5 ***** *.*.* ***** ..*.* ..*** 1 4 **** 5 5 ..... ..*.. .***. ..*.. ..... 5 3 ... .*. .*. *** .*. 3 3 .*. *.* .*. 4 4 *.** .... *.** *.**
0 0 0 0 0 4 1 1 2
2 seconds
256 megabytes
['implementation', '*1300']
A. Remove a Progressiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a list of numbers from 1 to n written from left to right on the blackboard.You perform an algorithm consisting of several steps (steps are 1-indexed). On the i-th step you wipe the i-th number (considering only remaining numbers). You wipe the whole number (not one digit). When there are less than i numbers remaining, you stop your algorithm. Now you wonder: what is the value of the x-th remaining number after the algorithm is stopped?InputThe first line contains one integer T (1 \le T \le 100) — the number of queries. The next T lines contain queries — one per line. All queries are independent.Each line contains two space-separated integers n and x (1 \le x < n \le 10^{9}) — the length of the list and the position we wonder about. It's guaranteed that after the algorithm ends, the list will still contain at least x numbers.OutputPrint T integers (one per query) — the values of the x-th number after performing the algorithm for the corresponding queries.ExampleInput 3 3 1 4 2 69 6 Output 2 4 12
3 3 1 4 2 69 6
2 4 12
2 seconds
256 megabytes
['math', '*800']
C. Scissors and Tapetime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a piece of paper in the shape of a simple polygon S. Your task is to turn it into a simple polygon T that has the same area as S.You can use two tools: scissors and tape. Scissors can be used to cut any polygon into smaller polygonal pieces. Tape can be used to combine smaller pieces into larger polygons. You can use each tool multiple times, in any order. The polygons given in the input have integer coordinates, but you are allowed to produce shapes with non-integer coordinates in your output.A formal definition of the task follows.A shape Q=(Q_0,\dots,Q_{n-1}) is a sequence of three or more points in the plane such that: The closed polyline Q_0Q_1Q_2\dots Q_{n-1}Q_0 never touches or intersects itself, and therefore it forms the boundary of a simple polygon. The polyline goes around the boundary of the polygon in the counter-clockwise direction. The polygon whose boundary is the shape Q will be denoted P(Q).Two shapes are called equivalent if one can be translated and/or rotated to become identical with the other.Note that mirroring a shape is not allowed. Also note that the order of points matters: the shape (Q_1,\dots,Q_{n-1},Q_0) is not necessarily equivalent to the shape (Q_0,\dots,Q_{n-1}).In the figure on the left: Shapes U and V are equivalent. Shape W is not equivalent with them because the points of W are given in a different order. Regardless of the order of points, the fourth shape is not equivalent with the previous ones either as flipping a shape is not allowed.In both input and output, a shape with n points is represented as a single line that contains 2n+1 space-separated numbers: the number n followed by the coordinates of the points: Q_{0,x}, Q_{0,y}, Q_{1,x}, ...Shapes have identification numbers (IDs). The given shape S has ID 0, the shapes you produce in your solutions are given IDs 1, 2, 3, ..., in the order in which they are produced.Shapes B_1,\dots,B_k form a subdivision of shape A if: The union of all P(B_i) is exactly P(A). For each i\neq j, the area of the intersection of P(B_i) and P(B_j) is zero. The scissors operation destroys one existing shape A and produces one or more shapes B_1,\dots,B_k that form a subdivision of A.In the figure: Shape A (square) subdivided into shapes B_1, B_2, B_3 (the three triangles). One valid way to describe one of the B_i is "3 3 1 6 1 5.1 4".The tape operation destroys one or more existing shapes A_1,\dots,A_k and produces one new shape B. In order to perform this operation, you must first specify shapes C_1,\dots,C_k and only then the final shape B. These shapes must satisfy the following: For each i, the shape C_i is equivalent to the shape A_i. The shapes C_1,\dots,C_k form a subdivision of the shape B. Informally, you choose the shape B and show how to move each of the existing A_i to its correct location C_i within B. Note that only the shape B gets a new ID, the shapes C_i do not.InputThe first line contains the source shape S.The second line contains the target shape T.Each shape has between 3 and 10 points, inclusive. Both shapes are given in the format specified above.All coordinates in the input are integers between -10^6 and 10^6, inclusive.In each shape, no three points form an angle smaller than 3 degrees. (This includes non-consecutive points and implies that no three points are collinear.)The polygons P(S) and P(T) have the same area.OutputWhenever you use the scissors operation, output a block of lines of the form: scissorsid(A) kB_1B_2...B_kwhere id(A) is the ID of the shape you want to destroy, k is the number of new shapes you want to produce, and B_1,\dots,B_k are those shapes.Whenever you use the tape operation, output a block of lines of the form: tapek id(A_1) ... id(A_k)C_1C_2...C_kBwhere k is the number of shapes you want to tape together, id(A_1),\dots,id(A_k) are their IDs, C_1,\dots,C_k are equivalent shapes showing their position within B, and B is the final shape obtained by taping them together.It is recommended to output coordinates of points to at least 10 decimal places.The output must satisfy the following: All coordinates of points in the output must be between -10^7 and 10^7, inclusive. Each shape in the output must have at most 100 points. In each operation the number k of shapes must be between 1 and 100, inclusive. The number of operations must not exceed 2000. The total number of points in all shapes in the output must not exceed 20000. In the end, there must be exactly one shape (that hasn't been destroyed), and that shape must be equivalent to T. All operations must be valid according to the checker. Solutions with small rounding errors will be accepted. (Internally, all comparisons check for absolute or relative error up to 10^{-3} when verifying each condition.) ScoringA shape is called a nice rectangle if it has the form ((0,0),~ (x,0),~ (x,y),~ (0,y)) for some positive integers x and y.A shape is called a nice square if additionally x=y.A shape A is called strictly convex if all inner angles of the polygon P(A) are smaller than 180 degrees.Subtask 1 (5 points): S and T are nice rectangles. All coordinates of all points are integers between 0 and 10, inclusiveSubtask 2 (13 points): S is a nice rectangle with x>y, and T is a nice squareSubtask 3 (12 points): S and T are nice rectanglesSubtask 4 (14 points): S is a triangle and T is a nice squareSubtask 5 (10 points): S and T are trianglesSubtask 6 (16 points): S is a strictly convex polygon and T is a nice rectangleSubtask 7 (11 points): T is a nice rectangleSubtask 8 (19 points): no additional constraintsExamplesInput 6 0 0 6 0 6 4 5 4 5 9 0 9 4 0 0 7 0 7 7 0 7 Output scissors 0 5 3 0 0 3 0 3 4 3 3 4 0 4 0 0 3 3 0 6 0 6 4 3 6 4 3 4 3 0 4 0 4 5 4 5 9 0 9 tape 5 1 2 5 3 4 3 0 3 0 0 4 0 3 4 0 7 0 7 4 4 0 3 4 0 7 4 3 7 3 7 4 7 7 3 7 3 3 7 0 7 0 3 4 0 0 7 0 7 7 0 7Input 4 0 0 3 0 3 3 0 3 4 7 -1 10 -1 11 2 8 2 Output scissors 0 2 3 0 0 1 3 0 3 4 1 3 0 0 3 0 3 3 tape 2 1 2 3 110 -1 111 2 110 2 4 108 2 107 -1 110 -1 110 2 4 107 -1 110 -1 111 2 108 2 Input 4 0 0 9 0 9 1 0 1 4 0 0 3 0 3 3 0 3 Output scissors 0 2 4 1.470000000 0 9 0 9 1 1.470000000 1 4 0 0 1.470000000 0 1.470000000 1 0 1 scissors 1 2 4 1.470000000 0 6 0 6 1 1.470000000 1 4 9 0 9 1 6 1 6 0 tape 2 4 3 4 3 2 3 1 6 1 6 2 4 6 1 1.470000000 1 1.470000000 0 6 0 6 1.470000000 0 6 0 6 2 3 2 3 1 1.470000000 1 scissors 5 4 4 1.470000000 0 3 0 3 1 1.470000000 1 4 3 0 4 0 4 2 3 2 4 4 2 4 0 5 0 5 2 4 5 0 6 0 6 2 5 2 tape 5 2 6 7 8 9 4 0 0 1.470000000 0 1.470000000 1 0 1 4 1.470000000 0 3 0 3 1 1.470000000 1 4 0 2 0 1 2 1 2 2 4 0 2 2 2 2 3 0 3 4 3 3 2 3 2 1 3 1 4 0 0 3 0 3 3 0 3 NoteThe figure below shows the first example output. On the left is the original figure after using the scissors, on the right are the corresponding C_i when we tape those pieces back together.In the second example output, note that it is sufficient if the final shape is equivalent to the target one, they do not have to be identical.The figure below shows three stages of the third example output. First, we cut the input rectangle into two smaller rectangles, then we cut the bigger of those two rectangles into two more. State after these cuts is shown in the top left part of the figure.Continuing, we tape the two new rectangles together to form a six-sided polygon, and then we cut that polygon into three 2-by-1 rectangles and one smaller rectangle. This is shown in the bottom left part of the figure.Finally, we take the rectangle we still have from the first step and the four new rectangles and we assemble them into the desired 3-by-3 square.
6 0 0 6 0 6 4 5 4 5 9 0 9 4 0 0 7 0 7 7 0 7
scissors 0 5 3 0 0 3 0 3 4 3 3 4 0 4 0 0 3 3 0 6 0 6 4 3 6 4 3 4 3 0 4 0 4 5 4 5 9 0 9 tape 5 1 2 5 3 4 3 0 3 0 0 4 0 3 4 0 7 0 7 4 4 0 3 4 0 7 4 3 7 3 7 4 7 7 3 7 3 3 7 0 7 0 3 4 0 0 7 0 7 7 0 7
1 second
1024 megabytes
['*special problem', 'constructive algorithms', 'geometry']
B. Magic Treetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputWe have a magic tree: a rooted tree on n vertices. The vertices are numbered 1 through n. Vertex 1 is the root.The magic tree gives us magic fruit. The fruit only grows in vertices of the tree other than the root. Each vertex contains at most one piece of fruit.It is now day 0 and no fruit is ripe yet. Each fruit will only be ripe for a single day. For each fruit, we are given the vertex v_j where it grows, the day d_j on which it will be ripe, and the amount w_j of magic juice we can extract from it if we harvest it when it is ripe.The fruits have to be harvested by cutting some branches of the tree. On each day, you may cut as many branches of the tree as you like. The parts of the tree you cut off will fall to the ground and you can collect all the ripe fruits they contain. All fruits that fall to the ground when they are not ripe are discarded and no magic juice is collected from them.Formally, on each day, you may erase some edges of the tree. Whenever you do so, the tree will split into multiple connected components. You then erase all components that do not contain the root and you harvest all ripe fruits those components contained.Given is a description of the tree together with the locations, ripening days and juiciness of all m fruits. Calculate the maximum total amount of magic juice we can harvest from the tree.InputThe first line contains three space-separated integers n (2 \le n \le 100,000), m (1 \le m \le n-1) and k (1 \le k \le 100,000) – the number of vertices, the number of fruits, and the maximum day on which a fruit may become ripe.The following n-1 lines contain the integers p_2, \dots, p_n, one per line. For each i (from 2 to n, inclusive), vertex p_i (1 \leq p_i \le i-1) is the parent of vertex i.Each of the last m lines describes one fruit. The j-th of these lines has the form "v_j\ d_j\ w_j" (2 \le v_j \le n, 1 \le d_j \le k, 1 \le w_j \le 10^9).It is guaranteed that no vertex contains more than one fruit (i.e., the values v_j are distinct).OutputOutput a single line with a single integer, the maximum amount of magic juice we can harvest from the tree.ScoringSubtask 1 (6 points): n, k \leq 20, and w_j = 1 for all jSubtask 2 (3 points): fruits only grow in the leaves of the treeSubtask 3 (11 points): p_i = i-1 for each i, and w_j = 1 for all jSubtask 4 (12 points): k \leq 2Subtask 5 (16 points): k \leq 20, and w_j = 1 for all jSubtask 6 (13 points): m \leq 1,000Subtask 7 (22 points): w_j = 1 for all jSubtask 8 (17 points): no additional constraintsExampleInput 6 4 10 1 2 1 4 4 3 4 5 4 7 2 5 4 1 6 9 3 Output 9 NoteIn the example input, one optimal solution looks as follows: On day 4, cut the edge between vertices 4 and 5 and harvest a ripe fruit with 1 unit of magic juice. On the same day, cut the edge between vertices 1 and 2 and harvest 5 units of magic juice from the ripe fruit in vertex 3. On day 7, do nothing. (We could harvest the fruit in vertex 4 that just became ripe, but doing so is not optimal.) On day 9, cut the edge between vertices 1 and 4. Discard the fruit in vertex 4 that is no longer ripe, and harvest 3 units of magic juice from the ripe fruit in vertex 6. (Alternately, we could achieve the same effect by cutting the edge between vertices 4 and 6.)
6 4 10 1 2 1 4 4 3 4 5 4 7 2 5 4 1 6 9 3
9
2 seconds
1024 megabytes
['*special problem', 'data structures', 'dp', 'trees']
A. Amusement Parktime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou have been hired to supervise the project of a new amusement park. The park will have a special gimmick: directed slides that can get customers from one attraction to another quickly and in an entertaining way.The park owner has given you the current project: a list of planned attractions and a list of slides that should be built between them. However, him being a businessman, he casually envisioned the impossible: among other things, he projected a slide coming from the Haunted Castle to the Roller Coaster, another from the Roller Coaster to the Drop Tower, and a third from the Drop Tower to the Haunted Castle. As the slides can only go downhill, it is evident why this is a problem. You don't have the luxury of ignoring the laws of physics when building the park, so you have to request changes in the project. Maybe he would accept reversing the slide between the Drop Tower and the Haunted Castle?Formally: The project is a list of attractions and a list of directed slides. Each slide starts at one attraction and ends at another attraction. A proposal is obtained from the project by reversing the directions of some slides (possibly none or all of them). A proposal is legal if there is a way to assign an elevation to each attraction in such a way that every slide goes downhill. The cost of a proposal is the number of slides whose directions were reversed. For a given project, find and report the sum of costs all legal proposals. Since this number may be large, output it modulo 998,244,353.InputThe first line contains two space-separated integers n, m (1 \leq n \leq 18, 0 \leq m \leq n(n-1)/2) – the number of attractions and the number of slides, respectively. The attractions are numbered 1 through n.Then, m lines follow. The i-th of these lines contains two space-separated integers a_i, b_i (1 \leq a_i, b_i \leq n) denoting a slide from a_i to b_i. You may assume that: There are no self-loops. (For each i: a_i \neq b_i.) No slide appears twice. (For all i \neq j: a_i \neq a_j or b_i \neq b_j.) No pair of attractions is connected in both directions. (The unordered pairs \{a_i, b_i\} are distinct.) OutputOutput one line with a single integer, the sum of costs of all legal proposals modulo 998,244,353.ScoringSubtask 1 (7 points): n \leq 3Subtask 2 (12 points): n \leq 6Subtask 3 (23 points): n \leq 10Subtask 4 (21 points): n \leq 15Subtask 5 (37 points): no additional constraintsExamplesInput 2 1 1 2 Output 1 Input 3 3 1 2 2 3 1 3 Output 9 NoteIn the first example, there are two proposals: The slide direction is not flipped. This proposal has cost 0. The slide direction is flipped. This proposal has cost 1. As both proposals are valid, the answer is 0 + 1 = 1.In the second example, there are eight proposals with the slide directions as follows: 1 \rightarrow 2, 2 \rightarrow 3, 1 \rightarrow 3 (cost 0) 1 \rightarrow 2, 2 \rightarrow 3, 3 \rightarrow 1 (cost 1) 1 \rightarrow 2, 3 \rightarrow 2, 1 \rightarrow 3 (cost 1) 1 \rightarrow 2, 3 \rightarrow 2, 3 \rightarrow 1 (cost 2) 2 \rightarrow 1, 2 \rightarrow 3, 1 \rightarrow 3 (cost 1) 2 \rightarrow 1, 2 \rightarrow 3, 3 \rightarrow 1 (cost 2) 2 \rightarrow 1, 3 \rightarrow 2, 1 \rightarrow 3 (cost 2) 2 \rightarrow 1, 3 \rightarrow 2, 3 \rightarrow 1 (cost 3) The second proposal is not legal, as there is a slide sequence 1 \rightarrow 2 \rightarrow 3 \rightarrow 1. This means that the attraction 1 has to be strictly higher than ifself, which is clearly impossible. Similarly, the seventh proposal is not legal. The answer is thus 0 + 1 + 2 + 1 + 2 + 3 = 9.
2 1 1 2
1
3 seconds
1024 megabytes
['*special problem', 'dp', 'math']
C. Cubewordtime limit per test1.7 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA cubeword is a special type of a crossword. When building a cubeword, you start by choosing a positive integer a: the side length of the cube. Then, you build a big cube consisting of a \times a \times a unit cubes. This big cube has 12 edges. Then, you discard all unit cubes that do not touch the edges of the big cube. The figure below shows the object you will get for a=6. Finally, you assign a letter to each of the unit cubes in the object. You must get a meaningful word along each edge of the big cube. Each edge can be read in either direction, and it is sufficient if one of the two directions of reading gives a meaningful word.The figure below shows the object for a=6 in which some unit cubes already have assigned letters. You can already read the words 'SUBMIT', 'ACCEPT' and 'TURING' along three edges of the big cube. You are given a list of valid words. Each word from the wordlist may appear on arbitrarily many edges of a valid cubeword. Find and report the number of different cubewords that can be constructed, modulo 998,244,353.If one cubeword can be obtained from another by rotation or mirroring, they are considered distinct.InputThe first line contains a single integer n (1 \leq n \leq 100,000) – the number of words.Then, n lines follow. Each of these lines contains one word that can appear on the edges of the big cube. The length of each word is between 3 and 10, inclusive.It is guaranteed that all words are different.OutputOutput a single integer, the number of distinct cubewords for the given list of valid words modulo 998,244,353.ScoringSubtask 1 (21 points): the words consist only of letters 'a' - 'f' (lowercase)Subtask 2 (29 points): the words consist only of letters 'a' - 'p' (lowercase)Subtask 3 (34 points): the words consist of letters 'a' - 'p' (lowercase) and 'A' - 'P' (uppercase)Subtask 4 (16 points): the words consist of letters 'a' - 'z' (lowercase), 'A' - 'Z' (uppercase) and digits '0' - '9'ExamplesInput 1 radar Output 1 Input 1 robot Output 2 Input 2 FLOW WOLF Output 2 Input 2 baobab bob Output 4097 Input 3 TURING SUBMIT ACCEPT Output 162 Input 3 MAN1LA MAN6OS AN4NAS Output 114 NoteIn the first sample, the only possibility is for the word "radar" to be on each edge of the cube.In the second sample, there are two cubes, which are just rotations of each other – the word "robot" is on every edge, and the difference between the two cubes is whether the lower left front corner contains 'r' or 't'.The third sample is similar to the second one. The fact that we can read the word on each edge in both directions does not affect the answer.In the fourth sample, there is one cube with the word "bob" on each edge. There are also 2^{12} = 4096 cubes with the word "baobab" on each edge. (For each of the 12 edges, we have two possible directions in which the word "baobab" can appear.)
1 radar
1
1.7 seconds
1024 megabytes
['*special problem', 'brute force', 'dp', 'meet-in-the-middle']
B. Dynamic Diametertime limit per test6 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a weighted undirected tree on n vertices and a list of q updates. Each update changes the weight of one edge. The task is to output the diameter of the tree after each update.(The distance between two vertices is the sum of the weights on the unique simple path that connects them. The diameter is the largest of all those distances.)InputThe first line contains three space-separated integers n, q and w (2 \leq n \leq 100,000, 1 \leq q \leq 100,000, 1 \leq w \leq 20,000,000,000,000) – the number of vertices in the tree, the number of updates and the limit on the weights of edges. The vertices are numbered 1 through n.Next, n-1 lines describing the initial tree follow. The i-th of these lines contains three space-separated integers a_i, b_i, c_i (1 \leq a_i, b_i \leq n, 0 \leq c_i < w) meaning that initially, there is an edge between vertices a_i and b_i with weight c_i. It is guaranteed that these n-1 lines describe a tree.Finally, q lines describing queries follow. The j-th of these lines contains two space-separated integers d_j, e_j (0 \leq d_j < n - 1, 0 \leq e_j < w). These two integers are then transformed according to the following scheme: d'_j = (d_j + last) \bmod (n - 1) e'_j = (e_j + last) \bmod w where last is the result of the last query (initially last=0). Tuple (d'_j, e'_j) represents a query which takes the d'_j+1-th edge from the input and sets its weight to e'_j.OutputOutput q lines. For each i, line i should contain the diameter of the tree after the i-th update.ScoringSubtask 1 (11 points): n,q \leq 100 and w \leq 10,000Subtask 2 (13 points): n,q \leq 5,000 and w \leq 10,000Subtask 3 (7 points): w \leq 10,000 and the edges of the tree are exactly all valid edges of the form \{1, i\} (Hence, the tree is a star centered at vertex 1.)Subtask 4 (18 points): w \leq 10,000, and the edges of the tree are exactly all valid edges of the forms \{i, 2i\} and \{i, 2i+1\} (Hence, if we were to root the tree at vertex 1, it would be a balanced binary tree.)Subtask 5 (24 points): it is guaranteed that after each update a longest simple path goes through vertex 1Subtask 6 (27 points): no additional constraintsExamplesInput 4 3 2000 1 2 100 2 3 1000 2 4 1000 2 1030 1 1020 1 890 Output 2030 2080 2050 Input 10 10 10000 1 9 1241 5 6 1630 10 5 1630 2 6 853 10 1 511 5 3 760 8 3 1076 4 10 1483 7 10 40 8 2051 5 6294 5 4168 7 1861 0 5244 6 5156 3 3001 8 5267 5 3102 8 3623 Output 6164 7812 8385 6737 6738 7205 6641 7062 6581 5155 NoteThe first sample is depicted in the figure below. The left-most picture shows the initial state of the graph. Each following picture depicts the situation after an update. The weight of the updated edge is painted green, and the diameter is red.The first query changes the weight of the 3rd edge, i.e. \{2, 4\}, to 1030. The largest distance between any pair of vertices is 2030 – the distance between 3 and 4.As the answer is 2030, the second query is d'_2 = (1 + 2030) \bmod 3 = 0 e'_2 = (1020 + 2030) \bmod 2000 = 1050 Hence the weight of the edge \{1, 2\} is changed to 1050. This causes the pair \{1, 4\} to be the pair with the greatest distance, namely 2080.The third query is decoded as d'_3 = (1 + 2080) \bmod 3 = 2 e'_3 = (890 + 2080) \bmod 2000 = 970 As the weight of the edge \{2, 4\} decreases to 970, the most distant pair is suddenly \{1, 3\} with 2050.
4 3 2000 1 2 100 2 3 1000 2 4 1000 2 1030 1 1020 1 890
2030 2080 2050
6 seconds
1024 megabytes
['*special problem', 'data structures', 'dfs and similar', 'divide and conquer', 'trees']
A. Building Skyscraperstime limit per test3.5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputWe are going to build a new city: the Metropolis. The city is going to be built on an infinite square grid. The finished city will consist of n skyscrapers, each occupying a different cell of the grid. At any moment during the construction, the cells that currently do not contain a skyscraper are called empty.You are given the planned coordinates of the n skyscrapers. Your task is to find an order in which they can be built while satisfying the rules listed below. The building crew has only one crane, so the Metropolis has to be constructed one skyscraper at a time. The first skyscraper can be built anywhere on the grid. Each subsequent skyscraper has to share a side or a corner with at least one of the previously built skyscrapers (so that it's easier to align the new skyscraper to the grid properly). When building a skyscraper, there has to be a way to deliver material to the construction site from the outside of Metropolis by only moving it through empty cells that share a side. In other words, there should be a path of side-adjacent empty cells that connects the cell that will contain the skyscraper to some cell (r,c) with |r|>10^9 and/or |c|>10^9. If a solution exists, let's denote the numbers of skyscrapers in the order in which they should be built by s_1, \dots, s_n. There are two types of subtasks:Type 1: You may produce any valid order.Type 2: You must find the order that maximizes s_n. Among those, you must find the one that maximizes s_{n-1}. And so on. In other words, you must find the valid order of building for which the sequence (s_n,s_{n-1},\dots,s_1) is lexicographically largest.InputThe first line contains a single integer n (1 \le n \le 150,000) – the number of skyscrapers.The second line contains a single integer t (1 \le t \le 2) describing the type of the subtask as defined above.Then, n lines follow. The i-th of these lines contains two space-separated integers r_i and c_i (|r_i|, |c_i| \le 10^9) denoting the coordinates of the cell containing skyscraper i.(The skyscrapers are not numbered in any particular order. The only reason why they have numbers is that they are used in the output format.)It is guaranteed that no two skyscrapers coincide.OutputIf it is impossible to build the skyscrapers according to the given rules, print a single line containing the string "NO".Otherwise, print n+1 lines. The first of these lines should contain the string "YES". For each i, the i-th of the remaining n lines should contain a single integer s_i.In subtasks with t = 1, if there are multiple valid orders, you may output any one of them.ScoringSubtask 1 (8 points): t = 1 and n \le 10Subtask 2 (14 points): t = 1 and n \le 200Subtask 3 (12 points): t = 1 and n \le 2,000Subtask 4 (17 points): t = 2 and n \le 2,000Subtask 5 (20 points): t = 1Subtask 6 (10 points): t = 2, n \le 70,000 and |r_i|, |c_i| \le 900 for each iSubtask 7 (19 points): t = 2ExamplesInput 3 2 0 0 0 1 0 2 Output YES 1 2 3 Input 3 1 0 0 1 1 2 2 Output YES 2 3 1 Input 2 1 0 0 0 2 Output NO NoteIn the first example, there are three skyscrapers in a row. All of them can always be reached from outside the Metropolis, and there are four build orders which preserve connectivity: 1, 2, 3 2, 1, 3 2, 3, 1 3, 2, 1 Since t = 2, we must choose the first option.In the second example, the only difference from the first example is that skyscraper 2 shares only corners with skyscrapers 1 and 3, the same set of orders as in the first sample is valid. Since t = 1, each of these answers is correct.In the third example, the Metropolis is disconnected. We obviously can't build that.
3 2 0 0 0 1 0 2
YES 1 2 3
3.5 seconds
1024 megabytes
['*special problem']
B. Tokitsukaze and Mahjongtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, \ldots, 9m, 1p, 2p, \ldots, 9p, 1s, 2s, \ldots, 9s.In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.Do you know the minimum number of extra suited tiles she needs to draw so that she can win?Here are some useful definitions in this game: A mentsu, also known as meld, is formed by a koutsu or a shuntsu; A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu; A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu. Some examples: [2m, 3p, 2s, 4m, 1s, 2s, 4s] — it contains no koutsu or shuntsu, so it includes no mentsu; [4s, 3m, 3p, 4s, 5p, 4s, 5p] — it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu; [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] — it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu. Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.InputThe only line contains three strings — the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.OutputPrint a single integer — the minimum number of extra suited tiles she needs to draw.ExamplesInput 1s 2s 3s Output 0 Input 9m 9m 9m Output 0 Input 3p 9m 2p Output 1 NoteIn the first example, Tokitsukaze already has a shuntsu.In the second example, Tokitsukaze already has a koutsu.In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile — 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
1s 2s 3s
0
1 second
256 megabytes
['brute force', 'implementation', '*1200']
A. Tokitsukaze and Enhancementtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTokitsukaze is one of the characters in the game "Kantai Collection". In this game, every character has a common attribute — health points, shortened to HP.In general, different values of HP are grouped into 4 categories: Category A if HP is in the form of (4 n + 1), that is, when divided by 4, the remainder is 1; Category B if HP is in the form of (4 n + 3), that is, when divided by 4, the remainder is 3; Category C if HP is in the form of (4 n + 2), that is, when divided by 4, the remainder is 2; Category D if HP is in the form of 4 n, that is, when divided by 4, the remainder is 0. The above-mentioned n can be any integer.These 4 categories ordered from highest to lowest as A > B > C > D, which means category A is the highest and category D is the lowest.While playing the game, players can increase the HP of the character. Now, Tokitsukaze wants you to increase her HP by at most 2 (that is, either by 0, 1 or 2). How much should she increase her HP so that it has the highest possible category?InputThe only line contains a single integer x (30 \leq x \leq 100) — the value Tokitsukaze's HP currently.OutputPrint an integer a (0 \leq a \leq 2) and an uppercase letter b (b \in \lbrace A, B, C, D \rbrace), representing that the best way is to increase her HP by a, and then the category becomes b.Note that the output characters are case-sensitive.ExamplesInput 33 Output 0 A Input 98 Output 1 B NoteFor the first example, the category of Tokitsukaze's HP is already A, so you don't need to enhance her ability.For the second example: If you don't increase her HP, its value is still 98, which equals to (4 \times 24 + 2), and its category is C. If you increase her HP by 1, its value becomes 99, which equals to (4 \times 24 + 3), and its category becomes B. If you increase her HP by 2, its value becomes 100, which equals to (4 \times 25), and its category becomes D. Therefore, the best way is to increase her HP by 1 so that the category of her HP becomes B.
33
0 A
1 second
256 megabytes
['brute force', '*800']
F. Tokitsukaze and Powerstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTokitsukaze is playing a room escape game designed by SkywalkerT. In this game, she needs to find out hidden clues in the room to reveal a way to escape.After a while, she realizes that the only way to run away is to open the digital door lock since she accidentally went into a secret compartment and found some clues, which can be interpreted as: Only when you enter n possible different passwords can you open the door; Passwords must be integers ranged from 0 to (m - 1); A password cannot be x (0 \leq x < m) if x and m are not coprime (i.e. x and m have some common divisor greater than 1); A password cannot be x (0 \leq x < m) if there exist non-negative integers e and k such that p^e = k m + x, where p is a secret integer; Any integer that doesn't break the above rules can be a password; Several integers are hidden in the room, but only one of them can be p. Fortunately, she finds that n and m are recorded in the lock. However, what makes Tokitsukaze frustrated is that she doesn't do well in math. Now that she has found an integer that is suspected to be p, she wants you to help her find out n possible passwords, or determine the integer cannot be p.InputThe only line contains three integers n, m and p (1 \leq n \leq 5 \times 10^5, 1 \leq p < m \leq 10^{18}).It is guaranteed that m is a positive integer power of a single prime number.OutputIf the number of possible different passwords is less than n, print a single integer -1.Otherwise, print n distinct integers ranged from 0 to (m - 1) as passwords. You can print these integers in any order. Besides, if there are multiple solutions, print any.ExamplesInput 1 2 1 Output -1 Input 3 5 1 Output 2 4 3 Input 2 5 4 Output 2 3 Input 4 9 8 Output 2 4 7 5 NoteIn the first example, there is no possible password.In each of the last three examples, the given integer n equals to the number of possible different passwords for the given integers m and p, so if the order of numbers in the output is ignored, the solution is unique as shown above.
1 2 1
-1
3 seconds
256 megabytes
['number theory', 'probabilities', '*3400']
E. Tokitsukaze and Explosiontime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTokitsukaze and her friends are trying to infiltrate a secret base built by Claris. However, Claris has been aware of that and set a bomb which is going to explode in a minute. Although they try to escape, they have no place to go after they find that the door has been locked.At this very moment, CJB, Father of Tokitsukaze comes. With his magical power given by Ereshkigal, the goddess of the underworld, CJB is able to set m barriers to protect them from the explosion. Formally, let's build a Cartesian coordinate system on the plane and assume the bomb is at O(0, 0). There are n persons in Tokitsukaze's crew, the i-th one of whom is at P_i(X_i, Y_i). Every barrier can be considered as a line with infinity length and they can intersect each other. For every person from Tokitsukaze's crew, there must be at least one barrier separating the bomb and him, which means the line between the bomb and him intersects with at least one barrier. In this definition, if there exists a person standing at the position of the bomb, any line through O(0, 0) will satisfy the requirement.Although CJB is very powerful, he still wants his barriers to be as far from the bomb as possible, in order to conserve his energy. Please help him calculate the maximum distance between the bomb and the closest barrier while all of Tokitsukaze's crew are safe.InputThe first line contains two integers n, m (1 \leq n, m \leq 10^5), indicating the number of people and the number of barriers respectively.The i-th line of the next n lines contains two integers X_i, Y_i (-10^5 \leq X_i, Y_i \leq 10^5), indicating the i-th person's location P_i(X_i, Y_i). Note that P_i may have the same coordinates as P_j (j \neq i) or even O.OutputPrint a single real number — the maximum distance meeting the requirement. Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max(1, |b|)} \leq 10^{-6}.ExamplesInput 3 1 2 0 0 2 -1 0 Output 0.0000000000 Input 1 1 0 0 Output 0.0000000000 Input 2 1 -1 -1 -1 -1 Output 1.4142135617 Input 3 100000 3 2 -1 -3 2 -5 Output 3.1622776602 NoteIn the first two examples, CJB must set the barrier crossing O(0, 0).In the last two examples, CJB can set each barrier crossing some P_i such that the barrier is perpendicular to the line between P_i and O.
3 1 2 0 0 2 -1 0
0.0000000000
6 seconds
256 megabytes
['binary search', 'greedy', '*3100']
D. Tokitsukaze and Strange Rectangletime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n points on the plane, the i-th of which is at (x_i, y_i). Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area.The strange area is enclosed by three lines, x = l, y = a and x = r, as its left side, its bottom side and its right side respectively, where l, r and a can be any real numbers satisfying that l < r. The upper side of the area is boundless, which you can regard as a line parallel to the x-axis at infinity. The following figure shows a strange rectangular area. A point (x_i, y_i) is in the strange rectangular area if and only if l < x_i < r and y_i > a. For example, in the above figure, p_1 is in the area while p_2 is not.Tokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other.InputThe first line contains a single integer n (1 \leq n \leq 2 \times 10^5) — the number of points on the plane.The i-th of the next n lines contains two integers x_i, y_i (1 \leq x_i, y_i \leq 10^9) — the coordinates of the i-th point.All points are distinct.OutputPrint a single integer — the number of different non-empty sets of points she can obtain.ExamplesInput31 11 21 3Output3Input31 12 13 1Output6Input42 12 23 13 2Output6NoteFor the first example, there is exactly one set having k points for k = 1, 2, 3, so the total number is 3.For the second example, the numbers of sets having k points for k = 1, 2, 3 are 3, 2, 1 respectively, and their sum is 6.For the third example, as the following figure shows, there are 2 sets having one point; 3 sets having two points; 1 set having four points. Therefore, the number of different non-empty sets in this example is 2 + 3 + 0 + 1 = 6.
Input31 11 21 3
Output3
3 seconds
256 megabytes
['data structures', 'divide and conquer', 'sortings', 'two pointers', '*2000']
C. Tokitsukaze and Dueltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output"Duel!"Betting on the lovely princess Claris, the duel between Tokitsukaze and Quailty has started.There are n cards in a row. Each card has two sides, one of which has color. At first, some of these cards are with color sides facing up and others are with color sides facing down. Then they take turns flipping cards, in which Tokitsukaze moves first. In each move, one should choose exactly k consecutive cards and flip them to the same side, which means to make their color sides all face up or all face down. If all the color sides of these n cards face the same direction after one's move, the one who takes this move will win.Princess Claris wants to know who will win the game if Tokitsukaze and Quailty are so clever that they won't make mistakes.InputThe first line contains two integers n and k (1 \le k \le n \le 10^5).The second line contains a single string of length n that only consists of 0 and 1, representing the situation of these n cards, where the color side of the i-th card faces up if the i-th character is 1, or otherwise, it faces down and the i-th character is 0.OutputPrint "once again" (without quotes) if the total number of their moves can exceed 10^9, which is considered a draw.In other cases, print "tokitsukaze" (without quotes) if Tokitsukaze will win, or "quailty" (without quotes) if Quailty will win.Note that the output characters are case-sensitive, and any wrong spelling would be rejected.ExamplesInput 4 2 0101 Output quailty Input 6 1 010101 Output once again Input 6 5 010101 Output tokitsukaze Input 4 1 0011 Output once again NoteIn the first example, no matter how Tokitsukaze moves, there would be three cards with color sides facing the same direction after her move, and Quailty can flip the last card to this direction and win.In the second example, no matter how Tokitsukaze moves, Quailty can choose the same card and flip back to the initial situation, which can allow the game to end in a draw.In the third example, Tokitsukaze can win by flipping the leftmost five cards up or flipping the rightmost five cards down.The fourth example can be explained in the same way as the second example does.
4 2 0101
quailty
1 second
256 megabytes
['brute force', 'games', 'greedy', '*2300']
B. Tokitsukaze, CSL and Stone Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTokitsukaze and CSL are playing a little game of stones.In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile. Supposing that both players always take their best moves and never make mistakes, who will win the game?Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of piles.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_1, a_2, \ldots, a_n \le 10^9), which mean the i-th pile has a_i stones.OutputPrint "sjfnb" (without quotes) if Tokitsukaze will win, or "cslnb" (without quotes) if CSL will win. Note the output characters are case-sensitive.ExamplesInput 1 0 Output cslnb Input 2 1 0 Output cslnb Input 2 2 2 Output sjfnb Input 3 2 3 1 Output sjfnb NoteIn the first example, Tokitsukaze cannot take any stone, so CSL will win.In the second example, Tokitsukaze can only take a stone from the first pile, and then, even though they have no stone, these two piles will have the same number of stones, which implies CSL will win.In the third example, Tokitsukaze will win. Here is one of the optimal ways: Firstly, Tokitsukaze can choose the first pile and take a stone from that pile. Then, CSL can only choose the first pile, because if he chooses the second pile, he will lose immediately. Finally, Tokitsukaze can choose the second pile, and then CSL will have no choice but to lose. In the fourth example, they only have one good choice at any time, so Tokitsukaze can make the game lasting as long as possible and finally win.
1 0
cslnb
1 second
256 megabytes
['games', '*1800']
A. Tokitsukaze and Discard Itemstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Tokitsukaze found an interesting game. Tokitsukaze had n items at the beginning of this game. However, she thought there were too many items, so now she wants to discard m (1 \le m \le n) special items of them.These n items are marked with indices from 1 to n. In the beginning, the item with index i is placed on the i-th position. Items are divided into several pages orderly, such that each page contains exactly k positions and the last positions on the last page may be left empty.Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded. Consider the first example from the statement: n=10, m=4, k=5, p=[3, 5, 7, 10]. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices 3 and 5. After, the first page remains to be special. It contains [1, 2, 4, 6, 7], Tokitsukaze discards the special item with index 7. After, the second page is special (since it is the first page containing a special item). It contains [9, 10], Tokitsukaze discards the special item with index 10. Tokitsukaze wants to know the number of operations she would do in total.InputThe first line contains three integers n, m and k (1 \le n \le 10^{18}, 1 \le m \le 10^5, 1 \le m, k \le n) — the number of items, the number of special items to be discarded and the number of positions in each page.The second line contains m distinct integers p_1, p_2, \ldots, p_m (1 \le p_1 < p_2 < \ldots < p_m \le n) — the indices of special items which should be discarded.OutputPrint a single integer — the number of operations that Tokitsukaze would do in total.ExamplesInput 10 4 5 3 5 7 10 Output 3 Input 13 4 5 7 8 9 10 Output 1 NoteFor the first example: In the first operation, Tokitsukaze would focus on the first page [1, 2, 3, 4, 5] and discard items with indices 3 and 5; In the second operation, Tokitsukaze would focus on the first page [1, 2, 4, 6, 7] and discard item with index 7; In the third operation, Tokitsukaze would focus on the second page [9, 10] and discard item with index 10. For the second example, Tokitsukaze would focus on the second page [6, 7, 8, 9, 10] and discard all special items at once.
10 4 5 3 5 7 10
3
1 second
256 megabytes
['implementation', 'two pointers', '*1400']
C. Candies!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a sequence of digits of length 2^k [a_1, a_2, \ldots, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})\bmod 10 for 0\le i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}\ge 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}.Less formally, we partition sequence of length 2^k into 2^{k-1} pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth \ldots, the last pair consists of the (2^k-1)-th and (2^k)-th numbers. For every pair such that sum of numbers in it is at least 10, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by 10 (and don't change the order of the numbers).Perform this operation with a resulting array until it becomes of length 1. Let f([a_1, a_2, \ldots, a_{2^k}]) denote the number of candies we get in this process. For example: if the starting sequence is [8, 7, 3, 1, 7, 0, 9, 4] then:After the first operation the sequence becomes [(8 + 7)\bmod 10, (3 + 1)\bmod 10, (7 + 0)\bmod 10, (9 + 4)\bmod 10] = [5, 4, 7, 3], and we get 2 candies as 8 + 7 \ge 10 and 9 + 4 \ge 10.After the second operation the sequence becomes [(5 + 4)\bmod 10, (7 + 3)\bmod 10] = [9, 0], and we get one more candy as 7 + 3 \ge 10. After the final operation sequence becomes [(9 + 0) \bmod 10] = [9]. Therefore, f([8, 7, 3, 1, 7, 0, 9, 4]) = 3 as we got 3 candies in total.You are given a sequence of digits of length n s_1, s_2, \ldots s_n. You have to answer q queries of the form (l_i, r_i), where for i-th query you have to output f([s_{l_i}, s_{l_i+1}, \ldots, s_{r_i}]). It is guaranteed that r_i-l_i+1 is of form 2^k for some nonnegative integer k.InputThe first line contains a single integer n (1 \le n \le 10^5) — the length of the sequence.The second line contains n digits s_1, s_2, \ldots, s_n (0 \le s_i \le 9).The third line contains a single integer q (1 \le q \le 10^5) — the number of queries.Each of the next q lines contains two integers l_i, r_i (1 \le l_i \le r_i \le n) — i-th query. It is guaranteed that r_i-l_i+1 is a nonnegative integer power of 2.OutputOutput q lines, in i-th line output single integer — f([s_{l_i}, s_{l_i + 1}, \ldots, s_{r_i}]), answer to the i-th query.ExamplesInput 8 8 7 3 1 7 0 9 4 3 1 8 2 5 7 7 Output 3 1 0 Input 6 0 1 2 3 3 5 3 1 2 1 4 3 6 Output 0 0 1 NoteThe first example illustrates an example from the statement.f([7, 3, 1, 7]) = 1: sequence of operations is [7, 3, 1, 7] \to [(7 + 3)\bmod 10, (1 + 7)\bmod 10] = [0, 8] and one candy as 7 + 3 \ge 10 \to [(0 + 8) \bmod 10] = [8], so we get only 1 candy.f([9]) = 0 as we don't perform operations with it.
8 8 7 3 1 7 0 9 4 3 1 8 2 5 7 7
3 1 0
2 seconds
256 megabytes
['data structures', 'dp', 'implementation', 'math', '*1400']
B. Number Circletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n numbers a_1, a_2, \ldots, a_n. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?For example, for the array [1, 4, 5, 6, 7, 8], the arrangement on the left is valid, while arrangement on the right is not, as 5\ge 4 + 1 and 8> 1 + 6. InputThe first line contains a single integer n (3\le n \le 10^5) — the number of numbers.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \le 10^9) — the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).OutputIf there is no solution, output "NO" in the first line. If there is a solution, output "YES" in the first line. In the second line output n numbers — elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.ExamplesInput 3 2 4 3 Output YES 4 2 3 Input 5 1 2 3 4 4 Output YES 4 4 2 1 3Input 3 13 8 5 Output NOInput 4 1 10 100 1000 Output NONoteOne of the possible arrangements is shown in the first example: 4< 2 + 3;2 < 4 + 3;3< 4 + 2.One of the possible arrangements is shown in the second example.No matter how we arrange 13, 8, 5 in a circle in the third example, 13 will have 8 and 5 as neighbors, but 13\ge 8 + 5. There is no solution in the fourth example.
3 2 4 3
YES 4 2 3
1 second
256 megabytes
['greedy', 'math', 'sortings', '*1100']
A. Keanu Reevestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem.Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For example, 1, 101, 0000 are good, while 01, 1001, and 111000 are not good.We are given a string s of length n consisting of only zeroes and ones. We need to cut s into minimal possible number of substrings s_1, s_2, \ldots, s_k such that all of them are good. More formally, we have to find minimal by number of strings sequence of good strings s_1, s_2, \ldots, s_k such that their concatenation (joining) equals s, i.e. s_1 + s_2 + \dots + s_k = s.For example, cuttings 110010 into 110 and 010 or into 11 and 0010 are valid, as 110, 010, 11, 0010 are all good, and we can't cut 110010 to the smaller number of substrings as 110010 isn't good itself. At the same time, cutting of 110010 into 1100 and 10 isn't valid as both strings aren't good. Also, cutting of 110010 into 1, 1, 0010 isn't valid, as it isn't minimal, even though all 3 strings are good.Can you help Keanu? We can show that the solution always exists. If there are multiple optimal answers, print any.InputThe first line of the input contains a single integer n (1\le n \le 100) — the length of the string s.The second line contains the string s of length n consisting only from zeros and ones.OutputIn the first line, output a single integer k (1\le k) — a minimal number of strings you have cut s into.In the second line, output k strings s_1, s_2, \ldots, s_k separated with spaces. The length of each string has to be positive. Their concatenation has to be equal to s and all of them have to be good.If there are multiple answers, print any.ExamplesInput 1 1 Output 1 1Input 2 10 Output 2 1 0Input 6 100011 Output 2 100 011 NoteIn the first example, the string 1 wasn't cut at all. As it is good, the condition is satisfied.In the second example, 1 and 0 both are good. As 10 isn't good, the answer is indeed minimal.In the third example, 100 and 011 both are good. As 100011 isn't good, the answer is indeed minimal.
1 1
1 1
1 second
256 megabytes
['strings', '*800']
E. Problem from Red Pandatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt Moscow Workshops ICPC team gets a balloon for each problem they solved first. Team MSU Red Panda got so many balloons that they didn't know how to spend them. So they came up with a problem with them.There are several balloons, not more than 10^6 in total, each one is colored in one of k colors. We can perform the following operation: choose k-1 balloons such that they are of k-1 different colors, and recolor them all into remaining color. We can perform this operation any finite number of times (for example, we can only perform the operation if there are at least k-1 different colors among current balls).How many different balloon configurations can we get? Only number of balloons of each color matters, configurations differing only by the order of balloons are counted as equal. As this number can be very large, output it modulo 998244353.InputThe first line contains a single integer k (2 \le k \le 10^5) —the number of colors.The second line contains k integers a_1, a_2, \ldots, a_k (0 \le a_i) —initial configuration of balloons. a_i is number of balloons of color i. The total number of balloons doesn't exceed 10^6. In other words,a_1 + a_2 + a_3 + \ldots + a_k \le 10^6.OutputOutput number of possible configurations modulo 998244353.ExamplesInput 3 0 1 2 Output 3 Input 4 1 1 1 1 Output 5Input 5 0 0 1 2 3 Output 1Input 3 2 2 8 Output 31 NoteIn the first example, there are 3 configurations we can get: [0, 1, 2], [2, 0, 1], [1, 2, 0].In the second example, we can apply the operation not more than once, and possible configurations are: [1, 1, 1, 1], [0, 0, 0, 4], [0, 0, 4, 0], [0, 4, 0, 0], [4, 0, 0, 0]. In the third example, we can't apply any operations, so the only achievable configuration is the starting one.
3 0 1 2
3
1 second
256 megabytes
['combinatorics', '*3300']
D. Make Equaltime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n numbers a_1, a_2, \dots, a_n. In one operation we can add to any one of those numbers a nonnegative integer power of 2.What is the smallest number of operations we need to perform to make all n numbers equal? It can be proved that under given constraints it doesn't exceed 10^{18}.InputThe first line contains a single integer n (1 \le n \le 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^{17}).OutputOutput exactly one integer — the smallest number of operations we need to perform to make all n numbers equal.ExamplesInput 4 228 228 228 228 Output 0Input 3 2 2 8 Output 3NoteIn the first example, all numbers are already equal. So the needed number of operation is 0.In the second example, we can apply the operation 3 times: add 8 to first 2, add 8 to second 2, add 2 to 8, making all numbers equal to 10. It can be proved that we can't make all numbers equal in less than 3 operations.
4 228 228 228 228
0
4 seconds
256 megabytes
['dp', '*3100']
C. Array Beautytime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call beauty of an array b_1, b_2, \ldots, b_n (n > 1)  — \min\limits_{1 \leq i < j \leq n} |b_i - b_j|.You're given an array a_1, a_2, \ldots a_n and a number k. Calculate the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements.InputThe first line contains integers n, k (2 \le k \le n \le 1000).The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^5).OutputOutput one integer — the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.ExamplesInput 4 3 1 7 3 5 Output 8Input 5 5 1 10 100 1000 10000 Output 9NoteIn the first example, there are 4 subsequences of length 3 — [1, 7, 3], [1, 3, 5], [7, 3, 5], [1, 7, 5], each of which has beauty 2, so answer is 8.In the second example, there is only one subsequence of length 5 — the whole array, which has the beauty equal to |10-1| = 9.
4 3 1 7 3 5
8
5 seconds
256 megabytes
['dp', '*2500']
B. Count Pairstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a prime number p, n integers a_1, a_2, \ldots, a_n, and an integer k. Find the number of pairs of indexes (i, j) (1 \le i < j \le n) for which (a_i + a_j)(a_i^2 + a_j^2) \equiv k \bmod p.InputThe first line contains integers n, p, k (2 \le n \le 3 \cdot 10^5, 2 \le p \le 10^9, 0 \le k \le p-1). p is guaranteed to be prime.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le p-1). It is guaranteed that all elements are different.OutputOutput a single integer — answer to the problem.ExamplesInput 3 3 0 0 1 2 Output 1Input 6 7 2 1 2 3 4 5 6 Output 3NoteIn the first example:(0+1)(0^2 + 1^2) = 1 \equiv 1 \bmod 3.(0+2)(0^2 + 2^2) = 8 \equiv 2 \bmod 3.(1+2)(1^2 + 2^2) = 15 \equiv 0 \bmod 3.So only 1 pair satisfies the condition.In the second example, there are 3 such pairs: (1, 5), (2, 3), (4, 6).
3 3 0 0 1 2
1
4 seconds
256 megabytes
['math', 'matrices', 'number theory', 'two pointers', '*2300']
A2. Add on a Tree: Revolutiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any integer number x and add x to values written on all edges on the simple path between u and v. Note that in previous subtask x was allowed to be any real, here it has to be integer.For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -1 on the path from 4 to 5. You are given some configuration of nonnegative integer pairwise different even numbers, written on the edges. For a given configuration determine if it is possible to achieve it with these operations, and, if it is possible, output the sequence of operations that leads to the given configuration. Constraints on the operations are listed in the output format section.Leave is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.InputThe first line contains a single integer n (2 \le n \le 1000) — the number of nodes in a tree.Each of the next n-1 lines contains three integers u, v, val (1 \le u, v \le n, u \neq v, 0 \le val \le 10\,000), meaning that there is an edge between nodes u and v with val written on it. It is guaranteed that these edges form a tree. It is guaranteed that all val numbers are pairwise different and even. OutputIf there aren't any sequences of operations which lead to the given configuration, output "NO".If it exists, output "YES" in the first line. In the second line output m — number of operations you are going to apply (0 \le m \le 10^5). Note that you don't have to minimize the number of the operations!In the next m lines output the operations in the following format:u, v, x (1 \le u, v \le n, u \not = v, x — integer, -10^9 \le x \le 10^9), where u, v — leaves, x — number we are adding. It is guaranteed that if there exists a sequence of operations producing given configuration, then there exists a sequence of operations producing given configuration, satisfying all the conditions above.ExamplesInput 5 1 2 2 2 3 4 3 4 10 3 5 18 Output NOInput 6 1 2 6 1 3 8 1 4 12 2 5 2 2 6 4 Output YES 4 3 6 1 4 6 3 3 4 7 4 5 2NoteThe configuration from the first sample is drawn below, and it is impossible to achieve. The sequence of operations from the second sample is illustrated below.
5 1 2 2 2 3 4 3 4 10 3 5 18
NO
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'implementation', 'trees', '*2500']
A1. Add on a Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5. Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.InputThe first line contains a single integer n (2 \le n \le 10^5) — the number of nodes.Each of the next n-1 lines contains two integers u and v (1 \le u, v \le n, u \neq v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.OutputIf there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO". Otherwise, output "YES". You can print each letter in any case (upper or lower).ExamplesInput 2 1 2 Output YESInput 3 1 2 2 3 Output NOInput 5 1 2 1 3 1 4 2 5 Output NOInput 6 1 2 1 3 1 4 2 5 2 6 Output YESNoteIn the first example, we can add any real x to the value written on the only edge (1, 2). In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3). Below you can see graphs from examples 3, 4:
2 1 2
YES
1 second
256 megabytes
['trees', '*1600']
G. Gang Uptime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe leader of some very secretive organization has decided to invite all other members to a meeting. All members of the organization live in the same town which can be represented as n crossroads connected by m two-directional streets. The meeting will be held in the leader's house near the crossroad 1. There are k members of the organization invited to the meeting; i-th of them lives near the crossroad a_i. All members of the organization receive the message about the meeting at the same moment and start moving to the location where the meeting is held. In the beginning of each minute each person is located at some crossroad. He or she can either wait a minute at this crossroad, or spend a minute to walk from the current crossroad along some street to another crossroad (obviously, it is possible to start walking along the street only if it begins or ends at the current crossroad). In the beginning of the first minute each person is at the crossroad where he or she lives. As soon as a person reaches the crossroad number 1, he or she immediately comes to the leader's house and attends the meeting.Obviously, the leader wants all other members of the organization to come up as early as possible. But, since the organization is very secretive, the leader does not want to attract much attention. Let's denote the discontent of the leader as follows initially the discontent is 0; whenever a person reaches the crossroad number 1, the discontent of the leader increases by c \cdot x, where c is some fixed constant, and x is the number of minutes it took the person to reach the crossroad number 1; whenever x members of the organization walk along the same street at the same moment in the same direction, dx^2 is added to the discontent, where d is some fixed constant. This is not cumulative: for example, if two persons are walking along the same street in the same direction at the same moment, then 4d is added to the discontent, not 5d. Before sending a message about the meeting, the leader can tell each member of the organization which path they should choose and where they should wait. Help the leader to establish a plan for every member of the organization so they all reach the crossroad 1, and the discontent is minimized.InputThe first line of the input contains five integer numbers n, m, k, c and d (2 \le n \le 50, n - 1 \le m \le 50, 1 \le k, c, d \le 50) — the number of crossroads, the number of streets, the number of persons invited to the meeting and the constants affecting the discontent, respectively.The second line contains k numbers a_1, a_2, ..., a_k (2 \le a_i \le n) — the crossroads where the members of the organization live.Then m lines follow, each denoting a bidirectional street. Each line contains two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i) denoting a street connecting crossroads x_i and y_i. There may be multiple streets connecting the same pair of crossroads.It is guaranteed that every crossroad can be reached from every other crossroad using the given streets. OutputPrint one integer: the minimum discontent of the leader after everyone reaches crossroad 1.ExamplesInput 3 2 4 2 3 3 3 3 3 1 2 2 3 Output 52 Input 3 3 4 2 3 3 2 2 3 1 2 2 3 2 3 Output 38 NoteThe best course of action in the first test is the following: the first person goes along the street 2 to the crossroad 2, then goes along the street 1 to the crossroad 1 and attends the meeting; the second person waits one minute on the crossroad 3, then goes along the street 2 to the crossroad 2, then goes along the street 1 to the crossroad 1 and attends the meeting; the third person waits two minutes on the crossroad 3, then goes along the street 2 to the crossroad 2, then goes along the street 1 to the crossroad 1 and attends the meeting; the fourth person waits three minutes on the crossroad 3, then goes along the street 2 to the crossroad 2, then goes along the street 1 to the crossroad 1 and attends the meeting.
3 2 4 2 3 3 3 3 3 1 2 2 3
52
4 seconds
512 megabytes
['flows', 'graphs', '*2500']
F. Expected Square Beautytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet x be an array of integers x = [x_1, x_2, \dots, x_n]. Let's define B(x) as a minimal size of a partition of x into subsegments such that all elements in each subsegment are equal. For example, B([3, 3, 6, 1, 6, 6, 6]) = 4 using next partition: [3, 3\ |\ 6\ |\ 1\ |\ 6, 6, 6].Now you don't have any exact values of x, but you know that x_i can be any integer value from [l_i, r_i] (l_i \le r_i) uniformly at random. All x_i are independent.Calculate expected value of (B(x))^2, or E((B(x))^2). It's guaranteed that the expected value can be represented as rational fraction \frac{P}{Q} where (P, Q) = 1, so print the value P \cdot Q^{-1} \mod 10^9 + 7.InputThe first line contains the single integer n (1 \le n \le 2 \cdot 10^5) — the size of the array x.The second line contains n integers l_1, l_2, \dots, l_n (1 \le l_i \le 10^9).The third line contains n integers r_1, r_2, \dots, r_n (l_i \le r_i \le 10^9).OutputPrint the single integer — E((B(x))^2) as P \cdot Q^{-1} \mod 10^9 + 7.ExamplesInput 3 1 1 1 1 2 3 Output 166666673 Input 3 3 4 5 4 5 6 Output 500000010 NoteLet's describe all possible values of x for the first sample: [1, 1, 1]: B(x) = 1, B^2(x) = 1; [1, 1, 2]: B(x) = 2, B^2(x) = 4; [1, 1, 3]: B(x) = 2, B^2(x) = 4; [1, 2, 1]: B(x) = 3, B^2(x) = 9; [1, 2, 2]: B(x) = 2, B^2(x) = 4; [1, 2, 3]: B(x) = 3, B^2(x) = 9; So E = \frac{1}{6} (1 + 4 + 4 + 9 + 4 + 9) = \frac{31}{6} or 31 \cdot 6^{-1} = 166666673.All possible values of x for the second sample: [3, 4, 5]: B(x) = 3, B^2(x) = 9; [3, 4, 6]: B(x) = 3, B^2(x) = 9; [3, 5, 5]: B(x) = 2, B^2(x) = 4; [3, 5, 6]: B(x) = 3, B^2(x) = 9; [4, 4, 5]: B(x) = 2, B^2(x) = 4; [4, 4, 6]: B(x) = 2, B^2(x) = 4; [4, 5, 5]: B(x) = 2, B^2(x) = 4; [4, 5, 6]: B(x) = 3, B^2(x) = 9; So E = \frac{1}{8} (9 + 9 + 4 + 9 + 4 + 4 + 4 + 9) = \frac{52}{8} or 13 \cdot 2^{-1} = 500000010.
3 1 1 1 1 2 3
166666673
2 seconds
256 megabytes
['dp', 'math', 'probabilities', '*2500']
E. Tree Paintingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black vertex and paint it black.Each time when you choose a vertex (even during the first turn), you gain the number of points equal to the size of the connected component consisting only of white vertices that contains the chosen vertex. The game ends when all vertices are painted black.Let's see the following example:Vertices 1 and 4 are painted black already. If you choose the vertex 2, you will gain 4 points for the connected component consisting of vertices 2, 3, 5 and 6. If you choose the vertex 9, you will gain 3 points for the connected component consisting of vertices 7, 8 and 9.Your task is to maximize the number of points you gain.InputThe first line contains an integer n — the number of vertices in the tree (2 \le n \le 2 \cdot 10^5).Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the indices of vertices it connects (1 \le u_i, v_i \le n, u_i \ne v_i).It is guaranteed that the given edges form a tree.OutputPrint one integer — the maximum number of points you gain if you will play optimally.ExamplesInput 9 1 2 2 3 2 5 2 6 1 4 4 9 9 7 9 8 Output 36 Input 5 1 2 1 3 2 4 2 5 Output 14 NoteThe first example tree is shown in the problem statement.
9 1 2 2 3 2 5 2 6 1 4 4 9 9 7 9 8
36
2 seconds
256 megabytes
['dfs and similar', 'dp', 'trees', '*2100']
D. Subarray Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n and an array b_1, b_2, \dots, b_n.For one operation you can sort in non-decreasing order any subarray a[l \dots r] of the array a.For example, if a = [4, 2, 2, 1, 3, 1] and you choose subbarray a[2 \dots 5], then the array turns into [4, 1, 2, 2, 3, 1]. You are asked to determine whether it is possible to obtain the array b by applying this operation any number of times (possibly zero) to the array a.InputThe first line contains one integer t (1 \le t \le 3 \cdot 10^5) — the number of queries.The first line of each query contains one integer n (1 \le n \le 3 \cdot 10^5).The second line of each query contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n).The third line of each query contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le n).It is guaranteed that \sum n \le 3 \cdot 10^5 over all queries in a test.OutputFor each query print YES (in any letter case) if it is possible to obtain an array b and NO (in any letter case) otherwise.ExampleInput 4 7 1 7 1 4 4 5 6 1 1 4 4 5 7 6 5 1 1 3 3 5 1 1 3 3 5 2 1 1 1 2 3 1 2 3 3 2 1 Output YES YES NO NO NoteIn first test case the can sort subarray a_1 \dots a_5, then a will turn into [1, 1, 4, 4, 7, 5, 6], and then sort subarray a_5 \dots a_6.
4 7 1 7 1 4 4 5 6 1 1 4 4 5 7 6 5 1 1 3 3 5 1 1 3 3 5 2 1 1 1 2 3 1 2 3 3 2 1
YES YES NO NO
2 seconds
256 megabytes
['data structures', 'sortings', '*2400']
C. Vasya And Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has an array a_1, a_2, \dots, a_n.You don't know this array, but he told you m facts about this array. The i-th fact is a triple of numbers t_i, l_i and r_i (0 \le t_i \le 1, 1 \le l_i < r_i \le n) and it means: if t_i=1 then subbarray a_{l_i}, a_{l_i + 1}, \dots, a_{r_i} is sorted in non-decreasing order; if t_i=0 then subbarray a_{l_i}, a_{l_i + 1}, \dots, a_{r_i} is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter. For example if a = [2, 1, 1, 3, 2] then he could give you three facts: t_1=1, l_1=2, r_1=4 (the subarray [a_2, a_3, a_4] = [1, 1, 3] is sorted), t_2=0, l_2=4, r_2=5 (the subarray [a_4, a_5] = [3, 2] is not sorted), and t_3=0, l_3=3, r_3=5 (the subarray [a_3, a_5] = [1, 3, 2] is not sorted).You don't know the array a. Find any array which satisfies all the given facts.InputThe first line contains two integers n and m (2 \le n \le 1000, 1 \le m \le 1000).Each of the next m lines contains three integers t_i, l_i and r_i (0 \le t_i \le 1, 1 \le l_i < r_i \le n).If t_i = 1 then subbarray a_{l_i}, a_{l_i + 1}, \dots , a_{r_i} is sorted. Otherwise (if t_i = 0) subbarray a_{l_i}, a_{l_i + 1}, \dots , a_{r_i} is not sorted.OutputIf there is no array that satisfies these facts in only line print NO (in any letter case).If there is a solution, print YES (in any letter case). In second line print n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the array a, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them.ExamplesInput 7 4 1 1 3 1 2 5 0 5 6 1 6 7 Output YES 1 2 2 3 5 4 4 Input 4 2 1 1 4 0 2 3 Output NO
7 4 1 1 3 1 2 5 0 5 6 1 6 7
YES 1 2 2 3 5 4 4
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1800']
B. Letters Shoptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.There are m friends, the i-th of them is named t_i. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for s="arrayhead" and t_i="arya" 5 letters have to be bought ("arrayhead"). For example, for s="arrayhead" and t_i="harry" 6 letters have to be bought ("arrayhead"). For example, for s="arrayhead" and t_i="ray" 5 letters have to be bought ("arrayhead"). For example, for s="arrayhead" and t_i="r" 2 letters have to be bought ("arrayhead"). For example, for s="arrayhead" and t_i="areahydra" all 9 letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string s.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of showcase string s.The second line contains string s, consisting of exactly n lowercase Latin letters.The third line contains one integer m (1 \le m \le 5 \cdot 10^4) — the number of friends.The i-th of the next m lines contains t_i (1 \le |t_i| \le 2 \cdot 10^5) — the name of the i-th friend.It is guaranteed that \sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5.OutputFor each friend print the length of the shortest prefix of letters from s s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount.It is guaranteed that every friend can construct her/his name using the letters from the string s.ExampleInput 9 arrayhead 5 arya harry ray r areahydra Output 5 6 5 2 9
9 arrayhead 5 arya harry ray r areahydra
5 6 5 2 9
2 seconds
256 megabytes
['binary search', 'implementation', 'strings', '*1300']
A. Stickers and Toystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.Each Kinder Surprise can be one of three types: it can contain a single sticker and no toy; it can contain a single toy and no sticker; it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.InputThe first line contains the single integer T (1 \le T \le 100) — the number of queries.Next T lines contain three integers n, s and t each (1 \le n \le 10^9, 1 \le s, t \le n, s + t \ge n) — the number of eggs, stickers and toys.All queries are independent.OutputPrint T integers (one number per query) — the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toyExampleInput 3 10 5 7 10 10 10 2 1 1 Output 6 1 2 NoteIn the first query, we have to take at least 6 eggs because there are 5 eggs with only toy inside and, in the worst case, we'll buy all of them.In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg.In the third query, we have to buy both eggs: one with a sticker and one with a toy.
3 10 5 7 10 10 10 2 1 1
6 1 2
2 seconds
256 megabytes
['math', '*900']
F. Vus the Cossack and a Graphtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVus the Cossack has a simple graph with n vertices and m edges. Let d_i be a degree of the i-th vertex. Recall that a degree of the i-th vertex is the number of conected edges to the i-th vertex.He needs to remain not more than \lceil \frac{n+m}{2} \rceil edges. Let f_i be the degree of the i-th vertex after removing. He needs to delete them in such way so that \lceil \frac{d_i}{2} \rceil \leq f_i for each i. In other words, the degree of each vertex should not be reduced more than twice. Help Vus to remain the needed edges!InputThe first line contains two integers n and m (1 \leq n \leq 10^6, 0 \leq m \leq 10^6) — the number of vertices and edges respectively.Each of the next m lines contains two integers u_i and v_i (1 \leq u_i, v_i \leq n) — vertices between which there is an edge.It is guaranteed that the graph does not have loops and multiple edges.It is possible to show that the answer always exists.OutputIn the first line, print one integer k (0 \leq k \leq \lceil \frac{n+m}{2} \rceil) — the number of edges which you need to remain.In each of the next k lines, print two integers u_i and v_i (1 \leq u_i, v_i \leq n) — the vertices, the edge between which, you need to remain. You can not print the same edge more than once.ExamplesInput 6 6 1 2 2 3 3 4 4 5 5 3 6 5 Output 5 2 1 3 2 5 3 5 4 6 5 Input 10 20 4 3 6 5 4 5 10 8 4 8 5 8 10 4 9 5 5 1 3 8 1 2 4 7 1 4 10 7 1 7 6 1 9 6 3 9 7 9 6 2 Output 12 2 1 4 1 5 4 6 5 7 1 7 4 8 3 8 5 9 3 9 6 10 4 10 7
6 6 1 2 2 3 3 4 4 5 5 3 6 5
5 2 1 3 2 5 3 5 4 6 5
4 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', 'implementation', '*2400']
E. Vus the Cossack and a Fieldtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVus the Cossack has a field with dimensions n \times m, which consists of "0" and "1". He is building an infinite field from this field. He is doing this in this way: He takes the current field and finds a new inverted field. In other words, the new field will contain "1" only there, where "0" was in the current field, and "0" there, where "1" was. To the current field, he adds the inverted field to the right. To the current field, he adds the inverted field to the bottom. To the current field, he adds the current field to the bottom right. He repeats it.For example, if the initial field was: \begin{matrix} 1 & 0 & \\ 1 & 1 & \\ \end{matrix} After the first iteration, the field will be like this: \begin{matrix} 1 & 0 & 0 & 1 \\ 1 & 1 & 0 & 0 \\ 0 & 1 & 1 & 0 \\ 0 & 0 & 1 & 1 \\ \end{matrix} After the second iteration, the field will be like this: \begin{matrix} 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\ 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 \\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\ 0 & 1 & 1 & 0 & 1 & 0 & 0 & 1 \\ 0 & 0 & 1 & 1 & 1 & 1 & 0 & 0 \\ 1 & 0 & 0 & 1 & 0 & 1 & 1 & 0 \\ 1 & 1 & 0& 0 & 0 & 0 & 1 & 1 \\ \end{matrix} And so on...Let's numerate lines from top to bottom from 1 to infinity, and columns from left to right from 1 to infinity. We call the submatrix (x_1, y_1, x_2, y_2) all numbers that have coordinates (x, y) such that x_1 \leq x \leq x_2 and y_1 \leq y \leq y_2.The Cossack needs sometimes to find the sum of all the numbers in submatrices. Since he is pretty busy right now, he is asking you to find the answers!InputThe first line contains three integers n, m, q (1 \leq n, m \leq 1\,000, 1 \leq q \leq 10^5) — the dimensions of the initial matrix and the number of queries.Each of the next n lines contains m characters c_{ij} (0 \leq c_{ij} \leq 1) — the characters in the matrix.Each of the next q lines contains four integers x_1, y_1, x_2, y_2 (1 \leq x_1 \leq x_2 \leq 10^9, 1 \leq y_1 \leq y_2 \leq 10^9) — the coordinates of the upper left cell and bottom right cell, between which you need to find the sum of all numbers.OutputFor each query, print the answer.ExamplesInput 2 2 5 10 11 1 1 8 8 2 4 5 6 1 2 7 8 3 3 6 8 5 6 7 8 Output 32 5 25 14 4 Input 2 3 7 100 101 4 12 5 17 5 4 9 4 1 4 13 18 12 1 14 9 3 10 7 18 3 15 12 17 8 6 8 12 Output 6 3 98 13 22 15 3 NoteThe first example is explained in the legend.
2 2 5 10 11 1 1 8 8 2 4 5 6 1 2 7 8 3 3 6 8 5 6 7 8
32 5 25 14 4
2 seconds
256 megabytes
['divide and conquer', 'implementation', 'math', '*2500']
D. Vus the Cossack and Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVus the Cossack has n real numbers a_i. It is known that the sum of all numbers is equal to 0. He wants to choose a sequence b the size of which is n such that the sum of all numbers is 0 and each b_i is either \lfloor a_i \rfloor or \lceil a_i \rceil. In other words, b_i equals a_i rounded up or down. It is not necessary to round to the nearest integer.For example, if a = [4.58413, 1.22491, -2.10517, -3.70387], then b can be equal, for example, to [4, 2, -2, -4]. Note that if a_i is an integer, then there is no difference between \lfloor a_i \rfloor and \lceil a_i \rceil, b_i will always be equal to a_i.Help Vus the Cossack find such sequence!InputThe first line contains one integer n (1 \leq n \leq 10^5) — the number of numbers.Each of the next n lines contains one real number a_i (|a_i| < 10^5). It is guaranteed that each a_i has exactly 5 digits after the decimal point. It is guaranteed that the sum of all the numbers is equal to 0.OutputIn each of the next n lines, print one integer b_i. For each i, |a_i-b_i|<1 must be met.If there are multiple answers, print any.ExamplesInput 4 4.58413 1.22491 -2.10517 -3.70387 Output 4 2 -2 -4 Input 5 -6.32509 3.30066 -0.93878 2.00000 1.96321 Output -6 3 -1 2 2 NoteThe first example is explained in the legend.In the second example, we can round the first and fifth numbers up, and the second and third numbers down. We can round the fourth number neither up, nor down.
4 4.58413 1.22491 -2.10517 -3.70387
4 2 -2 -4
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1500']
C. Vus the Cossack and Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings a and b. It is known that |b| \leq |a|, that is, the length of b is at most the length of a.The Cossack considers every substring of length |b| in string a. Let's call this substring c. He matches the corresponding characters in b and c, after which he counts the number of positions where the two strings are different. We call this function f(b, c).For example, let b = 00110, and c = 11000. In these strings, the first, second, third and fourth positions are different.Vus the Cossack counts the number of such substrings c such that f(b, c) is even.For example, let a = 01100010 and b = 00110. a has four substrings of the length |b|: 01100, 11000, 10001, 00010. f(00110, 01100) = 2; f(00110, 11000) = 4; f(00110, 10001) = 4; f(00110, 00010) = 1. Since in three substrings, f(b, c) is even, the answer is 3.Vus can not find the answer for big strings. That is why he is asking you to help him.InputThe first line contains a binary string a (1 \leq |a| \leq 10^6) — the first string.The second line contains a binary string b (1 \leq |b| \leq |a|) — the second string.OutputPrint one number — the answer.ExamplesInput 01100010 00110 Output 3 Input 1010111110 0110 Output 4 NoteThe first example is explained in the legend.In the second example, there are five substrings that satisfy us: 1010, 0101, 1111, 1111.
01100010 00110
3
1 second
256 megabytes
['implementation', 'math', '*1800']
A. Vus the Cossack and a Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVus the Cossack holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks.Determine whether the Cossack can reward all participants, giving each of them at least one pen and at least one notebook.InputThe first line contains three integers n, m, and k (1 \leq n, m, k \leq 100) — the number of participants, the number of pens, and the number of notebooks respectively.OutputPrint "Yes" if it possible to reward all the participants. Otherwise, print "No".You can print each letter in any case (upper or lower).ExamplesInput 5 8 6 Output Yes Input 3 9 3 Output Yes Input 8 5 20 Output No NoteIn the first example, there are 5 participants. The Cossack has 8 pens and 6 notebooks. Therefore, he has enough pens and notebooks.In the second example, there are 3 participants. The Cossack has 9 pens and 3 notebooks. He has more than enough pens but only the minimum needed number of notebooks.In the third example, there are 8 participants but only 5 pens. Since the Cossack does not have enough pens, the answer is "No".
5 8 6
Yes
1 second
256 megabytes
['implementation', '*800']
G2. Playlist for Polycarp (hard version)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 \le t_i \le 50), g_i is its genre (1 \le g_i \le 3).Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.InputThe first line of the input contains two integers n and T (1 \le n \le 50, 1 \le T \le 2500) — the number of songs in the player and the required total duration, respectively.Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 \le t_i \le 50, 1 \le g_i \le 3) — the duration of the i-th song and its genre, respectively.OutputOutput one integer — the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).ExamplesInput 3 3 1 1 1 2 1 3 Output 6 Input 3 3 1 1 1 1 1 3 Output 2 Input 4 10 5 3 2 1 3 2 5 1 Output 10 NoteIn the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given).
3 3 1 1 1 2 1 3
6
5 seconds
256 megabytes
['combinatorics', 'dp', '*2600']
G1. Playlist for Polycarp (easy version)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.In the player, Polycarp stores n songs, each of which is characterized by two parameters: t_i and g_i, where t_i is the length of the song in minutes (1 \le t_i \le 15), g_i is its genre (1 \le g_i \le 3).Polycarp wants to create such a playlist so that he can listen to music all the time on the way from the university to his home, and at the time of his arrival home, the playlist is over. Polycarp never interrupts songs and always listens to them from beginning to end. Thus, if he started listening to the i-th song, he would spend exactly t_i minutes on its listening. Polycarp also does not like when two songs of the same genre play in a row (i.e. successively/adjacently) or when the songs in his playlist are repeated.Help Polycarpus count the number of different sequences of songs (their order matters), the total duration is exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different.InputThe first line of the input contains two integers n and T (1 \le n \le 15, 1 \le T \le 225) — the number of songs in the player and the required total duration, respectively.Next, the n lines contain descriptions of songs: the i-th line contains two integers t_i and g_i (1 \le t_i \le 15, 1 \le g_i \le 3) — the duration of the i-th song and its genre, respectively.OutputOutput one integer — the number of different sequences of songs, the total length of exactly T, such that there are no two consecutive songs of the same genre in them and all the songs in the playlist are different. Since the answer may be huge, output it modulo 10^9 + 7 (that is, the remainder when dividing the quantity by 10^9 + 7).ExamplesInput 3 3 1 1 1 2 1 3 Output 6 Input 3 3 1 1 1 1 1 3 Output 2 Input 4 10 5 3 2 1 3 2 5 1 Output 10 NoteIn the first example, Polycarp can make any of the 6 possible playlist by rearranging the available songs: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] and [3, 2, 1] (indices of the songs are given).In the second example, the first and second songs cannot go in succession (since they have the same genre). Thus, Polycarp can create a playlist in one of 2 possible ways: [1, 3, 2] and [2, 3, 1] (indices of the songs are given).In the third example, Polycarp can make the following playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], [1, 4], [4, 1], [2, 3, 4] and [4, 3, 2] (indices of the songs are given).
3 3 1 1 1 2 1 3
6
5 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', '*2100']
F. Two Pizzastime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA company of n friends wants to order exactly two pizzas. It is known that in total there are 9 pizza ingredients in nature, which are denoted by integers from 1 to 9.Each of the n friends has one or more favorite ingredients: the i-th of friends has the number of favorite ingredients equal to f_i (1 \le f_i \le 9) and your favorite ingredients form the sequence b_{i1}, b_{i2}, \dots, b_{if_i} (1 \le b_{it} \le 9).The website of CodePizza restaurant has exactly m (m \ge 2) pizzas. Each pizza is characterized by a set of r_j ingredients a_{j1}, a_{j2}, \dots, a_{jr_j} (1 \le r_j \le 9, 1 \le a_{jt} \le 9) , which are included in it, and its price is c_j.Help your friends choose exactly two pizzas in such a way as to please the maximum number of people in the company. It is known that a person is pleased with the choice if each of his/her favorite ingredients is in at least one ordered pizza. If there are several ways to choose two pizzas so as to please the maximum number of friends, then choose the one that minimizes the total price of two pizzas.InputThe first line of the input contains two integers n and m (1 \le n \le 10^5, 2 \le m \le 10^5) — the number of friends in the company and the number of pizzas, respectively.Next, the n lines contain descriptions of favorite ingredients of the friends: the i-th of them contains the number of favorite ingredients f_i (1 \le f_i \le 9) and a sequence of distinct integers b_{i1}, b_{i2}, \dots, b_{if_i} (1 \le b_{it} \le 9).Next, the m lines contain pizza descriptions: the j-th of them contains the integer price of the pizza c_j (1 \le c_j \le 10^9), the number of ingredients r_j (1 \le r_j \le 9) and the ingredients themselves as a sequence of distinct integers a_{j1}, a_{j2}, \dots, a_{jr_j} (1 \le a_{jt} \le 9).OutputOutput two integers j_1 and j_2 (1 \le j_1,j_2 \le m, j_1 \ne j_2) denoting the indices of two pizzas in the required set. If there are several solutions, output any of them. Pizza indices can be printed in any order.ExamplesInput 3 4 2 6 7 4 2 3 9 5 3 2 3 9 100 1 7 400 3 3 2 5 100 2 9 2 500 3 2 9 5 Output 2 3 Input 4 3 1 1 1 2 1 3 1 4 10 4 1 2 3 4 20 4 1 2 3 4 30 4 1 2 3 4 Output 1 2 Input 1 5 9 9 8 7 6 5 4 3 2 1 3 4 1 2 3 4 1 4 5 6 7 8 4 4 1 3 5 7 1 4 2 4 6 8 5 4 1 9 2 8 Output 2 4
3 4 2 6 7 4 2 3 9 5 3 2 3 9 100 1 7 400 3 3 2 5 100 2 9 2 500 3 2 9 5
2 3
4 seconds
256 megabytes
['bitmasks', 'brute force', '*2100']
E. Polycarp and Snakestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n \times m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only 26 letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed 26.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals 1, i.e. each snake has size either 1 \times l or l \times 1, where l is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.InputThe first line of the input contains one integer t (1 \le t \le 10^5) — the number of test cases to solve. Then t test cases follow.The first line of the test case description contains two integers n, m (1 \le n,m \le 2000) — length and width of the checkered sheet of paper respectively.Next n lines of test case description contain m symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell.It is guaranteed that the total area of all sheets in one test doesn't exceed 4\cdot10^6.OutputPrint the answer for each test case in the input.In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO.If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer k (0 \le k \le 26) — number of snakes. Then print k lines, in each line print four integers r_{1,i}, c_{1,i}, r_{2,i} and c_{2,i} — coordinates of extreme cells for the i-th snake (1 \le r_{1,i}, r_{2,i} \le n, 1 \le c_{1,i}, c_{2,i} \le m). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them.Note that Polycarp starts drawing of snakes with an empty sheet of paper.ExamplesInput 1 5 6 ...a.. ..bbb. ...a.. .cccc. ...a.. Output YES 3 1 4 5 4 2 3 2 5 4 2 4 5 Input 3 3 3 ... ... ... 4 4 ..c. adda bbcb .... 3 5 ..b.. aaaaa ..b.. Output YES 0 YES 4 2 1 2 4 3 1 3 4 1 3 3 3 2 2 2 3 NO Input 2 3 3 ... .a. ... 2 2 bb cc Output YES 1 2 2 2 2 YES 3 1 1 1 2 1 1 1 2 2 1 2 2
1 5 6 ...a.. ..bbb. ...a.. .cccc. ...a..
YES 3 1 4 5 4 2 3 2 5 4 2 4 5
4 seconds
256 megabytes
['brute force', 'implementation', '*2000']
D. Extra Elementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence a_1, a_2, \dots, a_k is called an arithmetic progression if for each i from 1 to k elements satisfy the condition a_i = a_1 + c \cdot (i - 1) for some fixed c.For example, these five sequences are arithmetic progressions: [5, 7, 9, 11], [101], [101, 100, 99], [13, 97] and [5, 5, 5, 5, 5]. And these four sequences aren't arithmetic progressions: [3, 1, 2], [1, 2, 4, 8], [1, -1, 1, -1] and [1, 2, 3, 3, 3].You are given a sequence of integers b_1, b_2, \dots, b_n. Find any index j (1 \le j \le n), such that if you delete b_j from the sequence, you can reorder the remaining n-1 elements, so that you will get an arithmetic progression. If there is no such index, output the number -1.InputThe first line of the input contains one integer n (2 \le n \le 2\cdot10^5) — length of the sequence b. The second line contains n integers b_1, b_2, \dots, b_n (-10^9 \le b_i \le 10^9) — elements of the sequence b.OutputPrint such index j (1 \le j \le n), so that if you delete the j-th element from the sequence, you can reorder the remaining elements, so that you will get an arithmetic progression. If there are multiple solutions, you are allowed to print any of them. If there is no such index, print -1.ExamplesInput 5 2 6 8 7 4 Output 4Input 8 1 2 3 4 5 6 7 8 Output 1Input 4 1 2 4 8 Output -1NoteNote to the first example. If you delete the 4-th element, you can get the arithmetic progression [2, 4, 6, 8].Note to the second example. The original sequence is already arithmetic progression, so you can delete 1-st or last element and you will get an arithmetical progression again.
5 2 6 8 7 4
4
2 seconds
256 megabytes
['implementation', 'math', '*1700']
C2. Exam in BerSU (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.If you write a solution in Python, then prefer to send it in PyPy to speed up execution time.A session has begun at Beland State University. Many students are taking exams.Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following: The i-th student randomly chooses a ticket. if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam. if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.The duration of the whole exam for all students is M minutes (\max t_i \le M), so students at the end of the list have a greater possibility to run out of time to pass the exam.For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.InputThe first line of the input contains two integers n and M (1 \le n \le 2 \cdot 10^5, 1 \le M \le 2 \cdot 10^7) — the number of students and the total duration of the exam in minutes, respectively.The second line of the input contains n integers t_i (1 \le t_i \le 100) — time in minutes that i-th student spends to answer to a ticket.It's guaranteed that all values of t_i are not greater than M.OutputPrint n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.ExamplesInput 7 15 1 2 3 4 5 6 7 Output 0 0 0 0 0 2 3 Input 5 100 80 40 40 40 60 Output 0 1 1 2 3 NoteThe explanation for the example 1.Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
7 15 1 2 3 4 5 6 7
0 0 0 0 0 2 3
2 seconds
256 megabytes
['brute force', 'data structures', 'greedy', 'math', '*1700']
C1. Exam in BerSU (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.A session has begun at Beland State University. Many students are taking exams.Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following: The i-th student randomly chooses a ticket. if this ticket is too hard to the student, he doesn't answer and goes home immediately (this process is so fast that it's considered no time elapses). This student fails the exam. if the student finds the ticket easy, he spends exactly t_i minutes to pass the exam. After it, he immediately gets a mark and goes home. Students take the exam in the fixed order, one-by-one, without any interruption. At any moment of time, Polygraph Poligrafovich takes the answer from one student.The duration of the whole exam for all students is M minutes (\max t_i \le M), so students at the end of the list have a greater possibility to run out of time to pass the exam.For each student i, you should count the minimum possible number of students who need to fail the exam so the i-th student has enough time to pass the exam.For each student i, find the answer independently. That is, if when finding the answer for the student i_1 some student j should leave, then while finding the answer for i_2 (i_2>i_1) the student j student does not have to go home.InputThe first line of the input contains two integers n and M (1 \le n \le 100, 1 \le M \le 100) — the number of students and the total duration of the exam in minutes, respectively.The second line of the input contains n integers t_i (1 \le t_i \le 100) — time in minutes that i-th student spends to answer to a ticket.It's guaranteed that all values of t_i are not greater than M.OutputPrint n numbers: the i-th number must be equal to the minimum number of students who have to leave the exam in order to i-th student has enough time to pass the exam.ExamplesInput 7 15 1 2 3 4 5 6 7 Output 0 0 0 0 0 2 3 Input 5 100 80 40 40 40 60 Output 0 1 1 2 3 NoteThe explanation for the example 1.Please note that the sum of the first five exam times does not exceed M=15 (the sum is 1+2+3+4+5=15). Thus, the first five students can pass the exam even if all the students before them also pass the exam. In other words, the first five numbers in the answer are 0.In order for the 6-th student to pass the exam, it is necessary that at least 2 students must fail it before (for example, the 3-rd and 4-th, then the 6-th will finish its exam in 1+2+5+6=14 minutes, which does not exceed M).In order for the 7-th student to pass the exam, it is necessary that at least 3 students must fail it before (for example, the 2-nd, 5-th and 6-th, then the 7-th will finish its exam in 1+3+4+7=15 minutes, which does not exceed M).
7 15 1 2 3 4 5 6 7
0 0 0 0 0 2 3
2 seconds
256 megabytes
['greedy', 'sortings', '*1200']
B. Email from Polycarptime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMethodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.InputThe first line of the input contains one integer n (1 \le n \le 10^5) — the number of pairs to check. Further input contains n descriptions of pairs.The first line of each description contains a single non-empty word s consisting of lowercase Latin letters. The second line of the description contains a single non-empty word t consisting of lowercase Latin letters. The lengths of both strings are not greater than 10^6.It is guaranteed that the total length of all words s in the input is not greater than 10^6. Also, it is guaranteed that the total length of all words t in the input is not greater than 10^6.OutputOutput n lines. In the i-th line for the i-th pair of words s and t print YES if the word t could be printed by typing the word s. Otherwise, print NO.ExamplesInput 4 hello hello hello helloo hello hlllloo hello helo Output YES YES NO NO Input 5 aa bb codeforces codeforce polycarp poolycarpp aaaa aaaab abcdefghijklmnopqrstuvwxyz zabcdefghijklmnopqrstuvwxyz Output NO NO YES NO NO
4 hello hello hello helloo hello hlllloo hello helo
YES YES NO NO
3 seconds
256 megabytes
['implementation', 'strings', '*1200']
A. Ropewalkerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad.The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performance, the distance between each pair of ropewalkers was at least d.Ropewalkers can walk on the rope. In one second, only one ropewalker can change his position. Every ropewalker can change his position exactly by 1 (i. e. shift by 1 to the left or right direction on the rope). Agafon, Boniface and Konrad can not move at the same time (Only one of them can move at each moment). Ropewalkers can be at the same positions at the same time and can "walk past each other".You should find the minimum duration (in seconds) of the performance. In other words, find the minimum number of seconds needed so that the distance between each pair of ropewalkers can be greater or equal to d.Ropewalkers can walk to negative coordinates, due to the rope is infinite to both sides.InputThe only line of the input contains four integers a, b, c, d (1 \le a, b, c, d \le 10^9). It is possible that any two (or all three) ropewalkers are in the same position at the beginning of the performance.OutputOutput one integer — the minimum duration (in seconds) of the performance.ExamplesInput 5 2 6 3 Output 2 Input 3 1 5 6 Output 8 Input 8 3 3 2 Output 2 Input 2 3 10 4 Output 3 NoteIn the first example: in the first two seconds Konrad moves for 2 positions to the right (to the position 8), while Agafon and Boniface stay at their positions. Thus, the distance between Agafon and Boniface will be |5 - 2| = 3, the distance between Boniface and Konrad will be |2 - 8| = 6 and the distance between Agafon and Konrad will be |5 - 8| = 3. Therefore, all three pairwise distances will be at least d=3, so the performance could be finished within 2 seconds.
5 2 6 3
2
1 second
256 megabytes
['math', '*800']
E3. Daleks' Invasion (hard)time limit per test10 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWith your help, Heidi has prepared a plan of trap placement and defence. Yet suddenly, the Doctor popped out of the TARDIS and told her that he had spied on the Daleks' preparations, and there is more of them than ever. Desperate times require desperate measures, so Heidi is going to risk meeting with the Daleks and she will consider placing a trap along any Corridor.This means she needs your help again in calculating E_{max}(c) – the largest e \le 10^9 such that if we changed the energy requirement of c to e, then the Daleks might use c in their invasion – but this time for all Time Corridors.InputFirst line: number n of destinations, number m of corridors (2 \leq n \leq 10^5, n - 1 \leq m \leq 10^6). The next m lines: destinations a, b and energy e (1 \leq a, b \leq n, a \neq b, 0 \leq e \leq 10^9).No pair \{a, b\} will repeat. The graph is guaranteed to be connected. It is not guaranteed that all energy requirements e are distinct, or that the minimum spanning tree is unique.OutputOutput m lines, each containing one integer: E_{max}(c_i) for the i-th Corridor c_i from the input.ExampleInput3 31 2 82 3 33 1 4Output488
Input3 31 2 82 3 33 1 4
Output488
10 seconds
256 megabytes
['data structures', 'dsu', 'graphs', 'trees', '*2400']
E2. Daleks' Invasion (medium)time limit per test15 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful field test, Heidi is considering deploying a trap along some Corridor, possibly not the first one. She wants to avoid meeting the Daleks inside the Time Vortex, so for abundance of caution she considers placing the traps only along those Corridors that are not going to be used according to the current Daleks' plan – which is to use a minimum spanning tree of Corridors. Heidi knows that all energy requirements for different Corridors are now different, and that the Daleks have a single unique plan which they are intending to use.Your task is to calculate the number E_{max}(c), which is defined in the same way as in the easy version – i.e., the largest e \le 10^9 such that if we changed the energy of corridor c to e, the Daleks might use it – but now for every corridor that Heidi considers. InputThe first line: number n of destinations, number m of Time Corridors (2 \leq n \leq 10^5, n - 1 \leq m \leq 10^6). The next m lines: destinations a, b and energy e (1 \leq a, b \leq n, a \neq b, 0 \leq e \leq 10^9).No pair \{a, b\} will repeat. The graph is guaranteed to be connected. All energy requirements e are distinct.OutputOutput m-(n-1) lines, each containing one integer: E_{max}(c_i) for the i-th Corridor c_i from the input that is not part of the current Daleks' plan (minimum spanning tree).ExampleInput3 31 2 82 3 33 1 4Output4NoteIf m = n-1, then you need not output anything.
Input3 31 2 82 3 33 1 4
Output4
15 seconds
256 megabytes
['dfs and similar', 'graphs', 'shortest paths', 'trees', '*2100']
E1. Daleks' Invasion (easy)time limit per test6 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputHeidi found out that the Daleks have created a network of bidirectional Time Corridors connecting different destinations (at different times!). She suspects that they are planning another invasion on the entire Space and Time. In order to counter the invasion, she plans to deploy a trap in the Time Vortex, along a carefully chosen Time Corridor. She knows that tinkering with the Time Vortex is dangerous, so she consulted the Doctor on how to proceed. She has learned the following: Different Time Corridors require different amounts of energy to keep stable. Daleks are unlikely to use all corridors in their invasion. They will pick a set of Corridors that requires the smallest total energy to maintain, yet still makes (time) travel possible between any two destinations (for those in the know: they will use a minimum spanning tree). Setting the trap may modify the energy required to keep the Corridor stable. Heidi decided to carry out a field test and deploy one trap, placing it along the first Corridor. But she needs to know whether the Daleks are going to use this corridor after the deployment of the trap. She gives you a map of Time Corridors (an undirected graph) with energy requirements for each Corridor.For a Corridor c, E_{max}(c) is the largest e \le 10^9 such that if we changed the required amount of energy of c to e, then the Daleks may still be using c in their invasion (that is, it belongs to some minimum spanning tree). Your task is to calculate E_{max}(c_1) for the Corridor c_1 that Heidi plans to arm with a trap, which is the first edge in the graph.InputThe first line contains integers n and m (2 \leq n \leq 10^5, n - 1 \leq m \leq 10^6), number of destinations to be invaded and the number of Time Corridors.Each of the next m lines describes a Corridor: destinations a, b and energy e (1 \leq a, b \leq n, a \neq b, 0 \leq e \leq 10^9).It's guaranteed, that no pair \{a, b\} will repeat and that the graph is connected — that is, it is possible to travel between any two destinations using zero or more Time Corridors.OutputOutput a single integer: E_{max}(c_1) for the first Corridor c_1 from the input.ExampleInput3 31 2 82 3 33 1 4Output4NoteAfter the trap is set, the new energy requirement for the first Corridor may be either smaller, larger, or equal to the old energy requiremenet.In the example, if the energy of the first Corridor is set to 4 or less, then the Daleks may use the set of Corridors \{ \{ 1,2 \}, \{ 2,3 \} \} (in particular, if it were set to less than 4, then this would be the only set of Corridors that they would use). However, if it is larger than 4, then they will instead use the set \{ \{2,3\}, \{3,1\} \}.
Input3 31 2 82 3 33 1 4
Output4
6 seconds
128 megabytes
['graphs', 'trees', '*1900']
D2. Parallel Universes (Hard)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHeidi enjoyed performing the simulation because she knew exactly when a new universe would be formed and where, and when a non-existent link would be broken and where.However, the multiverse itself works in mysterious ways. Well, it works using probabilities, which to some people is mysterious.At each unit time, when a decision is made, one of the two events will happen randomly. Let's denote l as the current length of the multiverse. With a probability of p_{create} = 1 - \frac{l}{m}, a universe will be created. With a probability of p_{break}=\frac{l}{m}, a non-existent link will be broken at some position.More specifically, When a universe is created, it will manifest itself between any two adjacent universes or at one of the ends. Each position occurs with a probability of \frac{1}{l + 1}. When a link is broken, it could be cut between any two adjacent universes, each with a probability of \frac{1}{l-1}. After separating the multiverse into two segments, the segment NOT containing the Doctor will cease to exist. As earlier, the Doctor remains in the same universe. However, if at some point the multiverse breaks in such a way that the Doctor finds himself at the leftmost or rightmost end of it, the TARDIS stops functioning.In such a case, the Doctor must actually walk across the multiverse to find the tools to fix it.We are interested in the expected value of the length of the multiverse when such an event occurs.InputThe first and only line contains three integers n, k and m (1 \le k \le n \le m \le 250), the initial length of the multiverse, the initial position of the Doctor, and the maximum possible length of the multiverse.OutputOutput a single integer on a single line, indicating the expected length of the multiverse.If the answer is \frac{p}{q}, please print r where p \equiv r \cdot q (\text{mod } 10^9 + 7).ExamplesInput 2 1 2 Output 2 Input 2 2 10 Output 2 Input 3 2 3 Output 2 Input 3 2 5 Output 941659828 Input 10 4 20 Output 196683114 NoteFor the first and the second test case, without any change to the multiverse, the Doctor is already at one of the ends.For the third test case, the multiverse can only break at a position, which renders the Doctor at one of its ends.For the fourth case, things seem to be a little more complicated, because the multiverse can grow and then be broken again.
2 1 2
2
4 seconds
256 megabytes
['math', 'matrices', '*3100']
D1. Parallel Universes (Easy)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Third Doctor Who once correctly said that travel between parallel universes is "like travelling sideways". However, he incorrectly thought that there were infinite parallel universes, whereas in fact, as we now all know, there will never be more than 250.Heidi recently got her hands on a multiverse observation tool. She was able to see all n universes lined up in a row, with non-existent links between them. She also noticed that the Doctor was in the k-th universe.The tool also points out that due to restrictions originating from the space-time discontinuum, the number of universes will never exceed m.Obviously, the multiverse is unstable because of free will. Each time a decision is made, one of two events will randomly happen: a new parallel universe is created, or a non-existent link is broken.More specifically, When a universe is created, it will manifest itself between any two adjacent universes or at one of the ends. When a link is broken, it could be cut between any two adjacent universes. After separating the multiverse into two segments, the segment NOT containing the Doctor will cease to exist. Heidi wants to perform a simulation of t decisions. Each time a decision is made, Heidi wants to know the length of the multiverse (i.e. the number of universes), and the position of the Doctor.InputThe first line contains four integers n, k, m and t (2 \le k \le n \le m \le 250, 1 \le t \le 1000).Each of the following t lines is in one of the following formats: "1 i" — meaning that a universe is inserted at the position i (1 \le i \le l + 1), where l denotes the current length of the multiverse. "0 i" — meaning that the i-th link is broken (1 \le i \le l - 1), where l denotes the current length of the multiverse. OutputOutput t lines. Each line should contain l, the current length of the multiverse and k, the current position of the Doctor.It is guaranteed that the sequence of the steps will be valid, i.e. the multiverse will have length at most m and when the link breaking is performed, there will be at least one universe in the multiverse.ExampleInput 5 2 10 4 0 1 1 1 0 4 1 2 Output 4 1 5 2 4 2 5 3 NoteThe multiverse initially consisted of 5 universes, with the Doctor being in the second.First, link 1 was broken, leaving the multiverse with 4 universes, and the Doctor in the first.Then, a universe was added to the leftmost end of the multiverse, increasing the multiverse length to 5, and the Doctor was then in the second universe.Then, the rightmost link was broken.Finally, a universe was added between the first and the second universe.
5 2 10 4 0 1 1 1 0 4 1 2
4 1 5 2 4 2 5 3
1 second
256 megabytes
['implementation', '*1600']
C2. Heidi and the Turing Test (Medium)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Cybermen solved that first test much quicker than the Daleks. Luckily for us, the Daleks were angry (shocking!) and they destroyed some of the Cybermen.After the fighting stopped, Heidi gave them another task to waste their time on.There are n points on a plane. Given a radius r, find the maximum number of points that can be covered by an L^1-ball with radius r.An L^1-ball with radius r and center (x_0, y_0) in a 2D-plane is defined as the set of points (x, y) such that the Manhattan distance between (x_0, y_0) and (x, y) is at most r.Manhattan distance between (x_0, y_0) and (x, y) is defined as |x - x_0| + |y - y_0|.InputThe first line contains two integers n, r (1 \le n \le 300\,000, 1 \le r \le 10^6), the number of points and the radius of the ball, respectively. Each of the next n lines contains integers x_i, y_i (-10^6 \leq x_i, y_i \leq 10^6), describing the coordinates of the i-th point.It is guaranteed, that all points are distinct.OutputPrint one integer — the maximum number points that an L^1-ball with radius r can cover.ExamplesInput 5 1 1 1 1 -1 -1 1 -1 -1 2 0 Output 3 Input 5 2 1 1 1 -1 -1 1 -1 -1 2 0 Output 5 NoteIn the first example, a ball centered at (1, 0) covers the points (1, 1), (1, -1), (2, 0).In the second example, a ball centered at (0, 0) covers all the points.Note that x_0 and y_0 need not be integer.
5 1 1 1 1 -1 -1 1 -1 -1 2 0
3
2 seconds
256 megabytes
['data structures', '*2200']
C1. Heidi and the Turing Test (Easy)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Cybermen and the Daleks have long been the Doctor's main enemies. Everyone knows that both these species enjoy destroying everything they encounter. However, a little-known fact about them is that they both also love taking Turing tests!Heidi designed a series of increasingly difficult tasks for them to spend their time on, which would allow the Doctor enough time to save innocent lives!The funny part is that these tasks would be very easy for a human to solve.The first task is as follows. There are some points on the plane. All but one of them are on the boundary of an axis-aligned square (its sides are parallel to the axes). Identify that point.InputThe first line contains an integer n (2 \le n \le 10).Each of the following 4n + 1 lines contains two integers x_i, y_i (0 \leq x_i, y_i \leq 50), describing the coordinates of the next point.It is guaranteed that there are at least n points on each side of the square and all 4n + 1 points are distinct.OutputPrint two integers — the coordinates of the point that is not on the boundary of the square.ExamplesInput 2 0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2 Output 1 1 Input 2 0 0 0 1 0 2 0 3 1 0 1 2 2 0 2 1 2 2 Output 0 3 NoteIn both examples, the square has four sides x=0, x=2, y=0, y=2.
2 0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2
1 1
3 seconds
256 megabytes
['implementation', '*1600']
B3. The Doctor Meets Vader (Hard)time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe rebels have saved enough gold to launch a full-scale attack. Now the situation is flipped, the rebels will send out the spaceships to attack the Empire bases!The galaxy can be represented as an undirected graph with n planets (nodes) and m wormholes (edges), each connecting two planets.A total of s rebel spaceships and b empire bases are located at different planets in the galaxy.Each spaceship is given a location x, denoting the index of the planet on which it is located, an attacking strength a, a certain amount of fuel f, and a price to operate p.Each base is given a location x, a defensive strength d, and a certain amount of gold g.A spaceship can attack a base if both of these conditions hold: the spaceship's attacking strength is greater or equal than the defensive strength of the base the spaceship's fuel is greater or equal to the shortest distance, computed as the number of wormholes, between the spaceship's node and the base's node The rebels are very proud fighters. So, if a spaceship cannot attack any base, no rebel pilot will accept to operate it.If a spaceship is operated, the profit generated by that spaceship is equal to the gold of the base it attacks minus the price to operate the spaceship. Note that this might be negative. A spaceship that is operated will attack the base that maximizes its profit.Darth Vader likes to appear rich at all times. Therefore, whenever a base is attacked and its gold stolen, he makes sure to immediately refill that base with gold.Therefore, for the purposes of the rebels, multiple spaceships can attack the same base, in which case each spaceship will still receive all the gold of that base.The rebels have tasked Heidi and the Doctor to decide which set of spaceships to operate in order to maximize the total profit.However, as the war has been going on for a long time, the pilots have formed unbreakable bonds, and some of them refuse to operate spaceships if their friends are not also operating spaceships.They have a list of k dependencies of the form s_1, s_2, denoting that spaceship s_1 can be operated only if spaceship s_2 is also operated.InputThe first line of input contains integers n and m (1 \leq n \leq 100, 0 \leq m \leq 10000), the number of nodes and the number of edges, respectively.The next m lines contain integers u and v (1 \leq u, v \leq n) denoting an undirected edge between the two nodes.The next line contains integers s, b and k (1 \leq s, b \leq 10^5, 0 \leq k \leq 1000), the number of spaceships, bases, and dependencies, respectively.The next s lines contain integers x, a, f, p (1 \leq x \leq n, 0 \leq a, f, p \leq 10^9), denoting the location, attack, fuel, and price of the spaceship. Ships are numbered from 1 to s.The next b lines contain integers x, d, g (1 \leq x \leq n, 0 \leq d, g \leq 10^9), denoting the location, defence, and gold of the base.The next k lines contain integers s_1 and s_2 (1 \leq s_1, s_2 \leq s), denoting a dependency of s_1 on s_2.OutputPrint a single integer, the maximum total profit that can be achieved.ExampleInput 6 7 1 2 2 3 3 4 4 6 6 5 4 4 3 6 4 2 2 1 10 2 5 3 8 2 7 5 1 0 2 6 5 4 1 3 7 6 5 2 3 4 2 3 2 Output 2 NoteThe optimal strategy is to operate spaceships 1, 2, and 4, which will attack bases 1, 1, and 2, respectively.
6 7 1 2 2 3 3 4 4 6 6 5 4 4 3 6 4 2 2 1 10 2 5 3 8 2 7 5 1 0 2 6 5 4 1 3 7 6 5 2 3 4 2 3 2
2
4 seconds
512 megabytes
['flows', 'shortest paths', '*2700']
B2. The Doctor Meets Vader (Medium)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThanks to the Doctor's help, the rebels managed to steal enough gold to launch a full-scale attack on the Empire! However, Darth Vader is looking for revenge and wants to take back his gold.The rebels have hidden the gold in various bases throughout the galaxy. Darth Vader and the Empire are looking to send out their spaceships to attack these bases.The galaxy can be represented as an undirected graph with n planets (nodes) and m wormholes (edges), each connecting two planets.A total of s empire spaceships and b rebel bases are located at different planets in the galaxy.Each spaceship is given a location x, denoting the index of the planet on which it is located, an attacking strength a, and a certain amount of fuel f.Each base is given a location x, and a defensive strength d.A spaceship can attack a base if both of these conditions hold: the spaceship's attacking strength is greater or equal than the defensive strength of the base the spaceship's fuel is greater or equal to the shortest distance, computed as the number of wormholes, between the spaceship's planet and the base's planet Vader is very particular about his attacking formations. He requires that each spaceship is to attack at most one base and that each base is to be attacked by at most one spaceship.Vader knows that the rebels have hidden k gold in each base, so he will assign the spaceships to attack bases in such a way that maximizes the number of bases attacked.Therefore, for each base that is attacked, the rebels lose k gold.However, the rebels have the ability to create any number of dummy bases. With the Doctor's help, these bases would exist beyond space and time, so all spaceship can reach them and attack them. Moreover, a dummy base is designed to seem irresistible: that is, it will always be attacked by some spaceship.Of course, dummy bases do not contain any gold, but creating such a dummy base costs h gold.What is the minimum gold the rebels can lose if they create an optimal number of dummy bases?InputThe first line contains two integers n and m (1 \leq n \leq 100, 0 \leq m \leq 10000), the number of nodes and the number of edges, respectively.The next m lines contain two integers u and v (1 \leq u, v \leq n) denoting an undirected edge between the two nodes.The next line contains four integers s, b, k and h (1 \leq s, b \leq 1000, 0 \leq k, h \leq 10^9), the number of spaceships, the number of bases, the cost of having a base attacked, and the cost of creating a dummy base, respectively.The next s lines contain three integers x, a, f (1 \leq x \leq n, 0 \leq a, f \leq 10^9), denoting the location, attack, and fuel of the spaceship.The next b lines contain two integers x, d (1 \leq x \leq n, 0 \leq d \leq 10^9), denoting the location and defence of the base.OutputPrint a single integer, the minimum cost in terms of gold.ExampleInput 6 7 1 2 2 3 3 4 4 6 6 5 4 4 3 6 4 2 7 3 1 10 2 3 8 2 5 1 0 6 5 4 3 7 5 2 Output 12 NoteOne way to minimize the cost is to build 4 dummy bases, for a total cost of 4 \times 3 = 12.One empire spaceship will be assigned to attack each of these dummy bases, resulting in zero actual bases attacked.
6 7 1 2 2 3 3 4 4 6 6 5 4 4 3 6 4 2 7 3 1 10 2 3 8 2 5 1 0 6 5 4 3 7 5 2
12
3 seconds
256 megabytes
['flows', 'graph matchings', 'graphs', 'shortest paths', 'sortings', '*2200']
B1. The Doctor Meets Vader (Easy)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHeidi and Doctor Who hopped out of the TARDIS and found themselves at EPFL in 2018. They were surrounded by stormtroopers and Darth Vader was approaching. Miraculously, they managed to escape to a nearby rebel base but the Doctor was very confused. Heidi reminded him that last year's HC2 theme was Star Wars. Now he understood, and he's ready to face the evils of the Empire!The rebels have s spaceships, each with a certain attacking power a.They want to send their spaceships to destroy the empire bases and steal enough gold and supplies in order to keep the rebellion alive.The empire has b bases, each with a certain defensive power d, and a certain amount of gold g.A spaceship can attack all the bases which have a defensive power less than or equal to its attacking power.If a spaceship attacks a base, it steals all the gold in that base.The rebels are still undecided which spaceship to send out first, so they asked for the Doctor's help. They would like to know, for each spaceship, the maximum amount of gold it can steal.InputThe first line contains integers s and b (1 \leq s, b \leq 10^5), the number of spaceships and the number of bases, respectively.The second line contains s integers a (0 \leq a \leq 10^9), the attacking power of each spaceship.The next b lines contain integers d, g (0 \leq d \leq 10^9, 0 \leq g \leq 10^4), the defensive power and the gold of each base, respectively.OutputPrint s integers, the maximum amount of gold each spaceship can steal, in the same order as the spaceships are given in the input.ExampleInput 5 4 1 3 5 2 4 0 1 4 2 2 8 9 4 Output 1 9 11 9 11 NoteThe first spaceship can only attack the first base.The second spaceship can attack the first and third bases.The third spaceship can attack the first, second and third bases.
5 4 1 3 5 2 4 0 1 4 2 2 8 9 4
1 9 11 9 11
4 seconds
256 megabytes
['binary search', 'sortings', '*1400']
A3. Heidi Learns Hashing (Hard)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow Heidi is ready to crack Madame Kovarian's hashing function.Madame Kovarian has a very strict set of rules for name changes. Two names can be interchanged only if using the following hashing function on them results in a collision. However, the hashing function is parametrized, so one can always find a set of parameters that causes such a collision. Heidi decided to exploit this to her advantage.Given two strings w_1, w_2 of equal length n consisting of lowercase English letters and an integer m.Consider the standard polynomial hashing function:H_p(w) := \left( \sum_{i=0}^{|w|-1} w_i r^i \right) \mbox{mod}(p)where p is some prime, and r is some number such that 2\leq r \leq p-2.The goal is to find r and a prime p (m \leq p \leq 10^9) such that H_p(w_1) = H_p(w_2).Strings w_1 and w_2 are sampled independently at random from all strings of length n over lowercase English letters.InputThe first line contains two integers n and m (10 \le n \le 10^5, 2 \le m \le 10^5).The second and the third line, respectively, contain the words w_1, w_2 that were sampled independently at random from all strings of length n over lowercase English letters.OutputOutput integers p, r.p should be a prime in the range [m, 10^9] and r should be an integer satisfying r\in [2,p-2].At least one solution is guaranteed to exist. In case multiple solutions exist, print any of them.ExamplesInput 10 5 bgcbaaaaaa cccaaaaaaa Output 5 2Input 10 100 melodypond riversongg Output 118219 79724 NoteIn the first example, note that even though p=3 and r=2 also causes a colision of hashes, it is not a correct solution, since m is 5 and thus we want p\geq 5.In the second example, we are aware of the extra 'g' at the end. We just didn't realize that "River Song" and "Melody Pond" have different lengths...
10 5 bgcbaaaaaa cccaaaaaaa
5 2
5 seconds
256 megabytes
['fft', 'math', 'number theory', '*3100']
A2. Heidi Learns Hashing (Medium)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter learning about polynomial hashing, Heidi decided to learn about shift-xor hashing. In particular, she came across this interesting problem.Given a bitstring y \in \{0,1\}^n find out the number of different k (0 \leq k < n) such that there exists x \in \{0,1\}^n for which y = x \oplus \mbox{shift}^k(x).In the above, \oplus is the xor operation and \mbox{shift}^k is the operation of shifting a bitstring cyclically to the right k times. For example, 001 \oplus 111 = 110 and \mbox{shift}^3(00010010111000) = 00000010010111.InputThe first line contains an integer n (1 \leq n \leq 2 \cdot 10^5), the length of the bitstring y.The second line contains the bitstring y.OutputOutput a single integer: the number of suitable values of k.ExampleInput 4 1010 Output 3 NoteIn the first example: 1100\oplus \mbox{shift}^1(1100) = 1010 1000\oplus \mbox{shift}^2(1000) = 1010 0110\oplus \mbox{shift}^3(0110) = 1010 There is no x such that x \oplus x = 1010, hence the answer is 3.
4 1010
3
2 seconds
256 megabytes
['brute force', 'number theory', '*2100']
A1. Heidi Learns Hashing (Easy)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMelody Pond was stolen from her parents as a newborn baby by Madame Kovarian, to become a weapon of the Silence in their crusade against the Doctor. Madame Kovarian changed Melody's name to River Song, giving her a new identity that allowed her to kill the Eleventh Doctor.Heidi figured out that Madame Kovarian uses a very complicated hashing function in order to change the names of the babies she steals. In order to prevent this from happening to future Doctors, Heidi decided to prepare herself by learning some basic hashing techniques.The first hashing function she designed is as follows.Given two positive integers (x, y) she defines H(x,y):=x^2+2xy+x+1.Now, Heidi wonders if the function is reversible. That is, given a positive integer r, can you find a pair (x, y) (of positive integers) such that H(x, y) = r?If multiple such pairs exist, output the one with smallest possible x. If there is no such pair, output "NO".InputThe first and only line contains an integer r (1 \le r \le 10^{12}).OutputOutput integers x, y such that H(x,y) = r and x is smallest possible, or "NO" if no such pair exists.ExamplesInput 19 Output 1 8 Input 16 Output NO
19
1 8
1 second
256 megabytes
['brute force', 'math', 'number theory', '*1200']
H. Subsequences (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and the hard versions is constraints.A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".You are given a string s consisting of n lowercase Latin letters.In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.InputThe first line of the input contains two integers n and k (1 \le n \le 100, 1 \le k \le 10^{12}) — the length of the string and the size of the set, correspondingly.The second line of the input contains a string s consisting of n lowercase Latin letters.OutputPrint one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.ExamplesInput 4 5 asdf Output 4 Input 5 6 aaaaa Output 15 Input 5 7 aaaaa Output -1 Input 10 100 ajihiushda Output 233 NoteIn the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
4 5 asdf
4
2 seconds
256 megabytes
['dp', 'strings', '*1900']
G. Candy Box (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is a version of problem D from the same contest with some additional constraints and tasks.There are n candies in a candy box. The type of the i-th candy is a_i (1 \le a_i \le n). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type 1 and two candies of type 2 is bad).It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.You really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number f_i is given, which is equal to 0 if you really want to keep i-th candy for yourself, or 1 if you don't mind including it into your gift. It is possible that two candies of the same type have different values of f_i.You want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having f_i = 1 in your gift.You have to answer q independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.The first line of each query contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of candies.Then n lines follow, each containing two integers a_i and f_i (1 \le a_i \le n, 0 \le f_i \le 1), where a_i is the type of the i-th candy, and f_i denotes whether you want to keep the i-th candy for yourself (0 if you want to keep it, 1 if you don't mind giving it away).It is guaranteed that the sum of n over all queries does not exceed 2 \cdot 10^5.OutputFor each query print two integers: the maximum number of candies in a gift you can compose, according to the constraints in the statement; the maximum number of candies having f_i = 1 in a gift you can compose that contains the maximum possible number of candies. ExampleInput 3 8 1 0 4 1 2 0 4 1 5 1 6 1 3 0 2 0 4 1 1 1 1 2 1 2 1 9 2 0 2 0 4 1 4 1 4 1 7 0 7 1 7 0 7 1 Output 3 3 3 3 9 5 NoteIn the first query, you can include two candies of type 4 and one candy of type 5. All of them have f_i = 1 and you don't mind giving them away as part of the gift.
3 8 1 0 4 1 2 0 4 1 5 1 6 1 3 0 2 0 4 1 1 1 1 2 1 2 1 9 2 0 2 0 4 1 4 1 4 1 7 0 7 1 7 0 7 1
3 3 3 3 9 5
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*2000']
F. Topforces Strikes Backtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne important contest will take place on the most famous programming platform (Topforces) very soon!The authors have a pool of n problems and should choose at most three of them into this contest. The prettiness of the i-th problem is a_i. The authors have to compose the most pretty contest (in other words, the cumulative prettinesses of chosen problems should be maximum possible).But there is one important thing in the contest preparation: because of some superstitions of authors, the prettinesses of problems cannot divide each other. In other words, if the prettinesses of chosen problems are x, y, z, then x should be divisible by neither y, nor z, y should be divisible by neither x, nor z and z should be divisible by neither x, nor y. If the prettinesses of chosen problems are x and y then neither x should be divisible by y nor y should be divisible by x. Any contest composed from one problem is considered good.Your task is to find out the maximum possible total prettiness of the contest composed of at most three problems from the given pool.You have to answer q independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.The first line of the query contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of problems.The second line of the query contains n integers a_1, a_2, \dots, a_n (2 \le a_i \le 2 \cdot 10^5), where a_i is the prettiness of the i-th problem.It is guaranteed that the sum of n over all queries does not exceed 2 \cdot 10^5.OutputFor each query print one integer — the maximum possible cumulative prettiness of the contest composed of at most three problems from the given pool of problems in the query.ExampleInput 3 4 5 6 15 30 4 10 6 30 15 3 3 4 6 Output 30 31 10
3 4 5 6 15 30 4 10 6 30 15 3 3 4 6
30 31 10
3 seconds
256 megabytes
['brute force', 'math', 'sortings', '*2100']
E. Subsequences (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and the hard versions is constraints.A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".You are given a string s consisting of n lowercase Latin letters.In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.InputThe first line of the input contains two integers n and k (1 \le n, k \le 100) — the length of the string and the size of the set, correspondingly.The second line of the input contains a string s consisting of n lowercase Latin letters.OutputPrint one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.ExamplesInput 4 5 asdf Output 4 Input 5 6 aaaaa Output 15 Input 5 7 aaaaa Output -1 Input 10 100 ajihiushda Output 233 NoteIn the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
4 5 asdf
4
2 seconds
256 megabytes
['dp', 'graphs', 'implementation', 'shortest paths', '*2000']
D. Candy Box (easy version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is actually a subproblem of problem G from the same contest.There are n candies in a candy box. The type of the i-th candy is a_i (1 \le a_i \le n).You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type 1 and two candies of type 2 is bad). It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.You have to answer q independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries. Each query is represented by two lines.The first line of each query contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of candies.The second line of each query contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n), where a_i is the type of the i-th candy in the box.It is guaranteed that the sum of n over all queries does not exceed 2 \cdot 10^5.OutputFor each query print one integer — the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.ExampleInput 3 8 1 4 8 4 5 6 3 8 16 2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1 9 2 2 4 4 4 7 7 7 7 Output 3 10 9 NoteIn the first query, you can prepare a gift with two candies of type 8 and one candy of type 5, totalling to 3 candies.Note that this is not the only possible solution — taking two candies of type 4 and one candy of type 6 is also valid.
3 8 1 4 8 4 5 6 3 8 16 2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1 9 2 2 4 4 4 7 7 7 7
3 10 9
3 seconds
256 megabytes
['greedy', 'sortings', '*1400']
C. Computer Gametime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.During each turn Vova can choose what to do: If the current charge of his laptop battery is strictly greater than a, Vova can just play, and then the charge of his laptop battery will decrease by a; if the current charge of his laptop battery is strictly greater than b (b<a), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by b; if the current charge of his laptop battery is less than or equal to a and b at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of n turns the charge of the laptop battery is strictly greater than 0). Vova has to play exactly n turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 10^5) — the number of queries. Each query is presented by a single line.The only line of the query contains four integers k, n, a and b (1 \le k, n \le 10^9, 1 \le b < a \le 10^9) — the initial charge of Vova's laptop battery, the number of turns in the game and values a and b, correspondingly.OutputFor each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.ExampleInput 6 15 5 3 2 15 5 4 3 15 5 2 1 15 5 5 1 16 7 5 2 20 5 7 3 Output 4 -1 5 2 0 1 NoteIn the first example query Vova can just play 4 turns and spend 12 units of charge and then one turn play and charge and spend 2 more units. So the remaining charge of the battery will be 1.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be 0 after the last turn.
6 15 5 3 2 15 5 4 3 15 5 2 1 15 5 5 1 16 7 5 2 20 5 7 3
4 -1 5 2 0 1
3 seconds
256 megabytes
['binary search', 'math', '*1400']
B. Equalize Pricestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n products in the shop. The price of the i-th product is a_i. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.In fact, the owner of the shop can change the price of some product i in such a way that the difference between the old price of this product a_i and the new price b_i is at most k. In other words, the condition |a_i - b_i| \le k should be satisfied (|x| is the absolute value of x).He can change the price for each product not more than once. Note that he can leave the old prices for some products. The new price b_i of each product i should be positive (i.e. b_i > 0 should be satisfied for all i from 1 to n).Your task is to find out the maximum possible equal price B of all productts with the restriction that for all products the condiion |a_i - B| \le k should be satisfied (where a_i is the old price of the product and B is the same new price of all products) or report that it is impossible to find such price B.Note that the chosen price B should be integer.You should answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 100) — the number of queries. Each query is presented by two lines.The first line of the query contains two integers n and k (1 \le n \le 100, 1 \le k \le 10^8) — the number of products and the value k. The second line of the query contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^8), where a_i is the price of the i-th product.OutputPrint q integers, where the i-th integer is the answer B on the i-th query.If it is impossible to equalize prices of all given products with restriction that for all products the condition |a_i - B| \le k should be satisfied (where a_i is the old price of the product and B is the new equal price of all products), print -1. Otherwise print the maximum possible equal price of all products.ExampleInput 4 5 1 1 1 2 3 1 4 2 6 4 8 5 2 2 1 6 3 5 5 2 5 Output 2 6 -1 7 NoteIn the first example query you can choose the price B=2. It is easy to see that the difference between each old price and each new price B=2 is no more than 1.In the second example query you can choose the price B=6 and then all the differences between old and new price B=6 will be no more than 2.In the third example query you cannot choose any suitable price B. For any value B at least one condition out of two will be violated: |1-B| \le 2, |6-B| \le 2.In the fourth example query all values B between 1 and 7 are valid. But the maximum is 7, so it's the answer.
4 5 1 1 1 2 3 1 4 2 6 4 8 5 2 2 1 6 3 5 5 2 5
2 6 -1 7
1 second
256 megabytes
['math', '*900']
A. Nearest Interesting Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp knows that if the sum of the digits of a number is divisible by 3, then the number itself is divisible by 3. He assumes that the numbers, the sum of the digits of which is divisible by 4, are also somewhat interesting. Thus, he considers a positive integer n interesting if its sum of digits is divisible by 4.Help Polycarp find the nearest larger or equal interesting number for the given number a. That is, find the interesting number n such that n \ge a and n is minimal.InputThe only line in the input contains an integer a (1 \le a \le 1000).OutputPrint the nearest greater or equal interesting number for the given number a. In other words, print the interesting number n such that n \ge a and n is minimal.ExamplesInput 432 Output 435 Input 99 Output 103 Input 237 Output 237 Input 42 Output 44
432
435
1 second
256 megabytes
['implementation', '*800']
F. Maximum Sinetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have given integers a, b, p, and q. Let f(x) = \text{abs}(\text{sin}(\frac{p}{q} \pi x)).Find minimum possible integer x that maximizes f(x) where a \le x \le b.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100) — the number of test cases.The first line of each test case contains four integers a, b, p, and q (0 \le a \le b \le 10^{9}, 1 \le p, q \le 10^{9}).OutputPrint the minimum possible integer x for each test cases, separated by newline.ExampleInput 2 0 3 1 3 17 86 389 995 Output 1 55 NoteIn the first test case, f(0) = 0, f(1) = f(2) \approx 0.866, f(3) = 0.In the second test case, f(55) \approx 0.999969, which is the largest among all possible values.
2 0 3 1 3 17 86 389 995
1 55
3 seconds
256 megabytes
['binary search', 'data structures', 'number theory', '*2700']
E. Product Oriented Recurrencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet f_{x} = c^{2x-6} \cdot f_{x-1} \cdot f_{x-2} \cdot f_{x-3} for x \ge 4.You have given integers n, f_{1}, f_{2}, f_{3}, and c. Find f_{n} \bmod (10^{9}+7).InputThe only line contains five integers n, f_{1}, f_{2}, f_{3}, and c (4 \le n \le 10^{18}, 1 \le f_{1}, f_{2}, f_{3}, c \le 10^{9}).OutputPrint f_{n} \bmod (10^{9} + 7).ExamplesInput 5 1 2 5 3 Output 72900 Input 17 97 41 37 11 Output 317451037 NoteIn the first example, f_{4} = 90, f_{5} = 72900.In the second example, f_{17} \approx 2.28 \times 10^{29587}.
5 1 2 5 3
72900
1 second
256 megabytes
['dp', 'math', 'matrices', 'number theory', '*2300']
D. Complete Mirrortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them.InputThe first line contains a single integer n (1 \le n \le 10^{5}) — the number of vertices.Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 \le v_{i} \lt u_{i} \le n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree.OutputIf there is such root vertex exists, print any of them. Otherwise, print -1.ExamplesInput 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 NoteThis is the picture for the first example. 1, 5, 7 also can be a valid answer. This is the picture for the second example. You can see that it's impossible to find such root vertex.
7 1 2 2 3 3 4 4 5 3 6 6 7
3
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'dp', 'hashing', 'implementation', 'trees', '*2400']
C. Beautiful Lyricstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below. The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line. The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line. The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel.For example of a beautiful lyric, "hello hellooowww" "whatsup yowowowow" is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o".For example of a not beautiful lyric, "hey man""iam mcdic" is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times.InputThe first line contains single integer n (1 \le n \le 10^{5}) — the number of words.The i-th of the next n lines contains string s_{i} consisting lowercase alphabet letters — the i-th word. It is guaranteed that the sum of the total word length is equal or less than 10^{6}. Each word contains at least one vowel.OutputIn the first line, print m — the number of maximum possible beautiful lyrics.In next 2m lines, print m beautiful lyrics (two lines per lyric).If there are multiple answers, print any.ExamplesInput 14 wow this is the first mcdics codeforces round hooray i am proud about that Output 3 about proud hooray round wow first this is i that mcdics am Input 7 arsijo suggested the idea for this problem Output 0 Input 4 same same same differ Output 1 same differ same same NoteIn the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces".In the second example, you cannot form any beautiful lyric from given words.In the third example, you can use the word "same" up to three times.
14 wow this is the first mcdics codeforces round hooray i am proud about that
3 about proud hooray round wow first this is i that mcdics am
1 second
256 megabytes
['data structures', 'greedy', 'strings', '*1700']
B. Plus from Picturetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a given picture with size w \times h. Determine if the given picture has a single "+" shape or not. A "+" shape is described below: A "+" shape has one center nonempty cell. There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other words, there should be a ray in each direction. All other cells are empty. Find out if the given picture has single "+" shape.InputThe first line contains two integers h and w (1 \le h, w \le 500) — the height and width of the picture.The i-th of the next h lines contains string s_{i} of length w consisting "." and "*" where "." denotes the empty space and "*" denotes the non-empty space.OutputIf the given picture satisfies all conditions, print "YES". Otherwise, print "NO".You can output each letter in any case (upper or lower).ExamplesInput 5 6 ...... ..*... .****. ..*... ..*... Output YES Input 3 5 ..*.. ****. .*... Output NO Input 7 7 ....... ...*... ..****. ...*... ...*... ....... .*..... Output NO Input 5 6 ..**.. ..**.. ****** ..**.. ..**.. Output NO Input 3 7 .*...*. ***.*** .*...*. Output NO Input 5 10 .......... ..*....... .*.******. ..*....... .......... Output NO NoteIn the first example, the given picture contains one "+".In the second example, two vertical branches are located in a different column.In the third example, there is a dot outside of the shape.In the fourth example, the width of the two vertical branches is 2.In the fifth example, there are two shapes.In the sixth example, there is an empty space inside of the shape.
5 6 ...... ..*... .****. ..*... ..*...
YES
1 second
256 megabytes
['dfs and similar', 'implementation', 'strings', '*1300']
A. Filling Shapestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a given integer n. Find the number of ways to fill all 3 \times n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap. This picture describes when n = 4. The left one is the shape and the right one is 3 \times n tiles. InputThe only line contains one integer n (1 \le n \le 60) — the length.OutputPrint the number of ways to fill.ExamplesInput 4 Output 4Input 1 Output 0NoteIn the first example, there are 4 possible cases of filling.In the second example, you cannot fill the shapes in 3 \times 1 tiles.
4
4
1 second
256 megabytes
['dp', 'math', '*1000']
E2. A Story of One Country (Hard)time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis problem differs from the previous problem only in constraints.Petya decided to visit Byteland during the summer holidays. It turned out that the history of this country is quite unusual.Initially, there were n different countries on the land that is now Berland. Each country had its own territory that was represented as a rectangle on the map. The sides of the rectangle were parallel to the axes, and the corners were located at points with integer coordinates. Territories of no two countries intersected, but it was possible that some territories touched each other. As time passed, sometimes two countries merged into one. It only happened if the union of their territories was also a rectangle. In the end only one country remained — Byteland.Initially, each country had a rectangular castle inside its territory. Its sides were parallel to the axes and its corners had integer coordinates. Some castles might touch the border of the corresponding country and sides or other castles. Miraculously, after all the unions the castles are still intact. Unfortunately, their locations are the only information we have to restore the initial territories of the countries. The possible formation of Byteland. The castles are shown in blue. Petya wonders why no information about the initial countries remained. He suspected that the whole story is a fake. You were recommended to him as a smart person. Please check whether or not there exists a possible set of initial territories that could make the story true.InputThe first line contains a single integer n (1 \leq n \leq 100\,000) — the number of countries and castles.Each of the next n lines contains four integers a_i, b_i, c_i, d_i (0 \leq a_i < c_i \leq 10^9, 0 \leq b_i < d_i \leq 10^9) — the coordinates of the i-th castle, where (a_i, b_i) are the coordinates of the lower left corner and (c_i, d_i) are the coordinates of the upper right corner.It is guaranteed that no two castles intersect, however, they may touch.OutputIf there exists a possible set of territories that satisfies the story, print "YES", otherwise print "NO".You can print each letter in any case (upper or lower).ExamplesInput 4 0 0 1 2 0 2 1 3 1 0 2 1 1 1 2 3 Output YES Input 4 0 0 2 1 1 2 3 3 2 0 3 2 0 1 1 3 Output NO NoteThe castles in the first and second examples are shown on the pictures below.  
4 0 0 1 2 0 2 1 3 1 0 2 1 1 1 2 3
YES
4 seconds
512 megabytes
['brute force', 'greedy', 'sortings', '*3000']
E1. A Story of One Country (Easy)time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis problem differs from the next problem only in constraints.Petya decided to visit Byteland during the summer holidays. It turned out that the history of this country is quite unusual.Initially, there were n different countries on the land that is now Berland. Each country had its own territory that was represented as a rectangle on the map. The sides of the rectangle were parallel to the axes, and the corners were located at points with integer coordinates. Territories of no two countries intersected, but it was possible that some territories touched each other. As time passed, sometimes two countries merged into one. It only happened if the union of their territories was also a rectangle. In the end only one country remained — Byteland.Initially, each country had a rectangular castle inside its territory. Its sides were parallel to the axes and its corners had integer coordinates. Some castles might touch the border of the corresponding country and sides or other castles. Miraculously, after all the unions the castles are still intact. Unfortunately, their locations are the only information we have to restore the initial territories of the countries. The possible formation of Byteland. The castles are shown in blue. Petya wonders why no information about the initial countries remained. He suspected that the whole story is a fake. You were recommended to him as a smart person. Please check whether or not there exists a possible set of initial territories that could make the story true.InputThe first line contains a single integer n (1 \leq n \leq 1000) — the number of countries and castles.Each of the next n lines contains four integers a_i, b_i, c_i, d_i (0 \leq a_i < c_i \leq 10^9, 0 \leq b_i < d_i \leq 10^9) — the coordinates of the i-th castle, where (a_i, b_i) are the coordinates of the lower left corner and (c_i, d_i) are the coordinates of the upper right corner.It is guaranteed, that no two castles intersect, however, they may touch.OutputIf there exists a possible set of territories that satisfies the story, print "YES", otherwise print "NO".You can print each letter in any case (upper or lower).ExamplesInput 4 0 0 1 2 0 2 1 3 1 0 2 1 1 1 2 3 Output YES Input 4 0 0 2 1 1 2 3 3 2 0 3 2 0 1 1 3 Output NO NoteThe castles in the first and second examples are shown on the pictures below.  
4 0 0 1 2 0 2 1 3 1 0 2 1 1 1 2 3
YES
4 seconds
512 megabytes
['brute force', 'divide and conquer', 'sortings', '*2500']
D. Irrigationtime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMisha was interested in water delivery from childhood. That's why his mother sent him to the annual Innovative Olympiad in Irrigation (IOI). Pupils from all Berland compete there demonstrating their skills in watering. It is extremely expensive to host such an olympiad, so after the first n olympiads the organizers introduced the following rule of the host city selection.The host cities of the olympiads are selected in the following way. There are m cities in Berland wishing to host the olympiad, they are numbered from 1 to m. The host city of each next olympiad is determined as the city that hosted the olympiad the smallest number of times before. If there are several such cities, the city with the smallest index is selected among them.Misha's mother is interested where the olympiad will be held in some specific years. The only information she knows is the above selection rule and the host cities of the first n olympiads. Help her and if you succeed, she will ask Misha to avoid flooding your house.InputThe first line contains three integers n, m and q (1 \leq n, m, q \leq 500\,000) — the number of olympiads before the rule was introduced, the number of cities in Berland wishing to host the olympiad, and the number of years Misha's mother is interested in, respectively.The next line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq m), where a_i denotes the city which hosted the olympiad in the i-th year. Note that before the rule was introduced the host city was chosen arbitrarily.Each of the next q lines contains an integer k_i (n + 1 \leq k_i \leq 10^{18}) — the year number Misha's mother is interested in host city in.OutputPrint q integers. The i-th of them should be the city the olympiad will be hosted in the year k_i.ExamplesInput 6 4 10 3 1 1 1 2 2 7 8 9 10 11 12 13 14 15 16 Output 4 3 4 2 3 4 1 2 3 4 Input 4 5 4 4 4 5 1 15 9 13 6 Output 5 3 3 3 NoteIn the first example Misha's mother is interested in the first 10 years after the rule was introduced. The host cities these years are 4, 3, 4, 2, 3, 4, 1, 2, 3, 4.In the second example the host cities after the new city is introduced are 2, 3, 1, 2, 3, 5, 1, 2, 3, 4, 5, 1.
6 4 10 3 1 1 1 2 2 7 8 9 10 11 12 13 14 15 16
4 3 4 2 3 4 1 2 3 4
2.5 seconds
512 megabytes
['binary search', 'data structures', 'implementation', 'sortings', 'trees', 'two pointers', '*2200']
C. Flagtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputInnokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in n \cdot m colored pieces that form a rectangle with n rows and m columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe.Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different.   These subrectangles are flags.      These subrectangles are not flags. InputThe first line contains two integers n and m (1 \le n, m \le 1\,000) — the number of rows and the number of columns on the blanket.Each of the next n lines contains m lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors.OutputIn the only line print the number of subrectangles which form valid flags.ExamplesInput 4 3 aaa bbb ccb ddd Output 6 Input 6 1 a a b b c c Output 1 Note  The selected subrectangles are flags in the first example.
4 3 aaa bbb ccb ddd
6
2 seconds
512 megabytes
['brute force', 'combinatorics', 'dp', 'implementation', '*1900']
B. Split a Numbertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain.InputThe first line contains a single integer l (2 \le l \le 100\,000) — the length of the Dima's favorite number.The second line contains the positive integer n initially written on the strip: the Dima's favorite number.The integer n consists of exactly l digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip.OutputPrint a single integer — the smallest number Dima can obtain.ExamplesInput 7 1234567 Output 1801 Input 3 101 Output 11 NoteIn the first example Dima can split the number 1234567 into integers 1234 and 567. Their sum is 1801.In the second example Dima can split the number 101 into integers 10 and 1. Their sum is 11. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros.
7 1234567
1801
2 seconds
512 megabytes
['greedy', 'implementation', 'strings', '*1500']
A. Chunga-Changatime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputSoon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per coconut. Sasha has x chizhiks, Masha has y chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.Consider the following example. Suppose Sasha has 5 chizhiks, Masha has 4 chizhiks, and the price for one coconut be 3 chizhiks. If the girls don't exchange with chizhiks, they will buy 1 + 1 = 2 coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have 6 chizhiks, Masha will have 3 chizhiks, and the girls will buy 2 + 1 = 3 coconuts. It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).InputThe first line contains three integers x, y and z (0 \le x, y \le 10^{18}, 1 \le z \le 10^{18}) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut. OutputPrint two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.ExamplesInput 5 4 3 Output 3 1 Input 6 8 2 Output 7 0 NoteThe first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy 3 + 4 = 7 coconuts.
5 4 3
3 1
1 second
512 megabytes
['greedy', 'math', '*1000']
B. Nick and Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNick had received an awesome array of integers a=[a_1, a_2, \dots, a_n] as a gift for his 5 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a_1 \cdot a_2 \cdot \dots a_n of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index i (1 \le i \le n) and do a_i := -a_i - 1.For example, he can change array [3, -1, -4, 1] to an array [-4, -1, 3, 1] after applying this operation to elements with indices i=1 and i=3. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements a_1 \cdot a_2 \cdot \dots a_n which can be received using only this operation in some order.If there are multiple answers, print any of them.InputThe first line contains integer n (1 \leq n \leq 10^{5}) — number of integers in the array.The second line contains n integers a_1, a_2, \ldots, a_n (-10^{6} \leq a_i \leq 10^{6}) — elements of the arrayOutputPrint n numbers — elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array.If there are multiple answers, print any of them.ExamplesInput 4 2 2 2 2 Output -3 -3 -3 -3 Input 1 0 Output 0 Input 3 -3 -3 2 Output -3 -3 2
4 2 2 2 2
-3 -3 -3 -3
1 second
256 megabytes
['greedy', 'implementation', '*1500']
A. Alex and a Rhombustime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid.A 1-st order rhombus is just a square 1 \times 1 (i.e just a cell).A n-th order rhombus for all n \geq 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look at the picture to understand it better). Alex asks you to compute the number of cells in a n-th order rhombus.InputThe first and only input line contains integer n (1 \leq n \leq 100) — order of a rhombus whose numbers of cells should be computed.OutputPrint exactly one integer — the number of cells in a n-th order rhombus.ExamplesInput 1 Output 1Input 2 Output 5Input 3 Output 13NoteImages of rhombus corresponding to the examples are given in the statement.
1
1
1 second
256 megabytes
['dp', 'implementation', 'math', '*800']
E. Alesya and Discrete Mathtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe call a function good if its domain of definition is some set of integers and if in case it's defined in x and x-1, f(x) = f(x-1) + 1 or f(x) = f(x-1).Tanya has found n good functions f_{1}, \ldots, f_{n}, which are defined on all integers from 0 to 10^{18} and f_i(0) = 0 and f_i(10^{18}) = L for all i from 1 to n. It's an notorious coincidence that n is a divisor of L. She suggests Alesya a game. Using one question Alesya can ask Tanya a value of any single function in any single point. To win Alesya must choose integers l_{i} and r_{i} (0 \leq l_{i} \leq r_{i} \leq 10^{18}), such that f_{i}(r_{i}) - f_{i}(l_{i}) \geq \frac{L}{n} (here f_i(x) means the value of i-th function at point x) for all i such that 1 \leq i \leq n so that for any pair of two functions their segments [l_i, r_i] don't intersect (but may have one common point).Unfortunately, Tanya doesn't allow to make more than 2 \cdot 10^{5} questions. Help Alesya to win!It can be proved that it's always possible to choose [l_i, r_i] which satisfy the conditions described above.It's guaranteed, that Tanya doesn't change functions during the game, i.e. interactor is not adaptiveInputThe first line contains two integers n and L (1 \leq n \leq 1000, 1 \leq L \leq 10^{18}, n is a divisor of L)  — number of functions and their value in 10^{18}.OutputWhen you've found needed l_i, r_i, print "!" without quotes on a separate line and then n lines, i-th from them should contain two integers l_i, r_i divided by space.InteractionTo ask f_i(x), print symbol "?" without quotes and then two integers i and x (1 \leq i \leq n, 0 \leq x \leq 10^{18}). Note, you must flush your output to get a response.After that, you should read an integer which is a value of i-th function in point x.You're allowed not more than 2 \cdot 10^5 questions.To flush you can use (just after printing an integer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. Hacks:Only tests where 1 \leq L \leq 2000 are allowed for hacks, for a hack set a test using following format:The first line should contain two integers n and L (1 \leq n \leq 1000, 1 \leq L \leq 2000, n is a divisor of L)  — number of functions and their value in 10^{18}.Each of n following lines should contain L numbers l_1, l_2, ... , l_L (0 \leq l_j < 10^{18} for all 1 \leq j \leq L and l_j < l_{j+1} for all 1 < j \leq L), in i-th of them l_j means that f_i(l_j) < f_i(l_j + 1).ExampleInput 5 5 ? 1 0 ? 1 1 ? 2 1 ? 2 2 ? 3 2 ? 3 3 ? 4 3 ? 4 4 ? 5 4 ? 5 5 ! 0 1 1 2 2 3 3 4 4 5 Output 0 1 1 2 2 3 3 4 4 4 5 NoteIn the example Tanya has 5 same functions where f(0) = 0, f(1) = 1, f(2) = 2, f(3) = 3, f(4) = 4 and all remaining points have value 5.Alesya must choose two integers for all functions so that difference of values of a function in its points is not less than \frac{L}{n} (what is 1 here) and length of intersection of segments is zero.One possible way is to choose pairs [0, 1], [1, 2], [2, 3], [3, 4] and [4, 5] for functions 1, 2, 3, 4 and 5 respectively.
5 5 ? 1 0 ? 1 1 ? 2 1 ? 2 2 ? 3 2 ? 3 3 ? 4 3 ? 4 4 ? 5 4 ? 5 5 ! 0 1 1 2 2 3 3 4 4 5
0 1 1 2 2 3 3 4 4 4 5
5 seconds
256 megabytes
['divide and conquer', 'interactive', '*3200']
D. Fedor Runs for Presidenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedor runs for president of Byteland! In the debates, he will be asked how to solve Byteland's transport problem. It's a really hard problem because of Byteland's transport system is now a tree (connected graph without cycles). Fedor's team has found out in the ministry of transport of Byteland that there is money in the budget only for one additional road. In the debates, he is going to say that he will build this road as a way to maximize the number of distinct simple paths in the country. A simple path is a path which goes through every vertex no more than once. Two simple paths are named distinct if sets of their edges are distinct. But Byteland's science is deteriorated, so Fedor's team hasn't succeeded to find any scientists to answer how many distinct simple paths they can achieve after adding exactly one edge on the transport system?Help Fedor to solve it.An edge can be added between vertices that are already connected, but it can't be a loop.In this problem, we consider only simple paths of length at least two.InputThe first line contains one integer n (2 \leq n \leq 500\ 000) — number of vertices in Byteland's transport system.Each of the following n - 1 lines contains two integers v_i and u_i (1 \leq v_i, u_i \leq n). It's guaranteed that the graph is tree.OutputPrint exactly one integer — a maximal number of simple paths that can be achieved after adding one edge.ExamplesInput 2 1 2 Output 2 Input 4 1 2 1 3 1 4 Output 11 Input 6 1 2 1 3 3 4 3 5 4 6 Output 29
2 1 2
2
2 seconds
256 megabytes
['data structures', 'dp', 'trees', '*2700']
C. Serge and Dining Roomtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSerge came to the school dining room and discovered that there is a big queue here. There are m pupils in the queue. He's not sure now if he wants to wait until the queue will clear, so he wants to know which dish he will receive if he does. As Serge is very tired, he asks you to compute it instead of him.Initially there are n dishes with costs a_1, a_2, \ldots, a_n. As you already know, there are the queue of m pupils who have b_1, \ldots, b_m togrogs respectively (pupils are enumerated by queue order, i.e the first pupil in the queue has b_1 togrogs and the last one has b_m togrogs)Pupils think that the most expensive dish is the most delicious one, so every pupil just buys the most expensive dish for which he has money (every dish has a single copy, so when a pupil has bought it nobody can buy it later), and if a pupil doesn't have money for any dish, he just leaves the queue (so brutal capitalism...)But money isn't a problem at all for Serge, so Serge is buying the most expensive dish if there is at least one remaining.Moreover, Serge's school has a very unstable economic situation and the costs of some dishes or number of togrogs of some pupils can change. More formally, you must process q queries: change a_i to x. It means that the price of the i-th dish becomes x togrogs. change b_i to x. It means that the i-th pupil in the queue has x togrogs now. Nobody leaves the queue during those queries because a saleswoman is late.After every query, you must tell Serge price of the dish which he will buy if he has waited until the queue is clear, or -1 if there are no dishes at this point, according to rules described above.InputThe first line contains integers n and m (1 \leq n, m \leq 300\ 000) — number of dishes and pupils respectively. The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^{6}) — elements of array a. The third line contains m integers b_1, b_2, \ldots, b_{m} (1 \leq b_i \leq 10^{6}) — elements of array b. The fourth line conatins integer q (1 \leq q \leq 300\ 000) — number of queries.Each of the following q lines contains as follows: if a query changes price of some dish, it contains 1, and two integers i and x (1 \leq i \leq n, 1 \leq x \leq 10^{6}), what means a_i becomes x. if a query changes number of togrogs of some pupil, it contains 2, and two integers i and x (1 \leq i \leq m, 1 \leq x \leq 10^{6}), what means b_i becomes x. OutputFor each of q queries prints the answer as the statement describes, the answer of the i-th query in the i-th line (the price of the dish which Serge will buy or -1 if nothing remains)ExamplesInput 1 1 1 1 1 1 1 100 Output 100 Input 1 1 1 1 1 2 1 100 Output -1 Input 4 6 1 8 2 4 3 3 6 1 5 2 3 1 1 1 2 5 10 1 1 6 Output 8 -1 4 NoteIn the first sample after the first query, there is one dish with price 100 togrogs and one pupil with one togrog, so Serge will buy the dish with price 100 togrogs.In the second sample after the first query, there is one dish with price one togrog and one pupil with 100 togrogs, so Serge will get nothing.In the third sample after the first query, nobody can buy the dish with price 8, so Serge will take it. After the second query, all dishes will be bought, after the third one the third and fifth pupils will by the first and the second dishes respectively and nobody will by the fourth one.
1 1 1 1 1 1 1 100
100
4 seconds
256 megabytes
['binary search', 'data structures', 'graph matchings', 'greedy', 'implementation', 'math', 'trees', '*2200']
B. Tolik and His Uncletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.In this task you are given a cell field n \cdot m, consisting of n rows and m columns, where point's coordinates (x, y) mean it is situated in the x-th row and y-th column, considering numeration from one (1 \leq x \leq n, 1 \leq y \leq m). Initially, you stand in the cell (1, 1). Every move you can jump from cell (x, y), which you stand in, by any non-zero vector (dx, dy), thus you will stand in the (x+dx, y+dy) cell. Obviously, you can't leave the field, but also there is one more important condition — you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).Tolik's uncle is a very respectful person. Help him to solve this task!InputThe first and only line contains two positive integers n, m (1 \leq n \cdot m \leq 10^{6}) — the number of rows and columns of the field respectively.OutputPrint "-1" (without quotes) if it is impossible to visit every cell exactly once.Else print n \cdot m pairs of integers, i-th from them should contain two integers x_i, y_i (1 \leq x_i \leq n, 1 \leq y_i \leq m) — cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too.Notice that the first cell should have (1, 1) coordinates, according to the statement.ExamplesInput 2 3 Output 1 1 1 3 1 2 2 2 2 3 2 1Input 1 1 Output 1 1 NoteThe vectors from the first example in the order of making jumps are (0, 2), (0, -1), (1, 0), (0, 1), (0, -2).
2 3
1 1 1 3 1 2 2 2 2 3 2 1
1 second
256 megabytes
['constructive algorithms', '*1800']
A. Valeriy and Dequetime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, \ldots, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation.For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2].The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, \ldots, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation.Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque.Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.InputThe first line contains two integers n and q (2 \leq n \leq 10^5, 0 \leq q \leq 3 \cdot 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 \leq a_i \leq 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 \leq m_j \leq 10^{18}).OutputFor each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation.ExamplesInput 5 3 1 2 3 4 5 1 2 10 Output 1 2 2 3 5 2 Input 2 0 0 0 Output Note Consider all 10 steps for the first test in detail: [1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively.So, 2 we write to the beginning of the deque, and 1 — to the end.We get the following status of the deque: [2, 3, 4, 5, 1]. [2, 3, 4, 5, 1] \Rightarrow A = 2, B = 3. [3, 4, 5, 1, 2] [4, 5, 1, 2, 3] [5, 1, 2, 3, 4] [5, 2, 3, 4, 1] [5, 3, 4, 1, 2] [5, 4, 1, 2, 3] [5, 1, 2, 3, 4] [5, 2, 3, 4, 1] \Rightarrow A = 5, B = 2.
5 3 1 2 3 4 5 1 2 10
1 2 2 3 5 2
6 seconds
256 megabytes
['data structures', 'implementation', '*1500']
H. Stock Exchangetime limit per test6 secondsmemory limit per test16 megabytesinputstandard inputoutputstandard outputWarning: This problem has an unusual memory limit!Bob decided that he will not waste his prime years implementing GUI forms for a large corporation and instead will earn his supper on the Stock Exchange Reykjavik. The Stock Exchange Reykjavik is the only actual stock exchange in the world. The only type of transaction is to take a single share of stock x and exchange it for a single share of stock y, provided that the current price of share x is at least the current price of share y. There are 2n stocks listed on the SER that are of interest to Bob, numbered from 1 to 2n. Bob owns a single share of stocks 1 through n and would like to own a single share of each of n+1 through 2n some time in the future.Bob managed to forecast the price of each stock — in time t \geq 0, the stock i will cost a_i \cdot \lfloor t \rfloor + b_i. The time is currently t = 0. Help Bob find the earliest moment in time in which he can own a single share of each of n+1 through 2n, and the minimum number of stock exchanges he has to perform in order to do that.You may assume that the Stock Exchange has an unlimited amount of each stock at any point in time. InputThe first line contains a single integer n (1 \leq n \leq 2200) — the number stocks currently owned by Bob.Each of the next 2n lines contains integers a_i and b_i (0 \leq a_i, b_i \leq 10^9), representing the stock price of stock i. OutputIf it is impossible for Bob to achieve his goal, output a single integer -1.Otherwise, output two integers T and E, where T is the minimum time in which he can achieve his goal, and E is the minimum number of exchanges in which he can achieve his goal at time T.ExamplesInput 1 3 10 1 16 Output 3 1 Input 2 3 0 2 1 1 10 1 11 Output 6 3 Input 1 42 42 47 47 Output -1 Input 8 145 1729363 891 4194243 424 853731 869 1883440 843 556108 760 1538373 270 762781 986 2589382 610 99315884 591 95147193 687 99248788 65 95114537 481 99071279 293 98888998 83 99764577 769 96951171 Output 434847 11 Input 8 261 261639 92 123277 271 131614 320 154417 97 258799 246 17926 117 222490 110 39356 85 62864876 86 62781907 165 62761166 252 62828168 258 62794649 125 62817698 182 62651225 16 62856001 Output 1010327 11 NoteIn the first example, Bob simply waits until time t = 3, when both stocks cost exactly the same amount.In the second example, the optimum strategy is to exchange stock 2 for stock 1 at time t = 1, then exchange one share of stock 1 for stock 3 at time t = 5 (where both cost 15) and then at time t = 6 exchange the second on for the stock number 4 (when they cost 18 and 17, respectively). Note that he can achieve his goal also with only two exchanges, but this would take total time of t = 9, when he would finally be able to exchange the share number 2 for the share number 3. In the third example, Bob can never achieve his goal, as the second stock is always strictly more expensive than the first one.
1 3 10 1 16
3 1
6 seconds
16 megabytes
['binary search', 'flows', 'graphs', '*3500']
G. The Awesomest Vertextime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree on n vertices. The vertices are numbered from 1 to n; the root is the vertex number 1.Each vertex has two integers associated with it: a_i and b_i. We denote the set of all ancestors of v (including v itself) by R(v). The awesomeness of a vertex v is defined as \left| \sum_{w \in R(v)} a_w\right| \cdot \left|\sum_{w \in R(v)} b_w\right|,where |x| denotes the absolute value of x. Process q queries of one of the following forms: 1 v x — increase a_v by a positive integer x. 2 v — report the maximum awesomeness in the subtree of vertex v. InputThe first line contains two integers n and q (1 \leq n \leq 2\cdot 10^5, 1 \leq q \leq 10^5) — the number of vertices in the tree and the number of queries, respectively.The second line contains n - 1 integers p_2, p_3, \dots, p_n (1 \leq p_i < i), where p_i means that there is an edge between vertices i and p_i.The third line contains n integers a_1, a_2, \dots, a_n (-5000 \leq a_i \leq 5000), the initial values of a_i for each vertex.The fourth line contains n integers b_1, b_2, \dots, b_n (-5000 \leq b_i \leq 5000), the values of b_i for each vertex.Each of the next q lines describes a query. It has one of the following forms: 1 v x  (1 \leq v \leq n, 1\leq x \leq 5000). 2 v  (1 \leq v \leq n). OutputFor each query of the second type, print a single line with the maximum awesomeness in the respective subtree.ExampleInput5 61 1 2 210 -3 -7 -3 -1010 3 9 3 62 12 21 2 62 11 2 52 1Output10091169240NoteThe initial awesomeness of the vertices is [100, 91, 57, 64, 57]. The most awesome vertex in the subtree of vertex 1 (the first query) is 1, and the most awesome vertex in the subtree of vertex 2 (the second query) is 2. After the first update (the third query), the awesomeness changes to [100, 169, 57, 160, 57] and thus the most awesome vertex in the whole tree (the fourth query) is now 2.After the second update (the fifth query), the awesomeness becomes [100, 234, 57, 240, 152], hence the most awesome vertex (the sixth query) is now 4.
Input5 61 1 2 210 -3 -7 -3 -1010 3 9 3 62 12 21 2 62 11 2 52 1
Output10091169240
5 seconds
256 megabytes
['data structures', 'dfs and similar', '*3000']
F2. Long Colorful Striptime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the second subtask of problem F. The only differences between this and the first subtask are the constraints on the value of m and the time limit. It is sufficient to solve this subtask in order to hack it, but you need to solve both subtasks in order to hack the first one.There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0. Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 \leq a_i < b_i \leq m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i. Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i \neq 0). Every colour other than 0 is visible on the strip.Count the number of different pairs of sequences \{a_i\}_{i=1}^n, \{b_i\}_{i=1}^n that result in this configuration. Since this number may be large, output it modulo 998244353.InputThe first line contains a two integers n, m (1 \leq n \leq 500, n \leq m \leq 10^6) — the number of colours excluding the colour 0 and the length of the paper, respectively.The second line contains m space separated integers c_1, c_2, \ldots, c_m (1 \leq c_i \leq n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.OutputOutput a single integer — the number of ways Alice can perform the painting, modulo 998244353.ExamplesInput 3 3 1 2 3 Output 5 Input 2 3 1 2 1 Output 1 Input 2 3 2 1 2 Output 0 Input 7 7 4 5 1 6 2 3 7 Output 165 Input 8 17 1 3 2 2 7 8 2 5 5 4 4 4 1 1 6 1 1 Output 20 NoteIn the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.In the second example, Alice must first paint segment 0 3 with colour 1 and then segment 1 2 with colour 2.
3 3 1 2 3
5
6 seconds
256 megabytes
['dp', '*2600']
F1. Short Colorful Striptime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0. Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 \leq a_i < b_i \leq m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i. Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i \neq 0). Every colour other than 0 is visible on the strip.Count the number of different pairs of sequences \{a_i\}_{i=1}^n, \{b_i\}_{i=1}^n that result in this configuration. Since this number may be large, output it modulo 998244353.InputThe first line contains a two integers n, m (1 \leq n \leq 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.The second line contains m space separated integers c_1, c_2, \ldots, c_m (1 \leq c_i \leq n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.OutputOutput a single integer — the number of ways Alice can perform the painting, modulo 998244353.ExamplesInput 3 3 1 2 3 Output 5 Input 7 7 4 5 1 6 2 3 7 Output 165 NoteIn the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
3 3 1 2 3
5
3 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'dp', '*2200']
E. Archaeologytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters.InputThe input consists of a single string s (2 \leq |s| \leq 10^6). The string s consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.OutputOutput a palindrome t that is a subsequence of s and |t| \geq \lfloor \frac{|s|}{2} \rfloor.If there are multiple solutions, you may print any of them. You don't have to maximise the length of t.If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).ExamplesInput cacbac Output aba Input abc Output a Input cbacacacbcbababacbcb Output cbaaacbcaaabcNoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
cacbac
aba
1 second
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'strings', '*1900']
D. Prime Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!When building the graph, he needs four conditions to be satisfied: It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. The number of vertices must be exactly n — a number he selected. This number is not necessarily prime. The total number of edges must be prime. The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. Note that the graph can be disconnected.Please help Bob to find any such graph!InputThe input consists of a single integer n (3 \leq n \leq 1\,000) — the number of vertices.OutputIf there is no graph satisfying the conditions, print a single line containing the integer -1.Otherwise, first print a line containing a prime number m (2 \leq m \leq \frac{n(n-1)}{2}) — the number of edges in the graph. Then, print m lines, the i-th of which containing two integers u_i, v_i (1 \leq u_i, v_i \leq n) — meaning that there is an edge between vertices u_i and v_i. The degree of each vertex must be prime. There must be no multiple (parallel) edges or self-loops.If there are multiple solutions, you may print any of them.Note that the graph can be disconnected.ExamplesInput 4 Output 5 1 2 1 3 2 3 2 4 3 4Input 8 Output 13 1 2 1 3 2 3 1 4 2 4 1 5 2 5 1 6 2 6 1 7 1 8 5 8 7 8 NoteThe first example was described in the statement.In the second example, the degrees of vertices are [7, 5, 2, 2, 3, 2, 2, 3]. Each of these numbers is prime. Additionally, the number of edges, 13, is also a prime number, hence both conditions are satisfied.
4
5 1 2 1 3 2 3 2 4 3 4
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', 'number theory', '*1500']
C. Tilestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor — a square tile that is diagonally split into white and black part as depicted in the figure below. The dimension of this tile is perfect for this kitchen, as he will need exactly w \times h tiles without any scraps. That is, the width of the kitchen is w tiles, and the height is h tiles. As each tile can be rotated in one of four ways, he still needs to decide on how exactly he will tile the floor. There is a single aesthetic criterion that he wants to fulfil: two adjacent tiles must not share a colour on the edge — i.e. one of the tiles must have a white colour on the shared border, and the second one must be black. The picture on the left shows one valid tiling of a 3 \times 2 kitchen. The picture on the right shows an invalid arrangement, as the bottom two tiles touch with their white parts. Find the number of possible tilings. As this number may be large, output its remainder when divided by 998244353 (a prime number). InputThe only line contains two space separated integers w, h (1 \leq w,h \leq 1\,000) — the width and height of the kitchen, measured in tiles.OutputOutput a single integer n — the remainder of the number of tilings when divided by 998244353.ExamplesInput 2 2 Output 16 Input 2 4 Output 64
2 2
16
1 second
256 megabytes
['combinatorics', 'greedy', 'math', '*1300']
B. WOW Factortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly zero or all) characters. For example, for the string a="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string s, compute and output its wow factor. Note that it is not guaranteed that it is possible to get s from another string replacing "w" with "vv". For example, s can be equal to "vov".InputThe input contains a single non-empty string s, consisting only of characters "v" and "o". The length of s is at most 10^6.OutputOutput a single integer, the wow factor of s.ExamplesInput vvvovvv Output 4 Input vvovooovovvovoovoovvvvovovvvov Output 100 NoteThe first example is explained in the legend.
vvvovvv
4
1 second
256 megabytes
['dp', 'strings', '*1300']
A. Prime Ministertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice is the leader of the State Refactoring Party, and she is about to become the prime minister. The elections have just taken place. There are n parties, numbered from 1 to n. The i-th party has received a_i seats in the parliament.Alice's party has number 1. In order to become the prime minister, she needs to build a coalition, consisting of her party and possibly some other parties. There are two conditions she needs to fulfil: The total number of seats of all parties in the coalition must be a strict majority of all the seats, i.e. it must have strictly more than half of the seats. For example, if the parliament has 200 (or 201) seats, then the majority is 101 or more seats. Alice's party must have at least 2 times more seats than any other party in the coalition. For example, to invite a party with 50 seats, Alice's party must have at least 100 seats. For example, if n=4 and a=[51, 25, 99, 25] (note that Alice'a party has 51 seats), then the following set [a_1=51, a_2=25, a_4=25] can create a coalition since both conditions will be satisfied. However, the following sets will not create a coalition: [a_2=25, a_3=99, a_4=25] since Alice's party is not there; [a_1=51, a_2=25] since coalition should have a strict majority; [a_1=51, a_2=25, a_3=99] since Alice's party should have at least 2 times more seats than any other party in the coalition. Alice does not have to minimise the number of parties in a coalition. If she wants, she can invite as many parties as she wants (as long as the conditions are satisfied). If Alice's party has enough people to create a coalition on her own, she can invite no parties.Note that Alice can either invite a party as a whole or not at all. It is not possible to invite only some of the deputies (seats) from another party. In other words, if Alice invites a party, she invites all its deputies.Find and print any suitable coalition.InputThe first line contains a single integer n (2 \leq n \leq 100) — the number of parties.The second line contains n space separated integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 100) — the number of seats the i-th party has.OutputIf no coalition satisfying both conditions is possible, output a single line with an integer 0.Otherwise, suppose there are k (1 \leq k \leq n) parties in the coalition (Alice does not have to minimise the number of parties in a coalition), and their indices are c_1, c_2, \dots, c_k (1 \leq c_i \leq n). Output two lines, first containing the integer k, and the second the space-separated indices c_1, c_2, \dots, c_k. You may print the parties in any order. Alice's party (number 1) must be on that list. If there are multiple solutions, you may print any of them.ExamplesInput 3 100 50 50 Output 2 1 2 Input 3 80 60 60 Output 0 Input 2 6 5 Output 1 1 Input 4 51 25 99 25 Output 3 1 2 4 NoteIn the first example, Alice picks the second party. Note that she can also pick the third party or both of them. However, she cannot become prime minister without any of them, because 100 is not a strict majority out of 200.In the second example, there is no way of building a majority, as both other parties are too large to become a coalition partner.In the third example, Alice already has the majority. The fourth example is described in the problem statement.
3 100 50 50
2 1 2
1 second
256 megabytes
['greedy', '*800']