problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
E. Songwritertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndi is a mathematician, a computer scientist, and a songwriter. After spending so much time writing songs, he finally writes a catchy melody that he thought as his best creation. However, the singer who will sing the song/melody has a unique vocal range, thus, an adjustment may be needed.A melody is defined as a sequence of N notes which are represented by integers. Let A be the original melody written by Andi. Andi needs to adjust A into a new melody B such that for every i where 1 \le i < N: If A_i < A_{i+1}, then B_i < B_{i+1}. If A_i = A_{i+1}, then B_i = B_{i+1}. If A_i > A_{i+1}, then B_i > B_{i+1}. |B_i - B_{i+1}| \le K, i.e. the difference between two successive notes is no larger than K. Moreover, the singer also requires that all notes are within her vocal range, i.e. L \le B_i \le R for all 1 \le i \le N.Help Andi to determine whether such B exists, and find the lexicographically smallest B if it exists. A melody X is lexicographically smaller than melody Y if and only if there exists j (1 \le j \le N) such that X_i = Y_i for all i < j and X_{j} < Y_{j}.For example, consider a melody A = \{1,3,5,6,7,8,9,10,3,7,8,9,10,11,12,12\} as shown in the following figure. The diagonal arrow up in the figure implies that A_i < A_{i+1}, the straight right arrow implies that A_i = A_{i+1}, and the diagonal arrow down implies that A_i > A_{i+1}. Supposed we want to make a new melody with L = 1, R = 8, and K = 6. The new melody B = \{1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,8\} as shown in the figure satisfies all the requirements, and it is the lexicographically smallest possible.InputInput begins with a line containing four integers: N L R K (1 \le N \le 100\,000; 1 \le L \le R \le 10^9; 1 \le K \le 10^9) representing the number of notes in the melody, the vocal range (L and R), and the maximum difference between two successive notes in the new melody, respectively. The next line contains N integers: A_i (1 \le A_i \le 10^9) representing the original melody.OutputOutput in a line N integers (each separated by a single space) representing the lexicographically smallest melody satisfying all the requirements, or output -1 if there is no melody satisfying all the requirements. Note that it might be possible that the lexicographically smallest melody which satisfies all the requirements to be the same as the original melody.ExamplesInput 16 1 8 6 1 3 5 6 7 8 9 10 3 7 8 9 10 11 12 12 Output 1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 8 Input 16 1 8 6 1 3 5 6 7 8 9 10 3 7 8 9 10 11 12 13 Output -1 Input 16 1 10 10 1 3 5 6 7 8 9 10 3 7 8 9 1 11 12 13 Output 1 2 3 4 5 6 7 8 1 2 3 4 1 2 3 4 NoteExplanation for the sample input/output #1This is the example from the problem description.
16 1 8 6 1 3 5 6 7 8 9 10 3 7 8 9 10 11 12 12
1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 8
1 second
256 megabytes
['greedy', 'two pointers', '*2200']
D. Find String in a Gridtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a grid G containing R rows (numbered from 1 to R, top to bottom) and C columns (numbered from 1 to C, left to right) of uppercase characters. The character in the r^{th} row and the c^{th} column is denoted by G_{r, c}. You also have Q strings containing uppercase characters. For each of the string, you want to find the number of occurrences of the string in the grid.An occurrence of string S in the grid is counted if S can be constructed by starting at one of the cells in the grid, going right 0 or more times, and then going down 0 or more times. Two occurrences are different if the set of cells used to construct the string is different. Formally, for each string S, you would like to count the number of tuples \langle r, c, \Delta r, \Delta c \rangle such that: 1 \le r \le R and r \le r + \Delta r \le R 1 \le c \le C and c \le c + \Delta c \le C S = G_{r, c} G_{r, c + 1} \dots G_{r, c + \Delta c} G_{r + 1, c + \Delta c} \dots G_{r + \Delta r, c + \Delta c} InputInput begins with a line containing three integers: R C Q (1 \le R, C \le 500; 1 \le Q \le 200\,000) representing the size of the grid and the number of strings, respectively. The next R lines each contains C uppercase characters representing the grid. The c^{th} character on the r^{th} line is G_{r, c}. The next Q lines each contains a string S containing uppercase characters. The length of this string is a positive integer not more than 200\,000. The sum of the length of all Q strings combined is not more than 200\,000.OutputFor each query in the same order as input, output in a line an integer representing the number of occurrences of the string in the grid.ExamplesInput 3 3 5 ABC BCD DAB ABC BC BD AC A Output 2 3 1 0 2 Input 2 3 3 AAA AAA A AAA AAAAA Output 6 4 0 NoteExplanation for the sample input/output #1 There are 2 occurrences of "ABC", represented by the tuples \langle 1, 1, 1, 1 \rangle and \langle 1, 1, 0, 2 \rangle. There are 3 occurrences of "BC", represented by the tuples \langle 1, 2, 0, 1 \rangle, \langle 1, 2, 1, 0 \rangle, and \langle 2, 1, 0, 1 \rangle. There is 1 occurrence of "BD", represented by the tuple \langle 2, 1, 1, 0 \rangle. There is no occurrence of "AC". There are 2 occurrences of "A", represented by the tuples \langle 1, 1, 0, 0 \rangle and \langle 3, 2, 0, 0 \rangle.
3 3 5 ABC BCD DAB ABC BC BD AC A
2 3 1 0 2
5 seconds
256 megabytes
['data structures', 'dp', 'strings', 'trees', '*3000']
C. Even Pathtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPathfinding is a task of finding a route between two points. It often appears in many problems. For example, in a GPS navigation software where a driver can query for a suggested route, or in a robot motion planning where it should find a valid sequence of movements to do some tasks, or in a simple maze solver where it should find a valid path from one point to another point. This problem is related to solving a maze.The maze considered in this problem is in the form of a matrix of integers A of N \times N. The value of each cell is generated from a given array R and C of N integers each. Specifically, the value on the i^{th} row and j^{th} column, cell (i,j), is equal to R_i + C_j. Note that all indexes in this problem are from 1 to N.A path in this maze is defined as a sequence of cells (r_1,c_1), (r_2,c_2), \dots, (r_k,c_k) such that |r_i - r_{i+1}| + |c_i - c_{i+1}| = 1 for all 1 \le i < k. In other words, each adjacent cell differs only by 1 row or only by 1 column. An even path in this maze is defined as a path in which all the cells in the path contain only even numbers.Given a tuple \langle r_a,c_a,r_b,c_b \rangle as a query, your task is to determine whether there exists an even path from cell (r_a,c_a) to cell (r_b,c_b). To simplify the problem, it is guaranteed that both cell (r_a,c_a) and cell (r_b,c_b) contain even numbers.For example, let N = 5, R = \{6, 2, 7, 8, 3\}, and C = \{3, 4, 8, 5, 1\}. The following figure depicts the matrix A of 5 \times 5 which is generated from the given array R and C. Let us consider several queries: \langle 2, 2, 1, 3 \rangle: There is an even path from cell (2,2) to cell (1,3), e.g., (2,2), (2,3), (1,3). Of course, (2,2), (1,2), (1,3) is also a valid even path. \langle 4, 2, 4, 3 \rangle: There is an even path from cell (4,2) to cell (4,3), namely (4,2), (4,3). \langle 5, 1, 3, 4 \rangle: There is no even path from cell (5,1) to cell (3,4). Observe that the only two neighboring cells of (5,1) are cell (5,2) and cell (4,1), and both of them contain odd numbers (7 and 11, respectively), thus, there cannot be any even path originating from cell (5,1). InputInput begins with a line containing two integers: N Q (2 \le N \le 100\,000; 1 \le Q \le 100\,000) representing the size of the maze and the number of queries, respectively. The next line contains N integers: R_i (0 \le R_i \le 10^6) representing the array R. The next line contains N integers: C_i (0 \le C_i \le 10^6) representing the array C. The next Q lines each contains four integers: r_a c_a r_b c_b (1 \le r_a, c_a, r_b, c_b \le N) representing a query of \langle r_a, c_a, r_b, c_b \rangle. It is guaranteed that (r_a,c_a) and (r_b,c_b) are two different cells in the maze and both of them contain even numbers.OutputFor each query in the same order as input, output in a line a string "YES" (without quotes) or "NO" (without quotes) whether there exists an even path from cell (r_a,c_a) to cell (r_b,c_b).ExamplesInput 5 3 6 2 7 8 3 3 4 8 5 1 2 2 1 3 4 2 4 3 5 1 3 4 Output YES YES NO Input 3 2 30 40 49 15 20 25 2 2 3 3 1 2 2 2 Output NO YES NoteExplanation for the sample input/output #1This is the example from the problem description.
5 3 6 2 7 8 3 3 4 8 5 1 2 2 1 3 4 2 4 3 5 1 3 4
YES YES NO
1 second
256 megabytes
['data structures', 'implementation', '*1600']
B. Cleaning Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe new ICPC town has N junctions (numbered from 1 to N) which are connected by N-1 roads. It is possible from one junction to go to any other junctions by going through one or more roads. To make sure all the junctions are well-maintained, the government environment agency is planning to deploy their newest advanced cleaning robots. In addition to its cleaning ability, each robot is also equipped with a movement ability such that it can move from one junction to any other junctions connected by roads. However, as you might have guessed, such robots are not cheap. Therefore, the agency is considering the following deployment plan.Let T_k be the set of junctions which should be cleaned by the k^{th} robot (also known as, the robot's task), and |T_k| \ge 1 be the number of junctions in T_k. The junctions in T_k form a path, i.e. there exists a sequence of v_1, v_2, \dots, v_{|T_k|} where v_i \in T_k and v_i \neq v_j for all i \neq j such that each adjacent junction in this sequence is connected by a road. The union of T for all robots is equal to the set of all junctions in ICPC town. On the other hand, no two robots share a common junction, i.e. T_i \cap T_j = \emptyset if i \neq j.To avoid complaints from citizens for an inefficient operation, the deployment plan should be irreducible; in other words, there should be no two robots, i and j, such that T_i \cup T_j forms a (longer) path. Note that the agency does not care whether the number of robots being used is minimized as long as all the tasks are irreducible.Your task in this problem is to count the number of feasible deployment plan given the town's layout. A plan is feasible if and only if it satisfies all the above-mentioned requirements.For example, let N = 6 and the roads are \{(1,3),(2,3),(3,4),(4,5),(4,6)\}. There are 5 feasible deployment plans as shown in the following figure. The first plan uses 2 robots (labeled as A and B in the figure) to clean \{1,2,3\} and \{4,5,6\}. The second plan uses 3 robots (labeled as A, B, and C in the figure) to clean \{1,3,4,6\}, \{2\}, and \{5\}. The third plan uses 3 robots to clean \{1,3,4,5\}, \{2\}, and \{6\}. The fourth plan uses 3 robots to clean \{1\}, \{2,3,4,6\}, and \{5\}. The fifth plan uses 3 robots to clean \{1\}, \{2,3,4,5\}, and \{6\}. No other plans are feasible in this case. For example, the plan \{\{1,3\},\{2\},\{4,5,6\}\} is not feasible as the task \{1,3\} and \{2\} can be combined into a longer path \{1,3,2\}. The plan \{\{1,2,3,4\},\{5\},\{6\}\} is also not feasible as \{1,2,3,4\} is not a path.InputInput begins with a line containing an integer: N (1 \le N \le 100\,000) representing the number of junctions. The next N-1 lines each contains two integers: u_i v_i (1 \le u_i < v_i \le N) representing a road connecting junction u_i and junction v_i. It is guaranteed that it is possible from one junction to go to any other junctions by going through one or more roads.OutputOutput in a line an integer representing the number of feasible deployment plans. As this output can be large, you need to modulo the output by 1\,000\,000\,007.ExamplesInput 6 1 3 2 3 3 4 4 5 4 6 Output 5 Input 5 1 2 2 3 2 4 4 5 Output 3 NoteExplanation for the sample input/output #1This is the example from the problem description.
6 1 3 2 3 3 4 4 5 4 6
5
1 second
256 megabytes
['dp', 'trees', '*2300']
A. Copying Homeworktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDanang and Darto are classmates. They are given homework to create a permutation of N integers from 1 to N. Danang has completed the homework and created a permutation A of N integers. Darto wants to copy Danang's homework, but Danang asks Darto to change it up a bit so it does not look obvious that Darto copied.The difference of two permutations of N integers A and B, denoted by diff(A, B), is the sum of the absolute difference of A_i and B_i for all i. In other words, diff(A, B) = \Sigma_{i=1}^N |A_i - B_i|. Darto would like to create a permutation of N integers that maximizes its difference with A. Formally, he wants to find a permutation of N integers B_{max} such that diff(A, B_{max}) \ge diff(A, B') for all permutation of N integers B'.Darto needs your help! Since the teacher giving the homework is lenient, any permutation of N integers B is considered different with A if the difference of A and B is at least N. Therefore, you are allowed to return any permutation of N integers B such that diff(A, B) \ge N.Of course, you can still return B_{max} if you want, since it can be proven that diff(A, B_{max}) \ge N for any permutation A and N > 1. This also proves that there exists a solution for any permutation of N integers A. If there is more than one valid solution, you can output any of them.InputInput begins with a line containing an integer: N (2 \le N \le 100\,000) representing the size of Danang's permutation. The next line contains N integers: A_i (1 \le A_i \le N) representing Danang's permutation. It is guaranteed that all elements in A are distinct.OutputOutput in a line N integers (each separated by a single space) representing the permutation of N integers B such that diff(A, B) \ge N. As a reminder, all elements in the permutation must be between 1 to N and distinct.ExamplesInput 4 1 3 2 4 Output 4 2 3 1 Input 2 2 1 Output 1 2 NoteExplanation for the sample input/output #1With A = [1, 3, 2, 4] and B = [4, 2, 3, 1], diff(A, B) = |1 - 4| + |3 - 2| + |2 - 3| + |4 - 1| = 3 + 1 + 1 + 3 = 8. Since 8 \ge 4, [4, 2, 3, 1] is one of the valid output for this sample.
4 1 3 2 4
4 2 3 1
1 second
256 megabytes
['*1000']
F. Red-White Fencetime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp wants to build a fence near his house. He has n white boards and k red boards he can use to build it. Each board is characterised by its length, which is an integer.A good fence should consist of exactly one red board and several (possibly zero) white boards. The red board should be the longest one in the fence (every white board used in the fence should be strictly shorter), and the sequence of lengths of boards should be ascending before the red board and descending after it. Formally, if m boards are used, and their lengths are l_1, l_2, ..., l_m in the order they are placed in the fence, from left to right (let's call this array [l_1, l_2, \dots, l_m] the array of lengths), the following conditions should hold: there should be exactly one red board in the fence (let its index be j); for every i \in [1, j - 1] l_i < l_{i + 1}; for every i \in [j, m - 1] l_i > l_{i + 1}. When Polycarp will build his fence, he will place all boards from left to right on the same height of 0, without any gaps, so these boards compose a polygon: Example: a fence with [3, 5, 4, 2, 1] as the array of lengths. The second board is red. The perimeter of the fence is 20. Polycarp is interested in fences of some special perimeters. He has q even integers he really likes (these integers are Q_1, Q_2, ..., Q_q), and for every such integer Q_i, he wants to calculate the number of different fences with perimeter Q_i he can build (two fences are considered different if their arrays of lengths are different). Can you help him calculate these values?InputThe first line contains two integers n and k (1 \le n \le 3 \cdot 10^5, 1 \le k \le 5) — the number of white and red boards Polycarp has.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 3 \cdot 10^5) — the lengths of white boards Polycarp has.The third line contains k integers b_1, b_2, ..., b_k (1 \le b_i \le 3 \cdot 10^5) — the lengths of red boards Polycarp has. All b_i are distinct.The fourth line contains one integer q (1 \le q \le 3 \cdot 10^5) — the number of special integers.The fifth line contains q integers Q_1, Q_2, ..., Q_q (4 \le Q_i \le 12 \cdot 10^5, every Q_i is even) — the special integers Polycarp likes.OutputFor each Q_i, print one integer — the number of good fences with perimeter Q_i Polycarp can build, taken modulo 998244353.ExamplesInput 5 2 3 3 1 1 1 2 4 7 6 8 10 12 14 16 18 Output 1 2 2 4 6 4 1 Input 5 5 1 2 3 4 5 1 2 3 4 5 4 4 8 10 14 Output 1 3 5 20 NotePossible fences in the first example denoted by their arrays of lengths (the length of the red board is highlighted): with perimeter 6: [\textbf{2}]; with perimeter 8: [1, \textbf{2}], [\textbf{2}, 1]; with perimeter 10: [1, \textbf{2}, 1], [\textbf{4}]; with perimeter 12: [1, \textbf{4}], [3, \textbf{4}], [\textbf{4}, 1], [\textbf{4}, 3]; with perimeter 14: [1, \textbf{4}, 1], [1, \textbf{4}, 3], [3, \textbf{4}, 1], [3, \textbf{4}, 3], [1, 3, \textbf{4}], [\textbf{4}, 3, 1]; with perimeter 16: [1, \textbf{4}, 3, 1], [3, \textbf{4}, 3, 1], [1, 3, \textbf{4}, 1], [1, 3, \textbf{4}, 3]; with perimeter 18: [1, 3, \textbf{4}, 3, 1].
5 2 3 3 1 1 1 2 4 7 6 8 10 12 14 16 18
1 2 2 4 6 4 1
5 seconds
512 megabytes
['combinatorics', 'fft', '*2500']
E2. Voting (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}.Calculate the minimum number of coins you have to spend so that everyone votes for you.InputThe first line contains one integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases.The first line of each test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of voters.The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 \le p_i \le 10^9, 0 \le m_i < n).It is guaranteed that the sum of all n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you.ExampleInput 3 3 1 5 2 10 2 8 7 0 1 3 1 1 1 6 1 1 1 4 1 4 1 6 2 6 2 3 2 8 2 7 4 4 5 5 Output 8 0 7 NoteIn the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} \rightarrow {1, 3} \rightarrow {1, 2, 3}.In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} \rightarrow {1, 3, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 5, 6, 7} \rightarrow {1, 2, 3, 4, 5, 6, 7}.In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} \rightarrow {1, 2, 3, 4, 5} \rightarrow {1, 2, 3, 4, 5, 6}.
3 3 1 5 2 10 2 8 7 0 1 3 1 1 1 6 1 1 1 4 1 4 1 6 2 6 2 3 2 8 2 7 4 4 5 5
8 0 7
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', '*2400']
E1. Voting (Easy Version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.Now elections are held in Berland and you want to win them. More precisely, you want everyone to vote for you.There are n voters, and two ways to convince each of them to vote for you. The first way to convince the i-th voter is to pay him p_i coins. The second way is to make m_i other voters vote for you, and the i-th voter will vote for free.Moreover, the process of such voting takes place in several steps. For example, if there are five voters with m_1 = 1, m_2 = 2, m_3 = 2, m_4 = 4, m_5 = 5, then you can buy the vote of the fifth voter, and eventually everyone will vote for you. Set of people voting for you will change as follows: {5} \rightarrow {1, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 4, 5}.Calculate the minimum number of coins you have to spend so that everyone votes for you.InputThe first line contains one integer t (1 \le t \le 5000) — the number of test cases.The first line of each test case contains one integer n (1 \le n \le 5000) — the number of voters.The next n lines contains the description of voters. i-th line contains two integers m_i and p_i (1 \le p_i \le 10^9, 0 \le m_i < n).It is guaranteed that the sum of all n over all test cases does not exceed 5000.OutputFor each test case print one integer — the minimum number of coins you have to spend so that everyone votes for you.ExampleInput 3 3 1 5 2 10 2 8 7 0 1 3 1 1 1 6 1 1 1 4 1 4 1 6 2 6 2 3 2 8 2 7 4 4 5 5 Output 8 0 7 NoteIn the first test case you have to buy vote of the third voter. Then the set of people voting for you will change as follows: {3} \rightarrow {1, 3} \rightarrow {1, 2, 3}.In the second example you don't need to buy votes. The set of people voting for you will change as follows: {1} \rightarrow {1, 3, 5} \rightarrow {1, 2, 3, 5} \rightarrow {1, 2, 3, 5, 6, 7} \rightarrow {1, 2, 3, 4, 5, 6, 7}.In the third test case you have to buy votes of the second and the fifth voters. Then the set of people voting for you will change as follows: {2, 5} \rightarrow {1, 2, 3, 4, 5} \rightarrow {1, 2, 3, 4, 5, 6}.
3 3 1 5 2 10 2 8 7 0 1 3 1 1 1 6 1 1 1 4 1 4 1 6 2 6 2 3 2 8 2 7 4 4 5 5
8 0 7
2 seconds
512 megabytes
['data structures', 'dp', 'greedy', '*2300']
D. Salary Changingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example: the median of the sequence [5, 1, 10, 17, 6] is 6, the median of the sequence [1, 2, 1] is 1. It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + \dots + l_n \le s.Note that you don't have to spend all your s dollars on salaries.You have to answer t test cases.InputThe first line contains one integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases.The first line of each query contains two integers n and s (1 \le n < 2 \cdot 10^5, 1 \le s \le 2 \cdot 10^{14}) — the number of employees and the amount of money you have. The value n is not divisible by 2.The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 \le l_i \le r_i \le 10^9).It is guaranteed that the sum of all n over all queries does not exceed 2 \cdot 10^5.It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. \sum\limits_{i=1}^{n} l_i \le s.OutputFor each test case print one integer — the maximum median salary that you can obtain.ExampleInput 3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7 Output 11 1337 6 NoteIn the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.In the second test case, you have to pay 1337 dollars to the only employee.In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
3 3 26 10 12 1 4 10 11 1 1337 1 1000000000 5 26 4 4 2 4 6 8 5 6 2 7
11 1337 6
3 seconds
256 megabytes
['binary search', 'greedy', 'sortings', '*1900']
C. Minimize The Integertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a huge integer a consisting of n digits (n is between 1 and 3 \cdot 10^5, inclusive). It may contain leading zeros.You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2). For example, if a = 032867235 you can get the following integers in a single operation: 302867235 if you swap the first and the second digits; 023867235 if you swap the second and the third digits; 032876235 if you swap the fifth and the sixth digits; 032862735 if you swap the sixth and the seventh digits; 032867325 if you swap the seventh and the eighth digits. Note, that you can't swap digits on positions 2 and 4 because the positions are not adjacent. Also, you can't swap digits on positions 3 and 4 because the digits have the same parity.You can perform any number (possibly, zero) of such operations.Find the minimum integer you can obtain.Note that the resulting integer also may contain leading zeros.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases in the input.The only line of each test case contains the integer a, its length n is between 1 and 3 \cdot 10^5, inclusive.It is guaranteed that the sum of all values n does not exceed 3 \cdot 10^5.OutputFor each test case print line — the minimum integer you can obtain.ExampleInput 3 0709 1337 246432 Output 0079 1337 234642 NoteIn the first test case, you can perform the following sequence of operations (the pair of swapped digits is highlighted): 0 \underline{\textbf{70}} 9 \rightarrow 0079.In the second test case, the initial integer is optimal. In the third test case you can perform the following sequence of operations: 246 \underline{\textbf{43}} 2 \rightarrow 24 \underline{\textbf{63}}42 \rightarrow 2 \underline{\textbf{43}} 642 \rightarrow 234642.
3 0709 1337 246432
0079 1337 234642
2 seconds
256 megabytes
['greedy', 'two pointers', '*1600']
B. Binary Palindromestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA palindrome is a string t which reads the same backward as forward (formally, t[i] = t[|t| + 1 - i] for all i \in [1, |t|]). Here |t| denotes the length of a string t. For example, the strings 010, 1001 and 0 are palindromes.You have n binary strings s_1, s_2, \dots, s_n (each s_i consists of zeroes and/or ones). You can swap any pair of characters any number of times (possibly, zero). Characters can be either from the same string or from different strings — there are no restrictions.Formally, in one move you: choose four integer numbers x, a, y, b such that 1 \le x, y \le n and 1 \le a \le |s_x| and 1 \le b \le |s_y| (where x and y are string indices and a and b are positions in strings s_x and s_y respectively), swap (exchange) the characters s_x[a] and s_y[b]. What is the maximum number of strings you can make palindromic simultaneously?InputThe first line contains single integer Q (1 \le Q \le 50) — the number of test cases.The first line on each test case contains single integer n (1 \le n \le 50) — the number of binary strings you have.Next n lines contains binary strings s_1, s_2, \dots, s_n — one per line. It's guaranteed that 1 \le |s_i| \le 50 and all strings constist of zeroes and/or ones.OutputPrint Q integers — one per test case. The i-th integer should be the maximum number of palindromic strings you can achieve simultaneously performing zero or more swaps on strings from the i-th test case.ExampleInput 4 1 0 3 1110 100110 010101 2 11111 000001 2 001 11100111 Output 1 2 2 2 NoteIn the first test case, s_1 is palindrome, so the answer is 1.In the second test case you can't make all three strings palindromic at the same time, but you can make any pair of strings palindromic. For example, let's make s_1 = \text{0110}, s_2 = \text{111111} and s_3 = \text{010000}.In the third test case we can make both strings palindromic. For example, s_1 = \text{11011} and s_2 = \text{100001}.In the last test case s_2 is palindrome and you can make s_1 palindrome, for example, by swapping s_1[2] and s_1[3].
4 1 0 3 1110 100110 010101 2 11111 000001 2 001 11100111
1 2 2 2
2 seconds
256 megabytes
['greedy', 'strings', '*1400']
A. Broken Keyboardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string s appeared on the screen. When Polycarp presses a button with character c, one of the following events happened: if the button was working correctly, a character c appeared at the end of the string Polycarp was typing; if the button was malfunctioning, two characters c appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a \rightarrow abb \rightarrow abba \rightarrow abbac \rightarrow abbaca \rightarrow abbacabb \rightarrow abbacabba.You are given a string s which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases in the input.Then the test cases follow. Each test case is represented by one line containing a string s consisting of no less than 1 and no more than 500 lowercase Latin letters.OutputFor each test case, print one line containing a string res. The string res should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, res should be empty.ExampleInput 4 a zzaaz ccff cbddbb Output a z bc
4 a zzaaz ccff cbddbb
a z bc
1 second
256 megabytes
['brute force', 'strings', 'two pointers', '*1000']
N. Wirestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarpus has a complex electronic device. The core of this device is a circuit board. The board has 10^9 contact points which are numbered from 1 to 10^9. Also there are n wires numbered from 1 to n, each connecting two distinct contact points on the board. An electric signal can pass between wires A and B if: either both wires share the same contact point; or there is a sequence of wires starting with A and ending with B, and each pair of adjacent wires in the sequence share a contact point. The picture shows a circuit board with 5 wires. Contact points with numbers 2, 5, 7, 8, 10, 13 are used. Here an electrical signal can pass from wire 2 to wire 3, but not to wire 1. Currently the circuit board is broken. Polycarpus thinks that the board could be fixed if the wires were re-soldered so that a signal could pass between any pair of wires.It takes 1 minute for Polycarpus to re-solder an end of a wire. I.e. it takes one minute to change one of the two contact points for a wire. Any contact point from range [1, 10^9] can be used as a new contact point. A wire's ends must always be soldered to distinct contact points. Both wire's ends can be re-solded, but that will require two actions and will take 2 minutes in total.Find the minimum amount of time Polycarpus needs to re-solder wires so that a signal can pass between any pair of wires. Also output an optimal sequence of wire re-soldering.InputThe input contains one or several test cases. The first input line contains a single integer t — number of test cases. Then, t test cases follow.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the number of wires. The following n lines describe wires, each line containing two space-separated integers x_i, y_i (1 \le x_i, y_i \le 10^9, x_i \neq y_i) — contact points connected by the i-th wire. A couple of contact points can be connected with more than one wire.Sum of values of n across all test cases does not exceed 10^5.OutputFor each test case first print one line with a single integer k — the minimum number of minutes needed to re-solder wires so that a signal can pass between any pair of wires. In the following k lines print the description of re-solderings. Each re-soldering should be described by three integers w_j, a_j, b_j (1 \le w_j \le n, 1 \le a_j, b_j \le 10^9). Such triple means that during the j-th re-soldering an end of the w_j-th wire, which was soldered to contact point a_j, becomes soldered to contact point b_j instead. After each re-soldering of a wire it must connect two distinct contact points. If there are multiple optimal re-solderings, print any of them.ExampleInput 2 1 4 7 4 1 2 2 3 4 5 5 6 Output 0 1 2 3 5
2 1 4 7 4 1 2 2 3 4 5 5 6
0 1 2 3 5
3 seconds
512 megabytes
['dfs and similar', 'graphs', 'greedy', '*2000']
M. SmartGardentime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland Gardeners United Inc. hired you for the project called "SmartGarden". The main feature of this project is automatic garden watering.Formally the garden can be represented as a square of n \times n cells with rows numbered 1 to n from top to bottom and columns numbered 1 to n from left to right. Each cell of the garden contains either a plant or a slab. It's known that slabs are located on the main diagonal of the matrix representing the garden, and in the cells that are below the main diagonal and share a side with at least one cell of the main diagonal. All the remaining cells of the garden are filled with plants. Example of the garden for n=5. During implementation of the project you created a smart robot that takes a list of commands as an input, which are processed one by one. Each command contains: a list of horizontal lines (rows in the matrix representing the garden); a list of vertical lines (columns in the matrix representing the garden). While executing each command robot waters only cells in the intersection of specified rows and specified columns. So, if you specify r rows and c columns, then exactly r \cdot c cells will be watered.In the demo for the customer you have tuned robot in such a way that it waters all the garden. To do that you prepared a single command containing all n rows and all n columns.Unfortunately, 5 hours before the demo for your customer it turned out that the CEO of Berland Gardeners United Inc. was going to take part in it. Moreover, most probably he will be standing on a garden slab during the demo!Now you need to create a list of commands for the robot so that it waters all the plants and doesn't water any cell containing a slab. Since it's only a beta version of "SmartGarden", the total number of commands shouldn't exceed 50.Create a program that, for a given size of the garden, will find a list of no more than 50 commands that allow the robot to water all the plants in the garden without watering the slabs. It is allowed to water a plant several times.InputThe first and the only line of the input contains a single integer n (2 \le n \le 5000), where n is the size of the garden.OutputIn the first line print the total number of commands for the robot k (1 \le k \le 50). In the next 2 \cdot k lines print all the commands. Each command should be specified by 2 lines. The first line of each command should describe rows in the command and the second line should describe columns in the command. Each of these 2 lines should have the following format: the first number of the line should specify the total number of items x in the appropriate list; then x distinct numbers follow, where each number is in the range 1 \dots n and describes a chosen row for the first line and a chosen column for the second line. If there are multiple ways to water the garden, print any of them.ExamplesInput 2Output 2 1 1 1 2 1 1 1 2 Input 4Output 4 2 1 4 1 2 2 1 2 2 3 4 1 3 2 1 4 1 4 1 1
2
2 1 1 1 2 1 1 1 2
2 seconds
512 megabytes
['constructive algorithms', 'divide and conquer', '*2500']
L. Divide The Studentstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA group of students has recently been admitted to the Faculty of Computer Sciences at the Berland State University. Now the programming teacher wants to divide them into three subgroups for practice sessions.The teacher knows that a lot of programmers argue which language is the best. The teacher doesn't want to hear any arguments in the subgroups, so she wants to divide the students into three subgroups so that no pair of students belonging to the same subgroup want to argue.To perform this division, the teacher asked each student which programming language he likes. There are a students who answered that they enjoy Assembler, b students stated that their favourite language is Basic, and c remaining students claimed that C++ is the best programming language — and there was a large argument between Assembler fans and C++ fans.Now, knowing that Assembler programmers and C++ programmers can start an argument every minute, the teacher wants to divide the students into three subgroups so that every student belongs to exactly one subgroup, and there is no subgroup that contains at least one Assembler fan and at least one C++ fan. Since teaching a lot of students can be difficult, the teacher wants the size of the largest subgroup to be minimum possible.Please help the teacher to calculate the minimum possible size of the largest subgroup!InputThe first line contains one integer t (1 \le t \le 5) — the number of test cases in the input. Then test cases follow.Each test case consists of one line containing three integers a, b and c (1 \le a, b, c \le 1000) — the number of Assembler fans, Basic fans and C++ fans, respectively.OutputFor each test case print one integer — the minimum size of the largest subgroup if the students are divided in such a way that there is no subgroup that contains at least one Assembler fan and at least one C++ fan simultaneously.ExamplesInput 5 3 5 7 4 8 4 13 10 13 1000 1000 1000 13 22 7 Output 5 6 13 1000 14 Input 5 1 3 4 1000 1000 1 4 1 2 325 226 999 939 861 505 Output 3 667 3 517 769 NoteExplanation of the answers for the example 1: The first subgroup contains 3 Assembler fans and 2 Basic fans, the second subgroup — 5 C++ fans, the third subgroup — 2 C++ fans and 3 Basic fans. The first subgroup contains 4 Assembler fans, the second subgroup — 6 Basic fans, the third subgroup — 2 Basic fans and 4 C++ fans. The first subgroup contains all Assembler fans, the second subgroup — all Basic fans, the third subgroup — all C++ fans. The first subgroup contains all Assembler fans, the second subgroup — all Basic fans, the third subgroup — all C++ fans. The first subgroup contains 12 Assembler fans and 2 Basic fans, the second subgroup — 1 Assembler fan and 13 Basic fans, the third subgroup — 7 Basic fans and 7 C++ fans.
5 3 5 7 4 8 4 13 10 13 1000 1000 1000 13 22 7
5 6 13 1000 14
2 seconds
512 megabytes
['binary search', 'greedy', 'math', '*1500']
K. Projectorstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n lectures and m seminars to be conducted today at the Faculty of Approximate Sciences. The i-th lecture starts at a_i and ends at b_i (formally, time of the lecture spans an interval [a_i, b_i), the right bound is exclusive). The j-th seminar starts at p_j and ends at q_j (similarly, time of the seminar spans an interval [p_j, q_j), the right bound is exclusive).There are x HD-projectors numbered from 1 to x and y ordinary projectors numbered from x + 1 to x + y available at the faculty. Projectors should be distributed in such a way that: an HD-projector is used in each lecture; some projector (ordinary or HD) is used in each seminar; a projector (ordinary or HD) can only be used in one event at the same moment of time; if a projector is selected for an event, it is used there for the whole duration of the event; a projector can be reused in some following event, if it starts not earlier than current event finishes. You are to find such distribution of projectors, if it exists.Again, note that the right bound of the event's time range is not inclusive: if some event starts exactly when another event finishes, the projector can be reused (suppose that it is instantly transported to the location of the event).InputThe first line contains an integer t (1 \le t \le 300) — the number of test cases.Each test case starts with a line containing four integers n, m, x, y (0 \le n, m, x, y \le 300; n+m>0, x + y > 0) — the number of lectures, the number of seminars, the number of HD projectors and the number of ordinary projectors, respectively. The next n lines describe lectures. Each line contains two integers a_i, b_i (1 \le a_i < b_i \le 10^6) — the start time (inclusive) and finish time (exclusive) of the i-th lecture. The next m lines describe seminars. Each line contains two integers p_j, q_j (1 \le p_j < q_j \le 10^6) — the start time (inclusive) and finish time (exclusive) of the j-th seminar.OutputFor each test case, print YES if it is possible to distribute projectors in order to meet all requirements, or NO otherwise. In case of positive answer, output one additional line containing n + m integers. The first n integers should be not less than 1 and not greater than x, and the i-th of them should be the index of HD projector used in the i-th lecture. The last m integers should be not less than 1 and not greater than x + y, and the j-th of them should be the index of projector used in the j-th seminar. If there are multiple answers, print any of them.ExamplesInput 2 2 2 2 2 1 5 2 5 1 5 1 4 2 0 2 10 1 3 1 3 Output YES 2 1 4 3 YES 2 1 Input 3 1 2 1 1 3 4 2 4 1 3 3 4 2 3 5 7 1 3 1 7 4 8 2 5 1 6 2 8 0 1 1 0 1 1000000 Output YES 1 2 1 NO YES 1
2 2 2 2 2 1 5 2 5 1 5 1 4 2 0 2 10 1 3 1 3
YES 2 1 4 3 YES 2 1
3 seconds
512 megabytes
['flows', 'graphs', '*3100']
J. The Paradetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Berland Army is preparing for a large military parade. It is already decided that the soldiers participating in it will be divided into k rows, and all rows will contain the same number of soldiers.Of course, not every arrangement of soldiers into k rows is suitable. Heights of all soldiers in the same row should not differ by more than 1. The height of each soldier is an integer between 1 and n.For each possible height, you know the number of soldiers having this height. To conduct a parade, you have to choose the soldiers participating in it, and then arrange all of the chosen soldiers into k rows so that both of the following conditions are met: each row has the same number of soldiers, no row contains a pair of soldiers such that their heights differ by 2 or more. Calculate the maximum number of soldiers who can participate in the parade.InputThe first line contains one integer t (1 \le t \le 10000) — the number of test cases. Then the test cases follow. Each test case begins with a line containing two integers n and k (1 \le n \le 30000, 1 \le k \le 10^{12}) — the number of different heights of soldiers and the number of rows of soldiers in the parade, respectively.The second (and final) line of each test case contains n integers c_1, c_2, ..., c_n (0 \le c_i \le 10^{12}), where c_i is the number of soldiers having height i in the Berland Army.It is guaranteed that the sum of n over all test cases does not exceed 30000.OutputFor each test case, print one integer — the maximum number of soldiers that can participate in the parade.ExampleInput 5 3 4 7 1 13 1 1 100 1 3 100 2 1 1000000000000 1000000000000 4 1 10 2 11 1 Output 16 100 99 2000000000000 13 NoteExplanations for the example test cases: the heights of soldiers in the rows can be: [3, 3, 3, 3], [1, 2, 1, 1], [1, 1, 1, 1], [3, 3, 3, 3] (each list represents a row); all soldiers can march in the same row; 33 soldiers with height 1 in each of 3 rows; all soldiers can march in the same row; all soldiers with height 2 and 3 can march in the same row.
5 3 4 7 1 13 1 1 100 1 3 100 2 1 1000000000000 1000000000000 4 1 10 2 11 1
16 100 99 2000000000000 13
2 seconds
512 megabytes
['binary search', 'greedy', '*1800']
I. Show Must Go Ontime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe director of the famous dance show plans a tour. It is already decided that the tour will consist of up to m concerts.There are n dancers in the troupe. Each dancer is characterized by her awkwardness: the awkwardness of the i-th dancer is equal to a_i.The director likes diversity. For this reason, each concert will be performed by a different set of dancers. A dancer may perform in multiple concerts. For example, it is possible that a set of dancers performs in one concert and a subset of this set of dancers performs in another concert. The only constraint is that the same set of dancers cannot perform twice.The director prefers the set with larger number of dancers over the set with smaller number of dancers. If two sets consist of the same number of dancers, then the director prefers the one which has smaller sum of awkwardness of dancers. If two sets of dancers are equal in size and total awkwardness, then the director does not have a preference which one is better.A marketing study shows that viewers are not ready to come to a concert if the total awkwardness of all the dancers performing in the concert is greater than k.The director wants to find the best plan for m concerts. He thinks to write down all possible sets of dancers; then get rid of the sets with total awkwardness greater than k. The remaining sets of dancers will be sorted according to his preference. The most preferred set of dancers will give the first concert, the second preferred set — the second concert and so on until the m-th concert. If it turns out that the total number of valid sets is less than m, then the total number of concerts will be equal to the number of valid sets.It turns out that the director delegated finding the plan to you! Please, notice that there might be several acceptable plans due to the fact that the director does not have a preference over sets of dancers with the same size and total awkwardness. In this case any of these plans is good enough. For each concert find the number of dancers and the total awkwardness of the set performing. Also, for the last concert find its set of dancers.InputThe first line contains one integer t (1 \le t \le 10^5) — the number of test cases in the input. Then the test cases follow.Each test case begins with a line containing three integers n, k and m (1 \le n \le 10^6, 1 \le k \le 10^{18}, 1 \le m \le 10^6) — the total number of dancers, the maximum acceptable awkwardness of a set of dancers and the maximum number of concerts, respectively.The following line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{12}), where a_i is the awkwardness of the i-th dancer.The sum of the values of n over all test cases in the input does not exceed 10^6. Similarly, the sum of the values of m over all test cases in the input does not exceed 10^6.OutputPrint the answers to all test cases in the input.If the troupe cannot give concerts at all, then simply print one line "0". In this case, you should not print anything else.If the troupe gives a positive number of concerts r (r is equal to the minimum of m and the total number of valid sets), then first print the value of r, then r lines: the j-th line should contain two integers s_j and t_j — the number of dancers in the j-th concert and the total awkwardness of the dancers performing in the j-th concert. Complete the output to a test case with a line that describes the last set: print exactly s_r distinct integers from 1 to n — the numbers of the dancers who will perform at the r-th (last) concert, in any order. If there are several answers, print any of them.ExampleInput 3 7 13 10 3 1 5 1 8 2 13 2 10 1 12 12 3 32 100000 2 1 5 Output 10 5 12 4 7 4 9 4 10 4 11 4 11 4 12 4 13 3 4 3 5 2 4 1 0 7 3 8 2 3 2 6 2 7 1 1 1 2 1 5 3
3 7 13 10 3 1 5 1 8 2 13 2 10 1 12 12 3 32 100000 2 1 5
10 5 12 4 7 4 9 4 10 4 11 4 11 4 12 4 13 3 4 3 5 2 4 1 0 7 3 8 2 3 2 6 2 7 1 1 1 2 1 5 3
5 seconds
512 megabytes
['binary search', 'brute force', 'greedy', 'shortest paths', '*3100']
H. Happy Birthdaytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a set of birthday cake candles. Each of such candles represents a digit between 0 and 9, inclusive. Example of birthday cake candles. Let's denote the candle representing the digit d as d-candle.Your set contains c_0 instances of 0-candles, c_1 instances of 1-candles and so on. So, the total number of candles is c_0+c_1+\dots+c_9.These digits are needed to wish your cat a happy birthday. For each birthday, starting with the first, you want to compose the age of the cat using the digits from the set.Since you light candles for a very short time, candles don't have time to burn out. For this reason you can reuse candles an arbitrary number of times (therefore your set of candles never changes).For example, if you have one instance of each digit (i.e. c_0=c_1=\dots=c_9=1), you can compose any number from 1 to 10 using this set, but you cannot compose 11.You have to determine the first birthday, on which you cannot compose the age of the cat using the candles from your set. In other words, find the minimum number y such that all numbers from 1 to y-1 can be composed by digits from your set, but y cannot be composed.InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases in the input.The only line of each test case contains ten integer numbers c_0, c_1, \dots, c_9 (0 \le c_i \le 10^5) — the number of 0-candles, 1-candles, 2-candles and so on.It is guaranteed that the sum of all c_i in the input does not exceed 10^6.OutputFor each test case, output one integer in single line — the minimum age which cannot be composed by candles from your set. Please note that the age can be quite large (it may exceed the standard 64-bit integer types in your programming language).ExampleInput 4 1 1 1 1 1 1 1 1 1 1 0 0 1 1 2 2 3 3 4 4 1 2 1 2 1 3 1 0 0 0 0 1 2 1 4 3 1 1 2 1 Output 11 1 7 10
4 1 1 1 1 1 1 1 1 1 1 0 0 1 1 2 2 3 3 4 4 1 2 1 2 1 3 1 0 0 0 0 1 2 1 4 3 1 1 2 1
11 1 7 10
2 seconds
512 megabytes
['math', '*1500']
G. Discarding Gametime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEulampius has created a game with the following rules: there are two players in the game: a human and a computer; the game lasts for no more than n rounds. Initially both players have 0 points. In the j-th round the human gains a_j points, and the computer gains b_j points. The points are gained simultaneously; the game ends when one of the players gets k or more points. This player loses the game. If both players get k or more points simultaneously, both lose; if both players have less than k points after n rounds, the game ends in a tie; after each round the human can push the "Reset" button. If the human had x points, and the computer had y points before the button is pushed (of course, x < k and y < k), then after the button is pushed the human will have x' = max(0, \, x - y) points, and the computer will have y' = max(0, \, y - x) points. E. g. the push of "Reset" button transforms the state (x=3, \, y=5) into the state (x'=0, \, y'=2), and the state (x=8, \, y=2) into the state (x'=6, \, y'=0).Eulampius asked his friend Polycarpus to test the game. Polycarpus has quickly revealed that amounts of points gained by the human and the computer in each of n rounds are generated before the game and stored in a file. In other words, the pushes of the "Reset" button do not influence the values a_j and b_j, so sequences a and b are fixed and known in advance.Polycarpus wants to make a plan for the game. He would like to win the game pushing the "Reset" button as few times as possible. Your task is to determine this minimal number of pushes or determine that Polycarpus cannot win.InputThe first line of the input contains one integer t (1 \le t \le 10000) — the number of test cases. Then the test cases follow.The first line of each test case contains two integers n and k (1 \le n \le 2 \cdot 10^5, 2 \le k \le 10^9) — the maximum possible number of rounds in the game and the number of points, after reaching which a player loses, respectively.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_j < k), where a_j is the amount of points the human gains in the j-th round.The third line of each test case contains n integers b_1, b_2, \dots, b_n (1 \le b_j < k), where b_j is the amount of points the computer gains in the j-th round.The sum of n over all test cases in the input does not exceed 2 \cdot 10^5.OutputPrint the answers for all test cases in the order they appear in the input.If Polycarpus cannot win the game, then simply print one line "-1" (without quotes). In this case, you should not output anything else for that test case. Otherwise, the first line of the test case answer should contain one integer d — the minimum possible number of "Reset" button pushes, required to win the game. The next line should contain d distinct integers r_1, r_2, \dots, r_d (1 \le r_i < n) — the numbers of rounds, at the end of which Polycarpus has to press the "Reset" button, in arbitrary order. If d=0 then either leave the second line of the test case answer empty, or do not print the second line at all.If there are several possible solutions, print any of them.ExampleInput 3 4 17 1 3 5 7 3 5 7 9 11 17 5 2 8 2 4 6 1 2 7 2 5 4 6 3 3 5 1 7 4 2 5 3 6 17 6 1 2 7 2 5 1 7 4 2 5 3 Output 0 2 2 4 -1NoteIn the second test case, if the human pushes the "Reset" button after the second and the fourth rounds, the game goes as follows: after the first round the human has 5 points, the computer — 4 points; after the second round the human has 7 points, the computer — 10 points; the human pushes the "Reset" button and now he has 0 points and the computer — 3 points; after the third round the human has 8 points, the computer — 6 points; after the fourth round the human has 10 points, the computer — 9 points; the human pushes "Reset" button again, after it he has 1 point, the computer — 0 points; after the fifth round the human has 5 points, the computer — 5 points; after the sixth round the human has 11 points, the computer — 6 points; after the seventh round the human has 12 points, the computer — 13 points; after the eighth round the human has 14 points, the computer — 17 points; the human wins, as the computer has k or more points and the human — strictly less than k points.
3 4 17 1 3 5 7 3 5 7 9 11 17 5 2 8 2 4 6 1 2 7 2 5 4 6 3 3 5 1 7 4 2 5 3 6 17 6 1 2 7 2 5 1 7 4 2 5 3
0 2 2 4 -1
3 seconds
512 megabytes
['dp', 'greedy', 'two pointers', '*2300']
F. Data Centertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are developing a project to build a new data center. The data center will be a rectangle with an area of exactly n square meters. Each side of the data center must be an integer.Your goal is to minimize the impact of the external environment on the data center. For this reason, you want to minimize the length of the perimeter of the data center (that is, the sum of the lengths of its four sides).What is the minimum perimeter of a rectangular data center with an area of exactly n square meters, if the lengths of all its sides must be integers?InputThe first and only line of the input contains an integer n (1 \le n \le 10^5), where n is the area of the data center in square meters.OutputPrint the required minimum perimeter in meters.ExamplesInput 36 Output 24 Input 13 Output 28 Input 1 Output 4 NoteIn the first example, the required shape of the data center is 6\times6 square. Its area is 36 and the perimeter is 6+6+6+6=24.In the second example, the required shape of the data center is 1\times13 rectangle. Its area is 13 and the perimeter is 1+13+1+13=28.In the third example, the required shape of the data center is 1\times1 square. Its area is 1 and the perimeter is 1+1+1+1=4.
36
24
2 seconds
256 megabytes
['brute force', 'implementation', '*800']
E. The Coronationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe coronation of King Berl XXII is soon! The whole royal family, including n daughters of Berl XXII, will be present.The King has ordered his jeweler to assemble n beautiful necklaces, so each of the princesses could wear exactly one necklace during the ceremony — and now these necklaces are finished. Each necklace consists of m gems attached to a gold chain. There are two types of gems used in the necklaces — emeralds and sapphires. So, each necklace can be represented by a sequence of m gems (listed from left to right), and each gem is either an emerald or a sapphire. Formally, the i-th necklace can be represented by a binary string s_i of length m; if the j-th character of s_i is 0, then the j-th gem in the i-th necklace is an emerald; otherwise, this gem is a sapphire.Now, looking at the necklaces, the King is afraid that some of his daughters may envy the other daughters' necklaces. He wants all necklaces to look similar. Two necklaces are considered similar if there are at least k positions where these necklaces contain the same type of gems.For example, if there is a necklace represented by a sequence 01010111 and a necklace represented by a sequence 01100000, then there are 3 positions where these necklaces contain the same type of gems (both first gems are emeralds, both second gems are sapphires, and both fifth gems are emeralds). So if k = 3, these necklaces are similar, and if k = 4, they are not similar.The King thinks that if two of his daughters notice that their necklaces are not similar, then they may have a conflict — and, obviously, he doesn't want any conflicts during the coronation! So Berl XXII wants to tell some of his daughters to wear their necklaces backward. If a necklace is worn backward, then the sequence of gems in this necklace is reversed. For example, if a necklace is represented by a sequence 01100, then, if worn backward, it would be represented by a sequence 00110. The King wants to find the minimum number of necklaces to be worn backward during the coronation so that there are no conflicts.Berl XXII is too busy with preparation for the coronation, so he ordered you to resolve this issue for him. Help him — and he will give you a truly royal reward! InputThe first line contains one integer t (1 \le t \le 50) — the number of test cases. Then the test cases follow.Each test case begins with a line containing three integers n, m and k (2 \le n \le 50, 1 \le k \le m \le 50) — the number of necklaces, the number of gems in each necklace, and the minimum number of positions where two necklaces have to have the same type of gems in order to look similar, respectively.Then n lines follow, the i-th of them contains a binary string s_i of length m representing the i-th necklace.OutputFor each test case, print the answer as follows.If it is impossible to avoid the conflict, print -1 on a single line. In this case you should not output anything else for that test case.Otherwise, the first line of the test case answer should contain the single integer d — the minimum number of necklaces that are to be worn backward. The second line of the test case answer should contain the numbers of these necklaces (integers from 1 to n) in any order. If d = 0 then leave the second line of the test case answer empty. If there are multiple answers, you may print any of them.ExampleInput 5 5 7 2 1010100 0010101 1111010 1000010 0000101 6 9 3 011111110 100111000 111100000 000111111 110100111 111110111 3 4 2 0001 1000 0000 3 4 4 0001 1000 0000 2 4 3 0001 1000 Output 2 1 3 1 3 0 -1 1 1
5 5 7 2 1010100 0010101 1111010 1000010 0000101 6 9 3 011111110 100111000 111100000 000111111 110100111 111110111 3 4 2 0001 1000 0000 3 4 4 0001 1000 0000 2 4 3 0001 1000
2 1 3 1 3 0 -1 1 1
2 seconds
512 megabytes
['graphs', 'implementation', '*2300']
D. Conference Problemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA large-scale conference on unnatural sciences is going to be held soon in Berland! In total, n scientists from all around the world have applied. All of them have indicated a time segment when they will attend the conference: two integers l_i, r_i — day of arrival and day of departure.Also, some of the scientists have indicated their country, while some preferred not to. So, each scientist also has a value c_i, where: c_i > 0, if the scientist is coming from country c_i (all countries are numbered from 1 to 200); c_i = 0, if the scientist preferred to not indicate the country. Everyone knows that it is interesting and useful to chat with representatives of other countries! A participant of the conference will be upset if she will not meet people from other countries during the stay. It is possible to meet people during all time of stay, including the day of arrival and the day of departure.Conference organizers need to be ready for the worst! They are interested in the largest number x, that it is possible that among all people attending the conference exactly x will be upset.Help the organizers to find the maximum number of upset scientists.InputThe first line of the input contains integer t (1 \le t \le 100) — number of test cases. Then the test cases follow.The first line of each test case contains integer n (1 \le n \le 500) — the number of registered conference participants.Next n lines follow, each containing three integers l_i, r_i, c_i (1 \le l_i \le r_i \le 10^6, 0 \le c_i \le 200) — the day of arrival, the day of departure and the country (or the fact that it was not indicated) for the i-th participant.The sum of n among all test cases in the input does not exceed 500.OutputOutput t integers — maximum number of upset scientists for each test case.ExampleInput 2 4 1 10 30 5 6 30 6 12 0 1 1 0 4 1 2 1 2 3 0 3 4 0 4 5 2 Output 4 2
2 4 1 10 30 5 6 30 6 12 0 1 1 0 4 1 2 1 2 3 0 3 4 0 4 5 2
4 2
2 seconds
512 megabytes
['dp', '*3000']
C. Trip to Saint Petersburgtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are planning your trip to Saint Petersburg. After doing some calculations, you estimated that you will have to spend k rubles each day you stay in Saint Petersburg — you have to rent a flat, to eat at some local cafe, et cetera. So, if the day of your arrival is L, and the day of your departure is R, you will have to spend k(R - L + 1) rubles in Saint Petersburg.You don't want to spend a lot of money on your trip, so you decided to work in Saint Petersburg during your trip. There are n available projects numbered from 1 to n, the i-th of them lasts from the day l_i to the day r_i inclusive. If you choose to participate in the i-th project, then you have to stay and work in Saint Petersburg for the entire time this project lasts, but you get paid p_i rubles for completing it.Now you want to come up with an optimal trip plan: you have to choose the day of arrival L, the day of departure R and the set of projects S to participate in so that all the following conditions are met: your trip lasts at least one day (formally, R \ge L); you stay in Saint Petersburg for the duration of every project you have chosen (formally, for each s \in S L \le l_s and R \ge r_s); your total profit is strictly positive and maximum possible (formally, you have to maximize the value of \sum \limits_{s \in S} p_s - k(R - L + 1), and this value should be positive). You may assume that no matter how many projects you choose, you will still have time and ability to participate in all of them, even if they overlap.InputThe first line contains two integers n and k (1 \le n \le 2\cdot10^5, 1 \le k \le 10^{12}) — the number of projects and the amount of money you have to spend during each day in Saint Petersburg, respectively.Then n lines follow, each containing three integers l_i, r_i, p_i (1 \le l_i \le r_i \le 2\cdot10^5, 1 \le p_i \le 10^{12}) — the starting day of the i-th project, the ending day of the i-th project, and the amount of money you get paid if you choose to participate in it, respectively.OutputIf it is impossible to plan a trip with strictly positive profit, print the only integer 0.Otherwise, print two lines. The first line should contain four integers p, L, R and m — the maximum profit you can get, the starting day of your trip, the ending day of your trip and the number of projects you choose to complete, respectively. The second line should contain m distinct integers s_1, s_2, ..., s_{m} — the projects you choose to complete, listed in arbitrary order. If there are multiple answers with maximum profit, print any of them.ExamplesInput 4 5 1 1 3 3 3 11 5 5 17 7 7 4 Output 13 3 5 2 3 2 Input 1 3 1 2 5 Output 0 Input 4 8 1 5 16 2 4 9 3 3 24 1 5 13 Output 22 1 5 4 3 2 1 4
4 5 1 1 3 3 3 11 5 5 17 7 7 4
13 3 5 2 3 2
3 seconds
512 megabytes
['data structures', '*2100']
B. The Feast and the Bustime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEmployees of JebTrains are on their way to celebrate the 256-th day of the year! There are n employees and k teams in JebTrains. Each employee is a member of some (exactly one) team. All teams are numbered from 1 to k. You are given an array of numbers t_1, t_2, \dots, t_n where t_i is the i-th employee's team number.JebTrains is going to rent a single bus to get employees to the feast. The bus will take one or more rides. A bus can pick up an entire team or two entire teams. If three or more teams take a ride together they may start a new project which is considered unacceptable. It's prohibited to split a team, so all members of a team should take the same ride.It is possible to rent a bus of any capacity s. Such a bus can take up to s people on a single ride. The total cost of the rent is equal to s \cdot r burles where r is the number of rides. Note that it's impossible to rent two or more buses.Help JebTrains to calculate the minimum cost of the rent, required to get all employees to the feast, fulfilling all the conditions above.InputThe first line contains two integers n and k (1 \le n \le 5\cdot10^5, 1 \le k \le 8000) — the number of employees and the number of teams in JebTrains. The second line contains a sequence of integers t_1, t_2, \dots, t_n, where t_i (1 \le t_i \le k) is the i-th employee's team number. Every team contains at least one employee.OutputPrint the minimum cost of the rent.ExamplesInput 6 3 3 1 2 3 2 3 Output 6 Input 10 1 1 1 1 1 1 1 1 1 1 1 Output 10 Input 12 4 1 2 3 1 2 3 4 1 2 1 2 1 Output 12
6 3 3 1 2 3 2 3
6
2 seconds
512 megabytes
['brute force', 'constructive algorithms', 'greedy', 'math', '*1800']
A. Berstagramtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp recently signed up to a new social network Berstagram. He immediately published n posts there. He assigned numbers from 1 to n to all posts and published them one by one. So, just after publishing Polycarp's news feed contained posts from 1 to n — the highest post had number 1, the next one had number 2, ..., the lowest post had number n.After that he wrote down all likes from his friends. Likes were coming consecutively from the 1-st one till the m-th one. You are given a sequence a_1, a_2, \dots, a_m (1 \le a_j \le n), where a_j is the post that received the j-th like.News feed in Berstagram works in the following manner. Let's assume the j-th like was given to post a_j. If this post is not the highest (first) one then it changes its position with the one above. If a_j is the highest post nothing changes. For example, if n=3, m=5 and a=[3,2,1,3,3], then Polycarp's news feed had the following states: before the first like: [1, 2, 3]; after the first like: [1, 3, 2]; after the second like: [1, 2, 3]; after the third like: [1, 2, 3]; after the fourth like: [1, 3, 2]; after the fifth like: [3, 1, 2]. Polycarp wants to know the highest (minimum) and the lowest (maximum) positions for each post. Polycarp considers all moments of time, including the moment "before all likes".InputThe first line contains two integer numbers n and m (1 \le n \le 10^5, 1 \le m \le 4 \cdot10^5) — number of posts and number of likes. The second line contains integers a_1, a_2, \dots, a_m (1 \le a_j \le n), where a_j is the post that received the j-th like.OutputPrint n pairs of integer numbers. The i-th line should contain the highest (minimum) and the lowest (maximum) positions of the i-th post. You should take into account positions at all moments of time: before all likes, after each like and after all likes. Positions are numbered from 1 (highest) to n (lowest).ExamplesInput 3 5 3 2 1 3 3 Output 1 2 2 3 1 3 Input 10 6 7 3 5 7 3 6 Output 1 2 2 3 1 3 4 7 4 5 6 7 5 7 8 8 9 9 10 10
3 5 3 2 1 3 3
1 2 2 3 1 3
3 seconds
512 megabytes
['implementation', '*1400']
F. Maximum Weight Subsettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree, which consists of n vertices. Recall that a tree is a connected undirected graph without cycles. Example of a tree. Vertices are numbered from 1 to n. All vertices have weights, the weight of the vertex v is a_v.Recall that the distance between two vertices in the tree is the number of edges on a simple path between them.Your task is to find the subset of vertices with the maximum total weight (the weight of the subset is the sum of weights of all vertices in it) such that there is no pair of vertices with the distance k or less between them in this subset.InputThe first line of the input contains two integers n and k (1 \le n, k \le 200) — the number of vertices in the tree and the distance restriction, respectively.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^5), where a_i is the weight of the vertex i.The next n - 1 lines contain edges of the tree. Edge i is denoted by two integers u_i and v_i — the labels of vertices it connects (1 \le u_i, v_i \le n, u_i \ne v_i).It is guaranteed that the given edges form a tree.OutputPrint one integer — the maximum total weight of the subset in which all pairs of vertices have distance more than k.ExamplesInput 5 1 1 2 3 4 5 1 2 2 3 3 4 3 5 Output 11 Input 7 2 2 1 2 1 2 1 1 6 4 1 5 3 1 2 3 7 5 7 4 Output 4
5 1 1 2 3 4 5 1 2 2 3 3 4 3 5
11
2 seconds
256 megabytes
['dp', 'trees', '*2200']
E. By Elevator or Stairs?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are planning to buy an apartment in a n-floor building. The floors are numbered from 1 to n from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor.Let: a_i for all i from 1 to n-1 be the time required to go from the i-th floor to the (i+1)-th one (and from the (i+1)-th to the i-th as well) using the stairs; b_i for all i from 1 to n-1 be the time required to go from the i-th floor to the (i+1)-th one (and from the (i+1)-th to the i-th as well) using the elevator, also there is a value c — time overhead for elevator usage (you need to wait for it, the elevator doors are too slow!). In one move, you can go from the floor you are staying at x to any floor y (x \ne y) in two different ways: If you are using the stairs, just sum up the corresponding values of a_i. Formally, it will take \sum\limits_{i=min(x, y)}^{max(x, y) - 1} a_i time units. If you are using the elevator, just sum up c and the corresponding values of b_i. Formally, it will take c + \sum\limits_{i=min(x, y)}^{max(x, y) - 1} b_i time units. You can perform as many moves as you want (possibly zero).So your task is for each i to determine the minimum total time it takes to reach the i-th floor from the 1-st (bottom) floor.InputThe first line of the input contains two integers n and c (2 \le n \le 2 \cdot 10^5, 1 \le c \le 1000) — the number of floors in the building and the time overhead for the elevator rides.The second line of the input contains n - 1 integers a_1, a_2, \dots, a_{n-1} (1 \le a_i \le 1000), where a_i is the time required to go from the i-th floor to the (i+1)-th one (and from the (i+1)-th to the i-th as well) using the stairs.The third line of the input contains n - 1 integers b_1, b_2, \dots, b_{n-1} (1 \le b_i \le 1000), where b_i is the time required to go from the i-th floor to the (i+1)-th one (and from the (i+1)-th to the i-th as well) using the elevator.OutputPrint n integers t_1, t_2, \dots, t_n, where t_i is the minimum total time to reach the i-th floor from the first floor if you can perform as many moves as you want.ExamplesInput 10 2 7 6 18 6 16 18 1 17 17 6 9 3 10 9 1 10 1 5 Output 0 7 13 18 24 35 36 37 40 45 Input 10 1 3 2 3 1 3 3 1 4 1 1 2 3 4 4 1 2 1 3 Output 0 2 4 7 8 11 13 14 16 17
10 2 7 6 18 6 16 18 1 17 17 6 9 3 10 9 1 10 1 5
0 7 13 18 24 35 36 37 40 45
2 seconds
256 megabytes
['dp', 'shortest paths', '*1700']
D2. Too Many Segments (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i \le r_i) and it covers all integer points j such that l_i \le j \le r_i.The integer point is called bad if it is covered by strictly more than k segments.Your task is to remove the minimum number of segments so that there are no bad points at all.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5) — the number of segments and the maximum number of segments by which each integer point can be covered.The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 \le l_i \le r_i \le 2 \cdot 10^5) — the endpoints of the i-th segment.OutputIn the first line print one integer m (0 \le m \le n) — the minimum number of segments you need to remove so that there are no bad points.In the second line print m distinct integers p_1, p_2, \dots, p_m (1 \le p_i \le n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.ExamplesInput 7 2 11 11 9 11 7 8 8 9 7 8 9 11 7 9 Output 3 4 6 7 Input 5 1 29 30 30 30 29 29 28 30 30 30 Output 3 1 4 5 Input 6 1 2 3 3 3 2 3 2 2 2 3 2 3 Output 4 1 3 5 6
7 2 11 11 9 11 7 8 8 9 7 8 9 11 7 9
3 4 6 7
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*1800']
D1. Too Many Segments (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i \le r_i) and it covers all integer points j such that l_i \le j \le r_i.The integer point is called bad if it is covered by strictly more than k segments.Your task is to remove the minimum number of segments so that there are no bad points at all.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 200) — the number of segments and the maximum number of segments by which each integer point can be covered.The next n lines contain segments. The i-th line contains two integers l_i and r_i (1 \le l_i \le r_i \le 200) — the endpoints of the i-th segment.OutputIn the first line print one integer m (0 \le m \le n) — the minimum number of segments you need to remove so that there are no bad points.In the second line print m distinct integers p_1, p_2, \dots, p_m (1 \le p_i \le n) — indices of segments you remove in any order. If there are multiple answers, you can print any of them.ExamplesInput 7 2 11 11 9 11 7 8 8 9 7 8 9 11 7 9 Output 3 1 4 7 Input 5 1 29 30 30 30 29 29 28 30 30 30 Output 3 1 2 4 Input 6 1 2 3 3 3 2 3 2 2 2 3 2 3 Output 4 1 3 5 6
7 2 11 11 9 11 7 8 8 9 7 8 9 11 7 9
3 1 4 7
1 second
256 megabytes
['greedy', '*1800']
C2. Good Numbers (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the maximum value of n.You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n.The positive integer is called good if it can be represented as a sum of distinct powers of 3 (i.e. no duplicates of powers of 3 are allowed).For example: 30 is a good number: 30 = 3^3 + 3^1, 1 is a good number: 1 = 3^0, 12 is a good number: 12 = 3^2 + 3^1, but 2 is not a good number: you can't represent it as a sum of distinct powers of 3 (2 = 3^0 + 3^0), 19 is not a good number: you can't represent it as a sum of distinct powers of 3 (for example, the representations 19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0 are invalid), 20 is also not a good number: you can't represent it as a sum of distinct powers of 3 (for example, the representation 20 = 3^2 + 3^2 + 3^0 + 3^0 is invalid). Note, that there exist other representations of 19 and 20 as sums of powers of 3 but none of them consists of distinct powers of 3.For the given positive integer n find such smallest m (n \le m) that m is a good number.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 500) — the number of queries. Then q queries follow.The only line of the query contains one integer n (1 \le n \le 10^{18}).OutputFor each query, print such smallest integer m (where n \le m) that m is a good number.ExampleInput 8 1 2 6 13 14 3620 10000 1000000000000000000 Output 1 3 9 13 27 6561 19683 1350851717672992089
8 1 2 6 13 14 3620 10000 1000000000000000000
1 3 9 13 27 6561 19683 1350851717672992089
2 seconds
256 megabytes
['binary search', 'greedy', 'math', 'meet-in-the-middle', '*1500']
C1. Good Numbers (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the maximum value of n.You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n.The positive integer is called good if it can be represented as a sum of distinct powers of 3 (i.e. no duplicates of powers of 3 are allowed).For example: 30 is a good number: 30 = 3^3 + 3^1, 1 is a good number: 1 = 3^0, 12 is a good number: 12 = 3^2 + 3^1, but 2 is not a good number: you can't represent it as a sum of distinct powers of 3 (2 = 3^0 + 3^0), 19 is not a good number: you can't represent it as a sum of distinct powers of 3 (for example, the representations 19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0 are invalid), 20 is also not a good number: you can't represent it as a sum of distinct powers of 3 (for example, the representation 20 = 3^2 + 3^2 + 3^0 + 3^0 is invalid). Note, that there exist other representations of 19 and 20 as sums of powers of 3 but none of them consists of distinct powers of 3.For the given positive integer n find such smallest m (n \le m) that m is a good number.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 500) — the number of queries. Then q queries follow.The only line of the query contains one integer n (1 \le n \le 10^4).OutputFor each query, print such smallest integer m (where n \le m) that m is a good number.ExampleInput 7 1 2 6 13 14 3620 10000 Output 1 3 9 13 27 6561 19683
7 1 2 6 13 14 3620 10000
1 3 9 13 27 6561 19683
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*1300']
B2. Books Exchange (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers from 1 to n (i.e. p is a permutation). The sequence p doesn't change from day to day, it is fixed.For example, if n=6 and p=[4, 6, 1, 3, 5, 2] then at the end of the first day the book of the 1-st kid will belong to the 4-th kid, the 2-nd kid will belong to the 6-th kid and so on. At the end of the second day the book of the 1-st kid will belong to the 3-th kid, the 2-nd kid will belong to the 2-th kid and so on.Your task is to determine the number of the day the book of the i-th child is returned back to him for the first time for every i from 1 to n.Consider the following example: p = [5, 1, 2, 4, 3]. The book of the 1-st kid will be passed to the following kids: after the 1-st day it will belong to the 5-th kid, after the 2-nd day it will belong to the 3-rd kid, after the 3-rd day it will belong to the 2-nd kid, after the 4-th day it will belong to the 1-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 1000) — the number of queries. Then q queries follow.The first line of the query contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of kids in the query. The second line of the query contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n, all p_i are distinct, i.e. p is a permutation), where p_i is the kid which will get the book of the i-th kid.It is guaranteed that \sum n \le 2 \cdot 10^5 (sum of n over all queries does not exceed 2 \cdot 10^5).OutputFor each query, print the answer on it: n integers a_1, a_2, \dots, a_n, where a_i is the number of the day the book of the i-th child is returned back to him for the first time in this query.ExampleInput 6 5 1 2 3 4 5 3 2 3 1 6 4 6 2 1 5 3 1 1 4 3 4 1 2 5 5 1 2 4 3 Output 1 1 1 1 1 3 3 3 2 3 3 2 1 3 1 2 2 2 2 4 4 4 1 4
6 5 1 2 3 4 5 3 2 3 1 6 4 6 2 1 5 3 1 1 4 3 4 1 2 5 5 1 2 4 3
1 1 1 1 1 3 3 3 2 3 3 2 1 3 1 2 2 2 2 4 4 4 1 4
1 second
256 megabytes
['dfs and similar', 'dsu', 'math', '*1300']
B1. Books Exchange (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers from 1 to n (i.e. p is a permutation). The sequence p doesn't change from day to day, it is fixed.For example, if n=6 and p=[4, 6, 1, 3, 5, 2] then at the end of the first day the book of the 1-st kid will belong to the 4-th kid, the 2-nd kid will belong to the 6-th kid and so on. At the end of the second day the book of the 1-st kid will belong to the 3-th kid, the 2-nd kid will belong to the 2-th kid and so on.Your task is to determine the number of the day the book of the i-th child is returned back to him for the first time for every i from 1 to n.Consider the following example: p = [5, 1, 2, 4, 3]. The book of the 1-st kid will be passed to the following kids: after the 1-st day it will belong to the 5-th kid, after the 2-nd day it will belong to the 3-rd kid, after the 3-rd day it will belong to the 2-nd kid, after the 4-th day it will belong to the 1-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 200) — the number of queries. Then q queries follow.The first line of the query contains one integer n (1 \le n \le 200) — the number of kids in the query. The second line of the query contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n, all p_i are distinct, i.e. p is a permutation), where p_i is the kid which will get the book of the i-th kid.OutputFor each query, print the answer on it: n integers a_1, a_2, \dots, a_n, where a_i is the number of the day the book of the i-th child is returned back to him for the first time in this query.ExampleInput 6 5 1 2 3 4 5 3 2 3 1 6 4 6 2 1 5 3 1 1 4 3 4 1 2 5 5 1 2 4 3 Output 1 1 1 1 1 3 3 3 2 3 3 2 1 3 1 2 2 2 2 4 4 4 1 4
6 5 1 2 3 4 5 3 2 3 1 6 4 6 2 1 5 3 1 1 4 3 4 1 2 5 5 1 2 4 3
1 1 1 1 1 3 3 3 2 3 3 2 1 3 1 2 2 2 2 4 4 4 1 4
1 second
256 megabytes
['dsu', 'math', '*1000']
A. Yet Another Dividing into Teamstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that: No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than 1); the number of teams is the minimum possible. You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 100) — the number of queries. Then q queries follow.The first line of the query contains one integer n (1 \le n \le 100) — the number of students in the query. The second line of the query contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100, all a_i are distinct), where a_i is the programming skill of the i-th student.OutputFor each query, print the answer on it — the minimum number of teams you can form if no two students i and j such that |a_i - a_j| = 1 may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than 1)ExampleInput 4 4 2 10 1 20 2 3 6 5 2 3 4 99 100 1 42 Output 2 1 2 1 NoteIn the first query of the example, there are n=4 students with the skills a=[2, 10, 1, 20]. There is only one restriction here: the 1-st and the 3-th students can't be in the same team (because of |a_1 - a_3|=|2-1|=1). It is possible to divide them into 2 teams: for example, students 1, 2 and 4 are in the first team and the student 3 in the second team.In the second query of the example, there are n=2 students with the skills a=[3, 6]. It is possible to compose just a single team containing both students.
4 4 2 10 1 20 2 3 6 5 2 3 4 99 100 1 42
2 1 2 1
1 second
256 megabytes
['math', '*800']
D1. The World Is Just a Programming Task (Easy Version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version, n \le 500.Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.We remind that bracket sequence s is called correct if: s is empty; s is equal to "(t)", where t is correct bracket sequence; s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not.The cyclical shift of the string s of length n by k (0 \leq k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".Cyclical shifts i and j are considered different, if i \ne j.InputThe first line contains an integer n (1 \le n \le 500), the length of the string.The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".OutputThe first line should contain a single integer — the largest beauty of the string, which can be achieved by swapping some two characters.The second line should contain integers l and r (1 \leq l, r \leq n) — the indices of two characters, which should be swapped in order to maximize the string's beauty.In case there are several possible swaps, print any of them.ExamplesInput 10 ()()())(() Output 5 8 7 Input 12 )(()(()())() Output 4 5 10 Input 6 )))(() Output 0 1 1 NoteIn the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
10 ()()())(()
5 8 7
1 second
512 megabytes
['brute force', 'dp', 'greedy', 'implementation', '*2000']
B. Grow The Treetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point (0, 0). While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to OX or OY axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from (0, 0). Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.InputThe first line contains an integer n (1 \le n \le 100\,000) — the number of sticks Alexey got as a present.The second line contains n integers a_1, \ldots, a_n (1 \le a_i \le 10\,000) — the lengths of the sticks.OutputPrint one integer — the square of the largest possible distance from (0, 0) to the tree end.ExamplesInput 3 1 2 3 Output 26Input 4 1 1 2 2 Output 20NoteThe following pictures show optimal trees for example tests. The squared distance in the first example equals 5 \cdot 5 + 1 \cdot 1 = 26, and in the second example 4 \cdot 4 + 2 \cdot 2 = 20.
3 1 2 3
26
2 seconds
512 megabytes
['greedy', 'math', 'sortings', '*900']
A. Integer Pointstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew n distinct lines, given by equations y = x + p_i for some distinct p_1, p_2, \ldots, p_n.Then JLS drew on the same paper sheet m distinct lines given by equations y = -x + q_i for some distinct q_1, q_2, \ldots, q_m.DLS and JLS are interested in counting how many line pairs have integer intersection points, i.e. points with both coordinates that are integers. Unfortunately, the lesson will end up soon, so DLS and JLS are asking for your help.InputThe first line contains one integer t (1 \le t \le 1000), the number of test cases in the input. Then follow the test case descriptions.The first line of a test case contains an integer n (1 \le n \le 10^5), the number of lines drawn by DLS.The second line of a test case contains n distinct integers p_i (0 \le p_i \le 10^9) describing the lines drawn by DLS. The integer p_i describes a line given by the equation y = x + p_i.The third line of a test case contains an integer m (1 \le m \le 10^5), the number of lines drawn by JLS.The fourth line of a test case contains m distinct integers q_i (0 \le q_i \le 10^9) describing the lines drawn by JLS. The integer q_i describes a line given by the equation y = -x + q_i.The sum of the values of n over all test cases in the input does not exceed 10^5. Similarly, the sum of the values of m over all test cases in the input does not exceed 10^5.In hacks it is allowed to use only one test case in the input, so t=1 should be satisfied.OutputFor each test case in the input print a single integer — the number of line pairs with integer intersection points. ExampleInput 3 3 1 3 2 2 0 3 1 1 1 1 1 2 1 1 Output 3 1 0 NoteThe picture shows the lines from the first test case of the example. Black circles denote intersection points with integer coordinates.
3 3 1 3 2 2 0 3 1 1 1 1 1 2 1 1
3 1 0
2 seconds
512 megabytes
['geometry', 'math', '*1000']
F. Cursor Distancetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a string s of lowercase English letters. A cursor is positioned on one of the characters. The cursor can be moved with the following operation: choose a letter c and a direction (left or right). The cursor is then moved to the closest occurence of c in the chosen direction. If there is no letter c in that direction, the cursor stays in place. For example, if s = \mathtt{abaab} with the cursor on the second character (\mathtt{a[b]aab}), then: moving to the closest letter \mathtt{a} to the left places the cursor on the first character (\mathtt{[a]baab}); moving to the closest letter \mathtt{a} to the right places the cursor the third character (\mathtt{ab[a]ab}); moving to the closest letter \mathtt{b} to the right places the cursor on the fifth character (\mathtt{abaa[b]}); any other operation leaves the cursor in place.Let \mathrm{dist}(i, j) be the smallest number of operations needed to move the cursor from the i-th character to the j-th character. Compute \displaystyle \sum_{i = 1}^n \sum_{j = 1}^n \mathrm{dist}(i, j).InputThe only line contains a non-empty string s of at most 10^5 lowercase English letters.OutputPrint a single integer \displaystyle \sum_{i = 1}^n \sum_{j = 1}^n \mathrm{dist}(i, j).ExamplesInput abcde Output 20 Input abacaba Output 58 NoteIn the first sample case, \mathrm{dist}(i, j) = 0 for any pair i = j, and 1 for all other pairs.
abcde
20
2 seconds
512 megabytes
['*3500']
F. Daniel and Spring Cleaningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute 1 + 3 using the calculator, he gets 2 instead of 4. But when he tries computing 1 + 4, he gets the correct answer, 5. Puzzled by this mystery, he opened up his calculator and found the answer to the riddle: the full adders became half adders! So, when he tries to compute the sum a + b using the calculator, he instead gets the xorsum a \oplus b (read the definition by the link: https://en.wikipedia.org/wiki/Exclusive_or).As he saw earlier, the calculator sometimes gives the correct answer. And so, he wonders, given integers l and r, how many pairs of integers (a, b) satisfy the following conditions: a + b = a \oplus b l \leq a \leq r l \leq b \leq rHowever, Daniel the Barman is going to the bar and will return in two hours. He tells you to solve the problem before he returns, or else you will have to enjoy being blocked.InputThe first line contains a single integer t (1 \le t \le 100) — the number of testcases.Then, t lines follow, each containing two space-separated integers l and r (0 \le l \le r \le 10^9).OutputPrint t integers, the i-th integer should be the answer to the i-th testcase.ExampleInput 3 1 4 323 323 1 1000000 Output 8 0 3439863766 Notea \oplus b denotes the bitwise XOR of a and b.For the first testcase, the pairs are: (1, 2), (1, 4), (2, 1), (2, 4), (3, 4), (4, 1), (4, 2), and (4, 3).
3 1 4 323 323 1 1000000
8 0 3439863766
2 seconds
256 megabytes
['bitmasks', 'brute force', 'combinatorics', 'dp', '*2300']
E. Hyakugoku and Ladderstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHyakugoku has just retired from being the resident deity of the South Black Snail Temple in order to pursue her dream of becoming a cartoonist. She spent six months in that temple just playing "Cat's Cradle" so now she wants to try a different game — "Snakes and Ladders". Unfortunately, she already killed all the snakes, so there are only ladders left now. The game is played on a 10 \times 10 board as follows: At the beginning of the game, the player is at the bottom left square. The objective of the game is for the player to reach the Goal (the top left square) by following the path and climbing vertical ladders. Once the player reaches the Goal, the game ends. The path is as follows: if a square is not the end of its row, it leads to the square next to it along the direction of its row; if a square is the end of its row, it leads to the square above it. The direction of a row is determined as follows: the direction of the bottom row is to the right; the direction of any other row is opposite the direction of the row below it. See Notes section for visualization of path. During each turn, the player rolls a standard six-sided dice. Suppose that the number shown on the dice is r. If the Goal is less than r squares away on the path, the player doesn't move (but the turn is performed). Otherwise, the player advances exactly r squares along the path and then stops. If the player stops on a square with the bottom of a ladder, the player chooses whether or not to climb up that ladder. If she chooses not to climb, then she stays in that square for the beginning of the next turn. Some squares have a ladder in them. Ladders are only placed vertically — each one leads to the same square of some of the upper rows. In order for the player to climb up a ladder, after rolling the dice, she must stop at the square containing the bottom of the ladder. After using the ladder, the player will end up in the square containing the top of the ladder. She cannot leave the ladder in the middle of climbing. And if the square containing the top of the ladder also contains the bottom of another ladder, she is not allowed to use that second ladder. The numbers on the faces of the dice are 1, 2, 3, 4, 5, and 6, with each number having the same probability of being shown. Please note that: it is possible for ladders to overlap, but the player cannot switch to the other ladder while in the middle of climbing the first one; it is possible for ladders to go straight to the top row, but not any higher; it is possible for two ladders to lead to the same tile; it is possible for a ladder to lead to a tile that also has a ladder, but the player will not be able to use that second ladder if she uses the first one; the player can only climb up ladders, not climb down. Hyakugoku wants to finish the game as soon as possible. Thus, on each turn she chooses whether to climb the ladder or not optimally. Help her to determine the minimum expected number of turns the game will take.InputInput will consist of ten lines. The i-th line will contain 10 non-negative integers h_{i1}, h_{i2}, \dots, h_{i10}. If h_{ij} is 0, then the tile at the i-th row and j-th column has no ladder. Otherwise, the ladder at that tile will have a height of h_{ij}, i.e. climbing it will lead to the tile h_{ij} rows directly above. It is guaranteed that 0 \leq h_{ij} < i. Also, the first number of the first line and the first number of the last line always contain 0, i.e. the Goal and the starting tile never have ladders.OutputPrint only one line containing a single floating-point number — the minimum expected number of turns Hyakugoku can take to finish the game. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.ExamplesInput 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Output 33.0476190476 Input 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 Output 20.2591405923 Input 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 6 6 6 6 6 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Output 15.9047592939 NoteA visualization of the path and the board from example 2 is as follows: The tile with an 'S' is the starting tile and the tile with an 'E' is the Goal.For the first example, there are no ladders.For the second example, the board looks like the one in the right part of the image (the ladders have been colored for clarity).It is possible for ladders to overlap, as is the case with the red and yellow ladders and green and blue ladders. It is also possible for ladders to go straight to the top, as is the case with the black and blue ladders. However, it is not possible for ladders to go any higher (outside of the board). It is also possible that two ladders lead to the same tile, as is the case with the red and yellow ladders. Also, notice that the red and yellow ladders lead to the tile with the orange ladder. So if the player chooses to climb either of the red and yellow ladders, they will not be able to climb the orange ladder. Finally, notice that the green ladder passes through the starting tile of the blue ladder. The player cannot transfer from the green ladder to the blue ladder while in the middle of climbing the green ladder.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
33.0476190476
1 second
256 megabytes
['dp', 'probabilities', 'shortest paths', '*2300']
D. Shichikuji and Power Gridtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputShichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i \ne j.Shichikuji must provide electricity to each city either by building a power station in that city, or by making a connection between that city and another one that already has electricity. So the City has electricity if it has a power station in it or it is connected to a City which has electricity by a direct connection or via a chain of connections. Building a power station in City i will cost c_i yen; Making a connection between City i and City j will cost k_i + k_j yen per km of wire used for the connection. However, wires can only go the cardinal directions (North, South, East, West). Wires can cross each other. Each wire must have both of its endpoints in some cities. If City i and City j are connected by a wire, the wire will go through any shortest path from City i to City j. Thus, the length of the wire if City i and City j are connected is |x_i - x_j| + |y_i - y_j| km. Shichikuji wants to do this job spending as little money as possible, since according to her, there isn't really anything else in the world other than money. However, she died when she was only in fifth grade so she is not smart enough for this. And thus, the new resident deity asks for your help.And so, you have to provide Shichikuji with the following information: minimum amount of yen needed to provide electricity to all cities, the cities in which power stations will be built, and the connections to be made.If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.InputFirst line of input contains a single integer n (1 \leq n \leq 2000) — the number of cities.Then, n lines follow. The i-th line contains two space-separated integers x_i (1 \leq x_i \leq 10^6) and y_i (1 \leq y_i \leq 10^6) — the coordinates of the i-th city.The next line contains n space-separated integers c_1, c_2, \dots, c_n (1 \leq c_i \leq 10^9) — the cost of building a power station in the i-th city.The last line contains n space-separated integers k_1, k_2, \dots, k_n (1 \leq k_i \leq 10^9).OutputIn the first line print a single integer, denoting the minimum amount of yen needed.Then, print an integer v — the number of power stations to be built.Next, print v space-separated integers, denoting the indices of cities in which a power station will be built. Each number should be from 1 to n and all numbers should be pairwise distinct. You can print the numbers in arbitrary order.After that, print an integer e — the number of connections to be made.Finally, print e pairs of integers a and b (1 \le a, b \le n, a \ne b), denoting that a connection between City a and City b will be made. Each unordered pair of cities should be included at most once (for each (a, b) there should be no more (a, b) or (b, a) pairs). You can print the pairs in arbitrary order.If there are multiple ways to choose the cities and the connections to obtain the construction of minimum price, then print any of them.ExamplesInput 3 2 3 1 1 3 2 3 2 3 3 2 3 Output 8 3 1 2 3 0 Input 3 2 1 1 2 3 3 23 2 23 3 2 3 Output 27 1 2 2 1 2 2 3 NoteFor the answers given in the samples, refer to the following diagrams (cities with power stations are colored green, other cities are colored blue, and wires are colored red):For the first example, the cost of building power stations in all cities is 3 + 2 + 3 = 8. It can be shown that no configuration costs less than 8 yen.For the second example, the cost of building a power station in City 2 is 2. The cost of connecting City 1 and City 2 is 2 \cdot (3 + 2) = 10. The cost of connecting City 2 and City 3 is 3 \cdot (2 + 3) = 15. Thus the total cost is 2 + 10 + 15 = 27. It can be shown that no configuration costs less than 27 yen.
3 2 3 1 1 3 2 3 2 3 3 2 3
8 3 1 2 3 0
2 seconds
256 megabytes
['dsu', 'graphs', 'greedy', 'shortest paths', 'trees', '*1900']
C. Constanze's Machinetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConstanze is the smartest girl in her village but she has bad eyesight.One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe "code" onto the paper. Thanks to this machine, she can finally write messages without using her glasses.However, her dumb friend Akko decided to play a prank on her. Akko tinkered with the machine so that if you pronounce 'w', it will inscribe "uu" instead of "w", and if you pronounce 'm', it will inscribe "nn" instead of "m"! Since Constanze had bad eyesight, she was not able to realize what Akko did.The rest of the letters behave the same as before: if you pronounce any letter besides 'w' and 'm', the machine will just inscribe it onto a piece of paper.The next day, I received a letter in my mailbox. I can't understand it so I think it's either just some gibberish from Akko, or Constanze made it using her machine. But since I know what Akko did, I can just list down all possible strings that Constanze's machine would have turned into the message I got and see if anything makes sense.But I need to know how much paper I will need, and that's why I'm asking you for help. Tell me the number of strings that Constanze's machine would've turned into the message I got.But since this number can be quite large, tell me instead its remainder when divided by 10^9+7.If there are no strings that Constanze's machine would've turned into the message I got, then print 0.InputInput consists of a single line containing a string s (1 \leq |s| \leq 10^5) — the received message. s contains only lowercase Latin letters.OutputPrint a single integer — the number of strings that Constanze's machine would've turned into the message s, modulo 10^9+7.ExamplesInput ouuokarinn Output 4 Input banana Output 1 Input nnn Output 3 Input amanda Output 0 NoteFor the first example, the candidate strings are the following: "ouuokarinn", "ouuokarim", "owokarim", and "owokarinn".For the second example, there is only one: "banana".For the third example, the candidate strings are the following: "nm", "mn" and "nnn".For the last example, there are no candidate strings that the machine can turn into "amanda", since the machine won't inscribe 'm'.
ouuokarinn
4
1 second
256 megabytes
['dp', '*1400']
B. Restricted RPStime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n.Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times.Alice wins if she beats Bob in at least \lceil \frac{n}{2} \rceil (\frac{n}{2} rounded up to the nearest integer) hands, otherwise Alice loses.Note that in rock-paper-scissors: rock beats scissors; paper beats rock; scissors beat paper. The task is, given the sequence of hands that Bob will play, and the numbers a, b, c, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win.If there are multiple answers, print any of them.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.Then, t testcases follow, each consisting of three lines: The first line contains a single integer n (1 \le n \le 100). The second line contains three integers, a, b, c (0 \le a, b, c \le n). It is guaranteed that a + b + c = n. The third line contains a string s of length n. s is made up of only 'R', 'P', and 'S'. The i-th character is 'R' if for his i-th Bob plays rock, 'P' if paper, and 'S' if scissors. OutputFor each testcase: If Alice cannot win, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes). Also, print a string t of length n made up of only 'R', 'P', and 'S' — a sequence of hands that Alice can use to win. t must contain exactly a 'R's, b 'P's, and c 'S's. If there are multiple answers, print any of them. The "YES" / "NO" part of the output is case-insensitive (i.e. "yEs", "no" or "YEs" are all valid answers). Note that 'R', 'P' and 'S' are case-sensitive.ExampleInput 2 3 1 1 1 RPS 3 3 0 0 RPS Output YES PSR NO NoteIn the first testcase, in the first hand, Alice plays paper and Bob plays rock, so Alice beats Bob. In the second hand, Alice plays scissors and Bob plays paper, so Alice beats Bob. In the third hand, Alice plays rock and Bob plays scissors, so Alice beats Bob. Alice beat Bob 3 times, and 3 \ge \lceil \frac{3}{2} \rceil = 2, so Alice wins.In the second testcase, the only sequence of hands that Alice can play is "RRR". Alice beats Bob only in the last hand, so Alice can't win. 1 < \lceil \frac{3}{2} \rceil = 2.
2 3 1 1 1 RPS 3 3 0 0 RPS
YES PSR NO
1 second
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*1200']
A. Good ol' Numbers Coloringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the set of all nonnegative integers: {0, 1, 2, \dots}. Given two integers a and b (1 \le a, b \le 10^4). We paint all the numbers in increasing number first we paint 0, then we paint 1, then 2 and so on.Each number is painted white or black. We paint a number i according to the following rules: if i = 0, it is colored white; if i \ge a and i - a is colored white, i is also colored white; if i \ge b and i - b is colored white, i is also colored white; if i is still not colored white, it is colored black. In this way, each nonnegative integer gets one of two colors.For example, if a=3, b=5, then the colors of the numbers (in the order from 0) are: white (0), black (1), black (2), white (3), black (4), white (5), white (6), black (7), white (8), white (9), ...Note that: It is possible that there are infinitely many nonnegative integers colored black. For example, if a = 10 and b = 10, then only 0, 10, 20, 30 and any other nonnegative integers that end in 0 when written in base 10 are white. The other integers are colored black. It is also possible that there are only finitely many nonnegative integers colored black. For example, when a = 1 and b = 10, then there is no nonnegative integer colored black at all. Your task is to determine whether or not the number of nonnegative integers colored black is infinite.If there are infinitely many nonnegative integers colored black, simply print a line containing "Infinite" (without the quotes). Otherwise, print "Finite" (without the quotes).InputThe first line of input contains a single integer t (1 \le t \le 100) — the number of test cases in the input. Then t lines follow, each line contains two space-separated integers a and b (1 \le a, b \le 10^4).OutputFor each test case, print one line containing either "Infinite" or "Finite" (without the quotes). Output is case-insensitive (i.e. "infinite", "inFiNite" or "finiTE" are all valid answers).ExampleInput 4 10 10 1 10 6 9 7 3 Output Infinite Finite Infinite Finite
4 10 10 1 10 6 9 7 3
Infinite Finite Infinite Finite
1 second
256 megabytes
['math', 'number theory', '*1000']
G. Running in Pairstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDemonstrative competitions will be held in the run-up to the 20NN Berlatov Olympic Games. Today is the day for the running competition!Berlatov team consists of 2n runners which are placed on two running tracks; n runners are placed on each track. The runners are numbered from 1 to n on each track. The runner with number i runs through the entire track in i seconds.The competition is held as follows: first runners on both tracks start running at the same time; when the slower of them arrives at the end of the track, second runners on both tracks start running, and everyone waits until the slower of them finishes running, and so on, until all n pairs run through the track.The organizers want the run to be as long as possible, but if it lasts for more than k seconds, the crowd will get bored. As the coach of the team, you may choose any order in which the runners are arranged on each track (but you can't change the number of runners on each track or swap runners between different tracks).You have to choose the order of runners on each track so that the duration of the competition is as long as possible, but does not exceed k seconds.Formally, you want to find two permutations p and q (both consisting of n elements) such that sum = \sum\limits_{i=1}^{n} max(p_i, q_i) is maximum possible, but does not exceed k. If there is no such pair, report about it.InputThe first line contains two integers n and k (1 \le n \le 10^6, 1 \le k \le n^2) — the number of runners on each track and the maximum possible duration of the competition, respectively.OutputIf it is impossible to reorder the runners so that the duration of the competition does not exceed k seconds, print -1. Otherwise, print three lines. The first line should contain one integer sum — the maximum possible duration of the competition not exceeding k. The second line should contain a permutation of n integers p_1, p_2, \dots, p_n (1 \le p_i \le n, all p_i should be pairwise distinct) — the numbers of runners on the first track in the order they participate in the competition. The third line should contain a permutation of n integers q_1, q_2, \dots, q_n (1 \le q_i \le n, all q_i should be pairwise distinct) — the numbers of runners on the second track in the order they participate in the competition. The value of sum = \sum\limits_{i=1}^{n} max(p_i, q_i) should be maximum possible, but should not exceed k. If there are multiple answers, print any of them.ExamplesInput 5 20 Output 20 1 2 3 4 5 5 2 4 3 1 Input 3 9 Output 8 1 2 3 3 2 1 Input 10 54 Output -1 NoteIn the first example the order of runners on the first track should be [5, 3, 2, 1, 4], and the order of runners on the second track should be [1, 4, 2, 5, 3]. Then the duration of the competition is max(5, 1) + max(3, 4) + max(2, 2) + max(1, 5) + max(4, 3) = 5 + 4 + 2 + 5 + 4 = 20, so it is equal to the maximum allowed duration.In the first example the order of runners on the first track should be [2, 3, 1], and the order of runners on the second track should be [2, 1, 3]. Then the duration of the competition is 8, and it is the maximum possible duration for n = 3.
5 20
20 1 2 3 4 5 5 2 4 3 1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*2400']
F. Chipstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n chips arranged in a circle, numbered from 1 to n. Initially each chip has black or white color. Then k iterations occur. During each iteration the chips change their colors according to the following rules. For each chip i, three chips are considered: chip i itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip i becomes white. Otherwise, the chip i becomes black. Note that for each i from 2 to (n - 1) two neighbouring chips have numbers (i - 1) and (i + 1). The neighbours for the chip i = 1 are n and 2. The neighbours of i = n are (n - 1) and 1.The following picture describes one iteration with n = 6. The chips 1, 3 and 4 are initially black, and the chips 2, 5 and 6 are white. After the iteration 2, 3 and 4 become black, and 1, 5 and 6 become white. Your task is to determine the color of each chip after k iterations.InputThe first line contains two integers n and k (3 \le n \le 200\,000, 1 \le k \le 10^{9}) — the number of chips and the number of iterations, respectively.The second line contains a string consisting of n characters "W" and "B". If the i-th character is "W", then the i-th chip is white initially. If the i-th character is "B", then the i-th chip is black initially.OutputPrint a string consisting of n characters "W" and "B". If after k iterations the i-th chip is white, then the i-th character should be "W". Otherwise the i-th character should be "B".ExamplesInput 6 1 BWBBWW Output WBBBWW Input 7 3 WBWBWBW Output WWWWWWW Input 6 4 BWBWBW Output BWBWBW NoteThe first example is described in the statement.The second example: "WBWBWBW" \rightarrow "WWBWBWW" \rightarrow "WWWBWWW" \rightarrow "WWWWWWW". So all chips become white.The third example: "BWBWBW" \rightarrow "WBWBWB" \rightarrow "BWBWBW" \rightarrow "WBWBWB" \rightarrow "BWBWBW".
6 1 BWBBWW
WBBBWW
1 second
256 megabytes
['constructive algorithms', 'implementation', '*2300']
E. Minimizing Differencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a_1, a_2, \dots, a_n consisting of n integers.You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times.InputThe first line contains two integers n and k (2 \le n \le 10^{5}, 1 \le k \le 10^{14}) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively.The second line contains a sequence of integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{9}).OutputPrint the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than k times.ExamplesInput 4 5 3 1 7 5 Output 2 Input 3 10 100 100 100 Output 0 Input 10 9 4 5 5 7 5 4 5 2 4 3 Output 1 NoteIn the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3, 3, 5, 5], and the difference between maximum and minimum is 2. You still can perform one operation after that, but it's useless since you can't make the answer less than 2.In the second example all elements are already equal, so you may get 0 as the answer even without applying any operations.
4 5 3 1 7 5
2
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'greedy', 'sortings', 'ternary search', 'two pointers', '*2000']
D. Paint the Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. A tree is an undirected connected acyclic graph. Example of a tree. You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples (x, y, z) such that x \neq y, y \neq z, x \neq z, x is connected by an edge with y, and y is connected by an edge with z. The colours of x, y and z should be pairwise distinct. Let's call a painting which meets this condition good.You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.InputThe first line contains one integer n (3 \le n \le 100\,000) — the number of vertices.The second line contains a sequence of integers c_{1, 1}, c_{1, 2}, \dots, c_{1, n} (1 \le c_{1, i} \le 10^{9}), where c_{1, i} is the cost of painting the i-th vertex into the first color.The third line contains a sequence of integers c_{2, 1}, c_{2, 2}, \dots, c_{2, n} (1 \le c_{2, i} \le 10^{9}), where c_{2, i} is the cost of painting the i-th vertex into the second color.The fourth line contains a sequence of integers c_{3, 1}, c_{3, 2}, \dots, c_{3, n} (1 \le c_{3, i} \le 10^{9}), where c_{3, i} is the cost of painting the i-th vertex into the third color.Then (n - 1) lines follow, each containing two integers u_j and v_j (1 \le u_j, v_j \le n, u_j \neq v_j) — the numbers of vertices connected by the j-th undirected edge. It is guaranteed that these edges denote a tree.OutputIf there is no good painting, print -1.Otherwise, print the minimum cost of a good painting in the first line. In the second line print n integers b_1, b_2, \dots, b_n (1 \le b_i \le 3), where the i-th integer should denote the color of the i-th vertex. If there are multiple good paintings with minimum cost, print any of them.ExamplesInput 3 3 2 3 4 3 2 3 1 3 1 2 2 3 Output 6 1 3 2 Input 5 3 4 2 1 2 4 2 1 5 4 5 3 2 1 1 1 2 3 2 4 3 5 3 Output -1 Input 5 3 4 2 1 2 4 2 1 5 4 5 3 2 1 1 1 2 3 2 4 3 5 4 Output 9 1 3 2 1 3 NoteAll vertices should be painted in different colors in the first example. The optimal way to do it is to paint the first vertex into color 1, the second vertex — into color 3, and the third vertex — into color 2. The cost of this painting is 3 + 2 + 1 = 6.
3 3 2 3 4 3 2 3 1 3 1 2 2 3
6 1 3 2
3 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dp', 'graphs', 'implementation', 'trees', '*1800']
C. The Football Seasontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets w points, and the opposing team gets 0 points. If the game results in a draw, both teams get d points.The manager of the Berland capital team wants to summarize the results of the season, but, unfortunately, all information about the results of each match is lost. The manager only knows that the team has played n games and got p points for them.You have to determine three integers x, y and z — the number of wins, draws and loses of the team. If there are multiple answers, print any of them. If there is no suitable triple (x, y, z), report about it.InputThe first line contains four integers n, p, w and d (1 \le n \le 10^{12}, 0 \le p \le 10^{17}, 1 \le d < w \le 10^{5}) — the number of games, the number of points the team got, the number of points awarded for winning a match, and the number of points awarded for a draw, respectively. Note that w > d, so the number of points awarded for winning is strictly greater than the number of points awarded for draw.OutputIf there is no answer, print -1.Otherwise print three non-negative integers x, y and z — the number of wins, draws and losses of the team. If there are multiple possible triples (x, y, z), print any of them. The numbers should meet the following conditions: x \cdot w + y \cdot d = p, x + y + z = n. ExamplesInput 30 60 3 1 Output 17 9 4 Input 10 51 5 4 Output -1 Input 20 0 15 5 Output 0 0 20 NoteOne of the possible answers in the first example — 17 wins, 9 draws and 4 losses. Then the team got 17 \cdot 3 + 9 \cdot 1 = 60 points in 17 + 9 + 4 = 30 games.In the second example the maximum possible score is 10 \cdot 5 = 50. Since p = 51, there is no answer.In the third example the team got 0 points, so all 20 games were lost.
30 60 3 1
17 9 4
1 second
256 megabytes
['brute force', 'math', 'number theory', '*2000']
B. Rooms and Staircasestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay lives in a two-storied house. There are n rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between 1 and n). If Nikolay is currently in some room, he can move to any of the neighbouring rooms (if they exist). Rooms with numbers i and i+1 on each floor are neighbouring, for all 1 \leq i \leq n - 1. There may also be staircases that connect two rooms from different floors having the same numbers. If there is a staircase connecting the room x on the first floor and the room x on the second floor, then Nikolay can use it to move from one room to another. The picture illustrates a house with n = 4. There is a staircase between the room 2 on the first floor and the room 2 on the second floor, and another staircase between the room 4 on the first floor and the room 4 on the second floor. The arrows denote possible directions in which Nikolay can move. The picture corresponds to the string "0101" in the input. Nikolay wants to move through some rooms in his house. To do this, he firstly chooses any room where he starts. Then Nikolay moves between rooms according to the aforementioned rules. Nikolay never visits the same room twice (he won't enter a room where he has already been). Calculate the maximum number of rooms Nikolay can visit during his tour, if: he can start in any room on any floor of his choice, and he won't visit the same room twice. InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases in the input. Then test cases follow. Each test case consists of two lines.The first line contains one integer n (1 \le n \le 1\,000) — the number of rooms on each floor.The second line contains one string consisting of n characters, each character is either a '0' or a '1'. If the i-th character is a '1', then there is a staircase between the room i on the first floor and the room i on the second floor. If the i-th character is a '0', then there is no staircase between the room i on the first floor and the room i on the second floor.In hacks it is allowed to use only one test case in the input, so t = 1 should be satisfied.OutputFor each test case print one integer — the maximum number of rooms Nikolay can visit during his tour, if he can start in any room on any floor, and he won't visit the same room twice.ExampleInput 4 5 00100 8 00000000 5 11111 3 110 Output 6 8 10 6 NoteIn the first test case Nikolay may start in the first room of the first floor. Then he moves to the second room on the first floor, and then — to the third room on the first floor. Then he uses a staircase to get to the third room on the second floor. Then he goes to the fourth room on the second floor, and then — to the fifth room on the second floor. So, Nikolay visits 6 rooms.There are no staircases in the second test case, so Nikolay can only visit all rooms on the same floor (if he starts in the leftmost or in the rightmost room).In the third test case it is possible to visit all rooms: first floor, first room \rightarrow second floor, first room \rightarrow second floor, second room \rightarrow first floor, second room \rightarrow first floor, third room \rightarrow second floor, third room \rightarrow second floor, fourth room \rightarrow first floor, fourth room \rightarrow first floor, fifth room \rightarrow second floor, fifth room.In the fourth test case it is also possible to visit all rooms: second floor, third room \rightarrow second floor, second room \rightarrow second floor, first room \rightarrow first floor, first room \rightarrow first floor, second room \rightarrow first floor, third room.
4 5 00100 8 00000000 5 11111 3 110
6 8 10 6
1 second
256 megabytes
['brute force', 'implementation', '*1000']
A. Pens and Pencilstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and draw everything he has to during all of the practical classes. Polycarp writes lectures using a pen (he can't use a pencil to write lectures!); he can write down c lectures using one pen, and after that it runs out of ink. During practical classes Polycarp draws blueprints with a pencil (he can't use a pen to draw blueprints!); one pencil is enough to draw all blueprints during d practical classes, after which it is unusable.Polycarp's pencilcase can hold no more than k writing implements, so if Polycarp wants to take x pens and y pencils, they will fit in the pencilcase if and only if x + y \le k.Now Polycarp wants to know how many pens and pencils should he take. Help him to determine it, or tell that his pencilcase doesn't have enough room for all the implements he needs tomorrow!Note that you don't have to minimize the number of writing implements (though their total number must not exceed k).InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases in the input. Then the test cases follow.Each test case is described by one line containing five integers a, b, c, d and k, separated by spaces (1 \le a, b, c, d, k \le 100) — the number of lectures Polycarp has to attend, the number of practical classes Polycarp has to attend, the number of lectures which can be written down using one pen, the number of practical classes for which one pencil is enough, and the number of writing implements that can fit into Polycarp's pencilcase, respectively.In hacks it is allowed to use only one test case in the input, so t = 1 should be satisfied.OutputFor each test case, print the answer as follows:If the pencilcase can't hold enough writing implements to use them during all lectures and practical classes, print one integer -1. Otherwise, print two non-negative integers x and y — the number of pens and pencils Polycarp should put in his pencilcase. If there are multiple answers, print any of them. Note that you don't have to minimize the number of writing implements (though their total number must not exceed k).ExampleInput 3 7 5 4 5 8 7 5 4 5 2 20 53 45 26 4 Output 7 1 -1 1 3 NoteThere are many different answers for the first test case; x = 7, y = 1 is only one of them. For example, x = 3, y = 1 is also correct.x = 1, y = 3 is the only correct answer for the third test case.
3 7 5 4 5 8 7 5 4 5 2 20 53 45 26 4
7 1 -1 1 3
1 second
256 megabytes
['math', '*800']
B2. Character Swap (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k \le 1000, n \le 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 \le i,j \le n, the values i and j can be equal or different), and swaps the characters s_i and t_j.Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.InputThe first line contains a single integer k (1 \leq k \leq 1000), the number of test cases.For each of the test cases, the first line contains a single integer n (2 \leq n \leq 50), the length of the strings s and t. Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.OutputFor each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).In the case of "Yes" print m (1 \le m \le 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 \le i, j \le n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.ExampleInput 4 5 souse houhe 3 cat dog 2 aa az 3 abc bca Output Yes 1 1 4 No No Yes 3 1 2 3 1 2 3
4 5 souse houhe 3 cat dog 2 aa az 3 abc bca
Yes 1 1 4 No No Yes 3 1 2 3 1 2 3
1 second
256 megabytes
['strings', '*1600']
B1. Character Swap (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation exactly once: he takes two positions i and j (1 \le i,j \le n, the values i and j can be equal or different), and swaps the characters s_i and t_j. Can he succeed?Note that he has to perform this operation exactly once. He has to perform this operation.InputThe first line contains a single integer k (1 \leq k \leq 10), the number of test cases.For each of the test cases, the first line contains a single integer n (2 \leq n \leq 10^4), the length of the strings s and t. Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.OutputFor each test case, output "Yes" if Ujan can make the two strings equal and "No" otherwise.You can print each letter in any case (upper or lower).ExampleInput 4 5 souse houhe 3 cat dog 2 aa az 3 abc bca Output Yes No No No NoteIn the first test case, Ujan can swap characters s_1 and t_4, obtaining the word "house".In the second test case, it is not possible to make the strings equal using exactly one swap of s_i and t_j.
4 5 souse houhe 3 cat dog 2 aa az 3 abc bca
Yes No No No
1 second
256 megabytes
['strings', '*1000']
A. Maximum Squaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputUjan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i \times 1 (that is, the width is 1 and the height is a_i).Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.For example, if Ujan had planks with lengths 4, 3, 1, 4 and 5, he could choose planks with lengths 4, 3 and 5. Then he can cut out a 3 \times 3 square, which is the maximum possible. Note that this is not the only way he can obtain a 3 \times 3 square. What is the maximum side length of the square Ujan can get?InputThe first line of input contains a single integer k (1 \leq k \leq 10), the number of test cases in the input.For each test case, the first line contains a single integer n (1 \leq n \leq 1\,000), the number of planks Ujan has in store. The next line contains n integers a_1, \ldots, a_n (1 \leq a_i \leq n), the lengths of the planks.OutputFor each of the test cases, output a single integer, the maximum possible side length of the square.ExampleInput 4 5 4 3 1 4 5 4 4 4 4 4 3 1 1 1 5 5 5 1 1 5 Output 3 4 1 3 NoteThe first sample corresponds to the example in the statement.In the second sample, gluing all 4 planks will result in a 4 \times 4 square.In the third sample, the maximum possible square is 1 \times 1 and can be taken simply as any of the planks.
4 5 4 3 1 4 5 4 4 4 4 4 3 1 1 1 5 5 5 1 1 5
3 4 1 3
1 second
256 megabytes
['implementation', '*800']
E. Planar Perimetertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputUjan has finally cleaned up his house and now wants to decorate the interior. He decided to place a beautiful carpet that would really tie the guest room together.He is interested in carpets that are made up of polygonal patches such that each side of a patch is either a side of another (different) patch, or is an exterior side of the whole carpet. In other words, the carpet can be represented as a planar graph, where each patch corresponds to a face of the graph, each face is a simple polygon. The perimeter of the carpet is the number of the exterior sides. Ujan considers a carpet beautiful if it consists of f patches, where the i-th patch has exactly a_i sides, and the perimeter is the smallest possible. Find an example of such a carpet, so that Ujan can order it!InputThe first line of input contains a single integer f (1 \leq f \leq 10^5), the number of patches in the carpet. The next line contains f integers a_1, \ldots, a_f (3 \leq a_i \leq 3\cdot 10^5), the number of sides of the patches. The total number of the sides of the patches a_1 + \ldots + a_f does not exceed 3\cdot10^5.OutputOutput the description of the carpet as a graph. First, output a single integer n (3 \leq n \leq 3 \cdot 10^5), the total number of vertices in your graph (the vertices must be numbered from 1 to n). Then output f lines containing the description of the faces. The i-th line should describe the i-th face and contain a_i distinct integers v_{i,1}, \ldots, v_{i,a_i} (1 \leq v_{i,j} \leq n), which means that the vertices v_{i,j} and v_{i,(j \bmod{a_i})+1} are connected by an edge for any 1 \leq j \leq a_i.The graph should be planar and satisfy the restrictions described in the problem statement. Its perimeter should be the smallest possible. There should be no double edges or self-loops in the graph. The graph should be connected. Note that a solution always exists; if there are multiple solutions, output any of them.ExamplesInput 2 3 3 Output 4 2 1 4 1 2 3 Input 3 5 3 5 Output 6 1 2 3 4 5 4 5 6 1 3 4 6 5 NoteIn the first sample, the two triangular faces are connected by a single edge, which results in the minimum perimeter 4.The figure shows one possible configuration for the second sample. The minimum perimeter in this case is 3.
2 3 3
4 2 1 4 1 2 3
1 second
256 megabytes
['constructive algorithms', 'graphs', '*3200']
D. Number Discoverytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUjan needs some rest from cleaning, so he started playing with infinite sequences. He has two integers n and k. He creates an infinite sequence s by repeating the following steps. Find k smallest distinct positive integers that are not in s. Let's call them u_{1}, u_{2}, \ldots, u_{k} from the smallest to the largest. Append u_{1}, u_{2}, \ldots, u_{k} and \sum_{i=1}^{k} u_{i} to s in this order. Go back to the first step. Ujan will stop procrastinating when he writes the number n in the sequence s. Help him find the index of n in s. In other words, find the integer x such that s_{x} = n. It's possible to prove that all positive integers are included in s only once.InputThe first line contains a single integer t (1 \le t \le 10^{5}), the number of test cases.Each of the following t lines contains two integers n and k (1 \le n \le 10^{18}, 2 \le k \le 10^{6}), the number to be found in the sequence s and the parameter used to create the sequence s.OutputIn each of the t lines, output the answer for the corresponding test case.ExampleInput 2 10 2 40 5 Output 11 12 NoteIn the first sample, s = (1, 2, 3, 4, 5, 9, 6, 7, 13, 8, 10, 18, \ldots). 10 is the 11-th number here, so the answer is 11.In the second sample, s = (1, 2, 3, 4, 5, 15, 6, 7, 8, 9, 10, 40, \ldots).
2 10 2 40 5
11 12
2 seconds
256 megabytes
['math', '*3400']
C. Sum Balancetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputUjan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct. Ujan is lazy, so he will do the following reordering of the numbers exactly once. He will pick a single integer from each of the boxes, k integers in total. Then he will insert the chosen numbers — one integer in each of the boxes, so that the number of integers in each box is the same as in the beginning. Note that he may also insert an integer he picked from a box back into the same box.Ujan will be happy if the sum of the integers in each box is the same. Can he achieve this and make the boxes perfectly balanced, like all things should be?InputThe first line contains a single integer k (1 \leq k \leq 15), the number of boxes. The i-th of the next k lines first contains a single integer n_i (1 \leq n_i \leq 5\,000), the number of integers in box i. Then the same line contains n_i integers a_{i,1}, \ldots, a_{i,n_i} (|a_{i,j}| \leq 10^9), the integers in the i-th box. It is guaranteed that all a_{i,j} are distinct.OutputIf Ujan cannot achieve his goal, output "No" in a single line. Otherwise in the first line output "Yes", and then output k lines. The i-th of these lines should contain two integers c_i and p_i. This means that Ujan should pick the integer c_i from the i-th box and place it in the p_i-th box afterwards.If there are multiple solutions, output any of those.You can print each letter in any case (upper or lower).ExamplesInput 4 3 1 7 4 2 3 2 2 8 5 1 10 Output Yes 7 2 2 3 5 1 10 4 Input 2 2 3 -2 2 -1 5 Output No Input 2 2 -10 10 2 0 -20 Output Yes -10 2 -20 1 NoteIn the first sample, Ujan can put the number 7 in the 2nd box, the number 2 in the 3rd box, the number 5 in the 1st box and keep the number 10 in the same 4th box. Then the boxes will contain numbers \{1,5,4\}, \{3, 7\}, \{8,2\} and \{10\}. The sum in each box then is equal to 10.In the second sample, it is not possible to pick and redistribute the numbers in the required way.In the third sample, one can swap the numbers -20 and -10, making the sum in each box equal to -10.
4 3 1 7 4 2 3 2 2 8 5 1 10
Yes 7 2 2 3 5 1 10 4
1 second
256 megabytes
['bitmasks', 'dfs and similar', 'dp', 'graphs', '*2400']
B. 0-1 MSTtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputUjan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph.It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is connected by an edge. The weight of each edge is either 0 or 1; exactly m edges have weight 1, and all others have weight 0.Since Ujan doesn't really want to organize his notes, he decided to find the weight of the minimum spanning tree of the graph. (The weight of a spanning tree is the sum of all its edges.) Can you find the answer for Ujan so he stops procrastinating?InputThe first line of the input contains two integers n and m (1 \leq n \leq 10^5, 0 \leq m \leq \min(\frac{n(n-1)}{2},10^5)), the number of vertices and the number of edges of weight 1 in the graph. The i-th of the next m lines contains two integers a_i and b_i (1 \leq a_i, b_i \leq n, a_i \neq b_i), the endpoints of the i-th edge of weight 1.It is guaranteed that no edge appears twice in the input.OutputOutput a single integer, the weight of the minimum spanning tree of the graph.ExamplesInput 6 11 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 Output 2 Input 3 0 Output 0 NoteThe graph from the first sample is shown below. Dashed edges have weight 0, other edges have weight 1. One of the minimum spanning trees is highlighted in orange and has total weight 2. In the second sample, all edges have weight 0 so any spanning tree has total weight 0.
6 11 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6
2
1 second
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'sortings', '*1900']
A. Tile Paintingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputUjan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to paint the path from his house to the gate.The path consists of n consecutive tiles, numbered from 1 to n. Ujan will paint each tile in some color. He will consider the path aesthetic if for any two different tiles with numbers i and j, such that |j - i| is a divisor of n greater than 1, they have the same color. Formally, the colors of two tiles with numbers i and j should be the same if |i-j| > 1 and n \bmod |i-j| = 0 (where x \bmod y is the remainder when dividing x by y).Ujan wants to brighten up space. What is the maximum number of different colors that Ujan can use, so that the path is aesthetic?InputThe first line of input contains a single integer n (1 \leq n \leq 10^{12}), the length of the path.OutputOutput a single integer, the maximum possible number of colors that the path can be painted in.ExamplesInput 4 Output 2 Input 5 Output 5 NoteIn the first sample, two colors is the maximum number. Tiles 1 and 3 should have the same color since 4 \bmod |3-1| = 0. Also, tiles 2 and 4 should have the same color since 4 \bmod |4-2| = 0.In the second sample, all five colors can be used.
4
2
1 second
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1500']
F. Footballtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n football teams in the world. The Main Football Organization (MFO) wants to host at most m games. MFO wants the i-th game to be played between the teams a_i and b_i in one of the k stadiums. Let s_{ij} be the numbers of games the i-th team played in the j-th stadium. MFO does not want a team to have much more games in one stadium than in the others. Therefore, for each team i, the absolute difference between the maximum and minimum among s_{i1}, s_{i2}, \ldots, s_{ik} should not exceed 2.Each team has w_i — the amount of money MFO will earn for each game of the i-th team. If the i-th team plays l games, MFO will earn w_i \cdot l.MFO needs to find what games in what stadiums they need to host in order to earn as much money as possible, not violating the rule they set.However, this problem is too complicated for MFO. Therefore, they are asking you to help them.InputThe first line contains three integers n, m, k (3 \leq n \leq 100, 0 \leq m \leq 1\,000, 1 \leq k \leq 1\,000) — the number of teams, the number of games, and the number of stadiums.The second line contains n integers w_1, w_2, \ldots, w_n (1 \leq w_i \leq 1\,000) — the amount of money MFO will earn for each game of the i-th game.Each of the following m lines contains two integers a_i and b_i (1 \leq a_i, b_i \leq n, a_i \neq b_i) — the teams that can play the i-th game. It is guaranteed that each pair of teams can play at most one game.OutputFor each game in the same order, print t_i (1 \leq t_i \leq k) — the number of the stadium, in which a_i and b_i will play the game. If the i-th game should not be played, t_i should be equal to 0.If there are multiple answers, print any.ExampleInput 7 11 3 4 7 8 10 10 9 3 6 2 6 1 7 6 4 3 4 6 3 1 5 3 7 5 7 3 4 2 1 4 Output 3 2 1 1 3 1 2 1 2 3 2 NoteOne of possible solutions to the example is shown below:
7 11 3 4 7 8 10 10 9 3 6 2 6 1 7 6 4 3 4 6 3 1 5 3 7 5 7 3 4 2 1 4
3 2 1 1 3 1 2 1 2 3 2
1 second
256 megabytes
['graphs', '*3100']
F. Swiper, no swiping!time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputI'm the Map, I'm the Map! I'm the MAP!!!MapIn anticipation of new adventures Boots wanted to do a good deed. After discussion with the Map and Backpack, they decided to gift Dora a connected graph. After a long search, Boots chose t graph's variants, which Dora might like. However fox Swiper wants to spoil his plan.The Swiper knows, that Dora now is only able to count up to 3, so he has came up with a following idea. He wants to steal some non-empty set of vertices, so that the Dora won't notice the loss. He has decided to steal some non-empty set of vertices, so that after deletion of the stolen vertices and edges adjacent to them, every remaining vertex wouldn't change it's degree modulo 3. The degree of a vertex is the number of edges it is adjacent to. It would've been suspicious to steal all the vertices, so Swiper needs another plan.Boots are sure, that the crime can not be allowed. However they are afraid, that they won't be able to handle this alone. So Boots decided to ask for your help. Please determine for every graph's variant whether the Swiper can perform the theft or not.InputThe first line contains a single integer t (1 \le t \le 100\,000) — the number of graph variants.The first line of each variant contains integers n, m (1 \le n \le 500\,000, 0 \le m \le 500\,000), the number of vertexes and edges in the graph.Then m lines follow, each containing integers a_i, b_i (1 \le a_i, b_i \le n), the indices of the vertices connected with a corresponding edge.It's guaranteed, that the graph is connected and doesn't contain multiple edges or self-loops.It's guaranteed, that the sum of n over all variants is at most 500\,000 and that the sum of m over all variants is at most 500\,000.Descriptions of graph's variants are separated with an empty line.OutputFor each variant: In case the answer exists, print "Yes" and then the answer itself.The first line should contain an integer c (1 < c < n), the number of vertices the Crook can steal, without Dora noticing the loss. On the next line print c distinct integers, the indices of the graph's vertices in arbitrary order. Otherwise print "No". In case there are several correct ways to steal the vertices, print any of them.Please note, that it's not required to maximize the number of stolen vertices.ExampleInput 3 3 3 1 2 2 3 3 1 6 6 1 2 1 3 2 3 2 5 2 6 2 4 8 12 1 2 1 3 2 3 1 4 4 5 5 1 3 6 3 7 3 8 6 1 7 1 8 1 Output No Yes 3 4 5 6 Yes 3 6 7 8 NoteThe picture below shows the third variant from the example test. The set of the vertices the Crook can steal is denoted with bold.
3 3 3 1 2 2 3 3 1 6 6 1 2 1 3 2 3 2 5 2 6 2 4 8 12 1 2 1 3 2 3 1 4 4 5 5 1 3 6 3 7 3 8 6 1 7 1 8 1
No Yes 3 4 5 6 Yes 3 6 7 8
2 seconds
512 megabytes
['graphs', 'implementation', '*3400']
E. Turtletime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKolya has a turtle and a field of size 2 \times n. The field rows are numbered from 1 to 2 from top to bottom, while the columns are numbered from 1 to n from left to right.Suppose in each cell of the field there is a lettuce leaf. The energy value of lettuce leaf in row i and column j is equal to a_{i,j}. The turtle is initially in the top left cell and wants to reach the bottom right cell. The turtle can only move right and down and among all possible ways it will choose a way, maximizing the total energy value of lettuce leaves (in case there are several such paths, it will choose any of them).Kolya is afraid, that if turtle will eat too much lettuce, it can be bad for its health. So he wants to reorder lettuce leaves in the field, so that the energetic cost of leaves eaten by turtle will be minimized.InputThe first line contains an integer n (2 \le n \le 25) — the length of the field.The second line contains n integers a_{1, i} (0 \le a_{1, i} \le 50\,000), the energetic cost of lettuce leaves in the first row of the field.The third line contains n integers a_{2, i} (0 \le a_{2, i} \le 50\,000), the energetic cost of lettuce leaves in the second row of the field.OutputPrint two lines with n integers in each — the optimal reordering of lettuce from the input data.In case there are several optimal ways to reorder lettuce, print any of them.ExamplesInput 2 1 4 2 3 Output 1 3 4 2 Input 3 0 0 0 0 0 0 Output 0 0 0 0 0 0 Input 3 1 0 1 0 0 0 Output 0 0 1 0 1 0 NoteIn the first example, after reordering, the turtle will eat lettuce with total energetic cost 1+4+2 = 7.In the second example, the turtle will eat lettuce with energetic cost equal 0.In the third example, after reordering, the turtle will eat lettuce with total energetic cost equal 1.
2 1 4 2 3
1 3 4 2
5 seconds
512 megabytes
['dp', 'implementation', '*3100']
D. Catowice Citytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn the Catowice city next weekend the cat contest will be held. However, the jury members and the contestants haven't been selected yet. There are n residents and n cats in the Catowice, and each resident has exactly one cat living in his house. The residents and cats are numbered with integers from 1 to n, where the i-th cat is living in the house of i-th resident.Each Catowice resident is in friendship with several cats, including the one living in his house. In order to conduct a contest, at least one jury member is needed and at least one cat contestant is needed. Of course, every jury member should know none of the contestants. For the contest to be successful, it's also needed that the number of jury members plus the number of contestants is equal to n.Please help Catowice residents to select the jury and the contestants for the upcoming competition, or determine that it's impossible to do.InputThe first line contains an integer t (1 \le t \le 100\,000), the number of test cases. Then description of t test cases follow, where each description is as follows:The first line contains integers n and m (1 \le n \le m \le 10^6), the number of Catowice residents and the number of friendship pairs between residents and cats.Each of the next m lines contains integers a_i and b_i (1 \le a_i, b_i \le n), denoting that a_i-th resident is acquaintances with b_i-th cat. It's guaranteed that each pair of some resident and some cat is listed at most once.It's guaranteed, that for every i there exists a pair between i-th resident and i-th cat.Different test cases are separated with an empty line.It's guaranteed, that the sum of n over all test cases is at most 10^6 and that the sum of m over all test cases is at most 10^6.OutputFor every test case print: "No", if it's impossible to select the jury and contestants. Otherwise print "Yes".In the second line print two integers j and p (1 \le j, 1 \le p, j + p = n) — the number of jury members and the number of contest participants.In the third line print j distinct integers from 1 to n, the indices of the residents forming a jury.In the fourth line print p distinct integers from 1 to n, the indices of the cats, which will participate in the contest.In case there are several correct answers, print any of them. ExampleInput 4 3 4 1 1 2 2 3 3 1 3 3 7 1 1 1 2 1 3 2 2 3 1 3 2 3 3 1 1 1 1 2 4 1 1 1 2 2 1 2 2 Output Yes 2 1 1 3 2 Yes 1 2 2 1 3 No No NoteIn the first test case, we can select the first and the third resident as a jury. Both of them are not acquaintances with a second cat, so we can select it as a contestant.In the second test case, we can select the second resident as a jury. He is not an acquaintances with a first and a third cat, so they can be selected as contestants.In the third test case, the only resident is acquaintances with the only cat, so they can't be in the contest together. So it's not possible to make a contest with at least one jury and at least one cat.In the fourth test case, each resident is acquaintances with every cat, so it's again not possible to make a contest with at least one jury and at least one cat.
4 3 4 1 1 2 2 3 3 1 3 3 7 1 1 1 2 1 3 2 2 3 1 3 2 3 3 1 1 1 1 2 4 1 1 1 2 2 1 2 2
Yes 2 1 1 3 2 Yes 1 2 2 1 3 No No
2 seconds
512 megabytes
['2-sat', 'dfs and similar', 'graph matchings', 'graphs', '*2400']
C. Queue in the Traintime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n seats in the train's car and there is exactly one passenger occupying every seat. The seats are numbered from 1 to n from left to right. The trip is long, so each passenger will become hungry at some moment of time and will go to take boiled water for his noodles. The person at seat i (1 \leq i \leq n) will decide to go for boiled water at minute t_i.Tank with a boiled water is located to the left of the 1-st seat. In case too many passengers will go for boiled water simultaneously, they will form a queue, since there can be only one passenger using the tank at each particular moment of time. Each passenger uses the tank for exactly p minutes. We assume that the time it takes passengers to go from their seat to the tank is negligibly small. Nobody likes to stand in a queue. So when the passenger occupying the i-th seat wants to go for a boiled water, he will first take a look on all seats from 1 to i - 1. In case at least one of those seats is empty, he assumes that those people are standing in a queue right now, so he would be better seating for the time being. However, at the very first moment he observes that all seats with numbers smaller than i are busy, he will go to the tank.There is an unspoken rule, that in case at some moment several people can go to the tank, than only the leftmost of them (that is, seating on the seat with smallest number) will go to the tank, while all others will wait for the next moment.Your goal is to find for each passenger, when he will receive the boiled water for his noodles.InputThe first line contains integers n and p (1 \leq n \leq 100\,000, 1 \leq p \leq 10^9) — the number of people and the amount of time one person uses the tank.The second line contains n integers t_1, t_2, \dots, t_n (0 \leq t_i \leq 10^9) — the moments when the corresponding passenger will go for the boiled water.OutputPrint n integers, where i-th of them is the time moment the passenger on i-th seat will receive his boiled water.ExampleInput 5 314 0 310 942 628 0 Output 314 628 1256 942 1570 NoteConsider the example.At the 0-th minute there were two passengers willing to go for a water, passenger 1 and 5, so the first passenger has gone first, and returned at the 314-th minute. At this moment the passenger 2 was already willing to go for the water, so the passenger 2 has gone next, and so on. In the end, 5-th passenger was last to receive the boiled water.
5 314 0 310 942 628 0
314 628 1256 942 1570
1 second
512 megabytes
['data structures', 'greedy', 'implementation', '*2300']
B. The World Is Just a Programming Task (Hard Version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version, n \le 300\,000.Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya believes, that the beauty of the bracket string is a number of its cyclical shifts, which form a correct bracket sequence.To digress from his problems, Vasya decided to select two positions of the string (not necessarily distinct) and swap characters located at this positions with each other. Vasya will apply this operation exactly once. He is curious what is the maximum possible beauty he can achieve this way. Please help him.We remind that bracket sequence s is called correct if: s is empty; s is equal to "(t)", where t is correct bracket sequence; s is equal to t_1 t_2, i.e. concatenation of t_1 and t_2, where t_1 and t_2 are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not.The cyclical shift of the string s of length n by k (0 \leq k < n) is a string formed by a concatenation of the last k symbols of the string s with the first n - k symbols of string s. For example, the cyclical shift of string "(())()" by 2 equals "()(())".Cyclical shifts i and j are considered different, if i \ne j.InputThe first line contains an integer n (1 \le n \le 300\,000), the length of the string.The second line contains a string, consisting of exactly n characters, where each of the characters is either "(" or ")".OutputThe first line should contain a single integer — the largest beauty of the string, which can be achieved by swapping some two characters.The second line should contain integers l and r (1 \leq l, r \leq n) — the indices of two characters, which should be swapped in order to maximize the string's beauty.In case there are several possible swaps, print any of them.ExamplesInput 10 ()()())(() Output 5 8 7 Input 12 )(()(()())() Output 4 5 10 Input 6 )))(() Output 0 1 1 NoteIn the first example, we can swap 7-th and 8-th character, obtaining a string "()()()()()". The cyclical shifts by 0, 2, 4, 6, 8 of this string form a correct bracket sequence.In the second example, after swapping 5-th and 10-th character, we obtain a string ")(())()()(()". The cyclical shifts by 11, 7, 5, 3 of this string form a correct bracket sequence.In the third example, swap of any two brackets results in 0 cyclical shifts being correct bracket sequences.
10 ()()())(()
5 8 7
1 second
512 megabytes
['implementation', '*2500']
A. Ivan the Fool and the Probability Theorytime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.Ivan's brothers spent some time trying to explain that it's not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 10^9 + 7.InputThe only line contains two integers n and m (1 \le n, m \le 100\,000), the number of rows and the number of columns of the field.OutputPrint one integer, the number of random pictures modulo 10^9 + 7.ExampleInput 2 3 Output 8 NoteThe picture below shows all possible random pictures of size 2 by 3.
2 3
8
1 second
512 megabytes
['combinatorics', 'dp', 'math', '*1700']
G. Adilbek and the Watering Systemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek has to water his garden. He is going to do it with the help of a complex watering system: he only has to deliver water to it, and the mechanisms will do all the remaining job.The watering system consumes one liter of water per minute (if there is no water, it is not working). It can hold no more than c liters. Adilbek has already poured c_0 liters of water into the system. He is going to start watering the garden right now and water it for m minutes, and the watering system should contain at least one liter of water at the beginning of the i-th minute (for every i from 0 to m - 1).Now Adilbek wonders what he will do if the watering system runs out of water. He called n his friends and asked them if they are going to bring some water. The i-th friend answered that he can bring no more than a_i liters of water; he will arrive at the beginning of the t_i-th minute and pour all the water he has into the system (if the system cannot hold such amount of water, the excess water is poured out); and then he will ask Adilbek to pay b_i dollars for each liter of water he has brought. You may assume that if a friend arrives at the beginning of the t_i-th minute and the system runs out of water at the beginning of the same minute, the friend pours his water fast enough so that the system does not stop working.Of course, Adilbek does not want to pay his friends, but he has to water the garden. So he has to tell his friends how much water should they bring. Formally, Adilbek wants to choose n integers k_1, k_2, ..., k_n in such a way that: if each friend i brings exactly k_i liters of water, then the watering system works during the whole time required to water the garden; the sum \sum\limits_{i = 1}^{n} k_i b_i is minimum possible. Help Adilbek to determine the minimum amount he has to pay his friends or determine that Adilbek not able to water the garden for m minutes.You have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 5 \cdot 10^5) – the number of queries.The first line of each query contains four integers n, m, c and c_0 (0 \le n \le 5 \cdot 10^5, 2 \le m \le 10^9, 1 \le c_0 \le c \le 10^9) — the number of friends, the number of minutes of watering, the capacity of the watering system and the number of liters poured by Adilbek.Each of the next n lines contains three integers t_i, a_i, b_i ( 0 < t_i < m, 1 \le a_i \le c, 1 \le b_i \le 10^9) — the i-th friend's arrival time, the maximum amount of water i-th friend can bring and the cost of 1 liter from i-th friend.It is guaranteed that sum of all n over all queries does not exceed 5 \cdot 10^5.OutputFor each query print one integer — the minimum amount Adilbek has to pay his friends, or -1 if Adilbek is not able to water the garden for m minutes.ExampleInput 4 1 5 4 2 2 4 2 0 4 5 4 2 5 3 1 1 2 4 3 1 3 2 3 5 1 2 1 1 1 4 3 Output 6 0 -1 4
4 1 5 4 2 2 4 2 0 4 5 4 2 5 3 1 1 2 4 3 1 3 2 3 5 1 2 1 1 1 4 3
6 0 -1 4
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*2700']
F. The Maximum Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAssume that you have k one-dimensional segments s_1, s_2, \dots s_k (each segment is denoted by two integers — its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i \neq j) if and only if the segments s_i and s_j intersect (there exists at least one point that belongs to both of them).For example, if s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18], then the resulting graph is the following: A tree of size m is good if it is possible to choose m one-dimensional segments so that the graph built on these segments coincides with this tree.You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree.Note that you have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 15 \cdot 10^4) — the number of the queries. The first line of each query contains one integer n (2 \le n \le 3 \cdot 10^5) — the number of vertices in the tree.Each of the next n - 1 lines contains two integers x and y (1 \le x, y \le n) denoting an edge between vertices x and y. It is guaranteed that the given graph is a tree.It is guaranteed that the sum of all n does not exceed 3 \cdot 10^5.OutputFor each query print one integer — the maximum size of a good subtree of the given tree.ExampleInput 1 10 1 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 Output 8 NoteIn the first query there is a good subtree of size 8. The vertices belonging to this subtree are {9, 4, 10, 2, 5, 1, 6, 3}.
1 10 1 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10
8
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'trees', '*2200']
E. Keyboard Purchasetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a password which you often type — a string s of length n. Every character of this string is one of the first m lowercase Latin letters.Since you spend a lot of time typing it, you want to buy a new keyboard.A keyboard is a permutation of the first m Latin letters. For example, if m = 3, then there are six possible keyboards: abc, acb, bac, bca, cab and cba.Since you type your password with one finger, you need to spend time moving your finger from one password character to the next. The time to move from character s_i to character s_{i+1} is equal to the distance between these characters on keyboard. The total time you have to spend typing the password with a keyboard is called the slowness of this keyboard.More formaly, the slowness of keyboard is equal to \sum\limits_{i=2}^{n} |pos_{s_{i-1}} - pos_{s_i} |, where pos_x is position of letter x in keyboard.For example, if s is aacabc and the keyboard is bac, then the total time of typing this password is |pos_a - pos_a| + |pos_a - pos_c| + |pos_c - pos_a| + |pos_a - pos_b| + |pos_b - pos_c| = |2 - 2| + |2 - 3| + |3 - 2| + |2 - 1| + |1 - 3| = 0 + 1 + 1 + 1 + 2 = 5.Before buying a new keyboard you want to know the minimum possible slowness that the keyboard can have. InputThe first line contains two integers n and m (1 \le n \le 10^5, 1 \le m \le 20).The second line contains the string s consisting of n characters. Each character is one of the first m Latin letters (lowercase).OutputPrint one integer – the minimum slowness a keyboard can have.ExamplesInput 6 3 aacabc Output 5 Input 6 4 aaaaaa Output 0 Input 15 4 abacabadabacaba Output 16 NoteThe first test case is considered in the statement.In the second test case the slowness of any keyboard is 0.In the third test case one of the most suitable keyboards is bacd.
6 3 aacabc
5
1 second
256 megabytes
['bitmasks', 'dp', '*2200']
D. AB-stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe string t_1t_2 \dots t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: t = AABBB (letters t_1, t_2 belong to palindrome t_1 \dots t_2 and letters t_3, t_4, t_5 belong to palindrome t_3 \dots t_5); t = ABAA (letters t_1, t_2, t_3 belong to palindrome t_1 \dots t_3 and letter t_4 belongs to palindrome t_3 \dots t_4); t = AAAAA (all letters belong to palindrome t_1 \dots t_5); You are given a string s of length n, consisting of only letters A and B.You have to calculate the number of good substrings of string s.InputThe first line contains one integer n (1 \le n \le 3 \cdot 10^5) — the length of the string s.The second line contains the string s, consisting of letters A and B.OutputPrint one integer — the number of good substrings of string s.ExamplesInput 5 AABBB Output 6 Input 3 AAA Output 3 Input 7 AAABABB Output 15 NoteIn the first test case there are six good substrings: s_1 \dots s_2, s_1 \dots s_4, s_1 \dots s_5, s_3 \dots s_4, s_3 \dots s_5 and s_4 \dots s_5.In the second test case there are three good substrings: s_1 \dots s_2, s_1 \dots s_3 and s_2 \dots s_3.
5 AABBB
6
2 seconds
256 megabytes
['binary search', 'combinatorics', 'dp', 'strings', '*1900']
C. Standard Free2playtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a game where your character should overcome different obstacles. The current problem is to come down from a cliff. The cliff has height h, and there is a moving platform on each height x from 1 to h.Each platform is either hidden inside the cliff or moved out. At first, there are n moved out platforms on heights p_1, p_2, \dots, p_n. The platform on height h is moved out (and the character is initially standing there).If you character is standing on some moved out platform on height x, then he can pull a special lever, which switches the state of two platforms: on height x and x - 1. In other words, the platform you are currently standing on will hide in the cliff and the platform one unit below will change it state: it will hide if it was moved out or move out if it was hidden. In the second case, you will safely land on it. Note that this is the only way to move from one platform to another.Your character is quite fragile, so it can safely fall from the height no more than 2. In other words falling from the platform x to platform x - 2 is okay, but falling from x to x - 3 (or lower) is certain death. Sometimes it's not possible to come down from the cliff, but you can always buy (for donate currency) several magic crystals. Each magic crystal can be used to change the state of any single platform (except platform on height h, which is unaffected by the crystals). After being used, the crystal disappears.What is the minimum number of magic crystal you need to buy to safely land on the 0 ground level?InputThe first line contains one integer q (1 \le q \le 100) — the number of queries. Each query contains two lines and is independent of all other queries.The first line of each query contains two integers h and n (1 \le h \le 10^9, 1 \le n \le \min(h, 2 \cdot 10^5)) — the height of the cliff and the number of moved out platforms.The second line contains n integers p_1, p_2, \dots, p_n (h = p_1 > p_2 > \dots > p_n \ge 1) — the corresponding moved out platforms in the descending order of their heights.The sum of n over all queries does not exceed 2 \cdot 10^5.OutputFor each query print one integer — the minimum number of magic crystals you have to spend to safely come down on the ground level (with height 0).ExampleInput 4 3 2 3 1 8 6 8 7 6 5 3 2 9 6 9 8 5 4 3 1 1 1 1 Output 0 1 2 0
4 3 2 3 1 8 6 8 7 6 5 3 2 9 6 9 8 5 4 3 1 1 1 1
0 1 2 0
2 seconds
256 megabytes
['dp', 'greedy', 'math', '*1600']
B. Kill 'Em Alltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let's assume that the point x = 0 is where these parts meet.The right part of the corridor is filled with n monsters — for each monster, its initial coordinate x_i is given (and since all monsters are in the right part, every x_i is positive).The left part of the corridor is filled with crusher traps. If some monster enters the left part of the corridor or the origin (so, its current coordinate becomes less than or equal to 0), it gets instantly killed by a trap.The main weapon Ivan uses to kill the monsters is the Phoenix Rod. It can launch a missile that explodes upon impact, obliterating every monster caught in the explosion and throwing all other monsters away from the epicenter. Formally, suppose that Ivan launches a missile so that it explodes in the point c. Then every monster is either killed by explosion or pushed away. Let some monster's current coordinate be y, then: if c = y, then the monster is killed; if y < c, then the monster is pushed r units to the left, so its current coordinate becomes y - r; if y > c, then the monster is pushed r units to the right, so its current coordinate becomes y + r. Ivan is going to kill the monsters as follows: choose some integer point d and launch a missile into that point, then wait until it explodes and all the monsters which are pushed to the left part of the corridor are killed by crusher traps, then, if at least one monster is still alive, choose another integer point (probably the one that was already used) and launch a missile there, and so on.What is the minimum number of missiles Ivan has to launch in order to kill all of the monsters? You may assume that every time Ivan fires the Phoenix Rod, he chooses the impact point optimally.You have to answer q independent queries.InputThe first line contains one integer q (1 \le q \le 10^5) — the number of queries.The first line of each query contains two integers n and r (1 \le n, r \le 10^5) — the number of enemies and the distance that the enemies are thrown away from the epicenter of the explosion.The second line of each query contains n integers x_i (1 \le x_i \le 10^5) — the initial positions of the monsters.It is guaranteed that sum of all n over all queries does not exceed 10^5.OutputFor each query print one integer — the minimum number of shots from the Phoenix Rod required to kill all monsters.ExampleInput 2 3 2 1 3 5 4 1 5 2 3 5 Output 2 2 NoteIn the first test case, Ivan acts as follows: choose the point 3, the first monster dies from a crusher trap at the point -1, the second monster dies from the explosion, the third monster is pushed to the point 7; choose the point 7, the third monster dies from the explosion. In the second test case, Ivan acts as follows: choose the point 5, the first and fourth monsters die from the explosion, the second monster is pushed to the point 1, the third monster is pushed to the point 2; choose the point 2, the first monster dies from a crusher trap at the point 0, the second monster dies from the explosion.
2 3 2 1 3 5 4 1 5 2 3 5
2 2
1 second
256 megabytes
['greedy', 'sortings', '*1300']
A. Prime Subtractiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers x and y (it is guaranteed that x > y). You may choose any prime integer p and subtract it any number of times from x. Is it possible to make x equal to y?Recall that a prime number is a positive integer that has exactly two positive divisors: 1 and this integer itself. The sequence of prime numbers starts with 2, 3, 5, 7, 11.Your program should solve t independent test cases.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Then t lines follow, each describing a test case. Each line contains two integers x and y (1 \le y < x \le 10^{18}).OutputFor each test case, print YES if it is possible to choose a prime number p and subtract it any number of times from x so that x becomes equal to y. Otherwise, print NO.You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).ExampleInput 4 100 98 42 32 1000000000000000000 1 41 40 Output YES YES YES NO NoteIn the first test of the example you may choose p = 2 and subtract it once.In the second test of the example you may choose p = 5 and subtract it twice. Note that you cannot choose p = 7, subtract it, then choose p = 3 and subtract it again.In the third test of the example you may choose p = 3 and subtract it 333333333333333333 times.
4 100 98 42 32 1000000000000000000 1 41 40
YES YES YES NO
2 seconds
256 megabytes
['math', 'number theory', '*900']
H. Balanced Reversalstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have two strings a and b of equal even length n consisting of characters 0 and 1.We're in the endgame now. To finally make the universe perfectly balanced, you need to make strings a and b equal.In one step, you can choose any prefix of a of even length and reverse it. Formally, if a = a_1 a_2 \ldots a_n, you can choose a positive even integer p \le n and set a to a_p a_{p-1} \ldots a_1 a_{p+1} a_{p+2} \ldots a_n.Find a way to make a equal to b using at most n + 1 reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.InputThe first line contains a single integer t (1 \le t \le 2000), denoting the number of test cases.Each test case consists of two lines. The first line contains a string a of length n, and the second line contains a string b of the same length (2 \le n \le 4000; n \bmod 2 = 0). Both strings consist of characters 0 and 1.The sum of n over all t test cases doesn't exceed 4000.OutputFor each test case, if it's impossible to make a equal to b in at most n + 1 reversals, output a single integer -1.Otherwise, output an integer k (0 \le k \le n + 1), denoting the number of reversals in your sequence of steps, followed by k even integers p_1, p_2, \ldots, p_k (2 \le p_i \le n; p_i \bmod 2 = 0), denoting the lengths of prefixes of a to be reversed, in chronological order.Note that k doesn't have to be minimized. If there are many solutions, output any of them.ExampleInput 4 0100011011 1101011000 10101010 10101010 0011 1001 100011 110010 Output 3 6 4 10 0 -1 7 2 6 2 6 2 2 6 NoteIn the first test case, string a changes as follows: after the first reversal: 1000101011; after the second reversal: 0001101011; after the third reversal: 1101011000.
4 0100011011 1101011000 10101010 10101010 0011 1001 100011 110010
3 6 4 10 0 -1 7 2 6 2 6 2 2 6
2 seconds
512 megabytes
['constructive algorithms', '*3300']
G. Balanced Distributiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n friends living on a circular street. The friends and their houses are numbered clockwise from 0 to n-1.Initially person i has a_i stones. The friends want to make the distribution of stones among them perfectly balanced: everyone should possess the same number of stones.The only way to change the distribution of stones is by conducting meetings. During a meeting, people from exactly k consecutive houses (remember that the street is circular) gather at the same place and bring all their stones with them. All brought stones may be redistributed among people attending the meeting arbitrarily. The total number of stones they possess before the meeting and after the meeting must stay the same. After the meeting, everyone returns to their home.Find a way to make the distribution of stones perfectly balanced conducting as few meetings as possible.InputThe first line contains two integers n and k (2 \le k < n \le 10^5), denoting the number of friends and the size of each meeting.The second line contains n integers a_0, a_1, \ldots, a_{n-1} (0 \le a_i \le 10^4), denoting the number of stones people initially have.The sum of all a_i is divisible by n.OutputOutput the minimum number of meetings m (m \ge 0), followed by m descriptions of meetings in chronological order.The i-th description must consist of an integer s_i (0 \le s_i < n), followed by k non-negative integers b_{i, 0}, b_{i, 1}, \ldots, b_{i, k-1} (b_{i, j} \ge 0). Such a description denotes a meeting of people s_i, (s_i + 1) \bmod n, \ldots, (s_i + k - 1) \bmod n, and b_{i,j} denotes the number of stones person (s_i + j) \bmod n must have after the i-th meeting. The sum of b_{i, j} must match the total number of stones owned by these people before the i-th meeting.We can show that a solution exists for any valid input, and any correct output contains at most 10^7 non-whitespace characters.ExamplesInput 6 3 2 6 1 10 3 2 Output 3 2 7 3 4 5 4 4 2 1 4 4 4 Input 11 4 1 0 1 0 0 4 4 2 4 3 3 Output 3 3 2 2 2 2 8 2 2 2 5 10 2 2 2 2 NoteIn the first example, the distribution of stones changes as follows: after the first meeting: 2 6 \mathbf{7} \mathbf{3} \mathbf{4} 2; after the second meeting: \mathbf{4} \mathbf{2} 7 3 4 \mathbf{4}; after the third meeting: 4 \mathbf{4} \mathbf{4} \mathbf{4} 4 4. In the second example, the distribution of stones changes as follows: after the first meeting: 1 0 1 \mathbf{2} \mathbf{2} \mathbf{2} \mathbf{2} 2 4 3 3; after the second meeting: \mathbf{5} 0 1 2 2 2 2 2 \mathbf{2} \mathbf{2} \mathbf{2}; after the third meeting: \mathbf{2} \mathbf{2} \mathbf{2} 2 2 2 2 2 2 2 \mathbf{2}.
6 3 2 6 1 10 3 2
3 2 7 3 4 5 4 4 2 1 4 4 4
2 seconds
512 megabytes
['data structures', 'dp', 'greedy', '*3500']
F. Balanced Domino Placementstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a square grid with h rows and w columns with some dominoes on it. Each domino covers exactly two cells of the grid that share a common side. Every cell is covered by at most one domino.Let's call a placement of dominoes on the grid perfectly balanced if no row and no column contains a pair of cells covered by two different dominoes. In other words, every row and column may contain no covered cells, one covered cell, or two covered cells that belong to the same domino.You are given a perfectly balanced placement of dominoes on a grid. Find the number of ways to place zero or more extra dominoes on this grid to keep the placement perfectly balanced. Output this number modulo 998\,244\,353.InputThe first line contains three integers h, w, and n (1 \le h, w \le 3600; 0 \le n \le 2400), denoting the dimensions of the grid and the number of already placed dominoes. The rows are numbered from 1 to h, and the columns are numbered from 1 to w.Each of the next n lines contains four integers r_{i, 1}, c_{i, 1}, r_{i, 2}, c_{i, 2} (1 \le r_{i, 1} \le r_{i, 2} \le h; 1 \le c_{i, 1} \le c_{i, 2} \le w), denoting the row id and the column id of the cells covered by the i-th domino. Cells (r_{i, 1}, c_{i, 1}) and (r_{i, 2}, c_{i, 2}) are distinct and share a common side.The given domino placement is perfectly balanced.OutputOutput the number of ways to place zero or more extra dominoes on the grid to keep the placement perfectly balanced, modulo 998\,244\,353.ExamplesInput 5 7 2 3 1 3 2 4 4 4 5 Output 8 Input 5 4 2 1 2 2 2 4 3 4 4 Output 1 Input 23 42 0 Output 102848351 NoteIn the first example, the initial grid looks like this:Here are 8 ways to place zero or more extra dominoes to keep the placement perfectly balanced:In the second example, the initial grid looks like this:No extra dominoes can be placed here.
5 7 2 3 1 3 2 4 4 4 5
8
2 seconds
512 megabytes
['combinatorics', 'dp', '*2600']
E. Balanced Binary Search Treestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecall that a binary search tree is a rooted binary tree, whose nodes each store a key and each have at most two distinguished subtrees, left and right. The key in each node must be greater than any key stored in the left subtree, and less than any key stored in the right subtree.The depth of a vertex is the number of edges on the simple path from the vertex to the root. In particular, the depth of the root is 0.Let's call a binary search tree perfectly balanced if there doesn't exist a binary search tree with the same number of vertices that has a strictly smaller sum of depths of its vertices.Let's call a binary search tree with integer keys striped if both of the following conditions are satisfied for every vertex v: If v has a left subtree whose root is u, then the parity of the key of v is different from the parity of the key of u. If v has a right subtree whose root is w, then the parity of the key of v is the same as the parity of the key of w. You are given a single integer n. Find the number of perfectly balanced striped binary search trees with n vertices that have distinct integer keys between 1 and n, inclusive. Output this number modulo 998\,244\,353.InputThe only line contains a single integer n (1 \le n \le 10^6), denoting the required number of vertices.OutputOutput the number of perfectly balanced striped binary search trees with n vertices and distinct integer keys between 1 and n, inclusive, modulo 998\,244\,353.ExamplesInput 4 Output 1 Input 3 Output 0 NoteIn the first example, this is the only tree that satisfies the conditions: In the second example, here are various trees that don't satisfy some condition:
4
1
3 seconds
512 megabytes
['dp', 'math', '*2400']
D. Balanced Playlisttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour favorite music streaming platform has formed a perfectly balanced playlist exclusively for you. The playlist consists of n tracks numbered from 1 to n. The playlist is automatic and cyclic: whenever track i finishes playing, track i+1 starts playing automatically; after track n goes track 1.For each track i, you have estimated its coolness a_i. The higher a_i is, the cooler track i is.Every morning, you choose a track. The playlist then starts playing from this track in its usual cyclic fashion. At any moment, you remember the maximum coolness x of already played tracks. Once you hear that a track with coolness strictly less than \frac{x}{2} (no rounding) starts playing, you turn off the music immediately to keep yourself in a good mood.For each track i, find out how many tracks you will listen to before turning off the music if you start your morning with track i, or determine that you will never turn the music off. Note that if you listen to the same track several times, every time must be counted.InputThe first line contains a single integer n (2 \le n \le 10^5), denoting the number of tracks in the playlist.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9), denoting coolnesses of the tracks.OutputOutput n integers c_1, c_2, \ldots, c_n, where c_i is either the number of tracks you will listen to if you start listening from track i or -1 if you will be listening to music indefinitely.ExamplesInput 4 11 5 2 7 Output 1 1 3 2 Input 4 3 2 5 3 Output 5 4 3 6 Input 3 4 3 6 Output -1 -1 -1 NoteIn the first example, here is what will happen if you start with... track 1: listen to track 1, stop as a_2 < \frac{a_1}{2}. track 2: listen to track 2, stop as a_3 < \frac{a_2}{2}. track 3: listen to track 3, listen to track 4, listen to track 1, stop as a_2 < \frac{\max(a_3, a_4, a_1)}{2}. track 4: listen to track 4, listen to track 1, stop as a_2 < \frac{\max(a_4, a_1)}{2}. In the second example, if you start with track 4, you will listen to track 4, listen to track 1, listen to track 2, listen to track 3, listen to track 4 again, listen to track 1 again, and stop as a_2 < \frac{max(a_4, a_1, a_2, a_3, a_4, a_1)}{2}. Note that both track 1 and track 4 are counted twice towards the result.
4 11 5 2 7
1 1 3 2
2 seconds
512 megabytes
['binary search', 'data structures', 'implementation', '*2000']
C2. Balanced Removals (Harder)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version, n \le 50\,000.There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.You'd like to remove all n points using a sequence of \frac{n}{2} snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if \min(x_a, x_b) \le x_c \le \max(x_a, x_b), \min(y_a, y_b) \le y_c \le \max(y_a, y_b), and \min(z_a, z_b) \le z_c \le \max(z_a, z_b). Note that the bounding box might be degenerate. Find a way to remove all points in \frac{n}{2} snaps.InputThe first line contains a single integer n (2 \le n \le 50\,000; n is even), denoting the number of points.Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 \le x_i, y_i, z_i \le 10^8), denoting the coordinates of the i-th point.No two points coincide.OutputOutput \frac{n}{2} pairs of integers a_i, b_i (1 \le a_i, b_i \le n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.We can show that it is always possible to remove all points. If there are many solutions, output any of them.ExamplesInput 6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0 Output 3 6 5 1 2 4 Input 8 0 1 1 1 0 1 1 1 0 1 1 1 2 2 2 3 2 2 2 3 2 2 2 3 Output 4 5 1 6 2 7 3 8 NoteIn the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0
3 6 5 1 2 4
1 second
512 megabytes
['binary search', 'constructive algorithms', 'divide and conquer', 'greedy', 'implementation', 'sortings', '*1900']
C1. Balanced Removals (Easier)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version, n \le 2000.There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.You'd like to remove all n points using a sequence of \frac{n}{2} snaps. In one snap, you can remove any two points a and b that have not been removed yet and form a perfectly balanced pair. A pair of points a and b is perfectly balanced if no other point c (that has not been removed yet) lies within the axis-aligned minimum bounding box of points a and b.Formally, point c lies within the axis-aligned minimum bounding box of points a and b if and only if \min(x_a, x_b) \le x_c \le \max(x_a, x_b), \min(y_a, y_b) \le y_c \le \max(y_a, y_b), and \min(z_a, z_b) \le z_c \le \max(z_a, z_b). Note that the bounding box might be degenerate. Find a way to remove all points in \frac{n}{2} snaps.InputThe first line contains a single integer n (2 \le n \le 2000; n is even), denoting the number of points.Each of the next n lines contains three integers x_i, y_i, z_i (-10^8 \le x_i, y_i, z_i \le 10^8), denoting the coordinates of the i-th point.No two points coincide.OutputOutput \frac{n}{2} pairs of integers a_i, b_i (1 \le a_i, b_i \le n), denoting the indices of points removed on snap i. Every integer between 1 and n, inclusive, must appear in your output exactly once.We can show that it is always possible to remove all points. If there are many solutions, output any of them.ExamplesInput 6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0 Output 3 6 5 1 2 4 Input 8 0 1 1 1 0 1 1 1 0 1 1 1 2 2 2 3 2 2 2 3 2 2 2 3 Output 4 5 1 6 2 7 3 8 NoteIn the first example, here is what points and their corresponding bounding boxes look like (drawn in two dimensions for simplicity, as all points lie on z = 0 plane). Note that order of removing matters: for example, points 5 and 1 don't form a perfectly balanced pair initially, but they do after point 3 is removed.
6 3 1 0 0 3 0 2 2 0 1 0 0 1 3 0 0 1 0
3 6 5 1 2 4
1 second
512 megabytes
['constructive algorithms', 'geometry', 'greedy', '*1700']
B. Balanced Tunneltime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a tunnel on a one-way road. During a particular day, n cars numbered from 1 to n entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.Traffic regulations prohibit overtaking inside the tunnel. If car i overtakes any other car j inside the tunnel, car i must be fined. However, each car can be fined at most once.Formally, let's say that car i definitely overtook car j if car i entered the tunnel later than car j and exited the tunnel earlier than car j. Then, car i must be fined if and only if it definitely overtook at least one other car.Find the number of cars that must be fined. InputThe first line contains a single integer n (2 \le n \le 10^5), denoting the number of cars.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n), denoting the ids of cars in order of entering the tunnel. All a_i are pairwise distinct.The third line contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le n), denoting the ids of cars in order of exiting the tunnel. All b_i are pairwise distinct.OutputOutput the number of cars to be fined.ExamplesInput 5 3 5 2 1 4 4 3 2 5 1 Output 2 Input 7 5 2 3 6 7 1 4 2 3 6 7 1 4 5 Output 6 Input 2 1 2 1 2 Output 0 NoteThe first example is depicted below:Car 2 definitely overtook car 5, while car 4 definitely overtook cars 1, 2, 3 and 5. Cars 2 and 4 must be fined.In the second example car 5 was definitely overtaken by all other cars.In the third example no car must be fined.
5 3 5 2 1 4 4 3 2 5 1
2
1 second
512 megabytes
['data structures', 'sortings', 'two pointers', '*1300']
A. Balanced Rating Changestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputAnother Codeforces Round has just finished! It has gathered n participants, and according to the results, the expected rating change of participant i is a_i. These rating changes are perfectly balanced — their sum is equal to 0.Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.There are two conditions though: For each participant i, their modified rating change b_i must be integer, and as close to \frac{a_i}{2} as possible. It means that either b_i = \lfloor \frac{a_i}{2} \rfloor or b_i = \lceil \frac{a_i}{2} \rceil. In particular, if a_i is even, b_i = \frac{a_i}{2}. Here \lfloor x \rfloor denotes rounding down to the largest integer not greater than x, and \lceil x \rceil denotes rounding up to the smallest integer not smaller than x. The modified rating changes must be perfectly balanced — their sum must be equal to 0. Can you help with that?InputThe first line contains a single integer n (2 \le n \le 13\,845), denoting the number of participants.Each of the next n lines contains a single integer a_i (-336 \le a_i \le 1164), denoting the rating change of the i-th participant.The sum of all a_i is equal to 0.OutputOutput n integers b_i, each denoting the modified rating change of the i-th participant in order of input.For any i, it must be true that either b_i = \lfloor \frac{a_i}{2} \rfloor or b_i = \lceil \frac{a_i}{2} \rceil. The sum of all b_i must be equal to 0.If there are multiple solutions, print any. We can show that a solution exists for any valid input.ExamplesInput 3 10 -5 -5 Output 5 -2 -3 Input 7 -7 -29 0 3 24 -29 38 Output -3 -15 0 2 12 -15 19 NoteIn the first example, b_1 = 5, b_2 = -3 and b_3 = -2 is another correct solution.In the second example there are 6 possible solutions, one of them is shown in the example output.
3 10 -5 -5
5 -2 -3
1 second
512 megabytes
['implementation', 'math', '*1000']
F. Alice and the Cactustime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice recently found some cactuses growing near her house! After several months, more and more cactuses appeared and soon they blocked the road. So Alice wants to clear them.A cactus is a connected undirected graph. No edge of this graph lies on more than one simple cycle. Let's call a sequence of different nodes of the graph x_1, x_2, \ldots, x_k a simple cycle, if k \geq 3 and all pairs of nodes x_1 and x_2, x_2 and x_3, \ldots, x_{k-1} and x_k, x_k and x_1 are connected with edges. Edges (x_1, x_2), (x_2, x_3), \ldots, (x_{k-1}, x_k), (x_k, x_1) lies on this simple cycle.There are so many cactuses, so it seems hard to destroy them. But Alice has magic. When she uses the magic, every node of the cactus will be removed independently with the probability \frac{1}{2}. When a node is removed, the edges connected to it are also removed.Now Alice wants to test her magic. She has picked a cactus with n nodes and m edges. Let X[S] (where S is a subset of the removed nodes) be the number of connected components in the remaining graph after removing nodes of set S. Before she uses magic, she wants to know the variance of random variable X, if all nodes of the graph have probability \frac{1}{2} to be removed and all n of these events are independent. By the definition the variance is equal to E[(X - E[X])^2], where E[X] is the expected value of X. Help her and calculate this value by modulo 10^9+7.Formally, let M = 10^9 + 7 (a prime number). It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, find such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.InputThe first line contains two integers n and m, separated by space (1 \leq n \leq 5 \cdot 10^5, n - 1 \leq m \leq 5 \cdot 10^5) — the number of nodes and edges in the cactus.The following m lines contain two numbers u and v each, separated by space (1 \leq u, v \leq n, u \neq v) meaning that there is an edge between the nodes u and v.It is guaranteed that there are no loops and multiple edges in the graph and the given graph is cactus.OutputPrint one integer — the variance of the number of connected components in the remaining graph, after removing a set of nodes such that each node has probability \frac{1}{2} to be removed and all these events are independent. This value should be found by modulo 10^9+7.ExamplesInput 3 3 1 2 2 3 1 3 Output 984375007Input 5 6 1 2 2 3 1 3 3 4 4 5 3 5 Output 250000002NoteIn the first sample, the answer is \frac{7}{64}. If all nodes are removed the value of X is equal to 0, otherwise, it is equal to 1. So, the expected value of X is equal to 0\times\frac{1}{8}+1\times\frac{7}{8}=\frac{7}{8}. So, the variance of X is equal to (0 - \frac{7}{8})^2\times\frac{1}{8}+(1-\frac{7}{8})^2\times\frac{7}{8} = (\frac{7}{8})^2\times\frac{1}{8}+(\frac{1}{8})^2\times\frac{7}{8} = \frac{7}{64}.In the second sample, the answer is \frac{1}{4}.
3 3 1 2 2 3 1 3
984375007
3 seconds
256 megabytes
['dfs and similar', 'graphs', 'math', 'probabilities', '*3000']
E. Alice and the Unfair Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice is playing a game with her good friend, Marisa.There are n boxes arranged in a line, numbered with integers from 1 to n from left to right. Marisa will hide a doll in one of the boxes. Then Alice will have m chances to guess where the doll is. If Alice will correctly guess the number of box, where doll is now, she will win the game, otherwise, her friend will win the game.In order to win, Marisa will use some unfair tricks. After each time Alice guesses a box, she can move the doll to the neighboring box or just keep it at its place. Boxes i and i + 1 are neighboring for all 1 \leq i \leq n - 1. She can also use this trick once before the game starts.So, the game happens in this order: the game starts, Marisa makes the trick, Alice makes the first guess, Marisa makes the trick, Alice makes the second guess, Marisa makes the trick, \ldots, Alice makes m-th guess, Marisa makes the trick, the game ends.Alice has come up with a sequence a_1, a_2, \ldots, a_m. In the i-th guess, she will ask if the doll is in the box a_i. She wants to know the number of scenarios (x, y) (for all 1 \leq x, y \leq n), such that Marisa can win the game if she will put the doll at the x-th box at the beginning and at the end of the game, the doll will be at the y-th box. Help her and calculate this number.InputThe first line contains two integers n and m, separated by space (1 \leq n, m \leq 10^5) — the number of boxes and the number of guesses, which Alice will make.The next line contains m integers a_1, a_2, \ldots, a_m, separated by spaces (1 \leq a_i \leq n), the number a_i means the number of the box which Alice will guess in the i-th guess.OutputPrint the number of scenarios in a single line, or the number of pairs of boxes (x, y) (1 \leq x, y \leq n), such that if Marisa will put the doll into the box with number x, she can make tricks in such way, that at the end of the game the doll will be in the box with number y and she will win the game.ExamplesInput 3 3 2 2 2 Output 7Input 5 2 3 1 Output 21NoteIn the first example, the possible scenarios are (1, 1), (1, 2), (2, 1), (2, 2), (2, 3), (3, 2), (3, 3).Let's take (2, 2) as an example. The boxes, in which the doll will be during the game can be 2 \to 3 \to 3 \to 3 \to 2
3 3 2 2 2
7
1 second
256 megabytes
['binary search', 'data structures', 'dp', 'dsu', '*2500']
D. Alice and the Dolltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice got a new doll these days. It can even walk!Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.More formally, there exist 4 directions, in which the doll can look: The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1); The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y); The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1); The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y). .Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 \to 2, 2 \to 3, 3 \to 4, 4 \to 1. Standing in one cell, the doll can make at most one turn right.Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?InputThe first line contains three integers n, m and k, separated by spaces (1 \leq n,m \leq 10^5, 0 \leq k \leq 10^5) — the size of the maze and the number of obstacles.Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 \leq x_i \leq n,1 \leq y_i \leq m), which describes the position of the i-th obstacle.It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).OutputPrint 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.If it is impossible to walk across the maze by these rules print 'No' (without quotes).ExamplesInput 3 3 2 2 2 2 1 Output YesInput 3 3 2 3 1 2 2 Output NoInput 3 3 8 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3 Output YesNoteHere is the picture of maze described in the first example: In the first example, the doll can walk in this way: The doll is in the cell (1, 1), looks to the direction 1. Move straight; The doll is in the cell (1, 2), looks to the direction 1. Move straight; The doll is in the cell (1, 3), looks to the direction 1. Turn right; The doll is in the cell (1, 3), looks to the direction 2. Move straight; The doll is in the cell (2, 3), looks to the direction 2. Move straight; The doll is in the cell (3, 3), looks to the direction 2. Turn right; The doll is in the cell (3, 3), looks to the direction 3. Move straight; The doll is in the cell (3, 2), looks to the direction 3. Move straight; The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once.
3 3 2 2 2 2 1
Yes
1 second
256 megabytes
['brute force', 'data structures', 'greedy', 'implementation', '*2300']
C. Labstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn order to do some research, n^2 labs are built on different heights of a mountain. Let's enumerate them with integers from 1 to n^2, such that the lab with the number 1 is at the lowest place, the lab with the number 2 is at the second-lowest place, \ldots, the lab with the number n^2 is at the highest place.To transport water between the labs, pipes are built between every pair of labs. A pipe can transport at most one unit of water at a time from the lab with the number u to the lab with the number v if u > v.Now the labs need to be divided into n groups, each group should contain exactly n labs. The labs from different groups can transport water to each other. The sum of units of water that can be sent from a group A to a group B is equal to the number of pairs of labs (u, v) such that the lab with the number u is from the group A, the lab with the number v is from the group B and u > v. Let's denote this value as f(A,B) (i.e. f(A,B) is the sum of units of water that can be sent from a group A to a group B).For example, if n=3 and there are 3 groups X, Y and Z: X = \{1, 5, 6\}, Y = \{2, 4, 9\} and Z = \{3, 7, 8\}. In this case, the values of f are equal to: f(X,Y)=4 because of 5 \rightarrow 2, 5 \rightarrow 4, 6 \rightarrow 2, 6 \rightarrow 4, f(X,Z)=2 because of 5 \rightarrow 3, 6 \rightarrow 3, f(Y,X)=5 because of 2 \rightarrow 1, 4 \rightarrow 1, 9 \rightarrow 1, 9 \rightarrow 5, 9 \rightarrow 6, f(Y,Z)=4 because of 4 \rightarrow 3, 9 \rightarrow 3, 9 \rightarrow 7, 9 \rightarrow 8, f(Z,X)=7 because of 3 \rightarrow 1, 7 \rightarrow 1, 7 \rightarrow 5, 7 \rightarrow 6, 8 \rightarrow 1, 8 \rightarrow 5, 8 \rightarrow 6, f(Z,Y)=5 because of 3 \rightarrow 2, 7 \rightarrow 2, 7 \rightarrow 4, 8 \rightarrow 2, 8 \rightarrow 4. Please, divide labs into n groups with size n, such that the value \min f(A,B) over all possible pairs of groups A and B (A \neq B) is maximal.In other words, divide labs into n groups with size n, such that minimum number of the sum of units of water that can be transported from a group A to a group B for every pair of different groups A and B (A \neq B) as big as possible.Note, that the example above doesn't demonstrate an optimal division, but it demonstrates how to calculate the values f for some division.If there are many optimal divisions, you can find any.InputThe only line contains one number n (2 \leq n \leq 300).OutputOutput n lines:In the i-th line print n numbers, the numbers of labs of the i-th group, in any order you want.If there are multiple answers, that maximize the minimum number of the sum of units of water that can be transported from one group the another, you can print any.ExampleInput 3 Output 2 8 5 9 3 4 7 6 1 NoteIn the first test we can divide 9 labs into groups \{2, 8, 5\}, \{9, 3, 4\}, \{7, 6, 1\}.From the first group to the second group we can transport 4 units of water (8 \rightarrow 3, 8 \rightarrow 4, 5 \rightarrow 3, 5 \rightarrow 4).From the first group to the third group we can transport 5 units of water (2 \rightarrow 1, 8 \rightarrow 7, 8 \rightarrow 6, 8 \rightarrow 1, 5 \rightarrow 1).From the second group to the first group we can transport 5 units of water (9 \rightarrow 2, 9 \rightarrow 8, 9 \rightarrow 5, 3 \rightarrow 2, 4 \rightarrow 2).From the second group to the third group we can transport 5 units of water (9 \rightarrow 7, 9 \rightarrow 6, 9 \rightarrow 1, 3 \rightarrow 1, 4 \rightarrow 1).From the third group to the first group we can transport 4 units of water (7 \rightarrow 2, 7 \rightarrow 5, 6 \rightarrow 2, 6 \rightarrow 5).From the third group to the second group we can transport 4 units of water (7 \rightarrow 3, 7 \rightarrow 4, 6 \rightarrow 3, 6 \rightarrow 4).The minimal number of the sum of units of water, that can be transported from one group to another is equal to 4. It can be proved, that it is impossible to make a better division.
3
2 8 5 9 3 4 7 6 1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1300']
B. Alice and the List of Presentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice got many presents these days. So she decided to pack them into boxes and send them to her friends.There are n kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind.Also, there are m boxes. All of them are for different people, so they are pairwise distinct (consider that the names of m friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box.Alice wants to pack presents with the following rules: She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of n kinds, empty boxes are allowed); For each kind at least one present should be packed into some box. Now Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo 10^9+7.See examples and their notes for clarification.InputThe first line contains two integers n and m, separated by spaces (1 \leq n,m \leq 10^9) — the number of kinds of presents and the number of boxes that Alice has.OutputPrint one integer  — the number of ways to pack the presents with Alice's rules, calculated by modulo 10^9+7ExamplesInput 1 3 Output 7Input 2 2 Output 9NoteIn the first example, there are seven ways to pack presents:\{1\}\{\}\{\}\{\}\{1\}\{\}\{\}\{\}\{1\}\{1\}\{1\}\{\}\{\}\{1\}\{1\}\{1\}\{\}\{1\}\{1\}\{1\}\{1\}In the second example there are nine ways to pack presents:\{\}\{1,2\}\{1\}\{2\}\{1\}\{1,2\}\{2\}\{1\}\{2\}\{1,2\}\{1,2\}\{\}\{1,2\}\{1\}\{1,2\}\{2\}\{1,2\}\{1,2\}For example, the way \{2\}\{2\} is wrong, because presents of the first kind should be used in the least one box.
1 3
7
1 second
256 megabytes
['combinatorics', 'math', '*1500']
A. Stonestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice is playing with some stones.Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones.Each time she can do one of two operations: take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones); take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has 0 stones. Can you help her?InputThe first line contains one integer t (1 \leq t \leq 100)  — the number of test cases. Next t lines describe test cases in the following format:Line contains three non-negative integers a, b and c, separated by spaces (0 \leq a,b,c \leq 100) — the number of stones in the first, the second and the third heap, respectively.In hacks it is allowed to use only one test case in the input, so t = 1 should be satisfied.OutputPrint t lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer  — the maximum possible number of stones that Alice can take after making some operations. ExampleInput 3 3 4 5 1 0 5 5 3 2 Output 9 0 6 NoteFor the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is 9. It is impossible to make some operations to take more than 9 stones, so the answer is 9.
3 3 4 5 1 0 5 5 3 2
9 0 6
1 second
256 megabytes
['brute force', 'greedy', 'math', '*800']
F. Yet Another Substring Reversetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting only of first 20 lowercase Latin letters ('a', 'b', ..., 't').Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} \dots s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".You can perform the following operation no more than once: choose some substring s[l; r] and reverse it (i.e. the string s_l s_{l + 1} \dots s_r becomes s_r s_{r - 1} \dots s_l).Your goal is to maximize the length of the maximum substring of s consisting of distinct (i.e. unique) characters.The string consists of distinct characters if no character in this string appears more than once. For example, strings "abcde", "arctg" and "minecraft" consist of distinct characters but strings "codeforces", "abacaba" do not consist of distinct characters.InputThe only line of the input contains one string s consisting of no more than 10^6 characters 'a', 'b', ..., 't' (first 20 lowercase Latin letters).OutputPrint one integer — the maximum possible length of the maximum substring of s consisting of distinct characters after reversing no more than one its substring.ExamplesInput abacaba Output 3 Input abcdecdf Output 6 Input aabbcc Output 3 Input abcdeefc Output 6
abacaba
3
2 seconds
256 megabytes
['bitmasks', 'dp', '*2200']
E. Special Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define p_i(n) as the following permutation: [i, 1, 2, \dots, i - 1, i + 1, \dots, n]. This means that the i-th permutation is almost identity (i.e. which maps every element to itself) permutation but the element i is on the first position. Examples: p_1(4) = [1, 2, 3, 4]; p_2(4) = [2, 1, 3, 4]; p_3(4) = [3, 1, 2, 4]; p_4(4) = [4, 1, 2, 3]. You are given an array x_1, x_2, \dots, x_m (1 \le x_i \le n).Let pos(p, val) be the position of the element val in p. So, pos(p_1(4), 3) = 3, pos(p_2(4), 2) = 1, pos(p_4(4), 4) = 1.Let's define a function f(p) = \sum\limits_{i=1}^{m - 1} |pos(p, x_i) - pos(p, x_{i + 1})|, where |val| is the absolute value of val. This function means the sum of distances between adjacent elements of x in p.Your task is to calculate f(p_1(n)), f(p_2(n)), \dots, f(p_n(n)).InputThe first line of the input contains two integers n and m (2 \le n, m \le 2 \cdot 10^5) — the number of elements in each permutation and the number of elements in x.The second line of the input contains m integers (m, not n) x_1, x_2, \dots, x_m (1 \le x_i \le n), where x_i is the i-th element of x. Elements of x can repeat and appear in arbitrary order.OutputPrint n integers: f(p_1(n)), f(p_2(n)), \dots, f(p_n(n)).ExamplesInput 4 4 1 2 3 4 Output 3 4 6 5 Input 5 5 2 1 5 3 5 Output 9 8 12 6 8 Input 2 10 1 2 1 1 2 2 2 2 2 2 Output 3 3 NoteConsider the first example:x = [1, 2, 3, 4], so for the permutation p_1(4) = [1, 2, 3, 4] the answer is |1 - 2| + |2 - 3| + |3 - 4| = 3; for the permutation p_2(4) = [2, 1, 3, 4] the answer is |2 - 1| + |1 - 3| + |3 - 4| = 4; for the permutation p_3(4) = [3, 1, 2, 4] the answer is |2 - 3| + |3 - 1| + |1 - 4| = 6; for the permutation p_4(4) = [4, 1, 2, 3] the answer is |2 - 3| + |3 - 4| + |4 - 1| = 5. Consider the second example:x = [2, 1, 5, 3, 5], so for the permutation p_1(5) = [1, 2, 3, 4, 5] the answer is |2 - 1| + |1 - 5| + |5 - 3| + |3 - 5| = 9; for the permutation p_2(5) = [2, 1, 3, 4, 5] the answer is |1 - 2| + |2 - 5| + |5 - 3| + |3 - 5| = 8; for the permutation p_3(5) = [3, 1, 2, 4, 5] the answer is |3 - 2| + |2 - 5| + |5 - 1| + |1 - 5| = 12; for the permutation p_4(5) = [4, 1, 2, 3, 5] the answer is |3 - 2| + |2 - 5| + |5 - 4| + |4 - 5| = 6; for the permutation p_5(5) = [5, 1, 2, 3, 4] the answer is |3 - 2| + |2 - 1| + |1 - 4| + |4 - 1| = 8.
4 4 1 2 3 4
3 4 6 5
2 seconds
256 megabytes
['math', '*2000']
D. Distinct Characters Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of lowercase Latin letters and q queries for this string.Recall that the substring s[l; r] of the string s is the string s_l s_{l + 1} \dots s_r. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".There are two types of queries: 1~ pos~ c (1 \le pos \le |s|, c is lowercase Latin letter): replace s_{pos} with c (set s_{pos} := c); 2~ l~ r (1 \le l \le r \le |s|): calculate the number of distinct characters in the substring s[l; r]. InputThe first line of the input contains one string s consisting of no more than 10^5 lowercase Latin letters.The second line of the input contains one integer q (1 \le q \le 10^5) — the number of queries.The next q lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.OutputFor each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.ExamplesInput abacaba 5 2 1 4 1 4 b 1 5 b 2 4 6 2 1 7 Output 3 1 2 Input dfcbbcfeeedbaea 15 1 6 e 1 4 b 2 6 14 1 7 b 1 12 c 2 6 8 2 1 6 1 7 c 1 2 f 1 10 a 2 7 9 1 10 a 1 14 b 1 1 f 2 1 11 Output 5 2 5 2 6
abacaba 5 2 1 4 1 4 b 1 5 b 2 4 6 2 1 7
3 1 2
2 seconds
256 megabytes
['data structures', '*1600']
C. Pipestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a system of pipes. It consists of two rows, each row consists of n pipes. The top left pipe has the coordinates (1, 1) and the bottom right — (2, n).There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types: Types of pipes You can turn each of the given pipes 90 degrees clockwise or counterclockwise arbitrary (possibly, zero) number of times (so the types 1 and 2 can become each other and types 3, 4, 5, 6 can become each other).You want to turn some pipes in a way that the water flow can start at (1, 0) (to the left of the top left pipe), move to the pipe at (1, 1), flow somehow by connected pipes to the pipe at (2, n) and flow right to (2, n + 1).Pipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes: Examples of connected pipes Let's describe the problem using some example: The first example input And its solution is below: The first example answer As you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at (1, 2) 90 degrees clockwise, the pipe at (2, 3) 90 degrees, the pipe at (1, 6) 90 degrees, the pipe at (1, 7) 180 degrees and the pipe at (2, 7) 180 degrees. Then the flow of water can reach (2, n + 1) from (1, 0).You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 10^4) — the number of queries. Then q queries follow.Each query consists of exactly three lines. The first line of the query contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of pipes in each row. The next two lines contain a description of the first and the second rows correspondingly. Each row description consists of n digits from 1 to 6 without any whitespaces between them, each digit corresponds to the type of pipe in the corresponding cell. See the problem statement to understand which digits correspond to which types of pipes.It is guaranteed that the sum of n over all queries does not exceed 2 \cdot 10^5.OutputFor the i-th query print the answer for it — "YES" (without quotes) if it is possible to turn some pipes in a way that the water flow can reach (2, n + 1) from (1, 0), and "NO" otherwise.ExampleInput 6 7 2323216 1615124 1 3 4 2 13 24 2 12 34 3 536 345 2 46 54 Output YES YES YES NO YES NO NoteThe first query from the example is described in the problem statement.
6 7 2323216 1615124 1 3 4 2 13 24 2 12 34 3 536 345 2 46 54
YES YES YES NO YES NO
2 seconds
256 megabytes
['dp', 'implementation', '*1500']
B2. Social Network (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions are constraints on n and k.You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0).Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 \le id_i \le 10^9).If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.Otherwise (i.e. if there is no conversation with id_i on the screen): Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages.InputThe first line of the input contains two integers n and k (1 \le n, k \le 2 \cdot 10^5) — the number of messages and the number of conversations your smartphone can show.The second line of the input contains n integers id_1, id_2, \dots, id_n (1 \le id_i \le 10^9), where id_i is the ID of the friend which sends you the i-th message.OutputIn the first line of the output print one integer m (1 \le m \le min(n, k)) — the number of conversations shown after receiving all n messages.In the second line print m integers ids_1, ids_2, \dots, ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages.ExamplesInput 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 NoteIn the first example the list of conversations will change in the following way (in order from the first to last message): []; [1]; [2, 1]; [3, 2]; [3, 2]; [1, 3]; [1, 3]; [2, 1]. In the second example the list of conversations will change in the following way: []; [2]; [3, 2]; [3, 2]; [1, 3, 2]; and then the list will not change till the end.
7 2 1 2 3 2 1 3 2
2 2 1
2 seconds
256 megabytes
['data structures', 'implementation', '*1300']
B1. Social Network (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions are constraints on n and k.You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0).Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 \le id_i \le 10^9).If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.Otherwise (i.e. if there is no conversation with id_i on the screen): Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen. Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen. The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages.InputThe first line of the input contains two integers n and k (1 \le n, k \le 200) — the number of messages and the number of conversations your smartphone can show.The second line of the input contains n integers id_1, id_2, \dots, id_n (1 \le id_i \le 10^9), where id_i is the ID of the friend which sends you the i-th message.OutputIn the first line of the output print one integer m (1 \le m \le min(n, k)) — the number of conversations shown after receiving all n messages.In the second line print m integers ids_1, ids_2, \dots, ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages.ExamplesInput 7 2 1 2 3 2 1 3 2 Output 2 2 1 Input 10 4 2 3 3 1 1 2 1 2 3 3 Output 3 1 3 2 NoteIn the first example the list of conversations will change in the following way (in order from the first to last message): []; [1]; [2, 1]; [3, 2]; [3, 2]; [1, 3]; [1, 3]; [2, 1]. In the second example the list of conversations will change in the following way: []; [2]; [3, 2]; [3, 2]; [1, 3, 2]; and then the list will not change till the end.
7 2 1 2 3 2 1 3 2
2 2 1
2 seconds
256 megabytes
['implementation', '*1000']
A. Equalize Prices Againtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins.You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have.However, you don't want to lose any money so you want to choose the price in such a way that the sum of new prices is not less than the sum of the initial prices. It means that if you sell all n goods for the new price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.On the other hand, you don't want to lose customers because of big prices so among all prices you can choose you need to choose the minimum one.So you need to find the minimum possible equal price of all n goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 100) — the number of queries. Then q queries follow.The first line of the query contains one integer n (1 \le n \le 100) — the number of goods. The second line of the query contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^7), where a_i is the price of the i-th good.OutputFor each query, print the answer for it — the minimum possible equal price of all n goods so if you sell them for this price, you will receive at least the same (or greater) amount of money as if you sell them for their initial prices.ExampleInput 3 5 1 2 3 4 5 3 1 2 2 4 1 1 1 1 Output 3 2 1
3 5 1 2 3 4 5 3 1 2 2 4 1 1 1 1
3 2 1
1 second
256 megabytes
['math', '*800']
E. Middle-Outtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out.You are given two strings s and t of the same length n. Their characters are numbered from 1 to n from left to right (i.e. from the beginning to the end).In a single move you can do the following sequence of actions: choose any valid index i (1 \le i \le n), move the i-th character of s from its position to the beginning of the string or move the i-th character of s from its position to the end of the string. Note, that the moves don't change the length of the string s. You can apply a move only to the string s.For example, if s="test" in one move you can obtain: if i=1 and you move to the beginning, then the result is "test" (the string doesn't change), if i=2 and you move to the beginning, then the result is "etst", if i=3 and you move to the beginning, then the result is "stet", if i=4 and you move to the beginning, then the result is "ttes", if i=1 and you move to the end, then the result is "estt", if i=2 and you move to the end, then the result is "tste", if i=3 and you move to the end, then the result is "tets", if i=4 and you move to the end, then the result is "test" (the string doesn't change). You want to make the string s equal to the string t. What is the minimum number of moves you need? If it is impossible to transform s to t, print -1.InputThe first line contains integer q (1 \le q \le 100) — the number of independent test cases in the input.Each test case is given in three lines. The first line of a test case contains n (1 \le n \le 100) — the length of the strings s and t. The second line contains s, the third line contains t. Both strings s and t have length n and contain only lowercase Latin letters.There are no constraints on the sum of n in the test (i.e. the input with q=100 and all n=100 is allowed).OutputFor every test print minimum possible number of moves, which are needed to transform s into t, or -1, if it is impossible to do.ExamplesInput 3 9 iredppipe piedpiper 4 estt test 4 tste test Output 2 1 2 Input 4 1 a z 5 adhas dasha 5 aashd dasha 5 aahsd dasha Output -1 2 2 3 NoteIn the first example, the moves in one of the optimal answers are: for the first test case s="iredppipe", t="piedpiper": "iredppipe" \rightarrow "iedppiper" \rightarrow "piedpiper"; for the second test case s="estt", t="test": "estt" \rightarrow "test"; for the third test case s="tste", t="test": "tste" \rightarrow "etst" \rightarrow "test".
3 9 iredppipe piedpiper 4 estt test 4 tste test
2 1 2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'strings', '*2200']
C. Increasing Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem, a n \times m rectangular matrix a is called increasing if, for each row of i, when go from left to right, the values strictly increase (that is, a_{i,1}<a_{i,2}<\dots<a_{i,m}) and for each column j, when go from top to bottom, the values strictly increase (that is, a_{1,j}<a_{2,j}<\dots<a_{n,j}).In a given matrix of non-negative integers, it is necessary to replace each value of 0 with some positive integer so that the resulting matrix is increasing and the sum of its elements is maximum, or find that it is impossible.It is guaranteed that in a given value matrix all values of 0 are contained only in internal cells (that is, not in the first or last row and not in the first or last column).InputThe first line contains integers n and m (3 \le n, m \le 500) — the number of rows and columns in the given matrix a.The following lines contain m each of non-negative integers — the values in the corresponding row of the given matrix: a_{i,1}, a_{i,2}, \dots, a_{i,m} (0 \le a_{i,j} \le 8000).It is guaranteed that for all a_{i,j}=0, 1 < i < n and 1 < j < m are true.OutputIf it is possible to replace all zeros with positive numbers so that the matrix is increasing, print the maximum possible sum of matrix elements. Otherwise, print -1.ExamplesInput 4 5 1 3 5 6 7 3 0 7 0 9 5 0 0 0 10 8 9 10 11 12 Output 144 Input 3 3 1 2 3 2 0 4 4 5 6 Output 30 Input 3 3 1 2 3 3 0 4 4 5 6 Output -1 Input 3 3 1 2 3 2 3 4 3 4 2 Output -1 NoteIn the first example, the resulting matrix is as follows: 1 3 5 6 73 6 7 8 95 7 8 9 108 9 10 11 12In the second example, the value 3 must be put in the middle cell.In the third example, the desired resultant matrix does not exist.
4 5 1 3 5 6 7 3 0 7 0 9 5 0 0 0 10 8 9 10 11 12
144
2 seconds
256 megabytes
['greedy', '*1100']
B. Ania and Minimizingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnia has a large integer S. Its decimal representation has length n and doesn't contain any leading zeroes. Ania is allowed to change at most k digits of S. She wants to do it in such a way that S still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?InputThe first line contains two integers n and k (1 \leq n \leq 200\,000, 0 \leq k \leq n) — the number of digits in the decimal representation of S and the maximum allowed number of changed digits.The second line contains the integer S. It's guaranteed that S has exactly n digits and doesn't contain any leading zeroes.OutputOutput the minimal possible value of S which Ania can end with. Note that the resulting integer should also have n digits.ExamplesInput 5 3 51528 Output 10028 Input 3 2 102 Output 100 Input 1 1 1 Output 0 NoteA number has leading zeroes if it consists of at least two digits and its first digit is 0. For example, numbers 00, 00069 and 0101 have leading zeroes, while 0, 3000 and 1010 don't have leading zeroes.
5 3 51528
10028
1 second
256 megabytes
['greedy', 'implementation', '*1000']
A. Dawid and Bags of Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDawid has four bags of candies. The i-th of them contains a_i candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?Note, that you can't keep bags for yourself or throw them away, each bag should be given to one of the friends.InputThe only line contains four integers a_1, a_2, a_3 and a_4 (1 \leq a_i \leq 100) — the numbers of candies in each bag.OutputOutput YES if it's possible to give the bags to Dawid's friends so that both friends receive the same amount of candies, or NO otherwise. Each character can be printed in any case (either uppercase or lowercase).ExamplesInput 1 7 11 5 Output YES Input 7 3 2 5 Output NO NoteIn the first sample test, Dawid can give the first and the third bag to the first friend, and the second and the fourth bag to the second friend. This way, each friend will receive 12 candies.In the second sample test, it's impossible to distribute the bags.
1 7 11 5
YES
1 second
256 megabytes
['brute force', 'implementation', '*800']