contest_id
int32
1
2.13k
index
stringclasses
62 values
problem_id
stringlengths
2
6
title
stringlengths
0
67
rating
int32
0
3.5k
tags
stringlengths
0
139
statement
stringlengths
0
6.96k
input_spec
stringlengths
0
2.32k
output_spec
stringlengths
0
1.52k
note
stringlengths
0
5.06k
sample_tests
stringlengths
0
1.02k
difficulty_category
stringclasses
6 values
tag_count
int8
0
11
statement_length
int32
0
6.96k
input_spec_length
int16
0
2.32k
output_spec_length
int16
0
1.52k
contest_year
int16
0
21
1,054
G
1054G
G. New Road Network
3,300
constructive algorithms; greedy; math
The king of some country \(N\) decided to completely rebuild the road network. There are \(n\) people living in the country, they are enumerated from \(1\) to \(n\). It is possible to construct a road between the house of any citizen \(a\) to the house of any other citizen \(b\). There should not be more than one road between any pair of citizens. The road network must be connected, i.e. it should be possible to reach every citizen starting from anyone using roads. To save funds, it was decided to build exactly \(n-1\) road, so the road network should be a tree.However, it is not that easy as it sounds, that's why the king addressed you for help. There are \(m\) secret communities in the country, each of them unites a non-empty subset of citizens. The king does not want to conflict with any of the communities, so he wants to build the network such that the houses of members of each society form a connected subtree in network. A set of vertices forms a connected subtree if and only if the graph remains connected when we delete all the other vertices and all edges but ones that connect the vertices from the set.Help the king to determine if it is possible to build the desired road network, and if it is, build it.
Each test consists of one or more test cases.The first line contains a single integer \(t\) (\(1 \leq t \leq 2000\)) β€” the number of test cases.The following lines describe the test cases, each in the following format.The first line contains two integers \(n\) and \(m\) (\(1 \leq n, m \leq 2000\)) β€” the number of citizens and the number of secret communities. The next \(m\) lines contain the description of the communities. The \(i\)-th of these lines contains a string \(s_i\) of length \(n\), consisting of characters '0' and '1'. The citizen with number \(j\) is a member of the \(i\)-th community if and only if \(s_{{i}{j}}=1\). It is guaranteed that the string \(s_i\) contains at least one character '1' for each \(1 \leq i \leq m\).It is guaranteed that the sum of \(n\) for all test cases does not exceed \(2000\) and the sum of \(m\) for all test cases does not exceed \(2000\).
Print the answer for all test cases in the order they are given in the input, each in the following format.If there is no way to build the desired road network, print ""NO"" (without quotes).Otherwise in the first line print ""YES"" (without quotes).In the next \(n-1\) lines print the description of the road network: each line should contain two integers \(a\) and \(b\) (\(1 \leq a, b \leq n\), \(a \neq b\)) that denote you build a road between houses of citizens \(a\) and \(b\). The roads should form a connected tree, and each community should form a connected subtree.
In the first example you can build the following network: It is easy to see that for each community all the houses of its members form a connected subtree. For example, the \(2\)-nd community unites the citizens \(1\), \(2\), \(3\). They form a connected subtree, because if we delete everything except the houses \(1\), \(2\), \(3\) and the roads between them, two roads will remain: between \(1\) and \(3\) and between \(2\) and \(3\), forming a connected graph.There is no network in the second example suitable for the king.
Input: 24 30011111001113 3011101110 | Output: YES1 32 33 4NO
Master
3
1,230
891
576
10
2,036
A
2036A
A. Quintomania
800
implementation
Boris Notkin composes melodies. He represents them as a sequence of notes, where each note is encoded as an integer from \(0\) to \(127\) inclusive. The interval between two notes \(a\) and \(b\) is equal to \(|a - b|\) semitones.Boris considers a melody perfect if the interval between each two adjacent notes is either \(5\) semitones or \(7\) semitones.After composing his latest melodies, he enthusiastically shows you his collection of works. Help Boris Notkin understand whether his melodies are perfect.
The first line contains an integer \(t\) (\(1 \leq t \leq 1000\)) β€” the number of melodies.Each melody is described by two lines. The first line contains an integer \(n\) (\(2 \leq n \leq 50\)) β€” the number of notes in the melody.The second line contains \(n\) integers \(a_{1}, a_{2}, \dots, a_{n}\) (\(0 \leq a_{i} \leq 127\)) β€” the notes of the melody.
For each melody, output ""YES"", if it is perfect; otherwise, output ""NO"".You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
Input: 82114 109217 10376 83 88838 45 38 80 85 92 99 106563 58 65 58 658117 124 48 53 48 43 54 49595 102 107 114 1211072 77 82 75 70 75 68 75 68 75 | Output: YES YES YES NO YES NO YES YES
Beginner
1
510
355
237
20
1,501
B
1501B
B. Napoleon Cake
900
dp; implementation; sortings
This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.To bake a Napoleon cake, one has to bake \(n\) dry layers first, and then put them on each other in one stack, adding some cream. Arkady started with an empty plate, and performed the following steps \(n\) times: place a new cake layer on the top of the stack; after the \(i\)-th layer is placed, pour \(a_i\) units of cream on top of the stack. When \(x\) units of cream are poured on the top of the stack, top \(x\) layers of the cake get drenched in the cream. If there are less than \(x\) layers, all layers get drenched and the rest of the cream is wasted. If \(x = 0\), no layer gets drenched. The picture represents the first test case of the example. Help Arkady determine which layers of the cake eventually get drenched when the process is over, and which don't.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 20\,000\)). Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” the number of layers in the cake.The second line of each test case contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le n\)) β€” the amount of cream poured on the cake after adding each layer.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print a single line with \(n\) integers. The \(i\)-th of the integers should be equal to \(1\) if the \(i\)-th layer from the bottom gets drenched, and \(0\) otherwise.
Input: 3 6 0 3 0 0 1 3 10 0 0 0 1 0 5 0 0 0 2 3 0 0 0 | Output: 1 1 0 1 1 1 0 1 1 1 1 1 0 0 1 1 0 0 0
Beginner
3
1,047
554
188
15
613
E
613E
E. Puzzle Lover
3,200
dp; hashing; strings
Oleg Petrov loves crossword puzzles and every Thursday he buys his favorite magazine with crosswords and other word puzzles. In the last magazine Oleg found a curious puzzle, and the magazine promised a valuable prize for it's solution. We give a formal description of the problem below.The puzzle field consists of two rows, each row contains n cells. Each cell contains exactly one small English letter. You also are given a word w, which consists of k small English letters. A solution of the puzzle is a sequence of field cells c1, ..., ck, such that: For all i from 1 to k the letter written in the cell ci matches the letter wi; All the cells in the sequence are pairwise distinct; For all i from 1 to k - 1 cells ci and ci + 1 have a common side.Oleg Petrov quickly found a solution for the puzzle. Now he wonders, how many distinct solutions are there for this puzzle. Oleg Petrov doesn't like too large numbers, so calculate the answer modulo 109 + 7.Two solutions ci and c'i are considered distinct if the sequences of cells do not match in at least one position, that is there is such j in range from 1 to k, such that cj β‰  c'j.
The first two lines contain the state of the field for the puzzle. Each of these non-empty lines contains exactly n small English letters.The next line is left empty.The next line is non-empty and contains word w, consisting of small English letters.The length of each line doesn't exceed 2 000.
Print a single integer β€” the number of distinct solutions for the puzzle modulo 109 + 7.
Input: codeedoccode | Output: 4
Master
3
1,139
295
88
6
2,122
A
2122A
A. Greedy Grid
800
constructive algorithms; greedy
A path in a grid is called greedy if it starts at the top-left cell and moves only to the right or downward, always moving to its neighbor with the greater value (or either if the values are equal).The value of a path is the sum of the values of the cells it visits, including the start and end.Does there exist an \(n \times m\) grid of nonnegative integers such that no greedy path achieves the maximum value among all down/right paths?
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 5000\)). The description of the test cases follows. The only line of each test case contains two integers \(n\), \(m\) (\(1 \leq n, m \leq 100\)) β€” the number of rows and columns in the grid, respectively.
For each test case, on a separate line output ""YES"" if the required grid exists, and ""NO"" otherwise.You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
In the first test case, an example of a grid in which no greedy path achieves the maximum value out of all down/right paths is: $$$\( \begin{bmatrix} 3 & 5 & 1 \\ 2 & 1 & 2 \\ 5 & 4 & 3 \\ \end{bmatrix} \)\( Let \)a_{i, j}\( denote the value of the cell in the \)i\(-th row and \)j\(-th column. The maximum value of a down/right path is \)a_{1,1} + a_{2,1} + a_{3,1} + a_{3,2} + a_{3,3} = 17\(. This path isn't greedy because \)a_{1,2}\( is greater than \)a_{2,1}\(; thus, a greedy path must move right in the first step. The maximum value of a greedy path is \)a_{1,1} + a_{1,2} + a_{2,2} + a_{3,2} + a_{3,3} = 16$$$.In the second test case, it can be proven that no grid satisfies the conditions.
Input: 23 31 2 | Output: YES NO
Beginner
2
438
315
265
21
1,283
F
1283F
F. DIY Garland
2,200
constructive algorithms; greedy; trees
Polycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.Simple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of \(n\) lamps and \(n - 1\) wires. Exactly one lamp will be connected to power grid, and power will be transmitted from it to other lamps by the wires. Each wire connectes exactly two lamps; one lamp is called the main lamp for this wire (the one that gets power from some other wire and transmits it to this wire), the other one is called the auxiliary lamp (the one that gets power from this wire). Obviously, each lamp has at most one wire that brings power to it (and this lamp is the auxiliary lamp for this wire, and the main lamp for all other wires connected directly to it).Each lamp has a brightness value associated with it, the \(i\)-th lamp has brightness \(2^i\). We define the importance of the wire as the sum of brightness values over all lamps that become disconnected from the grid if the wire is cut (and all other wires are still working).Polycarp has drawn the scheme of the garland he wants to make (the scheme depicts all \(n\) lamp and \(n - 1\) wires, and the lamp that will be connected directly to the grid is marked; the wires are placed in such a way that the power can be transmitted to each lamp). After that, Polycarp calculated the importance of each wire, enumerated them from \(1\) to \(n - 1\) in descending order of their importance, and then wrote the index of the main lamp for each wire (in the order from the first wire to the last one).The following day Polycarp bought all required components of the garland and decided to solder it β€” but he could not find the scheme. Fortunately, Polycarp found the list of indices of main lamps for all wires. Can you help him restore the original scheme?
The first line contains one integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β€” the number of lamps.The second line contains \(n - 1\) integers \(a_1\), \(a_2\), ..., \(a_{n - 1}\) (\(1 \le a_i \le n\)), where \(a_i\) is the index of the main lamp for the \(i\)-th wire (wires are numbered in descending order of importance).
If it is impossible to restore the original scheme, print one integer \(-1\).Otherwise print the scheme as follows. In the first line, print one integer \(k\) (\(1 \le k \le n\)) β€” the index of the lamp that is connected to the power grid. Then print \(n - 1\) lines, each containing two integers \(x_i\) and \(y_i\) (\(1 \le x_i, y_i \le n\), \(x_i \ne y_i\)) β€” the indices of the lamps connected by some wire. The descriptions of the wires (and the lamps connected by a wire) can be printed in any order. The printed description must correspond to a scheme of a garland such that Polycarp could have written the list \(a_1\), \(a_2\), ..., \(a_{n - 1}\) from it. If there are multiple such schemes, output any of them.
The scheme for the first example (R denotes the lamp connected to the grid, the numbers on wires are their importance values):
Input: 6 3 6 3 1 5 | Output: 3 6 3 6 5 1 3 1 4 5 2
Hard
3
1,946
320
720
12
1,934
B
1934B
B. Yet Another Coin Problem
1,200
brute force; dp; greedy; math
You have \(5\) different types of coins, each with a value equal to one of the first \(5\) triangular numbers: \(1\), \(3\), \(6\), \(10\), and \(15\). These coin types are available in abundance. Your goal is to find the minimum number of these coins required such that their total value sums up to exactly \(n\).We can show that the answer always exists.
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 10^9\)) β€” the target value.
For each test case, output a single number β€” the minimum number of coins required.
In the first test case, for \(n = 1\), the answer is \(1\) since only one \(1\) value coin is sufficient. \(1 = 1 \cdot 1\).In the fourth test case, for \(n = 5\), the answer is \(3\), which can be achieved using two \(1\) value coins and one \(3\) value coin. \(5 = 2 \cdot 1 + 1 \cdot 3\).In the seventh test case, for \(n = 12\), the answer is \(2\), which can be achieved using two \(6\) value coins.In the ninth test case, for \(n = 16\), the answer is \(2\), which can be achieved using one \(1\) value coin and one \(15\) value coin or using one \(10\) value coin and one \(6\) value coin. \(16 = 1 \cdot 1 + 1 \cdot 15 = 1 \cdot 6 + 1 \cdot 10\).
Input: 14123571112141617182098402931328 | Output: 1 2 1 3 2 2 2 3 2 3 2 2 8 26862090
Easy
4
356
238
82
19
1,423
A
1423A
A. Wakanda Forever
3,500
In the Kingdom of Wakanda, the 2020 economic crisis has made a great impact on each city and its surrounding area. Cities have made a plan to build a fast train rail between them to boost the economy, but because of the insufficient funds, each city can only build a rail with one other city, and they want to do it together.Cities which are paired up in the plan will share the cost of building the rail between them, and one city might need to pay more than the other. Each city knows the estimated cost of building their part of the rail to every other city. One city can not have the same cost of building the rail with two different cities.If in a plan, there are two cities that are not connected, but the cost to create a rail between them is lower for each of them than the cost to build the rail with their current pairs, then that plan is not acceptable and the collaboration won't go on. Your task is to create a suitable plan for the cities (pairing of the cities) or say that such plan doesn't exist.
First line contains one integer \(N \;(2 \leq N \leq 10^3)\, \) β€” the number of cities.Each of the next \(N\) lines contains \(N-1\) integers \(A_{i,1}, A_{i,2}, ..., A_{i,i-1}, A_{i,i+1}, ..., A_{i,N-1}\; (1 \leq A_{i,j} \leq 10^9)\, \) β€” where \(A_{i,j}\) represents the cost for city \(i\) to build the rail to city \(j\). Note that in each line \(A_{i,i}\) is skipped.
Output should contain \(N\) integers \(O_{1}, O_{2}, ..., O_N\), where \(O_i\) represents the city with which city \(i\) should build the rail with, or \(-1\) if it is not possible to find the stable pairing.
Input: 4 35 19 20 76 14 75 23 43 78 14 76 98 | Output: 3 4 1 2
Master
0
1,013
372
208
14
1,517
F
1517F
F. Reunion
3,200
combinatorics; dp; trees
It is reported that the 2050 Conference will be held in Yunqi Town in Hangzhou from April 23 to 25, including theme forums, morning jogging, camping and so on.The relationship between the \(n\) volunteers of the 2050 Conference can be represented by a tree (a connected undirected graph with \(n\) vertices and \(n-1\) edges). The \(n\) vertices of the tree corresponds to the \(n\) volunteers and are numbered by \(1,2,\ldots, n\).We define the distance between two volunteers \(i\) and \(j\), dis\((i,j)\) as the number of edges on the shortest path from vertex \(i\) to vertex \(j\) on the tree. dis\((i,j)=0\) whenever \(i=j\).Some of the volunteers can attend the on-site reunion while others cannot. If for some volunteer \(x\) and nonnegative integer \(r\), all volunteers whose distance to \(x\) is no more than \(r\) can attend the on-site reunion, a forum with radius \(r\) can take place. The level of the on-site reunion is defined as the maximum possible radius of any forum that can take place.Assume that each volunteer can attend the on-site reunion with probability \(\frac{1}{2}\) and these events are independent. Output the expected level of the on-site reunion. When no volunteer can attend, the level is defined as \(-1\). When all volunteers can attend, the level is defined as \(n\).
The first line contains a single integer \(n\) (\(2\le n\le 300\)) denoting the number of volunteers.Each of the next \(n-1\) lines contains two integers \(a\) and \(b\) denoting an edge between vertex \(a\) and vertex \(b\).
Output the expected level modulo \(998\,244\,353\).Formally, let \(M = 998\,244\,353\). 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, output such an integer \(x\) that \(0 \le x < M\) and \(x \cdot q \equiv p \pmod{M}\).
For the first example, the following table shows all possible outcomes. \(yes\) means the volunteer can attend the on-site reunion and \(no\) means he cannot attend. $$$\(\begin{array}{cccc} 1 & 2 & 3 & level\\ yes & yes & yes & 3\\ yes & yes & no & 1\\ yes & no & yes & 0\\ yes & no & no & 0\\ no & yes & yes & 1\\ no & yes & no & 0\\ no & no & yes & 0\\ no & no & no & -1\\ \end{array}\)\( The expected level is \)\frac{3+1+1+(-1)}{2^3}=\frac{1}{2}$$$.
Input: 3 1 2 2 3 | Output: 499122177
Master
3
1,307
225
408
15
1,061
D
1061D
D. TV Shows
2,000
data structures; greedy; implementation; sortings
There are \(n\) TV shows you want to watch. Suppose the whole time is split into equal parts called ""minutes"". The \(i\)-th of the shows is going from \(l_i\)-th to \(r_i\)-th minute, both ends inclusive.You need a TV to watch a TV show and you can't watch two TV shows which air at the same time on the same TV, so it is possible you will need multiple TVs in some minutes. For example, if segments \([l_i, r_i]\) and \([l_j, r_j]\) intersect, then shows \(i\) and \(j\) can't be watched simultaneously on one TV.Once you start watching a show on some TV it is not possible to ""move"" it to another TV (since it would be too distracting), or to watch another show on the same TV until this show ends.There is a TV Rental shop near you. It rents a TV for \(x\) rupees, and charges \(y\) (\(y < x\)) rupees for every extra minute you keep the TV. So in order to rent a TV for minutes \([a; b]\) you will need to pay \(x + y \cdot (b - a)\). You can assume, that taking and returning of the TV doesn't take any time and doesn't distract from watching other TV shows. Find the minimum possible cost to view all shows. Since this value could be too large, print it modulo \(10^9 + 7\).
The first line contains integers \(n\), \(x\) and \(y\) (\(1 \le n \le 10^5\), \(1 \le y < x \le 10^9\)) β€” the number of TV shows, the cost to rent a TV for the first minute and the cost to rent a TV for every subsequent minute.Each of the next \(n\) lines contains two integers \(l_i\) and \(r_i\) (\(1 \le l_i \le r_i \le 10^9\)) denoting the start and the end minute of the \(i\)-th TV show.
Print exactly one integer β€” the minimum cost to view all the shows taken modulo \(10^9 + 7\).
In the first example, the optimal strategy would be to rent \(3\) TVs to watch: Show \([1, 2]\) on the first TV, Show \([4, 10]\) on the second TV, Shows \([2, 4], [5, 9], [10, 11]\) on the third TV. This way the cost for the first TV is \(4 + 3 \cdot (2 - 1) = 7\), for the second is \(4 + 3 \cdot (10 - 4) = 22\) and for the third is \(4 + 3 \cdot (11 - 2) = 31\), which gives \(60\) int total.In the second example, it is optimal watch each show on a new TV.In third example, it is optimal to watch both shows on a new TV. Note that the answer is to be printed modulo \(10^9 + 7\).
Input: 5 4 31 24 102 410 115 9 | Output: 60
Hard
4
1,184
394
93
10
1,408
D
1408D
D. Searchlights
2,000
binary search; brute force; data structures; dp; implementation; sortings; two pointers
There are \(n\) robbers at coordinates \((a_1, b_1)\), \((a_2, b_2)\), ..., \((a_n, b_n)\) and \(m\) searchlight at coordinates \((c_1, d_1)\), \((c_2, d_2)\), ..., \((c_m, d_m)\). In one move you can move each robber to the right (increase \(a_i\) of each robber by one) or move each robber up (increase \(b_i\) of each robber by one). Note that you should either increase all \(a_i\) or all \(b_i\), you can't increase \(a_i\) for some points and \(b_i\) for some other points.Searchlight \(j\) can see a robber \(i\) if \(a_i \leq c_j\) and \(b_i \leq d_j\). A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair \(i,j\) such that searchlight \(j\) can see a robber \(i\)).What is the minimum number of moves you need to perform to reach a safe configuration?
The first line of input contains two integers \(n\) and \(m\) (\(1 \leq n, m \leq 2000\)): the number of robbers and the number of searchlight.Each of the next \(n\) lines contains two integers \(a_i\), \(b_i\) (\(0 \leq a_i, b_i \leq 10^6\)), coordinates of robbers.Each of the next \(m\) lines contains two integers \(c_i\), \(d_i\) (\(0 \leq c_i, d_i \leq 10^6\)), coordinates of searchlights.
Print one integer: the minimum number of moves you need to perform to reach a safe configuration.
In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates \((3, 0)\).The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates \((2, 3)\) and \(3 > 2\).In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates \((3, 8)\), \((8, 3)\).It's easy the see that the configuration of the robbers is safe.It can be proved that you can't reach a safe configuration using no more than \(3\) moves.
Input: 1 1 0 0 2 3 | Output: 3
Hard
7
804
396
97
14
2,035
C
2035C
C. Alya and Permutation
1,400
bitmasks; constructive algorithms; math
Alya has been given a hard problem. Unfortunately, she is too busy running for student council. Please solve this problem for her.Given an integer \(n\), construct a permutation \(p\) of integers \(1, 2, \ldots, n\) that maximizes the value of \(k\) (which is initially \(0\)) after the following process.Perform \(n\) operations, on the \(i\)-th operation (\(i=1, 2, \dots, n\)), If \(i\) is odd, \(k=k\,\&\,p_i\), where \(\&\) denotes the bitwise AND operation. If \(i\) is even, \(k=k\,|\,p_i\), where \(|\) denotes the bitwise OR operation.
The first line contains a single integer \(t\) (\(1\le t\le 500\)) β€” the number of test cases.The only line of each test case contains a single integer \(n\) (\(5\le n\le 2 \cdot 10^5\)) β€” the length of the permutation.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, output the maximum value of \(k\) in the first line and output the permutation \(p_1, p_2,\ldots, p_n\) in the second line.If there are multiple such permutations, output any.
For the first test case, the value of \(k\) is determined as follows:\(k = 0\) initially. On the \(1\)st operation, \(1\) is odd, so Alya sets \(k\) to be \(k\&p_1 = 0\&2 = 0\). On the \(2\)nd operation, \(2\) is even, so Alya sets \(k\) to be \(k|p_2 = 0|1 = 1\). On the \(3\)rd operation, \(3\) is odd, so Alya sets \(k\) to be \(k\&p_3 = 1\&3 = 1\). On the \(4\)th operation, \(4\) is even, so Alya sets \(k\) to be \(k|p_4 = 1|4 = 5\). On the \(5\)th operation, \(5\) is odd, so Alya sets \(k\) to be \(k\&p_5 = 5\&5 = 5\).The final value of \(k\) is \(5\). It can be shown that the final value of \(k\) is at most \(5\) for all permutations of length \(5\). Another valid output is \([2, 3, 1, 4, 5]\).For the second test case, the final value of \(k\) is \(7\). It can be shown that the final value of \(k\) is at most \(7\) for all permutations of length \(6\). Other valid outputs include \([2, 4, 1, 6, 3, 5]\) and \([5, 2, 6, 1, 3, 4]\).
Input: 65678910 | Output: 5 2 1 3 4 5 7 1 2 4 6 5 3 7 2 4 5 1 3 6 7 15 2 4 5 1 3 6 7 8 9 2 4 5 6 7 1 3 8 9 15 1 2 3 4 5 6 8 10 9 7
Easy
3
544
311
195
20
985
F
985F
F. Isomorphic Strings
2,300
hashing; strings
You are given a string s of length n consisting of lowercase English letters.For two given strings s and t, say S is the set of distinct characters of s and T is the set of distinct characters of t. The strings s and t are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) f between S and T for which f(si) = ti. Formally: f(si) = ti for any index i, for any character there is exactly one character that f(x) = y, for any character there is exactly one character that f(x) = y. For example, the strings ""aababc"" and ""bbcbcz"" are isomorphic. Also the strings ""aaaww"" and ""wwwaa"" are isomorphic. The following pairs of strings are not isomorphic: ""aab"" and ""bbb"", ""test"" and ""best"".You have to handle m queries characterized by three integers x, y, len (1 ≀ x, y ≀ n - len + 1). For each query check if two substrings s[x... x + len - 1] and s[y... y + len - 1] are isomorphic.
The first line contains two space-separated integers n and m (1 ≀ n ≀ 2Β·105, 1 ≀ m ≀ 2Β·105) β€” the length of the string s and the number of queries.The second line contains string s consisting of n lowercase English letters.The following m lines contain a single query on each line: xi, yi and leni (1 ≀ xi, yi ≀ n, 1 ≀ leni ≀ n - max(xi, yi) + 1) β€” the description of the pair of the substrings to check.
For each query in a separate line print ""YES"" if substrings s[xi... xi + leni - 1] and s[yi... yi + leni - 1] are isomorphic and ""NO"" otherwise.
The queries in the example are following: substrings ""a"" and ""a"" are isomorphic: f(a) = a; substrings ""ab"" and ""ca"" are isomorphic: f(a) = c, f(b) = a; substrings ""bac"" and ""aba"" are not isomorphic since f(b) and f(c) must be equal to a at same time; substrings ""bac"" and ""cab"" are isomorphic: f(b) = c, f(a) = a, f(c) = b.
Input: 7 4abacaba1 1 11 4 22 1 32 4 3 | Output: YESYESNOYES
Expert
2
926
404
148
9
1,326
E
1326E
E. Bombs
2,400
data structures; two pointers
You are given a permutation, \(p_1, p_2, \ldots, p_n\).Imagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb.For some fixed configuration of bombs, consider the following process. Initially, there is an empty set, \(A\).For each \(i\) from \(1\) to \(n\): Add \(p_i\) to \(A\). If the \(i\)-th position contains a bomb, remove the largest element in \(A\).After the process is completed, \(A\) will be non-empty. The cost of the configuration of bombs equals the largest element in \(A\).You are given another permutation, \(q_1, q_2, \ldots, q_n\).For each \(1 \leq i \leq n\), find the cost of a configuration of bombs such that there exists a bomb in positions \(q_1, q_2, \ldots, q_{i-1}\). For example, for \(i=1\), you need to find the cost of a configuration without bombs, and for \(i=n\), you need to find the cost of a configuration with bombs in positions \(q_1, q_2, \ldots, q_{n-1}\).
The first line contains a single integer, \(n\) (\(2 \leq n \leq 300\,000\)).The second line contains \(n\) distinct integers \(p_1, p_2, \ldots, p_n\) (\(1 \leq p_i \leq n)\).The third line contains \(n\) distinct integers \(q_1, q_2, \ldots, q_n\) (\(1 \leq q_i \leq n)\).
Print \(n\) space-separated integers, such that the \(i\)-th of them equals the cost of a configuration of bombs in positions \(q_1, q_2, \ldots, q_{i-1}\).
In the first test: If there are no bombs, \(A\) is equal to \(\{1, 2, 3\}\) at the end of the process, so the cost of the configuration is \(3\). If there is one bomb in position \(1\), \(A\) is equal to \(\{1, 2\}\) at the end of the process, so the cost of the configuration is \(2\); If there are two bombs in positions \(1\) and \(2\), \(A\) is equal to \(\{1\}\) at the end of the process, so the cost of the configuration is \(1\). In the second test:Let's consider the process for \(i = 4\). There are three bombs on positions \(q_1 = 5\), \(q_2 = 2\), and \(q_3 = 1\).At the beginning, \(A = \{\}\). Operation \(1\): Add \(p_1 = 2\) to \(A\), so \(A\) is equal to \(\{2\}\). There exists a bomb in position \(1\), so we should delete the largest element from \(A\). \(A\) is equal to \(\{\}\). Operation \(2\): Add \(p_2 = 3\) to \(A\), so \(A\) is equal to \(\{3\}\). There exists a bomb in position \(2\), so we should delete the largest element from \(A\). \(A\) is equal to \(\{\}\). Operation \(3\): Add \(p_3 = 6\) to \(A\), so \(A\) is equal to \(\{6\}\). There is no bomb in position \(3\), so we do nothing. Operation \(4\): Add \(p_4 = 1\) to \(A\), so \(A\) is equal to \(\{1, 6\}\). There is no bomb in position \(4\), so we do nothing. Operation \(5\): Add \(p_5 = 5\) to \(A\), so \(A\) is equal to \(\{1, 5, 6\}\). There exists a bomb in position \(5\), so we delete the largest element from \(A\). Now, \(A\) is equal to \(\{1, 5\}\). Operation \(6\): Add \(p_6 = 4\) to \(A\), so \(A\) is equal to \(\{1, 4, 5\}\). There is no bomb in position \(6\), so we do nothing. In the end, we have \(A = \{1, 4, 5\}\), so the cost of the configuration is equal to \(5\).
Input: 3 3 2 1 1 2 3 | Output: 3 2 1
Expert
2
965
274
156
13
1,952
J
1952J
J. Help, what does it mean to be ""Based""
0
*special; brute force; constructive algorithms; expression parsing; implementation; sortings
Sup, gimme a single integer \(x\) (\(1 \le x \le 4\)) homie uwu :3
If \(x = 1\), spit out some based code that, like when ya feed it two integers \(a\) and \(b\), it hands over their sum.If \(x = 2\), slap some based code that takes an integer \(a\) and returns its absolute value like magic, no cap.If \(x = 3\), check this out: blaze some based code that grabs an integer \(n\) (\(1 \le n \le 50\)) and an array \(a\) of \(n\) distinct integers, then flexes the maximum value real quick.If \(x = 4\), toss me some based code that snatches an integer \(n\) (\(1 \le n \le 50\)), an array \(a\) of \(n\) distinct integers and an integer \(k\) (\(1 \le k \le n\)), then nails down that \(k\)-th largest value in the array. Get it, fam!
Slide into the ""My Submissions"" page and vibe check ur code by clicking on its ID. You'll see just how based or cringe it is.
Input: 1 | Output: yoink a yoink b *slaps a on top of b* yeet b go touch some grass
Beginner
6
0
66
667
19
1,245
D
1245D
D. Shichikuji and Power Grid
1,900
dsu; graphs; greedy; shortest paths; trees
Shichikuji 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.
First 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\)).
In 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.
For 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.
Input: 3 2 3 1 1 3 2 3 2 3 3 2 3 | Output: 8 3 1 2 3 0
Hard
5
1,941
567
963
12
1,505
E
1505E
E. Cakewalk
1,800
*special; greedy; implementation; shortest paths
A mouse encountered a nice big cake and decided to take a walk across it, eating the berries on top of the cake on its way. The cake is rectangular, neatly divided into squares; some of the squares have a berry in them, and some don't.The mouse is in a bit of a hurry, though, so once she enters the cake from its northwest corner (the top left cell in the input data), she will only go east (right) or south (down), until she reaches the southeast corner (the bottom right cell). She will eat every berry in the squares she passes through, but not in the other squares.The mouse tries to choose her path so as to maximize the number of berries consumed. However, her haste and hunger might be clouding her judgement, leading her to suboptimal decisions...
The first line of input contains two integers \(H\) and \(W\) (\(1 \le H, W \le 5\)), separated by a space, β€” the height and the width of the cake.The next \(H\) lines contain a string of \(W\) characters each, representing the squares of the cake in that row: '.' represents an empty square, and '*' represents a square with a berry.
Output the number of berries the mouse will eat following her strategy.
Input: 4 3 *.. .*. ..* ... | Output: 3
Medium
4
756
334
71
15
1,662
M
1662M
M. Bottle Arrangements
0
constructive algorithms
Gabriella has been instructed to organize a renowned wine tasting event which will be attended by \(m\) critics. On display, there will be \(n\) different varieties of wine, each of which can either be a red wine or a white wine.The wines will come in \(n\) bottles arranged in a line on the table, and, for convenience, each critic will sip from a contiguous interval of bottles: that is, he/she will taste exactly the bottles at position \(a, \, a + 1, \, \dots, \, b\) for some \(1 \le a \le b \le n\). The interval depends on the critic, who will select it on the spot according to their preferences. In fact, the \(i\)-th critic (\(1 \le i \le m\)) has requested that he/she wants to taste exactly \(r_i\) red wines and \(w_i\) white wines.Gabriella has yet to choose how many bottles of red wine and white wine there will be, and in what order they will appear. Help her find an arrangement (that is, a sequence of \(n\) bottles of either red or white wine) that satisfies the requests of all the critics, or state that no such arrangement exists.
Each test contains multiple test cases. The first line contains an integer \(t\) (\(1\le t\le 100\)) β€” the number of test cases. The descriptions of the \(t\) test cases follow.The first line of each test case contains two integers \(n\) and \(m\) (\(1 \le n \le 100\), \(1 \le m \le 100\)) β€” the number of bottles of wine and the number of critics.Each of the next \(m\) lines contains two integers \(r_i\) and \(w_i\) (\(0 \le r_i, \, w_i \le 100\), \(r_i + w_i \ge 1\)) β€” the number of red and white wines that the \(i\)-th critic wants to taste.
For each test case, if at least one solution exists, print a string of length \(n\) made up of the characters R and W, where the \(j\)-th character (\(1 \le j \le n\)) denotes the type of the wine in the \(j\)-th bottle of the arrangement (R for red and W for white). If there are multiple solutions, print any.If no solution exists, print the string IMPOSSIBLE.
In the first test case, there are \(n = 5\) bottles of wine to be arranged and \(m = 3\) critics. The arrangement RWRRW satisfies the requests of all three critics. Indeed: the first critic can choose the interval \([3, \, 3]\), which contains exactly one bottle of red wine (note that \([1, \, 1]\) and \([4, \, 4]\) are other valid choices); the second critic can choose the interval \([1, \, 5]\), which contains \(3\) bottles of red wine and \(2\) bottles of white wine; the third critic can choose the interval \([2, \, 5]\), which contains \(2\) bottles of red wine and \(2\) bottles of white wine.
Input: 35 31 03 22 24 32 11 10 33 20 20 3 | Output: RWRRW IMPOSSIBLE WWW
Beginner
1
1,053
549
362
16
178
F3
178F3
F3. Representative Sampling
2,500
The Smart Beaver from ABBYY has a long history of cooperating with the ""Institute of Cytology and Genetics"". Recently, the Institute staff challenged the Beaver with a new problem. The problem is as follows.There is a collection of n proteins (not necessarily distinct). Each protein is a string consisting of lowercase Latin letters. The problem that the scientists offered to the Beaver is to select a subcollection of size k from the initial collection of proteins so that the representativity of the selected subset of proteins is maximum possible.The Smart Beaver from ABBYY did some research and came to the conclusion that the representativity of a collection of proteins can be evaluated by a single number, which is simply calculated. Let's suppose we have a collection {a1, ..., ak} consisting of k strings describing proteins. The representativity of this collection is the following value: where f(x, y) is the length of the longest common prefix of strings x and y; for example, f(""abc"", ""abd"") = 2, and f(""ab"", ""bcd"") = 0.Thus, the representativity of collection of proteins {""abc"", ""abd"", ""abe""} equals 6, and the representativity of collection {""aaa"", ""ba"", ""ba""} equals 2.Having discovered that, the Smart Beaver from ABBYY asked the Cup contestants to write a program that selects, from the given collection of proteins, a subcollection of size k which has the largest possible value of representativity. Help him to solve this problem!
The first input line contains two integers n and k (1 ≀ k ≀ n), separated by a single space. The following n lines contain the descriptions of proteins, one per line. Each protein is a non-empty string of no more than 500 characters consisting of only lowercase Latin letters (a...z). Some of the strings may be equal.The input limitations for getting 20 points are: 1 ≀ n ≀ 20 The input limitations for getting 50 points are: 1 ≀ n ≀ 100 The input limitations for getting 100 points are: 1 ≀ n ≀ 2000
Print a single number denoting the largest possible value of representativity that a subcollection of size k of the given collection of proteins can have.
Input: 3 2ababzdabq | Output: 2
Expert
0
1,476
501
154
1
900
D
900D
D. Unusual Sequences
2,000
bitmasks; combinatorics; dp; math; number theory
Count the number of distinct sequences a1, a2, ..., an (1 ≀ ai) consisting of positive integers such that gcd(a1, a2, ..., an) = x and . As this number could be large, print the answer modulo 109 + 7.gcd here means the greatest common divisor.
The only line contains two positive integers x and y (1 ≀ x, y ≀ 109).
Print the number of such sequences modulo 109 + 7.
There are three suitable sequences in the first test: (3, 3, 3), (3, 6), (6, 3).There are no suitable sequences in the second test.
Input: 3 9 | Output: 3
Hard
5
243
70
50
9
725
B
725B
B. Food on the Plane
1,200
implementation; math
A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats 'd', 'e' and 'f' are located to the right. Seats 'a' and 'f' are located near the windows, while seats 'c' and 'd' are located near the aisle. It's lunch time and two flight attendants have just started to serve food. They move from the first rows to the tail, always maintaining a distance of two rows from each other because of the food trolley. Thus, at the beginning the first attendant serves row 1 while the second attendant serves row 3. When both rows are done they move one row forward: the first attendant serves row 2 while the second attendant serves row 4. Then they move three rows forward and the first attendant serves row 5 while the second attendant serves row 7. Then they move one row forward again and so on.Flight attendants work with the same speed: it takes exactly 1 second to serve one passenger and 1 second to move one row forward. Each attendant first serves the passengers on the seats to the right of the aisle and then serves passengers on the seats to the left of the aisle (if one looks in the direction of the cockpit). Moreover, they always serve passengers in order from the window to the aisle. Thus, the first passenger to receive food in each row is located in seat 'f', and the last one β€” in seat 'c'. Assume that all seats are occupied.Vasya has seat s in row n and wants to know how many seconds will pass before he gets his lunch.
The only line of input contains a description of Vasya's seat in the format ns, where n (1 ≀ n ≀ 1018) is the index of the row and s is the seat in this row, denoted as letter from 'a' to 'f'. The index of the row and the seat are not separated by a space.
Print one integer β€” the number of seconds Vasya has to wait until he gets his lunch.
In the first sample, the first flight attendant serves Vasya first, so Vasya gets his lunch after 1 second.In the second sample, the flight attendants will spend 6 seconds to serve everyone in the rows 1 and 3, then they will move one row forward in 1 second. As they first serve seats located to the right of the aisle in order from window to aisle, Vasya has to wait 3 more seconds. The total is 6 + 1 + 3 = 10.
Input: 1f | Output: 1
Easy
2
1,695
256
84
7
958
E1
958E1
E1. Guard Duty (easy)
1,600
brute force; geometry; greedy; math
The Rebel fleet is afraid that the Empire might want to strike back again. Princess Heidi needs to know if it is possible to assign R Rebel spaceships to guard B bases so that every base has exactly one guardian and each spaceship has exactly one assigned base (in other words, the assignment is a perfect matching). Since she knows how reckless her pilots are, she wants to be sure that any two (straight) paths – from a base to its assigned spaceship – do not intersect in the galaxy plane (that is, in 2D), and so there is no risk of collision.
The first line contains two space-separated integers R, B(1 ≀ R, B ≀ 10). For 1 ≀ i ≀ R, the i + 1-th line contains two space-separated integers xi and yi (|xi|, |yi| ≀ 10000) denoting the coordinates of the i-th Rebel spaceship. The following B lines have the same format, denoting the position of bases. It is guaranteed that no two points coincide and that no three points are on the same line.
If it is possible to connect Rebel spaceships and bases so as satisfy the constraint, output Yes, otherwise output No (without quote).
For the first example, one possible way is to connect the Rebels and bases in order.For the second example, there is no perfect matching between Rebels and bases.
Input: 3 30 02 03 1-2 10 32 2 | Output: Yes
Medium
4
547
397
134
9
570
C
570C
C. Replacement
1,600
constructive algorithms; data structures; implementation
Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring "".."" (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ""."". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.You need to process m queries, the i-th results in that the character at position xi (1 ≀ xi ≀ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).Help Daniel to process all queries.
The first line contains two integers n and m (1 ≀ n, m ≀ 300 000) the length of the string and the number of queries.The second line contains string s, consisting of n lowercase English letters and period signs.The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≀ xi ≀ n, ci β€” a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.
Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.
Note to the first sample test (replaced periods are enclosed in square brackets).The original string is "".b..bz...."". after the first query f(hb..bz....) = 4 (""hb[..]bz...."" β†’ ""hb.bz[..].."" β†’ ""hb.bz[..]."" β†’ ""hb.bz[..]"" β†’ ""hb.bz."") after the second query f(hbс.bz....) = 3 (""hbс.bz[..].."" β†’ ""hbс.bz[..]."" β†’ ""hbс.bz[..]"" β†’ ""hbс.bz."") after the third query f(hbс.bz..f.) = 1 (""hbс.bz[..]f."" β†’ ""hbс.bz.f."")Note to the second sample test.The original string is "".cc."". after the first query: f(..c.) = 1 (""[..]c."" β†’ "".c."") after the second query: f(....) = 3 (""[..].."" β†’ ""[..]."" β†’ ""[..]"" β†’ ""."") after the third query: f(.a..) = 1 ("".a[..]"" β†’ "".a."") after the fourth query: f(aa..) = 1 (""aa[..]"" β†’ ""aa."")
Input: 10 3.b..bz....1 h3 c9 f | Output: 431
Medium
3
910
433
129
5
1,836
A
1836A
A. Destroyer
800
implementation; sortings
John is a lead programmer on a destroyer belonging to the space navy of the Confederacy of Independent Operating Systems. One of his tasks is checking if the electronic brains of robots were damaged during battles.A standard test is to order the robots to form one or several lines, in each line the robots should stand one after another. After that, each robot reports the number of robots standing in front of it in its line. An example of robots' arrangement (the front of the lines is on the left). The robots report the numbers above. The \(i\)-th robot reported number \(l_i\). Unfortunately, John does not know which line each robot stands in, and can't check the reported numbers. Please determine if it is possible to form the lines in such a way that all reported numbers are correct, or not.
The first line contains a single integer \(t\) (\(1 \leq t \leq 100\)), denoting the number of test cases.The first line in each test case contains a single integer \(n\) (\(1 \le n \le 100\)) β€” the number of robots.The second line in each test case contains \(n\) integers \(l_1, l_2, \ldots, l_n\) (\(0 \leq l_i < 100\)), \(l_i\) is equal to the number of robots in front of the \(i\)-th robot in its line.The sum of \(n\) over all test cases won't exceed \(200\).
For each test case, output ""YES"", if there exists a robot arrangement consistent with robots' reports. Otherwise, output ""NO"".You can output the answer in any case (upper or lower). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be recognized as positive responses.
Example arrangement consistent with robot statements from the first example test case: Example arrangement consistent with robot statements from the second example is shown in the statement.In the third test case, the third robot claims that there are two machines in front of it. In such a case, the robot directly in front of it would have one machine in front. No robot claims that, so there is no valid arrangement.
Input: 560 1 2 0 1 090 0 0 0 1 1 1 2 230 0 219950 1 2 3 4 | Output: YES YES NO NO YES
Beginner
2
802
466
291
18
741
B
741B
B. Arpa's weak amphitheater and Mehrdad's valuable Hoses
1,600
dfs and similar; dp; dsu
Just to remind, girls in Arpa's land are really nice.Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≀ i < k, and a1 = x and ak = y. Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.
The first line contains integers n, m and w (1 ≀ n ≀ 1000, , 1 ≀ w ≀ 1000) β€” the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.The second line contains n integers w1, w2, ..., wn (1 ≀ wi ≀ 1000) β€” the weights of the Hoses.The third line contains n integers b1, b2, ..., bn (1 ≀ bi ≀ 106) β€” the beauties of the Hoses.The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≀ xi, yi ≀ n, xi β‰  yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.
Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.
In the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.
Input: 3 1 53 2 52 4 21 2 | Output: 6
Medium
3
1,000
603
131
7
1,552
A
1552A
A. Subsequence Permutation
800
sortings; strings
A string \(s\) of length \(n\), consisting of lowercase letters of the English alphabet, is given.You must choose some number \(k\) between \(0\) and \(n\). Then, you select \(k\) characters of \(s\) and permute them however you want. In this process, the positions of the other \(n-k\) characters remain unchanged. You have to perform this operation exactly once.For example, if \(s=\texttt{""andrea""}\), you can choose the \(k=4\) characters \(\texttt{""a_d_ea""}\) and permute them into \(\texttt{""d_e_aa""}\) so that after the operation the string becomes \(\texttt{""dneraa""}\).Determine the minimum \(k\) so that it is possible to sort \(s\) alphabetically (that is, after the operation its characters appear in alphabetical order).
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases. Then \(t\) test cases follow.The first line of each test case contains one integer \(n\) (\(1 \le n \le 40\)) β€” the length of the string.The second line of each test case contains the string \(s\). It is guaranteed that \(s\) contains only lowercase letters of the English alphabet.
For each test case, output the minimum \(k\) that allows you to obtain a string sorted alphabetically, through the operation described above.
In the first test case, we can choose the \(k=2\) characters \(\texttt{""_ol""}\) and rearrange them as \(\texttt{""_lo""}\) (so the resulting string is \(\texttt{""llo""}\)). It is not possible to sort the string choosing strictly less than \(2\) characters.In the second test case, one possible way to sort \(s\) is to consider the \(k=6\) characters \(\texttt{""_o__force_""}\) and rearrange them as \(\texttt{""_c__efoor_""}\) (so the resulting string is \(\texttt{""ccdeefoors""}\)). One can show that it is not possible to sort the string choosing strictly less than \(6\) characters.In the third test case, string \(s\) is already sorted (so we can choose \(k=0\) characters).In the fourth test case, we can choose all \(k=4\) characters \(\texttt{""dcba""}\) and reverse the whole string (so the resulting string is \(\texttt{""abcd""}\)).
Input: 4 3 lol 10 codeforces 5 aaaaa 4 dcba | Output: 2 6 0 4
Beginner
2
741
380
141
15
1,569
C
1569C
C. Jury Meeting
1,500
combinatorics; math
\(n\) people gathered to hold a jury meeting of the upcoming competition, the \(i\)-th member of the jury came up with \(a_i\) tasks, which they want to share with each other.First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation \(p\) of numbers from \(1\) to \(n\) (an array of size \(n\) where each integer from \(1\) to \(n\) occurs exactly once).Then the discussion goes as follows: If a jury member \(p_1\) has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If a jury member \(p_2\) has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. ... If a jury member \(p_n\) has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends. A permutation \(p\) is nice if none of the jury members tell two or more of their own tasks in a row. Count the number of nice permutations. The answer may be really large, so print it modulo \(998\,244\,353\).
The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases.The first line of the test case contains a single integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)) β€” number of jury members.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)) β€” the number of problems that the \(i\)-th member of the jury came up with.The sum of \(n\) over all test cases does not exceed \(2 \cdot 10^5\).
For each test case, print one integer β€” the number of nice permutations, taken modulo \(998\,244\,353\).
Explanation of the first test case from the example:There are two possible permutations, \(p = [1, 2]\) and \(p = [2, 1]\). For \(p = [1, 2]\), the process is the following: the first jury member tells a task; the second jury member tells a task; the first jury member doesn't have any tasks left to tell, so they are skipped; the second jury member tells a task. So, the second jury member has told two tasks in a row (in succession), so the permutation is not nice.For \(p = [2, 1]\), the process is the following: the second jury member tells a task; the first jury member tells a task; the second jury member tells a task. So, this permutation is nice.
Input: 4 2 1 2 3 5 5 5 4 1 3 3 7 6 3 4 2 1 3 3 | Output: 1 6 0 540
Medium
2
1,132
452
104
15
1,015
F
1015F
F. Bracket Substring
2,300
dp; strings
You are given a bracket sequence \(s\) (not necessarily a regular one). A bracket sequence is a string containing only characters '(' and ')'.A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences ""()()"" and ""(())"" are regular (the resulting expressions are: ""(1)+(1)"" and ""((1+1)+1)""), and "")("", ""("" and "")"" are not.Your problem is to calculate the number of regular bracket sequences of length \(2n\) containing the given bracket sequence \(s\) as a substring (consecutive sequence of characters) modulo \(10^9+7\) (\(1000000007\)).
The first line of the input contains one integer \(n\) (\(1 \le n \le 100\)) β€” the half-length of the resulting regular bracket sequences (the resulting sequences must have length equal to \(2n\)).The second line of the input contains one string \(s\) (\(1 \le |s| \le 200\)) β€” the string \(s\) that should be a substring in each of the resulting regular bracket sequences (\(|s|\) is the length of \(s\)).
Print only one integer β€” the number of regular bracket sequences containing the given bracket sequence \(s\) as a substring. Since this number can be huge, print it modulo \(10^9+7\) (\(1000000007\)).
All regular bracket sequences satisfying the conditions above for the first example: ""(((()))())""; ""((()()))()""; ""((()))()()""; ""(()(()))()""; ""()((()))()"". All regular bracket sequences satisfying the conditions above for the second example: ""((()))""; ""(()())""; ""(())()""; ""()(())"". And there is no regular bracket sequences of length \(4\) containing ""((("" as a substring in the third example.
Input: 5()))() | Output: 5
Expert
2
719
406
200
10
1,539
C
1539C
C. Stable Groups
1,200
greedy; sortings
There are \(n\) students numerated from \(1\) to \(n\). The level of the \(i\)-th student is \(a_i\). You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than \(x\).For example, if \(x = 4\), then the group with levels \([1, 10, 8, 4, 4]\) is stable (because \(4 - 1 \le x\), \(4 - 4 \le x\), \(8 - 4 \le x\), \(10 - 8 \le x\)), while the group with levels \([2, 10, 10, 7]\) is not stable (\(7 - 2 = 5 > x\)).Apart from the \(n\) given students, teachers can invite at most \(k\) additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).For example, if there are two students with levels \(1\) and \(5\); \(x = 2\); and \(k \ge 1\), then you can invite a new student with level \(3\) and put all the students in one stable group.
The first line contains three integers \(n\), \(k\), \(x\) (\(1 \le n \le 200\,000\), \(0 \le k \le 10^{18}\), \(1 \le x \le 10^{18}\)) β€” the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference.The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^{18}\)) β€” the students levels.
In the only line print a single integer: the minimum number of stable groups you can split the students into.
In the first example you can invite two students with levels \(2\) and \(11\). Then you can split the students into two stable groups: \([1, 1, 2, 5, 8, 11, 12, 13]\), \([20, 22]\). In the second example you are not allowed to invite new students, so you need \(3\) groups: \([1, 1, 5, 5, 20, 20]\) \([60, 70, 70, 70, 80, 90]\) \([420]\)
Input: 8 2 3 1 1 5 8 12 13 20 22 | Output: 2
Easy
2
964
378
109
15
1,070
M
1070M
M. Algoland and Berland
3,000
constructive algorithms; divide and conquer; geometry
Once upon a time Algoland and Berland were a single country, but those times are long gone. Now they are two different countries, but their cities are scattered on a common territory.All cities are represented as points on the Cartesian plane. Algoland consists of \(a\) cities numbered from \(1\) to \(a\). The coordinates of the \(i\)-th Algoland city are a pair of integer numbers \((xa_i, ya_i)\). Similarly, Berland consists of \(b\) cities numbered from \(1\) to \(b\). The coordinates of the \(j\)-th Berland city are a pair of integer numbers \((xb_j, yb_j)\). No three of the \(a+b\) mentioned cities lie on a single straight line.As the first step to unite the countries, Berland decided to build several bidirectional freeways. Each freeway is going to be a line segment that starts in a Berland city and ends in an Algoland city. Freeways can't intersect with each other at any point except freeway's start or end. Moreover, the freeways have to connect all \(a+b\) cities. Here, connectivity means that one can get from any of the specified \(a+b\) cities to any other of the \(a+b\) cities using freeways. Note that all freeways are bidirectional, which means that one can drive on each of them in both directions.Mayor of each of the \(b\) Berland cities allocated a budget to build the freeways that start from this city. Thus, you are given the numbers \(r_1, r_2, \dots, r_b\), where \(r_j\) is the number of freeways that are going to start in the \(j\)-th Berland city. The total allocated budget is very tight and only covers building the minimal necessary set of freeways. In other words, \(r_1+r_2+\dots+r_b=a+b-1\).Help Berland to build the freeways so that: each freeway is a line segment connecting a Berland city and an Algoland city, no freeways intersect with each other except for the freeway's start or end, freeways connect all \(a+b\) cities (all freeways are bidirectional), there are \(r_j\) freeways that start from the \(j\)-th Berland city.
Input contains one or several test cases. The first input line contains a single integer number \(t\) (\(1 \le t \le 3000\)) β€” number of test cases. Then, \(t\) test cases follow. Solve test cases separately, test cases are completely independent and do not affect each other.Each test case starts with a line containing space-separated integers \(a\) and \(b\) (\(1 \le a, b \le 3000\)) β€” numbers of Algoland cities and number of Berland cities correspondingly.The next line contains \(b\) space-separated integers \(r_1, r_2, \dots, r_b\) (\(1 \le r_b \le a\)) where \(r_j\) is the number of freeways, that should start in the \(j\)-th Berland city. It is guaranteed that \(r_1+r_2+\dots+r_b=a+b-1\).The next \(a\) lines contain coordinates of the Algoland cities β€” pairs of space-separated integers \(xa_i, ya_i\) (\(-10000 \le xa_i, ya_i \le 10000\)). The next \(b\) lines contain coordinates of the Berland cities β€” pairs of space-separated integers \(xb_i, yb_i\) (\(-10000 \le xb_i, yb_i \le 10000\)). All cities are located at distinct points, no three of the \(a+b\) cities lie on a single straight line.Sum of values \(a\) across all test cases doesn't exceed \(3000\). Sum of values \(b\) across all test cases doesn't exceed \(3000\).
For each of the \(t\) test cases, first print ""YES"" if there is an answer or ""NO"" otherwise.If there is an answer, print the freeway building plan in the next \(a+b-1\) lines. Each line of the plan should contain two space-separated integers \(j\) and \(i\) which means that a freeway from the \(j\)-th Berland city to the \(i\)-th Algoland city should be built. If there are multiple solutions, print any.
Input: 22 31 1 20 01 11 23 24 01 110 00 1 | Output: YES2 21 23 23 1YES1 1
Master
3
1,978
1,246
410
10
1,373
G
1373G
G. Pawns
2,600
data structures; divide and conquer; greedy
You are given a chessboard consisting of \(n\) rows and \(n\) columns. Rows are numbered from bottom to top from \(1\) to \(n\). Columns are numbered from left to right from \(1\) to \(n\). The cell at the intersection of the \(x\)-th column and the \(y\)-th row is denoted as \((x, y)\). Furthermore, the \(k\)-th column is a special column. Initially, the board is empty. There are \(m\) changes to the board. During the \(i\)-th change one pawn is added or removed from the board. The current board is good if we can move all pawns to the special column by the followings rules: Pawn in the cell \((x, y)\) can be moved to the cell \((x, y + 1)\), \((x - 1, y + 1)\) or \((x + 1, y + 1)\); You can make as many such moves as you like; Pawns can not be moved outside the chessboard; Each cell can not contain more than one pawn. The current board may not always be good. To fix it, you can add new rows to the board. New rows are added at the top, i. e. they will have numbers \(n+1, n+2, n+3, \dots\).After each of \(m\) changes, print one integer β€” the minimum number of rows which you have to add to make the board good.
The first line contains three integers \(n\), \(k\) and \(m\) (\(1 \le n, m \le 2 \cdot 10^5; 1 \le k \le n\)) β€” the size of the board, the index of the special column and the number of changes respectively.Then \(m\) lines follow. The \(i\)-th line contains two integers \(x\) and \(y\) (\(1 \le x, y \le n\)) β€” the index of the column and the index of the row respectively. If there is no pawn in the cell \((x, y)\), then you add a pawn to this cell, otherwise β€” you remove the pawn from this cell.
After each change print one integer β€” the minimum number of rows which you have to add to make the board good.
Input: 5 3 5 4 4 3 5 2 4 3 4 3 5 | Output: 0 1 2 2 1
Expert
3
1,125
501
110
13
2,112
C
2112C
C. Coloring Game
1,300
binary search; brute force; greedy; two pointers
Alice and Bob are playing a game using an integer array \(a\) of size \(n\).Initially, all elements of the array are colorless. First, Alice chooses \(3\) elements and colors them red. Then Bob chooses any element and colors it blue (if it was red β€” recolor it). Alice wins if the sum of the red elements is strictly greater than the value of the blue element.Your task is to calculate the number of ways that Alice can choose \(3\) elements in order to win regardless of Bob's actions.
The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases.The first line of each test case contains a single integer \(n\) (\(3 \le n \le 5000\)).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_1 \le a_2 \le \cdots \le a_n \le 10^5\)).Additional constraint on the input: the sum of \(n\) over all test cases doesn't exceed \(5000\).
For each test case, print a single integer β€” the number of ways that Alice can choose \(3\) elements in order to win regardless of Bob's actions.
In the first two test cases, no matter which three elements Alice chooses, Bob will be able to paint one element blue so that Alice does not win.In the third test case, Alice can choose any three elements. If Bob colors one of the red elements, the sum of red elements will be \(14\), and the sum of blue elements will be \(7\). If Bob chooses an uncolored element, the sum of red elements will be \(21\), and the sum of blue elements will be \(7\).In the fourth test case, Alice can choose either the \(1\)-st, \(3\)-rd and \(4\)-th element, or the \(2\)-nd, \(3\)-rd and \(4\)-th element.
Input: 631 2 341 1 2 457 7 7 7 751 1 2 2 462 3 3 4 5 551 1 1 1 3 | Output: 0 0 10 2 16 0
Easy
4
486
399
145
21
1,332
C
1332C
C. K-Complete Word
1,500
dfs and similar; dsu; greedy; implementation; strings
Word \(s\) of length \(n\) is called \(k\)-complete if \(s\) is a palindrome, i.e. \(s_i=s_{n+1-i}\) for all \(1 \le i \le n\); \(s\) has a period of \(k\), i.e. \(s_i=s_{k+i}\) for all \(1 \le i \le n-k\). For example, ""abaaba"" is a \(3\)-complete word, while ""abccba"" is not.Bob is given a word \(s\) of length \(n\) consisting of only lowercase Latin letters and an integer \(k\), such that \(n\) is divisible by \(k\). He wants to convert \(s\) to any \(k\)-complete word.To do this Bob can choose some \(i\) (\(1 \le i \le n\)) and replace the letter at position \(i\) with some other lowercase Latin letter.So now Bob wants to know the minimum number of letters he has to replace to convert \(s\) to any \(k\)-complete word.Note that Bob can do zero changes if the word \(s\) is already \(k\)-complete.You are required to answer \(t\) test cases independently.
The first line contains a single integer \(t\) (\(1 \le t\le 10^5\)) β€” the number of test cases.The first line of each test case contains two integers \(n\) and \(k\) (\(1 \le k < n \le 2 \cdot 10^5\), \(n\) is divisible by \(k\)).The second line of each test case contains a word \(s\) of length \(n\).It is guaranteed that word \(s\) only contains lowercase Latin letters. And it is guaranteed that the sum of \(n\) over all test cases will not exceed \(2 \cdot 10^5\).
For each test case, output one integer, representing the minimum number of characters he has to replace to convert \(s\) to any \(k\)-complete word.
In the first test case, one optimal solution is aaaaaa.In the second test case, the given word itself is \(k\)-complete.
Input: 4 6 2 abaaba 6 3 abaaba 36 9 hippopotomonstrosesquippedaliophobia 21 7 wudixiaoxingxingheclp | Output: 2 0 23 16
Medium
5
870
471
148
13
1,139
C
1139C
C. Edgy Trees
1,500
dfs and similar; dsu; graphs; math; trees
You are given a tree (a connected undirected graph without cycles) of \(n\) vertices. Each of the \(n - 1\) edges of the tree is colored in either black or red.You are also given an integer \(k\). Consider sequences of \(k\) vertices. Let's call a sequence \([a_1, a_2, \ldots, a_k]\) good if it satisfies the following criterion: We will walk a path (possibly visiting same edge/vertex multiple times) on the tree, starting from \(a_1\) and ending at \(a_k\). Start at \(a_1\), then go to \(a_2\) using the shortest path between \(a_1\) and \(a_2\), then go to \(a_3\) in a similar way, and so on, until you travel the shortest path between \(a_{k-1}\) and \(a_k\). If you walked over at least one black edge during this process, then the sequence is good. Consider the tree on the picture. If \(k=3\) then the following sequences are good: \([1, 4, 7]\), \([5, 5, 3]\) and \([2, 3, 7]\). The following sequences are not good: \([1, 4, 6]\), \([5, 5, 5]\), \([3, 7, 3]\).There are \(n^k\) sequences of vertices, count how many of them are good. Since this number can be quite large, print it modulo \(10^9+7\).
The first line contains two integers \(n\) and \(k\) (\(2 \le n \le 10^5\), \(2 \le k \le 100\)), the size of the tree and the length of the vertex sequence.Each of the next \(n - 1\) lines contains three integers \(u_i\), \(v_i\) and \(x_i\) (\(1 \le u_i, v_i \le n\), \(x_i \in \{0, 1\}\)), where \(u_i\) and \(v_i\) denote the endpoints of the corresponding edge and \(x_i\) is the color of this edge (\(0\) denotes red edge and \(1\) denotes black edge).
Print the number of good sequences modulo \(10^9 + 7\).
In the first example, all sequences (\(4^4\)) of length \(4\) except the following are good: \([1, 1, 1, 1]\) \([2, 2, 2, 2]\) \([3, 3, 3, 3]\) \([4, 4, 4, 4]\) In the second example, all edges are red, hence there aren't any good sequences.
Input: 4 4 1 2 1 2 3 1 3 4 1 | Output: 252
Medium
5
1,111
458
55
11
460
B
460B
B. Little Dima and Equation
1,500
brute force; implementation; math; number theory
Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment. Find all integer solutions x (0 < x < 109) of the equation:x = bΒ·s(x)a + c, where a, b, c are some predetermined constant values and function s(x) determines the sum of all digits in the decimal representation of number x.The teacher gives this problem to Dima for each lesson. He changes only the parameters of the equation: a, b, c. Dima got sick of getting bad marks and he asks you to help him solve this challenging problem.
The first line contains three space-separated integers: a, b, c (1 ≀ a ≀ 5; 1 ≀ b ≀ 10000; - 10000 ≀ c ≀ 10000).
Print integer n β€” the number of the solutions that you've found. Next print n integers in the increasing order β€” the solutions of the given equation. Print only integer solutions that are larger than zero and strictly less than 109.
Input: 3 2 8 | Output: 310 2008 13726
Medium
4
561
112
232
4
35
D
35D
D. Animals
1,700
dp; greedy
Once upon a time DravDe, an outstanding person famous for his professional achievements (as you must remember, he works in a warehouse storing Ogudar-Olok, a magical but non-alcoholic drink) came home after a hard day. That day he had to drink 9875 boxes of the drink and, having come home, he went to bed at once.DravDe dreamt about managing a successful farm. He dreamt that every day one animal came to him and asked him to let it settle there. However, DravDe, being unimaginably kind, could send the animal away and it went, rejected. There were exactly n days in DravDe’s dream and the animal that came on the i-th day, ate exactly ci tons of food daily starting from day i. But if one day the animal could not get the food it needed, it got really sad. At the very beginning of the dream there were exactly X tons of food on the farm.DravDe woke up terrified...When he retold the dream to you, he couldn’t remember how many animals were on the farm by the end of the n-th day any more, but he did remember that nobody got sad (as it was a happy farm) and that there was the maximum possible amount of the animals. That’s the number he wants you to find out. It should be noticed that the animals arrived in the morning and DravDe only started to feed them in the afternoon, so that if an animal willing to join them is rejected, it can’t eat any farm food. But if the animal does join the farm, it eats daily from that day to the n-th.
The first input line contains integers n and X (1 ≀ n ≀ 100, 1 ≀ X ≀ 104) β€” amount of days in DravDe’s dream and the total amount of food (in tons) that was there initially. The second line contains integers ci (1 ≀ ci ≀ 300). Numbers in the second line are divided by a space.
Output the only number β€” the maximum possible amount of animals on the farm by the end of the n-th day given that the food was enough for everybody.
Note to the first example: DravDe leaves the second and the third animal on the farm. The second animal will eat one ton of food on the second day and one ton on the third day. The third animal will eat one ton of food on the third day.
Input: 3 41 1 1 | Output: 2
Medium
2
1,442
277
148
0
827
E
827E
E. Rusty String
2,700
fft; math; strings
Grigory loves strings. Recently he found a metal strip on a loft. The strip had length n and consisted of letters ""V"" and ""K"". Unfortunately, rust has eaten some of the letters so that it's now impossible to understand which letter was written.Grigory couldn't understand for a long time what these letters remind him of, so he became interested in the following question: if we put a letter ""V"" or ""K"" on each unreadable position, which values can the period of the resulting string be equal to?A period of a string is such an integer d from 1 to the length of the string that if we put the string shifted by d positions to the right on itself, then all overlapping letters coincide. For example, 3 and 5 are periods of ""VKKVK"".
There are several (at least one) test cases in the input. The first line contains single integer β€” the number of test cases.There is an empty line before each test case. Each test case is described in two lines: the first line contains single integer n (1 ≀ n ≀ 5Β·105) β€” the length of the string, the second line contains the string of length n, consisting of letters ""V"", ""K"" and characters ""?"". The latter means the letter on its position is unreadable.It is guaranteed that the sum of lengths among all test cases doesn't exceed 5Β·105.For hacks you can only use tests with one test case.
For each test case print two lines. In the first line print the number of possible periods after we replace each unreadable letter with ""V"" or ""K"". In the next line print all these values in increasing order.
In the first test case from example we can obtain, for example, ""VKKVK"", which has periods 3 and 5.In the second test case we can obtain ""VVVVVV"" which has all periods from 1 to 6.In the third test case string ""KVKV"" has periods 2 and 4, and string ""KVKK"" has periods 3 and 4.
Input: 3 5V??VK 6?????? 4?VK? | Output: 23 561 2 3 4 5 632 3 4
Master
3
739
596
212
8
2,045
D
2045D
D. Aquatic Dragon
3,500
You live in an archipelago consisting of \(N\) islands (numbered from \(1\) to \(N\)) laid out in a single line. Island \(i\) is adjacent to island \(i+1\), for \(1 \leq i < N\). Between adjacent islands \(i\) and \(i+1\), there is a pair of one-directional underwater tunnels: one that allows you to walk from island \(i\) to island \(i+1\) and one for the opposite direction. Each tunnel can only be traversed at most once.You also have a dragon with you. It has a stamina represented by a non-negative integer. The stamina is required for the dragon to perform its abilities: swim and fly. Initially, its stamina is \(0\).Your dragon's stamina can be increased as follows. There is a magical shrine on each island \(i\) that will immediately increase your dragon's stamina by \(P_i\) (regardless the position of the dragon) when you visit island \(i\) for the first time. This event takes no time.When you are on an island, there are \(3\) moves that you can perform. Swim with your dragon to an adjacent island if your dragon and you are on the same island. You can perform if your dragon's stamina is at least \(D\). This move reduces your dragon's stamina by \(D\), and it takes \(T_s\) seconds to perform. Fly with your dragon to an adjacent island if your dragon and you are on the same island. You can perform this move if your dragon's stamina is not \(0\). This move sets your dragon's stamina to \(0\), and it takes \(T_f\) seconds to perform. Walk alone without your dragon to an adjacent island through the underwater tunnel. This move takes \(T_w\) seconds to perform. Once you walk through this tunnel, it cannot be used again. Note that both swimming and flying do not use tunnels.Your dragon and you are currently on island \(1\). Your mission is to go to island \(N\) with your dragon. Determine the minimum possible time to complete your mission.
The first line consists of five integers \(N\) \(D\) \(T_s\) \(T_f\) \(T_w\) (\(2 \leq N \leq 200\,000; 1 \leq D, T_s, T_f, T_w \leq 200\,000\)).The second line consists of \(N\) integers \(P_i\) (\(1 \leq P_i \leq 200\,000)\).
Output an integer in a single line representing the minimum possible time to go to island \(N\) with your dragon.
Explanation for the sample input/output #1The following sequence of events will complete your mission in the minimum time. The shrine on island \(1\) increases your dragon's stamina to \(1\). Fly with your dragon to island \(2\). The shrine on island \(2\) increases your dragon's stamina to \(2\). Walk alone to island \(3\). The shrine on island \(3\) increases your dragon's stamina to \(6\). Walk alone to island \(4\). The shrine on island \(4\) increases your dragon's stamina to \(8\). Walk alone to island \(3\). Walk alone to island \(2\). Swim with your dragon to island \(3\). Your dragon's stamina is now \(4\). Swim with your dragon to island \(4\). Your dragon's stamina is now \(0\). Walk alone to island \(5\). The shrine on island \(5\) increases your dragon's stamina to \(1\). Walk alone to island \(4\). Fly with your dragon to island \(5\). Explanation for the sample input/output #2Repeat the following process for \(1 \leq i < 5\): The shrine on island \(i\) increases your dragon's stamina, then use the stamina to fly with your dragon to island \(i+1\).
Input: 5 4 2 9 1 1 2 4 2 1 | Output: 28
Master
0
1,866
227
113
20
599
E
599E
E. Sandy and Nuts
2,600
bitmasks; dp; trees
Rooted tree is a connected graph without any simple cycles with one vertex selected as a root. In this problem the vertex number 1 will always serve as a root.Lowest common ancestor of two vertices u and v is the farthest from the root vertex that lies on both the path from u to the root and on path from v to the root. We will denote it as LCA(u, v).Sandy had a rooted tree consisting of n vertices that she used to store her nuts. Unfortunately, the underwater storm broke her tree and she doesn't remember all it's edges. She only managed to restore m edges of the initial tree and q triples ai, bi and ci, for which she supposes LCA(ai, bi) = ci.Help Sandy count the number of trees of size n with vertex 1 as a root, that match all the information she remembered. If she made a mess and there are no such trees then print 0. Two rooted trees are considered to be distinct if there exists an edge that occur in one of them and doesn't occur in the other one.
The first line of the input contains three integers n, m and q (1 ≀ n ≀ 13, 0 ≀ m < n, 0 ≀ q ≀ 100) β€” the number of vertices, the number of edges and LCA triples remembered by Sandy respectively.Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui β‰  vi) β€” the numbers of vertices connected by the i-th edge. It's guaranteed that this set of edges is a subset of edges of some tree.The last q lines contain the triplets of numbers ai, bi, ci (1 ≀ ai, bi, ci ≀ n). Each of these triples define LCA(ai, bi) = ci. It's not guaranteed that there exists a tree that satisfy all the given LCA conditions.
Print a single integer β€” the number of trees of size n that satisfy all the conditions.
In the second sample correct answer looks like this: In the third sample there are two possible trees: In the fourth sample the answer is 0 because the information about LCA is inconsistent.
Input: 4 0 0 | Output: 16
Expert
3
963
621
87
5
838
A
838A
A. Binary Blocks
1,400
brute force
You are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters ""0"" or ""1"", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisible by k, the image is padded with only zeros on the right and bottom so that they are divisible by k. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some k. More specifically, the steps are to first choose k, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this k. The image must be compressible in that state.
The first line of input will contain two integers n, m (2 ≀ n, m ≀ 2 500), the dimensions of the image.The next n lines of input will contain a binary string with exactly m characters, representing the image.
Print a single integer, the minimum number of pixels needed to toggle to make the image compressible.
We first choose k = 2.The image is padded as follows: 001000101100110010000000We can toggle the image to look as follows: 001100001100000000000000We can see that this image is compressible for k = 2.
Input: 3 5001001011011001 | Output: 5
Easy
1
872
208
101
8
1,023
E
1023E
E. Down or Right
2,100
constructive algorithms; interactive; matrices
This is an interactive problem.Bob lives in a square grid of size \(n \times n\), with rows numbered \(1\) through \(n\) from top to bottom, and columns numbered \(1\) through \(n\) from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer \(n\).Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move down or right to an adjacent cell, if it is allowed.You can ask at most \(4 \cdot n\) queries of form ""? \(r_1\) \(c_1\) \(r_2\) \(c_2\)"" (\(1 \le r_1 \le r_2 \le n\), \(1 \le c_1 \le c_2 \le n\)). The answer will be ""YES"" if Bob can get from a cell \((r_1, c_1)\) to a cell \((r_2, c_2)\), and ""NO"" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is ""NO"" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least \(n - 1\), i.e. the following condition must be satisfied: \((r_2 - r_1) + (c_2 - c_1) \ge n - 1\).It's guaranteed that Bob can get from the top-left corner \((1, 1)\) to the bottom-right corner \((n, n)\) and your task is to find a way to do it. You should print the answer in form ""! S"" where \(S\) is a string of length \(2 \cdot n - 2\) consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by \(1\), the right move increases the second coordinate by \(1\). If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.
The only line of the input contains an integer \(n\) (\(2 \le n \le 500\)) β€” the size of the grid.
When you are ready to print the answer, print a single line containing ""! S"" where where \(S\) is a string of length \(2 \cdot n - 2\) consisting of characters 'D' and 'R', denoting moves down and right respectively. The path should be a valid path going from the cell \((1, 1)\) to the cell \((n, n)\) passing only through allowed cells.
The first example is shown on the picture below. To hack, use the following input format:The first line should contain a single integer \(n\) (\(2 \le n \le 500\)) β€” the size of the grid.Each of the next \(n\) lines should contain a string of \(n\) characters '#' or '.', where '#' denotes a blocked cell, and '.' denotes an allowed cell.For example, the following text encodes the example shown above:4..#.#...###.....
Input: 4 YES NO YES YES | Output: ? 1 1 4 4 ? 1 2 4 3 ? 4 1 4 4 ? 1 4 4 4 ! RDRRDD
Hard
3
1,662
98
340
10
1,812
C
1812C
C. Digits
0
*special
The first line contains a single integer \(t\) (\(1 \le t \le 32\)) β€” the number of test cases.Each test case contains \(n\) lines. The \(i\)-th line contains an integer \(a_i\) (\(1 \le a_i \le 9\)).The sum of \(n\) over all test cases doesn't exceed \(155\).
For each test case, print one integer β€” the answer.
Input: 3 2 1 4 7 1 2 3 5 | Output: 8 7 30
Beginner
1
0
260
51
18
2,071
C
2071C
C. Trapmigiano Reggiano
1,700
constructive algorithms; data structures; dfs and similar; dp; greedy; sortings; trees
In an Italian village, a hungry mouse starts at vertex \(\textrm{st}\) on a given tree\(^{\text{βˆ—}}\) with \(n\) vertices.Given a permutation \(p\) of length \(n\)\(^{\text{†}}\), there are \(n\) steps. For the \(i\)-th step: A tempting piece of Parmesan cheese appears at vertex \(p_i\). If the mouse is currently at vertex \(p_i\), it will stay there and enjoy the moment. Otherwise, it will move along the simple path to vertex \(p_i\) by one edge. Your task is to find such a permutation so that, after all \(n\) steps, the mouse inevitably arrives at vertex \(\textrm{en}\), where a trap awaits.Note that the mouse must arrive at \(\textrm{en}\) after all \(n\) steps, though it may pass through \(\textrm{en}\) earlier during the process.\(^{\text{βˆ—}}\)A tree is a connected graph without cycles. \(^{\text{†}}\)A permutation of length \(n\) is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array), and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^4\)). The description of the test cases follows. The first line of each test case contains three integers \(n\), \(\textrm{st}\), and \(\textrm{en}\) (\(1 \le n \le 10^5\); \(1 \le \textrm{st}, \textrm{en} \le n\)) β€” the number of vertices of the tree, the starting vertex, and the trap vertex.Each of the next \(n - 1\) lines contains two integers \(u\) and \(v\) (\(1 \le u, v \le n\), \(u \neq v\)) β€” the indices of the vertices connected by an edge.It is guaranteed that the given edges form a tree.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case: If no such permutation exists, output \(-1\). Otherwise, output \(n\) integers \(p_1, p_2, \ldots, p_n\), representing the order in which the cheese will appear at the vertices, ensuring the mouse will eventually be caught at vertex \(\textrm{en}\). If there are multiple solutions, print any of them.
In the first test case, there is only one permutation with length \(n = 1\) that is \(p = [1]\), which successfully catches the mouse:$$$\(\textrm{st} = 1 \overset{p_1 = 1}{\xrightarrow{\hspace{1.3cm}}} 1 = \textrm{en}.\)\(In the second test case, one possible permutation with length \)n = 2\( is \)p = [1, 2]\(:\)\(\textrm{st} = 1 \overset{p_1 = 1}{\xrightarrow{\hspace{1.3cm}}} 1 \overset{p_2 = 2}{\xrightarrow{\hspace{1.3cm}}} 2 = \textrm{en}.\)\(In the third test case, one possible permutation with length \)n = 3\( is \)p = [3, 1, 2]\(:\)\(\textrm{st} = 2 \overset{p_1 = 3}{\xrightarrow{\hspace{1.3cm}}} 3 \overset{p_2 = 1}{\xrightarrow{\hspace{1.3cm}}} 2 \overset{p_3 = 2}{\xrightarrow{\hspace{1.3cm}}} 2 = \textrm{en}.\)$$$
Input: 41 1 12 1 21 23 2 21 22 36 1 41 21 34 55 61 4 | Output: 1 1 2 3 1 2 1 4 3 2 6 5
Medium
7
1,142
700
321
20
1,310
B
1310B
B. Double Elimination
2,500
dp; implementation
The biggest event of the year – Cota 2 world championship ""The Innernational"" is right around the corner. \(2^n\) teams will compete in a double-elimination format (please, carefully read problem statement even if you know what is it) to identify the champion. Teams are numbered from \(1\) to \(2^n\) and will play games one-on-one. All teams start in the upper bracket.All upper bracket matches will be held played between teams that haven't lost any games yet. Teams are split into games by team numbers. Game winner advances in the next round of upper bracket, losers drop into the lower bracket.Lower bracket starts with \(2^{n-1}\) teams that lost the first upper bracket game. Each lower bracket round consists of two games. In the first game of a round \(2^k\) teams play a game with each other (teams are split into games by team numbers). \(2^{k-1}\) loosing teams are eliminated from the championship, \(2^{k-1}\) winning teams are playing \(2^{k-1}\) teams that got eliminated in this round of upper bracket (again, teams are split into games by team numbers). As a result of each round both upper and lower bracket have \(2^{k-1}\) teams remaining. See example notes for better understanding.Single remaining team of upper bracket plays with single remaining team of lower bracket in grand-finals to identify championship winner.You are a fan of teams with numbers \(a_1, a_2, ..., a_k\). You want the championship to have as many games with your favourite teams as possible. Luckily, you can affect results of every championship game the way you want. What's maximal possible number of championship games that include teams you're fan of?
First input line has two integers \(n, k\) β€” \(2^n\) teams are competing in the championship. You are a fan of \(k\) teams (\(2 \le n \le 17; 0 \le k \le 2^n\)).Second input line has \(k\) distinct integers \(a_1, \ldots, a_k\) β€” numbers of teams you're a fan of (\(1 \le a_i \le 2^n\)).
Output single integer β€” maximal possible number of championship games that include teams you're fan of.
On the image, each game of the championship is denoted with an English letter (\(a\) to \(n\)). Winner of game \(i\) is denoted as \(Wi\), loser is denoted as \(Li\). Teams you're a fan of are highlighted with red background.In the first example, team \(6\) will play in 6 games if it looses the first upper bracket game (game \(c\)) and wins all lower bracket games (games \(h, j, l, m\)). In the second example, teams \(7\) and \(8\) have to play with each other in the first game of upper bracket (game \(d\)). Team \(8\) can win all remaining games in upper bracket, when teams \(1\) and \(7\) will compete in the lower bracket. In the third example, your favourite teams can play in all games of the championship.
Input: 3 1 6 | Output: 6
Expert
2
1,654
287
103
13
815
B
815B
B. Karen and Test
2,200
brute force; combinatorics; constructive algorithms; math
Karen has just arrived at school, and she has a math test today! The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points.There are n integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition.Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa.The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test.Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row?Since this number can be quite large, output only the non-negative remainder after dividing it by 109 + 7.
The first line of input contains a single integer n (1 ≀ n ≀ 200000), the number of numbers written on the first row.The next line contains n integers. Specifically, the i-th one among these is ai (1 ≀ ai ≀ 109), the i-th number on the first row.
Output a single integer on a line by itself, the number on the final row after performing the process above.Since this number can be quite large, print only the non-negative remainder after dividing it by 109 + 7.
In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15.Karen performs the operations as follows: The non-negative remainder after dividing the final number by 109 + 7 is still 36, so this is the correct output.In the second test case, the numbers written on the first row are 3, 7, 5 and 2.Karen performs the operations as follows: The non-negative remainder after dividing the final number by 109 + 7 is 109 + 6, so this is the correct output.
Input: 53 6 9 12 15 | Output: 36
Hard
4
1,222
246
213
8
442
D
442D
D. Adam and Tree
2,600
data structures; trees
When Adam gets a rooted tree (connected non-directed graph without cycles), he immediately starts coloring it. More formally, he assigns a color to each edge of the tree so that it meets the following two conditions: There is no vertex that has more than two incident edges painted the same color. For any two vertexes that have incident edges painted the same color (say, c), the path between them consists of the edges of the color c. Not all tree paintings are equally good for Adam. Let's consider the path from some vertex to the root. Let's call the number of distinct colors on this path the cost of the vertex. The cost of the tree's coloring will be the maximum cost among all the vertexes. Help Adam determine the minimum possible cost of painting the tree. Initially, Adam's tree consists of a single vertex that has number one and is the root. In one move Adam adds a new vertex to the already existing one, the new vertex gets the number equal to the minimum positive available integer. After each operation you need to calculate the minimum cost of coloring the resulting tree.
The first line contains integer n (1 ≀ n ≀ 106) β€” the number of times a new vertex is added. The second line contains n numbers pi (1 ≀ pi ≀ i) β€” the numbers of the vertexes to which we add another vertex.
Print n integers β€” the minimum costs of the tree painting after each addition.
The figure below shows one of the possible variants to paint a tree from the sample at the last moment. The cost of the vertexes with numbers 11 and 12 equals 3.
Input: 111 1 1 3 4 4 7 3 7 6 6 | Output: 1 1 1 1 1 2 2 2 2 2 3
Expert
2
1,091
205
78
4
1,651
B
1651B
B. Prove Him Wrong
800
constructive algorithms; greedy
Recently, your friend discovered one special operation on an integer array \(a\): Choose two indices \(i\) and \(j\) (\(i \neq j\)); Set \(a_i = a_j = |a_i - a_j|\). After playing with this operation for a while, he came to the next conclusion: For every array \(a\) of \(n\) integers, where \(1 \le a_i \le 10^9\), you can find a pair of indices \((i, j)\) such that the total sum of \(a\) will decrease after performing the operation. This statement sounds fishy to you, so you want to find a counterexample for a given integer \(n\). Can you find such counterexample and prove him wrong?In other words, find an array \(a\) consisting of \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i \le 10^9\)) such that for all pairs of indices \((i, j)\) performing the operation won't decrease the total sum (it will increase or not change the sum).
The first line contains a single integer \(t\) (\(1 \le t \le 100\)) β€” the number of test cases. Then \(t\) test cases follow.The first and only line of each test case contains a single integer \(n\) (\(2 \le n \le 1000\)) β€” the length of array \(a\).
For each test case, if there is no counterexample array \(a\) of size \(n\), print NO.Otherwise, print YES followed by the array \(a\) itself (\(1 \le a_i \le 10^9\)). If there are multiple counterexamples, print any.
In the first test case, the only possible pairs of indices are \((1, 2)\) and \((2, 1)\).If you perform the operation on indices \((1, 2)\) (or \((2, 1)\)), you'll get \(a_1 = a_2 = |1 - 337| = 336\), or array \([336, 336]\). In both cases, the total sum increases, so this array \(a\) is a counterexample.
Input: 325123 | Output: YES 1 337 NO YES 31 4 159
Beginner
2
846
251
217
16
1,051
A
1051A
A. Vasya And Password
1,200
greedy; implementation; strings
Vasya came up with a password to register for EatForces β€” a string \(s\). The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin letter and at least one lowercase Latin letter. For example, the passwords ""abaCABA12"", ""Z7q"" and ""3R24m"" are valid, and the passwords ""qwerty"", ""qwerty12345"" and ""Password"" are not. A substring of string \(s\) is a string \(x = s_l s_{l + 1} \dots s_{l + len - 1} (1 \le l \le |s|, 0 \le len \le |s| - l + 1)\). \(len\) is the length of the substring. Note that the empty string is also considered a substring of \(s\), it has the length \(0\).Vasya's password, however, may come too weak for the security settings of EatForces. He likes his password, so he wants to replace some its substring with another string of the same length in order to satisfy the above conditions. This operation should be performed exactly once, and the chosen string should have the minimal possible length.Note that the length of \(s\) should not change after the replacement of the substring, and the string itself should contain only lowercase and uppercase Latin letters and digits.
The first line contains a single integer \(T\) (\(1 \le T \le 100\)) β€” the number of testcases.Each of the next \(T\) lines contains the initial password \(s~(3 \le |s| \le 100)\), consisting of lowercase and uppercase Latin letters and digits.Only \(T = 1\) is allowed for hacks.
For each testcase print a renewed password, which corresponds to given conditions. The length of the replaced substring is calculated as following: write down all the changed positions. If there are none, then the length is \(0\). Otherwise the length is the difference between the first and the last changed position plus one. For example, the length of the changed substring between the passwords ""abcdef"" \(\rightarrow\) ""a7cdEf"" is \(4\), because the changed positions are \(2\) and \(5\), thus \((5 - 2) + 1 = 4\).It is guaranteed that such a password always exists.If there are several suitable passwords β€” output any of them.
In the first example Vasya's password lacks a digit, he replaces substring ""C"" with ""4"" and gets password ""abcD4E"". That means, he changed the substring of length 1.In the second example Vasya's password is ok from the beginning, and nothing has to be changed. That is the same as replacing the empty substring with another empty substring (length 0).
Input: 2abcDCEhtQw27 | Output: abcD4EhtQw27
Easy
3
1,299
280
636
10
1,692
E
1692E
E. Binary Deque
1,200
binary search; implementation; two pointers
Slavic has an array of length \(n\) consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array. What is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to \(s\) after performing all the operations? In case the sum \(s\) can't be obtained after any amount of operations, you should output -1.
The first line contains a single integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases.The first line of each test case contains two integers \(n\) and \(s\) (\(1 \leq n, s \leq 2 \cdot 10^5\)) β€” the length of the array and the needed sum of elements.The second line of each test case contains \(n\) integers \(a_i\) (\(0 \leq a_i \leq 1\)) β€” the elements of the array.It is guaranteed that the sum of \(n\) over all test cases doesn't exceed \(2 \cdot 10^5\).
For each test case, output a single integer β€” the minimum amount of operations required to have the total sum of the array equal to \(s\), or -1 if obtaining an array with sum \(s\) isn't possible.
In the first test case, the sum of the whole array is \(1\) from the beginning, so we don't have to make any operations.In the second test case, the sum of the array is \(2\) and we want it to be equal to \(1\), so we should remove the first element. The array turns into \([1, 0]\), which has a sum equal to \(1\).In the third test case, the sum of the array is \(5\) and we need it to be \(3\). We can obtain such a sum by removing the first two elements and the last element, doing a total of three operations. The array turns into \([0, 1, 1, 1, 0, 0]\), which has a sum equal to \(3\).
Input: 73 11 0 03 11 1 09 30 1 0 1 1 1 0 0 16 41 1 1 1 1 15 10 0 1 1 016 21 1 0 0 1 0 0 1 1 0 0 0 0 0 1 16 31 0 1 0 0 0 | Output: 0 1 3 2 2 7 -1
Easy
3
400
472
197
16
1,910
H
1910H
H. Sum of Digits of Sums
2,400
*special; binary search; data structures
You are given an array \([a_1, a_2, \dots, a_n]\), consisting of positive integers.For every \(i\) from \(1\) to \(n\), calculate \(\sum \limits_{j=1}^{n} F(a_i + a_j)\), where \(F(x)\) is the sum of digits of \(x\).
The first line contains one integer \(n\) (\(2 \le n \le 2 \cdot 10^5\)).The second line contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(1 \le a_i < 10^9\)).
Print \(n\) integers. The \(i\)-th of them should be equal to \(\sum \limits_{j=1}^{n} F(a_i + a_j)\).
Input: 4 1 3 3 7 | Output: 18 17 17 15
Expert
3
216
161
102
19
611
B
611B
B. New Year and Old Property
1,300
bitmasks; brute force; implementation
The year 2015 is almost over.Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system β€” 201510 = 111110111112. Note that he doesn't care about the number of zeros in the decimal representation.Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?Assume that all positive integers are always written without leading zeros.
The only line of the input contains two integers a and b (1 ≀ a ≀ b ≀ 1018) β€” the first year and the last year in Limak's interval respectively.
Print one integer – the number of years Limak will count in his chosen interval.
In the first sample Limak's interval contains numbers 510 = 1012, 610 = 1102, 710 = 1112, 810 = 10002, 910 = 10012 and 1010 = 10102. Two of them (1012 and 1102) have the described property.
Input: 5 10 | Output: 2
Easy
3
550
144
80
6
1,955
H
1955H
H. The Most Reckless Defense
2,300
bitmasks; brute force; constructive algorithms; dp; flows; graph matchings; shortest paths
You are playing a very popular Tower Defense game called ""Runnerfield 2"". In this game, the player sets up defensive towers that attack enemies moving from a certain starting point to the player's base.You are given a grid of size \(n \times m\), on which \(k\) towers are already placed and a path is laid out through which enemies will move. The cell at the intersection of the \(x\)-th row and the \(y\)-th column is denoted as \((x, y)\).Each second, a tower deals \(p_i\) units of damage to all enemies within its range. For example, if an enemy is located at cell \((x, y)\) and a tower is at \((x_i, y_i)\) with a range of \(r\), then the enemy will take damage of \(p_i\) if \((x - x_i) ^ 2 + (y - y_i) ^ 2 \le r ^ 2\).Enemies move from cell \((1, 1)\) to cell \((n, m)\), visiting each cell of the path exactly once. An enemy instantly moves to an adjacent cell horizontally or vertically, but before doing so, it spends one second in the current cell. If its health becomes zero or less during this second, the enemy can no longer move. The player loses if an enemy reaches cell \((n, m)\) and can make one more move.By default, all towers have a zero range, but the player can set a tower's range to an integer \(r\) (\(r > 0\)), in which case the health of all enemies will increase by \(3^r\). However, each \(r\) can only be used for at most one tower.Suppose an enemy has a base health of \(h\) units. If the tower ranges are \(2\), \(4\), and \(5\), then the enemy's health at the start of the path will be \(h + 3 ^ 2 + 3 ^ 4 + 3 ^ 5 = h + 9 + 81 + 243 = h + 333\). The choice of ranges is made once before the appearance of enemies and cannot be changed after the game starts.Find the maximum amount of base health \(h\) for which it is possible to set the ranges so that the player does not lose when an enemy with health \(h\) passes through (without considering the additions for tower ranges).
The first line contains an integer \(t\) (\(1 \le t \le 100\)) β€” the number of test cases.The first line of each test case contains three integers \(n\), \(m\), and \(k\) (\(2 \le n, m \le 50, 1 \le k < n \cdot m\)) β€” the dimensions of the field and the number of towers on it.The next \(n\) lines each contain \(m\) characters β€” the description of each row of the field, where the character ""."" denotes an empty cell, and the character ""#"" denotes a path cell that the enemies will pass through.Then follow \(k\) lines β€” the description of the towers. Each line of description contains three integers \(x_i\), \(y_i\), and \(p_i\) (\(1 \le x_i \le n, 1 \le y_i \le m, 1 \le p_i \le 500\)) β€” the coordinates of the tower and its attack parameter. All coordinates correspond to empty cells on the game field, and all pairs \((x_i, y_i)\) are pairwise distinct.It is guaranteed that the sum of \(n \cdot m\) does not exceed \(2500\) for all test cases.
For each test case, output the maximum amount of base health \(h\) on a separate line, for which it is possible to set the ranges so that the player does not lose when an enemy with health \(h\) passes through (without considering the additions for tower ranges).If it is impossible to choose ranges even for an enemy with \(1\) unit of base health, output ""0"".
In the first example, there is no point in increasing the tower range, as it will not be able to deal enough damage to the monster even with \(1\) unit of health.In the second example, the tower has a range of \(1\), and it deals damage to the monster in cells \((1, 1)\) and \((2, 2)\).In the third example, the tower has a range of \(2\), and it deals damage to the monster in all path cells. If the enemy's base health is \(1491\), then after the addition for the tower range, its health will be \(1491 + 3 ^ 2 = 1500\), which exactly equals the damage the tower will deal to it in three seconds.In the fourth example, the tower at \((1, 2)\) has a range of \(1\), and the tower at \((3, 1)\) has a range of \(2\).
Input: 62 2 1#.##1 2 12 2 1#.##1 2 22 2 1#.##1 2 5003 3 2#..##..##1 2 43 1 33 5 2#.####.#.####.#2 2 22 4 25 5 4#....#....#....#....#####3 2 1424 5 92 5 791 3 50 | Output: 0 1 1491 11 8 1797
Expert
7
1,917
954
363
19
671
D
671D
D. Roads in Yusland
2,900
data structures; dp; greedy
Mayor of Yusland just won the lottery and decided to spent money on something good for town. For example, repair all the roads in the town.Yusland consists of n intersections connected by n - 1 bidirectional roads. One can travel from any intersection to any other intersection using only these roads.There is only one road repairing company in town, named ""RC company"". Company's center is located at the intersection 1. RC company doesn't repair roads you tell them. Instead, they have workers at some intersections, who can repair only some specific paths. The i-th worker can be paid ci coins and then he repairs all roads on a path from ui to some vi that lies on the path from ui to intersection 1. Mayor asks you to choose the cheapest way to hire some subset of workers in order to repair all the roads in Yusland. It's allowed that some roads will be repaired more than once.If it's impossible to repair all roads print - 1.
The first line of the input contains two integers n and m (1 ≀ n, m ≀ 300 000) β€” the number of cities in Yusland and the number of workers respectively.Then follow nβˆ’1 line, each of them contains two integers xi and yi (1 ≀ xi, yi ≀ n) β€” indices of intersections connected by the i-th road.Last m lines provide the description of workers, each line containing three integers ui, vi and ci (1 ≀ ui, vi ≀ n, 1 ≀ ci ≀ 109). This means that the i-th worker can repair all roads on the path from vi to ui for ci coins. It's guaranteed that vi lies on the path from ui to 1. Note that vi and ui may coincide.
If it's impossible to repair all roads then print - 1. Otherwise print a single integer β€” minimum cost required to repair all roads using ""RC company"" workers.
In the first sample, we should choose workers with indices 1, 3, 4 and 5, some roads will be repaired more than once but it is OK. The cost will be equal to 2 + 3 + 1 + 2 = 8 coins.
Input: 6 51 21 33 44 54 62 1 23 1 44 1 35 3 16 3 2 | Output: 8
Master
3
935
602
161
6
812
D
812D
D. Sagheer and Kindergarten
2,700
dfs and similar; graphs; implementation; trees
Sagheer is working at a kindergarten. There are n children and m different toys. These children use well-defined protocols for playing with the toys: Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set. If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever. Children request toys at distinct moments of time. No two children request a toy at the same time. If a child is granted a toy, he never gives it back until he finishes playing with his lovely set. If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting. If two children are waiting for the same toy, then the child who requested it first will take the toy first.Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy.Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set.Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child x that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child x is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child x will make his last request, how many children will start crying?You will be given the scenario and q independent queries. Each query will be of the form x y meaning that the last request of the child x is for the toy y. Your task is to help Sagheer find the size of the maximal crying set when child x makes his last request.
The first line contains four integers n, m, k, q (1 ≀ n, m, k, q ≀ 105) β€” the number of children, toys, scenario requests and queries.Each of the next k lines contains two integers a, b (1 ≀ a ≀ n and 1 ≀ b ≀ m) β€” a scenario request meaning child a requests toy b. The requests are given in the order they are made by children.Each of the next q lines contains two integers x, y (1 ≀ x ≀ n and 1 ≀ y ≀ m) β€” the request to be added to the scenario meaning child x will request toy y just after getting the toy he is waiting for (if any).It is guaranteed that the scenario requests are consistent and no child is initially crying. All the scenario requests are distinct and no query coincides with a scenario request.
For each query, print on a single line the number of children who will start crying when child x makes his last request for toy y. Please answer all queries independent of each other.
In the first example, child 1 is waiting for toy 2, which child 2 has, while child 2 is waiting for top 3, which child 3 has. When child 3 makes his last request, the toy he requests is held by child 1. Each of the three children is waiting for a toy held by another child and no one is playing, so all the three will start crying.In the second example, at the beginning, child i is holding toy i for 1 ≀ i ≀ 4. Children 1 and 3 have completed their lovely sets. After they finish playing, toy 3 will be free while toy 1 will be taken by child 2 who has just completed his lovely set. After he finishes, toys 1 and 2 will be free and child 5 will take toy 1. Now: In the first query, child 5 will take toy 3 and after he finishes playing, child 4 can play. In the second query, child 5 will request toy 4 which is held by child 4. At the same time, child 4 is waiting for toy 1 which is now held by child 5. None of them can play and they will start crying.
Input: 3 3 5 11 12 23 31 22 33 1 | Output: 3
Master
4
2,253
715
183
8
1,571
B
1571B
B. Epic Novel
1,300
*special; math
Alex has bought a new novel that was published in \(n\) volumes. He has read these volumes one by one, and each volume has taken him several (maybe one) full days to read. So, on the first day, he was reading the first volume, and on each of the following days, he was reading either the same volume he had been reading on the previous day, or the next volume.Let \(v_i\) be the number of the volume Alex was reading on the \(i\)-th day. Here are some examples: one of the possible situations is \(v_1 = 1\), \(v_2 = 1\), \(v_3 = 2\), \(v_4 = 3\), \(v_5 = 3\) β€” this situation means that Alex has spent two days (\(1\)-st and \(2\)-nd) on the first volume, one day (\(3\)-rd) on the second volume, and two days (\(4\)-th and \(5\)-th) on the third volume; a situation \(v_1 = 2\), \(v_2 = 2\), \(v_3 = 3\) is impossible, since Alex started with the first volume (so \(v_1\) cannot be anything but \(1\)); a situation \(v_1 = 1\), \(v_2 = 2\), \(v_3 = 3\), \(v_4 = 1\) is impossible, since Alex won't return to the first volume after reading the third one; a situation \(v_1 = 1\), \(v_2 = 3\) is impossible, since Alex doesn't skip volumes. You know that Alex was reading the volume \(v_a\) on the day \(a\), and the volume \(v_c\) on the day \(c\). Now you want to guess which volume was he reading on the day \(b\), which is between the days \(a\) and \(c\) (so \(a < b < c\)). There may be some ambiguity, so you want to make any valid guess (i. e. choose some volume number \(v_b\) so it's possible that Alex was reading volume \(v_a\) on day \(a\), volume \(v_b\) on day \(b\), and volume \(v_c\) on day \(c\)).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). Description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 100\)) β€” the number of volumes the novel consists of.The second line of each test case contains two integers \(a\) and \(v_a\) (\(1 \le a \le 98\); \(1 \le v_a \le a\)) denoting that Alex was reading volume \(v_a\) at day \(a\).The third line of each test case contains two integers \(c\) and \(v_c\) (\(a + 2 \le c \le 100\); \(v_a \le v_c \le c\)) denoting that Alex was reading volume \(v_c\) at day \(c\).The fourth line of each test case contains one integer \(b\) (\(a < b < c\)) β€” the day you are interested in.It's guaranteed that the input is not controversial, in other words, Alex could read volume \(v_a\) at day \(a\) and volume \(v_c\) at day \(c\).
For each test case, print the possible index of volume Alex could read at day \(b\). If there are multiple answers, print any.
In the first test case, since Alex was reading volume \(1\) both at day \(1\) and at day \(100\) then he was reading volume \(1\) at any day between them.In the second test case, Alex could read any volume from \(1\) to \(4\) at day \(16\). For example, he could read volume \(1\) from day \(1\) to day \(15\), volume \(2\) at days \(16\) and \(17\), volume \(3\) at day \(18\) and volume \(4\) at days \(19\) and \(20\).In the third test case, there is only one possible situation: Alex read one volume per day, so at day \(42\) he read volume \(42\).
Input: 4 1 1 1 100 1 99 4 10 1 20 4 16 100 1 1 100 100 42 100 1 1 100 2 99 | Output: 1 2 42 1
Easy
2
1,616
899
126
15
1,608
E
1608E
E. The Cells on the Paper
2,800
binary search; implementation; sortings
On an endless checkered sheet of paper, \(n\) cells are chosen and colored in three colors, where \(n\) is divisible by \(3\). It turns out that there are exactly \(\frac{n}{3}\) marked cells of each of three colors! Find the largest such \(k\) that it's possible to choose \(\frac{k}{3}\) cells of each color, remove all other marked cells, and then select three rectangles with sides parallel to the grid lines so that the following conditions hold: No two rectangles can intersect (but they can share a part of the boundary). In other words, the area of intersection of any two of these rectangles must be \(0\). The \(i\)-th rectangle contains all the chosen cells of the \(i\)-th color and no chosen cells of other colors, for \(i = 1, 2, 3\).
The first line of the input contains a single integer \(n\) β€” the number of the marked cells (\(3 \leq n \le 10^5\), \(n\) is divisible by 3).The \(i\)-th of the following \(n\) lines contains three integers \(x_i\), \(y_i\), \(c_i\) (\(|x_i|,|y_i| \leq 10^9\); \(1 \leq c_i \leq 3\)), where \((x_i, y_i)\) are the coordinates of the \(i\)-th marked cell and \(c_i\) is its color.It's guaranteed that all cells \((x_i, y_i)\) in the input are distinct, and that there are exactly \(\frac{n}{3}\) cells of each color.
Output a single integer \(k\) β€” the largest number of cells you can leave.
In the first sample, it's possible to leave \(6\) cells with indexes \(1, 5, 6, 7, 8, 9\).In the second sample, it's possible to leave \(3\) cells with indexes \(1, 2, 3\).
Input: 9 2 3 1 4 1 2 2 1 3 3 4 1 5 3 2 4 4 3 2 4 1 5 2 2 3 5 3 | Output: 6
Master
3
748
516
74
16
730
D
730D
D. Running Over The Bridges
2,200
greedy; implementation; math
Polycarp is playing a game called ""Running Over The Bridges"". In this game he has to run over n bridges from the left to the right. Bridges are arranged one after the other, so the i-th bridge begins where the (i - 1)-th bridge ends.You have the following data about bridges: li and ti β€” the length of the i-th bridge and the maximum allowed time which Polycarp can spend running over the i-th bridge. Thus, if Polycarp is in the beginning of the bridge i at the time T then he has to leave it at the time T + ti or earlier. It is allowed to reach the right end of a bridge exactly at the time T + ti.Polycarp can run from the left side to the right one with speed 0.5, so he will run over a bridge with length s in time 2Β·s. Besides, he has several magical drinks. If he uses one drink, his speed increases twice (i.e. to value 1) for r seconds. All magical drinks are identical. Please note that Polycarp can use a drink only at integer moments of time, and he drinks it instantly and completely. Additionally, if Polycarp uses a drink at the moment T he can use the next drink not earlier than at the moment T + r.What is the minimal number of drinks Polycarp has to use to run over all n bridges? If this number is not greater than 105, then you have to find out the moments of time when Polycarp has to use each magical drink.
The first line contains two integers n and r (1 ≀ n ≀ 2Β·105, 1 ≀ r ≀ 1012) β€” the number of bridges and the duration of the effect of a magical drink.The second line contains a sequence of integers l1, l2, ..., ln (1 ≀ li ≀ 5Β·106), where li is equal to the length of the i-th bridge.The third line contains a sequence of integers t1, t2, ..., tn (1 ≀ ti ≀ 107), where ti is equal to the maximum allowed time which Polycarp can spend running over the i-th bridge.
The first line of the output should contain k β€” the minimal number of drinks which Polycarp has to use, or -1 if there is no solution.If the solution exists and the value of k is not greater than 105 then output k integers on the next line β€” moments of time from beginning of the game when Polycarp has to use drinks. Print the moments of time in chronological order. If there are several solutions, you can output any of them.
In the first case, there is only one bridge and it is clear that Polycarp cannot run over it without magical drinks. So, if he will use one magical drink on start (moment of time 0), and the second one β€” three seconds later (moment of time 3), he will be able to reach the end of the bridge in time. Please note, in this case there are several possible answers to the problem. For example, Polycarp can use the first drink at the moment of time 4 and the second one β€” at the moment of time 7.In the second case, Polycarp cannot run over all bridges even if he will use magical drinks. So, answer in this case is -1.In the fourth case, Polycarp can run over all bridges without magical drinks.
Input: 1 3710 | Output: 20 3
Hard
3
1,333
461
427
7
182
B
182B
B. Vasya's Calendar
1,000
implementation
Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present β€” the clock that shows not only the time, but also the date.The clock's face can display any number from 1 to d. It is guaranteed that ai ≀ d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d + 1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1.Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1.
The first line contains the single number d β€” the maximum number of the day that Vasya's clock can show (1 ≀ d ≀ 106).The second line contains a single integer n β€” the number of months in the year (1 ≀ n ≀ 2000).The third line contains n space-separated integers: ai (1 ≀ ai ≀ d) β€” the number of days in each month in the order in which they follow, starting from the first one.
Print a single number β€” the number of times Vasya manually increased the day number by one throughout the last year.
In the first sample the situation is like this: Day 1. Month 1. The clock shows 1. Vasya changes nothing. Day 2. Month 1. The clock shows 2. Vasya changes nothing. Day 1. Month 2. The clock shows 3. Vasya manually increases the day number by 1. After that the clock shows 4. Vasya increases the day number by 1 manually. After that the clock shows 1. Day 2. Month 2. The clock shows 2. Vasya changes nothing. In total, Vasya manually changed the day number by 1 exactly 2 times.
Input: 422 2 | Output: 2
Beginner
1
1,271
378
116
1
229
C
229C
C. Triangles
1,900
combinatorics; graphs; math
Alice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with n vertices, chooses some m edges and keeps them. Bob gets the remaining edges.Alice and Bob are fond of ""triangles"" in graphs, that is, cycles of length 3. That's why they wonder: what total number of triangles is there in the two graphs formed by Alice and Bob's edges, correspondingly?
The first line contains two space-separated integers n and m (1 ≀ n ≀ 106, 0 ≀ m ≀ 106) β€” the number of vertices in the initial complete graph and the number of edges in Alice's graph, correspondingly. Then m lines follow: the i-th line contains two space-separated integers ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi), β€” the numbers of the two vertices connected by the i-th edge in Alice's graph. It is guaranteed that Alice's graph contains no multiple edges and self-loops. It is guaranteed that the initial complete graph also contains no multiple edges and self-loops.Consider the graph vertices to be indexed in some way from 1 to n.
Print a single number β€” the total number of cycles of length 3 in Alice and Bob's graphs together.Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is advised to use the cin, cout streams or the %I64d specifier.
In the first sample Alice has 2 triangles: (1, 2, 3) and (2, 3, 4). Bob's graph has only 1 triangle : (1, 4, 5). That's why the two graphs in total contain 3 triangles.In the second sample Alice's graph has only one triangle: (1, 2, 3). Bob's graph has three triangles: (1, 4, 5), (2, 4, 5) and (3, 4, 5). In this case the answer to the problem is 4.
Input: 5 51 21 32 32 43 4 | Output: 3
Hard
3
466
629
243
2
1,263
D
1263D
D. Secret Passwords
1,500
dfs and similar; dsu; graphs
One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of \(n\) passwords β€” strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords \(a\) and \(b\) as follows: two passwords \(a\) and \(b\) are equivalent if there is a letter, that exists in both \(a\) and \(b\); two passwords \(a\) and \(b\) are equivalent if there is a password \(c\) from the list, which is equivalent to both \(a\) and \(b\). If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords ""a"", ""b"", ""ab"", ""d"", then passwords ""a"", ""b"", ""ab"" are equivalent to each other, but the password ""d"" is not equivalent to any other password from list. In other words, if: admin's password is ""b"", then you can access to system by using any of this passwords: ""a"", ""b"", ""ab""; admin's password is ""d"", then you can access to system by using only ""d"". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.
The first line contain integer \(n\) (\(1 \le n \le 2 \cdot 10^5\)) β€” number of passwords in the list. Next \(n\) lines contains passwords from the list – non-empty strings \(s_i\), with length at most \(50\) letters. Some of the passwords may be equal.It is guaranteed that the total length of all passwords does not exceed \(10^6\) letters. All of them consist only of lowercase Latin letters.
In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.
In the second example hacker need to use any of the passwords to access the system.
Input: 4 a b ab d | Output: 2
Medium
3
1,554
395
116
12
2,002
E
2002E
E. Cosmic Rays
2,300
brute force; data structures; dp
Given an array of integers \(s_1, s_2, \ldots, s_l\), every second, cosmic rays will cause all \(s_i\) such that \(i=1\) or \(s_i\neq s_{i-1}\) to be deleted simultaneously, and the remaining parts will be concatenated together in order to form the new array \(s_1, s_2, \ldots, s_{l'}\).Define the strength of an array as the number of seconds it takes to become empty.You are given an array of integers compressed in the form of \(n\) pairs that describe the array left to right. Each pair \((a_i,b_i)\) represents \(a_i\) copies of \(b_i\), i.e. \(\underbrace{b_i,b_i,\cdots,b_i}_{a_i\textrm{ times}}\).For each \(i=1,2,\dots,n\), please find the strength of the sequence described by the first \(i\) pairs.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1\le t\le10^4\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(1\le n\le3\cdot10^5\)) β€” the length of sequence \(a\).The next \(n\) lines contain two integers each \(a_i\), \(b_i\) (\(1\le a_i\le10^9,0\le b_i\le n\)) β€” the pairs which describe the sequence. It is guaranteed that the sum of all \(n\) does not exceed \(3\cdot10^5\).It is guaranteed that for all \(1\le i<n\), \(b_i\neq b_{i+1}\) holds.
For each test case, print one line containing \(n\) integers β€” the answer for each prefix of pairs.
In the first test case, for the prefix of length \(4\), the changes will be \([0,0,1,0,0,0,1,1,1,1,1]\rightarrow[0,0,0,1,1,1,1]\rightarrow[0,0,1,1,1]\rightarrow[0,1,1]\rightarrow[1]\rightarrow[]\), so the array becomes empty after \(5\) seconds.In the second test case, for the prefix of length \(4\), the changes will be \([6,6,6,6,3,6,6,6,6,0,0,0,0]\rightarrow[6,6,6,6,6,6,0,0,0]\rightarrow[6,6,6,6,6,0,0]\rightarrow[6,6,6,6,0]\rightarrow[6,6,6]\rightarrow[6,6]\rightarrow[6]\rightarrow[]\), so the array becomes empty after \(7\) seconds.
Input: 442 01 13 05 164 61 34 64 07 66 379 07 15 07 19 01 12 01010 74 92 27 92 88 511 715 512 74 0 | Output: 2 2 4 5 4 4 7 7 10 10 9 9 9 9 9 9 10 10 10 10 10 10 10 12 15 15 15
Expert
3
710
566
99
20
999
C
999C
C. Alphabetic Removals
1,200
implementation
You are given a string \(s\) consisting of \(n\) lowercase Latin letters. Polycarp wants to remove exactly \(k\) characters (\(k \le n\)) from the string \(s\). Polycarp uses the following algorithm \(k\) times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly \(k\) times, thus removing exactly \(k\) characters.Help Polycarp find the resulting string.
The first line of input contains two integers \(n\) and \(k\) (\(1 \le k \le n \le 4 \cdot 10^5\)) β€” the length of the string and the number of letters Polycarp will remove.The second line contains the string \(s\) consisting of \(n\) lowercase Latin letters.
Print the string that will be obtained from \(s\) after Polycarp removes exactly \(k\) letters using the above algorithm \(k\) times.If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Input: 15 3cccaabababaccbc | Output: cccbbabaccbc
Easy
1
716
259
243
9
2,030
A
2030A
A. A Gift From Orangutan
800
constructive algorithms; greedy; math; sortings
While exploring the jungle, you have bumped into a rare orangutan with a bow tie! You shake hands with the orangutan and offer him some food and water. In return...The orangutan has gifted you an array \(a\) of length \(n\). Using \(a\), you will construct two arrays \(b\) and \(c\), both containing \(n\) elements, in the following manner: \(b_i = \min(a_1, a_2, \ldots, a_i)\) for each \(1 \leq i \leq n\). \(c_i = \max(a_1, a_2, \ldots, a_i)\) for each \(1 \leq i \leq n\). Define the score of \(a\) as \(\sum_{i=1}^n c_i - b_i\) (i.e. the sum of \(c_i - b_i\) over all \(1 \leq i \leq n\)). Before you calculate the score, you can shuffle the elements of \(a\) however you want.Find the maximum score that you can get if you shuffle the elements of \(a\) optimally.
The first line contains \(t\) (\(1 \leq t \leq 100\)) β€” the number of test cases.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 1000\)) β€” the number of elements in \(a\).The following line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq 1000\)) β€” the elements of the array \(a\).It is guaranteed that the sum of \(n\) over all test cases does not exceed \(1000\).
For each test case, output the maximum score that you can get.
In the first test case, there is no other way to rearrange \(a\). So, \(b = [69]\) and \(c = [69]\). The only possible score is \(69 - 69 = 0\).In the second test case, you can rearrange \(a\) as \([7, 5, 6]\). Here, \(b = [7, 5, 5]\) and \(c = [7, 7, 7]\). The score in this case is \((7 - 7) + (7 - 5) + (7 - 5) = 4\). It can be shown this is the maximum possible score.
Input: 316937 6 551 1 1 2 2 | Output: 0 4 4
Beginner
4
770
413
62
20
1,511
B
1511B
B. GCD Length
1,100
constructive algorithms; math; number theory
You are given three integers \(a\), \(b\) and \(c\).Find two positive integers \(x\) and \(y\) (\(x > 0\), \(y > 0\)) such that: the decimal representation of \(x\) without leading zeroes consists of \(a\) digits; the decimal representation of \(y\) without leading zeroes consists of \(b\) digits; the decimal representation of \(gcd(x, y)\) without leading zeroes consists of \(c\) digits. \(gcd(x, y)\) denotes the greatest common divisor (GCD) of integers \(x\) and \(y\).Output \(x\) and \(y\). If there are multiple answers, output any of them.
The first line contains a single integer \(t\) (\(1 \le t \le 285\)) β€” the number of testcases.Each of the next \(t\) lines contains three integers \(a\), \(b\) and \(c\) (\(1 \le a, b \le 9\), \(1 \le c \le min(a, b)\)) β€” the required lengths of the numbers.It can be shown that the answer exists for all testcases under the given constraints.Additional constraint on the input: all testcases are different.
For each testcase print two positive integers β€” \(x\) and \(y\) (\(x > 0\), \(y > 0\)) such that the decimal representation of \(x\) without leading zeroes consists of \(a\) digits; the decimal representation of \(y\) without leading zeroes consists of \(b\) digits; the decimal representation of \(gcd(x, y)\) without leading zeroes consists of \(c\) digits.
In the example: \(gcd(11, 492) = 1\) \(gcd(13, 26) = 13\) \(gcd(140133, 160776) = 21\) \(gcd(1, 1) = 1\)
Input: 4 2 3 1 2 2 2 6 6 2 1 1 1 | Output: 11 492 13 26 140133 160776 1 1
Easy
3
550
408
359
15
1,614
C
1614C
C. Divan and bitwise operations
1,500
bitmasks; combinatorics; constructive algorithms; dp; math
Once Divan analyzed a sequence \(a_1, a_2, \ldots, a_n\) consisting of \(n\) non-negative integers as follows. He considered each non-empty subsequence of the sequence \(a\), computed the bitwise XOR of its elements and added up all the XORs, obtaining the coziness of the sequence \(a\).A sequence \(c\) is a subsequence of a sequence \(d\) if \(c\) can be obtained from \(d\) by deletion of several (possibly, zero or all) elements. For example, \([1, \, 2, \, 3, \, 4]\), \([2, \, 4]\), and \([2]\) are subsequences of \([1, \, 2, \, 3, \, 4]\), but \([4, \, 3]\) and \([0]\) are not.Divan was very proud of his analysis, but now he lost the sequence \(a\), and also the coziness value! However, Divan remembers the value of bitwise OR on \(m\) contiguous subsegments of the sequence \(a\). It turns out that each element of the original sequence is contained in at least one of these \(m\) segments.Divan asks you to help find the coziness of the sequence \(a\) using the information he remembers. If several coziness values are possible, print any.As the result can be very large, print the value modulo \(10^9 + 7\).
The first line contains one integer number \(t\) (\(1 \le t \le 10^3\)) β€” the number of test cases.The first line of each test case contains two integer numbers \(n\) and \(m\) (\(1 \le n, m \le 2 \cdot 10^5\)) β€” the length of the sequence and the number of contiguous segments whose bitwise OR values Divan remembers, respectively.The following \(m\) lines describe the segments, one per line.Each segment is described with three integers \(l\), \(r\), and \(x\) (\(1 \le l \le r \le n\), \(0 \le x \le 2^{30} - 1\)) β€” the first and last elements of the segment and the bitwise OR of \(a_l, a_{l + 1}, \ldots, a_r\), respectively.It is guaranteed that each element of the sequence is contained in at least one of the segments. It is guaranteed that there exists a sequence that satisfies all constraints.It is guaranteed that the sum of \(n\) and the sum of \(m\) over all test cases do not exceed \(2 \cdot 10^5\).
For each test case print the coziness any suitable sequence \(a\) modulo \(10^9 + 7\).
In first example, one of the sequences that fits the constraints is \([0, 2]\). Consider all its non-empty subsequences: \([0]\): the bitwise XOR of this subsequence is \(0\); \([2]\): the bitwise XOR of this subsequence is \(2\); \([0, 2]\): the bitwise XOR of this subsequence is \(2\). The sum of all results is \(4\), so it is the answer.In second example, one of the sequences that fits the constraints is \([0, \, 5, \, 5]\).In third example, one of the sequences that fits the constraints is \([5, \, 6, \, 7, \, 0, \, 2]\).
Input: 3 2 1 1 2 2 3 2 1 3 5 2 3 5 5 4 1 2 7 3 3 7 4 4 0 4 5 2 | Output: 4 20 112
Medium
5
1,122
916
86
16
1,773
H
1773H
H. Hot and Cold
2,600
binary search; interactive
This is an interactive problem.After emigrating to another country, little Hanna came across the fact that playing ""Hot and cold"" became more difficult: she does not understand the hint phrases! You are to write a helping program for her.The playground where the game happens is a rectangle, and the treasure is hidden in some point with integer coordinates between 0 and \(10^6\), inclusive. Hanna visits several points with valid coordinates. If the visited point contains the hidden treasure, she receives the phrase ""Found!"" in the local language. Fortunately, the intonations allow her to recognize this phrase β€” in this problem it will be denoted by an exclamation mark.Otherwise, for each visited point except for the first one, Hanna receives a phrase in the local language stating whether she is now ""Closer"", ""Further"", or ""At the same distance"" from the treasure, compared to the previous point. The distances are measured in Euclidean metric. After the first visited point, in case of no treasure there, Hanna receives the phrase ""Not found"" in the local language.Your program must help Hanna find the treasure by visiting at most 64 points.
Input: Tabilmadi Daha yakin Daha yakin Sama distanco Dalej Znaydeno! | Output: 500 200 560 230 566 240 566 238 30 239 566 239
Expert
2
1,165
0
0
17
72
C
72C
C. Extraordinarily Nice Numbers
1,200
*special; math
The positive integer a is a divisor of the positive integer b if and only if there exists a positive integer c such that a Γ— c = b. King Astyages thinks a positive integer x is extraordinarily nice if the number of its even divisors is equal to the number of its odd divisors.For example 3 has two positive divisors 3 and 1, both of which are odd, so 3 is not extraordinarily nice. On the other hand 2 is only divisible by 2 and 1, so it has one odd and one even divisor. Therefore 2 is extraordinarily nice.Given a positive integer x determine whether it's extraordinarily nice.
The input contains only a single integer x (1 ≀ x ≀ 103).
Write a single yes or no. Write yes if the number is extraordinarily nice and no otherwise.You don't need to care about capital or small letters. The output is case-insensitive.
Input: 2 | Output: yes
Easy
2
579
57
177
0
2,038
G
2038G
G. Guess One Character
1,900
constructive algorithms; implementation; interactive
This is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout) or cout.flush(), in Java or Kotlin β€” System.out.flush(), and in Python β€” sys.stdout.flush().The jury has a string \(s\) consisting of characters 0 and/or 1. The length of this string is \(n\). You can ask the following queries: \(1\) \(t\) β€” ""how many times does \(t\) appear in \(s\) as a contiguous substring?"" Here, \(t\) should be a string consisting of characters 0 and/or 1; its length should be at least \(1\) and at most \(n\). For example, if the string \(s\) is 111011 and the string \(t\) is 11, the response to the query is \(3\). You have to guess at least one character in the string \(s\) by asking no more than \(3\) queries. Note that giving the answer does not count as a query.In every test and in every test case, the string \(s\) is fixed beforehand.
In the example, there are \(3\) test cases: 101, 11 and 10. Note that everything after the // sign is a comment that explains which line means what in the interaction. The jury program won't print these comments in the actual problem, and you shouldn't print them. The empty lines are also added for your convenience, the jury program won't print them, and your solution should not print any empty lines.
Input: 3 // 3 test cases 3 // the length of the string is 3 1 // 101 occurs once 1 // guessed correctly 2 // the length of the string is 2 0 // 00 occurs zero times 0 // 0 occurs zero times 1 // guessed correctly 2 // the length of the string is 2 1 // 1 occurs once 0 // 01 occurs zero times 1 // guessed correctly | Output: 1 101 // how many times 101 occurs 0 2 0 // guess: s[2] is 0 1 00 // how many times 00 occurs 1 0 // how many times 0 occurs 0 1 1 // guess: s[1] is 1 1 1 // how many times 1 occurs 1 01 // how many times 01 occurs 0 2 0 // guess: s[2] is 0
Hard
3
932
0
0
20
2,096
A
2096A
A. Wonderful Sticks
800
constructive algorithms; greedy
You are the proud owner of \(n\) sticks. Each stick has an integer length from \(1\) to \(n\). The lengths of the sticks are distinct.You want to arrange the sticks in a row. There is a string \(s\) of length \(n - 1\) that describes the requirements of the arrangement.Specifically, for each \(i\) from \(1\) to \(n - 1\): If \(s_i = \texttt{<}\), then the length of the stick at position \(i + 1\) must be smaller than all sticks before it; If \(s_i = \texttt{>}\), then the length of the stick at position \(i + 1\) must be larger than all sticks before it.Find any valid arrangement of sticks. We can show that an answer always exists.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 500\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(2 \le n \le 100\)) β€” the number of sticks.The second line of each test case contains a single string \(s\) of length \(n - 1\) consisting of characters \(\texttt{<}\) and \(\texttt{>}\) β€” describing the requirements of the arrangement.
For each test case, output \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \leq a_i \leq n\), the \(a_i\) are distinct) β€” the lengths of the sticks in order. If there are multiple solutions, print any of them.
For the first test case, the requirements of the arrangement are as follows: \(s_1 = \texttt{<}\), which means \(a_2\) is smaller than \(a_1\).Thus, one possible arrangement is \([2, 1]\).For the second test case, the requirements of the arrangement are as follows: \(s_1 = \texttt{<}\), which means \(a_2\) is smaller than \(a_1\); \(s_2 = \texttt{<}\), which means \(a_3\) is smaller than \(a_1\) and \(a_2\); \(s_3 = \texttt{>}\), which means \(a_4\) is larger than \(a_1\), \(a_2\), and \(a_3\); \(s_4 = \texttt{<}\), which means \(a_5\) is smaller than \(a_1\), \(a_2\), \(a_3\), and \(a_4\).Thus, one possible arrangement is \([4, 3, 2, 5, 1]\).
Input: 52<5<<><2>3<>7><>>>< | Output: 2 1 4 3 2 5 1 1 2 2 1 3 3 4 2 5 6 7 1
Beginner
2
639
464
207
20
1,848
C
1848C
C. Vika and Price Tags
1,800
math; number theory
Vika came to her favorite cosmetics store ""Golden Pear"". She noticed that the prices of \(n\) items have changed since her last visit.She decided to analyze how much the prices have changed and calculated the difference between the old and new prices for each of the \(n\) items.Vika enjoyed calculating the price differences and decided to continue this process.Let the old prices be represented as an array of non-negative integers \(a\), and the new prices as an array of non-negative integers \(b\). Both arrays have the same length \(n\).In one operation, Vika constructs a new array \(c\) according to the following principle: \(c_i = |a_i - b_i|\). Then, array \(c\) renamed into array \(b\), and array \(b\) renamed into array \(a\) at the same time, after which Vika repeats the operation with them.For example, if \(a = [1, 2, 3, 4, 5, 6, 7]\); \(b = [7, 6, 5, 4, 3, 2, 1]\), then \(c = [6, 4, 2, 0, 2, 4, 6]\). Then, \(a = [7, 6, 5, 4, 3, 2, 1]\); \(b = [6, 4, 2, 0, 2, 4, 6]\).Vika decided to call a pair of arrays \(a\), \(b\) dull if after some number of such operations all elements of array \(a\) become zeros.Output ""YES"" if the original pair of arrays is dull, and ""NO"" otherwise.
Each test consists of multiple test cases. The first line contains a single integer \(t\) (\(1 \le t \le 10^4\)) β€” the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^5\)) β€” the number of items whose prices have changed.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(0 \le a_i \le 10^9\)) β€” the old prices of the items.The third line contains \(n\) integers \(b_1, b_2, \ldots, b_n\) (\(0 \le b_i \le 10^9\)) β€” the new prices of the items.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case, output ""YES"" if the pair of price arrays is dull, and ""NO"" otherwise.You can output each letter in any case (lowercase or uppercase). For example, the strings ""yEs"", ""yes"", ""Yes"", and ""YES"" will be accepted as a positive answer.
In the first test case, the array \(a\) is initially zero.In the second test case, after the first operation \(a = [1, 2, 3], b = [0, 0, 0]\). After the second operation \(a = [0, 0, 0], b = [1, 2, 3]\).In the third test case, it can be shown that the array \(a\) will never become zero.
Input: 940 0 0 01 2 3 431 2 31 2 321 22 16100 23 53 11 56 321245 31 12 6 6 671 2 3 4 5 6 77 6 5 4 3 2 134 0 24 0 232 5 21 3 426 14 220 00 3 | Output: YES YES NO NO YES YES NO YES YES
Medium
2
1,204
644
260
18
1,311
E
1311E
E. Construct the Binary Tree
2,200
brute force; constructive algorithms; trees
You are given two integers \(n\) and \(d\). You need to construct a rooted binary tree consisting of \(n\) vertices with a root at the vertex \(1\) and the sum of depths of all vertices equals to \(d\).A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex \(v\) is the last different from \(v\) vertex on the path from the root to the vertex \(v\). The depth of the vertex \(v\) is the length of the path from the root to the vertex \(v\). Children of vertex \(v\) are all vertices for which \(v\) is the parent. The binary tree is such a tree that no vertex has more than \(2\) children.You have to answer \(t\) independent test cases.
The first line of the input contains one integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases.The only line of each test case contains two integers \(n\) and \(d\) (\(2 \le n, d \le 5000\)) β€” the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of \(n\) and the sum of \(d\) both does not exceed \(5000\) (\(\sum n \le 5000, \sum d \le 5000\)).
For each test case, print the answer.If it is impossible to construct such a tree, print ""NO"" (without quotes) in the first line. Otherwise, print ""{YES}"" in the first line. Then print \(n-1\) integers \(p_2, p_3, \dots, p_n\) in the second line, where \(p_i\) is the parent of the vertex \(i\). Note that the sequence of parents you print should describe some binary tree.
Pictures corresponding to the first and the second test cases of the example:
Input: 3 5 7 10 19 10 18 | Output: YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO
Hard
3
699
414
377
13
1,077
B
1077B
B. Disturbed People
1,000
greedy
There is a house with \(n\) flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of \(n\) integer numbers \(a_1, a_2, \dots, a_n\), where \(a_i = 1\) if in the \(i\)-th flat the light is on and \(a_i = 0\) otherwise.Vova thinks that people in the \(i\)-th flats are disturbed and cannot sleep if and only if \(1 < i < n\) and \(a_{i - 1} = a_{i + 1} = 1\) and \(a_i = 0\).Vova is concerned by the following question: what is the minimum number \(k\) such that if people from exactly \(k\) pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number \(k\).
The first line of the input contains one integer \(n\) (\(3 \le n \le 100\)) β€” the number of flats in the house.The second line of the input contains \(n\) integers \(a_1, a_2, \dots, a_n\) (\(a_i \in \{0, 1\}\)), where \(a_i\) is the state of light in the \(i\)-th flat.
Print only one integer β€” the minimum number \(k\) such that if people from exactly \(k\) pairwise distinct flats will turn off the light then nobody will be disturbed.
In the first example people from flats \(2\) and \(7\) or \(4\) and \(7\) can turn off the light and nobody will be disturbed. It can be shown that there is no better answer in this example.There are no disturbed people in second and third examples.
Input: 10 1 1 0 1 1 0 1 0 1 0 | Output: 2
Beginner
1
684
271
167
10
1,114
E
1114E
E. Arithmetic Progression
2,200
binary search; interactive; number theory; probabilities
This is an interactive problem!An arithmetic progression or arithmetic sequence is a sequence of integers such that the subtraction of element with its previous element (\(x_i - x_{i - 1}\), where \(i \ge 2\)) is constant β€” such difference is called a common difference of the sequence.That is, an arithmetic progression is a sequence of form \(x_i = x_1 + (i - 1) d\), where \(d\) is a common difference of the sequence.There is a secret list of \(n\) integers \(a_1, a_2, \ldots, a_n\).It is guaranteed that all elements \(a_1, a_2, \ldots, a_n\) are between \(0\) and \(10^9\), inclusive.This list is special: if sorted in increasing order, it will form an arithmetic progression with positive common difference (\(d > 0\)). For example, the list \([14, 24, 9, 19]\) satisfies this requirement, after sorting it makes a list \([9, 14, 19, 24]\), which can be produced as \(x_n = 9 + 5 \cdot (n - 1)\).Also you are also given a device, which has a quite discharged battery, thus you can only use it to perform at most \(60\) queries of following two types: Given a value \(i\) (\(1 \le i \le n\)), the device will show the value of the \(a_i\). Given a value \(x\) (\(0 \le x \le 10^9\)), the device will return \(1\) if an element with a value strictly greater than \(x\) exists, and it will return \(0\) otherwise.Your can use this special device for at most \(60\) queries. Could you please find out the smallest element and the common difference of the sequence? That is, values \(x_1\) and \(d\) in the definition of the arithmetic progression. Note that the array \(a\) is not sorted.
Note that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The list in the example test is \([14, 24, 9, 19]\).
Input: 4 0 1 14 24 9 19 | Output: > 25 > 15 ? 1 ? 2 ? 3 ? 4 ! 9 5
Hard
4
1,592
0
0
11
630
Q
630Q
Q. Pyramids
1,700
geometry; math
IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids β€” one triangular, one quadrangular and one pentagonal.The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length.
The only line of the input contains three integers l3, l4, l5 (1 ≀ l3, l4, l5 ≀ 1000) β€” the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.
Output one number β€” the total volume of the pyramids. Absolute or relative error should not be greater than 10 - 9.
Input: 2 5 3 | Output: 38.546168065709
Medium
2
859
173
115
6
908
C
908C
C. New Year and Curling
1,500
brute force; geometry; implementation; math
Carol is currently curling.She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100.She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.
The first line will contain two integers n and r (1 ≀ n, r ≀ 1 000), the number of disks, and the radius of the disks, respectively.The next line will contain n integers x1, x2, ..., xn (1 ≀ xi ≀ 1 000) β€” the x-coordinates of the disks.
Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6.Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if for all coordinates.
The final positions of the disks will look as follows: In particular, note the position of the last disk.
Input: 6 25 5 6 8 3 12 | Output: 2 6.0 9.87298334621 13.3370849613 12.5187346573 13.3370849613
Medium
4
668
236
381
9
173
D
173D
D. Deputies
2,500
constructive algorithms; graphs; greedy; implementation
The Trinitarian kingdom has exactly n = 3k cities. All of them are located on the shores of river Trissisipi, which flows through the whole kingdom. Some of the cities are located on one side of the river, and all the rest are on the other side.Some cities are connected by bridges built between them. Each bridge connects two cities that are located on the opposite sides of the river. Between any two cities exists no more than one bridge.The recently inaugurated King Tristan the Third is busy distributing his deputies among cities. In total there are k deputies and the king wants to commission each of them to control exactly three cities. However, no deputy can be entrusted to manage the cities, which are connected by a bridge β€” the deputy can set a too high fee for travelling over the bridge to benefit his pocket, which is bad for the reputation of the king.Help King Tristan the Third distribute the deputies between the cities, if it is possible.
The first line contains two integers n and m β€” the number of cities and bridges (3 ≀ n < 105, n = 3k, 0 ≀ m ≀ 105). Next m lines describe the bridges. The i-th line contains two integers ai and bi β€” the numbers of cities that are connected by the i-th bridge (1 ≀ ai, bi ≀ n, ai β‰  bi, 1 ≀ i ≀ m).It is guaranteed that no bridge connects a city with itself and that any two cities are connected with no more than one bridge.
If distributing the deputies in the required manner is impossible, print in a single line ""NO"" (without the quotes).Otherwise, in the first line print ""YES"" (without the quotes), and in the second line print which deputy should be put in charge of each city. The i-th number should represent the number of the deputy (from 1 to k), who should be in charge of city numbered i-th in the input β€” overall there should be n numbers.If there are multiple solutions, print any of them.
Input: 6 61 24 13 56 52 64 6 | Output: YES1 2 1 2 2 1
Expert
4
960
423
482
1
28
C
28C
C. Bath Queue
2,200
combinatorics; dp; probabilities
There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.
The first line contains two positive integers n and m (1 ≀ n, m ≀ 50) β€” the amount of students and the amount of rooms. The second line contains m integers a1, a2, ... , am (1 ≀ ai ≀ 50). ai means the amount of wash basins in the i-th room.
Output single number: the expected value of the size of the largest queue. Your answer must have an absolute or relative error less than 10 - 9.
Input: 1 12 | Output: 1.00000000000000000000
Hard
3
534
240
144
0
1,530
E
1530E
E. Minimax
2,100
constructive algorithms; greedy; strings
Prefix function of string \(t = t_1 t_2 \ldots t_n\) and position \(i\) in it is defined as the length \(k\) of the longest proper (not equal to the whole substring) prefix of substring \(t_1 t_2 \ldots t_i\) which is also a suffix of the same substring.For example, for string \(t = \) abacaba the values of the prefix function in positions \(1, 2, \ldots, 7\) are equal to \([0, 0, 1, 0, 1, 2, 3]\).Let \(f(t)\) be equal to the maximum value of the prefix function of string \(t\) over all its positions. For example, \(f(\)abacaba\() = 3\).You are given a string \(s\). Reorder its characters arbitrarily to get a string \(t\) (the number of occurrences of any character in strings \(s\) and \(t\) must be equal). The value of \(f(t)\) must be minimized. Out of all options to minimize \(f(t)\), choose the one where string \(t\) is the lexicographically smallest.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^5\)). Description of the test cases follows.The only line of each test case contains string \(s\) (\(1 \le |s| \le 10^5\)) consisting of lowercase English letters.It is guaranteed that the sum of lengths of \(s\) over all test cases does not exceed \(10^5\).
For each test case print a single string \(t\).The multisets of letters in strings \(s\) and \(t\) must be equal. The value of \(f(t)\), the maximum of prefix functions in string \(t\), must be as small as possible. String \(t\) must be the lexicographically smallest string out of all strings satisfying the previous conditions.
A string \(a\) is lexicographically smaller than a string \(b\) if and only if one of the following holds: \(a\) is a prefix of \(b\), but \(a \ne b\); in the first position where \(a\) and \(b\) differ, the string \(a\) has a letter that appears earlier in the alphabet than the corresponding letter in \(b\).In the first test case, \(f(t) = 0\) and the values of prefix function are \([0, 0, 0, 0, 0]\) for any permutation of letters. String ckpuv is the lexicographically smallest permutation of letters of string vkcup.In the second test case, \(f(t) = 1\) and the values of prefix function are \([0, 1, 0, 1, 0, 1, 0]\).In the third test case, \(f(t) = 5\) and the values of prefix function are \([0, 1, 2, 3, 4, 5]\).
Input: 3 vkcup abababa zzzzzz | Output: ckpuv aababab zzzzzz
Hard
3
867
371
329
15
1,032
C
1032C
C. Playing Piano
1,700
constructive algorithms; dp
Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence \(a_1, a_2, \ldots, a_n\) of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.Paul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed.Let's denote the fingers of hand by numbers from \(1\) to \(5\). We call a fingering any sequence \(b_1, \ldots, b_n\) of fingers numbers. A fingering is convenient if for all \(1\leq i \leq n - 1\) the following holds: if \(a_i < a_{i+1}\) then \(b_i < b_{i+1}\), because otherwise Paul needs to take his hand off the keyboard to play the \((i+1)\)-st note; if \(a_i > a_{i+1}\) then \(b_i > b_{i+1}\), because of the same; if \(a_i = a_{i+1}\) then \(b_i\neq b_{i+1}\), because using the same finger twice in a row is dumb. Please note that there is \(\neq\), not \(=\) between \(b_i\) and \(b_{i+1}\). Please provide any convenient fingering or find out that there is none.
The first line contains a single integer \(n\) (\(1 \le n \le 10^5\)) denoting the number of notes.The second line contains \(n\) integers \(a_1, a_2, \ldots, a_n\) (\(1 \le a_i \le 2\cdot10^5\)) denoting the positions of notes on the keyboard.
If there is no convenient fingering, print \(-1\). Otherwise, print \(n\) numbers \(b_1, b_2, \ldots, b_n\), each from \(1\) to \(5\), denoting a convenient fingering, separated by spaces.
The third sample test is kinda ""Non stop"" song by Reflex.
Input: 5 1 1 4 2 2 | Output: 1 4 5 4 5
Medium
2
1,223
244
188
10
1,093
D
1093D
D. Beautiful Graph
1,700
dfs and similar; graphs
You are given an undirected unweighted graph consisting of \(n\) vertices and \(m\) edges.You have to write a number on each vertex of the graph. Each number should be \(1\), \(2\) or \(3\). The graph becomes beautiful if for each edge the sum of numbers on vertices connected by this edge is odd.Calculate the number of possible ways to write numbers \(1\), \(2\) and \(3\) on vertices so the graph becomes beautiful. Since this number may be large, print it modulo \(998244353\).Note that you have to write exactly one number on each vertex.The graph does not have any self-loops or multiple edges.
The first line contains one integer \(t\) (\(1 \le t \le 3 \cdot 10^5\)) β€” the number of tests in the input.The first line of each test contains two integers \(n\) and \(m\) (\(1 \le n \le 3 \cdot 10^5, 0 \le m \le 3 \cdot 10^5\)) β€” the number of vertices and the number of edges, respectively. Next \(m\) lines describe edges: \(i\)-th line contains two integers \(u_i\), \( v_i\) (\(1 \le u_i, v_i \le n; u_i \neq v_i\)) β€” indices of vertices connected by \(i\)-th edge.It is guaranteed that \(\sum\limits_{i=1}^{t} n \le 3 \cdot 10^5\) and \(\sum\limits_{i=1}^{t} m \le 3 \cdot 10^5\).
For each test print one line, containing one integer β€” the number of possible ways to write numbers \(1\), \(2\), \(3\) on the vertices of given graph so it becomes beautiful. Since answers may be large, print them modulo \(998244353\).
Possible ways to distribute numbers in the first test: the vertex \(1\) should contain \(1\), and \(2\) should contain \(2\); the vertex \(1\) should contain \(3\), and \(2\) should contain \(2\); the vertex \(1\) should contain \(2\), and \(2\) should contain \(1\); the vertex \(1\) should contain \(2\), and \(2\) should contain \(3\). In the second test there is no way to distribute numbers.
Input: 2 2 1 1 2 4 6 1 2 1 3 1 4 2 3 2 4 3 4 | Output: 4 0
Medium
2
600
588
236
10
2,009
C
2009C
C. The Legend of Freya the Frog
1,100
implementation; math
Freya the Frog is traveling on the 2D coordinate plane. She is currently at point \((0,0)\) and wants to go to point \((x,y)\). In one move, she chooses an integer \(d\) such that \(0 \leq d \leq k\) and jumps \(d\) spots forward in the direction she is facing. Initially, she is facing the positive \(x\) direction. After every move, she will alternate between facing the positive \(x\) direction and the positive \(y\) direction (i.e., she will face the positive \(y\) direction on her second move, the positive \(x\) direction on her third move, and so on). What is the minimum amount of moves she must perform to land on point \((x,y)\)?
The first line contains an integer \(t\) (\(1 \leq t \leq 10^4\)) β€” the number of test cases.Each test case contains three integers \(x\), \(y\), and \(k\) (\(0 \leq x, y \leq 10^9, 1 \leq k \leq 10^9\)).
For each test case, output the number of jumps Freya needs to make on a new line.
In the first sample, one optimal set of moves is if Freya jumps in the following way: (\(0,0\)) \(\rightarrow\) (\(2,0\)) \(\rightarrow\) (\(2,2\)) \(\rightarrow\) (\(3,2\)) \(\rightarrow\) (\(3,5\)) \(\rightarrow\) (\(6,5\)) \(\rightarrow\) (\(6,8\)) \(\rightarrow\) (\(9,8\)) \(\rightarrow\) (\(9,11\)). This takes 8 jumps.
Input: 39 11 30 10 81000000 100000 10 | Output: 8 4 199999
Easy
2
641
204
81
20
97
D
97D
D. Robot in Basement
2,700
bitmasks; brute force; implementation
The Professor has lost his home robot yet again. After some thinking Professor understood that he had left the robot in the basement.The basement in Professor's house is represented by a rectangle n Γ— m, split into 1 Γ— 1 squares. Some squares are walls which are impassable; other squares are passable. You can get from any passable square to any other passable square moving through edge-adjacent passable squares. One passable square is the exit from the basement. The robot is placed exactly in one passable square. Also the robot may be placed in the exit square.Professor is scared of going to the dark basement looking for the robot at night. However, he has a basement plan and the robot's remote control. Using the remote, Professor can send signals to the robot to shift one square left, right, up or down. When the robot receives a signal, it moves in the required direction if the robot's neighboring square in the given direction is passable. Otherwise, the robot stays idle.Professor wrote a sequence of k commands on a piece of paper. He thinks that the sequence can lead the robot out of the basement, wherever it's initial position might be. Professor programmed another robot to press the required buttons on the remote according to the notes on the piece of paper. Professor was just about to run the program and go to bed, when he had an epiphany.Executing each command takes some energy and Professor doesn't want to get huge electricity bill at the end of the month. That's why he wants to find in the sequence he has written out the minimal possible prefix that would guarantee to lead the robot out to the exit after the prefix is fulfilled. And that's the problem Professor challenges you with at this late hour.
The first line contains three integers n, m and k (3 ≀ n, m ≀ 150, 1 ≀ k ≀ 105). Next n lines contain m characters each β€” that is the Professor's basement's description: ""#"" stands for a wall, ""."" stands for a passable square and ""E"" stands for the exit from the basement (this square also is passable). It is possible to get from each passable square to the exit, all squares located by the n Γ— m rectangle's perimeter are the walls. Exactly one square is the exit from the basement. The last line contains k characters, the description of the sequence of commands that Professor has written out on a piece of paper. ""L"", ""R"", ""U"", ""D"" stand for commands left, right, up and down correspondingly.
Print in the output file the length of the smallest possible prefix that will lead the robot to the exit square. In other words, wherever the robot had been positioned initially, it should be positioned in the exit square after all the commands from the prefix are fulfilled (during doing commands the robot can come and leave the exit square, but only the last position of the robot is interesting for us). If Professor is mistaken and no prefix (including the whole sequence) can bring the robot to the exit, print ""-1"" (without the quotes). If there is the only passable square and it is the exit, print ""0"" (without the quotes).
Input: 5 5 7######...##...##E..######UULLDDR | Output: 6
Master
3
1,736
711
636
0
1,943
F
1943F
F. Minimum Hamming Distance
3,500
dp
You are given a binary string\(^\dagger\) \(s\) of length \(n\).A binary string \(p\) of the same length \(n\) is called good if for every \(i\) (\(1 \leq i \leq n\)), there exist indices \(l\) and \(r\) such that: \(1 \leq l \leq i \leq r \leq n\) \(s_i\) is a mode\(^\ddagger\) of the string \(p_lp_{l+1}\ldots p_r\) You are given another binary string \(t\) of length \(n\). Find the minimum Hamming distance\(^\S\) between \(t\) and any good string \(g\).\(^\dagger\) A binary string is a string that only consists of characters \(\mathtt{0}\) and \(\mathtt{1}\).\(^\ddagger\) Character \(c\) is a mode of string \(p\) of length \(m\) if the number of occurrences of \(c\) in \(p\) is at least \(\lceil \frac{m}{2} \rceil\). For example, \(\mathtt{0}\) is a mode of \(\mathtt{010}\), \(\mathtt{1}\) is not a mode of \(\mathtt{010}\), and both \(\mathtt{0}\) and \(\mathtt{1}\) are modes of \(\mathtt{011010}\).\(^\S\) The Hamming distance of strings \(a\) and \(b\) of length \(m\) is the number of indices \(i\) such that \(1 \leq i \leq m\) and \(a_i \neq b_i\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 10^5\)). The description of the test cases follows.The first line of each test case contains a single integer \(n\) (\(1 \le n \le 10^4\)) β€” the length of the binary string \(s\).The second line of each test case contains a binary string \(s\) of length \(n\) consisting of characters 0 and 1.The third line of each test case contains a binary string \(t\) of length \(n\) consisting of characters 0 and 1.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^6\), with the additional assurance that the sum of \(n^2\) over all test cases does not exceed \(10^8\)
For each test case, print the minimum Hamming distance between \(t\) and any good string \(g\).
In the first test case, \(g=\mathtt{000}\) is a good string which has Hamming distance \(0\) from \(t\).In the second test case, \(g=\mathtt{0011}\) is a good string which has Hamming distance \(2\) from \(t\). It can be proven that there are no good strings with Hamming distance less than \(2\) from \(t\).In the third test case, \(g=\mathtt{001100}\) is a good string which has Hamming distance \(1\) from \(t\).
Input: 330000004000011116111111000100 | Output: 0 2 1
Master
1
1,068
699
95
19
662
C
662C
C. Binary Table
2,600
bitmasks; brute force; divide and conquer; dp; fft; math
You are given a table consisting of n rows and m columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa.What is the minimum number of cells with value 1 you can get after applying some number of operations?
The first line of the input contains two integers n and m (1 ≀ n ≀ 20, 1 ≀ m ≀ 100 000) β€” the number of rows and the number of columns, respectively.Then n lines follows with the descriptions of the rows. Each line has length m and contains only digits '0' and '1'.
Output a single integer β€” the minimum possible number of ones you can get after applying some sequence of operations.
Input: 3 4011010100111 | Output: 2
Expert
6
328
265
117
6
1,703
B
1703B
B. ICPC Balloons
800
data structures; implementation
In an ICPC contest, balloons are distributed as follows: Whenever a team solves a problem, that team gets a balloon. The first team to solve a problem gets an additional balloon. A contest has 26 problems, labelled \(\textsf{A}\), \(\textsf{B}\), \(\textsf{C}\), ..., \(\textsf{Z}\). You are given the order of solved problems in the contest, denoted as a string \(s\), where the \(i\)-th character indicates that the problem \(s_i\) has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.
The first line of the input contains an integer \(t\) (\(1 \leq t \leq 100\)) β€” the number of testcases.The first line of each test case contains an integer \(n\) (\(1 \leq n \leq 50\)) β€” the length of the string.The second line of each test case contains a string \(s\) of length \(n\) consisting of uppercase English letters, denoting the order of solved problems.
For each test case, output a single integer β€” the total number of balloons that the teams received.
In the first test case, \(5\) balloons are given out: Problem \(\textsf{A}\) is solved. That team receives \(2\) balloons: one because they solved the problem, an an additional one because they are the first team to solve problem \(\textsf{A}\). Problem \(\textsf{B}\) is solved. That team receives \(2\) balloons: one because they solved the problem, an an additional one because they are the first team to solve problem \(\textsf{B}\). Problem \(\textsf{A}\) is solved. That team receives only \(1\) balloon, because they solved the problem. Note that they don't get an additional balloon because they are not the first team to solve problem \(\textsf{A}\). The total number of balloons given out is \(2+2+1=5\).In the second test case, there is only one problem solved. The team who solved it receives \(2\) balloons: one because they solved the problem, an an additional one because they are the first team to solve problem \(\textsf{A}\).
Input: 63ABA1A3ORZ5BAAAA4BKPT10CODEFORCES | Output: 5 2 6 7 8 17
Beginner
2
629
366
99
17
1,562
D1
1562D1
D1. Two Hundred Twenty One (easy version)
1,700
data structures; dp; math
This is the easy version of the problem. The difference between the versions is that the easy version does not require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine.The main element of this machine are \(n\) rods arranged along one straight line and numbered from \(1\) to \(n\) inclusive. Each of these rods must carry an electric charge quantitatively equal to either \(1\) or \(-1\) (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero.More formally, the rods can be represented as an array of \(n\) numbers characterizing the charge: either \(1\) or \(-1\). Then the condition must hold: \(a_1 - a_2 + a_3 - a_4 + \ldots = 0\), or \(\sum\limits_{i=1}^n (-1)^{i-1} \cdot a_i = 0\).Sparky charged all \(n\) rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has \(q\) questions. In the \(i\)th question Sparky asks: if the machine consisted only of rods with numbers \(l_i\) to \(r_i\) inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all.If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods.Help your friends and answer all of Sparky's questions!
Each test contains multiple test cases.The first line contains one positive integer \(t\) (\(1 \le t \le 10^3\)), denoting the number of test cases. Description of the test cases follows.The first line of each test case contains two positive integers \(n\) and \(q\) (\(1 \le n, q \le 3 \cdot 10^5\)) β€” the number of rods and the number of questions.The second line of each test case contains a non-empty string \(s\) of length \(n\), where the charge of the \(i\)-th rod is \(1\) if \(s_i\) is the ""+"" symbol, or \(-1\) if \(s_i\) is the ""-"" symbol.Each next line from the next \(q\) lines contains two positive integers \(l_i\) ans \(r_i\) (\(1 \le l_i \le r_i \le n\)) β€” numbers, describing Sparky's questions.It is guaranteed that the sum of \(n\) over all test cases does not exceed \(3 \cdot 10^5\), and the sum of \(q\) over all test cases does not exceed \(3 \cdot 10^5\).
For each test case, print a single integer β€” the minimal number of rods that can be removed.
In the first test case for the first query you can remove the rods numbered \(5\) and \(8\), then the following set of rods will remain: +--+--++-++-. It is easy to see that here the sign-variable sum is zero.In the second test case: For the first query, we can remove the rods numbered \(1\) and \(11\), then the following set of rods will remain: --++---++---. It is easy to see that here the sign-variable sum is zero. For the second query we can remove the rod numbered \(9\), then the following set of rods will remain: ---++-. It is easy to see that here the variable sum is zero. For the third query we can not remove the rods at all.
Input: 3 14 1 +--++---++-++- 1 14 14 3 +--++---+++--- 1 14 6 12 3 10 4 10 +-+- 1 1 1 2 1 3 1 4 2 2 2 3 2 4 3 3 3 4 4 4 | Output: 2 2 1 0 1 2 1 2 1 2 1 1 2 1
Medium
3
1,820
884
92
15
2,084
A
2084A
A. Max and Mod
800
constructive algorithms; math
You are given an integer \(n\). Find any permutation \(p\) of length \(n\)\(^{\text{βˆ—}}\) such that: For all \(2 \le i \le n\), \(\max(p_{i - 1}, p_i) \bmod i\) \(^{\text{†}}\) \(= i - 1\) is satisfied. If it is impossible to find such a permutation \(p\), output \(-1\).\(^{\text{βˆ—}}\)A permutation of length \(n\) is an array consisting of \(n\) distinct integers from \(1\) to \(n\) in arbitrary order. For example, \([2,3,1,5,4]\) is a permutation, but \([1,2,2]\) is not a permutation (\(2\) appears twice in the array), and \([1,3,4]\) is also not a permutation (\(n=3\) but there is \(4\) in the array). \(^{\text{†}}\)\(x \bmod y\) denotes the remainder from dividing \(x\) by \(y\).
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 99\)). The description of the test cases follows. The first line of each test case contains a single integer \(n\) (\(2 \le n \le 100\)).
For each test case: If such a permutation \(p\) doesn't exist, output a single integer \(-1\). Otherwise, output \(n\) integers \(p_1, p_2, \ldots, p_n\) β€” the permutation \(p\) you've found. If there are multiple answers, output any of them.
In the first test case, it is impossible to find such a permutation \(p\), so you should output \(-1\).In the fourth test case, \(p = [1, 5, 2, 3, 4]\) satisfies the condition: For \(i = 2\), \(\max(p_1, p_2) = 5\) and \(5 \bmod 2 = 1\). For \(i = 3\), \(\max(p_2, p_3) = 5\) and \(5 \bmod 3 = 2\). For \(i = 4\), \(\max(p_3, p_4) = 3\) and \(3 \bmod 4 = 3\). For \(i = 5\), \(\max(p_4, p_5) = 4\) and \(4 \bmod 5 = 4\).
Input: 42345 | Output: -1 3 2 1 -1 1 5 2 3 4
Beginner
2
691
247
242
20
1,916
F
1916F
F. Group Division
2,900
constructive algorithms; dfs and similar; graphs; greedy
In the \(31\)st lyceum, there were two groups of olympiad participants: computer science and mathematics. The number of computer scientists was \(n_1\), and the number of mathematicians was \(n_2\). It is not known for certain who belonged to which group, but it is known that there were friendly connections between some pairs of people (these connections could exist between a pair of people from the same group or from different groups).The connections were so strong that even if one person is removed along with all their friendly connections, any pair of people still remains acquainted either directly or through mutual friends.\(^{\dagger}\) More formally, two people \((x, y)\) are acquainted in the following case: there are people \(a_1, a_2, \ldots,a_n\) (\(1 \le a_i \le n_1 + n_2\)) such that the following conditions are simultaneously met:\(\bullet\) Person \(x\) is directly acquainted with \(a_1\).\(\bullet\) Person \(a_n\) is directly acquainted with \(y\).\(\bullet\) Person \(a_i\) is directly acquainted with \(a_{i + 1}\) for any (\(1 \le i \le n - 1\)).The teachers were dissatisfied with the fact that computer scientists were friends with mathematicians and vice versa, so they decided to divide the students into two groups in such a way that the following two conditions are met:\(\bullet\) There were \(n_1\) people in the computer science group, and \(n_2\) people in the mathematics group.\(\bullet\) Any pair of computer scientists should be acquainted (acquaintance involving mutual friends, who must be from the same group as the people in the pair, is allowed), the same should be true for mathematicians.Help them solve this problem and find out who belongs to which group.
Each test consists of several test cases. The first line contains a single integer \(t\) (\(1 \le t \le 1000\)) β€” the number of test cases. Then follows the description of the test cases.The first line of each test case contains three integers \(n_1\), \(n_2\), and \(m\) (\(1 \le n_1, n_2 \le 2000\), \(1 \le m \le 5000\)). \(n_1\), \(n_2\) are the sizes of the two groups described in the problem, and \(m\) is the number of friendly connections initially.The following \(m\) lines describe the friendly connections: in the \(i\)-th (\(1 \le i \le m\)) line, a pair of numbers \((a, b)\) is given, which means that the person with number \(a\) is friends with the person with number \(b\) (and vice versa).It is guaranteed that for each test case, all friendly connections are distinct.It is guaranteed that the sum of \(n_1 + n_2\) for all test cases does not exceed \(2000\), and the sum of \(m\) for all test cases does not exceed \(5000\).It is also guaranteed that for each test case, a solution exists.If there are several answers, print any of them.
For each test case, output two lines.In the first line, output \(n_1\) distinct numbers \(a_i\) (\(1 \le a_i \le n_1 + n_2\)) β€” the people belonging to the first group.In the second line, output \(n_2\) distinct numbers \(b_i\) (\(1 \le b_i \le n_1 + n_2\)) β€” the people belonging to the second group.All numbers must be distinct.If there are several possible answers, print any one.
Consider the third test case. The division into groups looks as follows: The students selected as computer scientists are colored in green, and those selected as mathematicians are colored in blue.Consider all pairs of computer scientists and how they are acquainted:Pairs \((4, 5), (4, 6)\) are directly acquainted.Pair \((5, 6)\) is acquainted through the computer scientist with number \(4\).Consider all pairs of mathematicians and how they are acquainted:Pairs \((1, 2), (2, 3)\) are directly acquainted.Pair \((1, 3)\) is acquainted through the mathematician with number \(2\).We conclude that any pair of people belonging to the same group is acquainted with each other, thus the division into two groups is correct.
Input: 31 2 32 31 31 21 4 72 53 42 41 23 54 51 53 3 71 21 62 32 53 44 54 6 | Output: 3 1 2 5 1 2 3 4 4 5 6 1 2 3
Master
4
1,710
1,058
383
19
1,227
E
1227E
E. Arson In Berland Forest
2,200
binary search; graphs; graphs; shortest paths
The Berland Forest can be represented as an infinite cell plane. Every cell contains a tree. That is, contained before the recent events.A destructive fire raged through the Forest, and several trees were damaged by it. Precisely speaking, you have a \(n \times m\) rectangle map which represents the damaged part of the Forest. The damaged trees were marked as ""X"" while the remaining ones were marked as ""."". You are sure that all burnt trees are shown on the map. All the trees outside the map are undamaged.The firemen quickly extinguished the fire, and now they are investigating the cause of it. The main version is that there was an arson: at some moment of time (let's consider it as \(0\)) some trees were set on fire. At the beginning of minute \(0\), only the trees that were set on fire initially were burning. At the end of each minute, the fire spread from every burning tree to each of \(8\) neighboring trees. At the beginning of minute \(T\), the fire was extinguished.The firemen want to find the arsonists as quickly as possible. The problem is, they know neither the value of \(T\) (how long the fire has been raging) nor the coordinates of the trees that were initially set on fire. They want you to find the maximum value of \(T\) (to know how far could the arsonists escape) and a possible set of trees that could be initially set on fire.Note that you'd like to maximize value \(T\) but the set of trees can be arbitrary.
The first line contains two integer \(n\) and \(m\) (\(1 \le n, m \le 10^6\), \(1 \le n \cdot m \le 10^6\)) β€” the sizes of the map.Next \(n\) lines contain the map. The \(i\)-th line corresponds to the \(i\)-th row of the map and contains \(m\)-character string. The \(j\)-th character of the \(i\)-th string is ""X"" if the corresponding tree is burnt and ""."" otherwise.It's guaranteed that the map contains at least one ""X"".
In the first line print the single integer \(T\) β€” the maximum time the Forest was on fire. In the next \(n\) lines print the certificate: the map (\(n \times m\) rectangle) where the trees that were set on fire are marked as ""X"" and all other trees are marked as ""."".
Input: 3 6 XXXXXX XXXXXX XXXXXX | Output: 1 ...... .X.XX. ......
Hard
4
1,449
430
272
12
1,178
F1
1178F1
F1. Short Colorful Strip
2,200
combinatorics; dfs and similar; dp
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of \(m\) and the time limit. You need to solve both subtasks in order to hack this one.There are \(n+1\) distinct colours in the universe, numbered \(0\) through \(n\). There is a strip of paper \(m\) centimetres long initially painted with colour \(0\). Alice took a brush and painted the strip using the following process. For each \(i\) from \(1\) to \(n\), in this order, she picks two integers \(0 \leq a_i < b_i \leq m\), such that the segment \([a_i, b_i]\) is currently painted with a single colour, and repaints it with colour \(i\). Alice chose the segments in such a way that each centimetre is now painted in some colour other than \(0\). Formally, the segment \([i-1, i]\) is painted with colour \(c_i\) (\(c_i \neq 0\)). Every colour other than \(0\) is visible on the strip.Count the number of different pairs of sequences \(\{a_i\}_{i=1}^n\), \(\{b_i\}_{i=1}^n\) that result in this configuration. Since this number may be large, output it modulo \(998244353\).
The first line contains a two integers \(n\), \(m\) (\(1 \leq n \leq 500\), \(n = m\)) β€” the number of colours excluding the colour \(0\) and the length of the paper, respectively.The second line contains \(m\) space separated integers \(c_1, c_2, \ldots, c_m\) (\(1 \leq c_i \leq n\)) β€” the colour visible on the segment \([i-1, i]\) after the process ends. It is guaranteed that for all \(j\) between \(1\) and \(n\) there is an index \(k\) such that \(c_k = j\).Note that since in this subtask \(n = m\), this means that \(c\) is a permutation of integers \(1\) through \(n\).
Output a single integer β€” the number of ways Alice can perform the painting, modulo \(998244353\).
In the first example, there are \(5\) ways, all depicted in the figure below. Here, \(0\) is white, \(1\) is red, \(2\) is green and \(3\) is blue.Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour \(2\).
Input: 3 3 1 2 3 | Output: 5
Hard
3
1,107
579
98
11
1,214
E
1214E
E. Petya and Construction Set
2,000
constructive algorithms; graphs; math; sortings; trees
It's Petya's birthday party and his friends have presented him a brand new ""Electrician-\(n\)"" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.Construction set ""Electrician-\(n\)"" consists of \(2n - 1\) wires and \(2n\) light bulbs. Each bulb has its own unique index that is an integer from \(1\) to \(2n\), while all wires look the same and are indistinguishable. In order to complete this construction set one has to use each of the wires to connect two distinct bulbs. We define a chain in a completed construction set as a sequence of distinct bulbs of length at least two, such that every two consecutive bulbs in this sequence are directly connected by a wire. Completed construction set configuration is said to be correct if a resulting network of bulbs and wires has a tree structure, i.e. any two distinct bulbs are the endpoints of some chain.Petya was assembling different configurations for several days, and he noticed that sometimes some of the bulbs turn on. After a series of experiments he came up with a conclusion that bulbs indexed \(2i\) and \(2i - 1\) turn on if the chain connecting them consists of exactly \(d_i\) wires. Moreover, the following important condition holds: the value of \(d_i\) is never greater than \(n\).Petya did his best but was not able to find a configuration that makes all bulbs to turn on, so he seeks your assistance. Please, find out a configuration that makes all bulbs shine. It is guaranteed that such configuration always exists.
The first line of the input contains a single integer \(n\) (\(1 \leq n \leq 100\,000\)) β€” the parameter of a construction set that defines the number of bulbs and the number of wires.Next line contains \(n\) integers \(d_1, d_2, \ldots, d_n\) (\(1 \leq d_i \leq n\)), where \(d_i\) stands for the number of wires the chain between bulbs \(2i\) and \(2i - 1\) should consist of.
Print \(2n - 1\) lines. The \(i\)-th of them should contain two distinct integers \(a_i\) and \(b_i\) (\(1 \leq a_i, b_i \leq 2n\), \(a_i \ne b_i\)) β€” indices of bulbs connected by a wire.If there are several possible valid answer you can print any of them.
Answer for the first sample test. Answer for the second sample test.
Input: 3 2 2 2 | Output: 1 6 2 6 3 5 3 6 4 5
Hard
5
1,545
378
257
12
2,097
F
2097F
F. Lost Luggage
3,500
dp; flows
As is known, the airline ""Trouble"" often loses luggage, and concerned journalists decided to calculate the maximum number of luggage pieces that may not return to travelers.The airline ""Trouble"" operates flights between \(n\) airports, numbered from \(1\) to \(n\). The journalists' experiment will last for \(m\) days. It is known that at midnight before the first day of the experiment, there were \(s_j\) lost pieces of luggage in the \(j\)-th airport. On the \(i\)-th day, the following occurs: In the morning, \(2n\) flights take off simultaneously, including \(n\) flights of the first type and \(n\) flights of the second type. The \(j\)-th flight of the first type flies from airport \(j\) to airport \((((j-2) \bmod n )+ 1)\) (the previous airport, with the first airport being the last), and it can carry no more than \(a_{i,j}\) lost pieces of luggage. The \(j\)-th flight of the second type flies from airport \(j\) to airport \(((j \bmod n) + 1)\) (the next airport, with the last airport being the first), and it can carry no more than \(c_{i,j}\) lost pieces of luggage. In the afternoon, a check of lost luggage is conducted at the airports. If after the flights have departed on that day, there are \(x\) pieces of luggage remaining in the \(j\)-th airport and \(x \ge b_{i, j}\), then at least \(x - b_{i, j}\) pieces of luggage are found, and they cease to be lost. In the evening, all \(2n\) flights conclude, and the lost luggage transported that day arrives at the corresponding airports. For each \(k\) from \(1\) to \(m\), the journalists want to know the maximum number of lost pieces of luggage that may be unfound during the checks over the first \(k\) days. Note that for each \(k\), these values are calculated independently.
Each test contains multiple test cases. The first line contains the number of test cases \(t\) (\(1 \le t \le 100\)). The description of the test cases follows. The first line of each test case contains two integers \(n\) and \(m\) (\(3 \le n \le 12\), \(1 \le m \le 2000\)) β€” the number of airports and the number of days of the experiment.The second line of each test case contains \(n\) integers \(s_1, s_2, \ldots, s_n\) (\(0 \le s_i \le 10^8\)) β€” the initial number of lost pieces of luggage in each airport.Next, the descriptions for each of the \(m\) days follow in order.The first line of the description of the \(i\)-th day contains \(n\) integers \(a_{i,1}, a_{i,2}, \ldots, a_{i,n}\) (\(0 \le a_{i, j} \le 10^8\)) β€” the maximum number of lost pieces of luggage that can be transported to the previous airport for each airport.The second line of the description of the \(i\)-th day contains \(n\) integers \(b_{i,1}, \ldots, b_{i,n}\) (\(0 \le b_{i, j} \le 10^8\)) β€” the minimum number of lost pieces of luggage that will be found on the \(i\)-th day in each airport.The third line of the description of the \(i\)-th day contains \(n\) integers \(c_{i,1}, \ldots, c_{i,n}\) (\(0 \le c_{i, j} \le 10^8\)) β€” the maximum number of lost pieces of luggage that can be transported to the next airport for each airport.It is guaranteed that the sum of \(m\) over all test cases does not exceed \(2000\).
For each test case, output \(m\) integers β€” the maximum number of unfound pieces of luggage for each number of days from \(1\) to \(m\).
In the first test case: On the first day, all \(5\) pieces of luggage may not be found, as the lost luggage can be sent on flights from each airport. In the morning of the second day, there may be no more than \(3\) pieces of luggage in the \(2\)-nd airport, no more than \(2\) pieces in the \(5\)-th airport, and no luggage in the other airports. All luggage from the \(5\)-th airport may remain there. In the \(2\)-nd airport, no more than \(2\) pieces of luggage can be sent on flights to neighboring airports. Thus, at least \(1\) piece of luggage will be found. By the end of the third day, lost luggage may only be in the \(1\)-st and \(2\)-nd airports. There can be no more than one piece in each, meaning that at most \(2\) pieces of luggage will remain unfound in total. The found luggage is marked in green. In the second test case, all pieces of luggage may remain in their original airports, and the inspection won't find any lost suitcases. Therefore, the answer is \(10^9 + 5\).
Input: 25 31 1 1 1 10 0 1 0 00 1 0 0 11 0 0 1 00 1 0 0 09 0 9 9 90 1 0 0 00 0 0 0 09 0 9 0 00 0 0 0 03 10 100000000 50 100000000 50 100000000 50 100000000 5 | Output: 5 4 2 100000005
Master
2
1,758
1,406
136
20
1,276
E
1276E
E. Four Stones
3,500
constructive algorithms
There are four stones on an infinite line in integer coordinates \(a_1, a_2, a_3, a_4\). The goal is to have the stones in coordinates \(b_1, b_2, b_3, b_4\). The order of the stones does not matter, that is, a stone from any position \(a_i\) can end up in at any position \(b_j\), provided there is a required number of stones in each position (that is, if a coordinate \(x\) appears \(k\) times among numbers \(b_1, \ldots, b_4\), there should be exactly \(k\) stones at \(x\) in the end).We are allowed to move stones with the following operation: choose two stones at distinct positions \(x\) and \(y\) with at least one stone each, and move one stone from \(x\) to \(2y - x\). In other words, the operation moves a stone to a symmetric position relative to some other stone. At any moment it is allowed to have any number of stones at the same position.Find any sequence of operations that achieves the goal, or determine that it is impossible. The sequence does not have to be shortest, but it may contain at most \(1000\) operations.
The first line contains four integers \(a_1, \ldots, a_4\) (\(-10^9 \leq a_i \leq 10^9\)) β€” initial coordinates of the stones. There may be multiple stones sharing the same coordinate.The second line contains four integers \(b_1, \ldots, b_4\) (\(-10^9 \leq b_i \leq 10^9\)) β€” target coordinates of the stones. There may be multiple targets sharing the same coordinate.
If there is no sequence of operations that achieves the goal, print a single integer \(-1\). Otherwise, on the first line print a single integer \(k\) (\(0 \leq k \leq 1000\)) β€” the number of operations in your sequence. On the next \(k\) lines, describe the operations. The \(i\)-th of these lines should contain two integers \(x_i\) and \(y_i\) (\(x_i \neq y_i\)) β€” coordinates of the moved stone and the center of symmetry stone for the \(i\)-th operation.For each operation \(i\), there should at least one stone in each of the coordinates \(x_i\) and \(y_i\), and the resulting coordinate \(2y_i - x_i\) must not exceed \(10^{18}\) by absolute value.If there are multiple suitable sequences, print any of them. It is guaranteed that if there is a suitable sequence of operations, then there is also a suitable sequence that satisfies all the additional requirement.
Input: 0 1 2 3 3 5 6 8 | Output: 3 1 3 2 5 0 3
Master
1
1,040
369
870
12
2,037
F
2037F
F. Ardent Flames
2,100
binary search; data structures; math; sortings; two pointers
You have obtained the new limited event character Xilonen. You decide to use her in combat.There are \(n\) enemies in a line. The \(i\)'th enemy from the left has health \(h_i\) and is currently at position \(x_i\). Xilonen has an attack damage of \(m\), and you are ready to defeat the enemies with her.Xilonen has a powerful ""ground stomp"" attack. Before you perform any attacks, you select an integer \(p\) and position Xilonen there (\(p\) can be any integer position, including a position with an enemy currently). Afterwards, for each attack, she deals \(m\) damage to an enemy at position \(p\) (if there are any), \(m-1\) damage to enemies at positions \(p-1\) and \(p+1\), \(m-2\) damage to enemies at positions \(p-2\) and \(p+2\), and so on. Enemies that are at least a distance of \(m\) away from Xilonen take no damage from attacks.Formally, if there is an enemy at position \(x\), she will deal \(\max(0,m - |p - x|)\) damage to that enemy each hit. Note that you may not choose a different \(p\) for different attacks. Over all possible \(p\), output the minimum number of attacks Xilonen must perform to defeat at least \(k\) enemies. If it is impossible to find a \(p\) such that eventually at least \(k\) enemies will be defeated, output \(-1\) instead. Note that an enemy is considered to be defeated if its health reaches \(0\) or below.
The first line contains an integer \(t\) (\(1 \leq t \leq 10^4\)) – the number of test cases.The first line of each test case contains three integers \(n\), \(m\), and \(k\) (\(1 \leq k \leq n \leq 10^5\), \(1 \leq m \leq 10^9\)).The following line contains \(n\) integers \(h_1, h_2, ..., h_n\) (\(1 \leq h_i \leq 10^9\)).The last line of each testcase contains \(n\) integers \(x_1, x_2, ..., x_n\) (\(1\leq x_i \leq 10^9\), \(x_i < x_{i+1}\) for all \(1 \leq i < n\))It is guaranteed that the sum of \(n\) over all test cases does not exceed \(10^5\).
For each test case, output an integer on a new line, the minimum number of attacks that must be performed to defeat at least \(k\) enemies. If it is impossible to find a \(p\) such that eventually at least \(k\) enemies will be defeated, output \(-1\) instead.
In the first testcase, it is optimal to select \(p=2\). Each attack, the first enemy takes \(5-|2-1|=4\) damage, the second enemy takes \(5\) damage, the third enemy takes \(4\) damage, the fourth enemy takes \(3\) damage, and the fifth enemy takes \(2\) damage. After \(2\) attacks, the first three enemies will be defeated. It can be shown that it is impossible to defeat \(3\) enemies in less than \(2\) attacks, no matter which \(p\) is selected.In the second testcase, we must kill all \(9\) enemies. By selecting \(p=5\), all nine enemies will be defeated in \(2\) attacks.In the third testcase, we must kill both enemies. However, it can be shown that no \(p\) selected will damage both enemies at the same time, so the answer is \(-1\).In the fourth testcase, selecting \(p=1\) will enable us to defeat the first enemy in \(6969697\) attacks.In the fifth testcase, selecting \(p=10\) will make each enemy take \(1\) damage per attack. Both enemies will be defeated in \(15\) attacks.
Input: 65 5 37 7 7 7 71 2 3 4 59 5 92 4 6 8 10 8 6 4 21 2 3 4 5 6 7 8 92 10 21 11 202 10 169696969 4204204201 202 10 210 151 192 2 21000000000 11 3 | Output: 2 2 -1 6969697 15 1000000000
Hard
5
1,359
554
260
20
1,965
E
1965E
E. Connected Cubes
3,100
constructive algorithms; games
There are \(n \cdot m\) unit cubes currently in positions \((1, 1, 1)\) through \((n, m, 1)\). Each of these cubes is one of \(k\) colors. You want to add additional cubes at any integer coordinates such that the subset of cubes of each color is connected, where two cubes are considered connected if they share a face.In other words, for every pair of cubes of the same color \(c\), it should be possible to travel from one to the other, moving only through cubes of color \(c\) that share a face.The existing cubes are currently in the corner of a room. There are colorless cubes completely filling the planes \(x = 0\), \(y = 0\), and \(z = 0\), preventing you from placing additional cubes there or at any negative coordinates. Find a solution that uses at most \(4 \cdot 10^5\) additional cubes (not including the cubes that are currently present), or determine that there is no solution. It can be shown that under the given constraints, if there is a solution, there is one using at most \(4 \cdot 10^5\) additional cubes.
The first line of the input contains three integers \(n\), \(m\), and \(k\) (\(2 \le n, m, k \le 50\)) β€” the number of rows and columns of cubes, and the number of colors, respectively.The \(i\)-th of the next \(n\) lines contains \(m\) integers. The \(j\)-th of these is \(a_{ij}\) (\(1 \le a_{ij} \le k\)) β€” the color of the cube at position \((i, j, 1)\). For every color from \(1\) to \(k\), it is guaranteed that there is at least one cube in the input of that color.
If there is no solution, print a single integer \(-1\).Otherwise, the first line of output should contain a single integer \(p\) (\(0 \le p \le 4 \cdot 10^5\)) β€” the number of additional cubes you will add.The next \(p\) lines should contain four integers \(x\), \(y\), \(z\) and \(c\) (\(1 \le x, y, z \le 10^6\), \(1 \le c \le k\)) β€” indicating that you are adding a cube with color \(c\) at position \((x, y, z)\).No two cubes in the output should have the same coordinates, and no cube in the output should have the same coordinates as any cube in the input.If there are multiple solutions, print any.
The image in the statement corresponds to the first example case, with \(\text{red} = 1\), \(\text{blue} = 2\), \(\text{green} = 3\).
Input: 3 4 33 2 3 11 1 1 11 3 3 2 | Output: 13 1 1 2 3 1 3 2 3 2 1 2 3 2 2 2 3 2 3 2 3 3 3 2 3 1 2 2 2 1 2 3 2 1 3 3 2 1 4 3 2 2 4 3 2 3 4 3 2 3 4 2 2
Master
2
1,029
472
605
19
73
C
73C
C. LionAge II
1,800
dp
Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character.
The first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters, - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data.
Output the only number β€” maximum possible euphony ΠΎf the new character's name.
In the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36.
Input: winner 44s e 7o s 8l o 13o o 8 | Output: 36
Medium
1
712
482
78
0
661
H
661H
H. Rotate Matrix
2,400
*special
You are given a square matrix of integer numbers. Rotate it 90 degrees clockwise (see examples for clarification of rotation).
The input consists of n lines (1 ≀ n ≀ 10, n is not given explicitly). Each of the lines contains n space-separated integers; j-th integer in i-th line corresponds to matrix element mij (1 ≀ mij ≀ 100).
Output the rotated matrix in the same format as the input.
Input: 1 2 34 5 67 8 9 | Output: 7 4 18 5 29 6 3
Expert
1
126
202
58
6
171
B
171B
B. Star
1,300
*special; combinatorics
The input contains a single integer a (1 ≀ a ≀ 18257).
Print a single integer output (1 ≀ output ≀ 2Β·109).
Input: 2 | Output: 13
Easy
2
0
54
51
1
613
C
613C
C. Necklace
2,500
constructive algorithms; math
Ivan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). Ivan has beads of n colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.
The first line of the input contains a single number n (1 ≀ n ≀ 26) β€” the number of colors of beads. The second line contains after n positive integers ai β€” the quantity of beads of i-th color. It is guaranteed that the sum of ai is at least 2 and does not exceed 100 000.
In the first line print a single number β€” the maximum number of beautiful cuts that a necklace composed from given beads may have. In the second line print any example of such necklace.Each color of the beads should be represented by the corresponding lowercase English letter (starting with a). As the necklace is cyclic, print it starting from any point.
In the first sample a necklace can have at most one beautiful cut. The example of such a necklace is shown on the picture.In the second sample there is only one way to compose a necklace.
Input: 34 2 1 | Output: 1abacaba
Expert
2
525
272
356
6
1,512
G
1512G
G. Short Task
1,700
brute force; dp; math; number theory
Let us denote by \(d(n)\) the sum of all divisors of the number \(n\), i.e. \(d(n) = \sum\limits_{k | n} k\).For example, \(d(1) = 1\), \(d(4) = 1+2+4=7\), \(d(6) = 1+2+3+6=12\).For a given number \(c\), find the minimum \(n\) such that \(d(n) = c\).
The first line contains one integer \(t\) (\(1 \le t \le 10^4\)). Then \(t\) test cases follow.Each test case is characterized by one integer \(c\) (\(1 \le c \le 10^7\)).
For each test case, output: ""-1"" if there is no such \(n\) that \(d(n) = c\); \(n\), otherwise.
Input: 12 1 2 3 4 5 6 7 8 9 10 39 691 | Output: 1 -1 2 3 -1 5 4 7 -1 -1 18 -1
Medium
4
250
171
97
15