Problem ID stringlengths 2 6 | Problem Description stringlengths 0 7.52k | Rating float64 800 3.5k | math bool 2 classes | greedy bool 2 classes | implementation bool 2 classes | dp bool 2 classes | data structures bool 2 classes | constructive algorithms bool 2 classes | brute force bool 2 classes | binary search bool 2 classes | sortings bool 2 classes | graphs bool 2 classes | __index_level_0__ int64 3 9.98k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
818B | _n_ children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation _a_1,u2009_a_2,u2009...,u2009_a__n_ of length _n_. It is an integer sequence such that each integer from 1 to _n_ appears exactly once in it. The game consists of _m_ steps. On each step the current leader with index _i_ counts out _a__i_ people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader. You are given numbers _l_1,u2009_l_2,u2009...,u2009_l__m_ — indices of leaders in the beginning of each step. Child with number _l_1 is the first leader in the game. Write a program which will restore a possible permutation _a_1,u2009_a_2,u2009...,u2009_a__n_. If there are multiple solutions then print any of them. If there is no solution then print -1. Input The first line contains two integer numbers _n_, _m_ (1u2009≤u2009_n_,u2009_m_u2009≤u2009100). The second line contains _m_ integer numbers _l_1,u2009_l_2,u2009...,u2009_l__m_ (1u2009≤u2009_l__i_u2009≤u2009_n_) — indices of leaders in the beginning of each step. Output Print such permutation of _n_ numbers _a_1,u2009_a_2,u2009...,u2009_a__n_ that leaders in the game will be exactly _l_1,u2009_l_2,u2009...,u2009_l__m_ if all the rules are followed. If there are multiple solutions print any of them. If there is no permutation which satisfies all described conditions print -1. Note Let's follow leadership in the first example: Child 2 starts. Leadership goes from 2 to 2u2009+u2009_a_2u2009=u20093. Leadership goes from 3 to 3u2009+u2009_a_3u2009=u20095. As it's greater than 4, it's going in a circle to 1. Leadership goes from 1 to 1u2009+u2009_a_1u2009=u20094. Leadership goes from 4 to 4u2009+u2009_a_4u2009=u20098. Thus in circle it still remains at 4. | 1,600 | false | false | true | false | false | false | false | false | false | false | 6,486 |
1941G | Building bridges did not help Bernard, and he continued to be late everywhere. Then Rudolf decided to teach him how to use the subway. Rudolf depicted the subway map as an undirected connected graph, without self-loops, where the vertices represent stations. There is at most one edge between any pair of vertices. Two vertices are connected by an edge if it is possible to travel directly between the corresponding stations, bypassing other stations. The subway in the city where Rudolf and Bernard live has a color notation. This means that any edge between stations has a specific color. Edges of a specific color together form a subway line. A subway line cannot contain unconnected edges and forms a connected subgraph of the given subway graph. An example of the subway map is shown in the figure. Rudolf claims that the route will be optimal if it passes through the minimum number of subway lines. Help Bernard determine this minimum number for the given departure and destination stations. Input The first line contains an integer $$$t$$$ ($$$1 le t le 10^4$$$)xa0— the number of test cases. This is followed by descriptions of the test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 le n le 2 cdot 10^5, 1 le m le 2 cdot 10^5$$$) — the number of subway stations and the number of direct routes between stations (i.e., graph edges). This is followed by $$$m$$$ lines — the description of the edges. Each line of the description contains three integers $$$u$$$, $$$v$$$, and $$$c$$$ ($$$1 le u, v le n, u e v, 1 le c le 2 cdot 10^5$$$) — the numbers of the vertices between which there is an edge, and the color of this edge. It is guaranteed that edges of the same color form a connected subgraph of the given subway graph. There is at most one edge between a pair of any two vertices. This is followed by two integers $$$b$$$ and $$$e$$$ ($$$1 le b, e le n$$$) — the departure and destination stations. The sum of all $$$n$$$ over all test cases does not exceed $$$2 cdot 10^5$$$. The sum of all $$$m$$$ over all test cases does not exceed $$$2 cdot 10^5$$$. Output For each testcase, output a single integer — the minimum number of subway lines through which the route from station $$$b$$$ to station $$$e$$$ can pass. Examples Input 5 6 6 1 2 1 2 3 1 5 2 2 2 4 2 4 6 2 3 6 3 1 3 6 6 1 2 1 2 3 1 5 2 2 2 4 2 4 6 2 3 6 3 1 6 6 6 1 2 1 2 3 1 5 2 2 2 4 2 4 6 2 3 6 3 6 6 4 3 1 2 1 1 3 1 4 1 1 2 3 6 7 1 2 43 1 3 34 4 6 43 6 3 43 2 3 43 5 3 43 4 5 43 1 6 Input 3 7 9 2 4 1 3 6 1 2 3 5 1 7 1 4 7 1 2 5 4 5 4 4 3 4 1 3 7 1 5 3 6 5 6 5 83691 4 1 83691 5 4 83691 3 2 83691 4 3 83691 5 1 6 7 6 1 83691 6 2 83691 2 5 83691 5 6 83691 2 3 83691 5 4 83574 3 5 83691 1 4 Note The subway graph for the first example is shown in the figure in the problem statement. In the first test case, from vertex $$$1$$$ to vertex $$$3$$$, you can travel along the path $$$1 ightarrow 2 ightarrow 3$$$, using only the green line. In the second test case, from vertex $$$1$$$ to vertex $$$6$$$, you can travel along the path $$$1 ightarrow 2 ightarrow 3 ightarrow 6$$$, using the green and blue lines. In the third test case, there is no need to travel from vertex $$$6$$$ to the same vertex, so the number of lines is $$$0$$$. In the fourth test case, all edges of the graph belong to one line, so the answer is $$$1$$$. | 2,000 | false | false | false | false | false | true | false | false | false | true | 633 |
204C | Little Elephant loves Furik and Rubik, who he met in a small city Kremenchug. The Little Elephant has two strings of equal length _a_ and _b_, consisting only of uppercase English letters. The Little Elephant selects a pair of substrings of equal length — the first one from string _a_, the second one from string _b_. The choice is equiprobable among all possible pairs. Let's denote the substring of _a_ as _x_, and the substring of _b_ — as _y_. The Little Elephant gives string _x_ to Furik and string _y_ — to Rubik. Let's assume that _f_(_x_,u2009_y_) is the number of such positions of _i_ (1u2009≤u2009_i_u2009≤u2009_x_), that _x__i_u2009=u2009_y__i_ (where _x_ is the length of lines _x_ and _y_, and _x__i_, _y__i_ are the _i_-th characters of strings _x_ and _y_, correspondingly). Help Furik and Rubik find the expected value of _f_(_x_,u2009_y_). Input The first line contains a single integer _n_ (1u2009≤u2009_n_u2009≤u20092·105) — the length of strings _a_ and _b_. The second line contains string _a_, the third line contains string _b_. The strings consist of uppercase English letters only. The length of both strings equals _n_. Output On a single line print a real number — the answer to the problem. The answer will be considered correct if its relative or absolute error does not exceed 10u2009-u20096. Note Let's assume that we are given string _a_u2009=u2009_a_1_a_2... _a__a_, then let's denote the string's length as _a_, and its _i_-th character — as _a__i_. A substring _a_[_l_... _r_] (1u2009≤u2009_l_u2009≤u2009_r_u2009≤u2009_a_) of string _a_ is string _a__l__a__l_u2009+u20091... _a__r_. String _a_ is a substring of string _b_, if there exists such pair of integers _l_ and _r_ (1u2009≤u2009_l_u2009≤u2009_r_u2009≤u2009_b_), that _b_[_l_... _r_]u2009=u2009_a_. Let's consider the first test sample. The first sample has 5 possible substring pairs: ("A", "B"), ("A", "A"), ("B", "B"), ("B", "A"), ("AB", "BA"). For the second and third pair value _f_(_x_,u2009_y_) equals 1, for the rest it equals 0. The probability of choosing each pair equals , that's why the answer is · 0 u2009+u2009 · 1 u2009+u2009 · 1 u2009+u2009 · 0 u2009+u2009 · 0 u2009=u2009 u2009=u2009 0.4. | 2,000 | true | false | false | false | false | false | false | false | false | false | 9,025 |
1063F | We call a sequence of strings _t_1,u2009...,u2009_t__k_ a journey of length _k_, if for each _i_u2009>u20091 _t__i_ is a substring of _t__i_u2009-u20091 and length of _t__i_ is strictly less than length of _t__i_u2009-u20091. For example, {_ab_,u2009_b_} is a journey, but {_ab_,u2009_c_} and {_a_,u2009_a_} are not. Define a journey on string _s_ as journey _t_1,u2009...,u2009_t__k_, such that all its parts can be nested inside _s_ in such a way that there exists a sequence of strings _u_1,u2009...,u2009_u__k_u2009+u20091 (each of these strings can be empty) and _s_u2009=u2009_u_1u2009_t_1u2009_u_2u2009_t_2... _u__k_u2009_t__k_u2009_u__k_u2009+u20091. As an example, {_ab_,u2009_b_} is a journey on string _abb_, but not on _bab_ because the journey strings _t__i_ should appear from the left to the right. The length of a journey on a string is the number of strings in it. Determine the maximum possible length of a journey on the given string _s_. Input The first line contains a single integer _n_ (1u2009≤u2009_n_u2009≤u2009500u2009000)xa0— the length of string _s_. The second line contains the string _s_ itself, consisting of _n_ lowercase Latin letters. Output Print one numberxa0— the maximum possible length of string journey on _s_. Note In the first sample, the string journey of maximum length is {_abcd_,u2009_bc_,u2009_c_}. In the second sample, one of the suitable journeys is {_bb_,u2009_b_}. | 3,300 | false | false | false | true | true | false | false | false | false | false | 5,391 |
1760G | You are given a weighted tree with $$$n$$$ vertices. Recall that a tree is a connected graph without any cycles. A weighted tree is a tree in which each edge has a certain weight. The tree is undirected, it doesn't have a root. Since trees bore you, you decided to challenge yourself and play a game on the given tree. In a move, you can travel from a node to one of its neighbors (another node it has a direct edge with). You start with a variable $$$x$$$ which is initially equal to $$$0$$$. When you pass through edge $$$i$$$, $$$x$$$ changes its value to $$$x ~mathsf{XOR}~ w_i$$$ (where $$$w_i$$$ is the weight of the $$$i$$$-th edge). Your task is to go from vertex $$$a$$$ to vertex $$$b$$$, but you are allowed to enter node $$$b$$$ if and only if after traveling to it, the value of $$$x$$$ will become $$$0$$$. In other words, you can travel to node $$$b$$$ only by using an edge $$$i$$$ such that $$$x ~mathsf{XOR}~ w_i = 0$$$. Once you enter node $$$b$$$ the game ends and you win. Additionally, you can teleport at most once at any point in time to any vertex except vertex $$$b$$$. You can teleport from any vertex, even from $$$a$$$. Answer with "YES" if you can reach vertex $$$b$$$ from $$$a$$$, and "NO" otherwise. Note that $$$mathsf{XOR}$$$ represents the xa0— the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$2 leq n leq 10^5$$$), ($$$1 leq a, b leq n; a e b$$$)xa0— the number of vertices, and the starting and desired ending node respectively. Each of the next $$$n-1$$$ lines denotes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ xa0— the labels of vertices it connects ($$$1 leq u_i, v_i leq n; u_i e v_i; 1 leq w_i leq 10^9$$$) and the weight of the respective edge. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. Output For each test case output "YES" if you can reach vertex $$$b$$$, and "NO" otherwise. Example Input 3 5 1 4 1 3 1 2 3 2 4 3 3 3 5 1 2 1 2 1 2 2 6 2 3 1 2 1 2 3 1 3 4 1 4 5 3 5 6 5 Note For the first test case, we can travel from node $$$1$$$ to node $$$3$$$, $$$x$$$ changing from $$$0$$$ to $$$1$$$, then we travel from node $$$3$$$ to node $$$2$$$, $$$x$$$ becoming equal to $$$3$$$. Now, we can teleport to node $$$3$$$ and travel from node $$$3$$$ to node $$$4$$$, reaching node $$$b$$$, since $$$x$$$ became equal to $$$0$$$ in the end, so we should answer "YES". For the second test case, we have no moves, since we can't teleport to node $$$b$$$ and the only move we have is to travel to node $$$2$$$ which is impossible since $$$x$$$ wouldn't be equal to $$$0$$$ when reaching it, so we should answer "NO". | 1,700 | false | false | false | false | false | false | false | false | false | true | 1,749 |
460C | Little beaver is a beginner programmer, so informatics is his favorite subject. Soon his informatics teacher is going to have a birthday and the beaver has decided to prepare a present for her. He planted _n_ flowers in a row on his windowsill and started waiting for them to grow. However, after some time the beaver noticed that the flowers stopped growing. The beaver thinks it is bad manners to present little flowers. So he decided to come up with some solutions. There are _m_ days left to the birthday. The height of the _i_-th flower (assume that the flowers in the row are numbered from 1 to _n_ from left to right) is equal to _a__i_ at the moment. At each of the remaining _m_ days the beaver can take a special watering and water _w_ contiguous flowers (he can do that only once at a day). At that each watered flower grows by one height unit on that day. The beaver wants the height of the smallest flower be as large as possible in the end. What maximum height of the smallest flower can he get? Input The first line contains space-separated integers _n_, _m_ and _w_ (1u2009≤u2009_w_u2009≤u2009_n_u2009≤u2009105;xa01u2009≤u2009_m_u2009≤u2009105). The second line contains space-separated integers _a_1,u2009_a_2,u2009...,u2009_a__n_ (1u2009≤u2009_a__i_u2009≤u2009109). Output Print a single integer — the maximum final height of the smallest flower. Note In the first sample beaver can water the last 3 flowers at the first day. On the next day he may not to water flowers at all. In the end he will get the following heights: [2, 2, 2, 3, 2, 2]. The smallest flower has height equal to 2. It's impossible to get height 3 in this test. | 1,700 | false | true | false | false | true | false | false | true | false | false | 7,999 |
1554A | You are given $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$. Find the maximum value of $$$max(a_l, a_{l + 1}, ldots, a_r) cdot min(a_l, a_{l + 1}, ldots, a_r)$$$ over all pairs $$$(l, r)$$$ of integers for which $$$1 le l < r le n$$$. Input The first line contains a single integer $$$t$$$ ($$$1 le t le 10,000$$$) xa0— the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 le n le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$1 le a_i le 10^6$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 cdot 10^5$$$. Output For each test case, print a single integer xa0— the maximum possible value of the product from the statement. Example Input 4 3 2 4 3 4 3 2 3 1 2 69 69 6 719313 273225 402638 473783 804745 323328 Output 12 6 4761 381274500335 Note Let $$$f(l, r) = max(a_l, a_{l + 1}, ldots, a_r) cdot min(a_l, a_{l + 1}, ldots, a_r)$$$. In the first test case, $$$f(1, 2) = max(a_1, a_2) cdot min(a_1, a_2) = max(2, 4) cdot min(2, 4) = 4 cdot 2 = 8$$$. $$$f(1, 3) = max(a_1, a_2, a_3) cdot min(a_1, a_2, a_3) = max(2, 4, 3) cdot min(2, 4, 3) = 4 cdot 2 = 8$$$. $$$f(2, 3) = max(a_2, a_3) cdot min(a_2, a_3) = max(4, 3) cdot min(4, 3) = 4 cdot 3 = 12$$$. So the maximum is $$$f(2, 3) = 12$$$. In the second test case, the maximum is $$$f(1, 2) = f(1, 3) = f(2, 3) = 6$$$. | 800 | false | true | false | false | false | false | false | false | false | false | 2,866 |
798A | Problem - 798A - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags brute force constructive algorithms strings *1000 No tag edit access → Contest materials ") Editorial") . Output Print "YES" (without quotes) if Mike can change exactly one character so that the resulting string is palindrome or "NO" (without quotes) otherwise. Examples Input abccaa Output YES Input abbcca Output NO Input abcda Output YES | 1,000 | false | false | false | false | false | true | true | false | false | false | 6,581 |
1746G | Anton decided to get ready for an Olympiad in Informatics. Ilya prepared $$$n$$$ tasks for him to solve. It is possible to submit the solution for the $$$i$$$-th task in the first $$$d_{i}$$$ days only. Anton cannot solve more than one task a day. Ilya estimated the usefulness of the $$$i$$$-th tasks as $$$r_{i}$$$ and divided the tasks into three topics, the topic of the $$$i$$$-th task is $$$type_{i}$$$. Anton wants to solve exactly $$$a$$$ tasks on the first topic, $$$b$$$ tasks on the second topic and $$$c$$$ tasks on the third topic. Tell Anton if it is possible to do so, and if it is, calculate the maximum total usefulness of the tasks he may solve. Input The first line of input contains a single integer $$$t$$$ ($$$1 le t le 10^4$$$)xa0— the number of test cases. The first line of each test case contains four integers $$$n, a, b, c$$$ ($$$1 le n le 10^5$$$, $$$0 le a, b, c le n$$$). The following $$$n$$$ lines contain three integers eachxa0— $$$r_i, type_i, d_i$$$ ($$$0 le r_i le 10^{9}$$$, $$$1 le type_i le 3$$$, $$$1 le d_i le n$$$). The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. Output For each test case print $$$-1$$$ if Anton cannot reach his goal; otherwise, print the maximum usefulness of the tasks he will solve. Example Input 4 4 1 1 0 1 2 1 1 1 1 0 1 2 1 2 2 3 1 1 1 1 1 2 7 2 1 9 3 2 4 2 1 0 100 2 1 5 2 3 7 1 2 5 1 2 5 1 1 1 10 3 1 9 2 3 20 1 1 16 1 4 1 3 4 Note In the first test case from the sample test Anton can solve tasks $$$2$$$ and $$$4$$$. In the second test case from the sample test it is impossible to fulfill Anton's wish. In the third test case from the sample test it is optimal to solve tasks $$$2$$$, $$$3$$$ and $$$4$$$. In the last test case from the sample test it is optimal to solve tasks $$$1$$$, $$$2$$$ and $$$4$$$. | 3,500 | false | false | true | true | true | false | false | true | true | false | 1,803 |
263A | You've got a 5u2009×u20095 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1. Swap two neighboring matrix rows, that is, rows with indexes _i_ and _i_u2009+u20091 for some integer _i_ (1u2009≤u2009_i_u2009<u20095). 2. Swap two neighboring matrix columns, that is, columns with indexes _j_ and _j_u2009+u20091 for some integer _j_ (1u2009≤u2009_j_u2009<u20095). You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful. Input The input consists of five lines, each line contains five integers: the _j_-th integer in the _i_-th line of the input represents the element of the matrix that is located on the intersection of the _i_-th row and the _j_-th column. It is guaranteed that the matrix consists of 24 zeroes and a single number one. Output Print a single integer — the minimum number of moves needed to make the matrix beautiful. Examples Input 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Input 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 | 800 | false | false | true | false | false | false | false | false | false | false | 8,783 |
367A | Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as _q_u2009=u2009_q_1_q_2... _q__k_. The algorithm consists of two steps: 1. Find any continuous subsequence (substring) of three characters of string _q_, which doesn't equal to either string "zyx", "xzy", "yxz". If _q_ doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. 2. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string _q_ if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string. Sereja wants to test his algorithm. For that, he has string _s_u2009=u2009_s_1_s_2... _s__n_, consisting of _n_ characters. The boy conducts a series of _m_ tests. As the _i_-th test, he sends substring _s__l__i__s__l__i_u2009+u20091... _s__r__i_ (1u2009≤u2009_l__i_u2009≤u2009_r__i_u2009≤u2009_n_) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (_l__i_,u2009_r__i_) determine if the algorithm works correctly on this test or not. Input The first line contains non-empty string _s_, its length (_n_) doesn't exceed 105. It is guaranteed that string _s_ only contains characters: 'x', 'y', 'z'. The second line contains integer _m_ (1u2009≤u2009_m_u2009≤u2009105) — the number of tests. Next _m_ lines contain the tests. The _i_-th line contains a pair of integers _l__i_, _r__i_ (1u2009≤u2009_l__i_u2009≤u2009_r__i_u2009≤u2009_n_). Output For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise. Examples Input zyxxxxxxyyz 5 5 5 1 3 1 11 1 4 3 6 Note In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly. | 1,500 | false | false | true | false | true | false | false | false | false | false | 8,365 |
274E | Imagine an _n_u2009×u2009_m_ grid with some blocked cells. The top left cell in the grid has coordinates (1,u20091) and the bottom right cell has coordinates (_n_,u2009_m_). There are _k_ blocked cells in the grid and others are empty. You flash a laser beam from the center of an empty cell (_x__s_,u2009_y__s_) in one of the diagonal directions (i.e. north-east, north-west, south-east or south-west). If the beam hits a blocked cell or the border of the grid it will reflect. The behavior of the beam reflection in different situations is depicted in the figure below. After a while the beam enters an infinite cycle. Count the number of empty cells that the beam goes through at least once. We consider that the beam goes through cell if it goes through its center. Input The first line of the input contains three integers _n_, _m_ and _k_ (1u2009≤u2009_n_,u2009_m_u2009≤u2009105,u20090u2009≤u2009_k_u2009≤u2009105). Each of the next _k_ lines contains two integers _x__i_ and _y__i_ (1u2009≤u2009_x__i_u2009≤u2009_n_,u20091u2009≤u2009_y__i_u2009≤u2009_m_) indicating the position of the _i_-th blocked cell. The last line contains _x__s_, _y__s_ (1u2009≤u2009_x__s_u2009≤u2009_n_,u20091u2009≤u2009_y__s_u2009≤u2009_m_) and the flash direction which is equal to "NE", "NW", "SE" or "SW". These strings denote directions (u2009-u20091,u20091), (u2009-u20091,u2009u2009-u20091), (1,u20091), (1,u2009u2009-u20091). It's guaranteed that no two blocked cells have the same coordinates. Output In the only line of the output print the number of empty cells that the beam goes through at least once. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 7 5 3 3 3 4 3 5 3 2 1 SE | 3,000 | false | false | true | false | true | false | false | false | false | false | 8,735 |
1506F | Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The $$$k$$$-th layer of the triangle contains $$$k$$$ points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers $$$(r, c)$$$ ($$$1 le c le r$$$), where $$$r$$$ is the number of the layer, and $$$c$$$ is the number of the point in the layer. From each point $$$(r, c)$$$ there are two directed edges to the points $$$(r+1, c)$$$ and $$$(r+1, c+1)$$$, but only one of the edges is activated. If $$$r + c$$$ is even, then the edge to the point $$$(r+1, c)$$$ is activated, otherwise the edge to the point $$$(r+1, c+1)$$$ is activated. Look at the picture for a better understanding. Activated edges are colored in black. Non-activated edges are colored in gray. From the point $$$(r_1, c_1)$$$ it is possible to reach the point $$$(r_2, c_2)$$$, if there is a path between them only from activated edges. For example, in the picture above, there is a path from $$$(1, 1)$$$ to $$$(3, 2)$$$, but there is no path from $$$(2, 1)$$$ to $$$(1, 1)$$$. Initially, you are at the point $$$(1, 1)$$$. For each turn, you can: Replace activated edge for point $$$(r, c)$$$. That is if the edge to the point $$$(r+1, c)$$$ is activated, then instead of it, the edge to the point $$$(r+1, c+1)$$$ becomes activated, otherwise if the edge to the point $$$(r+1, c+1)$$$, then instead if it, the edge to the point $$$(r+1, c)$$$ becomes activated. This action increases the cost of the path by $$$1$$$; Move from the current point to another by following the activated edge. This action does not increase the cost of the path. You are given a sequence of $$$n$$$ points of an infinite triangle $$$(r_1, c_1), (r_2, c_2), ldots, (r_n, c_n)$$$. Find the minimum cost path from $$$(1, 1)$$$, passing through all $$$n$$$ points in arbitrary order. Input The first line contains one integer $$$t$$$ ($$$1 le t le 10^4$$$) is the number of test cases. Then $$$t$$$ test cases follow. Each test case begins with a line containing one integer $$$n$$$ ($$$1 le n le 2 cdot 10^5$$$) is the number of points to visit. The second line contains $$$n$$$ numbers $$$r_1, r_2, ldots, r_n$$$ ($$$1 le r_i le 10^9$$$), where $$$r_i$$$ is the number of the layer in which $$$i$$$-th point is located. The third line contains $$$n$$$ numbers $$$c_1, c_2, ldots, c_n$$$ ($$$1 le c_i le r_i$$$), where $$$c_i$$$ is the number of the $$$i$$$-th point in the $$$r_i$$$ layer. It is guaranteed that all $$$n$$$ points are distinct. It is guaranteed that there is always at least one way to traverse all $$$n$$$ points. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 cdot 10^5$$$. | 2,000 | true | false | false | false | false | true | false | false | true | true | 3,138 |
1027B | You are given a chessboard of size $$$n imes n$$$. It is filled with numbers from $$$1$$$ to $$$n^2$$$ in the following way: the first $$$lceil frac{n^2}{2} ceil$$$ numbers from $$$1$$$ to $$$lceil frac{n^2}{2} ceil$$$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $$$n^2 - lceil frac{n^2}{2} ceil$$$ numbers from $$$lceil frac{n^2}{2} ceil + 1$$$ to $$$n^2$$$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $$$lceilfrac{x}{y} ceil$$$ means division $$$x$$$ by $$$y$$$ rounded up. For example, the left board on the following picture is the chessboard which is given for $$$n=4$$$ and the right board is the chessboard which is given for $$$n=5$$$. You are given $$$q$$$ queries. The $$$i$$$-th query is described as a pair $$$x_i, y_i$$$. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$. Input The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 le n le 10^9$$$, $$$1 le q le 10^5$$$) — the size of the board and the number of queries. The next $$$q$$$ lines contain two integers each. The $$$i$$$-th line contains two integers $$$x_i, y_i$$$ ($$$1 le x_i, y_i le n$$$) — description of the $$$i$$$-th query. Output For each query from $$$1$$$ to $$$q$$$ print the answer to this query. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$. Queries are numbered from $$$1$$$ to $$$q$$$ in order of the input. Note Answers to the queries from examples are on the board in the picture from the problem statement. | 1,200 | true | false | true | false | false | false | false | false | false | false | 5,575 |
2029H | Given is an undirected graph with $$$n$$$ vertices and $$$m$$$ edges. Each edge connects two vertices $$$(u, v)$$$ and has a probability of $$$frac{p}{q}$$$ of appearing each day. Initially, vertex $$$1$$$ has a message. At the end of the day, a vertex has a message if and only if itself or at least one of the vertices adjacent to it had the message the day before. Note that each day, each edge chooses its appearance independently. Calculate the expected number of days before all the vertices have the message, modulo $$$998,244,353$$$. Input The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1leq nleq 21$$$, $$$n-1leq mleqfrac{n(n-1)}{2}$$$). Then $$$m$$$ lines follow, each containing four integers $$$u$$$, $$$v$$$, $$$p$$$, and $$$q$$$ ($$$1leq u eq vleq n$$$, $$$1leq p<q<998,244,353$$$, $$$gcd(p,q)=1$$$)xa0— there is an undirected edge between $$$u$$$ and $$$v$$$, and it has a probability of appearance of $$$frac{p}{q}$$$ each day. It is guaranteed that there are no self-loops or multiple-edges in the graph and that the graph is connected if all of the edges appear. Additional constraint in the input: Let $$$g_{i,j}$$$ be the probability of appearance of the edge between $$$i$$$ and $$$j$$$ ($$$g_{i,j}=0$$$ if there is no edge between $$$i$$$ and $$$j$$$). It is guaranteed that for any $$$Ssubseteq{1,2,ldots,n}$$$ ($$$Sge 1$$$), $$$$$$ prod_{iin S}left(prod_{jin{1,2,ldots,n}setminus S}(1-g_{i,j}) ight) otequiv1pmod{998,244,353}. $$$$$$ Output Print a single integer in the only line of the outputxa0— the expected number of days, modulo $$$998,244,353$$$. Formally, let $$$M = 998,244,353$$$. It can be shown that the exact answer can be expressed as an irreducible fraction $$$frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q ot equiv 0 pmod{M}$$$. Output the integer equal to $$$p cdot q^{-1} bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 le x < M$$$ and $$$x cdot q equiv p pmod{M}$$$. Examples Input 3 3 1 2 1 2 1 3 1 2 2 3 1 2 Input 5 8 1 2 1 11 1 3 2 11 1 4 3 11 1 5 4 11 2 4 5 11 2 5 6 11 3 4 7 11 4 5 8 11 Input 21 22 1 2 3 4 2 3 4 5 3 4 5 6 5 6 7 8 6 7 8 9 7 8 9 10 8 9 2 3 9 10 3 4 10 11 4 5 11 12 5 6 12 13 6 7 13 14 7 8 14 15 8 9 15 16 9 10 16 17 2 3 17 18 3 4 18 19 4 5 19 20 5 6 20 21 6 7 1 10 100 1001 15 4 147 220 4 11 1 998244352 Note In the first test, the answer is equal to the expected number of days before the only edge in the graph first appears, and that is $$$frac{1}{0.1}=10$$$. In the second test, the answer is equal to $$$frac{20}{9}$$$ before it is taken modulo $$$998,244,353$$$. In the third test, the only vertex already has the message, so the answer is $$$0$$$. | 3,500 | false | false | false | true | false | false | true | false | false | false | 90 |
1632C | Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich. Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $$$a$$$ and $$$b$$$ ($$$a < b$$$). After that, the student can apply any of the following operations any number of times: $$$a := a + 1$$$ (increase $$$a$$$ by $$$1$$$), $$$b := b + 1$$$ (increase $$$b$$$ by $$$1$$$), $$$a := a b$$$ (replace $$$a$$$ with the . To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal. Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make $$$a$$$ equal to $$$b$$$. Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 10^4$$$). Description of the test cases follows. The only line for each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 le a < b le 10^6$$$). It is guaranteed that the sum of $$$b$$$ over all test cases does not exceed $$$10^6$$$. Output For each test case print one integer — the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal. Example Input 5 1 3 5 8 2 5 3 19 56678 164422 Note In the first test case, it is optimal to apply the third operation. In the second test case, it is optimal to apply the first operation three times. In the third test case, it is optimal to apply the second operation and then the third operation. | 1,600 | true | false | false | true | false | false | true | true | false | false | 2,456 |
1557E | This is an interactive problem. ICPC Assiut Community decided to hold a unique chess contest, and you were chosen to control a queen and hunt down the hidden king, while a member of ICPC Assiut Community controls this king. You compete on an $$$8 imes8$$$ chessboard, the rows are numerated from top to bottom, and the columns are numerated left to right, and the cell in row $$$x$$$ and column $$$y$$$ is denoted as $$$(x, y)$$$. In one turn you can move the queen to any of the squares on the same horizontal line, vertical line, or any of the diagonals. For example, if the queen was on square ($$$4$$$, $$$5$$$), you can move to ($$$q_1$$$, $$$5$$$), ($$$4$$$, $$$q_1$$$), ($$$q_1$$$, $$$9-q_1$$$), or ($$$q_2$$$, $$$q_2+1$$$) where ($$$1 le q_1 le 8$$$, $$$q_1 e 4$$$, $$$1 le q_2 le 7$$$, $$$q_2 e 4$$$). Note that the queen cannot stay on its current cell. In one turn, the king can move "Right", "Left", "Up", "Down", "Down-Right", "Down-Left", "Up-Left", or "Up-Right" such that he doesn't get out of the board. The king cannot move into a cell that is on the same row, column or diagonal with the queen (including the position of the queen itself). For example, if the king was on square ($$$4$$$, $$$5$$$), he can move to ($$$4+k_1$$$, $$$5+k_2$$$) where ($$$-1 le k_1,k_2 le 1$$$, $$$(k_1, k_2) e (0, 0)$$$). At the start of the game, you should place the queen at any location on the board, and this is done once per game. After that the king is secretly placed at any cell different from the queen's location. You do not know the position of the king. Then, the king and the queen take turns with the king moving first. The king moves to one of the possible directions ("Right", "Down", "Up-Left", etc.), and you are only given the direction it moves to. After that, you should move your queen by declaring the square to which your queen will move. The game follows like this until you win the game or run out of moves. You win if the king has no valid moves. You lose if after $$$130$$$ moves of the queen the king still has valid moves. Interaction In each test case, you should print the queen's starting cell immediately. If you placed the queen at the king's cell, you will win immediately. After that, you may make at most $$$130$$$ moves. Each move is made in the format $$$x$$$ $$$y$$$, where $$$x$$$ and $$$y$$$ are two integers ($$$1 leq x,y leq 8$$$) that denote the new row and column of the queen respectively. Your move should be a valid queen move. After the initial queen placement and after each move you will receive a string $$$s$$$ that represents the direction of the king's move. It will be one of the following: "Right", "Left", "Up", "Down", "Down-Right", "Down-Left", "Up-Left", "Up-Right", or "Done" if you win the game. You should consider "Done" as the end of each test case. 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. If at any point you make an invalid query or try to make more than $$$130$$$ queries for each test case, the game will terminate immediately and you will receive a Wrong Answer verdict. | 2,800 | false | false | false | false | false | true | true | false | false | false | 2,843 |
627A | Problem - 627A - Codeforces =============== xa0 ]( "8VC Venture Cup 2016 — Final Round") ? Input The first line of the input contains two integers _s_ and _x_ (2u2009≤u2009_s_u2009≤u20091012, 0u2009≤u2009_x_u2009≤u20091012), the sum and bitwise xor of the pair of positive integers, respectively. Output Print a single integer, the number of solutions to the given conditions. If no solutions exist, print 0. Examples Input 9 5 Output 4 Input 3 3 Output 2 Input 5 2 Output 0 Note In the first sample, we have the following solutions: (2,u20097), (3,u20096), (6,u20093), (7,u20092). In the second sample, the only solutions are (1,u20092) and (2,u20091). | 1,700 | true | false | false | true | false | false | false | false | false | false | 7,321 |
735B | Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are _n_ people who plan to move to the cities. The wealth of the _i_ of them is equal to _a__i_. Authorities plan to build two cities, first for _n_1 people and second for _n_2 people. Of course, each of _n_ candidates can settle in only one of the cities. Thus, first some subset of candidates of size _n_1 settle in the first city and then some subset of size _n_2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home. To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth _a__i_ among all its residents divided by the number of them (_n_1 or _n_2 depending on the city). The division should be done in real numbers without any rounding. Please, help authorities find the optimal way to pick residents for two cities. Input The first line of the input contains three integers _n_, _n_1 and _n_2 (1u2009≤u2009_n_,u2009_n_1,u2009_n_2u2009≤u2009100u2009000, _n_1u2009+u2009_n_2u2009≤u2009_n_)xa0— the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains _n_ integers _a_1,u2009_a_2,u2009...,u2009_a__n_ (1u2009≤u2009_a__i_u2009≤u2009100u2009000), the _i_-th of them is equal to the wealth of the _i_-th candidate. Output Print one real valuexa0— the maximum possible sum of arithmetic means of wealth of cities' residents. You answer will be considered correct if its absolute or relative error does not exceed 10u2009-u20096. Namely: let's assume that your answer is _a_, and the answer of the jury is _b_. The checker program will consider your answer correct, if . Note In the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second. In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (_a_3u2009+u2009_a_4)u2009/u20092u2009+u2009_a_2u2009=u2009(3u2009+u20092)u2009/u20092u2009+u20094u2009=u20096.5 | 1,100 | false | true | false | false | false | false | false | false | true | false | 6,851 |
1575L | Problem - 1575L - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags data structures divide and conquer dp sortings *2100 No tag edit access → Contest materials ") $$$ as the number of indices where $$$a_i = i$$$. You can pick an element from the current sequence and remove it, then concatenate the remaining elements together. For example, if you remove the $$$3$$$-rd element from the sequence $$$ | 2,100 | false | false | false | true | true | false | false | false | true | false | 2,757 |
276A | Problem - 276A - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags implementation *900 No tag edit access → Contest materials ") . Otherwise, the Rabbits get exactly _f__i_ units of joy. Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value. Input The first line contains two space-separated integers — _n_ (1u2009≤u2009_n_u2009≤u2009104) and _k_ (1u2009≤u2009_k_u2009≤u2009109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next _n_ lines contains two space-separated integers — _f__i_ (1u2009≤u2009_f__i_u2009≤u2009109) and _t__i_ (1u2009≤u2009_t__i_u2009≤u2009109) — the characteristics of the _i_-th restaurant. Output In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch. Examples Input 2 5 3 3 4 5 Output 4 Input 4 6 5 8 3 6 2 3 2 2 Output 3 Input 1 5 1 7 Output -1 | 900 | false | false | true | false | false | false | false | false | false | false | 8,732 |
1863C | You are given an array $$$a_1,a_2,ldots, a_n$$$ of pairwise distinct integers from $$$0$$$ to $$$n$$$. Consider the following operation: consecutively for each $$$i$$$ from $$$1$$$ to $$$n$$$ in this order, replace $$$a_i$$$ with $$$operatorname{MEX}(a_1, a_2, ldots, a_n)$$$. Here $$$operatorname{MEX}$$$ of a collection of integers $$$c_1, c_2, ldots, c_m$$$ is defined as the smallest non-negative integer $$$x$$$ which does not occur in the collection $$$c$$$. For example, $$$operatorname{MEX}(0, 2, 2, 1, 4) = 3$$$ and $$$operatorname{MEX}(1, 2) = 0$$$. Print the array after applying $$$k$$$ such operations. Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 10^5$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1le nle 10^5$$$, $$$1le kle 10^9$$$). The second line contains $$$n$$$ pairwise distinct integers $$$a_1,a_2,ldots, a_n$$$ ($$$0le a_ile n$$$) representing the elements of the array before applying the operations. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. Output For each test case, print all $$$n$$$ elements of the array after applying $$$k$$$ operations. Example Input 5 1 2 1 3 1 0 1 3 2 2 0 2 5 5 1 2 3 4 5 10 100 5 3 0 4 2 1 6 9 10 8 Output 1 2 0 1 2 1 2 3 4 5 0 7 5 3 0 4 2 1 6 9 10 Note In the first test case, here is the entire process: 1. On the first operation, the array changes from $$$[1]$$$ to $$$[0]$$$, since $$$operatorname{MEX}(1) = 0$$$. 2. On the second operation, the array changes from $$$[0]$$$ to $$$[1]$$$, since $$$operatorname{MEX}(0) = 1$$$. Thus, the array becomes $$$[1]$$$ after two operations. In the second test case, the array changes as follows during one operation: $$$[{mkern3muunderline{mkern-3mu {bf 0}mkern-3mu}mkern3mu}, 1, 3] ightarrow [2, {mkern3muunderline{mkern-3mu {bf 1}mkern-3mu}mkern3mu}, 3] ightarrow [2, 0, {mkern3muunderline{mkern-3mu {bf 3}mkern-3mu}mkern3mu}] ightarrow [2, 0, 1]$$$. In the third test case, the array changes as follows during one operation: $$$[{mkern3muunderline{mkern-3mu {bf 0}mkern-3mu}mkern3mu}, 2] ightarrow [1, {mkern3muunderline{mkern-3mu {bf 2}mkern-3mu}mkern3mu}] ightarrow [1, 0]$$$. And during the second operation: $$$[{mkern3muunderline{mkern-3mu {bf 1}mkern-3mu}mkern3mu}, 0] ightarrow [2, {mkern3muunderline{mkern-3mu {bf 0}mkern-3mu}mkern3mu}] ightarrow [2, 1]$$$. | 1,100 | true | false | true | false | false | false | false | false | false | false | 1,104 |
2021E2 | This is the hard version of the problem. In the three versions, the constraints on $$$n$$$ and $$$m$$$ are different. You can make hacks only if all the versions of the problem are solved. Pak Chanek is setting up internet connections for the village of Khuntien. The village can be represented as a connected simple graph with $$$n$$$ houses and $$$m$$$ internet cables connecting house $$$u_i$$$ and house $$$v_i$$$, each with a latency of $$$w_i$$$. There are $$$p$$$ houses that require internet. Pak Chanek can install servers in at most $$$k$$$ of the houses. The houses that need internet will then be connected to one of the servers. However, since each cable has its latency, the latency experienced by house $$$s_i$$$ requiring internet will be the maximum latency of the cables between that house and the server it is connected to. For each $$$k = 1,2,ldots,n$$$, help Pak Chanek determine the minimum total latency that can be achieved for all the houses requiring internet. Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 2000$$$). The description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$m$$$, $$$p$$$ ($$$2 le n le 5000$$$; $$$n-1 le m le 5000$$$; $$$1 le p le n$$$)xa0— the number of houses, the number of cables, and the number of houses that need internet. The second line of each test case contains $$$p$$$ integers $$$s_1, s_2, ldots, s_p$$$ ($$$1 le s_i le n$$$)xa0— the houses that need internet. It is guaranteed that all elements of $$$s$$$ are distinct. The $$$i$$$-th of the next $$$m$$$ lines of each test case contains three integers $$$u_i$$$, $$$v_i$$$, and $$$w_i$$$ ($$$1 le u_i < v_i le n$$$; $$$1 le w_i le 10^9$$$)xa0— the internet cable connecting house $$$u_i$$$ and house $$$v_i$$$ with latency of $$$w_i$$$. It is guaranteed that the given edges form a connected simple graph. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ do not exceed $$$5000$$$. Output For each test case, output $$$n$$$ integers: the minimum total latency that can be achieved for all the houses requiring internet for each $$$k = 1,2,ldots,n$$$. Example Input 2 9 8 5 2 5 6 8 9 1 2 1 1 3 2 3 4 10 4 5 3 4 6 5 1 7 10 7 8 4 7 9 2 3 3 2 3 1 1 2 1 2 3 3 1 3 2 Output 34 19 9 4 0 0 0 0 0 2 0 0 Note In the first test case for $$$k=3$$$, a possible optimal solution is to install servers at vertices $$$2$$$, $$$6$$$ and $$$8$$$ and obtain the following latency: $$$ ext{latency}(2) = 0$$$ $$$ ext{latency}(5) = max(3, 5) = 5$$$ $$$ ext{latency}(6) = 0$$$ $$$ ext{latency}(8) = 0$$$ $$$ ext{latency}(9) = max(2, 4) = 4$$$ So the total latency is $$$9$$$. | 2,500 | true | false | false | true | true | false | false | false | false | true | 140 |
108A | Problem - 108A - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags implementation strings *1000 No tag edit access → Contest materials ") | 1,000 | false | false | true | false | false | false | false | false | false | false | 9,451 |
1055E | You are a given a list of integers $$$a_1, a_2, ldots, a_n$$$ and $$$s$$$ of its segments $$$[l_j; r_j]$$$ (where $$$1 le l_j le r_j le n$$$). You need to select exactly $$$m$$$ segments in such a way that the $$$k$$$-th order statistic of the multiset of $$$a_i$$$, where $$$i$$$ is contained in at least one segment, is the smallest possible. If it's impossible to select a set of $$$m$$$ segments in such a way that the multiset contains at least $$$k$$$ elements, print -1. The $$$k$$$-th order statistic of a multiset is the value of the $$$k$$$-th element after sorting the multiset in non-descending order. Input The first line contains four integers $$$n$$$, $$$s$$$, $$$m$$$ and $$$k$$$ ($$$1 le m le s le 1500$$$, $$$1 le k le n le 1500$$$)xa0— the size of the list, the number of segments, the number of segments to choose and the statistic number. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 le a_i le 10^9$$$)xa0— the values of the numbers in the list. Each of the next $$$s$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 le l_i le r_i le n$$$)xa0— the endpoints of the segments. It is possible that some segments coincide. Output Print exactly one integerxa0— the smallest possible $$$k$$$-th order statistic, or -1 if it's impossible to choose segments in a way that the multiset contains at least $$$k$$$ elements. Examples Input 4 3 2 2 3 1 3 2 1 2 2 3 4 4 Input 5 2 1 1 1 2 3 4 5 2 4 1 5 Input 5 3 3 5 5 5 2 1 1 1 2 2 3 3 4 Note In the first example, one possible solution is to choose the first and the third segment. Together they will cover three elements of the list (all, except for the third one). This way the $$$2$$$-nd order statistic for the covered elements is $$$2$$$. | 2,500 | false | false | false | true | false | false | false | true | false | false | 5,435 |
305D | Olya has got a directed non-weighted graph, consisting of _n_ vertexes and _m_ edges. We will consider that the graph vertexes are indexed from 1 to _n_ in some manner. Then for any graph edge that goes from vertex _v_ to vertex _u_ the following inequation holds: _v_u2009<u2009_u_. Now Olya wonders, how many ways there are to add an arbitrary (possibly zero) number of edges to the graph so as the following conditions were met: 1. You can reach vertexes number _i_u2009+u20091,u2009_i_u2009+u20092,u2009...,u2009_n_ from any vertex number _i_ (_i_u2009<u2009_n_). 2. For any graph edge going from vertex _v_ to vertex _u_ the following inequation fulfills: _v_u2009<u2009_u_. 3. There is at most one edge between any two vertexes. 4. The shortest distance between the pair of vertexes _i_,u2009_j_ (_i_u2009<u2009_j_), for which _j_u2009-u2009_i_u2009≤u2009_k_ holds, equals _j_u2009-u2009_i_ edges. 5. The shortest distance between the pair of vertexes _i_,u2009_j_ (_i_u2009<u2009_j_), for which _j_u2009-u2009_i_u2009>u2009_k_ holds, equals either _j_u2009-u2009_i_ or _j_u2009-u2009_i_u2009-u2009_k_ edges. We will consider two ways distinct, if there is the pair of vertexes _i_,u2009_j_ (_i_u2009<u2009_j_), such that first resulting graph has an edge from _i_ to _j_ and the second one doesn't have it. Help Olya. As the required number of ways can be rather large, print it modulo 1000000007 (109u2009+u20097). Input The first line contains three space-separated integers _n_,u2009_m_,u2009_k_ (2u2009≤u2009_n_u2009≤u2009106,u20090u2009≤u2009_m_u2009≤u2009105,u20091u2009≤u2009_k_u2009≤u2009106). The next _m_ lines contain the description of the edges of the initial graph. The _i_-th line contains a pair of space-separated integers _u__i_,u2009_v__i_ (1u2009≤u2009_u__i_u2009<u2009_v__i_u2009≤u2009_n_) — the numbers of vertexes that have a directed edge from _u__i_ to _v__i_ between them. It is guaranteed that any pair of vertexes _u__i_,u2009_v__i_ has at most one edge between them. It also is guaranteed that the graph edges are given in the order of non-decreasing _u__i_. If there are multiple edges going from vertex _u__i_, then it is guaranteed that these edges are given in the order of increasing _v__i_. Output Print a single integer — the answer to the problem modulo 1000000007 (109u2009+u20097). Examples Input 7 8 2 1 2 2 3 3 4 3 6 4 5 4 7 5 6 6 7 Note In the first sample there are two ways: the first way is not to add anything, the second way is to add a single edge from vertex 2 to vertex 5. | 2,200 | true | false | false | false | false | false | false | false | false | false | 8,613 |
1190D | There are $$$n$$$ points on the plane, the $$$i$$$-th of which is at $$$(x_i, y_i)$$$. Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area. The strange area is enclosed by three lines, $$$x = l$$$, $$$y = a$$$ and $$$x = r$$$, as its left side, its bottom side and its right side respectively, where $$$l$$$, $$$r$$$ and $$$a$$$ can be any real numbers satisfying that $$$l < r$$$. The upper side of the area is boundless, which you can regard as a line parallel to the $$$x$$$-axis at infinity. The following figure shows a strange rectangular area. A point $$$(x_i, y_i)$$$ is in the strange rectangular area if and only if $$$l < x_i < r$$$ and $$$y_i > a$$$. For example, in the above figure, $$$p_1$$$ is in the area while $$$p_2$$$ is not. Tokitsukaze wants to know how many different non-empty sets she can obtain by picking all the points in a strange rectangular area, where we think two sets are different if there exists at least one point in one set of them but not in the other. Input The first line contains a single integer $$$n$$$ ($$$1 leq n leq 2 imes 10^5$$$)xa0— the number of points on the plane. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$1 leq x_i, y_i leq 10^9$$$)xa0— the coordinates of the $$$i$$$-th point. All points are distinct. Output Print a single integerxa0— the number of different non-empty sets of points she can obtain. Note For the first example, there is exactly one set having $$$k$$$ points for $$$k = 1, 2, 3$$$, so the total number is $$$3$$$. For the second example, the numbers of sets having $$$k$$$ points for $$$k = 1, 2, 3$$$ are $$$3$$$, $$$2$$$, $$$1$$$ respectively, and their sum is $$$6$$$. For the third example, as the following figure shows, there are $$$2$$$ sets having one point; $$$3$$$ sets having two points; $$$1$$$ set having four points. Therefore, the number of different non-empty sets in this example is $$$2 + 3 + 0 + 1 = 6$$$. | 2,000 | false | false | false | false | true | false | false | false | true | false | 4,747 |
1835A | Consider all equalities of form $$$a + b = c$$$, where $$$a$$$ has $$$A$$$ digits, $$$b$$$ has $$$B$$$ digits, and $$$c$$$ has $$$C$$$ digits. All the numbers are positive integers and are written without leading zeroes. Find the $$$k$$$-th lexicographically smallest equality when written as a string like above or determine that it does not exist. For example, the first three equalities satisfying $$$A = 1$$$, $$$B = 1$$$, $$$C = 2$$$ are $$$1 + 9 = 10$$$, $$$2 + 8 = 10$$$, $$$2 + 9 = 11$$$. An equality $$$s$$$ is lexicographically smaller than an equality $$$t$$$ with the same lengths of the numbers if and only if the following holds: in the first position where $$$s$$$ and $$$t$$$ differ, the equality $$$s$$$ has a smaller digit than the corresponding digit in $$$t$$$. Input Each test contains multiple test cases. The first line of input contains a single integer $$$t$$$ ($$$1 leq t leq 10^3$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains integers $$$A$$$, $$$B$$$, $$$C$$$, $$$k$$$ ($$$1 leq A, B, C leq 6$$$, $$$1 leq k leq 10^{12}$$$). Each input file has at most $$$5$$$ test cases which do not satisfy $$$A, B, C leq 3$$$. Output For each test case, if there are strictly less than $$$k$$$ valid equalities, output $$$-1$$$. Otherwise, output the $$$k$$$-th equality as a string of form $$$a + b = c$$$. Example Input 7 1 1 1 9 2 2 3 1 2 2 1 1 1 5 6 42 1 6 6 10000000 5 5 6 3031568815 6 6 6 1000000000000 Output 2 + 1 = 3 10 + 90 = 100 -1 9 + 99996 = 100005 -1 78506 + 28543 = 107049 -1 Note In the first test case, the first $$$9$$$ solutions are: $$$langle 1, 1, 2 angle, langle 1, 2, 3 angle, langle 1, 3, 4 angle, langle 1, 4, 5 angle, langle 1, 5, 6 angle, langle 1, 6, 7 angle, langle 1, 7, 8 angle, langle 1, 8, 9 angle, langle 2, 1, 3 angle$$$. Int the third test case, there are no solutions as the smallest possible values for $$$a$$$ and $$$b$$$ are larger than the maximal possible value of $$$c$$$ — $$$10 + 10 = 20 > 9$$$. Please note that whitespaces in the output matter. | 1,700 | true | false | true | false | false | false | true | false | false | false | 1,278 |
97D | The Professor has lost his home robot yet again. After some thinking Professor understood that he had left the robot in the basement. The basement in Professor's house is represented by a rectangle _n_u2009×u2009_m_, split into 1u2009×u20091 squares. Some squares are walls which are impassable; other squares are passable. You can get from any passable square to any other passable square moving through edge-adjacent passable squares. One passable square is the exit from the basement. The robot is placed exactly in one passable square. Also the robot may be placed in the exit square. Professor is scared of going to the dark basement looking for the robot at night. However, he has a basement plan and the robot's remote control. Using the remote, Professor can send signals to the robot to shift one square left, right, up or down. When the robot receives a signal, it moves in the required direction if the robot's neighboring square in the given direction is passable. Otherwise, the robot stays idle. Professor wrote a sequence of _k_ commands on a piece of paper. He thinks that the sequence can lead the robot out of the basement, wherever it's initial position might be. Professor programmed another robot to press the required buttons on the remote according to the notes on the piece of paper. Professor was just about to run the program and go to bed, when he had an epiphany. Executing each command takes some energy and Professor doesn't want to get huge electricity bill at the end of the month. That's why he wants to find in the sequence he has written out the minimal possible prefix that would guarantee to lead the robot out to the exit after the prefix is fulfilled. And that's the problem Professor challenges you with at this late hour. Input The first line contains three integers _n_, _m_ and _k_ (3u2009≤u2009_n_,u2009_m_u2009≤u2009150, 1u2009≤u2009_k_u2009≤u2009105). Next _n_ lines contain _m_ characters each — that is the Professor's basement's description: "#" stands for a wall, "." stands for a passable square and "E" stands for the exit from the basement (this square also is passable). It is possible to get from each passable square to the exit, all squares located by the _n_u2009×u2009_m_ rectangle's perimeter are the walls. Exactly one square is the exit from the basement. The last line contains _k_ characters, the description of the sequence of commands that Professor has written out on a piece of paper. "L", "R", "U", "D" stand for commands left, right, up and down correspondingly. Output Print in the output file the length of the smallest possible prefix that will lead the robot to the exit square. In other words, wherever the robot had been positioned initially, it should be positioned in the exit square after all the commands from the prefix are fulfilled (during doing commands the robot can come and leave the exit square, but only the last position of the robot is interesting for us). If Professor is mistaken and no prefix (including the whole sequence) can bring the robot to the exit, print "-1" (without the quotes). If there is the only passable square and it is the exit, print "0" (without the quotes). | 2,700 | false | false | true | false | false | false | true | false | false | false | 9,498 |
962B | There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger. The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting. Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all). Input The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 le n le 2cdot10^{5}$$$, $$$0 le a, b le 2cdot10^{5}$$$, $$$a + b > 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member. Output Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete. Note In the first example you can put all student, for example, in the following way: *.AB* In the second example you can put four students, for example, in the following way: *BAB*B In the third example you can put seven students, for example, in the following way: B*ABAB**A*B The letter A means a student-programmer, and the letter B — student-athlete. | 1,300 | false | true | true | false | false | true | false | false | false | false | 5,855 |
1946D | Yarik's birthday is coming soon, and Mark decided to give him an array $$$a$$$ of length $$$n$$$. Mark knows that Yarik loves bitwise operations very much, and he also has a favorite number $$$x$$$, so Mark wants to find the maximum number $$$k$$$ such that it is possible to select pairs of numbers xa0— the number of test cases. The following lines contain the descriptions of the test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 le n le 10^5, 0 le x < 2^{30}$$$)xa0— the length of the array $$$a$$$ and the number $$$x$$$ respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$0 le a_i < 2^{30}$$$)xa0— the array $$$a$$$ itself. It is guaranteed that the sum of the values of $$$n$$$ across all test cases does not exceed $$$10^5$$$. Output For each test case, output a single integer on a separate linexa0— the maximum suitable number $$$k$$$, and $$$-1$$$ if such $$$k$$$ does not exist. Example Input 8 3 1 1 2 3 2 2 1 1 2 2 1 3 2 3 0 0 3 2 0 0 1 4 2 1 3 3 7 2 2 2 3 5 0 0 1 2 2 1 Note In the first test case, you can take $$$k$$$ equal to $$$2$$$ and choose two segments [$$$1, 1$$$] and [$$$2, 3$$$], $$$(1) (2 oplus 3) = 1$$$. It can be shown that $$$2$$$ is the maximum possible answer. In the second test case, the segments [$$$1, 1$$$] and [$$$2, 2$$$] are suitable, $$$(1) (1) = 1$$$. It is not possible to make more segments. In the third test case, it is not possible to choose $$$2$$$ segments, as $$$(1) (3) = 3 > 2$$$, so the optimal answer is $$$1$$$. | 1,900 | false | true | true | false | false | true | true | false | false | false | 602 |
827A | Ivan had string _s_ consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string _s_. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string _s_. Namely, he remembers, that string _t__i_ occurs in string _s_ at least _k__i_ times or more, he also remembers exactly _k__i_ positions where the string _t__i_ occurs in string _s_: these positions are _x__i_,u20091,u2009_x__i_,u20092,u2009...,u2009_x__i_,u2009_k__i_. He remembers _n_ such strings _t__i_. You are to reconstruct lexicographically minimal string _s_ such that it fits all the information Ivan remembers. Strings _t__i_ and string _s_ consist of small English letters only. Input The first line contains single integer _n_ (1u2009≤u2009_n_u2009≤u2009105) — the number of strings Ivan remembers. The next _n_ lines contain information about the strings. The _i_-th of these lines contains non-empty string _t__i_, then positive integer _k__i_, which equal to the number of times the string _t__i_ occurs in string _s_, and then _k__i_ distinct positive integers _x__i_,u20091,u2009_x__i_,u20092,u2009...,u2009_x__i_,u2009_k__i_ in increasing order — positions, in which occurrences of the string _t__i_ in the string _s_ start. It is guaranteed that the sum of lengths of strings _t__i_ doesn't exceed 106, 1u2009≤u2009_x__i_,u2009_j_u2009≤u2009106, 1u2009≤u2009_k__i_u2009≤u2009106, and the sum of all _k__i_ doesn't exceed 106. The strings _t__i_ can coincide. It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists. Output Print lexicographically minimal string that fits all the information Ivan remembers. Examples Input 3 a 4 1 3 5 7 ab 2 1 5 ca 1 4 Input 3 ab 1 1 aba 1 3 ab 2 3 5 | 1,700 | false | true | false | false | true | false | false | false | true | false | 6,455 |
1296F | There are $$$n$$$ railway stations in Berland. They are connected to each other by $$$n-1$$$ railway sections. The railway network is connected, i.e. can be represented as an undirected tree. You have a map of that network, so for each railway section you know which stations it connects. Each of the $$$n-1$$$ sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from $$$1$$$ to $$$10^6$$$ inclusive. You asked $$$m$$$ passengers some questions: the $$$j$$$-th one told you three values: his departure station $$$a_j$$$; his arrival station $$$b_j$$$; minimum scenery beauty along the path from $$$a_j$$$ to $$$b_j$$$ (the train is moving along the shortest path from $$$a_j$$$ to $$$b_j$$$). You are planning to update the map and set some value $$$f_i$$$ on each railway section — the scenery beauty. The passengers' answers should be consistent with these values. Print any valid set of values $$$f_1, f_2, dots, f_{n-1}$$$, which the passengers' answer is consistent with or report that it doesn't exist. Input The first line contains a single integer $$$n$$$ ($$$2 le n le 5000$$$) — the number of railway stations in Berland. The next $$$n-1$$$ lines contain descriptions of the railway sections: the $$$i$$$-th section description is two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 le x_i, y_i le n, x_i e y_i$$$), where $$$x_i$$$ and $$$y_i$$$ are the indices of the stations which are connected by the $$$i$$$-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway. The next line contains a single integer $$$m$$$ ($$$1 le m le 5000$$$) — the number of passengers which were asked questions. Then $$$m$$$ lines follow, the $$$j$$$-th line contains three integers $$$a_j$$$, $$$b_j$$$ and $$$g_j$$$ ($$$1 le a_j, b_j le n$$$; $$$a_j e b_j$$$; $$$1 le g_j le 10^6$$$) — the departure station, the arrival station and the minimum scenery beauty along his path. Output If there is no answer then print a single integer -1. Otherwise, print $$$n-1$$$ integers $$$f_1, f_2, dots, f_{n-1}$$$ ($$$1 le f_i le 10^6$$$), where $$$f_i$$$ is some valid scenery beauty along the $$$i$$$-th railway section. If there are multiple answers, you can print any of them. Examples Input 4 1 2 3 2 3 4 2 1 2 5 1 3 3 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 Input 6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 | 2,100 | false | true | false | false | false | true | false | false | true | false | 4,211 |
1071E | A lot of people dream of convertibles (also often called cabriolets). Some of convertibles, however, don't have roof at all, and are vulnerable to rain. This is why Melon Ask, the famous inventor, decided to create a rain protection mechanism for convertibles. The workplace of the mechanism is a part of plane just above the driver. Its functional part consists of two rails with sliding endpoints of a piece of stretching rope. For the sake of simplicity we can consider this as a pair of parallel segments in a plane with the rope segment, whose endpoints we are free to choose as any points on these rails segments. The algorithmic part of the mechanism detects each particular raindrop and predicts when and where it reaches the plane. At this exact moment the rope segment must contain the raindrop point (so the rope adsorbs the raindrop). You are given the initial position of the rope endpoints and all information about raindrops. You are to choose the minimal possible speed $$$v$$$ of the endpoints sliding (both endpoints can slide in any direction along their segments independently of each other) in such a way that it is possible to catch all raindrops moving both endpoints with speed not greater than $$$v$$$, or find out that it's impossible no matter how high the speed is. Input The first line contains three integers $$$n$$$, $$$w$$$ and $$$h$$$ ($$$1 le n le 10^5$$$, $$$1le w, h le 10^3$$$), meaning that there are $$$n$$$ raindrops, and two rails are represented as segments connecting $$$(0, 0)$$$ and $$$(w, 0)$$$ and connecting $$$(0, h)$$$ and $$$(w, h)$$$. The second line contains two integers $$$e_1$$$ and $$$e_2$$$, meaning that the initial (that is, at the moment $$$t = 0$$$) positions of the endpoints are $$$(e_1, 0)$$$ and $$$(e_2, h)$$$ ($$$0le e_1, e_2le w$$$). The $$$i$$$-th of the following $$$n$$$ lines contains three integers $$$t_i$$$, $$$x_i$$$ and $$$y_i$$$ ($$$1le t_ile 10^5$$$, $$$0le x_i le w$$$, $$$0 < y_i < h$$$) meaning that the $$$i$$$-th raindrop touches the plane at the point $$$(x_i, y_i)$$$ at the time moment $$$t_i$$$. It is guaranteed that $$$t_i le t_{i+1}$$$ for all valid $$$i$$$. Output If it is impossible to catch all raindrops, print $$$-1$$$. Otherwise, print the least possible maximum speed of the rope endpoints for which it is possible to catch them all. Your answer is considered correct if the absolute or relative error doesn't exceed $$$10^{-4}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$frac{a - b}{max{(1, b)}} le 10^{-4}$$$. Examples Input 3 5 5 0 0 1 1 4 2 2 4 3 3 4 Input 3 5 5 0 0 1 2 1 1 3 3 1 4 2 Note That is how one can act in the first sample test: Here is the same for the second: | 3,500 | false | false | false | false | false | false | false | true | false | false | 5,354 |
764B | Young Timofey has a birthday today! He got kit of _n_ cubes as a birthday present from his parents. Every cube has a number _a__i_, which is written on it. Timofey put all the cubes in a row and went to unpack other presents. In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to _n_ in their order. Dima performs several steps, on step _i_ he reverses the segment of cubes from _i_-th to (_n_u2009-u2009_i_u2009+u20091)-th. He does this while _i_u2009≤u2009_n_u2009-u2009_i_u2009+u20091. After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holidayxa0— restore the initial order of the cubes using information of their current location. Input The first line contains single integer _n_ (1u2009≤u2009_n_u2009≤u20092·105)xa0— the number of cubes. The second line contains _n_ integers _a_1,u2009_a_2,u2009...,u2009_a__n_ (u2009-u2009109u2009≤u2009_a__i_u2009≤u2009109), where _a__i_ is the number written on the _i_-th cube after Dima has changed their order. Output Print _n_ integers, separated by spacesxa0— the numbers written on the cubes in their initial order. It can be shown that the answer is unique. Note Consider the first sample. 1. At the begining row was [2, 3, 9, 6, 7, 1, 4]. 2. After first operation row was [4, 1, 7, 6, 9, 3, 2]. 3. After second operation row was [4, 3, 9, 6, 7, 1, 2]. 4. After third operation row was [4, 3, 7, 6, 9, 1, 2]. 5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. | 900 | false | false | true | false | false | true | false | false | false | false | 6,731 |
1005C | A sequence $$$a_1, a_2, dots, a_n$$$ is called good if, for each element $$$a_i$$$, there exists an element $$$a_j$$$ ($$$i e j$$$) such that $$$a_i+a_j$$$ is a power of two (that is, $$$2^d$$$ for some non-negative integer $$$d$$$). For example, the following sequences are good: $$$[5, 3, 11]$$$ (for example, for $$$a_1=5$$$ we can choose $$$a_2=3$$$. Note that their sum is a power of two. Similarly, such an element can be found for $$$a_2$$$ and $$$a_3$$$), $$$[1, 1, 1, 1023]$$$, $$$[7, 39, 89, 25, 89]$$$, $$$[]$$$. Note that, by definition, an empty sequence (with a length of $$$0$$$) is good. For example, the following sequences are not good: $$$[16]$$$ (for $$$a_1=16$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two), $$$[4, 16]$$$ (for $$$a_1=4$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two), $$$[1, 3, 2, 8, 8, 8]$$$ (for $$$a_3=2$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two). You are given a sequence $$$a_1, a_2, dots, a_n$$$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements. Input The first line contains the integer $$$n$$$ ($$$1 le n le 120000$$$) — the length of the given sequence. The second line contains the sequence of integers $$$a_1, a_2, dots, a_n$$$ ($$$1 le a_i le 10^9$$$). Output Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $$$n$$$ elements, make it empty, and thus get a good sequence. Note In the first example, it is enough to delete one element $$$a_4=5$$$. The remaining elements form the sequence $$$[4, 7, 1, 4, 9]$$$, which is good. | 1,300 | false | true | true | false | false | false | true | false | false | false | 5,660 |
550B | You have _n_ problems. You have estimated the difficulty of the _i_-th one as integer _c__i_. Now you want to prepare a problemset for a contest, using some of the problems you've made. A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must be at least _l_ and at most _r_. Also, you think that the difference between difficulties of the easiest and the hardest of the chosen problems must be at least _x_. Find the number of ways to choose a problemset for the contest. Input The first line contains four integers _n_, _l_, _r_, _x_ (1u2009≤u2009_n_u2009≤u200915, 1u2009≤u2009_l_u2009≤u2009_r_u2009≤u2009109, 1u2009≤u2009_x_u2009≤u2009106) — the number of problems you have, the minimum and maximum value of total difficulty of the problemset and the minimum difference in difficulty between the hardest problem in the pack and the easiest one, respectively. The second line contains _n_ integers _c_1,u2009_c_2,u2009...,u2009_c__n_ (1u2009≤u2009_c__i_u2009≤u2009106) — the difficulty of each problem. Output Print the number of ways to choose a suitable problemset for the contest. Examples Input 4 40 50 10 10 20 30 25 Input 5 25 35 10 10 10 20 10 20 Note In the first example two sets are suitable, one consisting of the second and third problem, another one consisting of all three problems. In the second example, two sets of problems are suitable — the set of problems with difficulties 10 and 30 as well as the set of problems with difficulties 20 and 30. In the third example any set consisting of one problem of difficulty 10 and one problem of difficulty 20 is suitable. | 1,400 | false | false | false | false | false | false | true | false | false | false | 7,636 |
981B | Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies. In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies. All elements are enumerated with integers. The ChemForces company has discovered $$$n$$$ distinct chemical elements with indices $$$a_1, a_2, ldots, a_n$$$, and will get an income of $$$x_i$$$ Berland rubles if the $$$i$$$-th element from this list is in the set of this company. The TopChemist company discovered $$$m$$$ distinct chemical elements with indices $$$b_1, b_2, ldots, b_m$$$, and it will get an income of $$$y_j$$$ Berland rubles for including the $$$j$$$-th element from this list to its set. In other words, the first company can present any subset of elements from $$${a_1, a_2, ldots, a_n}$$$ (possibly empty subset), the second company can present any subset of elements from $$${b_1, b_2, ldots, b_m}$$$ (possibly empty subset). There shouldn't be equal elements in the subsets. Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible. Input The first line contains a single integer $$$n$$$ ($$$1 leq n leq 10^5$$$) xa0— the number of elements discovered by ChemForces. The $$$i$$$-th of the next $$$n$$$ lines contains two integers $$$a_i$$$ and $$$x_i$$$ ($$$1 leq a_i leq 10^9$$$, $$$1 leq x_i leq 10^9$$$) xa0— the index of the $$$i$$$-th element and the income of its usage on the exhibition. It is guaranteed that all $$$a_i$$$ are distinct. The next line contains a single integer $$$m$$$ ($$$1 leq m leq 10^5$$$) xa0— the number of chemicals invented by TopChemist. The $$$j$$$-th of the next $$$m$$$ lines contains two integers $$$b_j$$$ and $$$y_j$$$, ($$$1 leq b_j leq 10^9$$$, $$$1 leq y_j leq 10^9$$$) xa0— the index of the $$$j$$$-th element and the income of its usage on the exhibition. It is guaranteed that all $$$b_j$$$ are distinct. Note In the first example ChemForces can choose the set ($$$3, 7$$$), while TopChemist can choose ($$$1, 2, 4$$$). This way the total income is $$$(10 + 2) + (4 + 4 + 4) = 24$$$. In the second example ChemForces can choose the only element $$$10^9$$$, while TopChemist can choose ($$$14, 92, 35$$$). This way the total income is $$$(239) + (15 + 65 + 89) = 408$$$. | 1,000 | false | false | false | false | false | false | false | false | true | false | 5,799 |
605D | You are playing a board card game. In this game the player has two characteristics, _x_ and _y_xa0— the white magic skill and the black magic skill, respectively. There are _n_ spell cards lying on the table, each of them has four characteristics, _a__i_, _b__i_, _c__i_ and _d__i_. In one move a player can pick one of the cards and cast the spell written on it, but only if first two of it's characteristics meet the requirement _a__i_u2009≤u2009_x_ and _b__i_u2009≤u2009_y_, i.e. if the player has enough magic skill to cast this spell. However, after casting the spell the characteristics of a player change and become equal to _x_u2009=u2009_c__i_ and _y_u2009=u2009_d__i_. At the beginning of the game both characteristics of a player are equal to zero. The goal of the game is to cast the _n_-th spell. Your task is to make it in as few moves as possible. You are allowed to use spell in any order and any number of times (for example, you may not use some spells at all). Input The first line of the input contains a single integer _n_ (1u2009≤u2009_n_u2009≤u2009100u2009000)xa0— the number of cards on the table. Each of the next _n_ lines contains four integers _a__i_, _b__i_, _c__i_, _d__i_ (0u2009≤u2009_a__i_,u2009_b__i_,u2009_c__i_,u2009_d__i_u2009≤u2009109)xa0— the characteristics of the corresponding card. Output In the first line print a single integer _k_xa0— the minimum number of moves needed to cast the _n_-th spell and in the second line print _k_ numbersxa0— the indices of the cards in the order in which you should cast them. In case there are multiple possible solutions, print any of them. If it is impossible to cast the _n_-th spell, print u2009-u20091. Examples Input 4 0 0 3 4 2 2 5 3 4 1 1 7 5 3 8 8 Input 2 0 0 4 6 5 1 1000000000 1000000000 | 2,500 | false | false | false | false | true | false | false | false | false | false | 7,423 |
1627D | You have an array $$$a_1, a_2, dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it: Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i e j$$$) such that $$$gcd(a_i, a_j)$$$ is not present in the array, and add $$$gcd(a_i, a_j)$$$ to the end of the array. Here $$$gcd(x, y)$$$ denotes . The second line consists of $$$n$$$ integers $$$a_1, a_2, dots, a_n$$$ ($$$1 leq a_i leq 10^6$$$). All $$$a_i$$$ are distinct. Output Output a single line containing one integerxa0— the maximum number of times the operation can be performed on the given array. Note In the first example, one of the ways to perform maximum number of operations on the array is: Pick $$$i = 1, j= 5$$$ and add $$$gcd(a_1, a_5) = gcd(4, 30) = 2$$$ to the array. Pick $$$i = 2, j= 4$$$ and add $$$gcd(a_2, a_4) = gcd(20, 25) = 5$$$ to the array. Pick $$$i = 2, j= 5$$$ and add $$$gcd(a_2, a_5) = gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array. In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$. | 1,900 | true | false | false | true | false | false | true | false | false | false | 2,478 |
1387B1 | This problem is split into two tasks. In this task, you are required to find the minimum possible answer. In the task Village (Maximum) you are required to find the maximum possible answer. Each task is worth $$$50$$$ points. There are $$$N$$$ houses in a certain village. A single villager lives in each of the houses. The houses are connected by roads. Each road connects two houses and is exactly $$$1$$$ kilometer long. From each house it is possible to reach any other using one or several consecutive roads. In total there are $$$N-1$$$ roads in the village. One day all villagers decided to move to different houses — that is, after moving each house should again have a single villager living in it, but no villager should be living in the same house as before. We would like to know the smallest possible total length in kilometers of the shortest paths between the old and the new houses for all villagers. Example village with seven houses For example, if there are seven houses connected by roads as shown on the figure, the smallest total length is $$$8$$$ km (this can be achieved by moving $$$1 o 6$$$, $$$2 o 4$$$, $$$3 o 1$$$, $$$4 o 2$$$, $$$5 o 7$$$, $$$6 o 3$$$, $$$7 o 5$$$). Write a program that finds the smallest total length of the shortest paths in kilometers and an example assignment of the new houses to the villagers. Input The first line contains an integer $$$N$$$ ($$$1 < N le 10^5$$$). Houses are numbered by consecutive integers $$$1, 2, ldots, N$$$. Then $$$N-1$$$ lines follow that describe the roads. Each line contains two integers $$$a$$$ and $$$b$$$ ($$$1 le a, b le N$$$, $$$a eq b$$$) denoting that there is a road connecting houses $$$a$$$ and $$$b$$$. Output In the first line output the smallest total length of the shortest paths in kilometers. In the second line describe one valid assignment of the new houses with the smallest total length: $$$N$$$ space-separated distinct integers $$$v_1, v_2, ldots, v_N$$$. For each $$$i$$$, $$$v_i$$$ is the house number where the villager from the house $$$i$$$ should move ($$$v_i eq i$$$). If there are several valid assignments, output any of those. | 2,100 | false | true | false | true | false | false | false | false | false | false | 3,736 |
1660F1 | This is the easy version of Problem F. The only difference between the easy version and the hard version is the constraints. We will call a non-empty string balanced if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" and "" are not balanced. We will call a string promising if the string can be made balanced by several (possibly zero) uses of the following operation: replace two adjacent minus signs with one plus sign. In particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced. For example, the string "-+---" is promising, because you can replace two adjacent minuses with plus and get a balanced string "-++-", or get another balanced string "-+-+". How many non-empty substrings of the given string $$$s$$$ are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string $$$s$$$. Recall that a substring is a sequence of consecutive characters of the string. For example, for string "+-+" its substring are: "+-", "-+", "+", "+-+" (the string is a substring of itself) and some others. But the following strings are not its substring: "--", "++", "-++". Input The first line of the input contains an integer $$$t$$$ ($$$1 le t le 500$$$)xa0—the number of test cases in the test. Then the descriptions of test cases follow. Each test case of input data consists of two lines. The first line consists of the number $$$n$$$ ($$$1 le n le 3000$$$): the length of $$$s$$$. The second line of the test case contains the string $$$s$$$ of length $$$n$$$, consisting only of characters "+" and "-". It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$3000$$$. Output For each test case, print a single number: the number of the promising non-empty substrings of string $$$s$$$. Each non-empty promising substring must be counted in the answer as many times as it occurs in string $$$s$$$. | 1,700 | true | false | true | false | false | false | true | false | false | false | 2,321 |
2007C | Dora has just learned the programming language C++! However, she has completely misunderstood the meaning of C++. She considers it as two kinds of adding operations on the array $$$c$$$ with $$$n$$$ elements. Dora has two integers $$$a$$$ and $$$b$$$. In one operation, she can choose one of the following things to do. Choose an integer $$$i$$$ such that $$$1 leq i leq n$$$, and increase $$$c_i$$$ by $$$a$$$. Choose an integer $$$i$$$ such that $$$1 leq i leq n$$$, and increase $$$c_i$$$ by $$$b$$$. Note that $$$a$$$ and $$$b$$$ are constants, and they can be the same. Let's define a range of array $$$d$$$ as $$$max(d_i) - min(d_i)$$$. For instance, the range of the array $$$[1, 2, 3, 4]$$$ is $$$4 - 1 = 3$$$, the range of the array $$$[5, 2, 8, 2, 2, 1]$$$ is $$$8 - 1 = 7$$$, and the range of the array $$$[3, 3, 3]$$$ is $$$3 - 3 = 0$$$. After any number of operations (possibly, $$$0$$$), Dora calculates the range of the new array. You need to help Dora minimize this value, but since Dora loves exploring all by herself, you only need to tell her the minimized value. Input Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 leq t leq 10^4$$$)xa0— the number of test cases. The description of test cases follows. The first line of each test case contains three integers $$$n$$$, $$$a$$$, and $$$b$$$ ($$$1 leq n leq 10^5$$$, $$$1 leq a, b leq 10^9$$$)xa0— the length of the array $$$c$$$ and the constant values, respectively. The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, ldots, c_n$$$ ($$$1 leq c_i leq 10^9$$$)xa0— the initial elements of the array $$$c$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. Output For each test case, output a single integer — the minimum possible range of the array after any number of operations. Example Input 10 4 5 5 1 3 4 4 4 2 3 1 3 4 6 4 7 7 1 1 2 6 3 15 9 1 9 5 3 18 12 1 4 5 7 27 36 33 13 23 12 35 24 41 10 6 9 15 5 6 9 8 2 12 15 3 8 2 1 1000000000 1 1000000000 6 336718728 709848696 552806726 474775724 15129785 371139304 178408298 13106071 6 335734893 671469786 138885253 70095920 456876775 9345665 214704906 375508929 Output 3 0 3 2 3 5 1 0 17 205359241 Note In the first test case, we can increase $$$c_1 = 1$$$ by $$$a = 5$$$. The array $$$c$$$ will become $$$[6, 3, 4, 4]$$$, and the range is $$$3$$$. Note that there is more than one way to reach the answer. In the second test case, we can increase $$$c_1 = 1$$$ by $$$a = 2$$$ and then increase $$$c_1 = 3$$$ by $$$b = 3$$$. Also, we can increase $$$c_2 = 3$$$ by $$$b = 3$$$ and increase $$$c_3 = 4$$$ by $$$a = 2$$$. The array $$$c$$$ will become $$$[6, 6, 6, 6]$$$, and the range is $$$0$$$. | 1,500 | true | false | false | false | false | false | false | false | false | false | 209 |
1146B | Problem - 1146B - Codeforces =============== xa0 ]( "Forethought Future Cup") . He then generates a new string $$$t$$$ by concatenating $$$s$$$ and $$$s'$$$. In other words, $$$t=s+s'$$$ (look at notes for an example). You are given a string $$$t$$$. Your task is to find some $$$s$$$ that Bob could have used to generate $$$t$$$. It can be shown that if an answer exists, it will be unique. Input The first line of input contains a string $$$t$$$ ($$$1 leq t leq 10^5$$$) consisting of lowercase English letters. Output Print a string $$$s$$$ that could have generated $$$t$$$. It can be shown if an answer exists, it is unique. If no string exists, print ":(" (without double quotes, there is no space between the characters). Examples Input aaaaa Output aaaaa Input aacaababc Output :( Input ababacacbbcc Output ababacac Input baba Output :( Note In the first example, we have $$$s = $$$ "aaaaa", and $$$s' = $$$ "". In the second example, no such $$$s$$$ can work that will generate the given $$$t$$$. In the third example, we have $$$s = $$$ "ababacac", and $$$s' = $$$ "bbcc", and $$$t = s + s' = $$$ "ababacacbbcc". | 1,100 | false | false | true | false | false | false | false | false | false | false | 4,990 |
1906F | You are given a one-based array consisting of $$$N$$$ integers: $$$A_1, A_2, cdots, A_N$$$. Initially, the value of each element is set to $$$0$$$. There are $$$M$$$ operations (numbered from $$$1$$$ to $$$M$$$). Operation $$$i$$$ is represented by $$$langle L_i, R_i, X_i angle$$$. If operation $$$i$$$ is executed, all elements $$$A_j$$$ for $$$L_i leq j leq R_i$$$ will be increased by $$$X_i$$$. You have to answer $$$Q$$$ independent queries. Each query is represented by $$$langle K, S, T angle$$$ which represents the following task. Choose a range $$$[l, r]$$$ satisfying $$$S leq l leq r leq T$$$, and execute operations $$$l, l + 1, dots, r$$$. The answer to the query is the maximum value of $$$A_K$$$ after the operations are executed among all possible choices of $$$l$$$ and $$$r$$$. Input The first line consists of two integers $$$N$$$ $$$M$$$ ($$$1 leq N, M leq 100,000$$$). Each of the next $$$M$$$ lines consists of three integers $$$L_i$$$ $$$R_i$$$ $$$X_i$$$ ($$$1 leq L_i leq R_i leq N; -100,000 leq X_i leq 100,000$$$). The following line consists of an integer $$$Q$$$ ($$$1 leq Q leq 100,000$$$). Each of the next $$$Q$$$ lines consists of three integers $$$K$$$ $$$S$$$ $$$T$$$ ($$$1 leq K leq N; 1 leq S leq T leq M$$$). Output For each query, output in a single line, an integer which represent the answer of the query. Examples Input 2 6 1 1 -50 1 2 -20 2 2 -30 1 1 60 1 2 40 2 2 10 5 1 1 6 2 1 6 1 1 3 2 1 3 1 1 2 Input 5 3 1 3 3 2 4 -2 3 5 3 6 1 1 3 2 1 3 3 1 3 3 2 3 2 2 3 2 2 2 Note Explanation for the sample input/output #1 For query $$$1$$$, one of the solutions is to execute operation $$$4$$$ and $$$5$$$. For query $$$2$$$, one of the solutions is to execute operation $$$4$$$, $$$5$$$, and $$$6$$$. For query $$$3$$$, the only solution is to execute operation $$$3$$$. For query $$$4$$$, the only solution is to execute operation $$$1$$$. For query $$$6$$$, the only solution is to execute operation $$$2$$$. | 2,100 | false | false | false | false | true | false | false | false | true | false | 872 |
794G | Igor the analyst is at work. He learned about a feature in his text editor called "Replace All". Igor is too bored at work and thus he came up with the following problem: Given two strings _x_ and _y_ which consist of the English letters 'A' and 'B' only, a pair of strings (_s_,u2009_t_) is called good if: _s_ and _t_ consist of the characters '0' and '1' only. 1u2009≤u2009_s_,u2009_t_u2009≤u2009_n_, where _z_ denotes the length of string _z_, and _n_ is a fixed positive integer. If we replace all occurrences of 'A' in _x_ and _y_ with the string _s_, and replace all occurrences of 'B' in _x_ and _y_ with the string _t_, then the two obtained from _x_ and _y_ strings are equal. For example, if _x_u2009=u2009AAB, _y_u2009=u2009BB and _n_u2009=u20094, then (01, 0101) is one of good pairs of strings, because both obtained after replacing strings are "01010101". The flexibility of a pair of strings _x_ and _y_ is the number of pairs of good strings (_s_,u2009_t_). The pairs are ordered, for example the pairs (0, 1) and (1, 0) are different. You're given two strings _c_ and _d_. They consist of characters 'A', 'B' and '?' only. Find the sum of flexibilities of all possible pairs of strings (_c_',u2009_d_') such that _c_' and _d_' can be obtained from _c_ and _d_ respectively by replacing the question marks with either 'A' or 'B', modulo 109u2009+u20097. Input The first line contains the string _c_ (1u2009≤u2009_c_u2009≤u20093·105). The second line contains the string _d_ (1u2009≤u2009_d_u2009≤u20093·105). The last line contains a single integer _n_ (1u2009≤u2009_n_u2009≤u20093·105). Output Output a single integer: the answer to the problem, modulo 109u2009+u20097. Note For the first sample, there are four possible pairs of (_c_',u2009_d_'). If (_c_',u2009_d_')u2009=u2009(AA,u2009A), then the flexibility is 0. If (_c_',u2009_d_')u2009=u2009(AB,u2009A), then the flexibility is 0. If (_c_',u2009_d_')u2009=u2009(AA,u2009B), then the flexibility is 2, as the pairs of binary strings (1,u200911), (0,u200900) are the only good pairs. If (_c_',u2009_d_')u2009=u2009(AB,u2009B), then the flexibility is 0. Thus, the total flexibility is 2. For the second sample, there are 21u2009+u200922u2009+u2009...u2009+u2009210u2009=u20092046 possible binary strings of length not greater 10, and the set of pairs of good strings is precisely the set of pairs (_s_,u2009_s_), where _s_ is a binary string of length not greater than 10. | 3,400 | true | false | false | true | false | false | false | false | false | false | 6,594 |
707E | Like all children, Alesha loves New Year celebration. During the celebration he and his whole family dress up the fir-tree. Like all children, Alesha likes to play with garlandsxa0— chains consisting of a lightbulbs. Alesha uses a grid field sized _n_u2009×u2009_m_ for playing. The rows of the field are numbered from 1 to _n_ from the top to the bottom and columns are numbered from 1 to _m_ from the left to the right. Alesha has _k_ garlands which he places at the field. He does so in the way such that each lightbulb of each garland lies in the center of some cell in the field, and each cell contains at most one lightbulb. Of course lightbulbs, which are neighbours in some garland, appears in cells neighbouring by a side. The example of garland placing. Each garland is turned off or turned on at any moment. If some garland is turned on then each of its lightbulbs is turned on, the same applies for garland turned off. Each lightbulb in the whole garland set is unique, and thus, being turned on, brings Alesha some pleasure, described by an integer value. Turned off lightbulbs don't bring Alesha any pleasure. Alesha can turn garlands on and off and wants to know the sum of pleasure value which the lightbulbs, placed in the centers of the cells in some rectangular part of the field, bring him. Initially all the garlands are turned on. Alesha is still very little and can't add big numbers. He extremely asks you to help him. Input The first line of the input contains three integers _n_, _m_ and _k_ (1u2009≤u2009_n_,u2009_m_,u2009_k_u2009≤u20092000)xa0— the number of field rows, the number of field columns and the number of garlands placed at the field respectively. Next lines contains garlands set description in the following format: The first line of a single garland description contains a single integer _len_ (1u2009≤u2009_len_u2009≤u20092000)xa0— the number of lightbulbs in the garland. Each of the next _len_ lines contains three integers _i_, _j_ and _w_ (1u2009≤u2009_i_u2009≤u2009_n_, 1u2009≤u2009_j_u2009≤u2009_m_, 1u2009≤u2009_w_u2009≤u2009109)xa0— the coordinates of the cell containing a lightbullb and pleasure value Alesha gets from it if it is turned on. The lightbulbs are given in the order they are forming a chain in the garland. It is guaranteed that neighbouring lightbulbs are placed in the cells neighbouring by a side. The next line contains single integer _q_ (1u2009≤u2009_q_u2009≤u2009106)xa0— the number of events in Alesha's game. The next _q_ lines describes events in chronological order. The _i_-th of them describes the _i_-th event in the one of the following formats: SWITCH _i_xa0— Alesha turns off _i_-th garland if it is turned on, or turns it on if it is turned off. It is guaranteed that 1u2009≤u2009_i_u2009≤u2009_k_. ASK _x_1 _y_1 _x_2 _y_2xa0— Alesha wants to know the sum of pleasure values the lightbulbs, placed in a rectangular part of the field. Top-left cell of a part has coordinates (_x_1,u2009_y_1) and right-bottom cell has coordinates (_x_2,u2009_y_2). It is guaranteed that 1u2009≤u2009_x_1u2009≤u2009_x_2u2009≤u2009_n_ and 1u2009≤u2009_y_1u2009≤u2009_y_2u2009≤u2009_m_. There is no more than 2000 events of this type in the input. All the numbers in the input are integers. Please note that the input is quite large, so be careful while using some input ways. In particular, it's not recommended to use cin in codes on C++ and class Scanner in codes on Java. Output For each ASK operation print the sum Alesha wants to know in a separate line. Print the answers in chronological order. Examples Input 4 4 3 5 1 1 2 1 2 3 2 2 1 2 1 4 3 1 7 4 1 3 1 2 3 3 2 4 3 1 4 1 7 4 1 1 4 2 9 3 2 8 3 3 3 4 3 4 4 4 1 3 4 1 2 ASK 2 2 3 3 ASK 1 1 4 4 Input 4 4 1 8 4 1 1 3 1 2 2 1 1 1 1 7 1 2 5 2 2 4 2 3 1 1 3 1 3 ASK 1 1 3 2 SWITCH 1 ASK 1 1 3 2 Note This image illustrates the first sample case. | 2,400 | false | false | false | false | true | false | false | false | false | false | 6,990 |
1682E | Alice had a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. Alice can swap a pair $$$(x, y)$$$ which means swapping elements at positions $$$x$$$ and $$$y$$$ in $$$p$$$ (i.e. swap $$$p_x$$$ and $$$p_y$$$). Alice recently learned her first sorting algorithm, so she decided to sort her permutation in the minimum number of swaps possible. She wrote down all the swaps in the order in which she performed them to sort the permutation on a piece of paper. For example, $$$[(2, 3), (1, 3)]$$$ is a valid swap sequence by Alice for permutation $$$p = [3, 1, 2]$$$ whereas $$$[(1, 3), (2, 3)]$$$ is not because it doesn't sort the permutation. Note that we cannot sort the permutation in less than $$$2$$$ swaps. $$$[(1, 2), (2, 3), (2, 4), (2, 3)]$$$ cannot be a sequence of swaps by Alice for $$$p = [2, 1, 4, 3]$$$ even if it sorts the permutation because $$$p$$$ can be sorted in $$$2$$$ swaps, for example using the sequence $$$[(4, 3), (1, 2)]$$$. Unfortunately, Bob shuffled the sequence of swaps written by Alice. You are given Alice's permutation $$$p$$$ and the swaps performed by Alice in arbitrary order. Can you restore the correct sequence of swaps that sorts the permutation $$$p$$$? Since Alice wrote correct swaps before Bob shuffled them up, it is guaranteed that there exists some order of swaps that sorts the permutation. Input The first line contains $$$2$$$ integers $$$n$$$ and $$$m$$$ $$$(2 le n le 2 cdot 10^5, 1 le m le n - 1)$$$ xa0— the size of permutation and the minimum number of swaps required to sort the permutation. The next line contains $$$n$$$ integers $$$p_1, p_2, ..., p_n$$$ ($$$1 le p_i le n$$$, all $$$p_i$$$ are distinct) xa0— the elements of $$$p$$$. It is guaranteed that $$$p$$$ forms a permutation. Then $$$m$$$ lines follow. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ xa0— the $$$i$$$-th swap $$$(x_i, y_i)$$$. It is guaranteed that it is possible to sort $$$p$$$ with these $$$m$$$ swaps and that there is no way to sort $$$p$$$ with less than $$$m$$$ swaps. Output Print a permutation of $$$m$$$ integers xa0— a valid order of swaps written by Alice that sorts the permutation $$$p$$$. See sample explanation for better understanding. In case of multiple possible answers, output any. Note In the first example, $$$p = [2, 3, 4, 1]$$$, $$$m = 3$$$ and given swaps are $$$[(1, 4), (2, 1), (1, 3)]$$$. There is only one correct order of swaps i.e $$$[2, 3, 1]$$$. 1. First we perform the swap $$$2$$$ from the input i.e $$$(2, 1)$$$, $$$p$$$ becomes $$$[3, 2, 4, 1]$$$. 2. Then we perform the swap $$$3$$$ from the input i.e $$$(1, 3)$$$, $$$p$$$ becomes $$$[4, 2, 3, 1]$$$. 3. Finally we perform the swap $$$1$$$ from the input i.e $$$(1, 4)$$$ and $$$p$$$ becomes $$$[1, 2, 3, 4]$$$ which is sorted. In the second example, $$$p = [6, 5, 1, 3, 2, 4]$$$, $$$m = 4$$$ and the given swaps are $$$[(3, 1), (2, 5), (6, 3), (6, 4)]$$$. One possible correct order of swaps is $$$[4, 2, 1, 3]$$$. 1. Perform the swap $$$4$$$ from the input i.e $$$(6, 4)$$$, $$$p$$$ becomes $$$[6, 5, 1, 4, 2, 3]$$$. 2. Perform the swap $$$2$$$ from the input i.e $$$(2, 5)$$$, $$$p$$$ becomes $$$[6, 2, 1, 4, 5, 3]$$$. 3. Perform the swap $$$1$$$ from the input i.e $$$(3, 1)$$$, $$$p$$$ becomes $$$[1, 2, 6, 4, 5, 3]$$$. 4. Perform the swap $$$3$$$ from the input i.e $$$(6, 3)$$$ and $$$p$$$ becomes $$$[1, 2, 3, 4, 5, 6]$$$ which is sorted. There can be other possible answers such as $$$[1, 2, 4, 3]$$$. | 2,700 | true | true | false | false | false | true | false | false | true | true | 2,175 |
1119F | Niyaz has a tree with $$$n$$$ vertices numerated from $$$1$$$ to $$$n$$$. A tree is a connected graph without cycles. Each edge in this tree has strictly positive integer weight. A degree of a vertex is the number of edges adjacent to this vertex. Niyaz does not like when vertices in the tree have too large degrees. For each $$$x$$$ from $$$0$$$ to $$$(n-1)$$$, he wants to find the smallest total weight of a set of edges to be deleted so that degrees of all vertices become at most $$$x$$$. Input The first line contains a single integer $$$n$$$ ($$$2 le n le 250,000$$$)xa0— the number of vertices in Niyaz's tree. Each of the next $$$(n - 1)$$$ lines contains three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 le a, b le n$$$, $$$1 leq c leq 10^6$$$)xa0— the indices of the vertices connected by this edge and its weight, respectively. It is guaranteed that the given edges form a tree. Output Print $$$n$$$ integers: for each $$$x = 0, 1, ldots, (n-1)$$$ print the smallest total weight of such a set of edges that after one deletes the edges from the set, the degrees of all vertices become less than or equal to $$$x$$$. Examples Input 5 1 2 1 1 3 2 1 4 3 1 5 4 Input 5 1 2 1 2 3 2 3 4 5 4 5 14 Note In the first example, the vertex $$$1$$$ is connected with all other vertices. So for each $$$x$$$ you should delete the $$$(4-x)$$$ lightest edges outgoing from vertex $$$1$$$, so the answers are $$$1+2+3+4$$$, $$$1+2+3$$$, $$$1+2$$$, $$$1$$$ and $$$0$$$. In the second example, for $$$x=0$$$ you need to delete all the edges, for $$$x=1$$$ you can delete two edges with weights $$$1$$$ and $$$5$$$, and for $$$x geq 2$$$ it is not necessary to delete edges, so the answers are $$$1+2+5+14$$$, $$$1+5$$$, $$$0$$$, $$$0$$$ and $$$0$$$. | 3,400 | false | false | false | true | true | false | false | false | false | false | 5,089 |
353C | Problem - 353C - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags implementation math number theory *1600 No tag edit access → Contest materials ") ") , taking an integer from 0 to 2_n_u2009-u20091 as its single argument. Value _f_(_x_) is calculated by formula , where value _bit_(_i_) equals one if the binary representation of number _x_ contains a 1 on the _i_-th position, and zero otherwise. For example, if _n_u2009=u20094 and _x_u2009=u200911 (11u2009=u200920u2009+u200921u2009+u200923), then _f_(_x_)u2009=u2009_a_0u2009+u2009_a_1u2009+u2009_a_3. Help Valera find the maximum of function _f_(_x_) among all _x_, for which an inequality holds: 0u2009≤u2009_x_u2009≤u2009_m_. Input The first line contains integer _n_ (1u2009≤u2009_n_u2009≤u2009105) — the number of array elements. The next line contains _n_ space-separated integers _a_0,u2009_a_1,u2009...,u2009_a__n_u2009-u20091 (0u2009≤u2009_a__i_u2009≤u2009104) — elements of array _a_. The third line contains a sequence of digits zero and one without spaces _s_0_s_1... _s__n_u2009-u20091 — the binary representation of number _m_. Number _m_ equals . Output Print a single integer — the maximum value of function _f_(_x_) for all . Examples Input 2 3 8 10 Output 3 Input 5 17 0 10 2 1 11010 Output 27 Note In the first test case _m_u2009=u200920u2009=u20091,u2009_f_(0)u2009=u20090,u2009_f_(1)u2009=u2009_a_0u2009=u20093. In the second sample _m_u2009=u200920u2009+u200921u2009+u200923u2009=u200911, the maximum value of function equals _f_(5)u2009=u2009_a_0u2009+u2009_a_2u2009=u200917u2009+u200910u2009=u200927. | 1,600 | true | false | true | false | false | false | false | false | false | false | 8,421 |
1930G | Define a function $$$f$$$ such that for an array $$$b$$$, $$$f(b)$$$ returns the array of prefix maxima of $$$b$$$. In other words, $$$f(b)$$$ is an array containing only those elements $$$b_i$$$, for which $$$b_i=max(b_1,b_2,ldots,b_i)$$$, without changing their order. For example, $$$f([3,10,4,10,15,1])=[3,10,10,15]$$$. You are given a tree consisting of $$$n$$$ nodes rooted at $$$1$$$. A permutation$$$^dagger$$$ $$$p$$$ of is considered a pre-order of the tree if for all $$$i$$$ the following condition holds: Let $$$k$$$ be the number of proper descendants$$$^ddagger$$$ of node $$$p_i$$$. For all $$$x$$$ such that $$$i < x leq i+k$$$, $$$p_x$$$ is a proper descendant of node $$$p_i$$$. Find the number of distinct values of $$$f(a)$$$ over all possible pre-orders $$$a$$$. Since this value might be large, you only need to find it modulo $$$998,244,353$$$. $$$^dagger$$$ A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array), and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array). $$$^ddagger$$$ Node $$$t$$$ is a proper descendant of node $$$s$$$ if $$$s eq t$$$ and $$$s$$$ is on the unique simple path from $$$t$$$ to $$$1$$$. Input Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 leq t leq 10^5$$$)xa0— the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 leq n leq 10^6$$$)xa0— the number of vertices. The following next $$$n-1$$$ lines contain two integers $$$u$$$ and $$$v$$$ ($$$1 leq u, v leq n$$$, $$$u eq v$$$)xa0— denoting an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$. Note In the first test case, the only valid pre-order is $$$a=[1]$$$. So the only possible value of $$$f(a)$$$ is $$$[1]$$$. In the second test case, the only valid pre-order is $$$a=[1,2]$$$. So the only possible value $$$f(a)$$$ is $$$[1,2]$$$. In the third test case, the two valid pre-orders are $$$a=[1,2,3]$$$ and $$$a=[1,3,2]$$$. So the possible values of $$$f(a)$$$ are $$$[1,2,3]$$$ and $$$[1,3]$$$. In the fifth test case, the possible values of $$$f(a)$$$ are: $$$[1,5]$$$; $$$[1,2,5]$$$; $$$[1,3,5]$$$; $$$[1,4,5]$$$; $$$[1,2,3,5]$$$; $$$[1,2,4,5]$$$; $$$[1,3,4,5]$$$; $$$[1,2,3,4,5]$$$. | 3,100 | false | false | false | true | true | false | false | false | false | false | 704 |
131F | How many stars are there in the sky? A young programmer Polycarpus can't get this question out of his head! He took a photo of the starry sky using his digital camera and now he analyzes the resulting monochrome digital picture. The picture is represented by a rectangular matrix consisting of _n_ lines each containing _m_ characters. A character equals '1', if the corresponding photo pixel is white and '0', if it is black. Polycarpus thinks that he has found a star on the photo if he finds a white pixel surrounded by four side-neighboring pixels that are also white: 1 111 1 a star on the photo Polycarpus whats to cut out a rectangular area from the photo and give his mom as a present. This area should contain no less than _k_ stars. The stars can intersect, have shared white pixels on the photo. The boy will cut out the rectangular area so that its borders will be parallel to the sides of the photo and the cuts will go straight between the pixel borders. Now Polycarpus keeps wondering how many ways there are to cut an area out of the photo so that it met the conditions given above. Help Polycarpus find this number. Input The first line of the input data contains three integers _n_,u2009_m_ and _k_ (1u2009≤u2009_n_,u2009_m_u2009≤u2009500;1u2009≤u2009_k_u2009≤u2009_nm_). Then follow _n_ lines, containing the description of the given photo as a sequence of lines. Each line contains _m_ characters '0' or '1'. Output Print the required number of areas on the given photo. Examples Input 4 6 2 111000 111100 011011 000111 Input 5 5 4 11111 11111 11111 11111 11111 Note We'll number the rows and columns below starting from 1, the coordinates (_p_,u2009_q_) will denote a cell in row _p_, column _q_. In the first sample Polycarpus should cut out any area containing a rectangle whose opposite corners lie in cells (1,u20091) and (3,u20094). Only rectangles with opposite corners in (1,u20091) and (_x_,u2009_y_), where _x_u2009≥u20093 and _y_u2009≥u20094 fit the conditions. In the second sample any rectangle whose each side is no less than four, will do. The possible rectangle sizes are 4u2009×u20094, 4u2009×u20095, 5u2009×u20094 and 5u2009×u20095. Such figures can be cut in 4 ways, 2 ways, 2 ways and 1 way correspondingly. Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cin, cout streams or the %I64d specificator. | 2,000 | false | false | false | false | false | false | false | true | false | false | 9,348 |
575B | Ruritania is a country with a very badly maintained road network, which is not exactly good news for lorry drivers that constantly have to do deliveries. In fact, when roads are maintained, they become one-way. It turns out that it is sometimes impossible to get from one town to another in a legal way – however, we know that all towns are reachable, though illegally! Fortunately for us, the police tend to be very corrupt and they will allow a lorry driver to break the rules and drive in the wrong direction provided they receive ‘a small gift’. There is one patrol car for every road and they will request 1000 Ruritanian dinars when a driver drives in the wrong direction. However, being greedy, every time a patrol car notices the same driver breaking the rule, they will charge double the amount of money they requested the previous time on that particular road. Borna is a lorry driver that managed to figure out this bribing pattern. As part of his job, he has to make _K_ stops in some towns all over Ruritania and he has to make these stops in a certain order. There are _N_ towns (enumerated from 1 to _N_) in Ruritania and Borna’s initial location is the capital city i.e. town 1. He happens to know which ones out of the _N_u2009-u20091 roads in Ruritania are currently unidirectional, but he is unable to compute the least amount of money he needs to prepare for bribing the police. Help Borna by providing him with an answer and you will be richly rewarded. Input The first line contains _N_, the number of towns in Ruritania. The following _N_u2009-u20091 lines contain information regarding individual roads between towns. A road is represented by a tuple of integers (_a_,_b_,_x_), which are separated with a single whitespace character. The numbers _a_ and _b_ represent the cities connected by this particular road, and x is either 0 or 1: 0 means that the road is bidirectional, 1 means that only the _a_u2009→u2009_b_ direction is legal. The next line contains _K_, the number of stops Borna has to make. The final line of input contains K positive integers _s_1,u2009…,u2009_s__K_: the towns Borna has to visit. 1u2009≤u2009_N_u2009≤u2009105 1u2009≤u2009_K_u2009≤u2009106 1u2009≤u2009_a_,u2009_b_u2009≤u2009_N_ for all roads for all roads 1u2009≤u2009_s__i_u2009≤u2009_N_ for all 1u2009≤u2009_i_u2009≤u2009_K_ Output The output should contain a single number: the least amount of thousands of Ruritanian dinars Borna should allocate for bribes, modulo 109u2009+u20097. Examples Input 5 1 2 0 2 3 0 5 1 1 3 4 1 5 5 4 5 2 2 Note Borna first takes the route 1u2009→u20095 and has to pay 1000 dinars. After that, he takes the route 5u2009→u20091u2009→u20092u2009→u20093u2009→u20094 and pays nothing this time. However, when he has to return via 4u2009→u20093u2009→u20092u2009→u20091u2009→u20095, he needs to prepare 3000 (1000+2000) dinars. Afterwards, getting to 2 via 5u2009→u20091u2009→u20092 will cost him nothing. Finally, he doesn't even have to leave town 2 to get to 2, so there is no need to prepare any additional bribe money. Hence he has to prepare 4000 dinars in total. | 2,200 | false | false | false | false | false | false | false | false | false | true | 7,551 |
2024B | There is a vending machine that sells lemonade. The machine has a total of $$$n$$$ slots. You know that initially, the $$$i$$$-th slot contains $$$a_i$$$ cans of lemonade. There are also $$$n$$$ buttons on the machine, each button corresponds to a slot, with exactly one button corresponding to each slot. Unfortunately, the labels on the buttons have worn off, so you do not know which button corresponds to which slot. When you press the button corresponding to the $$$i$$$-th slot, one of two events occurs: If there is a can of lemonade in the $$$i$$$-th slot, it will drop out and you will take it. At this point, the number of cans in the $$$i$$$-th slot decreases by $$$1$$$. If there are no cans of lemonade left in the $$$i$$$-th slot, nothing will drop out. After pressing, the can drops out so quickly that it is impossible to track from which slot it fell. The contents of the slots are hidden from your view, so you cannot see how many cans are left in each slot. The only thing you know is the initial number of cans in the slots: $$$a_1, a_2, ldots, a_n$$$. Determine the minimum number of button presses needed to guarantee that you receive at least $$$k$$$ cans of lemonade. Note that you can adapt your strategy during the button presses based on whether you received a can or not. It is guaranteed that there are at least $$$k$$$ cans of lemonade in total in the machine. In other words, $$$k leq a_1 + a_2 + ldots + a_n$$$. Input Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 le t le 10^4$$$)xa0— the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 le n le 2 cdot 10^5$$$, $$$1 leq k leq 10^9$$$)xa0— the number of slots in the machine and the required number of cans of lemonade. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$1 le a_i le 10^9$$$)xa0— the number of cans in the slots. It is guaranteed that $$$k leq a_1 + a_2 + ldots + a_n$$$, meaning there are at least $$$k$$$ cans of lemonade in the machine. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 cdot 10^5$$$. Output For each test case, output a single integer — the minimum number of button presses needed to guarantee that you receive at least $$$k$$$ cans of lemonade. Example Input 5 2 1 1 1 2 2 1 2 3 4 2 1 3 10 50 1 1 3 8 8 9 12 13 27 27 2 1000000000 1000000000 500000000 Output 1 2 5 53 1000000000 Note In the first test case, we can simply press the first button and receive one can of lemonade. In the second test case, we can press each button once and guarantee that we receive $$$2$$$ cans of lemonade. Note that if we simply press one button twice, we might not be lucky, and that button could correspond to the first slot, in which case we would only receive $$$1$$$ can of lemonade for two presses. In the third test case, one of the optimal strategies is as follows: Press the first button twice. After the first press, a can of lemonade will definitely drop out. Then there are two options: If no can of lemonade drops after the second press, we know that this button must correspond to the second slot, since $$$a_2 = 1$$$ and $$$a_1, a_3 > 1$$$. Then we can press the second button twice and the third button once. Since $$$a_1, a_3 geq 2$$$, we will definitely receive three cans of lemonade for these three presses. Thus, after $$$5$$$ presses, we will have $$$4$$$ cans of lemonade. If a can of lemonade drops after the second press, we can make one press on the second button and one press on the third button. After each of these presses, we will definitely receive a can of lemonade. Thus, after $$$4$$$ presses, we will have $$$4$$$ cans of lemonade. It can be shown that it is impossible to guarantee receiving $$$4$$$ cans of lemonade with only $$$4$$$ presses, so the answer is $$$5$$$. | 1,100 | false | false | false | false | false | true | false | true | true | false | 124 |
1498B | You are given $$$n$$$ rectangles, each of height $$$1$$$. Each rectangle's width is a power of $$$2$$$ (i.u2009e. it can be represented as $$$2^x$$$ for some non-negative integer $$$x$$$). You are also given a two-dimensional box of width $$$W$$$. Note that $$$W$$$ may or may not be a power of $$$2$$$. Moreover, $$$W$$$ is at least as large as the width of the largest rectangle. You have to find the smallest height of this box, such that it is able to fit all the given rectangles. It is allowed to have some empty space left in this box after fitting all the rectangles. You cannot rotate the given rectangles to make them fit into the box. Moreover, any two distinct rectangles must not overlap, i.u2009e., any two distinct rectangles must have zero intersection area. See notes for visual explanation of sample input. Input The first line of input contains one integer $$$t$$$ ($$$1 le t le 5 cdot 10^3$$$) — the number of test cases. Each test case consists of two lines. For each test case: the first line contains two integers $$$n$$$ ($$$1 le n le 10^5$$$) and $$$W$$$ ($$$1 le W le 10^9$$$); the second line contains $$$n$$$ integers $$$w_1, w_2, dots, w_n$$$ ($$$1 le w_i le 10^6$$$), where $$$w_i$$$ is the width of the $$$i$$$-th rectangle. Each $$$w_i$$$ is a power of $$$2$$$; additionally, $$$maxlimits_{i=1}^{n} w_i le W$$$. The sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. Output Output $$$t$$$ integers. The $$$i$$$-th integer should be equal to the answer to the $$$i$$$-th test case — the smallest height of the box. Example Input 2 5 16 1 2 8 4 8 6 10 2 8 8 2 2 8 Note For the first test case in the sample input, the following figure shows one way to fit the given five rectangles into the 2D box with minimum height: In the figure above, the number inside each rectangle is its width. The width of the 2D box is $$$16$$$ (indicated with arrow below). The minimum height required for the 2D box in this case is $$$2$$$ (indicated on the left). In the second test case, you can have a minimum height of three by keeping two blocks (one each of widths eight and two) on each of the three levels. | 1,300 | false | true | false | false | true | false | false | true | false | false | 3,180 |
1480A | Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $$$s = s_1 s_2 dots s_n$$$ of length $$$n$$$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move. In a move, a player must choose an index $$$i$$$ ($$$1 leq i leq n$$$) that has not been chosen before, and change $$$s_i$$$ to any other lowercase English letter $$$c$$$ that $$$c eq s_i$$$. When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be. 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 e 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$$$. Input Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 le t le 1000$$$) xa0— the number of test cases. Description of the test cases follows. The only line of each test case contains a single string $$$s$$$ ($$$1 leq s leq 50$$$) consisting of lowercase English letters. Output For each test case, print the final string in a single line. Note In the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'. In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'. In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'. | 800 | false | true | false | false | false | false | false | false | false | false | 3,275 |
35C | After a terrifying forest fire in Berland a forest rebirth program was carried out. Due to it _N_ rows with _M_ trees each were planted and the rows were so neat that one could map it on a system of coordinates so that the _j_-th tree in the _i_-th row would have the coordinates of (_i_,u2009_j_). However a terrible thing happened and the young forest caught fire. Now we must find the coordinates of the tree that will catch fire last to plan evacuation. The burning began in _K_ points simultaneously, which means that initially _K_ trees started to burn. Every minute the fire gets from the burning trees to the ones that aren’t burning and that the distance from them to the nearest burning tree equals to 1. Find the tree that will be the last to start burning. If there are several such trees, output any. Input The first input line contains two integers _N_,u2009_M_ (1u2009≤u2009_N_,u2009_M_u2009≤u20092000) — the size of the forest. The trees were planted in all points of the (_x_,u2009_y_) (1u2009≤u2009_x_u2009≤u2009_N_,u20091u2009≤u2009_y_u2009≤u2009_M_) type, _x_ and _y_ are integers. The second line contains an integer _K_ (1u2009≤u2009_K_u2009≤u200910) — amount of trees, burning in the beginning. The third line contains _K_ pairs of integers: _x_1,u2009_y_1,u2009_x_2,u2009_y_2,u2009...,u2009_x__k_,u2009_y__k_ (1u2009≤u2009_x__i_u2009≤u2009_N_,u20091u2009≤u2009_y__i_u2009≤u2009_M_) — coordinates of the points from which the fire started. It is guaranteed that no two points coincide. Output Output a line with two space-separated integers _x_ and _y_ — coordinates of the tree that will be the last one to start burning. If there are several such trees, output any. | 1,500 | false | false | false | false | false | false | true | false | false | false | 9,821 |
1437C | Chef Monocarp has just put $$$n$$$ dishes into an oven. He knows that the $$$i$$$-th dish has its optimal cooking time equal to $$$t_i$$$ minutes. At any positive integer minute $$$T$$$ Monocarp can put no more than one dish out of the oven. If the $$$i$$$-th dish is put out at some minute $$$T$$$, then its unpleasant value is $$$T - t_i$$$xa0— the absolute difference between $$$T$$$ and $$$t_i$$$. Once the dish is out of the oven, it can't go back in. Monocarp should put all the dishes out of the oven. What is the minimum total unpleasant value Monocarp can obtain? Input The first line contains a single integer $$$q$$$ ($$$1 le q le 200$$$)xa0— the number of testcases. Then $$$q$$$ testcases follow. The first line of the testcase contains a single integer $$$n$$$ ($$$1 le n le 200$$$)xa0— the number of dishes in the oven. The second line of the testcase contains $$$n$$$ integers $$$t_1, t_2, dots, t_n$$$ ($$$1 le t_i le n$$$)xa0— the optimal cooking time for each dish. The sum of $$$n$$$ over all $$$q$$$ testcases doesn't exceed $$$200$$$. Output Print a single integer for each testcasexa0— the minimum total unpleasant value Monocarp can obtain when he puts out all the dishes out of the oven. Remember that Monocarp can only put the dishes out at positive integer minutes and no more than one dish at any minute. Example Input 6 6 4 2 4 4 5 2 7 7 7 7 7 7 7 7 1 1 5 5 1 2 4 3 4 1 4 4 4 21 21 8 1 4 1 5 21 1 8 21 11 21 11 3 12 8 19 15 9 11 13 Note In the first example Monocarp can put out the dishes at minutes $$$3, 1, 5, 4, 6, 2$$$. That way the total unpleasant value will be $$$4 - 3 + 2 - 1 + 4 - 5 + 4 - 4 + 6 - 5 + 2 - 2 = 4$$$. In the second example Monocarp can put out the dishes at minutes $$$4, 5, 6, 7, 8, 9, 10$$$. In the third example Monocarp can put out the dish at minute $$$1$$$. In the fourth example Monocarp can put out the dishes at minutes $$$5, 1, 2, 4, 3$$$. In the fifth example Monocarp can put out the dishes at minutes $$$1, 3, 4, 5$$$. | 1,800 | true | true | false | true | false | false | false | false | true | false | 3,483 |
1672D | There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times: Choose two indices $$$l$$$ and $$$r$$$ where $$$1 le l < r le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l ldots r] = [a_{l+1}, a_{l+2}, ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times. Input Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 leq t leq 10^4$$$) xa0— the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 le n le 2 cdot 10 ^ 5$$$) xa0— the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$1 le a_i le n$$$) xa0— elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, ldots, b_n$$$ ($$$1 le b_i le n$$$) xa0— elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 cdot 10 ^ 5$$$ Output For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response). Example Input 5 5 1 2 3 3 2 1 3 3 2 2 5 1 2 4 2 1 4 2 2 1 1 5 2 4 5 5 2 2 2 4 5 5 3 1 2 3 1 2 3 3 1 1 2 2 1 1 Note In the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$. In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$. In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation. | 1,700 | false | true | true | false | false | true | false | false | false | false | 2,242 |
159E | Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color _c__i_ and size _s__i_. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower. A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes. Input The first line contains an integer _n_ (2u2009≤u2009_n_u2009≤u2009105) — the number of cubes. Next _n_ lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers _c__i_ and _s__i_ (1u2009≤u2009_c__i_,u2009_s__i_u2009≤u2009109) — the _i_-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors. Output Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to _n_ in the order in which they were given in the input. If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator. | 1,700 | false | true | false | false | true | false | false | false | true | false | 9,236 |
2022A | Enter Register HOME TOP CATALOG CONTESTS GYM PROBLEMSET GROUPS RATING EDU API CALENDAR HELP RAYAN Codeforces Round 978 (Div. 2) Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags constructive algorithms greedy implementation math *800 No tag edit access → Contest materials Announcement (en) Tutorial (en) PROBLEMS SUBMIT STATUS STANDINGS CUSTOM TEST A. Bus to Pénjamo time limit per test1 second memory limit per test256 megabytes Ya vamos llegando a Péeeenjamoo ♫♫♫ There are $$$n$$$ families travelling to Pénjamo to witness Mexico's largest-ever "walking a chicken on a leash" marathon. The $$$i$$$-th family has $$$a_i$$$ family members. All families will travel using a single bus consisting of $$$r$$$ rows with $$$2$$$ seats each. A person is considered happy if: Another family member is seated in the same row as them, or They are sitting alone in their row (with an empty seat next to them). Determine the maximum number of happy people in an optimal seating arrangement. Note that everyone must be seated in the bus. It is guaranteed that all family members will fit on the bus. Formally, it is guaranteed that $$$displaystylesum_{i=1}^{n}a_i le 2r$$$. Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 1000$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$r$$$ ($$$1 le n le 100$$$; $$$1 le r le 500$$$)xa0— the number of families and the number of rows in the bus. The second line contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$1 le a_i le 10$$$)xa0— the number of family members in each family. Output For each test case, output the maximum number of happy people in an optimal seating arrangement. Example input 4 3 3 2 3 1 3 3 2 2 2 4 5 1 1 2 2 4 5 3 1 1 3 output 4 6 6 6 Note In the first test case, the two members of the first family can sit together in the first row, while the two members of the second family can sit together in the second row. The remaining member of the second family can sit in the third row along with a member of the third family. This seating arrangement is shown below, where the $$$4$$$ happy people are colored green. $$$color{green}{1}$$$ $$$color{green}{1}$$$ $$$color{green}{2}$$$ $$$color{green}{2}$$$ $$$2$$$ $$$3$$$ In the second test case, a possible seating arrangement with $$$6$$$ happy people is shown below. $$$color{green}{3}$$$ $$$color{green}{3}$$$ $$$color{green}{1}$$$ $$$color{green}{1}$$$ $$$color{green}{2}$$$ $$$color{green}{2}$$$ In the third test case, a possible seating arrangement with $$$6$$$ happy people is shown below. $$$color{green}{4}$$$ $$$color{green}{4}$$$ $$$color{green}{}$$$ $$$color{green}{2}$$$ $$$color{green}{3}$$$ $$$color{green}{3}$$$ $$$color{green}{1}$$$ $$$color{green}{}$$$ $$$color{green}{}$$$ $$$color{green}{}$$$ Codeforces (c) | 800 | true | true | true | false | false | true | false | false | false | false | 138 |
734F | Problem - 734F - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags bitmasks constructive algorithms implementation math *2500 No tag edit access → Contest materials ") ") xa0— the size of arrays _b_ and _c_. The second line contains _n_ integers _b__i_ (0u2009≤u2009_b__i_u2009≤u2009109)xa0— elements of the array _b_. Third line contains _n_ integers _c__i_ (0u2009≤u2009_c__i_u2009≤u2009109)xa0— elements of the array _c_. Output If there is no solution, print u2009-u20091. Otherwise, the only line of the output should contain _n_ non-negative integers _a__i_xa0— elements of the array _a_. If there are multiple possible solutions, you may print any of them. Examples Input 4 6 8 4 4 16 22 10 10 Output 3 5 1 1 Input 5 8 25 14 7 16 19 6 9 4 25 Output -1 | 2,500 | true | false | true | false | false | true | false | false | false | false | 6,853 |
70E | Thought it is already the XXI century, the Mass Media isn't very popular in Walrusland. The cities get news from messengers who can only travel along roads. The network of roads in Walrusland is built so that it is possible to get to any city from any other one in exactly one way, and the roads' lengths are equal. The North Pole governor decided to carry out an information reform. Several cities were decided to be chosen and made regional centers. Maintaining a region center takes _k_ fishlars (which is a local currency) per year. It is assumed that a regional center always has information on the latest news. For every city which is not a regional center, it was decided to appoint a regional center which will be responsible for keeping this city informed. In that case the maintenance costs will be equal to _d__len_ fishlars per year, where _len_ is the distance from a city to the corresponding regional center, measured in the number of roads along which one needs to go. Your task is to minimize the costs to carry out the reform. Input The first line contains two given numbers _n_ and _k_ (1u2009≤u2009_n_u2009≤u2009180,u20091u2009≤u2009_k_u2009≤u2009105). The second line contains _n_u2009-u20091 integers _d__i_, numbered starting with 1 (_d__i_u2009≤u2009_d__i_u2009+u20091,u20090u2009≤u2009_d__i_u2009≤u2009105). Next _n_u2009-u20091 lines contain the pairs of cities connected by a road. Output On the first line print the minimum number of fishlars needed for a year's maintenance. On the second line print _n_ numbers, where the _i_-th number will represent the number of the regional center, appointed to the _i_-th city. If the _i_-th city is a regional center itself, then you should print number _i_. If there are several solutions to that problem, print any of them. Examples Input 8 10 2 5 9 11 15 19 20 1 4 1 3 1 7 4 6 2 8 2 3 3 5 | 2,700 | false | false | true | true | false | false | false | false | false | false | 9,617 |
1583A | A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person. You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $$$n$$$ ($$$n ge 3$$$) positive distinct integers (i.e. different, no duplicates are allowed). Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer $$$x$$$ is called composite if there exists a positive integer $$$y$$$ such that $$$1 < y < x$$$ and $$$x$$$ is divisible by $$$y$$$. If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists. Input Each test consists of multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 leq n leq 100$$$)xa0— the length of the array. The second line of each test case contains $$$n$$$ distinct integers $$$a_{1},a_{2},dots,a_{n}$$$ ($$$1 leq a_{i} leq 200$$$)xa0— the elements of the array. Output Each test case should have two lines of output. The first line should contain a single integer $$$x$$$: the size of the largest subset with composite sum. The next line should contain $$$x$$$ space separated integers representing the indices of the subset of the initial array. Example Input 4 3 8 1 2 4 6 9 4 2 9 1 2 3 4 5 6 7 8 9 3 200 199 198 Output 2 2 1 4 2 1 4 3 9 6 9 1 2 3 4 5 7 8 3 1 2 3 Note In the first test case, the subset $$${a_2, a_1}$$$ has a sum of $$$9$$$, which is a composite number. The only subset of size $$$3$$$ has a prime sum equal to $$$11$$$. Note that you could also have selected the subset $$${a_1, a_3}$$$ with sum $$$8 + 2 = 10$$$, which is composite as it's divisible by $$$2$$$. In the second test case, the sum of all elements equals to $$$21$$$, which is a composite number. Here we simply take the whole array as our subset. | 800 | true | false | false | false | false | false | false | false | false | false | 2,717 |
2033C | Even in university, students need to relax. That is why Sakurakos teacher decided to go on a field trip. It is known that all of the students will be walking in one line. The student with index $$$i$$$ has some topic of interest which is described as $$$a_i$$$. As a teacher, you want to minimise the disturbance of the line of students. The disturbance of the line is defined as the number of neighbouring people with the same topic of interest. In other words, disturbance is the number of indices $$$j$$$ ($$$1 le j < n$$$) such that $$$a_j = a_{j + 1}$$$. In order to do this, you can choose index $$$i$$$ ($$$1le ile n$$$) and swap students at positions $$$i$$$ and $$$n-i+1$$$. You can perform any number of swaps. Your task is to determine the minimal amount of disturbance that you can achieve by doing the operation described above any number of times. Input The first line contains one integer $$$t$$$ ($$$1le tle 10^4$$$)xa0— the number of test cases. Each test case is described by two lines. The first line contains one integer $$$n$$$ ($$$2 le n le 10^5$$$)xa0— the length of the line of students. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1le a_ile n$$$)xa0— the topics of interest of students in line. It is guaranteed that the sum of $$$n$$$ across all test cases does not exceed $$$2cdot 10^5$$$. Note In the first example, it is necessary to apply the operation to $$$i=2$$$, thus the array will become $$$[1, extbf{2}, 1, extbf{1}, 3]$$$, with the bold elements indicating those that have swapped places. The disturbance of this array is equal to $$$1$$$. In the fourth example, it is sufficient to apply the operation to $$$i=3$$$, thus the array will become $$$[2, 1, extbf{2}, extbf{1}, 2, 4]$$$. The disturbance of this array is equal to $$$0$$$. In the eighth example, it is sufficient to apply the operation to $$$i=3$$$, thus the array will become $$$[1, 4, extbf{1}, 5, extbf{3}, 1, 3]$$$. The disturbance of this array is equal to $$$0$$$. | 1,400 | false | true | false | true | false | false | false | false | false | false | 66 |
1805B | You are given a string $$$s$$$. You can apply this operation to the string exactly once: choose index $$$i$$$ and move character $$$s_i$$$ to the beginning of the string (removing it at the old position). For example, if you apply the operation with index $$$i=4$$$ to the string "abaacd" with numbering from $$$1$$$, you get the string "aabacd". What is the lexicographically minimal$$$^{dagger}$$$ string you can obtain by this operation? $$$^{dagger}$$$A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ of the same length if and only if the following holds: 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$$$. Input Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 le t le 10^4$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 le n le 10 ^ 5$$$)xa0— the length of the string. The second line of each test case contains the string $$$s$$$ of length $$$n$$$, consisting of lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10 ^ 5$$$. Output For each test case, on a separate line print the lexicographically smallest string that can be obtained after applying the operation to the original string exactly once. Example Input 4 3 cba 4 acac 5 abbcb 4 aaba Output acb aacc abbcb aaab Note In the first test case, you need to move the last character to the beginning. In the second case, you need to move the second letter "a". In the third set you need to apply the operation with $$$i=1$$$, then the string will not change. | 800 | false | true | false | false | false | false | false | false | false | false | 1,448 |
1111A | We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $$$s$$$ can transform to another superhero with name $$$t$$$ if $$$s$$$ can be made equal to $$$t$$$ by changing any vowel in $$$s$$$ to any other vowel and any consonant in $$$s$$$ to any other consonant. Multiple changes can be made. In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants. Given the names of two superheroes, determine if the superhero with name $$$s$$$ can be transformed to the Superhero with name $$$t$$$. Input The first line contains the string $$$s$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. The second line contains the string $$$t$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. Both strings $$$s$$$ and $$$t$$$ are guaranteed to be different and consist of lowercase English letters only. Output Output "Yes" (without quotes) if the superhero with name $$$s$$$ can be transformed to the superhero with name $$$t$$$ and "No" (without quotes) otherwise. You can print each letter in any case (upper or lower). Note In the first sample, since both 'a' and 'u' are vowels, it is possible to convert string $$$s$$$ to $$$t$$$. In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string $$$s$$$ to $$$t$$$. | 1,000 | false | false | true | false | false | false | false | false | false | false | 5,141 |
1607F | The robot is located on a checkered rectangular board of size $$$n imes m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columnsxa0— from $$$1$$$ to $$$m$$$ from left to right. The robot is able to move from the current cell to one of the four cells adjacent by side. Each cell has one of the symbols 'L', 'R', 'D' or 'U' written on it, indicating the direction in which the robot will move when it gets in that cellxa0— left, right, down or up, respectively. The robot can start its movement in any cell. He then moves to the adjacent square in the direction indicated on the current square in one move. If the robot moves beyond the edge of the board, it falls and breaks. If the robot appears in the cell it already visited before, it breaks (it stops and doesn't move anymore). Robot can choose any cell as the starting cell. Its goal is to make the maximum number of steps before it breaks or stops. Determine from which square the robot should start its movement in order to execute as many commands as possible. A command is considered successfully completed if the robot has moved from the square on which that command was written (it does not matter whether to another square or beyond the edge of the board). Input The first line contains an integer $$$t$$$ ($$$1 le t le 10000$$$)xa0— the number of test cases in the test. Each test case's description is preceded by a blank line. Next is a line that contains integers $$$n$$$ and $$$m$$$ ($$$1 le n le 2000$$$; $$$1 le m le 2000$$$)xa0— the height and width of the board. This line followed by $$$n$$$ lines, the $$$i$$$-th of which describes the $$$i$$$-th line of the board. Each of them is exactly $$$m$$$ letters long and consists of symbols 'L', 'R', 'D' and 'U'. It is guaranteed that the sum of sizes of all boards in the input does not exceed $$$4cdot10^6$$$. Output For each test case, output three integers $$$r$$$, $$$c$$$ and $$$d$$$ ($$$1 le r le n$$$; $$$1 le c le m$$$; $$$d ge 0$$$), which denote that the robot should start moving from cell $$$(r, c)$$$ to make the maximum number of moves $$$d$$$. If there are several answers, output any of them. Example Input 7 1 1 R 1 3 RRL 2 2 DL RU 2 2 UD RU 3 2 DL UL RU 4 4 RRRD RUUD URUD ULLR 4 4 DDLU RDDU UUUU RDLD Output 1 1 1 1 1 3 1 1 4 2 1 3 3 1 5 4 3 12 1 1 4 | 2,300 | false | false | true | false | false | false | true | false | false | true | 2,618 |
1925B | Jay managed to create a problem of difficulty $$$x$$$ and decided to make it the second problem for Codeforces Round #921. But Yash fears that this problem will make the contest highly unbalanced, and the coordinator will reject it. So, he decided to break it up into a problemset of $$$n$$$ sub-problems such that the difficulties of all the sub-problems are a positive integer and their sum is equal to $$$x$$$. The coordinator, Aleksey, defines the balance of a problemset as the denoting the number of test cases. Each test case contains a single line of input containing two integers $$$x$$$ ($$$1leq xleq 10^8$$$) and $$$n$$$ ($$$1leq nleq x$$$). Output For each test case, print a single line containing a single integer denoting the maximum balance of the problemset Yash can achieve. Note For the first test case, one possible way is to break up the problem of difficulty $$$10$$$ into a problemset having three problems of difficulties $$$4$$$, $$$2$$$ and $$$4$$$ respectively, giving a balance equal to $$$2$$$. For the second test case, there is only one way to break up the problem of difficulty $$$5$$$ into a problemset of $$$5$$$ problems with each problem having a difficulty $$$1$$$ giving a balance equal to $$$1$$$. | 1,200 | true | true | false | false | false | false | true | false | false | false | 739 |
919A | We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $$$a$$$ yuan for $$$b$$$ kilos (You don't need to care about what "yuan" is), the same as $$$a/b$$$ yuan for a kilo. Now imagine you'd like to buy $$$m$$$ kilos of apples. You've asked $$$n$$$ supermarkets and got the prices. Find the minimum cost for those apples. You can assume that there are enough apples in all supermarkets. Input The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 leq n leq 5,000$$$, $$$1 leq m leq 100$$$), denoting that there are $$$n$$$ supermarkets and you want to buy $$$m$$$ kilos of apples. The following $$$n$$$ lines describe the information of the supermarkets. Each line contains two positive integers $$$a, b$$$ ($$$1 leq a, b leq 100$$$), denoting that in this supermarket, you are supposed to pay $$$a$$$ yuan for $$$b$$$ kilos of apples. Output The only line, denoting the minimum cost for $$$m$$$ kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed $$$10^{-6}$$$. Formally, let your answer be $$$x$$$, and the jury's answer be $$$y$$$. Your answer is considered correct if $$$frac{x - y}{max{(1, y)}} le 10^{-6}$$$. Note In the first sample, you are supposed to buy $$$5$$$ kilos of apples in supermarket $$$3$$$. The cost is $$$5/3$$$ yuan. In the second sample, you are supposed to buy $$$1$$$ kilo of apples in supermarket $$$2$$$. The cost is $$$98/99$$$ yuan. | 800 | false | true | true | false | false | false | true | false | false | false | 6,056 |
1916A | In a sequence $$$a$$$, whose product was equal to $$$2023$$$, $$$k$$$ numbers were removed, leaving a sequence $$$b$$$ of length $$$n$$$. Given the resulting sequence $$$b$$$, find any suitable sequence $$$a$$$ and output which $$$k$$$ elements were removed from it, or state that such a sequence could not have existed. Notice that you are not guaranteed that such array exists. Input Each test consists of several test cases. The first line contains a single integer $$$t$$$ ($$$1 le t le 100$$$)xa0— the number of test cases. This is followed by a description of the test cases. The first line of each test case contains two integers $$$n$$$ ($$$1 le n, k le 5$$$)xa0— the size of sequence $$$b$$$ and the number of numbers removed from sequence $$$a$$$. The second line contains $$$n$$$ integers $$$b_1,b_2, ldots,b_n$$$ ($$$1 leq b_i leq 2023$$$)xa0— the remaining sequence. The values of $$$b_i$$$ might not be divisors of $$$2023$$$. Output For each test case, output "YES" if the sequence $$$a$$$ exists, and in the following line output $$$k$$$ non-negative integers that were removed from the sequence $$$a$$$. If the sequence $$$a$$$ does not exist, output "NO" in a single line. You can output the answer in any case (uppercase or lowercase). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive answers. Example Input 7 2 2 5 2 3 1 7 17 7 4 2 1 289 1 1 3 1 7 17 17 1 1 289 1 1 2023 1 3 1 Output NO NO YES 7 1 YES 1 YES 7 YES 1 YES 7 17 17 Note In third test case product is equal to $$$289 cdot 7 = 2023$$$. In fourth test case product is already equal to $$$2023$$$. In seventh test case product is equal to $$$7 cdot 17 cdot 17 = 2023$$$. | 800 | true | false | true | false | false | true | false | false | false | false | 803 |
929A | Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды. Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть _n_ точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке _x_1 километров вдоль улицы, второйxa0— в точке _x_2 и так далее, _n_-й велопрокат находится в точке _x__n_. Школа Аркадия находится в точке _x_1 (то есть там же, где и первый велопрокат), а домxa0— в точке _x__n_ (то есть там же, где и _n_-й велопрокат). Известно, что _x__i_u2009<u2009_x__i_u2009+u20091 для всех 1u2009≤u2009_i_u2009<u2009_n_. Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение. За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше _k_ километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком. Входные данные В первой строке следуют два целых числа _n_ и _k_ (2u2009≤u2009_n_u2009≤u20091u2009000, 1u2009≤u2009_k_u2009≤u2009100u2009000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде. В следующей строке следует последовательность целых чисел _x_1,u2009_x_2,u2009...,u2009_x__n_ (0u2009≤u2009_x_1u2009<u2009_x_2u2009<u2009...u2009<u2009_x__n_u2009≤u2009100u2009000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания. Выходные данные Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката. Примечание В первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома. Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах. | 1,400 | false | true | true | false | false | false | false | false | false | false | 5,990 |
1363E | Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end. To achieve this, he can perform the following operation any number of times: Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target. Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible. Input First line contains a single integer $$$n$$$ $$$(1 le n le 2 cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 leq a_i leq 10^9, 0 leq b_i, c_i leq 1)$$$ xa0— the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 leq u, v leq n, ext{ } u e v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree. Output Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible. Examples Input 5 1 0 1 20 1 0 300 0 1 4000 0 0 50000 1 0 1 2 2 3 2 4 1 5 Input 5 10000 0 1 2000 1 0 300 0 1 40 0 0 1 1 0 1 2 2 3 2 4 1 5 Input 2 109 0 1 205 0 1 1 2 Note The tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node. In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node. In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially. | 2,000 | false | true | false | true | false | false | false | false | false | false | 3,864 |
606A | Problem - 606A - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags implementation *1200 No tag edit access → Contest materials ? Input The first line of the input contains three integers _a_, _b_ and _c_ (0u2009≤u2009_a_,u2009_b_,u2009_c_u2009≤u20091u2009000u2009000)xa0— the number of blue, violet and orange spheres that are in the magician's disposal. The second line of the input contains three integers, _x_, _y_ and _z_ (0u2009≤u2009_x_,u2009_y_,u2009_z_u2009≤u20091u2009000u2009000)xa0— the number of blue, violet and orange spheres that he needs to get. Output If the wizard is able to obtain the required numbers of spheres, print "Yes". Otherwise, print "No". Examples Input 4 4 0 2 1 2 Output Yes Input 5 6 1 2 7 2 Output No Input 3 3 3 2 2 2 Output Yes Note In the first sample the wizard has 4 blue and 4 violet spheres. In his first action he can turn two blue spheres into one violet one. After that he will have 2 blue and 5 violet spheres. Then he turns 4 violet spheres into 2 orange spheres and he ends up with 2 blue, 1 violet and 2 orange spheres, which is exactly what he needs. | 1,200 | false | false | true | false | false | false | false | false | false | false | 7,421 |
648A | Statement is not available on English language Профиль горного хребта схематично задан в виде прямоугольной таблицы из символов «.» (пустое пространство) и «*» (часть горы). Каждый столбец таблицы содержит хотя бы одну «звёздочку». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*». ........... .........*. .*.......*. **.......*. **..*...**. *********** Пример изображения горного хребта. Маршрут туриста проходит через весь горный хребет слева направо. Каждый день турист перемещается вправоxa0— в соседний столбец в схематичном изображении. Конечно, каждый раз он поднимается (или опускается) в самую верхнюю точку горы, которая находится в соответствующем столбце. Считая, что изначально турист находится в самой верхней точке в первом столбце, а закончит свой маршрут в самой верхней точке в последнем столбце, найдите две величины: наибольший подъём за день (равен 0, если в профиле горного хребта нет ни одного подъёма), наибольший спуск за день (равен 0, если в профиле горного хребта нет ни одного спуска). Входные данные В первой строке входных данных записаны два целых числа _n_ и _m_ (1u2009≤u2009_n_,u2009_m_u2009≤u2009100)xa0— количество строк и столбцов в схематичном изображении соответственно. Далее следуют _n_ строк по _m_ символов в каждойxa0— схематичное изображение горного хребта. Каждый символ схематичного изображенияxa0— это либо «.», либо «*». Каждый столбец матрицы содержит хотя бы один символ «*». Гарантируется, что любой из символов «*» либо находится в нижней строке матрицы, либо непосредственно под ним находится другой символ «*». Выходные данные Выведите через пробел два целых числа: величину наибольшего подъёма за день (или 0, если в профиле горного хребта нет ни одного подъёма), величину наибольшего спуска за день (или 0, если в профиле горного хребта нет ни одного спуска). Примеры Входные данные 6 11 ........... .........*. .*.......*. **.......*. **..*...**. ********** Входные данные 5 5 .... ...* ..** .*** **** Входные данные 8 7 ....... .*..... .*..... .**.... .**.*.. .****. .***** ****** Примечание В первом тестовом примере высоты гор равны: 3,u20094,u20091,u20091,u20092,u20091,u20091,u20091,u20092,u20095,u20091. Наибольший подъем равен 3 и находится между горой номер 9 (её высота равна 2) и горой номер 10 (её высота равна 5). Наибольший спуск равен 4 и находится между горой номер 10 (её высота равна 5) и горой номер 11 (её высота равна 1). Во втором тестовом примере высоты гор равны: 1,u20092,u20093,u20094,u20095. Наибольший подъём равен 1 и находится, например, между горой номер 2 (ее высота равна 2) и горой номер 3 (её высота равна 3). Так как в данном горном хребте нет спусков, то величина наибольшего спуска равна 0. В третьем тестовом примере высоты гор равны: 1,u20097,u20095,u20093,u20094,u20092,u20093. Наибольший подъём равен 6 и находится между горой номер 1 (её высота равна 1) и горой номер 2 (её высота равна 7). Наибольший спуск равен 2 и находится между горой номер 2 (её высота равна 7) и горой номер 3 (её высота равна 5). Такой же спуск находится между горой номер 5 (её высота равна 4) и горой номер 6 (её высота равна 2). | 900 | false | false | true | false | false | true | false | false | false | false | 7,227 |
1442C | You are given a directed graph of $$$n$$$ vertices and $$$m$$$ edges. Vertices are numbered from $$$1$$$ to $$$n$$$. There is a token in vertex $$$1$$$. The following actions are allowed: Token movement. To move the token from vertex $$$u$$$ to vertex $$$v$$$ if there is an edge $$$u o v$$$ in the graph. This action takes $$$1$$$ second. Graph transposition. To transpose all the edges in the graph: replace each edge $$$u o v$$$ by an edge $$$v o u$$$. This action takes increasingly more time: $$$k$$$-th transposition takes $$$2^{k-1}$$$ seconds, i.e. the first transposition takes $$$1$$$ second, the second one takes $$$2$$$ seconds, the third one takes $$$4$$$ seconds, and so on. The goal is to move the token from vertex $$$1$$$ to vertex $$$n$$$ in the shortest possible time. Print this time modulo $$$998,244,353$$$. Input The first line of input contains two integers $$$n, m$$$ ($$$1 le n, m le 200,000$$$). The next $$$m$$$ lines contain two integers each: $$$u, v$$$ ($$$1 le u, v le n; u e v$$$), which represent the edges of the graph. It is guaranteed that all ordered pairs $$$(u, v)$$$ are distinct. It is guaranteed that it is possible to move the token from vertex $$$1$$$ to vertex $$$n$$$ using the actions above. Output Print one integer: the minimum required time modulo $$$998,244,353$$$. Note The first example can be solved by transposing the graph and moving the token to vertex $$$4$$$, taking $$$2$$$ seconds. The best way to solve the second example is the following: transpose the graph, move the token to vertex $$$2$$$, transpose the graph again, move the token to vertex $$$3$$$, transpose the graph once more and move the token to vertex $$$4$$$. | 2,400 | false | true | false | false | false | false | false | false | false | true | 3,462 |
1717D | Madoka decided to entrust the organization of a major computer game tournament "OSU"! In this tournament, matches are held according to the "Olympic system". In other words, there are $$$2^n$$$ participants in the tournament, numbered with integers from $$$1$$$ to $$$2^n$$$. There are $$$n$$$ rounds in total in the tournament. In the $$$i$$$-th round there are $$$2^{n - i}$$$ matches between two players (one of whom is right, the other is left), after which the winners go further along the tournament grid, and the losing participants are eliminated from the tournament. Herewith, the relative order in the next round does not change. And the winner of the tournamentxa0— is the last remaining participant. But the smaller the participant's number, the more he will pay Madoka if he wins, so Madoka wants the participant with the lowest number to win. To do this, she can arrange the participants in the first round as she likes, and also determine for each match who will winxa0— the participant on the left or right. But Madoka knows that tournament sponsors can change the winner in matches no more than $$$k$$$ times. (That is, if the participant on the left won before the change, then the participant on the right will win after the change, and if the participant on the right won, then the participant on the left will win after the change). So, the first image shows the tournament grid that Madoka made, where the red lines denote who should win the match. And the second one shows the tournament grid, after one change in the outcome of the match by sponsors (a match between $$$1$$$ and $$$3$$$ players). Print the minimum possible number of the winner in the tournament, which Madoka can get regardless of changes in sponsors. But since the answer can be very large, output it modulo $$$10^9 + 7$$$. Note that we need to minimize the answer, and only then take it modulo. Input The first and the only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 le n le 10^5, 1 le k le min(2^n - 1, 10^9)$$$)xa0— the number of rounds in the tournament and the number of outcomes that sponsors can change. Note In the first example, there is only one match between players $$$1$$$ and $$$2$$$, so the sponsors can always make player $$$2$$$ wins. The tournament grid from the second example is shown in the picture in the statement. | 1,900 | true | true | false | false | false | true | false | false | false | false | 1,978 |
1575J | Mr. Chanek has a new game called Dropping Balls. Initially, Mr. Chanek has a grid $$$a$$$ of size $$$n imes m$$$ Each cell $$$(x,y)$$$ contains an integer $$$a_{x,y}$$$ denoting the direction of how the ball will move. $$$a_{x,y}=1$$$ — the ball will move to the right (the next cell is $$$(x, y + 1)$$$); $$$a_{x,y}=2$$$ — the ball will move to the bottom (the next cell is $$$(x + 1, y)$$$); $$$a_{x,y}=3$$$ — the ball will move to the left (the next cell is $$$(x, y - 1)$$$). Every time a ball leaves a cell $$$(x,y)$$$, the integer $$$a_{x,y}$$$ will change to $$$2$$$. Mr. Chanek will drop $$$k$$$ balls sequentially, each starting from the first row, and on the $$$c_1, c_2, dots, c_k$$$-th ($$$1 leq c_i leq m$$$) columns. Determine in which column each ball will end up in (position of the ball after leaving the grid). Input The first line contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 leq n, m leq 1000$$$, $$$1 leq k leq 10^5$$$) — the size of the grid and the number of balls dropped by Mr. Chanek. The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i,1},a_{i,2},ldots,a_{i,m}$$$ ($$$1 leq a_{i,j} leq 3$$$). It will satisfy $$$a_{i, 1} e 3$$$ and $$$a_{i, m} e 1$$$. The next line contains $$$k$$$ integers $$$c_1, c_2, ldots, c_k$$$ ($$$1 leq c_i leq m$$$) — the balls' column positions dropped by Mr. Chanek sequentially. Output Output $$$k$$$ integers — the $$$i$$$-th integer denoting the column where the $$$i$$$-th ball will end. Examples Input 5 5 3 1 2 3 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 1 Note In the first example, the first ball will drop as follows. Note that the cell $$$(1, 1)$$$ will change direction to the bottom direction. The second and third balls will drop as follows. All balls will be dropped from the first row and on the $$$c_1, c_2, dots, c_k$$$-th columns respectively. A ball will stop dropping once it leaves the grid. | 1,500 | false | false | true | false | false | false | true | true | false | false | 2,759 |
1743E | Monocarp is playing a video game. In the game, he controls a spaceship and has to destroy an enemy spaceship. Monocarp has two lasers installed on his spaceship. Both lasers $$$1$$$ and $$$2$$$ have two values: $$$p_i$$$xa0— the power of the laser; $$$t_i$$$xa0— the reload time of the laser. When a laser is fully charged, Monocarp can either shoot it or wait for the other laser to charge and shoot both of them at the same time. An enemy spaceship has $$$h$$$ durability and $$$s$$$ shield capacity. When Monocarp shoots an enemy spaceship, it receives $$$(P - s)$$$ damage (i.u2009e. $$$(P - s)$$$ gets subtracted from its durability), where $$$P$$$ is the total power of the lasers that Monocarp shoots (i.u2009e. $$$p_i$$$ if he only shoots laser $$$i$$$ and $$$p_1 + p_2$$$ if he shoots both lasers at the same time). An enemy spaceship is considered destroyed when its durability becomes $$$0$$$ or lower. Initially, both lasers are zero charged. What's the lowest amount of time it can take Monocarp to destroy an enemy spaceship? Input The first line contains two integers $$$p_1$$$ and $$$t_1$$$ ($$$2 le p_1 le 5000$$$; $$$1 le t_1 le 10^{12}$$$)xa0— the power and the reload time of the first laser. The second line contains two integers $$$p_2$$$ and $$$t_2$$$ ($$$2 le p_2 le 5000$$$; $$$1 le t_2 le 10^{12}$$$)xa0— the power and the reload time of the second laser. The third line contains two integers $$$h$$$ and $$$s$$$ ($$$1 le h le 5000$$$; $$$1 le s < min(p_1, p_2)$$$)xa0— the durability and the shield capacity of an enemy spaceship. Note that the last constraint implies that Monocarp will always be able to destroy an enemy spaceship. Output Print a single integerxa0— the lowest amount of time it can take Monocarp to destroy an enemy spaceship. Examples Input 10 1 5000 100000 25 9 Note In the first example, Monocarp waits for both lasers to charge, then shoots both lasers at $$$10$$$, they deal $$$(5 + 4 - 1) = 8$$$ damage. Then he waits again and shoots lasers at $$$20$$$, dealing $$$8$$$ more damage. In the second example, Monocarp doesn't wait for the second laser to charge. He just shoots the first laser $$$25$$$ times, dealing $$$(10 - 9) = 1$$$ damage each time. | 2,400 | false | false | false | true | false | false | false | true | false | false | 1,820 |
1512F | Polycarp is wondering about buying a new computer, which costs $$$c$$$ tugriks. To do this, he wants to get a job as a programmer in a big company. There are $$$n$$$ positions in Polycarp's company, numbered starting from one. An employee in position $$$i$$$ earns $$$a[i]$$$ tugriks every day. The higher the position number, the more tugriks the employee receives. Initially, Polycarp gets a position with the number $$$1$$$ and has $$$0$$$ tugriks. Each day Polycarp can do one of two things: If Polycarp is in the position of $$$x$$$, then he can earn $$$a[x]$$$ tugriks. If Polycarp is in the position of $$$x$$$ ($$$x < n$$$) and has at least $$$b[x]$$$ tugriks, then he can spend $$$b[x]$$$ tugriks on an online course and move to the position $$$x+1$$$. For example, if $$$n=4$$$, $$$c=15$$$, $$$a=[1, 3, 10, 11]$$$, $$$b=[1, 2, 7]$$$, then Polycarp can act like this: On the first day, Polycarp is in the $$$1$$$-st position and earns $$$1$$$ tugrik. Now he has $$$1$$$ tugrik; On the second day, Polycarp is in the $$$1$$$-st position and move to the $$$2$$$-nd position. Now he has $$$0$$$ tugriks; On the third day, Polycarp is in the $$$2$$$-nd position and earns $$$3$$$ tugriks. Now he has $$$3$$$ tugriks; On the fourth day, Polycarp is in the $$$2$$$-nd position and is transferred to the $$$3$$$-rd position. Now he has $$$1$$$ tugriks; On the fifth day, Polycarp is in the $$$3$$$-rd position and earns $$$10$$$ tugriks. Now he has $$$11$$$ tugriks; On the sixth day, Polycarp is in the $$$3$$$-rd position and earns $$$10$$$ tugriks. Now he has $$$21$$$ tugriks; Six days later, Polycarp can buy himself a new computer. Find the minimum number of days after which Polycarp will be able to buy himself a new computer. Input The first line contains a single integer $$$t$$$ ($$$1 le t le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$c$$$ ($$$2 le n le 2 cdot 10^5$$$, $$$1 le c le 10^9$$$)xa0— the number of positions in the company and the cost of a new computer. The second line of each test case contains $$$n$$$ integers $$$a_1 le a_2 le ldots le a_n$$$ ($$$1 le a_i le 10^9$$$). The third line of each test case contains $$$n - 1$$$ integer $$$b_1, b_2, ldots, b_{n-1}$$$ ($$$1 le b_i le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 cdot 10^5$$$. | 1,900 | false | true | true | true | false | false | true | false | false | false | 3,104 |
1526B | Problem - 1526B - Codeforces =============== xa0 ]( --- Finished → Virtual participation Virtual contest is a way to take part in past contest, as close as possible to participation on time. It is supported only ICPC mode for virtual contests. If you've seen these problems, a virtual contest is not for you - solve these problems in the archive. If you just want to solve some problem from a contest, a virtual contest is not for you - solve this problem in the archive. Never use someone else's code, read the tutorials or communicate with other person during a virtual contest. → Problem tags dp math number theory *1400 No tag edit access → Contest materials ") Editorial") . For instance, $$$33=11+11+11$$$ $$$144=111+11+11+11$$$ Input The first line of input contains a single integer $$$t$$$ $$$(1 leq t leq 10000)$$$ — the number of testcases. The first and only line of each testcase contains a single integer $$$x$$$ $$$(1 leq x leq 10^9)$$$ — the number you have to make. Output For each testcase, you should output a single string. If you can make $$$x$$$, output "YES" (without quotes). Otherwise, output "NO". You can print each letter of "YES" and "NO" in any case (upper or lower). Example Input 3 33 144 69 Output YES YES NO Note Ways to make $$$33$$$ and $$$144$$$ were presented in the statement. It can be proved that we can't present $$$69$$$ this way. | 1,400 | true | false | false | true | false | false | false | false | false | false | 3,035 |
1276D | Vasya has a tree with $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, and $$$n - 1$$$ edges numbered from $$$1$$$ to $$$n - 1$$$. Initially each vertex contains a token with the number of the vertex written on it. Vasya plays a game. He considers all edges of the tree by increasing of their indices. For every edge he acts as follows: If both endpoints of the edge contain a token, remove a token from one of the endpoints and write down its number. Otherwise, do nothing. The result of the game is the sequence of numbers Vasya has written down. Note that there may be many possible resulting sequences depending on the choice of endpoints when tokens are removed. Vasya has played for such a long time that he thinks he exhausted all possible resulting sequences he can obtain. He wants you to verify him by computing the number of distinct sequences modulo $$$998,244,353$$$. Input The first line contains a single integer $$$n$$$ ($$$2 leq n leq 2 cdot 10^5$$$)xa0— the number of vertices of the tree. The next $$$n - 1$$$ lines describe edges of the tree. The $$$i$$$-th of these lines contains two integers $$$u_i, v_i$$$ ($$$1 leq u_i, v_i leq n$$$)xa0— endpoints of the edge with index $$$i$$$. It is guaranteed that the given graph is indeed a tree. Note In the first sample case the distinct sequences are $$$(1), (2, 1), (2, 3, 1), (2, 3, 4, 1), (2, 3, 4, 5)$$$. Int the second sample case the distinct sequences are $$$(2, 6, 5, 3), (2, 6, 5, 7), (2, 6, 7, 2), (2, 6, 7, 5), (2, 7, 3), (2, 7, 5), (7, 1, 3), (7, 1, 5), (7, 2, 3), (7, 2, 5)$$$. | 2,900 | false | false | false | true | false | false | false | false | false | false | 4,312 |
417B | During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check. Each participant is identified by some unique positive integer _k_, and each sent solution _A_ is characterized by two numbers: _x_xa0— the number of different solutions that are sent before the first solution identical to _A_, and _k_ — the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same _x_. It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number _x_ (_x_u2009>u20090) of the participant with number _k_, then the testing system has a solution with number _x_u2009-u20091 of the same participant stored somewhere before. During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so. Input The first line of the input contains an integer _n_ (1u2009≤u2009_n_u2009≤u2009105)xa0— the number of solutions. Each of the following _n_ lines contains two integers separated by space _x_ and _k_ (0u2009≤u2009_x_u2009≤u2009105; 1u2009≤u2009_k_u2009≤u2009105)xa0— the number of previous unique solutions and the identifier of the participant. Output A single line of the output should contain «YES» if the data is in chronological order, and «NO» otherwise. | 1,400 | false | false | true | false | false | false | false | false | false | false | 8,156 |
672B | A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string _s_ consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string _s_ to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba". If string _s_ has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible. Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible. Input The first line of the input contains an integer _n_ (1u2009≤u2009_n_u2009≤u2009100u2009000)xa0— the length of the string _s_. The second line contains the string _s_ of length _n_ consisting of only lowercase English letters. Output If it's impossible to change the string _s_ such that all its substring are distinct print -1. Otherwise print the minimum required number of changes. Note In the first sample one of the possible solutions is to change the first character to 'b'. In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko". | 1,000 | false | false | true | false | false | true | false | false | false | false | 7,134 |
404E | Valera has a strip infinite in both directions and consisting of cells. The cells are numbered by integers. The cell number 0 has a robot. The robot has instructions — the sequence of moves that he must perform. In one move, the robot moves one cell to the left or one cell to the right, according to instructions. Before the robot starts moving, Valera puts obstacles in some cells of the strip, excluding cell number 0. If the robot should go into the cell with an obstacle according the instructions, it will skip this move. Also Valera indicates the finish cell in which the robot has to be after completing the entire instructions. The finishing cell should be different from the starting one. It is believed that the robot completed the instructions successfully, if during the process of moving he visited the finish cell exactly once — at its last move. Moreover, the latter move cannot be skipped. Let's assume that _k_ is the minimum number of obstacles that Valera must put to make the robot able to complete the entire sequence of instructions successfully and end up in some finishing cell. You need to calculate in how many ways Valera can choose _k_ obstacles and the finishing cell so that the robot is able to complete the instructions successfully. Input The first line contains a sequence of characters without spaces _s_1_s_2... _s__n_ (1u2009≤u2009_n_u2009≤u2009106), consisting only of letters "L" and "R". If character _s__i_ equals "L", then the robot on the _i_-th move must try to move one cell to the left. If the _s__i_-th character equals "R", then the robot on the _i_-th move must try to move one cell to the right. Output Print a single integer — the required number of ways. It's guaranteed that this number fits into 64-bit signed integer type. Note In the first sample Valera mustn't add any obstacles and his finishing cell must be cell 2. In the second sample, Valera must add an obstacle in cell number 1, and his finishing cell must be cell number u2009-u20091. In this case robot skips the first two moves and on the third move he goes straight from the starting cell to the finishing one. But if Valera doesn't add any obstacles, or adds an obstacle to another cell, then the robot visits the finishing cell more than once. | 2,200 | false | true | true | false | false | false | false | true | false | false | 8,206 |
1966B | There is an $$$n imes m$$$ grid of white and black squares. In one operation, you can select any two squares of the same color, and color all squares in the subrectangle between them that color. Formally, if you select positions $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$, both of which are currently the same color $$$c$$$, set the color of all $$$(x, y)$$$ where $$$min(x_1, x_2) le x le max(x_1, x_2)$$$ and $$$min(y_1, y_2) le y le max(y_1, y_2)$$$ to $$$c$$$. This diagram shows a sequence of two possible operations on a grid: Is it possible for all squares in the grid to be the same color, after performing any number of operations (possibly zero)? Input The first line of the input contains a single integer $$$t$$$ ($$$1 le t le 10^4$$$)xa0— the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 le n, m le 500$$$)xa0— the number of rows and columns in the grid, respectively. Each of the next $$$n$$$ lines contains $$$m$$$ characters 'W' and 'B'xa0— the initial colors of the squares of the grid. It is guaranteed that the sum of $$$ncdot m$$$ over all test cases does not exceed $$$3cdot 10^5$$$. Output For each test case, print "YES" if it is possible to make all squares in the grid the same color, and "NO" otherwise. You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses. Example Input 8 2 1 W B 6 6 WWWWBW WBWWWW BBBWWW BWWWBB WWBWBB BBBWBW 1 1 W 2 2 BB BB 3 4 BWBW WBWB BWBW 4 2 BB BB WW WW 4 4 WWBW BBWB WWBB BBBB 1 5 WBBWB Output NO YES YES YES YES NO YES NO Note In the first example, it is impossible to ever change the color of any square with an operation, so we output NO. The second example is the case pictured above. As shown in that diagram, it is possible for all squares to be white after two operations, so we output YES. In the third and fourth examples, all squares are already the same color, so we output YES. In the fifth example we can do everything in two operations. First, select positions $$$(2, 1)$$$ and $$$(1, 4)$$$ and color all squares with $$$1 le x le 2$$$ and $$$1 le y le 4$$$ to white. Then, select positions $$$(2, 1)$$$ and $$$(3, 4)$$$ and color all squares with $$$2 le x le 3$$$ and $$$1 le y le 4$$$ to white. After these two operations all squares are white. | 1,100 | false | false | true | false | false | true | false | false | false | false | 509 |
1965D | There is a hidden array $$$a$$$ of $$$n$$$ positive integers. You know that $$$a$$$ is a palindrome, or in other words, for all $$$1 le i le n$$$, $$$a_i = a_{n + 1 - i}$$$. You are given the sums of all but one of its distinct subarrays, in arbitrary order. The subarray whose sum is not given can be any of the $$$frac{n(n+1)}{2}$$$ distinct subarrays of $$$a$$$. Recover any possible palindrome $$$a$$$. The input is chosen such that there is always at least one array $$$a$$$ that satisfies the conditions. An array $$$b$$$ is a subarray of $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Input The first line of the input contains a single integer $$$t$$$ ($$$1 le t le 200$$$)xa0— the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 le n le 1000$$$)xa0— the size of the array $$$a$$$. The next line of each test case contains $$$frac{n(n+1)}{2} - 1$$$ integers $$$s_i$$$ ($$$1leq s_i leq 10^9$$$)xa0— all but one of the subarray sums of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$. Additional constraint on the input: There is always at least one valid solution. Hacks are disabled for this problem. Output For each test case, print one line containing $$$n$$$ positive integers $$$a_1, a_2, cdots a_n$$$xa0— any valid array $$$a$$$. Note that $$$a$$$ must be a palindrome. If there are multiple solutions, print any. Example Input 7 3 1 2 3 4 1 4 18 2 11 9 7 11 7 2 9 4 5 10 5 16 3 3 13 8 8 4 8 10 4 6 4 20 14 14 6 5 1 2 3 4 5 4 3 2 1 1 2 3 2 1 5 1 1 2 2 2 3 3 3 3 4 5 5 6 8 3 500000000 1000000000 500000000 500000000 1000000000 Output 1 2 1 7 2 2 7 3 5 5 3 6 4 4 6 1 1 1 1 1 2 1 2 1 2 500000000 500000000 500000000 Note For the first example case, the subarrays of $$$a = [1, 2, 1]$$$ are: $$$[1]$$$ with sum $$$1$$$, $$$[2]$$$ with sum $$$2$$$, $$$[1]$$$ with sum $$$1$$$, $$$[1, 2]$$$ with sum $$$3$$$, $$$[2, 1]$$$ with sum $$$3$$$, $$$[1, 2, 1]$$$ with sum $$$4$$$. So the full list of subarray sums is $$$1, 1, 2, 3, 3, 4$$$, and the sum that is missing from the input list is $$$3$$$. For the second example case, the missing subarray sum is $$$4$$$, for the subarray $$$[2, 2]$$$. For the third example case, the missing subarray sum is $$$13$$$, because there are two subarrays with sum $$$13$$$ ($$$[3, 5, 5]$$$ and $$$[5, 5, 3]$$$) but $$$13$$$ only occurs once in the input. | 2,900 | false | false | false | false | false | true | false | false | false | false | 513 |
1923B | You are playing a computer game. The current level of this game can be modeled as a straight line. Your character is in point $$$0$$$ of this line. There are $$$n$$$ monsters trying to kill your character; the $$$i$$$-th monster has health equal to $$$a_i$$$ and is initially in the point $$$x_i$$$. Every second, the following happens: first, you fire up to $$$k$$$ bullets at monsters. Each bullet targets exactly one monster and decreases its health by $$$1$$$. For each bullet, you choose its target arbitrary (for example, you can fire all bullets at one monster, fire all bullets at different monsters, or choose any other combination). Any monster can be targeted by a bullet, regardless of its position and any other factors; then, all alive monsters with health $$$0$$$ or less die; then, all alive monsters move $$$1$$$ point closer to you (monsters to the left of you increase their coordinates by $$$1$$$, monsters to the right of you decrease their coordinates by $$$1$$$). If any monster reaches your character (moves to the point $$$0$$$), you lose. Can you survive and kill all $$$n$$$ monsters without letting any of them reach your character? Input The first line of the input contains one integer $$$t$$$ ($$$1 le t le 3 cdot 10^4$$$) — the number of test cases. Each test case consists of three lines: the first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 le n le 3 cdot 10^5$$$; $$$1 le k le 2 cdot 10^9$$$); the second line contains $$$n$$$ integers $$$a_1, a_2, dots, a_n$$$ ($$$1 le a_i le 10^9$$$); the third line contains $$$n$$$ integers $$$x_1, x_2, dots, x_n$$$ ($$$-n le x_1 < x_2 < x_3 < dots < x_n le n$$$; $$$x_i e 0$$$). Additional constraint on the input: the sum of $$$n$$$ over all test cases does not exceed $$$3 cdot 10^5$$$. Output For each test case, print YES if you can kill all $$$n$$$ monsters before they reach your character, or NO otherwise. You can output each letter of the answer in any case (upper or lower). For example, the strings yEs, yes, Yes, and YES will all be recognized as positive responses. Example Input 5 3 2 1 2 3 -1 2 3 2 1 1 1 -1 1 4 10 3 4 2 5 -3 -2 1 3 5 3 2 1 3 2 5 -3 -2 3 4 5 2 1 1 2 1 2 Note In the first example, you can act as follows: during the $$$1$$$-st second, fire $$$1$$$ bullet at the $$$1$$$-st monster and $$$1$$$ bullet at the $$$3$$$-rd monster. Then the $$$1$$$-st monster dies, the $$$2$$$-nd and the $$$3$$$-rd monster move closer; during the $$$2$$$-nd second, fire $$$2$$$ bullets at the $$$2$$$-nd monster. Then the $$$2$$$-nd monster dies, the $$$3$$$-rd monster moves closer; during the $$$3$$$-rd second, fire $$$2$$$ bullets at the $$$3$$$-rd monster. Then the $$$3$$$-rd monster dies. In the second example, you can fire only $$$1$$$ bullet, so you can kill only one of the two monsters during the $$$1$$$-st second. Then, the remaining monster moves closer and kills your character. | 1,100 | false | true | true | true | false | false | false | false | false | false | 751 |
1326E | You are given a permutation, $$$p_1, p_2, ldots, p_n$$$. Imagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb. For some fixed configuration of bombs, consider the following process. Initially, there is an empty set, $$$A$$$. For each $$$i$$$ from $$$1$$$ to $$$n$$$: Add $$$p_i$$$ to $$$A$$$. If the $$$i$$$-th position contains a bomb, remove the largest element in $$$A$$$. After the process is completed, $$$A$$$ will be non-empty. The cost of the configuration of bombs equals the largest element in $$$A$$$. You are given another permutation, $$$q_1, q_2, ldots, q_n$$$. For each $$$1 leq i leq n$$$, find the cost of a configuration of bombs such that there exists a bomb in positions $$$q_1, q_2, ldots, q_{i-1}$$$. For example, for $$$i=1$$$, you need to find the cost of a configuration without bombs, and for $$$i=n$$$, you need to find the cost of a configuration with bombs in positions $$$q_1, q_2, ldots, q_{n-1}$$$. Input The first line contains a single integer, $$$n$$$ ($$$2 leq n leq 300,000$$$). The second line contains $$$n$$$ distinct integers $$$p_1, p_2, ldots, p_n$$$ ($$$1 leq p_i leq n)$$$. The third line contains $$$n$$$ distinct integers $$$q_1, q_2, ldots, q_n$$$ ($$$1 leq q_i leq n)$$$. Output Print $$$n$$$ space-separated integers, such that the $$$i$$$-th of them equals the cost of a configuration of bombs in positions $$$q_1, q_2, ldots, q_{i-1}$$$. Note In the first test: If there are no bombs, $$$A$$$ is equal to $$${1, 2, 3}$$$ at the end of the process, so the cost of the configuration is $$$3$$$. If there is one bomb in position $$$1$$$, $$$A$$$ is equal to $$${1, 2}$$$ at the end of the process, so the cost of the configuration is $$$2$$$; If there are two bombs in positions $$$1$$$ and $$$2$$$, $$$A$$$ is equal to $$${1}$$$ at the end of the process, so the cost of the configuration is $$$1$$$. In the second test: Let's consider the process for $$$i = 4$$$. There are three bombs on positions $$$q_1 = 5$$$, $$$q_2 = 2$$$, and $$$q_3 = 1$$$. At the beginning, $$$A = {}$$$. Operation $$$1$$$: Add $$$p_1 = 2$$$ to $$$A$$$, so $$$A$$$ is equal to $$${2}$$$. There exists a bomb in position $$$1$$$, so we should delete the largest element from $$$A$$$. $$$A$$$ is equal to $$${}$$$. Operation $$$2$$$: Add $$$p_2 = 3$$$ to $$$A$$$, so $$$A$$$ is equal to $$${3}$$$. There exists a bomb in position $$$2$$$, so we should delete the largest element from $$$A$$$. $$$A$$$ is equal to $$${}$$$. Operation $$$3$$$: Add $$$p_3 = 6$$$ to $$$A$$$, so $$$A$$$ is equal to $$${6}$$$. There is no bomb in position $$$3$$$, so we do nothing. Operation $$$4$$$: Add $$$p_4 = 1$$$ to $$$A$$$, so $$$A$$$ is equal to $$${1, 6}$$$. There is no bomb in position $$$4$$$, so we do nothing. Operation $$$5$$$: Add $$$p_5 = 5$$$ to $$$A$$$, so $$$A$$$ is equal to $$${1, 5, 6}$$$. There exists a bomb in position $$$5$$$, so we delete the largest element from $$$A$$$. Now, $$$A$$$ is equal to $$${1, 5}$$$. Operation $$$6$$$: Add $$$p_6 = 4$$$ to $$$A$$$, so $$$A$$$ is equal to $$${1, 4, 5}$$$. There is no bomb in position $$$6$$$, so we do nothing. In the end, we have $$$A = {1, 4, 5}$$$, so the cost of the configuration is equal to $$$5$$$. | 2,400 | false | false | false | false | true | false | false | false | false | false | 4,082 |
1941A | Rudolf is going to visit Bernard, and he decided to take the metro to get to him. The ticket can be purchased at a machine that accepts exactly two coins, the sum of which does not exceed $$$k$$$. Rudolf has two pockets with coins. In the left pocket, there are $$$n$$$ coins with denominations $$$b_1, b_2, dots, b_n$$$. In the right pocket, there are $$$m$$$ coins with denominations $$$c_1, c_2, dots, c_m$$$. He wants to choose exactly one coin from the left pocket and exactly one coin from the right pocket (two coins in total). Help Rudolf determine how many ways there are to select indices $$$f$$$ and $$$s$$$ such that $$$b_f + c_s le k$$$. Input The first line contains an integer $$$t$$$ ($$$1 le t le 100$$$) — the number of test cases. Then follows the description of each test case. The first line of each test case contains three natural numbers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 le n, m le 100, 1 le k le 2000$$$) — the number of coins in the left and right pockets, and the maximum sum of two coins for the ticket payment at the counter, respectively. The second line of each test case contains $$$n$$$ integers $$$b_i$$$ ($$$1 le b_i le 1000$$$) — the denominations of coins in the left pocket. The third line of each test case contains $$$m$$$ integers $$$c_i$$$ ($$$1 le c_i le 1000$$$) — the denominations of coins in the right pocket. Output For each testcase, output a single integer — the number of ways Rudolf can select two coins, taking one from each pocket, so that the sum of the coins does not exceed $$$k$$$. Example Input 4 4 4 8 1 5 10 14 2 1 8 1 2 3 4 4 8 1 2 3 4 2 7 1 1 1 1 2 7 3 4 2000 1 1 1 1 1 1 1 Note Note that the pairs indicate the indices of the coins in the array, not their denominations. In the first test case, Rudolf can choose the following pairs of coins: $$$[1, 1], [1, 2], [1, 4], [2, 1], [2, 2], [2, 4]$$$. In the second test case, Rudolf cannot choose one coin from each pocket in any way, as the sum of any two elements from the first and second arrays will exceed the value of $$$k=4$$$. In the third test case, Rudolf can choose: $$$[1, 1], [2, 1], [3, 1], [4, 1]$$$. In the fourth test case, Rudolf can choose any coin from the left pocket and any coin from the right pocket. | 800 | true | false | false | false | false | false | true | false | false | false | 639 |
1710E | You are given two arrays of integers $$$a_1,a_2,dots,a_n$$$ and $$$b_1,b_2,dots,b_m$$$. Alice and Bob are going to play a game. Alice moves first and they take turns making a move. They play on a grid of size $$$n imes m$$$ (a grid with $$$n$$$ rows and $$$m$$$ columns). Initially, there is a rook positioned on the first row and first column of the grid. During her/his move, a player can do one of the following two operations: 1. Move the rook to a different cell on the same row or the same column of the current cell. A player cannot move the rook to a cell that has been visited $$$1000$$$ times before (i.e., the rook can stay in a certain cell at most $$$1000$$$ times during the entire game). Note that the starting cell is considered to be visited once at the beginning of the game. 2. End the game immediately with a score of $$$a_r+b_c$$$, where $$$(r, c)$$$ is the current cell (i.e., the rook is on the $$$r$$$-th row and $$$c$$$-th column). Bob wants to maximize the score while Alice wants to minimize it. If they both play this game optimally, what is the final score of the game? Input The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 leq n,m leq 2 cdot 10^5$$$) — the length of the arrays $$$a$$$ and $$$b$$$ (which coincide with the number of rows and columns of the grid). The second line contains the $$$n$$$ integers $$$a_1, a_2, dots, a_n$$$ ($$$1 leq a_i leq 5 cdot 10^8$$$). The third line contains the $$$m$$$ integers $$$b_1, b_2,dots, b_n$$$ ($$$1 leq b_i leq 5 cdot 10^8$$$). Output Print a single line containing the final score of the game. Examples Input 4 5 235499701 451218171 355604420 132973458 365049318 264083156 491406845 62875547 175951751 Note In the first test case, Alice moves the rook to $$$(2, 1)$$$ and Bob moves the rook to $$$(1, 1)$$$. This process will repeat for $$$999$$$ times until finally, after Alice moves the rook, Bob cannot move it back to $$$(1, 1)$$$ because it has been visited $$$1000$$$ times before. So the final score of the game is $$$a_2+b_1=4$$$. In the second test case, the final score of the game is $$$a_3+b_5$$$. | 2,400 | false | false | false | false | false | false | false | true | false | false | 2,016 |
594B | For months Maxim has been coming to work on his favorite bicycle. And quite recently he decided that he is ready to take part in a cyclists' competitions. He knows that this year _n_ competitions will take place. During the _i_-th competition the participant must as quickly as possible complete a ride along a straight line from point _s__i_ to point _f__i_ (_s__i_u2009<u2009_f__i_). Measuring time is a complex process related to usage of a special sensor and a time counter. Think of the front wheel of a bicycle as a circle of radius _r_. Let's neglect the thickness of a tire, the size of the sensor, and all physical effects. The sensor is placed on the rim of the wheel, that is, on some fixed point on a circle of radius _r_. After that the counter moves just like the chosen point of the circle, i.e. moves forward and rotates around the center of the circle. At the beginning each participant can choose any point _b__i_, such that his bike is fully behind the starting line, that is, _b__i_u2009<u2009_s__i_u2009-u2009_r_. After that, he starts the movement, instantly accelerates to his maximum speed and at time _ts__i_, when the coordinate of the sensor is equal to the coordinate of the start, the time counter starts. The cyclist makes a complete ride, moving with his maximum speed and at the moment the sensor's coordinate is equal to the coordinate of the finish (moment of time _tf__i_), the time counter deactivates and records the final time. Thus, the counter records that the participant made a complete ride in time _tf__i_u2009-u2009_ts__i_. Maxim is good at math and he suspects that the total result doesn't only depend on his maximum speed _v_, but also on his choice of the initial point _b__i_. Now Maxim is asking you to calculate for each of _n_ competitions the minimum possible time that can be measured by the time counter. The radius of the wheel of his bike is equal to _r_. Input The first line contains three integers _n_, _r_ and _v_ (1u2009≤u2009_n_u2009≤u2009100u2009000,u20091u2009≤u2009_r_,u2009_v_u2009≤u2009109)xa0— the number of competitions, the radius of the front wheel of Max's bike and his maximum speed, respectively. Next _n_ lines contain the descriptions of the contests. The _i_-th line contains two integers _s__i_ and _f__i_ (1u2009≤u2009_s__i_u2009<u2009_f__i_u2009≤u2009109)xa0— the coordinate of the start and the coordinate of the finish on the _i_-th competition. Output Print _n_ real numbers, the _i_-th number should be equal to the minimum possible time measured by the time counter. Your answer will be considered correct if its absolute or relative error will not exceed 10u2009-u20096. Namely: let's assume that your answer equals _a_, and the answer of the jury is _b_. The checker program will consider your answer correct if . | 2,500 | false | false | false | false | false | false | false | true | false | false | 7,471 |
1053E | Euler is a little, cute squirrel. When the autumn comes, he collects some reserves for winter. The interesting fact is that Euler likes to collect acorns in a specific way. A tree can be described as $$$n$$$ acorns connected by $$$n - 1$$$ branches, such that there is exactly one way between each pair of acorns. Let's enumerate the acorns from $$$1$$$ to $$$n$$$. The squirrel chooses one acorn (not necessary with number $$$1$$$) as a start, and visits them in a way called "Euler tour" (see notes), collecting each acorn when he visits it for the last time. Today morning Kate was observing Euler. She took a sheet of paper and wrote down consecutive indices of acorns on his path. Unfortunately, during her way to home it started raining and some of numbers became illegible. Now the girl is very sad, because she has to present the observations to her teacher. "Maybe if I guess the lacking numbers, I'll be able to do it!" she thought. Help her and restore any valid Euler tour of some tree or tell that she must have made a mistake. Input The first line contains a single integer $$$n$$$ ($$$1 leq n leq 5 cdot 10^5$$$), denoting the number of acorns in the tree. The second line contains $$$2n - 1$$$ integers $$$a_1, a_2, ldots, a_{2n-1}$$$ ($$$0 leq a_i leq n$$$) — the Euler tour of the tree that Kate wrote down. $$$0$$$ means an illegible number, which has to be guessed. Output If there is no Euler tour satisfying the given description, output "no" in the first line. Otherwise, on the first line output "yes", and then in the second line print the Euler tour which satisfy the given description. Any valid Euler tour will be accepted, since the teacher doesn't know how exactly the initial tree looks. Note An Euler tour of a tree with $$$n$$$ acorns is a sequence of $$$2n - 1$$$ indices of acorns. such that each acorn occurs at least once, the first and the last acorns are same and each two consecutive acorns are directly connected with a branch. | 3,500 | false | false | false | false | false | true | false | false | false | false | 5,448 |
534D | On February, 30th _n_ students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in stayed in CTOP until the end of the day and never left. At any time any three students could join together and start participating in a team contest, which lasted until the end of the day. The team did not distract from the contest for a minute, so when another student came in and greeted those who were present, he did not shake hands with the members of the contest writing team. Each team consisted of exactly three students, and each student could not become a member of more than one team. Different teams could start writing contest at different times. Given how many present people shook the hands of each student, get a possible order in which the students could have come to CTOP. If such an order does not exist, then print that this is impossible. Please note that some students could work independently until the end of the day, without participating in a team contest. Input The first line contains integer _n_ (1u2009≤u2009_n_u2009≤u20092·105) — the number of students who came to CTOP. The next line contains _n_ integers _a_1,u2009_a_2,u2009...,u2009_a__n_ (0u2009≤u2009_a__i_u2009<u2009_n_), where _a__i_ is the number of students with who the _i_-th student shook hands. Output If the sought order of students exists, print in the first line "Possible" and in the second line print the permutation of the students' numbers defining the order in which the students entered the center. Number _i_ that stands to the left of number _j_ in this permutation means that the _i_-th student came earlier than the _j_-th student. If there are multiple answers, print any of them. If the sought order of students doesn't exist, in a single line print "Impossible". Examples Output Possible 7 5 2 1 6 8 3 4 9 Note In the first sample from the statement the order of events could be as follows: student 4 comes in (_a_4u2009=u20090), he has no one to greet; student 5 comes in (_a_5u2009=u20091), he shakes hands with student 4; student 1 comes in (_a_1u2009=u20092), he shakes hands with two students (students 4, 5); student 3 comes in (_a_3u2009=u20093), he shakes hands with three students (students 4, 5, 1); students 4, 5, 3 form a team and start writing a contest; student 2 comes in (_a_2u2009=u20091), he shakes hands with one student (number 1). In the second sample from the statement the order of events could be as follows: student 7 comes in (_a_7u2009=u20090), he has nobody to greet; student 5 comes in (_a_5u2009=u20091), he shakes hands with student 7; student 2 comes in (_a_2u2009=u20092), he shakes hands with two students (students 7, 5); students 7, 5, 2 form a team and start writing a contest; student 1 comes in(_a_1u2009=u20090), he has no one to greet (everyone is busy with the contest); student 6 comes in (_a_6u2009=u20091), he shakes hands with student 1; student 8 comes in (_a_8u2009=u20092), he shakes hands with two students (students 1, 6); student 3 comes in (_a_3u2009=u20093), he shakes hands with three students (students 1, 6, 8); student 4 comes in (_a_4u2009=u20094), he shakes hands with four students (students 1, 6, 8, 3); students 8, 3, 4 form a team and start writing a contest; student 9 comes in (_a_9u2009=u20092), he shakes hands with two students (students 1, 6). In the third sample from the statement the order of events is restored unambiguously: student 1 comes in (_a_1u2009=u20090), he has no one to greet; student 3 comes in (or student 4) (_a_3u2009=u2009_a_4u2009=u20091), he shakes hands with student 1; student 2 comes in (_a_2u2009=u20092), he shakes hands with two students (students 1, 3 (or 4)); the remaining student 4 (or student 3), must shake one student's hand (_a_3u2009=u2009_a_4u2009=u20091) but it is impossible as there are only two scenarios: either a team formed and he doesn't greet anyone, or he greets all the three present people who work individually. | 1,900 | false | true | false | false | true | true | false | true | false | false | 7,698 |
1129B | Consider the following problem: given an array $$$a$$$ containing $$$n$$$ integers (indexed from $$$0$$$ to $$$n-1$$$), find $$$maxlimits_{0 leq l leq r leq n-1} sumlimits_{l leq i leq r} (r-l+1) cdot a_i$$$. In this problem, $$$1 leq n leq 2,000$$$ and $$$a_i leq 10^6$$$. In an attempt to solve the problem described, Alice quickly came up with a blazing-fast greedy algorithm and coded it. Her implementation in pseudocode is as follows: function find_answer(n, a) # Assumes n is an integer between 1 and 2000, inclusive # Assumes a is a list containing n integers: a[0], a[1], ..., a[n-1] res = 0 cur = 0 k = -1 for i = 0 to i = n-1 cur = cur + a[i] if cur < 0 cur = 0 k = i res = max(res, (i-k)*cur) return res Also, as you can see, Alice's idea is not entirely correct. For example, suppose $$$n = 4$$$ and $$$a = [6, -8, 7, -42]$$$. Then, find_answer(n, a) would return $$$7$$$, but the correct answer is $$$3 cdot (6-8+7) = 15$$$. You told Alice that her solution is incorrect, but she did not believe what you said. Given an integer $$$k$$$, you are to find any sequence $$$a$$$ of $$$n$$$ integers such that the correct answer and the answer produced by Alice's algorithm differ by exactly $$$k$$$. Note that although the choice of $$$n$$$ and the content of the sequence is yours, you must still follow the constraints earlier given: that $$$1 leq n leq 2,000$$$ and that the absolute value of each element does not exceed $$$10^6$$$. If there is no such sequence, determine so. Output If there is no sought sequence, print "-1". Otherwise, in the first line, print one integer $$$n$$$ ($$$1 leq n leq 2,000$$$), denoting the number of elements in the sequence. Then, in the second line, print $$$n$$$ space-separated integers: $$$a_0, a_1, ldots, a_{n-1}$$$ ($$$a_i leq 10^6$$$). Note The first sample corresponds to the example given in the problem statement. In the second sample, one answer is $$$n = 7$$$ with $$$a = [30, -12, -99, 123, -2, 245, -300]$$$, in which case find_answer(n, a) returns $$$1098$$$, while the correct answer is $$$1710$$$. | 2,000 | false | false | false | false | false | true | false | false | false | false | 5,075 |
1338E | Due to the success of TWICE, JYP Entertainment has earned countless money and emerged as the biggest entertainment firm by market capitalization. Therefore, the boss, JYP, has decided to create a new nation and has appointed you to provide a design diagram. The new nation consists of $$$n$$$ cities and some roads between them. JYP has given some restrictions: To guarantee efficiency while avoiding chaos, for any $$$2$$$ different cities $$$A$$$ and $$$B$$$, there is exactly one road between them, and it is one-directional. There are no roads connecting a city to itself. The logo of rivaling companies should not appear in the plan, that is, there does not exist $$$4$$$ distinct cities $$$A$$$,$$$B$$$,$$$C$$$,$$$D$$$ , such that the following configuration occurs. JYP has given criteria for your diagram. For two cities $$$A$$$,$$$B$$$, let $$$dis(A,B)$$$ be the smallest number of roads you have to go through to get from $$$A$$$ to $$$B$$$. If it is not possible to walk from $$$A$$$ to $$$B$$$, $$$dis(A,B) = 614n$$$. Then, the efficiency value is defined to be the sum of $$$dis(A,B)$$$ for all ordered pairs of distinct cities $$$(A,B)$$$. Note that $$$dis(A,B)$$$ doesn't have to be equal to $$$dis(B,A)$$$. You have drawn a design diagram that satisfies JYP's restrictions. Find the sum of $$$dis(A,B)$$$ over all ordered pairs of cities $$$(A,B)$$$ with $$$A eq B$$$. Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input. Input The first line contains a single integer $$$n$$$ ($$$4 le n le 8000$$$, $$$n equiv 0 pmod{4}$$$)xa0— the number of cities. A binary matrix is encrypted in the following format. Each of $$$n$$$ next lines contains $$$frac{n}{4}$$$ one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from $$$0$$$ to $$$9$$$ or as uppercase Latin letters from $$$A$$$ to $$$F$$$). Binary representation of each of these numbers denotes next $$$4$$$ elements of the matrix in the corresponding row. For example, if the number $$$B$$$ is given, then the corresponding elements are $$$1011$$$, and if the number is $$$5$$$, then the corresponding elements are $$$0101$$$. After you obtain the decrypted binary matrix, the $$$j$$$-th character of the $$$i$$$-th row is $$$1$$$ if the one-directional road between cities $$$i$$$ and $$$j$$$ is directed from $$$i$$$ to $$$j$$$, and $$$0$$$ otherwise. It is guaranteed that the graph satisfies the restrictions mentioned above. Output Output one integer, representing the sum of $$$dis(A,B)$$$ over all ordered pairs of cities $$$(A,B)$$$ with $$$A eq B$$$. Examples Input 8 7F 3F 1F 0C 06 03 11 18 Note The first example corresponds to the matrix: $$$begin{matrix} 0111 0010 0001 0100 end{matrix}$$$ Which corresponds to this graph: $$$dis(1,2)=dis(1,3)=dis(1,4)=dis(2,3)=dis(3,4)=dis(4,2)=1$$$ $$$dis(2,4)=dis(4,3)=dis(3,2)=2$$$ $$$dis(2,1)=dis(3,1)=dis(4,1)=2456$$$ Therefore the answer for the diagram is $$$7380$$$. | 3,500 | false | false | false | false | false | false | false | false | false | true | 4,010 |
1621G | You are given the sequence of integers $$$a_1, a_2, ldots, a_n$$$ of length $$$n$$$. The sequence of indices $$$i_1 < i_2 < ldots < i_k$$$ of length $$$k$$$ denotes the subsequence $$$a_{i_1}, a_{i_2}, ldots, a_{i_k}$$$ of length $$$k$$$ of sequence $$$a$$$. The subsequence $$$a_{i_1}, a_{i_2}, ldots, a_{i_k}$$$ of length $$$k$$$ of sequence $$$a$$$ is called increasing subsequence if $$$a_{i_j} < a_{i_{j+1}}$$$ for each $$$1 leq j < k$$$. The weight of the increasing subsequence $$$a_{i_1}, a_{i_2}, ldots, a_{i_k}$$$ of length $$$k$$$ of sequence $$$a$$$ is the number of $$$1 leq j leq k$$$, such that exists index $$$i_k < x leq n$$$ and $$$a_x > a_{i_j}$$$. For example, if $$$a = [6, 4, 8, 6, 5]$$$, then the sequence of indices $$$i = [2, 4]$$$ denotes increasing subsequence $$$[4, 6]$$$ of sequence $$$a$$$. The weight of this increasing subsequence is $$$1$$$, because for $$$j = 1$$$ exists $$$x = 5$$$ and $$$a_5 = 5 > a_{i_1} = 4$$$, but for $$$j = 2$$$ such $$$x$$$ doesn't exist. Find the sum of weights of all increasing subsequences of $$$a$$$ modulo $$$10^9+7$$$. Input The first line contains a single integer $$$t$$$ ($$$1 leq t leq 1000$$$)xa0— the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 leq n leq 2 cdot 10^5$$$)xa0— the length of the sequence $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, ldots, a_n$$$ ($$$1 leq a_i leq 10^9$$$)xa0— the sequence $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 cdot 10^5$$$. Note In the first test case the following increasing subsequences of $$$a$$$ have not zero weight: The weight of $$$[a_1] = [6]$$$ is $$$1$$$. The weight of $$$[a_2] = [4]$$$ is $$$1$$$. The weight of $$$[a_2, a_3] = [4, 8]$$$ is $$$1$$$. The weight of $$$[a_2, a_4] = [4, 6]$$$ is $$$1$$$. The sum of weights of increasing subsequences is $$$4$$$. In the second test case there are $$$7$$$ increasing subsequences of $$$a$$$ with not zero weight: $$$3$$$ with weight $$$1$$$, $$$3$$$ with weight $$$2$$$ and $$$1$$$ with weight $$$3$$$. The sum of weights is $$$12$$$. | 3,200 | true | false | false | true | true | false | false | false | false | false | 2,514 |
1200A | Amugae has a hotel consisting of $$$10$$$ rooms. The rooms are numbered from $$$0$$$ to $$$9$$$ from left to right. The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance. One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory. Input The first line consists of an integer $$$n$$$ ($$$1 le n le 10^5$$$), the number of events in Amugae's memory. The second line consists of a string of length $$$n$$$ describing the events in chronological order. Each character represents: 'L': A customer arrives from the left entrance. 'R': A customer arrives from the right entrance. '0', '1', ..., '9': The customer in room $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$ respectively) leaves. It is guaranteed that there is at least one empty room when a customer arrives, and there is a customer in the room $$$x$$$ when $$$x$$$ ($$$0$$$, $$$1$$$, ..., $$$9$$$) is given. Also, all the rooms are initially empty. Output In the only line, output the hotel room's assignment status, from room $$$0$$$ to room $$$9$$$. Represent an empty room as '0', and an occupied room as '1', without spaces. Note In the first example, hotel room's assignment status after each action is as follows. First of all, all rooms are empty. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. L: one more customer from the left entrance. Assignment status is 1110000001. 1: the customer in room $$$1$$$ leaves. Assignment status is 1010000001. R: one more customer from the right entrance. Assignment status is 1010000011. L: one more customer from the left entrance. Assignment status is 1110000011. 1: the customer in room $$$1$$$ leaves. Assignment status is 1010000011. So after all, hotel room's final assignment status is 1010000011. In the second example, hotel room's assignment status after each action is as follows. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. 0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000 again. 0: the customer in room $$$0$$$ leaves. Assignment status is 0000000000. L: a customer arrives to the hotel through the left entrance. Assignment status is 1000000000. L: one more customer from the left entrance. Assignment status is 1100000000. R: one more customer from the right entrance. Assignment status is 1100000001. R: one more customer from the right entrance. Assignment status is 1100000011. 9: the customer in room $$$9$$$ leaves. Assignment status is 1100000010. So after all, hotel room's final assignment status is 1100000010. | 800 | false | false | true | false | true | false | true | false | false | false | 4,701 |
852I | This story is happening in a town named BubbleLand. There are _n_ houses in BubbleLand. In each of these _n_ houses lives a boy or a girl. People there really love numbers and everyone has their favorite number _f_. That means that the boy or girl that lives in the _i_-th house has favorite number equal to _f__i_. The houses are numerated with numbers 1 to _n_. The houses are connected with _n_u2009-u20091 bidirectional roads and you can travel from any house to any other house in the town. There is exactly one path between every pair of houses. A new dating had agency opened their offices in this mysterious town and the citizens were very excited. They immediately sent _q_ questions to the agency and each question was of the following format: _a_ _b_xa0— asking how many ways are there to choose a couple (boy and girl) that have the same favorite number and live in one of the houses on the unique path from house _a_ to house _b_. Help the dating agency to answer the questions and grow their business. Input The first line contains an integer _n_ (1u2009≤u2009_n_u2009≤u2009105), the number of houses in the town. The second line contains _n_ integers, where the _i_-th number is 1 if a boy lives in the _i_-th house or 0 if a girl lives in _i_-th house. The third line contains _n_ integers, where the _i_-th number represents the favorite number _f__i_ (1u2009≤u2009_f__i_u2009≤u2009109) of the girl or boy that lives in the _i_-th house. The next _n_u2009-u20091 lines contain information about the roads and the _i_-th line contains two integers _a__i_ and _b__i_ (1u2009≤u2009_a__i_,u2009_b__i_u2009≤u2009_n_) which means that there exists road between those two houses. It is guaranteed that it's possible to reach any house from any other. The following line contains an integer _q_ (1u2009≤u2009_q_u2009≤u2009105), the number of queries. Each of the following _q_ lines represents a question and consists of two integers _a_ and _b_ (1u2009≤u2009_a_,u2009_b_u2009≤u2009_n_). Output For each of the _q_ questions output a single number, the answer to the citizens question. Example Input 7 1 0 0 1 0 1 0 9 2 9 2 2 9 9 2 6 1 2 4 2 6 5 3 6 7 4 2 1 3 7 5 Note In the first question from house 1 to house 3, the potential couples are (1,u20093) and (6,u20093). In the second question from house 7 to house 5, the potential couples are (7,u20096), (4,u20092) and (4,u20095). | 2,300 | false | false | false | false | false | false | true | false | false | true | 6,335 |
876A | Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is _a_ meters, between Rabbit's and Eeyore's house is _b_ meters, between Owl's and Eeyore's house is _c_ meters. For enjoying his life and singing merry songs Winnie-the-Pooh should have a meal _n_ times a day. Now he is in the Rabbit's house and has a meal for the first time. Each time when in the friend's house where Winnie is now the supply of honey is about to end, Winnie leaves that house. If Winnie has not had a meal the required amount of times, he comes out from the house and goes to someone else of his two friends. For this he chooses one of two adjacent paths, arrives to the house on the other end and visits his friend. You may assume that when Winnie is eating in one of his friend's house, the supply of honey in other friend's houses recover (most probably, they go to the supply store). Winnie-the-Pooh does not like physical activity. He wants to have a meal _n_ times, traveling minimum possible distance. Help him to find this distance. Input First line contains an integer _n_ (1u2009≤u2009_n_u2009≤u2009100)xa0— number of visits. Second line contains an integer _a_ (1u2009≤u2009_a_u2009≤u2009100)xa0— distance between Rabbit's and Owl's houses. Third line contains an integer _b_ (1u2009≤u2009_b_u2009≤u2009100)xa0— distance between Rabbit's and Eeyore's houses. Fourth line contains an integer _c_ (1u2009≤u2009_c_u2009≤u2009100)xa0— distance between Owl's and Eeyore's houses. Output Output one numberxa0— minimum distance in meters Winnie must go through to have a meal _n_ times. Note In the first test case the optimal path for Winnie is the following: first have a meal in Rabbit's house, then in Owl's house, then in Eeyore's house. Thus he will pass the distance 2u2009+u20091u2009=u20093. In the second test case Winnie has a meal in Rabbit's house and that is for him. So he doesn't have to walk anywhere at all. | 900 | true | false | false | false | false | false | false | false | false | false | 6,242 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.