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
C. Hyperspace Highwaystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn an unspecified solar system, there are N planets. A space government company has recently hired space contractors to build M bidirectional Hyperspace™ highways, each connecting two different planets. The primary objective, which was to make sure that every planet can be reached from any other planet taking only Hyperspace™ highways, has been completely fulfilled. Unfortunately, lots of space contractors had friends and cousins in the Space Board of Directors of the company, so the company decided to do much more than just connecting all planets. In order to make spending enormous amounts of space money for Hyperspace™ highways look neccessary, they decided to enforce a strict rule on the Hyperspace™ highway network: whenever there is a way to travel through some planets and return to the starting point without travelling through any planet twice, every pair of planets on the itinerary should be directly connected by a Hyperspace™ highway. In other words, the set of planets in every simple cycle induces a complete subgraph.You are designing a Hyperspace™ navigational app, and the key technical problem you are facing is finding the minimal number of Hyperspace™ highways one needs to use to travel from planet A to planet B. As this problem is too easy for Bubble Cup, here is a harder task: your program needs to do it for Q pairs of planets.InputThe first line contains three positive integers N (1\leq N\leq 100\,000), M (1\leq M\leq 500\,000) and Q (1\leq Q\leq 200\,000), denoting the number of planets, the number of Hyperspace™ highways, and the number of queries, respectively.Each of the following M lines contains a highway: highway i is given by two integers u_i and v_i (1 \leq u_i < v_i \leq N), meaning the planets u_i and v_i are connected by a Hyperspace™ highway. It is guaranteed that the network of planets and Hyperspace™ highways forms a simple connected graph.Each of the following Q lines contains a query: query j is given by two integers a_j and b_j (1 \leq a_j < b_j \leq N ), meaning we are interested in the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j.OutputOutput Q lines: the j-th line of output should contain the minimal number of Hyperspace™ highways one needs to take to travel from planet a_j to planet b_j.ExamplesInput5 7 21 21 31 42 32 43 41 51 42 5Output12Input8 11 41 22 33 44 51 31 63 53 74 75 76 81 52 46 73 8Output2233NoteThe graph from the second sample:
Input5 7 21 21 31 42 32 43 41 51 42 5
Output12
1 second
256 megabytes
['dfs and similar', 'graphs', 'trees', '*2300']
B. Space Isaactime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a number from the second bag, and then sums them modulo M.What are the residues modulo M that Ajs cannot obtain with this action?InputThe first line contains two positive integer N (1 \leq N \leq 200\,000) and M (N+1 \leq M \leq 10^{9}), denoting the number of the elements in the first bag and the modulus, respectively.The second line contains N nonnegative integers a_1,a_2,\ldots,a_N (0 \leq a_1<a_2< \ldots< a_N<M), the contents of the first bag. OutputIn the first line, output the cardinality K of the set of residues modulo M which Ajs cannot obtain.In the second line of the output, print K space-separated integers greater or equal than zero and less than M, which represent the residues Ajs cannot obtain. The outputs should be sorted in increasing order of magnitude. If K=0, do not output the second line.ExamplesInput2 53 4Output12Input4 10000000005 25 125 625Output0Input2 41 3Output20 2NoteIn the first sample, the first bag and the second bag contain \{3,4\} and \{0,1,2\}, respectively. Ajs can obtain every residue modulo 5 except the residue 2: 4+1 \equiv 0, \, 4+2 \equiv 1, \, 3+0 \equiv 3, \, 3+1 \equiv 4 modulo 5. One can check that there is no choice of elements from the first and the second bag which sum to 2 modulo 5.In the second sample, the contents of the first bag are \{5,25,125,625\}, while the second bag contains all other nonnegative integers with at most 9 decimal digits. Every residue modulo 1\,000\,000\,000 can be obtained as a sum of an element in the first bag and an element in the second bag.
Input2 53 4
Output12
1.5 seconds
256 megabytes
['hashing', 'number theory', '*2400']
A. Last chancetime limit per test2 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputIt is the year 2969. 1000 years have passed from the moon landing. Meanwhile, the humanity colonized the Hyperspace™ and lived in harmony.Until we realized that we were not alone.Not too far away from the Earth, the massive fleet of aliens' spaceships is preparing to attack the Earth. For the first time in a while, the humanity is in real danger. Crisis and panic are everywhere. The scientists from all around the solar system have met and discussed the possible solutions. However, no progress has been made.The Earth's last hope is YOU!Fortunately, the Earth is equipped with very powerful defense systems made by MDCS. There are N aliens' spaceships which form the line. The defense system consists of three types of weapons: SQL rockets – every SQL rocket can destroy at most one spaceship in the given set. Cognition beams – every Cognition beam has an interval [l,r] and can destroy at most one spaceship in that interval. OMG bazooka – every OMG bazooka has three possible targets, however, each bazooka can destroy either zero or exactly two spaceships. In addition, due to the smart targeting system, the sets of the three possible targets of any two different OMG bazookas are disjoint (that means that every ship is targeted with at most one OMG bazooka). Your task is to make a plan of the attack which will destroy the largest possible number of spaceships. Every destroyed spaceship should be destroyed with exactly one weapon.InputThe first line contains two integers: the number of your weapons N (1\leq N\leq 5000) and the number of spaceships M (1\leq M\leq 5000).In the next N lines, each line starts with one integer that represents type (either 0, 1 or 2). If the type is 0, then the weapon is SQL rocket, the rest of the line contains strictly positive number K (\sum{K} \leq 100 000) and array k_i (1\leq k_i\leq M) of K integers. If the type is 1, then the weapon is Cognition beam, the rest of the line contains integers l and r (1\leq l\leq r\leq M). If the type is 2 then the weapon is OMG bazooka, the rest of the line contains distinct numbers a, b and c (1 \leq a,b,c \leq M).OutputThe first line should contain the maximum number of destroyed spaceships — X.In the next X lines, every line should contain two numbers A and B, where A is an index of the weapon and B is an index of the spaceship which was destroyed by the weapon A.ExampleInput3 50 1 42 5 4 11 1 4Output42 13 21 42 5NoteSQL rocket can destroy only 4th spaceship. OMG Bazooka can destroy two of 1st, 4th or 5th spaceship, and Cognition beam can destroy any spaceship from the interval [1,4]. The maximum number of destroyed spaceship is 4, and one possible plan is that SQL rocket should destroy 4th spaceship, OMG bazooka should destroy 1st and 5th spaceship and Cognition beam should destroy 2nd spaceship.
Input3 50 1 42 5 4 11 1 4
Output42 13 21 42 5
2 seconds
128 megabytes
['data structures', 'flows', 'graph matchings', 'graphs', 'trees', '*2500']
F. DFStime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet T be a tree on n vertices. Consider a graph G_0, initially equal to T. You are given a sequence of q updates, where the i-th update is given as a pair of two distinct integers u_i and v_i. For every i from 1 to q, we define the graph G_i as follows: If G_{i-1} contains an edge \{u_i, v_i\}, then remove this edge to form G_i. Otherwise, add this edge to G_{i-1} to form G_i. Formally, G_i := G_{i-1} \triangle \{\{u_i, v_i\}\} where \triangle denotes the set symmetric difference. Furthermore, it is guaranteed that T is always a subgraph of G_i. In other words, an update never removes an edge of T.Consider a connected graph H and run a depth-first search on it. One can see that the tree edges (i.e. the edges leading to a not yet visited vertex at the time of traversal) form a spanning tree of the graph H. This spanning tree is not generally fixed for a particular graph — it depends on the starting vertex, and on the order in which the neighbors of each vertex are traversed. We call vertex w good if one can order the neighbors of each vertex in such a way that the depth-first search started from w produces T as the spanning tree. For every i from 1 to q, find and report the number of good vertices.InputThe first line contains two integers n and q (3 \le n \le 2\cdot 10^5, 1 \le q \le 2 \cdot 10^5) — the number of nodes and the number of updates, respectively.Each of the next n-1 lines contains two integers u and v (1 \le u, v \le n, u \ne v) — vertices connected by an edge in T. It is guaranteed that this graph is a tree.Each of the next q lines contains two integers u and v (1 \le u, v \le n, u \ne v) — the endpoints of the edge that is added or removed. It is guaranteed that this edge does not belong to T.OutputFor each update, print one integer k — the number of good vertices w after the corresponding update.ExamplesInput3 21 21 32 33 2Output23Input6 61 22 31 44 51 62 53 45 26 43 46 5Output323232NoteThe first sample is depicted in the following figure. After the first update, G contains all three possible edges. The result of a DFS is as follows: Let the starting vertex be 1. We have two choices of ordering the neighbors of 1, either [2, 3] or [3, 2]. If we choose the former, then we reach vertex 2. Regardless of the ordering of its neighbors, the next visited vertex will be 3. Thus, the spanning tree generated by this DFS will contain edges \{1, 2\} and \{2, 3\}, which does not equal to T. If we choose the latter, we obtain a spanning tree with edges \{1, 3\} and \{2, 3\}. Hence, there is no way of ordering the neighbors of vertices such that the DFS produces T, and subsequently 1 is not a good vertex. Let the starting vertex be 2. We have two choices of traversing its neighbors. If we visit 3 first, then the spanning tree will consist of edges \{2,3\} and \{1,3\}, which is not equal to T. If we, however, visit 1 first, then we can only continue to 3 from here, and the spanning tree will consist of edges \{1, 2\} and \{1,3\}, which equals to T. Hence, 2 is a good vertex. The case when we start in the vertex 3 is symmetrical to starting in 2, and hence 3 is a good vertex. Therefore, the answer is 2.After the second update, the edge between 2 and 3 is removed, and G = T. It follows that the spanning tree generated by DFS will be always equal to T independent of the choice of the starting vertex. Thus, the answer is 3.In the second sample, the set of good vertices after the corresponding query is: \{2, 3, 5\} \{3, 5\} \{3, 4, 5\} \{4, 5\} \{4, 5, 6\} \{5, 6\}
Input3 21 21 32 33 2
Output23
6 seconds
512 megabytes
['data structures', '*2700']
E. Grid Sorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an n \times m grid. Each grid cell is filled with a unique integer from 1 to nm so that each integer appears exactly once.In one operation, you can choose an arbitrary cycle of the grid and move all integers along that cycle one space over. Here, a cycle is any sequence that satisfies the following conditions: There are at least four squares. Each square appears at most once. Every pair of adjacent squares, and also the first and last squares, share an edge. For example, if we had the following grid: We can choose an arbitrary cycle like this one: To get the following grid: In this particular case, the chosen cycle can be represented as the sequence [1, 2, 3, 6, 5, 8, 7, 4], the numbers are in the direction that we want to rotate them in.Find any sequence of operations to sort the grid so that the array created by concatenating the rows from the highest to the lowest is sorted (look at the first picture above).Note you do not need to minimize number of operations or sum of cycle lengths. The only constraint is that the sum of all cycles lengths must not be greater than 10^5. We can show that an answer always exists under the given constraints. Output any valid sequence of moves that will sort the grid.InputThe first line contains two integers n and m (3 \leq n,m \leq 20) — the dimensions of the grid.Each of the next n lines contains m integers x_{i,1}, x_{i,2}, \ldots, x_{i, m} (1 \leq x_{i,j} \leq nm), denoting the values of the block in row i and column j. It is guaranteed that all x_{i,j} are distinct.OutputFirst, print a single integer k, the number of operations (k \geq 0).On each of the next k lines, print a cycle as follows:s\ y_1\ y_2\ \ldots\ y_sHere, s is the number of blocks to move (s \geq 4). Here we have block y_1 moving to where block y_2 is, block y_2 moving to where block y_3 is, and so on with block y_s moving to where block y_1 is.The sum of s over all operations must be at most 10^5.ExamplesInput3 34 1 27 6 38 5 9Output18 1 4 7 8 5 6 3 2Input3 51 2 3 5 1011 6 4 14 912 7 8 13 15Output34 4 14 13 84 5 10 9 44 12 7 6 11NoteThe first sample is the case in the statement. Here, we can use the cycle in reverse order to sort the grid.
Input3 34 1 27 6 38 5 9
Output18 1 4 7 8 5 6 3 2
2 seconds
256 megabytes
['implementation', '*3100']
D. Deduction Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an array a of 2^{30} integers, indexed from 0 to 2^{30}-1. Initially, you know that 0 \leq a_i < 2^{30} (0 \leq i < 2^{30}), but you do not know any of the values. Your task is to process queries of two types: 1 l r x: You are informed that the bitwise xor of the subarray [l, r] (ends inclusive) is equal to x. That is, a_l \oplus a_{l+1} \oplus \ldots \oplus a_{r-1} \oplus a_r = x, where \oplus is the bitwise xor operator. In some cases, the received update contradicts past updates. In this case, you should ignore the contradicting update (the current update). 2 l r: You are asked to output the bitwise xor of the subarray [l, r] (ends inclusive). If it is still impossible to know this value, considering all past updates, then output -1.Note that the queries are encoded. That is, you need to write an online solution.InputThe first line contains a single integer q (1 \leq q \leq 2 \cdot 10^5) — the number of queries.Each of the next q lines describes a query. It contains one integer t (1 \leq t \leq 2) — the type of query.The given queries will be encoded in the following way: let last be the answer to the last query of the second type that you have answered (initially, last = 0). If the last answer was -1, set last = 1. If t = 1, three integers follow, l', r', and x' (0 \leq l', r', x' < 2^{30}), meaning that you got an update. First, do the following: l = l' \oplus last, r = r' \oplus last, x = x' \oplus last and, if l > r, swap l and r.This means you got an update that the bitwise xor of the subarray [l, r] is equal to x (notice that you need to ignore updates that contradict previous updates). If t = 2, two integers follow, l' and r' (0 \leq l', r' < 2^{30}), meaning that you got a query. First, do the following: l = l' \oplus last, r = r' \oplus last and, if l > r, swap l and r.For the given query, you need to print the bitwise xor of the subarray [l, r]. If it is impossible to know, print -1. Don't forget to change the value of last.It is guaranteed there will be at least one query of the second type.OutputAfter every query of the second type, output the bitwise xor of the given subarray or -1 if it is still impossible to know.ExamplesInput122 1 22 1 10737418221 0 3 42 0 02 3 32 0 31 6 7 32 4 41 0 2 12 0 02 4 42 0 0Output-1-1-1-15-1635Input41 5 5 91 6 6 51 6 5 102 6 5Output12NoteIn the first example, the real queries (without being encoded) are: 12 2 1 2 2 0 1073741823 1 1 2 5 2 1 1 2 2 2 2 1 2 1 2 3 6 2 1 1 1 1 3 0 2 1 1 2 2 2 2 3 3 The answers for the first two queries are -1 because we don't have any such information on the array initially. The first update tells us a_1 \oplus a_2 = 5. Note that we still can't be certain about the values a_1 or a_2 independently (for example, it could be that a_1 = 1, a_2 = 4, and also a_1 = 3, a_2 = 6). After we receive all three updates, we have enough information to deduce a_1, a_2, a_3 independently. In the second example, notice that after the first two updates we already know that a_5 \oplus a_6 = 12, so the third update is contradicting, and we ignore it.
Input122 1 22 1 10737418221 0 3 42 0 02 3 32 0 31 6 7 32 4 41 0 2 12 0 02 4 42 0 0
Output-1-1-1-15-1635
2 seconds
256 megabytes
['data structures', 'dsu', '*2400']
C. Optimal Polygon Perimetertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.We define the distance between two points p_1 = (x_1, y_1) and p_2 = (x_2, y_2) as their Manhattan distance: d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as p_1, p_2, \ldots, p_k (k \geq 3), then the perimeter of the polygon is d(p_1, p_2) + d(p_2, p_3) + \ldots + d(p_k, p_1).For some parameter k, let's consider all the polygons that can be formed from the given set of points, having any k vertices, such that the polygon is not self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define f(k) to be the maximal perimeter.Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: In the middle polygon, the order of points (p_1, p_3, p_2, p_4) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is (p_1, p_2, p_3, p_4), which is the left polygon.Your task is to compute f(3), f(4), \ldots, f(n). In other words, find the maximum possible perimeter for each possible number of points (i.e. 3 to n).InputThe first line contains a single integer n (3 \leq n \leq 3\cdot 10^5) — the number of points. Each of the next n lines contains two integers x_i and y_i (-10^8 \leq x_i, y_i \leq 10^8) — the coordinates of point p_i.The set of points is guaranteed to be convex, all points are distinct, the points are ordered in clockwise order, and there will be no three collinear points.OutputFor each i (3\leq i\leq n), output f(i).ExamplesInput42 44 33 01 3Output12 14 Input30 00 22 0Output8 NoteIn the first example, for f(3), we consider four possible polygons: (p_1, p_2, p_3), with perimeter 12. (p_1, p_2, p_4), with perimeter 8. (p_1, p_3, p_4), with perimeter 12. (p_2, p_3, p_4), with perimeter 12. For f(4), there is only one option, taking all the given points. Its perimeter 14.In the second example, there is only one possible polygon. Its perimeter is 8.
Input42 44 33 01 3
Output12 14
2 seconds
256 megabytes
['dp', 'geometry', '*2100']
B. Intersecting Subtreestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree.You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled x_1, x_2, \ldots, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, \ldots, y_{k_2} in his labeling. The values of x_1, x_2, \ldots, x_{k_1} and y_1, y_2, \ldots, y_{k_2} are known to both of you. The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes. You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most 5 questions, each of which is in one of the following two forms: A x: Andrew will look at vertex x in your labeling and tell you the number of this vertex in Li Chen's labeling. B y: Andrew will look at vertex y in Li Chen's labeling and tell you the number of this vertex in your labeling. Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.InteractionEach test consists of several test cases.The first line of input contains a single integer t (1 \leq t \leq 100) — the number of test cases.For each testcase, your program should interact in the following format.The first line contains a single integer n (1 \leq n \leq 1\,000) — the number of nodes in the tree.Each of the next n-1 lines contains two integers a_i and b_i (1\leq a_i, b_i\leq n) — the edges of the tree, indicating an edge between node a_i and b_i according to your labeling of the nodes.The next line contains a single integer k_1 (1 \leq k_1 \leq n) — the number of nodes in your subtree.The next line contains k_1 distinct integers x_1,x_2,\ldots,x_{k_1} (1 \leq x_i \leq n) — the indices of the nodes in your subtree, according to your labeling. It is guaranteed that these vertices form a subtree.The next line contains a single integer k_2 (1 \leq k_2 \leq n) — the number of nodes in Li Chen's subtree.The next line contains k_2 distinct integers y_1, y_2, \ldots, y_{k_2} (1 \leq y_i \leq n) — the indices (according to Li Chen's labeling) of the nodes in Li Chen's subtree. It is guaranteed that these vertices form a subtree according to Li Chen's labelling of the tree's nodes.Test cases will be provided one by one, so you must complete interacting with the previous test (i.e. by printing out a common node or -1 if there is not such node) to start receiving the next one.You can ask the Andrew two different types of questions. You can print "A x" (1 \leq x \leq n). Andrew will look at vertex x in your labeling and respond to you with the number of this vertex in Li Chen's labeling. You can print "B y" (1 \leq y \leq n). Andrew will look at vertex y in Li Chen's labeling and respond to you with the number of this vertex in your labeling. You may only ask at most 5 questions per tree.When you are ready to answer, print "C s", where s is your label of a vertex that is common to both subtrees, or -1, if no such vertex exists. Printing the answer does not count as a question. Remember to flush your answer to start receiving the next test case. After printing a question do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If the judge responds with -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.Hack FormatTo hack, use the following format. Note that you can only hack with one test case.The first line should contain a single integer t (t=1).The second line should contain a single integer n (1 \leq n \leq 1\,000).The third line should contain n integers p_1, p_2, \ldots, p_n (1\leq p_i\leq n) — a permutation of 1 to n. This encodes the labels that Li Chen chose for his tree. In particular, Li Chen chose label p_i for the node you labeled i.Each of the next n-1 lines should contain two integers a_i and b_i (1\leq a_i, b_i\leq n). These edges should form a tree.The next line should contain a single integer k_1 (1 \leq k_1 \leq n).The next line should contain k_1 distinct integers x_1,x_2,\ldots,x_{k_1} (1 \leq x_i \leq n). These vertices should form a subtree.The next line should contain a single integer k_2 (1 \leq k_2 \leq n).The next line should contain k_2 distinct integers y_1, y_2, \ldots, y_{k_2} (1 \leq y_i \leq n). These vertices should form a subtree in Li Chen's tree according to the permutation above.ExamplesInput131 22 3111221OutputA 1B 2C 1Input261 21 31 44 54 641 3 4 533 5 2361 21 31 44 54 631 2 334 1 65OutputB 2C 1A 1C -1NoteFor the first sample, Li Chen's hidden permutation is [2, 3, 1], and for the second, his hidden permutation is [5, 3, 2, 4, 1, 6] for both cases.In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose: In the first question, you ask Andrew to look at node 1 in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with 2. At this point, you know that both of your subtrees contain the same node (i.e. node 1 according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node 2 in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with 1 (this step was given with the only reason — to show you how to ask questions).For the second sample, there are two test cases. The first looks is the one from the statement: We first ask "B 2", and Andrew will tell us 3. In this case, we know 3 is a common vertex, and moreover, any subtree with size 3 that contains node 3 must contain node 1 as well, so we can output either "C 1" or "C 3" as our answer.In the second case in the second sample, the situation looks as follows: In this case, you know that the only subtree of size 3 that doesn't contain node 1 is subtree 4,5,6. You ask Andrew for the label of node 1 in Li Chen's labelling and Andrew says 5. In this case, you know that Li Chen's subtree doesn't contain node 1, so his subtree must be consist of the nodes 4,5,6 (in your labelling), thus the two subtrees have no common nodes.
Input131 22 3111221
OutputA 1B 2C 1
2 seconds
256 megabytes
['dfs and similar', 'interactive', 'trees', '*1900']
A. The Tower is Going Hometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number.Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates (1,1). But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the upper side of the field (that is, in any cell that is in the row with number 10^9).Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells: Vertical. Each of these is defined by one number x. Such spells create an infinite blocking line between the columns x and x+1. Horizontal. Each of these is defined by three numbers x_1, x_2, y. Such spells create a blocking segment that passes through the top side of the cells, which are in the row y and in columns from x_1 to x_2 inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells. An example of a chessboard. Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell (r_0,c_0) into the cell (r_1,c_1) only under the condition that r_1 = r_0 or c_1 = c_0 and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!InputThe first line contains two integers n and m (0 \le n,m \le 10^5) — the number of vertical and horizontal spells.Each of the following n lines contains one integer x (1 \le x < 10^9) — the description of the vertical spell. It will create a blocking line between the columns of x and x+1.Each of the following m lines contains three integers x_1, x_2 and y (1 \le x_{1} \le x_{2} \le 10^9, 1 \le y < 10^9) — the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number y, in columns from x_1 to x_2 inclusive.It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.OutputIn a single line print one integer — the minimum number of spells the rook needs to remove so it can get from the cell (1,1) to at least one cell in the row with the number 10^9ExamplesInput2 3681 5 61 9 42 4 2Output1Input1 341 5 31 9 44 6 6Output1Input0 21 1000000000 41 1000000000 2Output2Input0 0Output0Input2 3461 4 31 5 21 6 5Output2NoteIn the first sample, in order for the rook return home, it is enough to remove the second horizontal spell. Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home. In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell. Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home. In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them. Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home. In the fourth sample, we have no spells, which means that we do not need to remove anything.In the fifth example, we can remove the first vertical and third horizontal spells. Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.
Input2 3681 5 61 9 42 4 2
Output1
1 second
256 megabytes
['binary search', 'two pointers', '*1700']
G. Speckled Bandtime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIldar took a band (a thin strip of cloth) and colored it. Formally, the band has n cells, each of them is colored into one of 26 colors, so we can denote each color with one of the lowercase letters of English alphabet. Ildar decided to take some segment of the band [l, r] (1 \le l \le r \le n) he likes and cut it from the band. So he will create a new band that can be represented as a string t = s_l s_{l+1} \ldots s_r.After that Ildar will play the following game: he cuts the band t into some new bands and counts the number of different bands among them. Formally, Ildar chooses 1 \le k \le |t| indexes 1 \le i_1 < i_2 < \ldots < i_k = |t| and cuts t to k bands-strings t_1 t_2 \ldots t_{i_1}, t_{i_1 + 1} \ldots t_{i_2}, \ldots, {t_{i_{k-1} + 1}} \ldots t_{i_k} and counts the number of different bands among them. He wants to know the minimal possible number of different bands he can get under the constraint that at least one band repeats at least two times. The result of the game is this number. If it is impossible to cut t in such a way, the result of the game is -1.Unfortunately Ildar hasn't yet decided which segment he likes, but he has q segments-candidates [l_1, r_1], [l_2, r_2], ..., [l_q, r_q]. Your task is to calculate the result of the game for each of them.InputThe first line contains one integer n (1 \le n \le 200\,000) — the length of the band Ildar has.The second line contains a string s consisting of n lowercase English letters — the band Ildar has.The third line contains a single integer q (1 \le q \le 200\,000) — the number of segments Ildar has chosen as candidates.Each of the next q lines contains two integer integers l_i and r_i (1 \le l_i \le r_i \le n) denoting the ends of the i-th segment.OutputOutput q lines, where the i-th of them should contain the result of the game on the segment [l_i, r_i].ExampleInput9abcabcdce71 64 75 96 91 93 64 4Output1-14322-1NoteConsider the first example.If Ildar chooses the segment [1, 6], he cuts a string t = abcabc. If he cuts t into two bands abc and abc, the band abc repeats two times and the number of different tapes is 1. So, the result of this game is 1.If Ildar chooses the segment [4, 7], he cuts a string t = abcd. It is impossible to cut this band in such a way that there is at least one band repeating at least two times. So, the result of this game is -1.If Ildar chooses the segment [3, 6], he cuts a string t = cabc. If he cuts t into three bands c, ab and c, the band c repeats two times and the number of different bands is 2. So, the result of this game is 2.
Input9abcabcdce71 64 75 96 91 93 64 4
Output1-14322-1
7 seconds
512 megabytes
['data structures', 'divide and conquer', 'hashing', 'string suffix structures', 'strings', '*3500']
F. Make It Onetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJanusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of n integers a_i.It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score 1. Now Janusz wonders, for given sequence, how much elements should the player choose?InputThe first line contains an only integer n (1 \le n \le 300\,000) — the number of integers in the sequence.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 300\,000).OutputIf there is no subset of the given sequence with gcd equal to 1, output -1.Otherwise, output exactly one integer — the size of the smallest subset with gcd equal to 1.ExamplesInput310 6 15Output3Input32 4 6Output-1Input730 60 21 42 70 15 30Output3NoteIn the first example, selecting a subset of all numbers gives a gcd of 1 and for all smaller subsets the gcd is greater than 1.In the second example, for all subsets of numbers the gcd is at least 2.
Input310 6 15
Output3
3 seconds
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'math', 'number theory', 'shortest paths', '*2500']
E. Train Hard, Win Easytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZibi is a competitive programming coach. There are n competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems.Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the less the score is, the better).We know that the i-th competitor will always have score x_i when he codes the first task and y_i when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest.Zibi wants all competitors to write a contest with each other. However, there are m pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?InputThe first line contains two integers n and m (2 \le n \le 300\,000, 0 \le m \le 300\,000) — the number of participants and the number of pairs of people who will not write a contest together.Each of the next n lines contains two integers x_i and y_i (-10^9 \le x_i, y_i \le 10^9) — the scores which will the i-th competitor get on the first problem and on the second problem. It is guaranteed that there are no two people having both x_i and y_i same.Each of the next m lines contain two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \ne v_i) — indices of people who don't want to write a contest in one team. Each unordered pair of indices will appear at most once.OutputOutput n integers — the sum of scores for all participants in the same order as they appear in the input.ExamplesInput3 21 22 31 31 22 3Output3 0 3 Input3 31 22 31 31 22 31 3Output0 0 0 Input5 3-1 32 41 13 52 21 42 33 5Output4 14 4 16 10 NoteIn the first example, there will be only one team consisting of persons 1 and 3. The optimal strategy for them is to assign the first task to the 3-rd person and the second task to the 1-st person, this will lead to score equal to 1 + 2 = 3.In the second example, nobody likes anyone, so there won't be any trainings. It seems that Zibi won't be titled coach in that case...
Input3 21 22 31 31 22 3
Output3 0 3
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', 'sortings', '*1900']
D. Mysterious Crimetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAcingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked m neighbours of Ada about clients who have visited her in that unlucky day. Let's number the clients from 1 to n. Each neighbour's testimony is a permutation of these numbers, which describes the order in which clients have been seen by the asked neighbour.However, some facts are very suspicious – how it is that, according to some of given permutations, some client has been seen in the morning, while in others he has been seen in the evening? "In the morning some of neighbours must have been sleeping!" — thinks Gawry — "and in the evening there's been too dark to see somebody's face...". Now he wants to delete some prefix and some suffix (both prefix and suffix can be empty) in each permutation, so that they'll be non-empty and equal to each other after that — some of the potential criminals may disappear, but the testimony won't stand in contradiction to each other.In how many ways he can do it? Two ways are called different if the remaining common part is different.InputThe first line contains two integers n and m (1 \le n \le 100\,000, 1 \le m \le 10) — the number of suspects and the number of asked neighbors.Each of the next m lines contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n). It is guaranteed that these integers form a correct permutation (that is, each number from 1 to n appears exactly once).OutputOutput a single integer denoting the number of ways to delete some prefix and some suffix of each permutation (possibly empty), such that the remaining parts will be equal and non-empty.ExamplesInput3 21 2 32 3 1Output4Input5 61 2 3 4 52 3 1 4 53 4 5 1 23 5 4 2 12 3 5 4 11 2 3 4 5Output5Input2 21 22 1Output2NoteIn the first example, all possible common parts are [1], [2], [3] and [2, 3].In the second and third examples, you can only leave common parts of length 1.
Input3 21 2 32 3 1
Output4
1 second
256 megabytes
['brute force', 'combinatorics', 'math', 'meet-in-the-middle', 'two pointers', '*1700']
C. Smallest Wordtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting.Today, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. "It would look much better when I'll swap some of them!" — thought the girl — "but how to do it?". After a while, she got an idea. IA will look at all prefixes with lengths from 1 to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing?A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.InputThe first and the only line contains a string s (1 \le |s| \le 1000), describing the initial string formed by magnets. The string s consists only of characters 'a' and 'b'.OutputOutput exactly |s| integers. If IA should reverse the i-th prefix (that is, the substring from 1 to i), the i-th integer should be equal to 1, and it should be equal to 0 otherwise.If there are multiple possible sequences leading to the optimal answer, print any of them.ExamplesInputbbabOutput0 1 1 0InputaaaaaOutput1 0 0 0 1NoteIn the first example, IA can reverse the second and the third prefix and get a string "abbb". She cannot get better result, since it is also lexicographically smallest string obtainable by permuting characters of the initial string.In the second example, she can reverse any subset of prefixes — all letters are 'a'.
Inputbbab
Output0 1 1 0
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1500']
B. Lost Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBajtek, known for his unusual gifts, recently got an integer array x_0, x_1, \ldots, x_{k-1}.Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As a formal description of a says, a_0 = 0 and for all other i (1 \le i \le n) a_i = x_{(i-1)\bmod k} + a_{i-1}, where p \bmod q denotes the remainder of division p by q.For example, if the x = [1, 2, 3] and n = 5, then: a_0 = 0, a_1 = x_{0\bmod 3}+a_0=x_0+0=1, a_2 = x_{1\bmod 3}+a_1=x_1+1=3, a_3 = x_{2\bmod 3}+a_2=x_2+3=6, a_4 = x_{3\bmod 3}+a_3=x_0+6=7, a_5 = x_{4\bmod 3}+a_4=x_1+7=9. So, if the x = [1, 2, 3] and n = 5, then a = [0, 1, 3, 6, 7, 9].Now the boy hopes that he will be able to restore x from a! Knowing that 1 \le k \le n, help him and find all possible values of k — possible lengths of the lost array.InputThe first line contains exactly one integer n (1 \le n \le 1000) — the length of the array a, excluding the element a_0.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^6).Note that a_0 is always 0 and is not given in the input.OutputThe first line of the output should contain one integer l denoting the number of correct lengths of the lost array.The second line of the output should contain l integers — possible lengths of the lost array in increasing order.ExamplesInput51 2 3 4 5Output51 2 3 4 5 Input51 3 5 6 8Output23 5 Input31 5 3Output13 NoteIn the first example, any k is suitable, since a is an arithmetic progression.Possible arrays x: [1] [1, 1] [1, 1, 1] [1, 1, 1, 1] [1, 1, 1, 1, 1]In the second example, Bajtek's array can have three or five elements.Possible arrays x: [1, 2, 2] [1, 2, 2, 1, 2]For example, k = 4 is bad, since it leads to 6 + x_0 = 8 and 0 + x_0 = 1, which is an obvious contradiction.In the third example, only k = n is good.Array [1, 4, -2] satisfies the requirements.Note that x_i may be negative.
Input51 2 3 4 5
Output51 2 3 4 5
1 second
256 megabytes
['implementation', '*1200']
A. Electionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAwruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from this person. Of course 0 \le k - a_i holds.Awruk knows that if he loses his life is over. He has been speaking a lot with his friends and now he knows a_1, a_2, \dots, a_n — how many votes for Elodreip each student wants to give. Now he wants to change the number k to win the elections. Of course he knows that bigger k means bigger chance that somebody may notice that he has changed something and then he will be disqualified.So, Awruk knows a_1, a_2, \dots, a_n — how many votes each student will give to his opponent. Help him select the smallest winning number k. In order to win, Awruk needs to get strictly more votes than Elodreip.InputThe first line contains integer n (1 \le n \le 100) — the number of students in the school.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 100) — the number of votes each student gives to Elodreip.OutputOutput the smallest integer k (k \ge \max a_i) which gives Awruk the victory. In order to win, Awruk needs to get strictly more votes than Elodreip.ExamplesInput51 1 1 5 1Output5Input52 2 3 2 2Output5NoteIn the first example, Elodreip gets 1 + 1 + 1 + 5 + 1 = 9 votes. The smallest possible k is 5 (it surely can't be less due to the fourth person), and it leads to 4 + 4 + 4 + 0 + 4 = 16 votes for Awruk, which is enough to win.In the second example, Elodreip gets 11 votes. If k = 4, Awruk gets 9 votes and loses to Elodreip.
Input51 1 1 5 1
Output5
1 second
256 megabytes
['implementation', 'math', '*800']
F. Leaf Setstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected tree, consisting of n vertices.The vertex is called a leaf if it has exactly one vertex adjacent to it.The distance between some pair of vertices is the number of edges in the shortest path between them.Let's call some set of leaves beautiful if the maximum distance between any pair of leaves in it is less or equal to k.You want to split all leaves into non-intersecting beautiful sets. What is the minimal number of sets in such a split?InputThe first line contains two integers n and k (3 \le n \le 10^6, 1 \le k \le 10^6) — the number of vertices in the tree and the maximum distance between any pair of leaves in each beautiful set.Each of the next n - 1 lines contains two integers v_i and u_i (1 \le v_i, u_i \le n) — the description of the i-th edge. It is guaranteed that the given edges form a tree.OutputPrint a single integer — the minimal number of beautiful sets the split can have. ExamplesInput9 31 21 32 42 53 66 76 83 9Output2Input5 31 22 33 44 5Output2Input6 11 21 31 41 51 6Output5NoteHere is the graph for the first example:
Input9 31 21 32 42 53 66 76 83 9
Output2
3 seconds
256 megabytes
['data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'sortings', 'trees', '*2400']
E. Vasya and Magic Matrixtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has got a magic matrix a of size n \times m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column.Vasya has also got a chip. Initially, the chip is in the intersection of the r-th row and the c-th column (that is, in the element a_{rc}). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element.After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it.Euclidean distance between matrix elements with coordinates (i_1, j_1) and (i_2, j_2) is equal to \sqrt{(i_1-i_2)^2 + (j_1-j_2)^2}.Calculate the expected value of the Vasya's final score.It can be shown that the answer can be represented as \frac{P}{Q}, where P and Q are coprime integer numbers, and Q \not\equiv 0~(mod ~ 998244353). Print the value P \cdot Q^{-1} modulo 998244353.InputThe first line of the input contains two integers n and m (1 \le n, m \le 1\,000) — the number of rows and the number of columns in the matrix a.The following n lines contain description of the matrix a. The i-th line contains m integers a_{i1}, a_{i2}, \dots, a_{im} ~ (0 \le a_{ij} \le 10^9).The following line contains two integers r and c (1 \le r \le n, 1 \le c \le m) — the index of row and the index of column where the chip is now.OutputPrint the expected value of Vasya's final score in the format described in the problem statement.ExamplesInput1 41 1 2 11 3Output2Input2 31 5 72 3 11 2Output665496238NoteIn the first example, Vasya will move his chip exactly once. The expected value of the final score is equal to \frac{1^2 + 2^2+ 1^2}{3} = 2.
Input1 41 1 2 11 3
Output2
3 seconds
256 megabytes
['dp', 'math', 'probabilities', '*2300']
D. Petya and Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has an array a consisting of n integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than t. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs l, r (l \le r) such that a_l + a_{l+1} + \dots + a_{r-1} + a_r < t.InputThe first line contains two integers n and t (1 \le n \le 200\,000, |t| \le 2\cdot10^{14}).The second line contains a sequence of integers a_1, a_2, \dots, a_n (|a_{i}| \le 10^{9}) — the description of Petya's array. Note that there might be negative, zero and positive elements.OutputPrint the number of segments in Petya's array with the sum of elements less than t.ExamplesInput5 45 -1 3 4 -1Output5Input3 0-1 2 -3Output4Input4 -1-2 1 -2 3Output3NoteIn the first example the following segments have sum less than 4: [2, 2], sum of elements is -1 [2, 3], sum of elements is 2 [3, 3], sum of elements is 3 [4, 5], sum of elements is 3 [5, 5], sum of elements is -1
Input5 45 -1 3 4 -1
Output5
2 seconds
256 megabytes
['data structures', 'divide and conquer', 'two pointers', '*1800']
C. Array Producttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. You can perform the following operations with it: Choose some positions i and j (1 \le i, j \le n, i \ne j), write the value of a_i \cdot a_j into the j-th cell and remove the number from the i-th cell; Choose some position i and remove the number from the i-th cell (this operation can be performed no more than once and at any point of time, not necessarily in the beginning). The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.Your task is to perform exactly n - 1 operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print any sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of elements in the array.The second line contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9) — the elements of the array.OutputPrint n - 1 lines. The k-th line should contain one of the two possible operations.The operation of the first type should look like this: 1~ i_k~ j_k, where 1 is the type of operation, i_k and j_k are the positions of the chosen elements.The operation of the second type should look like this: 2~ i_k, where 2 is the type of operation, i_k is the position of the chosen element. Note that there should be no more than one such operation.If there are multiple possible sequences of operations leading to the maximum number — print any of them.ExamplesInput55 -2 0 1 -3Output2 31 1 21 2 41 4 5Input55 2 0 4 0Output1 3 52 51 1 21 2 4Input22 -1Output2 2Input40 -10 0 0Output1 1 21 2 31 3 4Input40 0 0 0Output1 1 21 2 31 3 4NoteLet X be the removed number in the array. Let's take a look at all the examples:The first example has, for example, the following sequence of transformations of the array: [5, -2, 0, 1, -3] \to [5, -2, X, 1, -3] \to [X, -10, X, 1, -3] \to [X, X, X, -10, -3] \to [X, X, X, X, 30]. Thus, the maximum answer is 30. Note, that other sequences that lead to the answer 30 are also correct.The second example has, for example, the following sequence of transformations of the array: [5, 2, 0, 4, 0] \to [5, 2, X, 4, 0] \to [5, 2, X, 4, X] \to [X, 10, X, 4, X] \to [X, X, X, 40, X]. The following answer is also allowed: 1 5 31 4 21 2 12 3Then the sequence of transformations of the array will look like this: [5, 2, 0, 4, 0] \to [5, 2, 0, 4, X] \to [5, 8, 0, X, X] \to [40, X, 0, X, X] \to [40, X, X, X, X].The third example can have the following sequence of transformations of the array: [2, -1] \to [2, X].The fourth example can have the following sequence of transformations of the array: [0, -10, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0].The fifth example can have the following sequence of transformations of the array: [0, 0, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0].
Input55 -2 0 1 -3
Output2 31 1 21 2 41 4 5
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1700']
B. Vitaminstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland shop sells n kinds of juices. Each juice has its price c_i. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.InputThe first line contains a single integer n (1 \le n \le 1\,000) — the number of juices.Each of the next n lines contains an integer c_i (1 \le c_i \le 100\,000) and a string s_i — the price of the i-th juice and the vitamins it contains. String s_i contains from 1 to 3 characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string s_i. The order of letters in strings s_i is arbitrary.OutputPrint -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.ExamplesInput45 C6 B16 BAC4 AOutput15Input210 AB15 BAOutput-1Input510 A9 BC11 CA4 A5 BOutput13Input6100 A355 BCA150 BC160 AC180 B190 CAOutput250Input25 BA11 CBOutput16NoteIn the first example Petya buys the first, the second and the fourth juice. He spends 5 + 6 + 4 = 15 and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is 16, which isn't optimal.In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".
Input45 C6 B16 BAC4 A
Output15
2 seconds
256 megabytes
['bitmasks', 'brute force', 'dp', 'implementation', '*1200']
A. Benchestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k.Nobody leaves the taken seat during the whole process.InputThe first line contains a single integer n (1 \le n \le 100) — the number of benches in the park.The second line contains a single integer m (1 \le m \le 10\,000) — the number of people additionally coming to the park.Each of the next n lines contains a single integer a_i (1 \le a_i \le 100) — the initial number of people on the i-th bench.OutputPrint the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park.ExamplesInput461111Output3 7Input1105Output15 15Input36165Output6 12Input37165Output7 13NoteIn the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining — the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench.The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it.
Input461111
Output3 7
1 second
256 megabytes
['binary search', 'implementation', '*1100']
F. Ray in the tubetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tube which is reflective inside represented as two non-coinciding, but parallel to Ox lines. Each line has some special integer points — positions of sensors on sides of the tube.You are going to emit a laser ray in the tube. To do so, you have to choose two integer points A and B on the first and the second line respectively (coordinates can be negative): the point A is responsible for the position of the laser, and the point B — for the direction of the laser ray. The laser ray is a ray starting at A and directed at B which will reflect from the sides of the tube (it doesn't matter if there are any sensors at a reflection point or not). A sensor will only register the ray if the ray hits exactly at the position of the sensor. Examples of laser rays. Note that image contains two examples. The 3 sensors (denoted by black bold points on the tube sides) will register the blue ray but only 2 will register the red. Calculate the maximum number of sensors which can register your ray if you choose points A and B on the first and the second lines respectively.InputThe first line contains two integers n and y_1 (1 \le n \le 10^5, 0 \le y_1 \le 10^9) — number of sensors on the first line and its y coordinate.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — x coordinates of the sensors on the first line in the ascending order.The third line contains two integers m and y_2 (1 \le m \le 10^5, y_1 < y_2 \le 10^9) — number of sensors on the second line and its y coordinate. The fourth line contains m integers b_1, b_2, \ldots, b_m (0 \le b_i \le 10^9) — x coordinates of the sensors on the second line in the ascending order.OutputPrint the only integer — the maximum number of sensors which can register the ray.ExampleInput3 11 5 61 33Output3NoteOne of the solutions illustrated on the image by pair A_2 and B_2.
Input3 11 5 61 33
Output3
2 seconds
256 megabytes
['data structures', 'divide and conquer', 'dp', 'math', '*2500']
E. Tree Reconstructiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from 1 to n. For every edge e of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge e (and only this edge) is erased from the tree.Monocarp has given you a list of n - 1 pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.InputThe first line contains one integer n (2 \le n \le 1\,000) — the number of vertices in the tree.Each of the next n-1 lines contains two integers a_i and b_i each (1 \le a_i < b_i \le n) — the maximal indices of vertices in the components formed if the i-th edge is removed.OutputIf there is no such tree that can produce the given list of pairs, print "NO" (without quotes).Otherwise print "YES" (without quotes) in the first line and the edges of the tree in the next n - 1 lines. Each of the last n - 1 lines should contain two integers x_i and y_i (1 \le x_i, y_i \le n) — vertices connected by an edge.Note: The numeration of edges doesn't matter for this task. Your solution will be considered correct if your tree produces the same pairs as given in the input file (possibly reordered). That means that you can print the edges of the tree you reconstructed in any order.ExamplesInput43 41 43 4OutputYES1 33 22 4Input31 31 3OutputNOInput31 22 3OutputNONotePossible tree from the first example. Dotted lines show edges you need to remove to get appropriate pairs.
Input43 41 43 4
OutputYES1 33 22 4
1 second
256 megabytes
['constructive algorithms', 'data structures', 'graphs', 'greedy', '*1900']
D. Glidertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA plane is flying at a constant height of h meters above the ground surface. Let's consider that it is flying from the point (-10^9, h) to the point (10^9, h) parallel with Ox axis.A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to Ox axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second.There are ascending air flows on certain segments, each such segment is characterized by two numbers x_1 and x_2 (x_1 < x_2) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along Ox axis, covering one unit of distance every second. If the glider jumps out at 1, he will stop at 10. Otherwise, if he jumps out at 2, he will stop at 12. Determine the maximum distance along Ox axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is 0.InputThe first line contains two integers n and h (1 \le n \le 2\cdot10^{5}, 1 \le h \le 10^{9}) — the number of ascending air flow segments and the altitude at which the plane is flying, respectively.Each of the next n lines contains two integers x_{i1} and x_{i2} (1 \le x_{i1} < x_{i2} \le 10^{9}) — the endpoints of the i-th ascending air flow segment. No two segments intersect, and they are given in ascending order.OutputPrint one integer — the maximum distance along Ox axis that the glider can fly from the point where he jumps off the plane to the point where he lands if he can start his flight at any integer coordinate.ExamplesInput3 42 57 910 11Output10Input5 105 711 1216 2025 2630 33Output18Input1 10000000001 1000000000Output1999999999NoteIn the first example if the glider can jump out at (2, 4), then the landing point is (12, 0), so the distance is 12-2 = 10.In the second example the glider can fly from (16,10) to (34,0), and the distance is 34-16=18.In the third example the glider can fly from (-100,1000000000) to (1999999899,0), so the distance is 1999999899-(-100)=1999999999.
Input3 42 57 910 11
Output10
2 seconds
256 megabytes
['binary search', 'data structures', 'two pointers', '*1700']
C. Coffee Breaktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Monocarp got a job. His working day lasts exactly m minutes. During work, Monocarp wants to drink coffee at certain moments: there are n minutes a_1, a_2, \dots, a_n, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute a_i, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least d minutes pass between any two coffee breaks. Monocarp also wants to take these n coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than d minutes pass between the end of any working day and the start of the following working day.For each of the n given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent. InputThe first line contains three integers n, m, d (1 \le n \le 2\cdot10^{5}, n \le m \le 10^{9}, 1 \le d \le m) — the number of coffee breaks Monocarp wants to have, the length of each working day, and the minimum number of minutes between any two consecutive coffee breaks.The second line contains n distinct integers a_1, a_2, \dots, a_n (1 \le a_i \le m), where a_i is some minute when Monocarp wants to have a coffee break.OutputIn the first line, write the minimum number of days required to make a coffee break in each of the n given minutes. In the second line, print n space separated integers. The i-th of integers should be the index of the day during which Monocarp should have a coffee break at minute a_i. Days are numbered from 1. If there are multiple optimal solutions, you may print any of them.ExamplesInput4 5 33 5 1 2Output33 1 1 2 Input10 10 110 5 7 4 6 3 2 1 9 8Output22 1 1 2 2 1 2 1 1 2 NoteIn the first example, Monocarp can take two coffee breaks during the first day (during minutes 1 and 5, 3 minutes will pass between these breaks). One break during the second day (at minute 2), and one break during the third day (at minute 3).In the second example, Monocarp can determine the day of the break as follows: if the minute when he wants to take a break is odd, then this break is on the first day, if it is even, then this break is on the second day.
Input4 5 33 5 1 2
Output33 1 1 2
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'two pointers', '*1600']
B. Buying a TV Settime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than a and screen height not greater than b. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is w, and the height of the screen is h, then the following condition should be met: \frac{w}{h} = \frac{x}{y}.There are many different TV sets in the shop. Monocarp is sure that for any pair of positive integers w and h there is a TV set with screen width w and height h in the shop.Monocarp isn't ready to choose the exact TV set he is going to buy. Firstly he wants to determine the optimal screen resolution. He has decided to try all possible variants of screen size. But he must count the number of pairs of positive integers w and h, beforehand, such that (w \le a), (h \le b) and (\frac{w}{h} = \frac{x}{y}).In other words, Monocarp wants to determine the number of TV sets having aspect ratio \frac{x}{y}, screen width not exceeding a, and screen height not exceeding b. Two TV sets are considered different if they have different screen width or different screen height.InputThe first line contains four integers a, b, x, y (1 \le a, b, x, y \le 10^{18}) — the constraints on the screen width and height, and on the aspect ratio.OutputPrint one integer — the number of different variants to choose TV screen width and screen height so that they meet the aforementioned constraints.ExamplesInput17 15 5 3Output3Input14 16 7 22Output0Input4 2 6 4Output1Input1000000000000000000 1000000000000000000 999999866000004473 999999822000007597Output1000000063NoteIn the first example, there are 3 possible variants: (5, 3), (10, 6), (15, 9).In the second example, there is no TV set meeting the constraints.In the third example, there is only one variant: (3, 2).
Input17 15 5 3
Output3
1 second
256 megabytes
['math', '*1000']
A. Heisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards had indices 10, 11, 12, 13, 14, 15 and 16.After the heist, only n keyboards remain, and they have indices a_1, a_2, \dots, a_n. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither x nor the number of keyboards in the store before the heist.InputThe first line contains single integer n (1 \le n \le 1\,000) — the number of keyboards in the store that remained after the heist.The second line contains n distinct integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{9}) — the indices of the remaining keyboards. The integers a_i are given in arbitrary order and are pairwise distinct.OutputPrint the minimum possible number of keyboards that have been stolen if the staff remember neither x nor the number of keyboards in the store before the heist.ExamplesInput410 13 12 8Output2Input57 5 6 4 8Output0NoteIn the first example, if x=8 then minimum number of stolen keyboards is equal to 2. The keyboards with indices 9 and 11 were stolen during the heist.In the second example, if x=4 then nothing was stolen during the heist.
Input410 13 12 8
Output2
1 second
256 megabytes
['greedy', 'implementation', 'sortings', '*800']
B. Shashlik Cookingtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputLong story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.This time Miroslav laid out n skewers parallel to each other, and enumerated them with consecutive integers from 1 to n in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number i, it leads to turning k closest skewers from each side of the skewer i, that is, skewers number i - k, i - k + 1, ..., i - 1, i + 1, ..., i + k - 1, i + k (if they exist). For example, let n = 6 and k = 1. When Miroslav turns skewer number 3, then skewers with numbers 2, 3, and 4 will come up turned over. If after that he turns skewer number 1, then skewers number 1, 3, and 4 will be turned over, while skewer number 2 will be in the initial position (because it is turned again).As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all n skewers with the minimal possible number of actions. For example, for the above example n = 6 and k = 1, two turnings are sufficient: he can turn over skewers number 2 and 5.Help Miroslav turn over all n skewers.InputThe first line contains two integers n and k (1 \leq n \leq 1000, 0 \leq k \leq 1000) — the number of skewers and the number of skewers from each side that are turned in one step.OutputThe first line should contain integer l — the minimum number of actions needed by Miroslav to turn over all n skewers. After than print l integers from 1 to n denoting the number of the skewer that is to be turned over at the corresponding step.ExamplesInput7 2Output21 6 Input5 1Output21 4 NoteIn the first example the first operation turns over skewers 1, 2 and 3, the second operation turns over skewers 4, 5, 6 and 7.In the second example it is also correct to turn over skewers 2 and 5, but turning skewers 2 and 4, or 1 and 5 are incorrect solutions because the skewer 3 is in the initial state after these operations.
Input7 2
Output21 6
1 second
512 megabytes
['dp', 'greedy', 'math', '*1300']
A. Palindrome Dancetime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future.On the day when the suits were to be bought, the director was told that the participants of the olympiad will be happy if the colors of the suits on the scene will form a palindrome. A palindrome is a sequence that is the same when read from left to right and when read from right to left. The director liked the idea, and she wants to buy suits so that the color of the leftmost dancer's suit is the same as the color of the rightmost dancer's suit, the 2nd left is the same as 2nd right, and so on.The director knows how many burls it costs to buy a white suit, and how many burls to buy a black suit. You need to find out whether it is possible to buy suits to form a palindrome, and if it's possible, what's the minimal cost of doing so. Remember that dancers can not change positions, and due to bureaucratic reasons it is not allowed to buy new suits for the dancers who already have suits, even if it reduces the overall spending.InputThe first line contains three integers n, a, and b (1 \leq n \leq 20, 1 \leq a, b \leq 100) — the number of dancers, the cost of a white suit, and the cost of a black suit.The next line contains n numbers c_i, i-th of which denotes the color of the suit of the i-th dancer. Number 0 denotes the white color, 1 — the black color, and 2 denotes that a suit for this dancer is still to be bought.OutputIf it is not possible to form a palindrome without swapping dancers and buying new suits for those who have one, then output -1. Otherwise, output the minimal price to get the desired visual effect.ExamplesInput5 100 10 1 2 1 2Output101Input3 10 121 2 0Output-1Input3 12 10 1 0Output0NoteIn the first sample, the cheapest way to obtain palindromic colors is to buy a black suit for the third from left dancer and a white suit for the rightmost dancer.In the second sample, the leftmost dancer's suit already differs from the rightmost dancer's suit so there is no way to obtain the desired coloring.In the third sample, all suits are already bought and their colors form a palindrome.
Input5 100 10 1 2 1 2
Output101
1 second
512 megabytes
['greedy', '*1000']
E. Summer Oenothera Exhibitiontime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWhile some people enjoy spending their time solving programming contests, Dina prefers taking beautiful pictures. As soon as Byteland Botanical Garden announced Summer Oenothera Exhibition she decided to test her new camera there.The exhibition consists of l = 10^{100} Oenothera species arranged in a row and consecutively numbered with integers from 0 to l - 1. Camera lens allows to take a photo of w species on it, i.e. Dina can take a photo containing flowers with indices from x to x + w - 1 for some integer x between 0 and l - w. We will denote such photo with [x, x + w - 1].She has taken n photos, the i-th of which (in chronological order) is [x_i, x_i + w - 1] in our notation. She decided to build a time-lapse video from these photos once she discovered that Oenothera blossoms open in the evening. Dina takes each photo and truncates it, leaving its segment containing exactly k flowers, then she composes a video of these photos keeping their original order and voilà, a beautiful artwork has been created!A scene is a contiguous sequence of photos such that the set of flowers on them is the same. The change between two scenes is called a cut. For example, consider the first photo contains flowers [1, 5], the second photo contains flowers [3, 7] and the third photo contains flowers [8, 12]. If k = 3, then Dina can truncate the first and the second photo into [3, 5], and the third photo into [9, 11]. First two photos form a scene, third photo also forms a scene and the transition between these two scenes which happens between the second and the third photos is a cut. If k = 4, then each of the transitions between photos has to be a cut.Dina wants the number of cuts to be as small as possible. Please help her! Calculate the minimum possible number of cuts for different values of k.InputThe first line contains three positive integer n, w, q (1 \leq n, q \leq 100\,000, 1 \leq w \leq 10^9) — the number of taken photos, the number of flowers on a single photo and the number of queries.Next line contains n non-negative integers x_i (0 \le x_i \le 10^9) — the indices of the leftmost flowers on each of the photos.Next line contains q positive integers k_i (1 \le k_i \le w) — the values of k for which you have to solve the problem.It's guaranteed that all k_i are distinct.OutputPrint q integers — for each width of the truncated photo k_i, the minimum number of cuts that is possible.ExamplesInput3 6 52 4 01 2 3 4 5Output00112Input6 4 31 2 3 4 3 21 2 3Output012
Input3 6 52 4 01 2 3 4 5
Output00112
7 seconds
512 megabytes
['data structures', '*3400']
D. You Are Given a Treetime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA tree is an undirected graph with exactly one simple path between each pair of vertices. We call a set of simple paths k-valid if each vertex of the tree belongs to no more than one of these paths (including endpoints) and each path consists of exactly k vertices.You are given a tree with n vertices. For each k from 1 to n inclusive find what is the maximum possible size of a k-valid set of simple paths.InputThe first line of the input contains a single integer n (2 \le n \le 100\,000) — the number of vertices in the tree.Then following n - 1 lines describe the tree, each of them contains two integers v, u (1 \le v, u \le n) — endpoints of the corresponding edge.It is guaranteed, that the given graph is a tree. OutputOutput n numbers, the i-th of which is the maximum possible number of paths in an i-valid set of paths.ExamplesInput71 22 33 44 55 66 7Output7321111Input61 22 32 41 55 6Output622110NoteOne way to achieve the optimal number of paths for the second sample is illustrated in the following picture:
Input71 22 33 44 55 66 7
Output7321111
7 seconds
512 megabytes
['data structures', 'dp', 'trees', '*2800']
C. Network Safetytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Metropolis computer network consists of n servers, each has an encryption key in the range from 0 to 2^k - 1 assigned to it. Let c_i be the encryption key assigned to the i-th server. Additionally, m pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms specifics, a data communication channel can only be considered safe if the two servers it connects have distinct encryption keys. The initial assignment of encryption keys is guaranteed to keep all data communication channels safe.You have been informed that a new virus is actively spreading across the internet, and it is capable to change the encryption key of any server it infects. More specifically, the virus body contains some unknown number x in the same aforementioned range, and when server i is infected, its encryption key changes from c_i to c_i \oplus x, where \oplus denotes the bitwise XOR operation.Sadly, you know neither the number x nor which servers of Metropolis are going to be infected by the dangerous virus, so you have decided to count the number of such situations in which all data communication channels remain safe. Formally speaking, you need to find the number of pairs (A, x), where A is some (possibly empty) subset of the set of servers and x is some number in the range from 0 to 2^k - 1, such that when all servers from the chosen subset A and none of the others are infected by a virus containing the number x, all data communication channels remain safe. Since this number can be quite big, you are asked to find its remainder modulo 10^9 + 7.InputThe first line of input contains three integers n, m and k (1 \leq n \leq 500\,000, 0 \leq m \leq \min(\frac{n(n - 1)}{2}, 500\,000), 0 \leq k \leq 60) — the number of servers, the number of pairs of servers directly connected by a data communication channel, and the parameter k, which defines the range of possible values for encryption keys.The next line contains n integers c_i (0 \leq c_i \leq 2^k - 1), the i-th of which is the encryption key used by the i-th server.The next m lines contain two integers u_i and v_i each (1 \leq u_i, v_i \leq n, u_i \ne v_i) denoting that those servers are connected by a data communication channel. It is guaranteed that each pair of servers appears in this list at most once.OutputThe only output line should contain a single integer — the number of safe infections of some subset of servers by a virus with some parameter, modulo 10^9 + 7.ExamplesInput4 4 20 1 0 11 22 33 44 1Output50Input4 5 37 1 7 21 22 33 44 12 4Output96NoteConsider the first example.Possible values for the number x contained by the virus are 0, 1, 2 and 3.For values 0, 2 and 3 the virus can infect any subset of the set of servers, which gives us 16 pairs for each values. A virus containing the number 1 can infect either all of the servers, or none. This gives us 16 + 2 + 16 + 16 = 50 pairs in total.
Input4 4 20 1 0 11 22 33 44 1
Output50
3 seconds
512 megabytes
['dfs and similar', 'dsu', 'graphs', 'math', 'sortings', '*2200']
B. Subway Pursuittime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.The subway of the Metropolis is one line (regular straight line with no self-intersections) with n stations, indexed consecutively from 1 to n. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers l and r (l \le r), and then check, whether the train is located on a station with index between l and r, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most k stations away. Formally, if the train was at the station x when the gadget was applied, then at the next application of the gadget the train can appear at any station y such that \max(1, x - k) \leq y \leq \min(n, x + k).Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.After an examination of the gadget you found that it is very old and can hold no more than 4500 applications, after which it will break and your mission will be considered a failure.Can you find the station with the train using no more than 4500 applications of the gadgets?InputThe first line contains two integers n and k (1 \leq n \leq 10^{18}, 0 \leq k \leq 10) — the number of stations and the maximum number of stations the train can move between two applications of the gadget.InteractionYou can apply the gadget at most 4500 times. In order to apply the gadget you need to print two space-separated integers l and r (1 \leq l \leq r \leq n). You will then receive either string "Yes", if the train is between stations l and r, inclusive, or string "No" otherwise. If l = r and you received "Yes", then you found the train successfully, and your program must halt immediately.Answer "Bad" instead of "Yes" or "No" means that you made an invalid query or made too many queries. Exit immediately after receiving "Bad" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. HacksIn order to hack, you should present a test in the following format.The first line should contain three integers n, k and p (1 \le n \le 10^{18}, 0 \le k \le 10, 1 \le p \le n) — the number of stations, the maximum number of stations the train can move between two applications of the gadget and the initial position of the train, respectively.Each of the next 4500 lines should contain a single integer x (1 \le x \le n) — the positions of the train after each query. Two consecutive positions (including the initial one) should not differ by more than k.For example, the following lines are the first lines of the sample test.10 2 553577...ExampleInput10 2YesNoYesYesOutput3 53 33 45 5NoteIn the first sample, the train was initially at the station 5, after the first application of the gadget it did not move, after the second application it moved to the station 3, and after the third application moved again to the station 5.
Input10 2YesNoYesYes
Output3 53 33 45 5
2 seconds
512 megabytes
['binary search', 'interactive', 'probabilities', '*2100']
A. Timetabletime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are two bus stops denoted A and B, and there n buses that go from A to B every day. The shortest path from A to B takes t units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route.At each station one can find a sorted list of moments of time when a bus is at this station. We denote this list as a_1 < a_2 < \ldots < a_n for stop A and as b_1 < b_2 < \ldots < b_n for stop B. The buses always depart from A and arrive to B according to the timetable, but the order in which the buses arrive may differ. Let's call an order of arrivals valid if each bus arrives at least t units of time later than departs.It is known that for an order to be valid the latest possible arrival for the bus that departs at a_i is b_{x_i}, i.e. x_i-th in the timetable. In other words, for each i there exists such a valid order of arrivals that the bus departed i-th arrives x_i-th (and all other buses can arrive arbitrary), but there is no valid order of arrivals in which the i-th departed bus arrives (x_i + 1)-th.Formally, let's call a permutation p_1, p_2, \ldots, p_n valid, if b_{p_i} \ge a_i + t for all i. Then x_i is the maximum value of p_i among all valid permutations.You are given the sequences a_1, a_2, \ldots, a_n and x_1, x_2, \ldots, x_n, but not the arrival timetable. Find out any suitable timetable for stop B b_1, b_2, \ldots, b_n or determine that there is no such timetable.InputThe first line of the input contains two integers n and t (1 \leq n \leq 200\,000, 1 \leq t \leq 10^{18}) — the number of buses in timetable for and the minimum possible travel time from stop A to stop B.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_1 < a_2 < \ldots < a_n \leq 10^{18}), defining the moments of time when the buses leave stop A.The third line contains n integers x_1, x_2, \ldots, x_n (1 \leq x_i \leq n), the i-th of them stands for the maximum possible timetable position, at which the i-th bus leaving stop A can arrive at stop B. OutputIf a solution exists, print "Yes" (without quotes) in the first line of the output.In the second line print n integers b_1, b_2, \ldots, b_n (1 \leq b_1 < b_2 < \ldots < b_n \leq 3 \cdot 10^{18}). We can show that if there exists any solution, there exists a solution that satisfies such constraints on b_i. If there are multiple valid answers you can print any of them.If there is no valid timetable, print "No" (without quotes) in the only line of the output.ExamplesInput3 104 6 82 2 3OutputYes16 17 21 Input2 11 22 1OutputNoNoteConsider the first example and the timetable b_1, b_2, \ldots, b_n from the output.To get x_1 = 2 the buses can arrive in the order (2, 1, 3). To get x_2 = 2 and x_3 = 3 the buses can arrive in the order (1, 2, 3). x_1 is not 3, because the permutations (3, 1, 2) and (3, 2, 1) (all in which the 1-st bus arrives 3-rd) are not valid (sube buses arrive too early), x_2 is not 3 because of similar reasons.
Input3 104 6 82 2 3
OutputYes16 17 21
2 seconds
512 megabytes
['constructive algorithms', 'data structures', 'greedy', 'math', '*2300']
F. Wrap Aroundtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s.Find the number of distinct cyclical binary strings of length n which contain s as a substring.The cyclical string t contains s as a substring if there is some cyclical shift of string t, such that s is a substring of this cyclical shift of t.For example, the cyclical string "000111" contains substrings "001", "01110" and "10", but doesn't contain "0110" and "10110".Two cyclical strings are called different if they differ from each other as strings. For example, two different strings, which differ from each other by a cyclical shift, are still considered different cyclical strings.InputThe first line contains a single integer n (1 \le n \le 40) — the length of the target string t.The next line contains the string s (1 \le |s| \le n) — the string which must be a substring of cyclical string t. String s contains only characters '0' and '1'.OutputPrint the only integer — the number of distinct cyclical binary strings t, which contain s as a substring.ExamplesInput20Output3Input41010Output2Input2010101010101010Output962NoteIn the first example, there are three cyclical strings, which contain "0" — "00", "01" and "10".In the second example, there are only two such strings — "1010", "0101".
Input20
Output3
2 seconds
256 megabytes
['dp', 'strings', '*2900']
E. Maximum Matchingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n blocks, each of them is of the form [color_1|value|color_2], where the block can also be flipped to get [color_2|value|color_1]. A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C.The value of the sequence is defined as the sum of the values of the blocks in this sequence.Find the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence.InputThe first line of input contains a single integer n (1 \le n \le 100) — the number of given blocks.Each of the following n lines describes corresponding block and consists of \mathrm{color}_{1,i}, \mathrm{value}_i and \mathrm{color}_{2,i} (1 \le \mathrm{color}_{1,i}, \mathrm{color}_{2,i} \le 4, 1 \le \mathrm{value}_i \le 100\,000).OutputPrint exactly one integer — the maximum total value of the subset of blocks, which makes a valid sequence.ExamplesInput62 1 41 2 43 4 42 8 33 16 31 32 2Output63Input71 100000 11 100000 21 100000 24 50000 33 50000 44 50000 43 50000 3Output300000Input41 1000 12 500 23 250 34 125 4Output1000NoteIn the first example, it is possible to form a valid sequence from all blocks.One of the valid sequences is the following:[4|2|1] [1|32|2] [2|8|3] [3|16|3] [3|4|4] [4|1|2]The first block from the input ([2|1|4] \to [4|1|2]) and second ([1|2|4] \to [4|2|1]) are flipped.In the second example, the optimal answers can be formed from the first three blocks as in the following (the second or the third block from the input is flipped):[2|100000|1] [1|100000|1] [1|100000|2]In the third example, it is not possible to form a valid sequence of two or more blocks, so the answer is a sequence consisting only of the first block since it is the block with the largest value.
Input62 1 41 2 43 4 42 8 33 16 31 32 2
Output63
2 seconds
256 megabytes
['bitmasks', 'brute force', 'dfs and similar', 'dp', 'graphs', '*2400']
D. Slimetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists). When a slime with a value x eats a slime with a value y, the eaten slime disappears, and the value of the remaining slime changes to x - y.The slimes will eat each other until there is only one slime left. Find the maximum possible value of the last slime.InputThe first line of the input contains an integer n (1 \le n \le 500\,000) denoting the number of slimes.The next line contains n integers a_i (-10^9 \le a_i \le 10^9), where a_i is the value of i-th slime.OutputPrint an only integer — the maximum possible value of the last slime.ExamplesInput42 1 2 1Output4Input50 -1 -1 -1 -1Output4NoteIn the first example, a possible way of getting the last slime with value 4 is: Second slime eats the third slime, the row now contains slimes 2, -1, 1 Second slime eats the third slime, the row now contains slimes 2, -2 First slime eats the second slime, the row now contains 4 In the second example, the first slime can keep eating slimes to its right to end up with a value of 4.
Input42 1 2 1
Output4
2 seconds
256 megabytes
['dp', 'greedy', 'implementation', '*1800']
C. Gamblingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo players A and B have a list of n integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements \{1, 2, 2, 3\} in a list and you decided to choose 2 for the next turn, only a single instance of 2 will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.InputThe first line of input contains an integer n (1 \le n \le 100\,000) — the sizes of the list.The second line contains n integers a_i (1 \le a_i \le 10^6), describing the list of the player A, who starts the game.The third line contains n integers b_i (1 \le b_i \le 10^6), describing the list of the player B.OutputOutput the difference between A's score and B's score (A-B) if both of them are playing optimally.ExamplesInput21 45 1Output0Input3100 100 100100 100 100Output0Input22 15 6Output-3NoteIn the first example, the game could have gone as follows: A removes 5 from B's list. B removes 4 from A's list. A takes his 1. B takes his 1. Hence, A's score is 1, B's score is 1 and difference is 0.There is also another optimal way of playing: A removes 5 from B's list. B removes 4 from A's list. A removes 1 from B's list. B removes 1 from A's list. The difference in the scores is still 0.In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be 0.
Input21 45 1
Output0
2 seconds
256 megabytes
['greedy', 'sortings', '*1300']
B. Non-Coprime Partitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFind out if it is possible to partition the first n positive integers into two non-empty disjoint sets S_1 and S_2 such that:\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1 Here \mathrm{sum}(S) denotes the sum of all elements present in set S and \mathrm{gcd} means thegreatest common divisor.Every integer number from 1 to n should be present in exactly one of S_1 or S_2.InputThe only line of the input contains a single integer n (1 \le n \le 45\,000)OutputIf such partition doesn't exist, print "No" (quotes for clarity).Otherwise, print "Yes" (quotes for clarity), followed by two lines, describing S_1 and S_2 respectively.Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty.If there are multiple possible partitions — print any of them.ExamplesInput1OutputNoInput3OutputYes1 22 1 3 NoteIn the first example, there is no way to partition a single number into two non-empty sets, hence the answer is "No".In the second example, the sums of the sets are 2 and 4 respectively. The \mathrm{gcd}(2, 4) = 2 > 1, hence that is one of the possible answers.
Input1
OutputNo
2 seconds
256 megabytes
['constructive algorithms', 'math', '*1100']
A. Equalitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase.A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not.A subsequence of s called good if the number of occurences of each of the first k letters of the alphabet is the same.Find the length of the longest good subsequence of s. InputThe first line of the input contains integers n (1\le n \le 10^5) and k (1 \le k \le 26).The second line of the input contains the string s of length n. String s only contains uppercase letters from 'A' to the k-th letter of Latin alphabet.OutputPrint the only integer — the length of the longest good subsequence of string s.ExamplesInput9 3ACAABCCABOutput6Input9 4ABCABCABCOutput0NoteIn the first example, "ACBCAB" ("ACAABCCAB") is one of the subsequences that has the same frequency of 'A', 'B' and 'C'. Subsequence "CAB" also has the same frequency of these letters, but doesn't have the maximum possible length.In the second example, none of the subsequences can have 'D', hence the answer is 0.
Input9 3ACAABCCAB
Output6
2 seconds
256 megabytes
['implementation', 'strings', '*800']
H. Securitytime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSome programming website is establishing a secure communication protocol. For security reasons, they want to choose several more or less random strings.Initially, they have a string s consisting of lowercase English letters. Now they want to choose q strings using the following steps, and you are to help them. A string x consisting of lowercase English letters and integers l and r (1 \leq l \leq r \leq |s|) are chosen. Consider all non-empty distinct substrings of the s_l s_{l + 1} \ldots s_r, that is all distinct strings s_i s_{i+1} \ldots s_{j} where l \le i \le j \le r. Among all of them choose all strings that are lexicographically greater than x. If there are no such strings, you should print -1. Otherwise print the lexicographically smallest among them. String a is lexicographically less than string b, if either a is a prefix of b and a \ne b, or there exists such a position i (1 \le i \le min(|a|, |b|)), such that a_i < b_i and for all j (1 \le j < i) a_j = b_j. Here |a| denotes the length of the string a.InputThe first line of input contains a non-empty string s (1 \leq |s| \leq 10^{5}) consisting of lowercase English letters.The second line contains an integer q (1 \le q \le 2 \cdot 10^5) — the number of strings to select.Each of the next q lines contains two integers l, r (1 \leq l \leq r \leq |s|) and a non-empty string x consisting of lowercase English letters. The total length of strings x for all queries does not exceed 2 \cdot 10^{5}.OutputOutput q lines, each of them should contain the desired string or -1, if there is no such string.ExamplesInputbaa51 2 ba2 3 a1 2 b2 3 aa1 3 bOutput-1aaba-1baInputbacb41 2 ba2 3 ac1 3 ac3 4 cOutput-1cbcbInputbba11 1 bOutput-1NoteConsider the first example.The string s is "baa". The queries are as follows. We consider the substring s_1 s_2 that is "ba". It has substrings "b", "a" and "ba", since none of them is greater than the query string "ba", the answer is -1. We consider substring "aa". Among its substrings only "aa" is greater than the query string "a". So the answer is "aa". We consider substring "ba". Out of "b", "a" and "ba" only "ba" is greater than the query string "b", so the answer is "ba". We consider substring "aa". No substring of "aa" is greater than the query string "aa" so the answer is -1. We consider substring "baa" and it has (among others) substrings "ba", "baa" which are greater than the query string "b". Since "ba" is lexicographically smaller than "baa", the answer is "ba".
Inputbaa51 2 ba2 3 a1 2 b2 3 aa1 3 b
Output-1aaba-1ba
4 seconds
512 megabytes
['data structures', 'string suffix structures', '*3200']
G. A Game on Stringstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game on strings.Initially, they have some string t. In one move the first player selects the character c present in t and erases all it's occurrences in t, thus splitting t into many smaller strings. The game then goes independently with each of the strings — to make the move player selects one of the strings and one of the characters there, deletes all occurrences and adds the remaining string back to the game.Alice always starts the game, and then Alice and Bob take turns making moves. The player who is unable to make a move (because there is no string left) loses.Alice and Bob used to always start with a string s, but recently they found out that this became too boring. Now before each game they choose two integers l and r such that 1 \le l \le r \le |s| and play the game with the string s_{l} s_{l+1} s_{l+2} \ldots s_{r} instead.Given the string s and integers l, r for each game. Find who is going to win each game assuming they are smart and are playing optimally.InputThe first line contains the string s (1 \le |s| \le 10^5) consisting of lowercase English letters. This is the string Alice and Bob used to start with.The second line contains a single integer m (1 \le m \le 10^5) — the number of games to analyze.Each of the next m lines contains two integers l and r (1 \le l \le r \le |s|) — the bounds of the starting substring in the string s.OutputFor each game output a single line containing the name of the winner — "Alice" or "Bob" respectively.ExamplesInputaaab21 21 4OutputAliceBobInputaaccbdb25 71 7OutputAliceAliceNoteIn the first example, In the first game the string "aa" is selected. Alice deletes character 'a' and Bob is unable to move. In the second game the string "aaab" is selected. No matter what character Alice will delete, Bob deletes the other one and Alice is unable to move. In the second example Alice wins both game "bdb" and "aaccbdb".To win game "bdb" Alice can erase symbol 'd', the game then goes independently on strings "b" and "b". Bob deletes one of this strings and the Alice deletes the other one and Bob is unable to move.To win game "aaccbdb" Alice can erase symbol 'd', the game then goes independently on strings "aaccb" and "b". It is possible to show, that no matter what are the moves, the remaining game can only finish in exactly 4 moves, so the Bob will be unable to move after that.
Inputaaab21 21 4
OutputAliceBob
4 seconds
256 megabytes
['games', '*3200']
F. Maximum Reductiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a of n integers and an integer k (2 \le k \le n), where each element of the array is denoted by a_i (0 \le i < n). Perform the operation z given below on a and print the value of z(a,k) modulo 10^{9}+7.function z(array a, integer k): if length(a) < k: return 0 else: b = empty array ans = 0 for i = 0 .. (length(a) - k): temp = a[i] for j = i .. (i + k - 1): temp = max(temp, a[j]) append temp to the end of b ans = ans + temp return ans + z(b, k)InputThe first line of input contains two integers n and k (2 \le k \le n \le 10^6) — the length of the initial array a and the parameter k.The second line of input contains n integers a_0, a_1, \ldots, a_{n - 1} (1 \le a_{i} \le 10^9) — the elements of the array a.OutputOutput the only integer, the value of z(a,k) modulo 10^9+7.ExamplesInput3 29 1 10Output29Input5 35 8 7 1 9Output34NoteIn the first example: for a=(9,1,10), ans=19 and b=(9,10), for a=(9,10), ans=10 and b=(10), for a=(10), ans=0. So the returned value is 19+10+0=29.In the second example: for a=(5,8,7,1,9), ans=25 and b=(8,8,9), for a=(8,8,9), ans=9 and b=(9), for a=(9), ans=0. So the returned value is 25+9+0=34.
Input3 29 1 10
Output29
2 seconds
256 megabytes
['combinatorics', 'data structures', 'math', '*2500']
E. Tripstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.We want to plan a trip for every evening of m days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: Either this person does not go on the trip, Or at least k of his friends also go on the trip. Note that the friendship is not transitive. That is, if a and b are friends and b and c are friends, it does not necessarily imply that a and c are friends.For each day, find the maximum number of people that can go on the trip on that day.InputThe first line contains three integers n, m, and k (2 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5, 1 \le k < n) — the number of people, the number of days and the number of friends each person on the trip should have in the group.The i-th (1 \leq i \leq m) of the next m lines contains two integers x and y (1\leq x, y\leq n, x\ne y), meaning that persons x and y become friends on the morning of day i. It is guaranteed that x and y were not friends before.OutputPrint exactly m lines, where the i-th of them (1\leq i\leq m) contains the maximum number of people that can go on the trip on the evening of the day i.ExamplesInput4 4 22 31 21 31 4Output0033Input5 8 22 14 25 45 24 35 14 13 2Output00033445Input5 7 21 53 22 53 41 25 31 3Output0000344NoteIn the first example, 1,2,3 can go on day 3 and 4. In the second example, 2,4,5 can go on day 4 and 5. 1,2,4,5 can go on day 6 and 7. 1,2,3,4,5 can go on day 8. In the third example, 1,2,5 can go on day 5. 1,2,3,5 can go on day 6 and 7.
Input4 4 22 31 21 31 4
Output0033
2 seconds
256 megabytes
['graphs', '*2200']
D. Valid BFS?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe BFS algorithm is defined as follows. Consider an undirected graph with vertices numbered from 1 to n. Initialize q as a new queue containing only vertex 1, mark the vertex 1 as used. Extract a vertex v from the head of the queue q. Print the index of vertex v. Iterate in arbitrary order through all such vertices u that u is a neighbor of v and is not marked yet as used. Mark the vertex u as used and insert it into the tail of the queue q. If the queue is not empty, continue from step 2. Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print.In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree starting from vertex 1. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) which denotes the number of nodes in the tree. The following n - 1 lines describe the edges of the tree. Each of them contains two integers x and y (1 \le x, y \le n) — the endpoints of the corresponding edge of the tree. It is guaranteed that the given graph is a tree.The last line contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the sequence to check.OutputPrint "Yes" (quotes for clarity) if the sequence corresponds to some valid BFS traversal of the given tree and "No" (quotes for clarity) otherwise.You can print each letter in any case (upper or lower).ExamplesInput41 21 32 41 2 3 4OutputYesInput41 21 32 41 2 4 3OutputNoNoteBoth sample tests have the same tree in them.In this tree, there are two valid BFS orderings: 1, 2, 3, 4, 1, 3, 2, 4. The ordering 1, 2, 4, 3 doesn't correspond to any valid BFS order.
Input41 21 32 41 2 3 4
OutputYes
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'shortest paths', 'trees', '*1700']
C. Equalizetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two binary strings a and b of the same length. You can perform the following two operations on the string a: Swap any two bits at indices i and j respectively (1 \le i, j \le n), the cost of this operation is |i - j|, that is, the absolute difference between i and j. Select any arbitrary index i (1 \le i \le n) and flip (change 0 to 1 or 1 to 0) the bit at this index. The cost of this operation is 1. Find the minimum cost to make the string a equal to b. It is not allowed to modify string b.InputThe first line contains a single integer n (1 \le n \le 10^6) — the length of the strings a and b.The second and third lines contain strings a and b respectively.Both strings a and b have length n and contain only '0' and '1'.OutputOutput the minimum cost to make the string a equal to b.ExamplesInput3100001Output2Input401010011Output1NoteIn the first example, one of the optimal solutions is to flip index 1 and index 3, the string a changes in the following way: "100" \to "000" \to "001". The cost is 1 + 1 = 2.The other optimal solution is to swap bits and indices 1 and 3, the string a changes then "100" \to "001", the cost is also |1 - 3| = 2.In the second example, the optimal solution is to swap bits at indices 2 and 3, the string a changes as "0101" \to "0011". The cost is |2 - 3| = 1.
Input3100001
Output2
1 second
256 megabytes
['dp', 'greedy', 'strings', '*1300']
B. Reach Mediantime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers and an integer s. It is guaranteed that n is odd.In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s.The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array 6, 5, 8 is equal to 6, since if we sort this array we will get 5, 6, 8, and 6 is located on the middle position.InputThe first line contains two integers n and s (1\le n\le 2\cdot 10^5-1, 1\le s\le 10^9) — the length of the array and the required value of median.The second line contains n integers a_1, a_2, \ldots, a_n (1\le a_i \le 10^9) — the elements of the array a.It is guaranteed that n is odd.OutputIn a single line output the minimum number of operations to make the median being equal to s.ExamplesInput3 86 5 8Output2Input7 2021 15 12 11 20 19 12Output6NoteIn the first sample, 6 can be increased twice. The array will transform to 8, 5, 8, which becomes 5, 8, 8 after sorting, hence the median is equal to 8.In the second sample, 19 can be increased once and 15 can be increased five times. The array will become equal to 21, 20, 12, 11, 20, 20, 12. If we sort this array we get 11, 12, 12, 20, 20, 20, 21, this way the median is 20.
Input3 86 5 8
Output2
1 second
256 megabytes
['greedy', '*1300']
A. Packetstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n coins, each of the same value of 1.Distribute them into packets such that any amount x (1 \leq x \leq n) can be formed using some (possibly one or all) number of these packets.Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, however it may be reused for the formation of other x's.Find the minimum number of packets in such a distribution.InputThe only line contains a single integer n (1 \leq n \leq 10^9) — the number of coins you have.OutputOutput a single integer — the minimum possible number of packets, satisfying the condition above.ExamplesInput6Output3Input2Output2NoteIn the first example, three packets with 1, 2 and 3 coins can be made to get any amount x (1\leq x\leq 6). To get 1 use the packet with 1 coin. To get 2 use the packet with 2 coins. To get 3 use the packet with 3 coins. To get 4 use packets with 1 and 3 coins. To get 5 use packets with 2 and 3 coins To get 6 use all packets. In the second example, two packets with 1 and 1 coins can be made to get any amount x (1\leq x\leq 2).
Input6
Output3
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1300']
G. Sources and Sinkstime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an acyclic directed graph, consisting of n vertices and m edges. The graph contains no multiple edges and no self-loops.The vertex is called a source if it has no incoming edges. The vertex is called a sink if it has no outgoing edges. These definitions imply that some vertices can be both source and sink.The number of sources in the given graph is equal to the number of sinks in it, and each of these numbers doesn't exceed 20.The following algorithm is applied to the graph: if the graph has no sources and sinks then quit; choose arbitrary source s, arbitrary sink t, add an edge from t to s to the graph and go to step 1 (that operation pops s out of sources and t out of sinks). Note that s and t may be the same vertex, then a self-loop is added. At the end you check if the graph becomes strongly connected (that is, any vertex is reachable from any other vertex).Your task is to check that the graph becomes strongly connected no matter the choice of sources and sinks on the second step of the algorithm.InputThe first line contains two integers n and m (1 \le n, m \le 10^6) — the number of vertices and the number of edges in the graph, respectively.Each of the next m lines contains two integers v_i, u_i (1 \le v_i, u_i \le n, v_i \ne u_i) — the description of the i-th edge of the original graph.It is guaranteed that the number of sources and the number of sinks in the graph are the same and they don't exceed 20. It is guaranteed that the given graph contains no multiple edges. It is guaranteed that the graph contains no cycles.OutputPrint "YES" if the graph becomes strongly connected no matter the choice of sources and sinks on the second step of the algorithm. Otherwise print "NO".ExamplesInput3 11 2OutputNOInput3 31 21 32 3OutputYESInput4 41 21 34 24 3OutputYES
Input3 11 2
OutputNO
7 seconds
512 megabytes
['bitmasks', 'brute force', 'dfs and similar', '*2700']
F. Relatively Prime Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider some positive integer x. Its prime factorization will be of form x = 2^{k_1} \cdot 3^{k_2} \cdot 5^{k_3} \cdot \dotsLet's call x elegant if the greatest common divisor of the sequence k_1, k_2, \dots is equal to 1. For example, numbers 5 = 5^1, 12 = 2^2 \cdot 3, 72 = 2^3 \cdot 3^2 are elegant and numbers 8 = 2^3 (GCD = 3), 2500 = 2^2 \cdot 5^4 (GCD = 2) are not.Count the number of elegant integers from 2 to n.Each testcase contains several values of n, for each of them you are required to solve the problem separately.InputThe first line contains a single integer T (1 \le T \le 10^5) — the number of values of n in the testcase.Each of the next T lines contains a single integer n_i (2 \le n_i \le 10^{18}).OutputPrint T lines — the i-th line should contain the number of elegant numbers from 2 to n_i.ExampleInput4427210Output21616NoteHere is the list of non-elegant numbers up to 10: 4 = 2^2, GCD = 2; 8 = 2^3, GCD = 3; 9 = 3^2, GCD = 2. The rest have GCD = 1.
Input4427210
Output21616
2 seconds
256 megabytes
['combinatorics', 'math', 'number theory', '*2400']
E. Covered Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line.Count the number of distinct points with integer coordinates, which are covered by at least one segment.InputThe first line contains a single integer n (1 \le n \le 1000) — the number of segments.Each of the next n lines contains four integers Ax_i, Ay_i, Bx_i, By_i (-10^6 \le Ax_i, Ay_i, Bx_i, By_i \le 10^6) — the coordinates of the endpoints A, B (A \ne B) of the i-th segment.It is guaranteed that no two segments lie on the same line.OutputPrint a single integer — the number of distinct points with integer coordinates, which are covered by at least one segment.ExamplesInput90 0 4 4-1 5 4 04 0 4 45 2 11 26 1 6 75 6 11 610 1 10 77 0 9 810 -1 11 -1Output42Input4-1 2 1 2-1 0 1 0-1 0 0 30 3 1 0Output7NoteThe image for the first example: Several key points are marked blue, the answer contains some non-marked points as well.The image for the second example:
Input90 0 4 4-1 5 4 04 0 4 45 2 11 26 1 6 75 6 11 610 1 10 77 0 9 810 -1 11 -1
Output42
2 seconds
256 megabytes
['fft', 'geometry', 'number theory', '*2400']
D. Vasya and Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has two arrays A and B of lengths n and m, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array [1, 10, 100, 1000, 10000] Vasya can obtain array [1, 1110, 10000], and from array [1, 2, 3] Vasya can obtain array [6].Two arrays A and B are considered equal if and only if they have the same length and for each valid i A_i = B_i.Vasya wants to perform some of these operations on array A, some on array B, in such a way that arrays A and B become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays A and B equal.InputThe first line contains a single integer n~(1 \le n \le 3 \cdot 10^5) — the length of the first array.The second line contains n integers a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9) — elements of the array A.The third line contains a single integer m~(1 \le m \le 3 \cdot 10^5) — the length of the second array.The fourth line contains m integers b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9) - elements of the array B.OutputPrint a single integer — the maximum length of the resulting arrays after some operations were performed on arrays A and B in such a way that they became equal.If there is no way to make array equal, print "-1".ExamplesInput511 2 3 5 7411 7 3 7Output3Input21 21100Output-1Input31 2 331 2 3Output3
Input511 2 3 5 7411 7 3 7
Output3
1 second
256 megabytes
['greedy', 'two pointers', '*1600']
C. Classy Numberstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call some positive integer classy if its decimal representation contains no more than 3 non-zero digits. For example, numbers 4, 200000, 10203 are classy and numbers 4231, 102306, 7277420000 are not.You are given a segment [L; R]. Count the number of classy integers x such that L \le x \le R.Each testcase contains several segments, for each of them you are required to solve the problem separately.InputThe first line contains a single integer T (1 \le T \le 10^4) — the number of segments in a testcase.Each of the next T lines contains two integers L_i and R_i (1 \le L_i \le R_i \le 10^{18}).OutputPrint T lines — the i-th line should contain the number of classy integers on a segment [L_i; R_i].ExampleInput41 10001024 102465536 65536999999 1000001Output1000102
Input41 10001024 102465536 65536999999 1000001
Output1000102
3 seconds
256 megabytes
['combinatorics', 'dp', '*1900']
B. Diagonal Walking v.2time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMikhail walks on a Cartesian plane. He starts at the point (0, 0), and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point (0, 0), he can go to any of the following points in one move: (1, 0); (1, 1); (0, 1); (-1, 1); (-1, 0); (-1, -1); (0, -1); (1, -1). If Mikhail goes from the point (x1, y1) to the point (x2, y2) in one move, and x1 \ne x2 and y1 \ne y2, then such a move is called a diagonal move.Mikhail has q queries. For the i-th query Mikhail's target is to go to the point (n_i, m_i) from the point (0, 0) in exactly k_i moves. Among all possible movements he want to choose one with the maximum number of diagonal moves. Your task is to find the maximum number of diagonal moves or find that it is impossible to go from the point (0, 0) to the point (n_i, m_i) in k_i moves.Note that Mikhail can visit any point any number of times (even the destination point!).InputThe first line of the input contains one integer q (1 \le q \le 10^4) — the number of queries.Then q lines follow. The i-th of these q lines contains three integers n_i, m_i and k_i (1 \le n_i, m_i, k_i \le 10^{18}) — x-coordinate of the destination point of the query, y-coordinate of the destination point of the query and the number of moves in the query, correspondingly.OutputPrint q integers. The i-th integer should be equal to -1 if Mikhail cannot go from the point (0, 0) to the point (n_i, m_i) in exactly k_i moves described above. Otherwise the i-th integer should be equal to the the maximum number of diagonal moves among all possible movements.ExampleInput32 2 34 3 710 1 9Output16-1NoteOne of the possible answers to the first test case: (0, 0) \to (1, 0) \to (1, 1) \to (2, 2).One of the possible answers to the second test case: (0, 0) \to (0, 1) \to (1, 2) \to (0, 3) \to (1, 4) \to (2, 3) \to (3, 2) \to (4, 3).In the third test case Mikhail cannot reach the point (10, 1) in 9 moves.
Input32 2 34 3 710 1 9
Output16-1
1 second
256 megabytes
['math', '*1600']
A. Function Heighttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of 2n+1 integer points on a Cartesian plane. Points are numbered from 0 to 2n inclusive. Let P_i be the i-th point. The x-coordinate of the point P_i equals i. The y-coordinate of the point P_i equals zero (initially). Thus, initially P_i=(i,0).The given points are vertices of a plot of a piecewise function. The j-th piece of the function is the segment P_{j}P_{j + 1}.In one move you can increase the y-coordinate of any point with odd x-coordinate (i.e. such points are P_1, P_3, \dots, P_{2n-1}) by 1. Note that the corresponding segments also change.For example, the following plot shows a function for n=3 (i.e. number of points is 2\cdot3+1=7) in which we increased the y-coordinate of the point P_1 three times and y-coordinate of the point P_5 one time: Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).Let the height of the plot be the maximum y-coordinate among all initial points in the plot (i.e. points P_0, P_1, \dots, P_{2n}). The height of the plot on the picture above is 3.Your problem is to say which minimum possible height can have the plot consisting of 2n+1 vertices and having an area equal to k. Note that it is unnecessary to minimize the number of moves.It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding 10^{18}.InputThe first line of the input contains two integers n and k (1 \le n, k \le 10^{18}) — the number of vertices in a plot of a piecewise function and the area we need to obtain.OutputPrint one integer — the minimum possible height of a plot consisting of 2n+1 vertices and with an area equals k. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding 10^{18}.ExamplesInput4 3Output1Input4 12Output3Input999999999999999999 999999999999999986Output1NoteOne of the possible answers to the first example: The area of this plot is 3, the height of this plot is 1.There is only one possible answer to the second example: The area of this plot is 12, the height of this plot is 3.
Input4 3
Output1
1 second
256 megabytes
['math', '*1000']
E. Little C Loves 3 IIItime limit per test1 secondmemory limit per test64 megabytesinputstandard inputoutputstandard outputLittle C loves number «3» very much. He loves all things about it.Now he is interested in the following problem:There are two arrays of 2^n intergers a_0,a_1,...,a_{2^n-1} and b_0,b_1,...,b_{2^n-1}.The task is for each i (0 \leq i \leq 2^n-1), to calculate c_i=\sum a_j \cdot b_k (j|k=i and j\&k=0, where "|" denotes bitwise or operation and "\&" denotes bitwise and operation).It's amazing that it can be proved that there are exactly 3^n triples (i,j,k), such that j|k=i, j\&k=0 and 0 \leq i,j,k \leq 2^n-1. So Little C wants to solve this excellent problem (because it's well related to 3) excellently.Help him calculate all c_i. Little C loves 3 very much, so he only want to know each c_i \& 3.InputThe first line contains one integer n (0 \leq n \leq 21).The second line contains 2^n integers in [0,3] without spaces — the i-th of them is a_{i-1}.The third line contains 2^n integers in [0,3] without spaces — the i-th of them is b_{i-1}.OutputPrint one line contains 2^n integers in [0,3] without spaces — the i-th of them is c_{i-1}\&3. (It's obvious that c_{i}\&3 is in [0,3]).ExamplesInput11111Output12Input201233210Output0322
Input11111
Output12
1 second
64 megabytes
['bitmasks', 'dp', 'math', '*3200']
D. Intervals of Intervalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle D is a friend of Little C who loves intervals very much instead of number "3".Now he has n intervals on the number axis, the i-th of which is [a_i,b_i].Only the n intervals can not satisfy him. He defines the value of an interval of intervals [l,r] (1 \leq l \leq r \leq n, l and r are both integers) as the total length of the union of intervals from the l-th to the r-th.He wants to select exactly k different intervals of intervals such that the sum of their values is maximal. Please help him calculate the maximal sum.InputFirst line contains two integers n and k (1 \leq n \leq 3 \cdot 10^5, 1 \leq k \leq \min\{\frac{n(n+1)}{2},10^9\}) — the number of intervals Little D has and the number of intervals of intervals he will select.Each of the next n lines contains two integers a_i and b_i, the i-th line of the n lines describing the i-th interval (1 \leq a_i < b_i \leq 10^9).OutputPrint one integer — the maximal sum of values Little D can get.ExamplesInput2 11 32 4Output3Input3 31 45 73 6Output15NoteFor the first example, Little D will select [1,2], the union of the first interval and the second interval is [1,4], whose length is 3.For the second example, Little D will select [1,2], [2,3] and [1,3], the answer is 5+6+4=15.
Input2 11 32 4
Output3
2 seconds
256 megabytes
['binary search', 'data structures', 'two pointers', '*3500']
C. Region Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in the Kingdom of Autumn, numbered from 1 to n. People can travel between any two cities using n-1 two-directional roads.This year, the government decides to separate the kingdom. There will be regions of different levels. The whole kingdom will be the region of level 1. Each region of i-th level should be separated into several (at least two) regions of i+1-th level, unless i-th level is the last level. Each city should belong to exactly one region of each level and for any two cities in the same region, it should be possible to travel between them passing the cities in the same region only.According to research, for each city i, there is a value a_i, which describes the importance of this city. All regions of the same level should have an equal sum of city importances.Your task is to find how many plans there are to determine the separation of the regions that all the conditions are satisfied. Two plans are considered different if and only if their numbers of levels are different or there exist two cities in the same region of one level in one plan but in different regions of this level in the other plan. Since the answer may be very large, output it modulo 10^9+7.InputThe first line contains one integer n (1 \leq n \leq 10^6) — the number of the cities.The second line contains n integers, the i-th of which is a_i (1 \leq a_i \leq 10^9) — the value of each city.The third line contains n-1 integers, p_1, p_2, \ldots, p_{n-1}; p_i (p_i \leq i) describes a road between cities p_i and i+1.OutputPrint one integer — the number of different plans modulo 10^9+7.ExamplesInput41 1 1 11 2 3Output4Input41 1 1 11 2 2Output2Input41 2 1 21 1 3Output3NoteFor the first example, there are 4 different plans:Plan 1: Level-1: \{1,2,3,4\}.Plan 2: Level-1: \{1,2,3,4\}, Level-2: \{1,2\},\{3,4\}.Plan 3: Level-1: \{1,2,3,4\}, Level-2: \{1\},\{2\},\{3\},\{4\}.Plan 4: Level-1: \{1,2,3,4\}, Level-2: \{1,2\},\{3,4\}, Level-3: \{1\},\{2\},\{3\},\{4\}.For the second example, there are 2 different plans:Plan 1: Level-1: \{1,2,3,4\}.Plan 2: Level-1: \{1,2,3,4\}, Level-2: \{1\},\{2\},\{3\},\{4\}.For the third example, there are 3 different plans:Plan 1: Level-1: \{1,2,3,4\}.Plan 2: Level-1: \{1,2,3,4\}, Level-2: \{1,2\},\{3,4\}.Plan 3: Level-1: \{1,2,3,4\}, Level-2: \{1,3\},\{2\},\{4\}.
Input41 1 1 11 2 3
Output4
2 seconds
256 megabytes
['combinatorics', 'dp', 'number theory', 'trees', '*2700']
B. Little C Loves 3 IItime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle C loves number «3» very much. He loves all things about it.Now he is playing a game on a chessboard of size n \times m. The cell in the x-th row and in the y-th column is called (x,y). Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between which is exactly 3. The Manhattan distance between two cells (x_i,y_i) and (x_j,y_j) is defined as |x_i-x_j|+|y_i-y_j|.He want to place as many chessmen as possible on the chessboard. Please help him find the maximum number of chessmen he can place.InputA single line contains two integers n and m (1 \leq n,m \leq 10^9) — the number of rows and the number of columns of the chessboard.OutputPrint one integer — the maximum number of chessmen Little C can place.ExamplesInput2 2Output0Input3 3Output8NoteIn the first example, the Manhattan distance between any two cells is smaller than 3, so the answer is 0.In the second example, a possible solution is (1,1)(3,2), (1,2)(3,3), (2,1)(1,3), (3,1)(2,3).
Input2 2
Output0
1 second
256 megabytes
['brute force', 'constructive algorithms', 'flows', 'graph matchings', '*2200']
A. Enlarge GCDtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. F has n positive integers, a_1, a_2, \ldots, a_n.He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.Your task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.InputThe first line contains an integer n (2 \leq n \leq 3 \cdot 10^5) — the number of integers Mr. F has.The second line contains n integers, a_1, a_2, \ldots, a_n (1 \leq a_i \leq 1.5 \cdot 10^7).OutputPrint an integer — the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.You should not remove all of the integers.If there is no solution, print «-1» (without quotes).ExamplesInput31 2 4Output1Input46 9 15 30Output2Input31 1 1Output-1NoteIn the first example, the greatest common divisor is 1 in the beginning. You can remove 1 so that the greatest common divisor is enlarged to 2. The answer is 1.In the second example, the greatest common divisor is 3 in the beginning. You can remove 6 and 9 so that the greatest common divisor is enlarged to 15. There is no solution which removes only one integer. So the answer is 2.In the third example, there is no solution to enlarge the greatest common divisor. So the answer is -1.
Input31 2 4
Output1
1 second
256 megabytes
['number theory', '*1800']
G. Chip Gametime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob decided to play one ultimate game. They have n piles, the i-th pile initially contain v_i chips. Alice selects a positive integer a from interval [1, m], and Bob selects a number b the same way. Then the game starts. In her turn, Alice can select any pile containing at least a chips, and remove exactly a chips from it. Similarly, in his turn, Bob can choose any pile with at least b chips, and remove exactly b chips from it. If a player cannot make a move, he or she loses. If both players play optimally, the outcome ultimately depends on the choice of a and b, and on the starting player. Consider a fixed pair (a,b). There are four types of games: Alice wins, regardless of who starts. Bob wins, regardless of who starts. If Alice starts, she wins. If Bob starts, he wins. We say that the first player wins. If Alice starts, Bob wins. If Bob starts, Alice wins. We say that the second player wins. Among all choices of a and b (i.e. for each pair (a, b) such that 1\leq a, b\leq m), determine how many games are won by Alice (regardless of who starts), how many are won by Bob (regardless of who starts), how many are won by the first player, and how many are won by the second player. InputThe first line contains two integers n and m (1 \leq n \leq 100, 1 \leq m \leq 10^5) — the number of piles, and the upper bound on the number of chips allowed to be taken in one turn, respectively. The second line contains n integers v_1, v_2, \dots, v_n (1 \leq v_i \leq 10^{18}) — the starting number of chips in each pile.OutputPrint a single line containing four integers w_a, w_b, w_f, w_s — the number of games won by Alice, Bob, the first player, the second player, respectively. ExamplesInput2 24 5Output1 1 1 1Input2 204 5Output82 82 6 230NoteIn the first sample, there are a total of four choices for the tuple (a,b). a = b = 1: It does not matter from which pile the chips are removed — there are 9 turns to be made, and the first player also makes the last, and hence he wins. a = b = 2: The second player may win by always selecting the same pile as the first before there are 0 and 1 chips in the piles. Since it is impossible to remove 2 chips from any of them, the first player loses. a = 1 and b = 2: Suppose Alice starts. She can win by removing a single chip from the pile with 5 chips and then copying Bob's decision. After the next four turns, the game ends with 1 chip in each pile and Bob unable to make a move. Suppose Bob starts. If he removes two chips from second pile, Alice counters by removing a chip from the first pile. From then on, she can always copy Bob's decision and win. If Bob removes two chips from the first pile in his first turn, Alice can also remove one. As the first pile only has one chip left, Bob is forced to remove two chips from the second pile, leaving 3. Regardless of what Alice does, she wins. Hence, Alice wins no matter who starts. a = 2 and b = 1: This is symmetric with the previous case — hence Bob always wins. In the second sample, a lot of games, e.g. a = 7 and b = 6, end without anybody being able to remove single chip — which counts as a win for the second player. The games won for the first player are (1, 1), (1, 4), (2, 3), (3, 2), (4, 1), and (5, 5).
Input2 24 5
Output1 1 1 1
5 seconds
256 megabytes
['games', '*3500']
F. Boolean Computertime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has a computer that operates on w-bit integers. The computer has n registers for values. The current content of the registers is given as an array a_1, a_2, \ldots, a_n. The computer uses so-called "number gates" to manipulate this data. Each "number gate" takes two registers as inputs and calculates a function of the two values stored in those registers. Note that you can use the same register as both inputs.Each "number gate" is assembled from bit gates. There are six types of bit gates: AND, OR, XOR, NOT AND, NOT OR, and NOT XOR, denoted "A", "O", "X", "a", "o", "x", respectively. Each bit gate takes two bits as input. Its output given the input bits b_1, b_2 is given below: \begin{matrix} b_1 & b_2 & A & O & X & a & o & x \\ 0 & 0 & 0 & 0 & 0 & 1 & 1 & 1 \\ 0 & 1 & 0 & 1 & 1 & 1 & 0 & 0 \\ 1 & 0 & 0 & 1 & 1 & 1 & 0 & 0 \\ 1 & 1 & 1 & 1 & 0 & 0 & 0 & 1 \\ \end{matrix} To build a "number gate", one takes w bit gates and assembles them into an array. A "number gate" takes two w-bit integers x_1 and x_2 as input. The "number gate" splits the integers into w bits and feeds the i-th bit of each input to the i-th bit gate. After that, it assembles the resulting bits again to form an output word. For instance, for 4-bit computer we might have a "number gate" "AXoA" (AND, XOR, NOT OR, AND). For two inputs, 13 = 1101_2 and 10 = 1010_2, this returns 12 = 1100_2, as 1 and 1 is 1, 1 xor 0 is 1, not (0 or 1) is 0, and finally 1 and 0 is 0. You are given a description of m "number gates". For each gate, your goal is to report the number of register pairs for which the "number gate" outputs the number 0. In other words, find the number of ordered pairs (i,j) where 1 \leq i,j \leq n, such that w_k(a_i, a_j) = 0, where w_k is the function computed by the k-th "number gate".InputThe first line contains three integers: w, n, and m~(1 \leq w \leq 12, 1 \leq n \leq 3\cdot 10^4, 1 \leq m \leq 5\cdot 10^4) — the word size, the number of variables, and the number of gates.The second line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i < 2^w) — the value of variables stored in the registers.Each of the next m lines contains a string g_j~(|g_j| = w) with a description of a single gate. Each character of g_j is one of "A", "O", "X", "a", "o", "x".OutputPrint m lines. The i-th line should contain the number of ordered pairs of variables for which the i-th gate returns zero.ExamplesInput4 3 113 10 6AXoAOutput3Input1 7 60 1 1 0 1 0 0AOXaoxOutput40162593324Input6 2 447 12AOXaoxAAaaAAxxxxxxXXXXXXOutput2302Input2 2 22 0xOOxOutput20NoteIn the first test case, the inputs in binary are 1101, 1010, 0110. The pairs that return 0 are (13, 6), (6, 13), and (6, 6). As it was already mentioned in the problem statement, 13 \oplus 10 = 10 \oplus 13 = 12. The other pairs are 13 \oplus 13 = 11, 10 \oplus 10 = 8 and 10 \oplus 6 = 6 \oplus 10 = 4.
Input4 3 113 10 6AXoA
Output3
7 seconds
256 megabytes
['bitmasks', 'brute force', 'fft', 'math', '*2800']
E. Hidden Bipartite Graphtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob has a simple undirected connected graph (without self-loops and multiple edges). He wants to learn whether his graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color) or not. As he is not very good at programming, he asked Alice for help. He does not want to disclose his graph to Alice, but he agreed that Alice can ask him some questions about the graph.The only question that Alice can ask is the following: she sends s — a subset of vertices of the original graph. Bob answers with the number of edges that have both endpoints in s. Since he doesn't want Alice to learn too much about the graph, he allows her to ask no more than 20000 questions. Furthermore, he suspects that Alice might introduce false messages to their communication channel, so when Alice finally tells him whether the graph is bipartite or not, she also needs to provide a proof — either the partitions themselves or a cycle of odd length.Your task is to help Alice to construct the queries, find whether the graph is bipartite. InputThe first line contains a single integer n (1 \leq n \leq 600) — the number of vertices in Bob's graph.InteractionFirst, read an integer n (1\leq n\leq 600) — the number of vertices in Bob's graph.To make a query, print two lines. First of which should be in the format "? k" (1 \leq k \leq n), where k is the size of the set to be queried. The second line should contain k space separated distinct integers s_1, s_2, \dots, s_k (1 \leq s_i \leq n) — the vertices of the queried set.After each query read a single integer m (0 \leq m \leq \frac{n(n-1)}{2}) — the number of edges between the vertices of the set \{s_i\}.You are not allowed to ask more than 20000 queries.If m = -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.After printing a query do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.When you know the answer, you need to print it.The format of the answer depends on whether the graph is bipartite or not.If the graph is bipartite, print two lines. The first should contain the letter "Y" (short for "YES") followed by a space, and then a single integer s (0 \leq s \leq n) — the number of vertices in one of the partitions. Second line should contain s integers a_1, a_2, \dots, a_s — vertices belonging to the first partition. All a_i must be distinct, and all edges in the main graph must have exactly one endpoint in the set \{a_i\}.If the graph is not bipartite, print two lines. The first should contain the letter "N" (short for "NO") followed by a space, and then a single integer l (3 \leq l \leq n) — the length of one simple cycle of odd length. Second line should contain l integers c_1, c_2, \dots, c_l — the vertices along the cycle. It must hold that for all 1 \leq i \leq l, there is an edge \{c_i, c_{(i \mod l)+1}\} in the main graph, and all c_i are distinct.If there are multiple possible answers, you may print any of them.Hacks format For hacks, use the following format:The first line contains two integers n and m~(1 \leq n \leq 600, 0 \leq m \leq \frac{n(n-1)}{2}) — the number of vertices and edges of the graph, respectively.Each of the next m lines contains two integers u_i and v_i~(1 \leq u_i, v_i \leq n) mean that there is an edge between u_i and v_i. There must not be any multiple edges, no loops, and the graph must be connected.For example, you need to use this test to get the first sample:4 44 11 33 22 4ExamplesInput4401110Output? 4 1 2 3 4? 21 2? 21 3? 21 4? 22 4? 23 4Y 21 2Input443Output? 41 4 2 3? 31 2 4N 32 1 4NoteIn the first case, Alice learns that there are 4 edges in the whole graph. Over the course of the next three queries, she learns that vertex 1 has two neighbors: 3 and 4. She then learns that while vertex 2 is adjacent to 4, the vertex 3 isn't adjacent to 4. There is only one option for the remaining edge, and that is (2, 3). This means that the graph is a cycle on four vertices, with (1, 2) being one partition and (3, 4) being the second. Here, it would be also valid to output "3 4" on the second line.In the second case, we also have a graph on four vertices and four edges. In the second query, Alice learns that there are three edges among vertices (1, 2, 4). The only way this could possibly happen is that those form a triangle. As the triangle is not bipartite, Alice can report it as a proof. Notice that she does not learn where the fourth edge is, but she is able to answer Bob correctly anyway.
Input4401110
Output? 4 1 2 3 4? 21 2? 21 3? 21 4? 22 4? 23 4Y 21 2
4 seconds
256 megabytes
['binary search', 'constructive algorithms', 'dfs and similar', 'graphs', 'interactive', '*2800']
D. Divisorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a_1, a_2, \ldots, a_n. Each of a_i has between 3 and 5 divisors. Consider a = \prod a_i — the product of all input integers. Find the number of divisors of a. As this number may be very large, print it modulo prime number 998244353.InputThe first line contains a single integer n (1 \leq n \leq 500) — the number of numbers.Each of the next n lines contains an integer a_i (1 \leq a_i \leq 2\cdot 10^{18}). It is guaranteed that the number of divisors of each a_i is between 3 and 5.OutputPrint a single integer d — the number of divisors of the product a_1 \cdot a_2 \cdot \dots \cdot a_n modulo 998244353.Hacks inputFor hacks, the input needs to be provided in a special format.The first line contains an integer n (1 \leq n \leq 500) — the number of numbers.Each of the next n lines contains a prime factorization of a_i. The line contains an integer k_i (2 \leq k_i \leq 4) — the number of prime factors of a_i and k_i integers p_{i,j} (2 \leq p_{i,j} \leq 2 \cdot 10^{18}) where p_{i,j} is the j-th prime factor of a_i. Before supplying the input to the contestant, a_i = \prod p_{i,j} are calculated. Note that each p_{i,j} must be prime, each computed a_i must satisfy a_i \leq 2\cdot10^{18} and must have between 3 and 5 divisors. The contestant will be given only a_i, and not its prime factorization. For example, you need to use this test to get the first sample:32 3 32 3 52 11 13InteractionFrom the technical side, this problem is interactive. Therefore, do not forget to output end of line and flush the output. Also, do not read more than you need. To flush the output, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.ExamplesInput3915143Output32Input17400840699802997Output4Input8 46060617591286934606066102679989460606976755294346060631164880334606063930903637460606474531924146060639309040214606065559735517Output1920Input34816Output10NoteIn the first case, a = 19305. Its divisors are 1, 3, 5, 9, 11, 13, 15, 27, 33, 39, 45, 55, 65, 99, 117, 135, 143, 165, 195, 297, 351, 429, 495, 585, 715, 1287, 1485, 1755, 2145, 3861, 6435, 19305 — a total of 32.In the second case, a has four divisors: 1, 86028121, 86028157, and 7400840699802997 .In the third case a = 202600445671925364698739061629083877981962069703140268516570564888699 375209477214045102253766023072401557491054453690213483547.In the fourth case, a=512=2^9, so answer equals to 10.
Input3915143
Output32
1 second
256 megabytes
['interactive', 'math', 'number theory', '*2000']
C. Permutation Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long day, Alice and Bob decided to play a little game. The game board consists of n cells in a straight line, numbered from 1 to n, where each cell contains a number a_i between 1 and n. Furthermore, no two cells contain the same number. A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell i to cell j only if the following two conditions are satisfied: the number in the new cell j must be strictly larger than the number in the old cell i (i.e. a_j > a_i), and the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. |i-j|\bmod a_i = 0). Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of numbers.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n). Furthermore, there are no pair of indices i \neq j such that a_i = a_j.OutputPrint s — a string of n characters, where the i-th character represents the outcome of the game if the token is initially placed in the cell i. If Alice wins, then s_i has to be equal to "A"; otherwise, s_i has to be equal to "B". ExamplesInput83 6 5 4 2 7 1 8OutputBAAAABABInput153 11 2 5 10 9 7 13 15 8 4 12 6 1 14OutputABAAAABBBAABAABNoteIn the first sample, if Bob puts the token on the number (not position): 1: Alice can move to any number. She can win by picking 7, from which Bob has no move. 2: Alice can move to 3 and 5. Upon moving to 5, Bob can win by moving to 8. If she chooses 3 instead, she wins, as Bob has only a move to 4, from which Alice can move to 8. 3: Alice can only move to 4, after which Bob wins by moving to 8. 4, 5, or 6: Alice wins by moving to 8. 7, 8: Alice has no move, and hence she loses immediately.
Input83 6 5 4 2 7 1 8
OutputBAAAABAB
1 second
256 megabytes
['brute force', 'dp', 'games', '*1600']
B. Square Differencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice has a lovely piece of cloth. It has the shape of a square with a side of length a centimeters. Bob also wants such piece of cloth. He would prefer a square with a side of length b centimeters (where b < a). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to Bob. Now she is left with an ugly L shaped cloth (see pictures below).Alice would like to know whether the area of her cloth expressed in square centimeters is prime. Could you help her to determine it?InputThe first line contains a number t (1 \leq t \leq 5) — the number of test cases.Each of the next t lines describes the i-th test case. It contains two integers a and b~(1 \leq b < a \leq 10^{11}) — the side length of Alice's square and the side length of the square that Bob wants.OutputPrint t lines, where the i-th line is the answer to the i-th test case. Print "YES" (without quotes) if the area of the remaining piece of cloth is prime, otherwise print "NO".You can print each letter in an arbitrary case (upper or lower).ExampleInput46 516 1361690850361 2477762263034 33OutputYESNONOYESNoteThe figure below depicts the first test case. The blue part corresponds to the piece which belongs to Bob, and the red part is the piece that Alice keeps for herself. The area of the red part is 6^2 - 5^2 = 36 - 25 = 11, which is prime, so the answer is "YES". In the second case, the area is 16^2 - 13^2 = 87, which is divisible by 3. In the third case, the area of the remaining piece is 61690850361^2 - 24777622630^2 = 3191830435068605713421. This number is not prime because 3191830435068605713421 = 36913227731 \cdot 86468472991 .In the last case, the area is 34^2 - 33^2 = 67.
Input46 516 1361690850361 2477762263034 33
OutputYESNONOYES
2 seconds
256 megabytes
['math', 'number theory', '*1100']
A. King Escapetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing chess on a huge chessboard with dimensions n \times n. Alice has a single piece left — a queen, located at (a_x, a_y), while Bob has only the king standing at (b_x, b_y). Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himself — he needs to march his king to (c_x, c_y) in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.Bob will win if he can move his king from (b_x, b_y) to (c_x, c_y) without ever getting in check. Remember that a king can move to any of the 8 adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.InputThe first line contains a single integer n (3 \leq n \leq 1000) — the dimensions of the chessboard.The second line contains two integers a_x and a_y (1 \leq a_x, a_y \leq n) — the coordinates of Alice's queen.The third line contains two integers b_x and b_y (1 \leq b_x, b_y \leq n) — the coordinates of Bob's king.The fourth line contains two integers c_x and c_y (1 \leq c_x, c_y \leq n) — the coordinates of the location that Bob wants to get to.It is guaranteed that Bob's king is currently not in check and the target location is not in check either.Furthermore, the king is not located on the same square as the queen (i.e. a_x \neq b_x or a_y \neq b_y), and the target does coincide neither with the queen's position (i.e. c_x \neq a_x or c_y \neq a_y) nor with the king's position (i.e. c_x \neq b_x or c_y \neq b_y).OutputPrint "YES" (without quotes) if Bob can get from (b_x, b_y) to (c_x, c_y) without ever getting in check, otherwise print "NO".You can print each letter in any case (upper or lower).ExamplesInput84 41 33 1OutputYESInput84 42 31 6OutputNOInput83 51 26 1OutputNONoteIn the diagrams below, the squares controlled by the black queen are marked red, and the target square is marked blue.In the first case, the king can move, for instance, via the squares (2, 3) and (3, 2). Note that the direct route through (2, 2) goes through check. In the second case, the queen watches the fourth rank, and the king has no means of crossing it. In the third case, the queen watches the third file.
Input84 41 33 1
OutputYES
1 second
256 megabytes
['dfs and similar', 'graphs', 'implementation', '*1000']
G. Chatteringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n parrots standing in a circle. Each parrot has a certain level of respect among other parrots, namely r_i. When a parrot with respect level x starts chattering, x neighbours to the right and to the left of it start repeating the same words in 1 second. Their neighbours then start repeating as well, and so on, until all the birds begin to chatter.You are given the respect levels of all parrots. For each parrot answer a question: if this certain parrot starts chattering, how many seconds will pass until all other birds will start repeating it?InputIn the first line of input there is a single integer n, the number of parrots (1 \leq n \leq 10^5).In the next line of input there are n integers r_1, ..., r_n, the respect levels of parrots in order they stand in the circle (1 \leq r_i \leq n).OutputPrint n integers. i-th of them should equal the number of seconds that is needed for all parrots to start chattering if the i-th parrot is the first to start.ExamplesInput 4 1 1 4 1 Output 2 2 1 2 Input 8 1 2 2 1 5 1 3 1 Output 3 3 2 2 1 2 2 3
4 1 1 4 1
2 2 1 2
2 seconds
256 megabytes
['*2900']
F. Vasya and Maximum Matchingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has got a tree consisting of n vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove.A matching in the graph is a subset of its edges such that there is no vertex incident to two (or more) edges from the subset. A maximum matching is a matching such that the number of edges in the subset is maximum possible among all matchings in this graph.Since the answer may be large, output it modulo 998244353.InputThe first line contains one integer n (1 \le n \le 3 \cdot 10^5) — the number of vertices in the tree.Each of the next n − 1 lines contains two integers u and v (1 \le u, v \le n, u \neq v) denoting an edge between vertex u and vertex v. It is guaranteed that these edges form a tree.OutputPrint one integer — the number of ways to delete some (possibly empty) subset of edges so that the maximum matching in the resulting graph is unique. Print the answer modulo 998244353.ExamplesInput41 21 31 4Output4Input41 22 33 4Output6Input1Output1NotePossible ways to delete edges in the first example: delete (1, 2) and (1, 3). delete (1, 2) and (1, 4). delete (1, 3) and (1, 4). delete all edges. Possible ways to delete edges in the second example: delete no edges. delete (1, 2) and (2, 3). delete (1, 2) and (3, 4). delete (2, 3) and (3, 4). delete (2, 3). delete all edges.
Input41 21 31 4
Output4
3 seconds
256 megabytes
['dp', 'trees', '*2400']
E. The Unbearable Lightness of Weightstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a set of n weights. You know that their masses are a_1, a_2, ..., a_n grams, but you don't know which of them has which mass. You can't distinguish the weights.However, your friend does know the mass of each weight. You can ask your friend to give you exactly k weights with the total mass m (both parameters k and m are chosen by you), and your friend will point to any valid subset of weights, if it is possible.You are allowed to make this query only once. Find the maximum possible number of weights you can reveal after this query.InputThe first line contains a single integer n (1 \le n \le 100) — the number of weights.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 100) — the masses of the weights.OutputPrint the maximum number of weights you can learn the masses for after making a single query.ExamplesInput 4 1 4 2 2 Output 2 Input 6 1 2 4 4 4 9 Output 2 NoteIn the first example we can ask for a subset of two weights with total mass being equal to 4, and the only option is to get \{2, 2\}.Another way to obtain the same result is to ask for a subset of two weights with the total mass of 5 and get \{1, 4\}. It is easy to see that the two remaining weights have mass of 2 grams each.In the second example we can ask for a subset of two weights with total mass being 8, and the only answer is \{4, 4\}. We can prove it is not possible to learn masses for three weights in one query, but we won't put the proof here.
4 1 4 2 2
2
1 second
256 megabytes
['dp', 'math', '*2100']
D. Barcelonian Distancetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem we consider a very simplified model of Barcelona city.Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points (x, y) for which ax + by + c = 0.One can walk along streets, including the avenue. You are given two integer points A and B somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to B from A.InputThe first line contains three integers a, b and c (-10^9\leq a, b, c\leq 10^9, at least one of a and b is not zero) representing the Diagonal Avenue.The next line contains four integers x_1, y_1, x_2 and y_2 (-10^9\leq x_1, y_1, x_2, y_2\leq 10^9) denoting the points A = (x_1, y_1) and B = (x_2, y_2).OutputFind the minimum possible travel distance between A and B. 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|)}} \le 10^{-6}.ExamplesInput 1 1 -3 0 3 3 0 Output 4.2426406871 Input 3 1 -9 0 3 3 -1 Output 6.1622776602 NoteThe first example is shown on the left picture while the second example us shown on the right picture below. The avenue is shown with blue, the origin is shown with the black dot.
1 1 -3 0 3 3 0
4.2426406871
1 second
256 megabytes
['geometry', 'implementation', '*1900']
C. Playing Pianotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence a_1, a_2, \ldots, a_n of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.Paul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed.Let's denote the fingers of hand by numbers from 1 to 5. We call a fingering any sequence b_1, \ldots, b_n of fingers numbers. A fingering is convenient if for all 1\leq i \leq n - 1 the following holds: if a_i < a_{i+1} then b_i < b_{i+1}, because otherwise Paul needs to take his hand off the keyboard to play the (i+1)-st note; if a_i > a_{i+1} then b_i > b_{i+1}, because of the same; if a_i = a_{i+1} then b_i\neq b_{i+1}, because using the same finger twice in a row is dumb. Please note that there is \neq, not = between b_i and b_{i+1}. Please provide any convenient fingering or find out that there is none.InputThe first line contains a single integer n (1 \le n \le 10^5) denoting the number of notes.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 2\cdot10^5) denoting the positions of notes on the keyboard.OutputIf there is no convenient fingering, print -1. Otherwise, print n numbers b_1, b_2, \ldots, b_n, each from 1 to 5, denoting a convenient fingering, separated by spaces.ExamplesInput 5 1 1 4 2 2 Output 1 4 5 4 5 Input 7 1 5 7 8 10 3 1 Output 1 2 3 4 5 4 3 Input 19 3 3 7 9 8 8 8 8 7 7 7 7 5 3 3 3 3 8 8 Output 1 3 4 5 4 5 4 5 4 5 4 5 4 3 5 4 3 5 4 NoteThe third sample test is kinda "Non stop" song by Reflex.
5 1 1 4 2 2
1 4 5 4 5
1 second
256 megabytes
['constructive algorithms', 'dp', '*1700']
B. Personalized Cuptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt many competitions that have a word «cup» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.The nameplate is to be rectangular and the text on it will be printed as a table of several rows and columns. Having some measurements done, the organizers have found out that the number a of rows cannot be greater than 5 while the number b of columns cannot exceed 20. Every cell of the table will contain either an asterisk («*») or a letter of user's handle.Furthermore, the organizers want the rows of the table to be uniform, which means that the number of asterisks used in different rows should differ by at most one (i.e. you can't have two asterisks in the first row and none in the second). The main goal, however, is to obtain the winner's handle precisely when reading the table from top to bottom and from left to right in every row (skipping asterisks).The organizers want for the nameplate to have as few rows as possible and among all valid tables with the minimum number of rows they want to choose the one that has the minimum number of columns.The winner is not yet determined so your task is to write a program that, given a certain handle, generates the necessary table.InputThe only line contains one string s (1 \le |s| \le 100), comprised of uppercase and lowercase Latin letters,  — the handle of the winner.OutputIn the first line output the minimum number a of rows in the table and the minimum number b of columns in an optimal table with rows.The following a lines should contain b characters each  — any valid table.ExamplesInput tourist Output 1 7 tourist Input MyNameIsLifeIAmForeverByYourSideMyNameIsLife Output 3 15 MyNameIsLifeIAm ForeverByYourSi deMyNameIsL*ife
tourist
1 7 tourist
1 second
256 megabytes
['*1200']
A. Kitchen Utensilstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe king's birthday dinner was attended by k guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.All types of utensils in the kingdom are numbered from 1 to 100. It is known that every set of utensils is the same and consist of different types of utensils, although every particular type may appear in the set at most once. For example, a valid set of utensils can be composed of one fork, one spoon and one knife.After the dinner was over and the guests were dismissed, the king wondered what minimum possible number of utensils could be stolen. Unfortunately, the king has forgotten how many dishes have been served for every guest but he knows the list of all the utensils left after the dinner. Your task is to find the minimum possible number of stolen utensils.InputThe first line contains two integer numbers n and k (1 \le n \le 100, 1 \le k \le 100)  — the number of kitchen utensils remaining after the dinner and the number of guests correspondingly.The next line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 100)  — the types of the utensils remaining. Equal values stand for identical utensils while different values stand for different utensils.OutputOutput a single value — the minimum number of utensils that could be stolen by the guests.ExamplesInput 5 2 1 2 2 1 3 Output 1 Input 10 3 1 3 3 1 3 5 5 5 5 100 Output 14 NoteIn the first example it is clear that at least one utensil of type 3 has been stolen, since there are two guests and only one such utensil. But it is also possible that every person received only one dish and there were only six utensils in total, when every person got a set (1, 2, 3) of utensils. Therefore, the answer is 1.One can show that in the second example at least 2 dishes should have been served for every guest, so the number of utensils should be at least 24: every set contains 4 utensils and every one of the 3 guests gets two such sets. Therefore, at least 14 objects have been stolen. Please note that utensils of some types (for example, of types 2 and 4 in this example) may be not present in the set served for dishes.
5 2 1 2 2 1 3
1
1 second
256 megabytes
['*900']
F. Familiar Operationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers a and b. There are two possible operations: multiply one of the numbers by some prime p; divide one of the numbers on its prime factor p. What is the minimum number of operations required to obtain two integers having the same number of divisors? You are given several such pairs, you need to find the answer for each of them.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of pairs of integers for which you are to find the answer.Each of the next t lines contain two integers a_i and b_i (1 \le a_i, b_i \le 10^6).OutputOutput t lines — the i-th of them should contain the answer for the pair a_i, b_i.ExampleInput89 10100 17220 7017 194 1832 20100 32224 385Output13101011NoteThese are the numbers with equal number of divisors, which are optimal to obtain in the sample test case: (27, 10), 4 divisors (100, 1156), 9 divisors (220, 140), 12 divisors (17, 19), 2 divisors (12, 18), 6 divisors (50, 32), 6 divisors (224, 1925), 12 divisors Note that there can be several optimal pairs of numbers.
Input89 10100 17220 7017 194 1832 20100 32224 385
Output13101011
2 seconds
256 megabytes
['brute force', 'graphs', 'math', '*2800']
E. Triple Flipstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n that consists of zeros and ones.You can perform the following operation multiple times. The operation consists of two steps: Choose three integers 1 \le x < y < z \le n, that form an arithmetic progression (y - x = z - y). Flip the values a_x, a_y, a_z (i.e. change 1 to 0, change 0 to 1). Determine if it is possible to make all elements of the array equal to zero. If yes, print the operations that lead the the all-zero state. Your solution should not contain more than (\lfloor \frac{n}{3} \rfloor + 12) operations. Here \lfloor q \rfloor denotes the number q rounded down. We can show that it is possible to make all elements equal to zero in no more than this number of operations whenever it is possible to do so at all.InputThe first line contains a single integer n (3 \le n \le 10^5) — the length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 1) — the elements of the array.OutputPrint "YES" (without quotes) if the answer exists, otherwise print "NO" (without quotes). You can print each letter in any case (upper or lower).If there is an answer, in the second line print an integer m (0 \le m \le (\lfloor \frac{n}{3} \rfloor + 12)) — the number of operations in your answer.After that in (i + 2)-th line print the i-th operations — the integers x_i, y_i, z_i. You can print them in arbitrary order.ExamplesInput51 1 0 1 1OutputYES21 3 52 3 4Input30 1 0OutputNONoteIn the first sample the shown output corresponds to the following solution: 1 1 0 1 1 (initial state); 0 1 1 1 0 (the flipped positions are the first, the third and the fifth elements); 0 0 0 0 0 (the flipped positions are the second, the third and the fourth elements). Other answers are also possible. In this test the number of operations should not exceed \lfloor \frac{5}{3} \rfloor + 12 = 1 + 12 = 13.In the second sample the only available operation is to flip all the elements. This way it is only possible to obtain the arrays 0 1 0 and 1 0 1, but it is impossible to make all elements equal to zero.
Input51 1 0 1 1
OutputYES21 3 52 3 4
1 second
256 megabytes
['constructive algorithms', '*2600']
D. Minimum pathtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix of size n \times n filled with lowercase English letters. You can change no more than k letters in this matrix.Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is 2n - 1.Find the lexicographically smallest string that can be associated with a path after changing letters in at most k cells of the matrix.A string a is lexicographically smaller than a string b, if the first different letter in a and b is smaller in a.InputThe first line contains two integers n and k (1 \le n \le 2000, 0 \le k \le n^2) — the size of the matrix and the number of letters you can change.Each of the next n lines contains a string of n lowercase English letters denoting one row of the matrix.OutputOutput the lexicographically smallest string that can be associated with some valid path after changing no more than k letters in the matrix.ExamplesInput4 2abcdbcdebcadbcdeOutputaaabcdeInput5 3bwwwzhrhdhsepspsqfafajbvwOutputaaaepfafwInput7 6ypnxnnppnxonpmnxanpouxnnpmudnhtdudunpmuduhpmutsnzOutputaaaaaaadudsnzNoteIn the first sample test case it is possible to change letters 'b' in cells (2, 1) and (3, 1) to 'a', then the minimum path contains cells (1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4). The first coordinate corresponds to the row and the second coordinate corresponds to the column.
Input4 2abcdbcdebcadbcde
Outputaaabcde
1.5 seconds
256 megabytes
['greedy', '*1900']
C. Cram Timetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.Lesha knows that today he can study for at most a hours, and he will have b hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number k in k hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.Thus, the student has to fully read several lecture notes today, spending at most a hours in total, and fully read several lecture notes tomorrow, spending at most b hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?InputThe only line of input contains two integers a and b (0 \leq a, b \leq 10^{9}) — the number of hours Lesha has today and the number of hours Lesha has tomorrow.OutputIn the first line print a single integer n (0 \leq n \leq a) — the number of lecture notes Lesha has to read in the first day. In the second line print n distinct integers p_1, p_2, \ldots, p_n (1 \leq p_i \leq a), the sum of all p_i should not exceed a.In the third line print a single integer m (0 \leq m \leq b) — the number of lecture notes Lesha has to read in the second day. In the fourth line print m distinct integers q_1, q_2, \ldots, q_m (1 \leq q_i \leq b), the sum of all q_i should not exceed b.All integers p_i and q_i should be distinct. The sum n + m should be largest possible.ExamplesInput3 3Output13 22 1 Input9 12Output23 641 2 4 5NoteIn the first example Lesha can read the third note in 3 hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending 3 hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.In the second example Lesha should read the third and the sixth notes in the first day, spending 9 hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending 12 hours in total.
Input3 3
Output13 22 1
1 second
256 megabytes
['greedy', '*1600']
B. Curiosity Has No Limitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Masha came to math classes today, she saw two integer sequences of length n - 1 on the blackboard. Let's denote the elements of the first sequence as a_i (0 \le a_i \le 3), and the elements of the second sequence as b_i (0 \le b_i \le 3).Masha became interested if or not there is an integer sequence of length n, which elements we will denote as t_i (0 \le t_i \le 3), so that for every i (1 \le i \le n - 1) the following is true: a_i = t_i | t_{i + 1} (where | denotes the bitwise OR operation) and b_i = t_i \& t_{i + 1} (where \& denotes the bitwise AND operation). The question appeared to be too difficult for Masha, so now she asked you to check whether such a sequence t_i of length n exists. If it exists, find such a sequence. If there are multiple such sequences, find any of them.InputThe first line contains a single integer n (2 \le n \le 10^5) — the length of the sequence t_i. The second line contains n - 1 integers a_1, a_2, \ldots, a_{n-1} (0 \le a_i \le 3) — the first sequence on the blackboard.The third line contains n - 1 integers b_1, b_2, \ldots, b_{n-1} (0 \le b_i \le 3) — the second sequence on the blackboard.OutputIn the first line print "YES" (without quotes), if there is a sequence t_i that satisfies the conditions from the statements, and "NO" (without quotes), if there is no such sequence.If there is such a sequence, on the second line print n integers t_1, t_2, \ldots, t_n (0 \le t_i \le 3) — the sequence that satisfies the statements conditions.If there are multiple answers, print any of them.ExamplesInput43 3 21 2 0OutputYES1 3 2 0 Input31 33 2OutputNONoteIn the first example it's easy to see that the sequence from output satisfies the given conditions: t_1 | t_2 = (01_2) | (11_2) = (11_2) = 3 = a_1 and t_1 \& t_2 = (01_2) \& (11_2) = (01_2) = 1 = b_1; t_2 | t_3 = (11_2) | (10_2) = (11_2) = 3 = a_2 and t_2 \& t_3 = (11_2) \& (10_2) = (10_2) = 2 = b_2; t_3 | t_4 = (10_2) | (00_2) = (10_2) = 2 = a_3 and t_3 \& t_4 = (10_2) \& (00_2) = (00_2) = 0 = b_3. In the second example there is no such sequence.
Input43 3 21 2 0
OutputYES1 3 2 0
1 second
256 megabytes
['*1500']
A. Golden Platetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a plate and you want to add some gilding to it. The plate is a rectangle that we split into w\times h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one — 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings should consist of all bordering cells on the inner rectangle of size (w - 4(i - 1))\times(h - 4(i - 1)). The picture corresponds to the third example. Your task is to compute the number of cells to be gilded.InputThe only line contains three integers w, h and k (3 \le w, h \le 100, 1 \le k \le \left\lfloor \frac{min(n, m) + 1}{4}\right\rfloor, where \lfloor x \rfloor denotes the number x rounded down) — the number of rows, columns and the number of rings, respectively.OutputPrint a single positive integer — the number of cells to be gilded.ExamplesInput3 3 1Output8Input7 9 1Output28Input7 9 2Output40NoteThe first example is shown on the picture below. The second example is shown on the picture below. The third example is shown in the problem description.
Input3 3 1
Output8
1 second
256 megabytes
['implementation', 'math', '*800']
G. Linear Congruential Generatortime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tuple generator f^{(k)} = (f_1^{(k)}, f_2^{(k)}, \dots, f_n^{(k)}), where f_i^{(k)} = (a_i \cdot f_i^{(k - 1)} + b_i) \bmod p_i and f^{(0)} = (x_1, x_2, \dots, x_n). Here x \bmod y denotes the remainder of x when divided by y. All p_i are primes.One can see that with fixed sequences x_i, y_i, a_i the tuples f^{(k)} starting from some index will repeat tuples with smaller indices. Calculate the maximum number of different tuples (from all f^{(k)} for k \ge 0) that can be produced by this generator, if x_i, a_i, b_i are integers in the range [0, p_i - 1] and can be chosen arbitrary. The answer can be large, so print the remainder it gives when divided by 10^9 + 7InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in the tuple.The second line contains n space separated prime numbers — the modules p_1, p_2, \ldots, p_n (2 \le p_i \le 2 \cdot 10^6).OutputPrint one integer — the maximum number of different tuples modulo 10^9 + 7.ExamplesInput42 3 5 7Output210Input35 3 3Output30NoteIn the first example we can choose next parameters: a = [1, 1, 1, 1], b = [1, 1, 1, 1], x = [0, 0, 0, 0], then f_i^{(k)} = k \bmod p_i.In the second example we can choose next parameters: a = [1, 1, 2], b = [1, 1, 0], x = [0, 0, 1].
Input42 3 5 7
Output210
2 seconds
512 megabytes
['number theory', '*2900']
F. Putting Boxes Togethertime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an infinite line consisting of cells. There are n boxes in some cells of this line. The i-th box stands in the cell a_i and has weight w_i. All a_i are distinct, moreover, a_{i - 1} < a_i holds for all valid i.You would like to put together some boxes. Putting together boxes with indices in the segment [l, r] means that you will move some of them in such a way that their positions will form some segment [x, x + (r - l)].In one step you can move any box to a neighboring cell if it isn't occupied by another box (i.e. you can choose i and change a_i by 1, all positions should remain distinct). You spend w_i units of energy moving the box i by one cell. You can move any box any number of times, in arbitrary order.Sometimes weights of some boxes change, so you have queries of two types: id nw — weight w_{id} of the box id becomes nw. l r — you should compute the minimum total energy needed to put together boxes with indices in [l, r]. Since the answer can be rather big, print the remainder it gives when divided by 1000\,000\,007 = 10^9 + 7. Note that the boxes are not moved during the query, you only should compute the answer. Note that you should minimize the answer, not its remainder modulo 10^9 + 7. So if you have two possible answers 2 \cdot 10^9 + 13 and 2 \cdot 10^9 + 14, you should choose the first one and print 10^9 + 6, even though the remainder of the second answer is 0.InputThe first line contains two integers n and q (1 \le n, q \le 2 \cdot 10^5) — the number of boxes and the number of queries.The second line contains n integers a_1, a_2, \dots a_n (1 \le a_i \le 10^9) — the positions of the boxes. All a_i are distinct, a_{i - 1} < a_i holds for all valid i.The third line contains n integers w_1, w_2, \dots w_n (1 \le w_i \le 10^9) — the initial weights of the boxes.Next q lines describe queries, one query per line.Each query is described in a single line, containing two integers x and y. If x < 0, then this query is of the first type, where id = -x, nw = y (1 \le id \le n, 1 \le nw \le 10^9). If x > 0, then the query is of the second type, where l = x and r = y (1 \le l_j \le r_j \le n). x can not be equal to 0.OutputFor each query of the second type print the answer on a separate line. Since answer can be large, print the remainder it gives when divided by 1000\,000\,007 = 10^9 + 7.ExampleInput5 81 2 6 7 101 1 1 1 21 11 51 33 5-3 5-1 101 42 5Output01034187NoteLet's go through queries of the example: 1\ 1 — there is only one box so we don't need to move anything. 1\ 5 — we can move boxes to segment [4, 8]: 1 \cdot |1 - 4| + 1 \cdot |2 - 5| + 1 \cdot |6 - 6| + 1 \cdot |7 - 7| + 2 \cdot |10 - 8| = 10. 1\ 3 — we can move boxes to segment [1, 3]. 3\ 5 — we can move boxes to segment [7, 9]. -3\ 5 — w_3 is changed from 1 to 5. -1\ 10 — w_1 is changed from 1 to 10. The weights are now equal to w = [10, 1, 5, 1, 2]. 1\ 4 — we can move boxes to segment [1, 4]. 2\ 5 — we can move boxes to segment [5, 8].
Input5 81 2 6 7 101 1 1 1 21 11 51 33 5-3 5-1 101 42 5
Output01034187
2.5 seconds
256 megabytes
['data structures', '*2500']
E. Vasya and Good Sequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a sequence a consisting of n integers a_1, a_2, \dots, a_n. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number 6 (\dots 00000000110_2) into 3 (\dots 00000000011_2), 12 (\dots 000000001100_2), 1026 (\dots 10000000010_2) and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence.Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with bitwise exclusive or of all elements equal to 0.For the given sequence a_1, a_2, \ldots, a_n Vasya'd like to calculate number of integer pairs (l, r) such that 1 \le l \le r \le n and sequence a_l, a_{l + 1}, \dots, a_r is good.InputThe first line contains a single integer n (1 \le n \le 3 \cdot 10^5) — length of the sequence.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{18}) — the sequence a.OutputPrint one integer — the number of pairs (l, r) such that 1 \le l \le r \le n and the sequence a_l, a_{l + 1}, \dots, a_r is good.ExamplesInput36 7 14Output2Input41 2 1 16Output4NoteIn the first example pairs (2, 3) and (1, 3) are valid. Pair (2, 3) is valid since a_2 = 7 \rightarrow 11, a_3 = 14 \rightarrow 11 and 11 \oplus 11 = 0, where \oplus — bitwise exclusive or. Pair (1, 3) is valid since a_1 = 6 \rightarrow 3, a_2 = 7 \rightarrow 13, a_3 = 14 \rightarrow 14 and 3 \oplus 13 \oplus 14 = 0.In the second example pairs (1, 2), (2, 3), (3, 4) and (1, 4) are valid.
Input36 7 14
Output2
2 seconds
256 megabytes
['bitmasks', 'dp', '*2000']
D. Vasya and Triangletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 \le x_1, x_2, x_3 \le n, 0 \le y_1, y_2, y_3 \le m and the area of the triangle formed by these points is equal to \frac{nm}{k}.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.InputThe single line contains three integers n, m, k (1\le n, m \le 10^9, 2 \le k \le 10^9).OutputIf there are no such points, print "NO".Otherwise print "YES" in the first line. The next three lines should contain integers x_i, y_i — coordinates of the points, one point per line. If there are multiple solutions, print any of them.You can print each letter in any case (upper or lower).ExamplesInput4 3 3OutputYES1 02 34 1Input4 4 7OutputNONoteIn the first example area of the triangle should be equal to \frac{nm}{k} = 4. The triangle mentioned in the output is pictured below: In the second example there is no triangle with area \frac{nm}{k} = \frac{16}{7}.
Input4 3 3
OutputYES1 02 34 1
1 second
256 megabytes
['geometry', 'number theory', '*1800']
C. Vasya and Golden Tickettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Vasya found a golden ticket — a sequence which consists of n digits a_1a_2\dots a_n. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket 350178 is lucky since it can be divided into three segments 350, 17 and 8: 3+5+0=1+7=8. Note that each digit of sequence should belong to exactly one segment.Help Vasya! Tell him if the golden ticket he found is lucky or not.InputThe first line contains one integer n (2 \le n \le 100) — the number of digits in the ticket.The second line contains n digits a_1 a_2 \dots a_n (0 \le a_i \le 9) — the golden ticket. Digits are printed without spaces.OutputIf the golden ticket is lucky then print "YES", otherwise print "NO" (both case insensitive).ExamplesInput573452OutputYESInput41248OutputNONoteIn the first example the ticket can be divided into 7, 34 and 52: 7=3+4=5+2.In the second example it is impossible to divide ticket into segments with equal sum.
Input573452
OutputYES
1 second
256 megabytes
['implementation', '*1300']
B. Vasya and Cornfieldtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).InputThe first line contains two integers n and d (1 \le d < n \le 100).The second line contains a single integer m (1 \le m \le 100) — the number of grasshoppers.The i-th of the next m lines contains two integers x_i and y_i (0 \le x_i, y_i \le n) — position of the i-th grasshopper.OutputPrint m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".You can print each letter in any case (upper or lower).ExamplesInput7 242 44 16 34 5OutputYESNONOYESInput8 744 42 88 16 1OutputYESNOYESYESNoteThe cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
Input7 242 44 16 34 5
OutputYESNONOYES
1 second
256 megabytes
['geometry', '*1100']
A. In Search of an Easy Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard.If at least one of these n people has answered that the problem is hard, the coordinator decides to change the problem. For the given responses, check if the problem is easy enough.InputThe first line contains a single integer n (1 \le n \le 100) — the number of people who were asked to give their opinions.The second line contains n integers, each integer is either 0 or 1. If i-th integer is 0, then i-th person thinks that the problem is easy; if it is 1, then i-th person thinks that the problem is hard.OutputPrint one word: "EASY" if the problem is easy according to all responses, or "HARD" if there is at least one person who thinks the problem is hard. You may print every letter in any register: "EASY", "easy", "EaSY" and "eAsY" all will be processed correctly.ExamplesInput30 0 1OutputHARDInput10OutputEASYNoteIn the first example the third person says it's a hard problem, so it should be replaced.In the second example the problem easy for the only person, so it doesn't have to be replaced.
Input30 0 1
OutputHARD
1 second
256 megabytes
['implementation', '*800']
F. Multicolored Markerstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an infinite board of square tiles. Initially all tiles are white.Vova has a red marker and a blue marker. Red marker can color a tiles. Blue marker can color b tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly a red tiles and exactly b blue tiles across the board.Vova wants to color such a set of tiles that: they would form a rectangle, consisting of exactly a+b colored tiles; all tiles of at least one color would also form a rectangle. Here are some examples of correct colorings: Here are some examples of incorrect colorings: Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?It is guaranteed that there exists at least one correct coloring.InputA single line contains two integers a and b (1 \le a, b \le 10^{14}) — the number of tiles red marker should color and the number of tiles blue marker should color, respectively.OutputPrint a single integer — the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly a tiles red and exactly b tiles blue.It is guaranteed that there exists at least one correct coloring.ExamplesInput4 4Output12Input3 9Output14Input9 3Output14Input3 6Output12Input506 2708Output3218NoteThe first four examples correspond to the first picture of the statement.Note that for there exist multiple correct colorings for all of the examples.In the first example you can also make a rectangle with sides 1 and 8, though its perimeter will be 18 which is greater than 8.In the second example you can make the same resulting rectangle with sides 3 and 4, but red tiles will form the rectangle with sides 1 and 3 and blue tiles will form the rectangle with sides 3 and 3.
Input4 4
Output12
3 seconds
256 megabytes
['binary search', 'brute force', 'math', 'number theory', '*2000']
E. Tree with Small Distancestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loops and multiple edges.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.The following n - 1 lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 \le u_i, v_i \le n). It is guaranteed that the given edges form a tree. It is guaranteed that there are no loops and multiple edges in the given edges.OutputPrint a single integer — the minimum number of edges you have to add in order to make the shortest distance from the vertex 1 to any other vertex at most 2. Note that you are not allowed to add loops and multiple edges.ExamplesInput71 22 32 44 54 65 7Output2Input71 21 32 42 53 61 7Output0Input71 22 33 43 53 63 7Output1NoteThe tree corresponding to the first example: The answer is 2, some of the possible answers are the following: [(1, 5), (1, 6)], [(1, 4), (1, 7)], [(1, 6), (1, 7)].The tree corresponding to the second example: The answer is 0.The tree corresponding to the third example: The answer is 1, only one possible way to reach it is to add the edge (1, 3).
Input71 22 32 44 54 65 7
Output2
1 second
256 megabytes
['dp', 'graphs', 'greedy', '*2100']
D. Concatenated Multiplestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a, consisting of n positive integers.Let's call a concatenation of numbers x and y the number that is obtained by writing down numbers x and y one right after another without changing the order. For example, a concatenation of numbers 12 and 3456 is a number 123456.Count the number of ordered pairs of positions (i, j) (i \neq j) in array a such that the concatenation of a_i and a_j is divisible by k.InputThe first line contains two integers n and k (1 \le n \le 2 \cdot 10^5, 2 \le k \le 10^9).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).OutputPrint a single integer — the number of ordered pairs of positions (i, j) (i \neq j) in array a such that the concatenation of a_i and a_j is divisible by k.ExamplesInput6 1145 1 10 12 11 7Output7Input4 22 78 4 10Output12Input5 23 7 19 3 3Output0NoteIn the first example pairs (1, 2), (1, 3), (2, 3), (3, 1), (3, 4), (4, 2), (4, 3) suffice. They produce numbers 451, 4510, 110, 1045, 1012, 121, 1210, respectively, each of them is divisible by 11.In the second example all n(n - 1) pairs suffice.In the third example no pair is sufficient.
Input6 1145 1 10 12 11 7
Output7
2 seconds
256 megabytes
['implementation', 'math', '*1900']
C. Maximal Intersectiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or 0 in case the intersection is an empty set.For example, the intersection of segments [1;5] and [3;10] is [3;5] (length 2), the intersection of segments [1;5] and [5;7] is [5;5] (length 0) and the intersection of segments [1;5] and [6;6] is an empty set (length 0).Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining (n - 1) segments has the maximal possible length.InputThe first line contains a single integer n (2 \le n \le 3 \cdot 10^5) — the number of segments in the sequence.Each of the next n lines contains two integers l_i and r_i (0 \le l_i \le r_i \le 10^9) — the description of the i-th segment.OutputPrint a single integer — the maximal possible length of the intersection of (n - 1) remaining segments after you remove exactly one segment from the sequence.ExamplesInput41 32 60 43 3Output1Input52 61 30 41 200 4Output2Input34 51 29 20Output0Input23 101 5Output7NoteIn the first example you should remove the segment [3;3], the intersection will become [2;3] (length 1). Removing any other segment will result in the intersection [3;3] (length 0).In the second example you should remove the segment [1;3] or segment [2;6], the intersection will become [2;4] (length 2) or [1;3] (length 2), respectively. Removing any other segment will result in the intersection [2;3] (length 1).In the third example the intersection will become an empty set no matter the segment you remove.In the fourth example you will get the intersection [3;10] (length 7) if you remove the segment [1;5] or the intersection [1;5] (length 4) if you remove the segment [3;10].
Input41 32 60 43 3
Output1
3 seconds
256 megabytes
['greedy', 'math', 'sortings', '*1600']
B. Creating the Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a problemset consisting of n problems. The difficulty of the i-th problem is a_i. It is guaranteed that all difficulties are distinct and are given in the increasing order.You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let a_{i_1}, a_{i_2}, \dots, a_{i_p} be the difficulties of the selected problems in increasing order. Then for each j from 1 to p-1 a_{i_{j + 1}} \le a_{i_j} \cdot 2 should hold. It means that the contest consisting of only one problem is always valid.Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of problems in the problemset.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — difficulties of the problems. It is guaranteed that difficulties of the problems are distinct and are given in the increasing order.OutputPrint a single integer — maximum number of problems in the contest satisfying the condition in the problem statement.ExamplesInput101 2 5 6 7 10 21 23 24 49Output4Input52 10 50 110 250Output1Input64 7 12 100 150 199Output3NoteDescription of the first example: there are 10 valid contests consisting of 1 problem, 10 valid contests consisting of 2 problems ([1, 2], [5, 6], [5, 7], [5, 10], [6, 7], [6, 10], [7, 10], [21, 23], [21, 24], [23, 24]), 5 valid contests consisting of 3 problems ([5, 6, 7], [5, 6, 10], [5, 7, 10], [6, 7, 10], [21, 23, 24]) and a single valid contest consisting of 4 problems ([5, 6, 7, 10]).In the second example all the valid contests consist of 1 problem.In the third example are two contests consisting of 3 problems: [4, 7, 12] and [100, 150, 199].
Input101 2 5 6 7 10 21 23 24 49
Output4
1 second
256 megabytes
['dp', 'greedy', 'math', '*1200']
A. Many Equal Substringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string t consisting of n lowercase Latin letters and an integer number k.Let's define a substring of some string s with indices from l to r as s[l \dots r].Your task is to construct such string s of minimum possible length that there are exactly k positions i such that s[i \dots i + n - 1] = t. In other words, your task is to construct such string s of minimum possible length that there are exactly k substrings of s equal to t.It is guaranteed that the answer is always unique.InputThe first line of the input contains two integers n and k (1 \le n, k \le 50) — the length of the string t and the number of substrings.The second line of the input contains the string t consisting of exactly n lowercase Latin letters.OutputPrint such string s of minimum possible length that there are exactly k substrings of s equal to t.It is guaranteed that the answer is always unique.ExamplesInput3 4abaOutputababababaInput3 2catOutputcatcat
Input3 4aba
Outputababababa
1 second
256 megabytes
['implementation', 'strings', '*1300']
H. Make Squaretime limit per test7 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputWe call an array b_1, b_2, \ldots, b_m good, if there exist two indices i < j such that b_i \cdot b_j is a perfect square.Given an array b_1, b_2, \ldots, b_m, in one action you can perform one of the following: multiply any element b_i by any prime p; divide any element b_i by prime p, if b_i is divisible by p. Let f(b_1, b_2, \ldots, b_m) be the minimum number of actions needed to make the array b good.You are given an array of n integers a_1, a_2, \ldots, a_n and q queries of the form l_i, r_i. For each query output f(a_{l_i}, a_{l_i + 1}, \ldots, a_{r_i}).InputThe first line contains two integers n and q (2 \le n \le 194\,598, 1 \le q \le 1\,049\,658) — the length of the array and the number of queries.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 5\,032\,107) — the elements of the array.Each of the next q lines contains two integers l_i and r_i (1 \le l_i < r_i \le n) — the parameters of a query.OutputOutput q lines — the answers for each query in the order they are given in the input.ExampleInput10 1034 37 28 16 44 36 43 50 22 131 34 86 109 103 108 95 61 41 72 6Output2013011100NoteIn the first query of the first sample you can multiply second number by 7 to get 259 and multiply the third one by 37 to get 1036. Then a_2 \cdot a_3 = 268\,324 = 518^2.In the second query subarray is already good because a_4 \cdot a_6 = 24^2.In the third query you can divide 50 by 2 to get 25. Then a_6 \cdot a_8 = 30^2.
Input10 1034 37 28 16 44 36 43 50 22 131 34 86 109 103 108 95 61 41 72 6
Output2013011100
7 seconds
1024 megabytes
['math', '*2900']
G. Guess the numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is interactive.You should guess hidden number x which is between 1 and M = 10004205361450474, inclusive.You could use up to 5 queries.In each query, you can output an increasing sequence of k \leq x integers, each between 1 and M, inclusive, and you will obtain one of the following as an answer: either the hidden number belongs to your query sequence, in this case you immediately win; or you will be given where the hidden number is located with respect to your query sequence, that is, either it is less than all numbers from the sequence, greater than all numbers from the sequence, or you will be given such an i that the hidden number x is between the i-th and the (i+1)-st numbers of your sequence. See the interaction section for clarity.Be aware that the interactor is adaptive, i.e. the hidden number can depend on queries the solution makes. However, it is guaranteed that for any solution the interactor works non-distinguishable from the situation when the hidden number is fixed beforehand.Hacks are allowed only with fixed hidden number. A hack is represented by a single integer between 1 and M. In all pretests the hidden number is fixed as well.InteractionYou can make up to 5 queries. To make a query print a number k (1 \le k \le 10^4) and then an increasing sequence t_0 < t_1 < \ldots < t_{k-1} of k numbers, each between 1 and M, inclusive. If k > x, you lose.You get one integer as a response. If it is -2, it means you made an invalid query or you lost. Exit immediately after receiving -2 and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream. If it is -1, you guessed the number and should terminate too. Otherwise you get a number i between 0 and k, inclusive, denoting where the hidden number is, with respect to the printed numbers. If i = 0, then x < t_0. If i = k, then t_{k-1} < x. Otherwise t_{i-1} < x < t_i. After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.ExampleInput 20-1Output2 2 32 20 303 5 7 9NoteIn the first example the number 5 is hidden.
Input 20-1
Output2 2 32 20 303 5 7 9
2 seconds
256 megabytes
['dp', 'interactive', '*3000']
F. Make Symmetricaltime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a set of points A, initially it is empty. There are three types of queries: Insert a point (x_i, y_i) to A. It is guaranteed that this point does not belong to A at this moment. Remove a point (x_i, y_i) from A. It is guaranteed that this point belongs to A at this moment. Given a point (x_i, y_i), calculate the minimum number of points required to add to A to make A symmetrical with respect to the line containing points (0, 0) and (x_i, y_i). Note that these points are not actually added to A, i.e. these queries are independent from each other. InputThe first line contains a single integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Each of the following q lines describes a query and contains three integers t_i, x_i and y_i ( t_i \in \{1, 2, 3\}, 1 \le x_i, y_i \le 112\,904) — the type of the query and the coordinates of the point. Type 1 is addition of the point, type 2 is removal of the point, type 3 is the query to compute the minimum number of points required to make A symmetrical. It is guaranteed that there are no more than 10^5 queries of type 3 and no more than 10^5 queries having type 1 or 2.OutputFor each query of the third type output a line with a single integer — the answer to this query.ExamplesInput121 1 61 6 11 5 51 2 33 4 41 3 23 7 72 2 32 6 13 8 82 5 53 1 1Output1022Input61 1 23 1 11 1 13 2 22 1 13 2 4Output110NoteThe first example is shown on the picture below.
Input121 1 61 6 11 5 51 2 33 4 41 3 23 7 72 2 32 6 13 8 82 5 53 1 1
Output1022
6 seconds
512 megabytes
['brute force', '*2900']
E. Restore Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile discussing a proper problem A for a Codeforces Round, Kostya created a cyclic array of positive integers a_1, a_2, \ldots, a_n. Since the talk was long and not promising, Kostya created a new cyclic array b_1, b_2, \ldots, b_{n} so that b_i = (a_i \mod a_{i + 1}), where we take a_{n+1} = a_1. Here mod is the modulo operation. When the talk became interesting, Kostya completely forgot how array a had looked like. Suddenly, he thought that restoring array a from array b would be an interesting problem (unfortunately, not A).InputThe first line contains a single integer n (2 \le n \le 140582) — the length of the array a.The second line contains n integers b_1, b_2, \ldots, b_{n} (0 \le b_i \le 187126).OutputIf it is possible to restore some array a of length n so that b_i = a_i \mod a_{(i \mod n) + 1} holds for all i = 1, 2, \ldots, n, print «YES» in the first line and the integers a_1, a_2, \ldots, a_n in the second line. All a_i should satisfy 1 \le a_i \le 10^{18}. We can show that if an answer exists, then an answer with such constraint exists as well.It it impossible to restore any valid a, print «NO» in one line.You can print each letter in any case (upper or lower).ExamplesInput41 3 1 0OutputYES1 3 5 2Input24 4OutputNONoteIn the first example: 1 \mod 3 = 1 3 \mod 5 = 3 5 \mod 2 = 1 2 \mod 1 = 0
Input41 3 1 0
OutputYES1 3 5 2
2 seconds
256 megabytes
['constructive algorithms', '*2400']
D. Order booktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider a simplified version of order book of some stock. The order book is a list of orders (offers) from people that want to buy or sell one unit of the stock, each order is described by direction (BUY or SELL) and price.At every moment of time, every SELL offer has higher price than every BUY offer. In this problem no two ever existed orders will have the same price.The lowest-price SELL order and the highest-price BUY order are called the best offers, marked with black frames on the picture below. The presented order book says that someone wants to sell the product at price 12 and it's the best SELL offer because the other two have higher prices. The best BUY offer has price 10. There are two possible actions in this orderbook: Somebody adds a new order of some direction with some price. Somebody accepts the best possible SELL or BUY offer (makes a deal). It's impossible to accept not the best SELL or BUY offer (to make a deal at worse price). After someone accepts the offer, it is removed from the orderbook forever.It is allowed to add new BUY order only with prices less than the best SELL offer (if you want to buy stock for higher price, then instead of adding an order you should accept the best SELL offer). Similarly, one couldn't add a new SELL order with price less or equal to the best BUY offer. For example, you can't add a new offer "SELL 20" if there is already an offer "BUY 20" or "BUY 25" — in this case you just accept the best BUY offer.You have a damaged order book log (in the beginning the are no orders in book). Every action has one of the two types: "ADD p" denotes adding a new order with price p and unknown direction. The order must not contradict with orders still not removed from the order book. "ACCEPT p" denotes accepting an existing best offer with price p and unknown direction.The directions of all actions are lost. Information from the log isn't always enough to determine these directions. Count the number of ways to correctly restore all ADD action directions so that all the described conditions are satisfied at any moment. Since the answer could be large, output it modulo 10^9 + 7. If it is impossible to correctly restore directions, then output 0.InputThe first line contains an integer n (1 \le n \le 363\,304) — the number of actions in the log.Each of the next n lines contains a string "ACCEPT" or "ADD" and an integer p (1 \le p \le 308\,983\,066), describing an action type and price. All ADD actions have different prices. For ACCEPT action it is guaranteed that the order with the same price has already been added but has not been accepted yet.OutputOutput the number of ways to restore directions of ADD actions modulo 10^9 + 7.ExamplesInput6ADD 1ACCEPT 1ADD 2ACCEPT 2ADD 3ACCEPT 3Output8Input4ADD 1ADD 2ADD 3ACCEPT 2Output2Input7ADD 1ADD 2ADD 3ADD 4ADD 5ACCEPT 3ACCEPT 5Output0NoteIn the first example each of orders may be BUY or SELL.In the second example the order with price 1 has to be BUY order, the order with the price 3 has to be SELL order.
Input6ADD 1ACCEPT 1ADD 2ACCEPT 2ADD 3ACCEPT 3
Output8
2 seconds
256 megabytes
['combinatorics', 'data structures', 'greedy', '*2100']
C. Rectanglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n rectangles on a plane with coordinates of their bottom left and upper right points. Some (n-1) of the given n rectangles have some common point. A point belongs to a rectangle if this point is strictly inside the rectangle or belongs to its boundary.Find any point with integer coordinates that belongs to at least (n-1) given rectangles.InputThe first line contains a single integer n (2 \le n \le 132\,674) — the number of given rectangles.Each the next n lines contains four integers x_1, y_1, x_2 and y_2 (-10^9 \le x_1 < x_2 \le 10^9, -10^9 \le y_1 < y_2 \le 10^9) — the coordinates of the bottom left and upper right corners of a rectangle.OutputPrint two integers x and y — the coordinates of any point that belongs to at least (n-1) given rectangles.ExamplesInput30 0 1 11 1 2 23 0 4 1Output1 1Input30 0 1 10 1 1 21 0 2 1Output1 1Input40 0 5 50 0 4 41 1 4 41 1 4 4Output1 1Input50 0 10 81 2 6 72 3 5 63 4 4 58 1 9 2Output3 4NoteThe picture below shows the rectangles in the first and second samples. The possible answers are highlighted. The picture below shows the rectangles in the third and fourth samples.
Input30 0 1 11 1 2 23 0 4 1
Output1 1
2 seconds
256 megabytes
['geometry', 'implementation', 'sortings', '*1600']