problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
⌀ | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
C. Sasha and a Patient Friendtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya and Sasha are friends, that's why Sasha knows everything about Fedya.Fedya keeps his patience in an infinitely large bowl. But, unlike the bowl, Fedya's patience isn't infinite, that is why let v be the number of liters of Fedya's patience, and, as soon as v becomes equal to 0, the bowl will burst immediately. There is one tap in the bowl which pumps s liters of patience per second. Notice that s can be negative, in that case, the tap pumps out the patience. Sasha can do different things, so he is able to change the tap's speed. All actions that Sasha does can be represented as q queries. There are three types of queries: "1 t s" — add a new event, means that starting from the t-th second the tap's speed will be equal to s. "2 t" — delete the event which happens at the t-th second. It is guaranteed that such event exists. "3 l r v" — Sasha wonders: if you take all the events for which l \le t \le r and simulate changes of Fedya's patience from the very beginning of the l-th second till the very beginning of the r-th second inclusive (the initial volume of patience, at the beginning of the l-th second, equals to v liters) then when will be the moment when the bowl will burst. If that does not happen, then the answer will be -1. Since Sasha does not want to check what will happen when Fedya's patience ends, and he has already come up with the queries, he is asking you to help him and find the answer for each query of the 3-rd type.It is guaranteed that at any moment of time, there won't be two events which happen at the same second.InputThe first line contans one integer q (1 \le q \le 10^5) — the number of queries.Each of the next q lines have one of the following formats: 1 t s (1 \le t \le 10^9, -10^9 \le s \le 10^9), means that a new event is added, which means that starting from the t-th second the tap's speed will be equal to s. 2 t (1 \le t \le 10^9), means that the event which happens at the t-th second must be deleted. Guaranteed that such exists. 3 l r v (1 \le l \le r \le 10^9, 0 \le v \le 10^9), means that you should simulate the process from the very beginning of the l-th second till the very beginning of the r-th second inclusive, and to say when will the bowl burst. It is guaranteed that t, s, l, r, v in all the queries are integers.Also, it is guaranteed that there is at least one query of the 3-rd type, and there won't be a query of the 1-st type with such t, that there already exists an event which happens at that second t.OutputFor each query of the 3-rd type, print in a new line the moment when the bowl will burst or print -1 if it won't happen.Your answer will be considered correct if it's absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}.ExamplesInput
6
1 2 1
1 4 -3
3 1 6 1
3 1 6 3
3 1 6 4
3 1 6 5
Output
5
5.666667
6
-1
Input
10
1 2 2
1 4 4
1 7 -10
3 2 4 1
3 5 6 0
3 1 15 1
2 4
3 1 15 1
1 8 1
3 1 15 1
Output
-1
5
8.7
8.1
-1
Input
5
1 1000 9999999
1 2000 -9999
3 1000 2000 0
2 1000
3 1000 2002 1
Output
1000
2000.0001
NoteIn the first example all the queries of the 3-rd type cover all the events, it's simulation is following: | 6
1 2 1
1 4 -3
3 1 6 1
3 1 6 3
3 1 6 4
3 1 6 5
| 5 5.666667 6 -1 | 1.5 seconds | 256 megabytes | ['binary search', 'data structures', 'implementation', '*2800'] |
B. Sasha and One More Nametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times k, so they got k+1 pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using 3 cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome s find such minimum k, that you can cut this string into k + 1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. It there is no answer, then print "Impossible" (without quotes).InputThe first line contains one string s (1 \le |s| \le 5\,000) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that s is a palindrome.OutputPrint one integer k — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).ExamplesInput
nolon
Output
2
Input
otto
Output
1
Input
qqqq
Output
Impossible
Input
kinnikkinnik
Output
1
NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin. | nolon
| 2 | 1 second | 256 megabytes | ['constructive algorithms', 'hashing', 'strings', '*1800'] |
A. Sasha and a Bit of Relaxtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful.Therefore, Sasha decided to upsolve the following problem:You have an array a with n integers. You need to count the number of funny pairs (l, r) (l \leq r). To check if a pair (l, r) is a funny pair, take mid = \frac{l + r - 1}{2}, then if r - l + 1 is an even number and a_l \oplus a_{l+1} \oplus \ldots \oplus a_{mid} = a_{mid + 1} \oplus a_{mid + 2} \oplus \ldots \oplus a_r, then the pair is funny. In other words, \oplus of elements of the left half of the subarray from l to r should be equal to \oplus of elements of the right half. Note that \oplus denotes the bitwise XOR operation.It is time to continue solving the contest, so Sasha asked you to solve this task.InputThe first line contains one integer n (2 \le n \le 3 \cdot 10^5) — the size of the array.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i < 2^{20}) — array itself.OutputPrint one integer — the number of funny pairs. You should consider only pairs where r - l + 1 is even number.ExamplesInput51 2 3 4 5Output1Input63 2 2 3 7 6Output3Input342 4 2Output0NoteBe as cool as Sasha, upsolve problems!In the first example, the only funny pair is (2, 5), as 2 \oplus 3 = 4 \oplus 5 = 1.In the second example, funny pairs are (2, 3), (1, 4), and (3, 6).In the third example, there are no funny pairs. | Input51 2 3 4 5 | Output1 | 1 second | 256 megabytes | ['dp', 'implementation', '*1600'] |
F. MST Unificationtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected weighted connected graph with n vertices and m edges without loops and multiple edges.The i-th edge is e_i = (u_i, v_i, w_i); the distance between vertices u_i and v_i along the edge e_i is w_i (1 \le w_i). The graph is connected, i. e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.A minimum spanning tree (MST) in case of positive weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by 1. You can increase the weight of each edge multiple (possibly, zero) times.Suppose that the initial MST cost is k. Your problem is to increase weights of some edges with minimum possible number of operations in such a way that the cost of MST in the obtained graph remains k, but MST is unique (it means that there is only one way to choose MST in the obtained graph).Your problem is to calculate the minimum number of operations required to do it.InputThe first line of the input contains two integers n and m (1 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5) — the number of vertices and the number of edges in the initial graph.The next m lines contain three integers each. The i-th line contains the description of the i-th edge e_i. It is denoted by three integers u_i, v_i and w_i (1 \le u_i, v_i \le n, u_i \ne v_i, 1 \le w \le 10^9), where u_i and v_i are vertices connected by the i-th edge and w_i is the weight of this edge.It is guaranteed that the given graph doesn't contain loops and multiple edges (i.e. for each i from 1 to m u_i \ne v_i and for each unordered pair of vertices (u, v) there is at most one edge connecting this pair of vertices). It is also guaranteed that the given graph is connected.OutputPrint one integer — the minimum number of operations to unify MST of the initial graph without changing the cost of MST.ExamplesInput
8 10
1 2 1
2 3 2
2 4 5
1 4 2
6 3 3
6 1 3
3 5 2
3 7 1
4 8 1
6 2 4
Output
1
Input
4 3
2 1 3
4 3 4
2 4 1
Output
0
Input
3 3
1 2 1
2 3 2
1 3 3
Output
0
Input
3 3
1 2 1
2 3 3
1 3 3
Output
1
Input
1 0
Output
0
Input
5 6
1 2 2
2 3 1
4 5 3
2 4 2
1 4 2
1 5 3
Output
2
NoteThe picture corresponding to the first example: You can, for example, increase weight of the edge (1, 6) or (6, 3) by 1 to unify MST.The picture corresponding to the last example: You can, for example, increase weights of edges (1, 5) and (2, 4) by 1 to unify MST. | 8 10
1 2 1
2 3 2
2 4 5
1 4 2
6 3 3
6 1 3
3 5 2
3 7 1
4 8 1
6 2 4
| 1 | 3 seconds | 256 megabytes | ['binary search', 'dsu', 'graphs', 'greedy', '*2100'] |
E2. Array and Segments (Hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is a number of elements in the array.You are given an array a consisting of n integers. The value of the i-th element of the array is a_i.You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 \le l_j \le r_j \le n.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0].You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value \max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains two integers n and m (1 \le n \le 10^5, 0 \le m \le 300) — the length of the array a and the number of segments, respectively.The second line of the input contains n integers a_1, a_2, \dots, a_n (-10^6 \le a_i \le 10^6), where a_i is the value of the i-th element of the array a.The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 \le l_j \le r_j \le n), where l_j and r_j are the ends of the j-th segment.OutputIn the first line of the output print one integer d — the maximum possible value \max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a.In the second line of the output print one integer q (0 \le q \le m) — the number of segments you apply.In the third line print q distinct integers c_1, c_2, \dots, c_q in any order (1 \le c_k \le m) — indices of segments you apply to the array a in such a way that the value \max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i of the obtained array b is maximum possible.If there are multiple answers, you can print any.ExamplesInput
5 4
2 -2 3 1 2
1 3
4 5
2 5
1 3
Output
6
2
4 1
Input
5 4
2 -2 3 1 4
3 5
3 4
2 4
2 5
Output
7
2
3 2
Input
1 0
1000000
Output
0
0
NoteIn the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6.In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7.In the third example you cannot do anything so the answer is 0. | 5 4
2 -2 3 1 2
1 3
4 5
2 5
1 3
| 6 2 4 1 | 2 seconds | 256 megabytes | ['data structures', 'implementation', '*2100'] |
E1. Array and Segments (Easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is a number of elements in the array.You are given an array a consisting of n integers. The value of the i-th element of the array is a_i.You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 \le l_j \le r_j \le n.You can choose some subset of the given set of segments and decrease values on each of the chosen segments by one (independently). For example, if the initial array a = [0, 0, 0, 0, 0] and the given segments are [1; 3] and [2; 4] then you can choose both of them and the array will become b = [-1, -2, -2, -1, 0].You have to choose some subset of the given segments (each segment can be chosen at most once) in such a way that if you apply this subset of segments to the array a and obtain the array b then the value \max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i will be maximum possible.Note that you can choose the empty set.If there are multiple answers, you can print any.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains two integers n and m (1 \le n \le 300, 0 \le m \le 300) — the length of the array a and the number of segments, respectively.The second line of the input contains n integers a_1, a_2, \dots, a_n (-10^6 \le a_i \le 10^6), where a_i is the value of the i-th element of the array a.The next m lines are contain two integers each. The j-th of them contains two integers l_j and r_j (1 \le l_j \le r_j \le n), where l_j and r_j are the ends of the j-th segment.OutputIn the first line of the output print one integer d — the maximum possible value \max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i if b is the array obtained by applying some subset of the given segments to the array a.In the second line of the output print one integer q (0 \le q \le m) — the number of segments you apply.In the third line print q distinct integers c_1, c_2, \dots, c_q in any order (1 \le c_k \le m) — indices of segments you apply to the array a in such a way that the value \max\limits_{i=1}^{n}b_i - \min\limits_{i=1}^{n}b_i of the obtained array b is maximum possible.If there are multiple answers, you can print any.ExamplesInput
5 4
2 -2 3 1 2
1 3
4 5
2 5
1 3
Output
6
2
1 4
Input
5 4
2 -2 3 1 4
3 5
3 4
2 4
2 5
Output
7
2
3 2
Input
1 0
1000000
Output
0
0
NoteIn the first example the obtained array b will be [0, -4, 1, 1, 2] so the answer is 6.In the second example the obtained array b will be [2, -3, 1, -1, 4] so the answer is 7.In the third example you cannot do anything so the answer is 0. | 5 4
2 -2 3 1 2
1 3
4 5
2 5
1 3
| 6 2 1 4 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'implementation', '*1800'] |
D. Diverse Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is 1) have distinct colors.In other words, if the obtained garland is t then for each i from 1 to n-1 the condition t_i \ne t_{i + 1} should be satisfied.Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of lamps.The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' — colors of lamps in the garland.OutputIn the first line of the output print one integer r — the minimum number of recolors needed to obtain a diverse garland from the given one.In the second line of the output print one string t of length n — a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.ExamplesInput
9
RBGRRBRGG
Output
2
RBGRGBRGR
Input
8
BBBGBRRR
Output
2
BRBGBRGR
Input
13
BBRRRRGGGGGRR
Output
6
BGRBRBGBGBGRG
| 9
RBGRRBRGG
| 2 RBGRGBRGR | 1 second | 256 megabytes | ['constructive algorithms', 'dp', 'greedy', '*1400'] |
C. Nice Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is t, then for each i, j such that t_i = t_j should be satisfied |i-j|~ mod~ 3 = 0. The value |x| means absolute value of x, the operation x~ mod~ y means remainder of x when divided by y.For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of lamps.The second line of the input contains the string s consisting of n characters 'R', 'G' and 'B' — colors of lamps in the garland.OutputIn the first line of the output print one integer r — the minimum number of recolors needed to obtain a nice garland from the given one.In the second line of the output print one string t of length n — a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.ExamplesInput
3
BRB
Output
1
GRB
Input
7
RGBGRBB
Output
3
RGBRGBR
| 3
BRB
| 1 GRB | 1 second | 256 megabytes | ['brute force', 'greedy', 'math', '*1300'] |
B. Divisors of Two Integerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list.For example, if x=4 and y=6 then the given list can be any permutation of the list [1, 2, 4, 1, 2, 3, 6]. Some of the possible lists are: [1, 1, 2, 4, 6, 3, 2], [4, 6, 1, 1, 2, 3, 2] or [1, 6, 3, 2, 4, 1, 2].Your problem is to restore suitable positive integer numbers x and y that would yield the same list of divisors (possibly in different order).It is guaranteed that the answer exists, i.e. the given list of divisors corresponds to some positive integers x and y.InputThe first line contains one integer n (2 \le n \le 128) — the number of divisors of x and y.The second line of the input contains n integers d_1, d_2, \dots, d_n (1 \le d_i \le 10^4), where d_i is either divisor of x or divisor of y. If a number is divisor of both numbers x and y then there are two copies of this number in the list.OutputPrint two positive integer numbers x and y — such numbers that merged list of their divisors is the permutation of the given list of integers. It is guaranteed that the answer exists.ExampleInput
10
10 2 8 1 2 4 1 20 4 5
Output
20 8
| 10
10 2 8 1 2 4 1 20 4 5
| 20 8 | 1 second | 256 megabytes | ['brute force', 'greedy', 'math', 'number theory', '*1100'] |
A. Two distinct pointstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other. The example of two segments on the x-axis. Your problem is to find two integers a and b such that l_1 \le a \le r_1, l_2 \le b \le r_2 and a \ne b. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment [l_1; r_1] and the second one belongs to the segment [l_2; r_2].It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.You have to answer q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 500) — the number of queries.Each of the next q lines contains four integers l_{1_i}, r_{1_i}, l_{2_i} and r_{2_i} (1 \le l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} \le 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}) — the ends of the segments in the i-th query.OutputPrint 2q integers. For the i-th query print two integers a_i and b_i — such numbers that l_{1_i} \le a_i \le r_{1_i}, l_{2_i} \le b_i \le r_{2_i} and a_i \ne b_i. Queries are numbered in order of the input.It is guaranteed that the answer exists. If there are multiple answers, you can print any.ExampleInput
5
1 2 1 2
2 6 3 4
2 4 1 3
1 2 1 3
1 4 5 8
Output
2 1
3 4
3 2
1 2
3 7
| 5
1 2 1 2
2 6 3 4
2 4 1 3
1 2 1 3
1 4 5 8
| 2 1 3 4 3 2 1 2 3 7 | 1 second | 256 megabytes | ['implementation', '*800'] |
G. Vasya and Maximum Profittime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit.Vasya has n problems to choose from. They are numbered from 1 to n. The difficulty of the i-th problem is d_i. Moreover, the problems are given in the increasing order by their difficulties. The difficulties of all tasks are pairwise distinct. In order to add the i-th problem to the contest you need to pay c_i burles to its author. For each problem in the contest Vasya gets a burles.In order to create a contest he needs to choose a consecutive subsegment of tasks.So the total earnings for the contest are calculated as follows: if Vasya takes problem i to the contest, he needs to pay c_i to its author; for each problem in the contest Vasya gets a burles; let gap(l, r) = \max\limits_{l \le i < r} (d_{i + 1} - d_i)^2. If Vasya takes all the tasks with indices from l to r to the contest, he also needs to pay gap(l, r). If l = r then gap(l, r) = 0. Calculate the maximum profit that Vasya can earn by taking a consecutive segment of tasks.InputThe first line contains two integers n and a (1 \le n \le 3 \cdot 10^5, 1 \le a \le 10^9) — the number of proposed tasks and the profit for a single problem, respectively.Each of the next n lines contains two integers d_i and c_i (1 \le d_i, c_i \le 10^9, d_i < d_{i+1}).OutputPrint one integer — maximum amount of burles Vasya can earn.ExamplesInput
5 10
1 15
5 3
6 11
7 2
11 22
Output
13
Input
3 5
1 8
2 19
3 11
Output
0
| 5 10
1 15
5 3
6 11
7 2
11 22
| 13 | 3.5 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'data structures', 'dp', 'dsu', '*2400'] |
F. Vasya and Endless Creditstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya wants to buy himself a nice new car. Unfortunately, he lacks some money. Currently he has exactly 0 burles.However, the local bank has n credit offers. Each offer can be described with three numbers a_i, b_i and k_i. Offers are numbered from 1 to n. If Vasya takes the i-th offer, then the bank gives him a_i burles at the beginning of the month and then Vasya pays bank b_i burles at the end of each month for the next k_i months (including the month he activated the offer). Vasya can take the offers any order he wants.Each month Vasya can take no more than one credit offer. Also each credit offer can not be used more than once. Several credits can be active at the same time. It implies that Vasya pays bank the sum of b_i over all the i of active credits at the end of each month.Vasya wants to buy a car in the middle of some month. He just takes all the money he currently has and buys the car of that exact price.Vasya don't really care what he'll have to pay the bank back after he buys a car. He just goes out of the country on his car so that the bank can't find him anymore.What is the maximum price that car can have?InputThe first line contains one integer n (1 \le n \le 500) — the number of credit offers.Each of the next n lines contains three integers a_i, b_i and k_i (1 \le a_i, b_i, k_i \le 10^9).OutputPrint one integer — the maximum price of the car.ExamplesInput
4
10 9 2
20 33 1
30 115 1
5 3 2
Output
32
Input
3
40 1 2
1000 1100 5
300 2 1
Output
1337
NoteIn the first example, the following sequence of offers taken is optimal: 4 \rightarrow 3.The amount of burles Vasya has changes the following way: 5 \rightarrow 32 \rightarrow -86 \rightarrow .... He takes the money he has in the middle of the second month (32 burles) and buys the car.The negative amount of money means that Vasya has to pay the bank that amount of burles.In the second example, the following sequence of offers taken is optimal: 3 \rightarrow 1 \rightarrow 2.The amount of burles Vasya has changes the following way: 0 \rightarrow 300 \rightarrow 338 \rightarrow 1337 \rightarrow 236 \rightarrow -866 \rightarrow .... | 4
10 9 2
20 33 1
30 115 1
5 3 2
| 32 | 3 seconds | 256 megabytes | ['dp', 'flows', 'graph matchings', 'graphs', 'sortings', '*2600'] |
E. Vasya and Binary Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string s of length n consisting only of digits 0 and 1. Also he has an array a of length n. Vasya performs the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue together the remaining parts (any of them can be empty). For example, if he erases substring 111 from string 111110 he will get the string 110. Vasya gets a_x points for erasing substring of length x.Vasya wants to maximize his total points, so help him with this! InputThe first line contains one integer n (1 \le n \le 100) — the length of string s.The second line contains string s, consisting only of digits 0 and 1.The third line contains n integers a_1, a_2, \dots a_n (1 \le a_i \le 10^9), where a_i is the number of points for erasing the substring of length i.OutputPrint one integer — the maximum total points Vasya can get.ExamplesInput
7
1101001
3 4 9 100 1 2 3
Output
109
Input
5
10101
3 10 15 15 15
Output
23
NoteIn the first example the optimal sequence of erasings is: 1101001 \rightarrow 111001 \rightarrow 11101 \rightarrow 1111 \rightarrow \varnothing.In the second example the optimal sequence of erasings is: 10101 \rightarrow 1001 \rightarrow 11 \rightarrow \varnothing. | 7
1101001
3 4 9 100 1 2 3
| 109 | 2 seconds | 256 megabytes | ['dp', '*2400'] |
D. Compressiontime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary matrix A of size n \times n. Let's denote an x-compression of the given matrix as a matrix B of size \frac{n}{x} \times \frac{n}{x} such that for every i \in [1, n], j \in [1, n] the condition A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil] is met.Obviously, x-compression is possible only if x divides n, but this condition is not enough. For example, the following matrix of size 2 \times 2 does not have any 2-compression: 01 10 For the given matrix A, find maximum x such that an x-compression of this matrix is possible.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.InputThe first line contains one number n (4 \le n \le 5200) — the number of rows and columns in the matrix A. It is guaranteed that n is divisible by 4.Then the representation of matrix follows. Each of n next lines contains \frac{n}{4} one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from 0 to 9 or as uppercase Latin letters from A to F). Binary representation of each of these numbers denotes next 4 elements of the matrix in the corresponding row. For example, if the number B is given, then the corresponding elements are 1011, and if the number is 5, then the corresponding elements are 0101.Elements are not separated by whitespaces.OutputPrint one number: maximum x such that an x-compression of the given matrix is possible.ExamplesInput
8
E7
E7
E7
00
00
E7
E7
E7
Output
1
Input
4
7
F
F
F
Output
1
NoteThe first example corresponds to the matrix: 11100111 11100111 11100111 00000000 00000000 11100111 11100111 11100111 It is easy to see that the answer on this example is 1. | 8
E7
E7
E7
00
00
E7
E7
E7
| 1 | 2.5 seconds | 256 megabytes | ['dp', 'implementation', 'math', 'number theory', '*1800'] |
C. Brutalitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.You are given a sequence of hits, the i-th hit deals a_i units of damage to the opponent's character. To perform the i-th hit you have to press the button s_i on your gamepad. Hits are numbered from 1 to n.You know that if you press some button more than k times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of a_i over all i for the hits which weren't skipped.Note that if you skip the hit then the counter of consecutive presses the button won't reset.Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5) — the number of hits and the maximum number of times you can push the same button in a row.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the damage of the i-th hit.The third line of the input contains the string s consisting of exactly n lowercase Latin letters — the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).OutputPrint one integer dmg — the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.ExamplesInput
7 3
1 5 16 18 7 2 10
baaaaca
Output
54
Input
5 5
2 4 1 3 1000
aaaaa
Output
1010
Input
5 4
2 4 1 3 1000
aaaaa
Output
1009
Input
8 1
10 15 2 1 4 8 15 16
qqwweerr
Output
41
Input
6 3
14 18 9 19 2 15
cccccc
Output
52
Input
2 1
10 10
qq
Output
10
NoteIn the first example you can choose hits with numbers [1, 3, 4, 5, 6, 7] with the total damage 1 + 16 + 18 + 7 + 2 + 10 = 54.In the second example you can choose all hits so the total damage is 2 + 4 + 1 + 3 + 1000 = 1010.In the third example you can choose all hits expect the third one so the total damage is 2 + 4 + 3 + 1000 = 1009.In the fourth example you can choose hits with numbers [2, 3, 6, 8]. Only this way you can reach the maximum total damage 15 + 2 + 8 + 16 = 41.In the fifth example you can choose only hits with numbers [2, 4, 6] with the total damage 18 + 19 + 15 = 52.In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage 10. | 7 3
1 5 16 18 7 2 10
baaaaca
| 54 | 1 second | 256 megabytes | ['greedy', 'sortings', 'two pointers', '*1300'] |
B. Digital roottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday at the lesson of mathematics, Petya learns about the digital root.The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. Let's denote the digital root of x as S(x). Then S(5)=5, S(38)=S(3+8=11)=S(1+1=2)=2, S(10)=S(1+0=1)=1.As a homework Petya got n tasks of the form: find k-th positive number whose digital root is x.Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all n tasks from Petya's homework.InputThe first line contains a single integer n (1 \le n \le 10^3) — the number of tasks in Petya's homework. The next n lines contain two integers k_i (1 \le k_i \le 10^{12}) and x_i (1 \le x_i \le 9) — i-th Petya's task in which you need to find a k_i-th positive number, the digital root of which is x_i.OutputOutput n lines, i-th line should contain a single integer — the answer to the i-th problem.ExampleInput
3
1 5
5 2
3 1
Output
5
38
19
| 3
1 5
5 2
3 1
| 5 38 19 | 1 second | 256 megabytes | ['math', 'number theory', '*1000'] |
A. Digits Sequence Dividingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence s consisting of n digits from 1 to 9.You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is t_1, t_2, \dots, t_k, where k is the number of element in a division, then for each i from 1 to k-1 the condition t_{i} < t_{i + 1} (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if s=654 then you can divide it into parts [6, 54] and it will be suitable division. But if you will divide it into parts [65, 4] then it will be bad division because 65 > 4. If s=123 then you can divide it into parts [1, 23], [1, 2, 3] but not into parts [12, 3].Your task is to find any suitable division for each of the q independent queries.InputThe first line of the input contains one integer q (1 \le q \le 300) — the number of queries.The first line of the i-th query contains one integer number n_i (2 \le n_i \le 300) — the number of digits in the i-th query.The second line of the i-th query contains one string s_i of length n_i consisting only of digits from 1 to 9.OutputIf the sequence of digits in the i-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query.Otherwise in the first line of the answer to this query print "YES", on the second line print k_i — the number of parts in your division of the i-th query sequence and in the third line print k_i strings t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i} — your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string s_i.See examples for better understanding.ExampleInput
4
6
654321
4
1337
2
33
4
2122
Output
YES
3
6 54 321
YES
3
1 3 37
NO
YES
2
21 22
| 4
6
654321
4
1337
2
33
4
2122
| YES 3 6 54 321 YES 3 1 3 37 NO YES 2 21 22 | 1 second | 256 megabytes | ['greedy', 'strings', '*900'] |
F. Lunar New Year and a Recursive Sequencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLunar New Year is approaching, and Bob received a gift from his friend recently — a recursive sequence! He loves this sequence very much and wants to play with it.Let f_1, f_2, \ldots, f_i, \ldots be an infinite sequence of positive integers. Bob knows that for i > k, f_i can be obtained by the following recursive equation:f_i = \left(f_{i - 1} ^ {b_1} \cdot f_{i - 2} ^ {b_2} \cdot \cdots \cdot f_{i - k} ^ {b_k}\right) \bmod p,which in short isf_i = \left(\prod_{j = 1}^{k} f_{i - j}^{b_j}\right) \bmod p,where p = 998\,244\,353 (a widely-used prime), b_1, b_2, \ldots, b_k are known integer constants, and x \bmod y denotes the remainder of x divided by y.Bob lost the values of f_1, f_2, \ldots, f_k, which is extremely troublesome – these are the basis of the sequence! Luckily, Bob remembers the first k - 1 elements of the sequence: f_1 = f_2 = \ldots = f_{k - 1} = 1 and the n-th element: f_n = m. Please find any possible value of f_k. If no solution exists, just tell Bob that it is impossible to recover his favorite sequence, regardless of Bob's sadness.InputThe first line contains a positive integer k (1 \leq k \leq 100), denoting the length of the sequence b_1, b_2, \ldots, b_k.The second line contains k positive integers b_1, b_2, \ldots, b_k (1 \leq b_i < p).The third line contains two positive integers n and m (k < n \leq 10^9, 1 \leq m < p), which implies f_n = m.OutputOutput a possible value of f_k, where f_k is a positive integer satisfying 1 \leq f_k < p. If there are multiple answers, print any of them. If no such f_k makes f_n = m, output -1 instead.It is easy to show that if there are some possible values of f_k, there must be at least one satisfying 1 \leq f_k < p.ExamplesInput
3
2 3 5
4 16
Output
4
Input
5
4 7 1 5 6
7 14187219
Output
6
Input
8
2 3 5 6 1 7 9 10
23333 1
Output
1
Input
1
2
88888 66666
Output
-1
Input
3
998244352 998244352 998244352
4 2
Output
-1
Input
10
283 463 213 777 346 201 463 283 102 999
2333333 6263423
Output
382480067
NoteIn the first sample, we have f_4 = f_3^2 \cdot f_2^3 \cdot f_1^5. Therefore, applying f_3 = 4, we have f_4 = 16. Note that there can be multiple answers.In the third sample, applying f_7 = 1 makes f_{23333} = 1.In the fourth sample, no such f_1 makes f_{88888} = 66666. Therefore, we output -1 instead. | 3
2 3 5
4 16
| 4 | 3 seconds | 256 megabytes | ['math', 'matrices', 'number theory', '*2400'] |
E. Lunar New Year and Red Envelopestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLunar New Year is approaching, and Bob is going to receive some red envelopes with countless money! But collecting money from red envelopes is a time-consuming process itself.Let's describe this problem in a mathematical way. Consider a timeline from time 1 to n. The i-th red envelope will be available from time s_i to t_i, inclusive, and contain w_i coins. If Bob chooses to collect the coins in the i-th red envelope, he can do it only in an integer point of time between s_i and t_i, inclusive, and he can't collect any more envelopes until time d_i (inclusive) after that. Here s_i \leq t_i \leq d_i holds.Bob is a greedy man, he collects coins greedily — whenever he can collect coins at some integer time x, he collects the available red envelope with the maximum number of coins. If there are multiple envelopes with the same maximum number of coins, Bob would choose the one whose parameter d is the largest. If there are still multiple choices, Bob will choose one from them randomly.However, Alice — his daughter — doesn't want her father to get too many coins. She could disturb Bob at no more than m integer time moments. If Alice decides to disturb Bob at time x, he could not do anything at time x and resumes his usual strategy at the time x + 1 (inclusive), which may lead to missing some red envelopes.Calculate the minimum number of coins Bob would get if Alice disturbs him optimally.InputThe first line contains three non-negative integers n, m and k (1 \leq n \leq 10^5, 0 \leq m \leq 200, 1 \leq k \leq 10^5), denoting the length of the timeline, the number of times Alice can disturb Bob and the total number of red envelopes, respectively.The following k lines describe those k red envelopes. The i-th line contains four positive integers s_i, t_i, d_i and w_i (1 \leq s_i \leq t_i \leq d_i \leq n, 1 \leq w_i \leq 10^9) — the time segment when the i-th envelope is available, the time moment Bob can continue collecting after collecting the i-th envelope, and the number of coins in this envelope, respectively.OutputOutput one integer — the minimum number of coins Bob would get if Alice disturbs him optimally.ExamplesInput
5 0 2
1 3 4 5
2 5 5 8
Output
13Input
10 1 6
1 1 2 4
2 2 6 2
3 3 3 3
4 4 4 5
5 5 5 7
6 6 6 9
Output
2Input
12 2 6
1 5 5 4
4 6 6 2
3 8 8 3
2 9 9 5
6 10 10 7
8 12 12 9
Output
11NoteIn the first sample, Alice has no chance to disturb Bob. Therefore Bob will collect the coins in the red envelopes at time 1 and 5, collecting 13 coins in total.In the second sample, Alice should disturb Bob at time 1. Therefore Bob skips the first envelope, collects the second one and can not do anything after that. So the answer is 2. | 5 0 2
1 3 4 5
2 5 5 8
| 13 | 3 seconds | 256 megabytes | ['data structures', 'dp', '*2100'] |
D. Lunar New Year and a Wandertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, \ldots, a_n is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: x is a prefix of y, but x \ne y (this is impossible in this problem as all considered sequences have the same length); in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. InputThe first line contains two positive integers n and m (1 \leq n, m \leq 10^5), denoting the number of nodes and edges, respectively.The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 \leq u_i, v_i \leq n), representing the nodes the i-th edge connects.Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.OutputOutput a line containing the lexicographically smallest sequence a_1, a_2, \ldots, a_n Bob can record.ExamplesInput
3 2
1 2
1 3
Output
1 2 3
Input
5 5
1 4
3 4
5 4
3 2
1 5
Output
1 4 3 2 5
Input
10 10
1 4
6 8
2 5
3 7
9 4
5 6
3 4
8 10
8 9
1 10
Output
1 4 3 7 9 8 6 5 2 10
NoteIn the first sample, Bob's optimal wandering path could be 1 \rightarrow 2 \rightarrow 1 \rightarrow 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be 1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one. | 3 2
1 2
1 3
| 1 2 3 | 3 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'graphs', 'greedy', 'shortest paths', '*1500'] |
C. Lunar New Year and Number Divisiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLunar New Year is approaching, and Bob is struggling with his homework – a number division problem.There are n positive integers a_1, a_2, \ldots, a_n on Bob's homework paper, where n is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least 2 numbers. Suppose the numbers are divided into m groups, and the sum of the numbers in the j-th group is s_j. Bob's aim is to minimize the sum of the square of s_j, that is \sum_{j = 1}^{m} s_j^2.Bob is puzzled by this hard problem. Could you please help him solve it?InputThe first line contains an even integer n (2 \leq n \leq 3 \cdot 10^5), denoting that there are n integers on Bob's homework paper.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^4), describing the numbers you need to deal with.OutputA single line containing one integer, denoting the minimum of the sum of the square of s_j, which is \sum_{i = j}^{m} s_j^2, where m is the number of groups.ExamplesInput
4
8 5 2 3
Output
164
Input
6
1 1 1 2 2 2
Output
27
NoteIn the first sample, one of the optimal solutions is to divide those 4 numbers into 2 groups \{2, 8\}, \{5, 3\}. Thus the answer is (2 + 8)^2 + (5 + 3)^2 = 164.In the second sample, one of the optimal solutions is to divide those 6 numbers into 3 groups \{1, 2\}, \{1, 2\}, \{1, 2\}. Thus the answer is (1 + 2)^2 + (1 + 2)^2 + (1 + 2)^2 = 27. | 4
8 5 2 3
| 164 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', 'sortings', '*900'] |
B. Lunar New Year and Food Orderingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLunar New Year is approaching, and Bob is planning to go for a famous restaurant — "Alice's".The restaurant "Alice's" serves n kinds of food. The cost for the i-th kind is always c_i. Initially, the restaurant has enough ingredients for serving exactly a_i dishes of the i-th kind. In the New Year's Eve, m customers will visit Alice's one after another and the j-th customer will order d_j dishes of the t_j-th kind of food. The (i + 1)-st customer will only come after the i-th customer is completely served.Suppose there are r_i dishes of the i-th kind remaining (initially r_i = a_i). When a customer orders 1 dish of the i-th kind, the following principles will be processed. If r_i > 0, the customer will be served exactly 1 dish of the i-th kind. The cost for the dish is c_i. Meanwhile, r_i will be reduced by 1. Otherwise, the customer will be served 1 dish of the cheapest available kind of food if there are any. If there are multiple cheapest kinds of food, the one with the smallest index among the cheapest will be served. The cost will be the cost for the dish served and the remain for the corresponding dish will be reduced by 1. If there are no more dishes at all, the customer will leave angrily. Therefore, no matter how many dishes are served previously, the cost for the customer is 0.If the customer doesn't leave after the d_j dishes are served, the cost for the customer will be the sum of the cost for these d_j dishes.Please determine the total cost for each of the m customers.InputThe first line contains two integers n and m (1 \leq n, m \leq 10^5), representing the number of different kinds of food and the number of customers, respectively.The second line contains n positive integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^7), where a_i denotes the initial remain of the i-th kind of dishes.The third line contains n positive integers c_1, c_2, \ldots, c_n (1 \leq c_i \leq 10^6), where c_i denotes the cost of one dish of the i-th kind.The following m lines describe the orders of the m customers respectively. The j-th line contains two positive integers t_j and d_j (1 \leq t_j \leq n, 1 \leq d_j \leq 10^7), representing the kind of food and the number of dishes the j-th customer orders, respectively.OutputPrint m lines. In the j-th line print the cost for the j-th customer.ExamplesInput
8 5
8 6 2 1 4 5 7 5
6 3 3 2 6 2 3 2
2 8
1 4
4 7
3 4
6 10
Output
22
24
14
10
39
Input
6 6
6 6 6 6 6 6
6 66 666 6666 66666 666666
1 6
2 6
3 6
4 6
5 6
6 66
Output
36
396
3996
39996
399996
0
Input
6 6
6 6 6 6 6 6
6 66 666 6666 66666 666666
1 6
2 13
3 6
4 11
5 6
6 6
Output
36
11058
99996
4333326
0
0
NoteIn the first sample, 5 customers will be served as follows. Customer 1 will be served 6 dishes of the 2-nd kind, 1 dish of the 4-th kind, and 1 dish of the 6-th kind. The cost is 6 \cdot 3 + 1 \cdot 2 + 1 \cdot 2 = 22. The remain of the 8 kinds of food will be \{8, 0, 2, 0, 4, 4, 7, 5\}. Customer 2 will be served 4 dishes of the 1-st kind. The cost is 4 \cdot 6 = 24. The remain will be \{4, 0, 2, 0, 4, 4, 7, 5\}. Customer 3 will be served 4 dishes of the 6-th kind, 3 dishes of the 8-th kind. The cost is 4 \cdot 2 + 3 \cdot 2 = 14. The remain will be \{4, 0, 2, 0, 4, 0, 7, 2\}. Customer 4 will be served 2 dishes of the 3-rd kind, 2 dishes of the 8-th kind. The cost is 2 \cdot 3 + 2 \cdot 2 = 10. The remain will be \{4, 0, 0, 0, 4, 0, 7, 0\}. Customer 5 will be served 7 dishes of the 7-th kind, 3 dishes of the 1-st kind. The cost is 7 \cdot 3 + 3 \cdot 6 = 39. The remain will be \{1, 0, 0, 0, 4, 0, 0, 0\}.In the second sample, each customer is served what they order except the last one, who leaves angrily without paying. For example, the second customer is served 6 dishes of the second kind, so the cost is 66 \cdot 6 = 396.In the third sample, some customers may not be served what they order. For example, the second customer is served 6 dishes of the second kind, 6 of the third and 1 of the fourth, so the cost is 66 \cdot 6 + 666 \cdot 6 + 6666 \cdot 1 = 11058. | 8 5
8 6 2 1 4 5 7 5
6 3 3 2 6 2 3 2
2 8
1 4
4 7
3 4
6 10
| 22 24 14 10 39 | 2 seconds | 256 megabytes | ['data structures', 'implementation', '*1500'] |
A. Lunar New Year and Cross Countingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLunar New Year is approaching, and you bought a matrix with lots of "crosses".This matrix M of size n \times n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 \leq i, j \leq n. We define a cross appearing in the i-th row and the j-th column (1 < i, j < n) if and only if M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = 'X'.The following figure illustrates a cross appearing at position (2, 2) in a 3 \times 3 matrix. X.X.X.X.X Your task is to find out the number of crosses in the given matrix M. Two crosses are different if and only if they appear in different rows or columns.InputThe first line contains only one positive integer n (1 \leq n \leq 500), denoting the size of the matrix M.The following n lines illustrate the matrix M. Each line contains exactly n characters, each of them is 'X' or '.'. The j-th element in the i-th line represents M(i, j), where 1 \leq i, j \leq n.OutputOutput a single line containing only one integer number k — the number of crosses in the given matrix M.ExamplesInput
5
.....
.XXX.
.XXX.
.XXX.
.....
Output
1
Input
2
XX
XX
Output
0
Input
6
......
X.X.X.
.X.X.X
X.X.X.
.X.X.X
......
Output
4
NoteIn the first sample, a cross appears at (3, 3), so the answer is 1.In the second sample, no crosses appear since n < 3, so the answer is 0.In the third sample, crosses appear at (3, 2), (3, 4), (4, 3), (4, 5), so the answer is 4. | 5
.....
.XXX.
.XXX.
.XXX.
.....
| 1 | 2 seconds | 256 megabytes | ['implementation', '*800'] |
E. Helping Hiasat time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHiasat registered a new account in NeckoForces and when his friends found out about that, each one of them asked to use his name as Hiasat's handle.Luckily for Hiasat, he can change his handle in some points in time. Also he knows the exact moments friends will visit his profile page. Formally, you are given a sequence of events of two types: 1 — Hiasat can change his handle. 2 s — friend s visits Hiasat's profile. The friend s will be happy, if each time he visits Hiasat's profile his handle would be s.Hiasat asks you to help him, find the maximum possible number of happy friends he can get.InputThe first line contains two integers n and m (1 \le n \le 10^5, 1 \le m \le 40) — the number of events and the number of friends.Then n lines follow, each denoting an event of one of two types: 1 — Hiasat can change his handle. 2 s — friend s (1 \le |s| \le 40) visits Hiasat's profile. It's guaranteed, that each friend's name consists only of lowercase Latin letters.It's guaranteed, that the first event is always of the first type and each friend will visit Hiasat's profile at least once.OutputPrint a single integer — the maximum number of happy friends.ExamplesInput
5 3
1
2 motarack
2 mike
1
2 light
Output
2
Input
4 3
1
2 alice
2 bob
2 tanyaromanova
Output
1
NoteIn the first example, the best way is to change the handle to the "motarack" in the first event and to the "light" in the fourth event. This way, "motarack" and "light" will be happy, but "mike" will not.In the second example, you can choose either "alice", "bob" or "tanyaromanova" and only that friend will be happy. | 5 3
1
2 motarack
2 mike
1
2 light
| 2 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'dp', 'meet-in-the-middle', '*2200'] |
D. Kilani and the Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKilani is playing a game with his friends. This game can be represented as a grid of size n \times m, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell).The game is played in rounds. In each round players expand turn by turn: firstly, the first player expands, then the second player expands and so on. The expansion happens as follows: for each castle the player owns now, he tries to expand into the empty cells nearby. The player i can expand from a cell with his castle to the empty cell if it's possible to reach it in at most s_i (where s_i is player's expansion speed) moves to the left, up, right or down without going through blocked cells or cells occupied by some other player's castle. The player examines the set of cells he can expand to and builds a castle in each of them at once. The turned is passed to the next player after that. The game ends when no player can make a move. You are given the game field and speed of the expansion for each player. Kilani wants to know for each player how many cells he will control (have a castle their) after the game ends.InputThe first line contains three integers n, m and p (1 \le n, m \le 1000, 1 \le p \le 9) — the size of the grid and the number of players.The second line contains p integers s_i (1 \le s \le 10^9) — the speed of the expansion for every player.The following n lines describe the game grid. Each of them consists of m symbols, where '.' denotes an empty cell, '#' denotes a blocked cell and digit x (1 \le x \le p) denotes the castle owned by player x.It is guaranteed, that each player has at least one castle on the grid.OutputPrint p integers — the number of cells controlled by each player after the game ends.ExamplesInput
3 3 2
1 1
1..
...
..2
Output
6 3
Input
3 4 4
1 1 1 1
....
#...
1234
Output
1 4 3 3
NoteThe picture below show the game before it started, the game after the first round and game after the second round in the first example: In the second example, the first player is "blocked" so he will not capture new cells for the entire game. All other player will expand up during the first two rounds and in the third round only the second player will move to the left. | 3 3 2
1 1
1..
...
..2
| 6 3 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'implementation', 'shortest paths', '*1900'] |
C. Ayoub and Lost Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub had an array a of integers of size n and this array had two interesting properties: All the integers in the array were between l and r (inclusive). The sum of all the elements was divisible by 3. Unfortunately, Ayoub has lost his array, but he remembers the size of the array n and the numbers l and r, so he asked you to find the number of ways to restore the array. Since the answer could be very large, print it modulo 10^9 + 7 (i.e. the remainder when dividing by 10^9 + 7). In case there are no satisfying arrays (Ayoub has a wrong memory), print 0.InputThe first and only line contains three integers n, l and r (1 \le n \le 2 \cdot 10^5 , 1 \le l \le r \le 10^9) — the size of the lost array and the range of numbers in the array.OutputPrint the remainder when dividing by 10^9 + 7 the number of ways to restore the array.ExamplesInput
2 1 3
Output
3
Input
3 2 2
Output
1
Input
9 9 99
Output
711426616
NoteIn the first example, the possible arrays are : [1,2], [2,1], [3, 3].In the second example, the only possible array is [2, 2, 2]. | 2 1 3
| 3 | 1 second | 256 megabytes | ['combinatorics', 'dp', 'math', '*1500'] |
B. Zuhair and Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a string s of length n and integer k (1 \le k \le n). The string s has a level x, if x is largest non-negative integer, such that it's possible to find in s: x non-intersecting (non-overlapping) substrings of length k, all characters of these x substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings). A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers i and j (1 \le i \le j \le n), denoted as s[i \dots j] = "s_{i}s_{i+1} \dots s_{j}".For example, if k = 2, then: the string "aabb" has level 1 (you can select substring "aa"), the strings "zzzz" and "zzbzz" has level 2 (you can select two non-intersecting substrings "zz" in each of them), the strings "abed" and "aca" have level 0 (you can't find at least one substring of the length k=2 containing the only distinct character). Zuhair gave you the integer k and the string s of length n. You need to find x, the level of the string s.InputThe first line contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5) — the length of the string and the value of k.The second line contains the string s of length n consisting only of lowercase Latin letters.OutputPrint a single integer x — the level of the string.ExamplesInput
8 2
aaacaabb
Output
2
Input
2 1
ab
Output
1
Input
4 2
abab
Output
0
NoteIn the first example, we can select 2 non-intersecting substrings consisting of letter 'a': "(aa)ac(aa)bb", so the level is 2.In the second example, we can select either substring "a" or "b" to get the answer 1. | 8 2
aaacaabb
| 2 | 1 second | 256 megabytes | ['brute force', 'implementation', 'strings', '*1100'] |
A. Salem and Sticks time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSalem gave you n sticks with integer positive lengths a_1, a_2, \ldots, a_n.For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from a to b is |a - b|, where |x| means the absolute value of x.A stick length a_i is called almost good for some integer t if |a_i - t| \le 1.Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer t and the total cost of changing is minimum possible. The value of t is not fixed in advance and you can choose it as any positive integer. As an answer, print the value of t and the minimum cost. If there are multiple optimal choices for t, print any of them.InputThe first line contains a single integer n (1 \le n \le 1000) — the number of sticks.The second line contains n integers a_i (1 \le a_i \le 100) — the lengths of the sticks.OutputPrint the value of t and the minimum possible cost. If there are multiple optimal choices for t, print any of them.ExamplesInput
3
10 1 4
Output
3 7
Input
5
1 1 2 2 3
Output
2 0
NoteIn the first example, we can change 1 into 2 and 10 into 4 with cost |1 - 2| + |10 - 4| = 1 + 6 = 7 and the resulting lengths [2, 4, 4] are almost good for t = 3.In the second example, the sticks lengths are already almost good for t = 2, so we don't have to do anything. | 3
10 1 4
| 3 7 | 1 second | 256 megabytes | ['brute force', 'implementation', '*1100'] |
B. Game with stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo people are playing a game with a string s, consisting of lowercase latin letters. On a player's turn, he should choose two consecutive equal letters in the string and delete them. For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.Your task is to determine which player will win if both play optimally.InputThe only line contains the string s, consisting of lowercase latin letters (1 \leq |s| \leq 100\,000), where |s| means the length of a string s.OutputIf the first player wins, print "Yes". If the second player wins, print "No".ExamplesInput
abacaba
Output
No
Input
iiq
Output
Yes
Input
abba
Output
No
NoteIn the first example the first player is unable to make a turn, so he loses.In the second example first player turns the string into "q", then second player is unable to move, so he loses. | abacaba
| No | 1 second | 256 megabytes | ['data structures', 'implementation', 'math', '*1200'] |
A. Splitting into digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has his favourite number n. He wants to split it to some non-zero digits. It means, that he wants to choose some digits d_1, d_2, \ldots, d_k, such that 1 \leq d_i \leq 9 for all i and d_1 + d_2 + \ldots + d_k = n.Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among d_1, d_2, \ldots, d_k. Help him!InputThe first line contains a single integer n — the number that Vasya wants to split (1 \leq n \leq 1000).OutputIn the first line print one integer k — the number of digits in the partition. Note that k must satisfy the inequality 1 \leq k \leq n. In the next line print k digits d_1, d_2, \ldots, d_k separated by spaces. All digits must satisfy the inequalities 1 \leq d_i \leq 9.You should find a partition of n in which the number of different digits among d_1, d_2, \ldots, d_k will be minimal possible among all partitions of n into non-zero digits. Among such partitions, it is allowed to find any. It is guaranteed that there exists at least one partition of the number n into digits.ExamplesInput
1
Output
1
1 Input
4
Output
2
2 2
Input
27
Output
3
9 9 9
NoteIn the first test, the number 1 can be divided into 1 digit equal to 1.In the second test, there are 3 partitions of the number 4 into digits in which the number of different digits is 1. This partitions are [1, 1, 1, 1], [2, 2] and [4]. Any of these partitions can be found. And, for example, dividing the number 4 to the digits [1, 1, 2] isn't an answer, because it has 2 different digits, that isn't the minimum possible number. | 1
| 1 1 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', 'math', '*800'] |
E. Radix sumtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define radix sum of number a consisting of digits a_1, \ldots ,a_k and number b consisting of digits b_1, \ldots ,b_k(we add leading zeroes to the shorter number to match longer length) as number s(a,b) consisting of digits (a_1+b_1)\mod 10, \ldots ,(a_k+b_k)\mod 10. The radix sum of several integers is defined as follows: s(t_1, \ldots ,t_n)=s(t_1,s(t_2, \ldots ,t_n))You are given an array x_1, \ldots ,x_n. The task is to compute for each integer i (0 \le i < n) number of ways to consequently choose one of the integers from the array n times, so that the radix sum of these integers is equal to i. Calculate these values modulo 2^{58}.InputThe first line contains integer n — the length of the array(1 \leq n \leq 100000).The second line contains n integers x_1, \ldots x_n — array elements(0 \leq x_i < 100000).OutputOutput n integers y_0, \ldots, y_{n-1} — y_i should be equal to corresponding number of ways modulo 2^{58}.ExamplesInput
2
5 6
Output
1
2
Input
4
5 7 5 7
Output
16
0
64
0
NoteIn the first example there exist sequences: sequence (5,5) with radix sum 0, sequence (5,6) with radix sum 1, sequence (6,5) with radix sum 1, sequence (6,6) with radix sum 2. | 2
5 6
| 1 2 | 4 seconds | 256 megabytes | ['fft', 'math', 'number theory', '*3400'] |
D. Professional layertime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCardbluff is popular sport game in Telegram. Each Cardbluff player has ever dreamed about entrance in the professional layer. There are n judges now in the layer and you are trying to pass the entrance exam. You have a number k — your skill in Cardbluff.Each judge has a number a_i — an indicator of uncertainty about your entrance to the professional layer and a number e_i — an experience playing Cardbluff. To pass the exam you need to convince all judges by playing with them. You can play only one game with each judge. As a result of a particular game, you can divide the uncertainty of i-th judge by any natural divisor of a_i which is at most k. If GCD of all indicators is equal to 1, you will enter to the professional layer and become a judge.Also, you want to minimize the total amount of spent time. So, if you play with x judges with total experience y you will spend x \cdot y seconds.Print minimal time to enter to the professional layer or -1 if it's impossible.InputThere are two numbers in the first line n and k (1 \leq n \leq 10^6, 1 \leq k \leq 10^{12}) — the number of judges and your skill in Cardbluff.The second line contains n integers, where i-th number a_i (1 \leq a_i \leq 10^{12}) — the uncertainty of i-th judgeThe third line contains n integers in the same format (1 \leq e_i \leq 10^9), e_i — the experience of i-th judge.OutputPrint the single integer — minimal number of seconds to pass exam, or -1 if it's impossibleExamplesInput
3 6
30 30 30
100 4 5
Output
18
Input
1 1000000
1
100
Output
0
Input
3 5
7 7 7
1 1 1
Output
-1
| 3 6
30 30 30
100 4 5
| 18 | 3 seconds | 512 megabytes | ['bitmasks', 'dp', '*3100'] |
C. Johnny Solvingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday is tuesday, that means there is a dispute in JOHNNY SOLVING team again: they try to understand who is Johnny and who is Solving. That's why guys asked Umnik to help them. Umnik gave guys a connected graph with n vertices without loops and multiedges, such that a degree of any vertex is at least 3, and also he gave a number 1 \leq k \leq n. Because Johnny is not too smart, he promised to find a simple path with length at least \frac{n}{k} in the graph. In reply, Solving promised to find k simple by vertices cycles with representatives, such that: Length of each cycle is at least 3. Length of each cycle is not divisible by 3. In each cycle must be a representative - vertex, which belongs only to this cycle among all printed cycles. You need to help guys resolve the dispute, for that you need to find a solution for Johnny: a simple path with length at least \frac{n}{k} (n is not necessarily divided by k), or solution for Solving: k cycles that satisfy all the conditions above. If there is no any solution - print -1. InputThe first line contains three integers n, m and k (1 \leq k \leq n \leq 2.5 \cdot 10^5, 1 \leq m \leq 5 \cdot 10^5)Next m lines describe edges of the graph in format v, u (1 \leq v, u \leq n). It's guaranteed that v \neq u and all m pairs are distinct.It's guaranteed that a degree of each vertex is at least 3.OutputPrint PATH in the first line, if you solve problem for Johnny. In the second line print the number of vertices in the path c (c \geq \frac{n}{k}). And in the third line print vertices describing the path in route order.Print CYCLES in the first line, if you solve problem for Solving. In the following lines describe exactly k cycles in the following format: in the first line print the size of the cycle c (c \geq 3). In the second line print the cycle in route order. Also, the first vertex in the cycle must be a representative.Print -1 if there is no any solution. The total amount of printed numbers in the output must be at most 10^6. It's guaranteed, that if exists any solution then there is a correct output satisfies this restriction.ExamplesInput
4 6 2
1 2
1 3
1 4
2 3
2 4
3 4
Output
PATH
4
1 2 3 4 Input
10 18 2
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
2 3
3 4
2 4
5 6
6 7
5 7
8 9
9 10
8 10
Output
CYCLES
4
4 1 2 3
4
7 1 5 6
| 4 6 2
1 2
1 3
1 4
2 3
2 4
3 4
| PATH 4 1 2 3 4 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'math', '*2700'] |
B. Game with modulotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him: "x", if (x \bmod a) \geq (y \bmod a). "y", if (x \bmod a) < (y \bmod a). We define (x \bmod a) as a remainder of division x by a.Vasya should guess the number a using no more, than 60 questions.It's guaranteed that Petya has a number, that satisfies the inequality 1 \leq a \leq 10^9.Help Vasya playing this game and write a program, that will guess the number a.InteractionYour program should play several games.Before the start of any game your program should read the string: "start" (without quotes) — the start of the new game. "mistake" (without quotes) — in the previous game, you found the wrong answer. Your program should terminate after reading this string and it will get verdict "Wrong answer". "end" (without quotes) — all games finished. Your program should terminate after reading this string. After reading the string "start" (without quotes) the new game starts. At the beginning, your program should ask several questions about pairs of non-negative integer numbers (x, y). You can only ask the numbers, that satisfy the inequalities 0 \leq x, y \leq 2 \cdot 10^9. To ask a question print "? x y" (without quotes). As the answer, you should read one symbol: "x" (without quotes), if (x \bmod a) \geq (y \bmod a). "y" (without quotes), if (x \bmod a) < (y \bmod a). "e" (without quotes) — you asked more than 60 questions. Your program should terminate after reading this string and it will get verdict "Wrong answer". After your program asked several questions your program should print the answer in form "! a" (without quotes). You should print the number a satisfying the inequalities 1 \leq a \leq 10^9. It's guaranteed that Petya's number a satisfied this condition. After that, the current game will finish.We recall that your program can't ask more than 60 questions during one game.If your program doesn't terminate after reading "mistake" (without quotes), "end" (without quotes) or "e" (without quotes), it can get any verdict, because it will continue reading from closed input. Also, if your program prints answer or question in the incorrect format it can get any verdict, too. Be careful.Don't forget to flush the output after printing questions and answers.To flush the output, you can use: fflush(stdout) in C++. System.out.flush() in Java. stdout.flush() in Python. flush(output) in Pascal. See the documentation for other languages. It's guaranteed that you should play at least 1 and no more than 100 games.Hacks:In hacks, you can use only one game. To hack a solution with Petya's number a (1 \leq a \leq 10^9) in the first line you should write a single number 1 and in the second line you should write a single number a.ExampleInput
start
x
x
start
x
x
y
start
x
x
y
y
end
Output
? 0 0
? 10 1
! 1
? 0 0
? 3 4
? 2 5
! 2
? 2 4
? 2 5
? 3 10
? 9 1
! 3
NoteIn the first test, you should play 3 games with Petya's numbers 1, 2 and 3.In the first game, Petya will answer "x" (without quotes) to any question, because (x \bmod 1) = 0 for any integer x. In the second game, if you will ask pair (0, 0), the answer will be "x" (without quotes), because (0 \bmod 2) \geq (0 \bmod 2). But if you will ask pair (2, 5), the answer will be "y" (without quotes), because (2 \bmod 2) < (5 \bmod 2), because (2 \bmod 2) = 0 and (5 \bmod 2) = 1. | start
x
x
start
x
x
y
start
x
x
y
y
end
| ? 0 0 ? 10 1 ! 1 ? 0 0 ? 3 4 ? 2 5 ! 2 ? 2 4 ? 2 5 ? 3 10 ? 9 1 ! 3 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'interactive', '*2000'] |
A. Grid gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.InputThe only line contains a string s consisting of zeroes and ones (1 \le |s| \le 1000). Zero describes vertical tile, one describes horizontal tile.OutputOutput |s| lines — for each tile you should output two positive integers r,c, not exceeding 4, representing numbers of smallest row and column intersecting with it.If there exist multiple solutions, print any of them.ExampleInput
010
Output
1 1
1 2
1 4NoteFollowing image illustrates the example after placing all three tiles: Then the first row is deleted: | 010
| 1 1 1 2 1 4 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1400'] |
F. Elongated Matrixtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix a, consisting of n rows and m columns. Each cell contains an integer in it.You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: firstly visit all cells of the first column from the top row to the bottom one, then the same for the second column and so on. During the traversal you write down the sequence of the numbers on the cells in the same order you visited them. Let that sequence be s_1, s_2, \dots, s_{nm}. The traversal is k-acceptable if for all i (1 \le i \le nm - 1) |s_i - s_{i + 1}| \ge k.Find the maximum integer k such that there exists some order of rows of matrix a that it produces a k-acceptable traversal.InputThe first line contains two integers n and m (1 \le n \le 16, 1 \le m \le 10^4, 2 \le nm) — the number of rows and the number of columns, respectively.Each of the next n lines contains m integers (1 \le a_{i, j} \le 10^9) — the description of the matrix.OutputPrint a single integer k — the maximum number such that there exists some order of rows of matrix a that it produces an k-acceptable traversal.ExamplesInput
4 2
9 9
10 8
5 3
4 3
Output
5
Input
2 4
1 2 3 4
10 3 7 3
Output
0
Input
6 1
3
6
2
5
1
4
Output
3
NoteIn the first example you can rearrange rows as following to get the 5-acceptable traversal:5 310 84 39 9Then the sequence s will be [5, 10, 4, 9, 3, 8, 3, 9]. Each pair of neighbouring elements have at least k = 5 difference between them.In the second example the maximum k = 0, any order is 0-acceptable.In the third example the given order is already 3-acceptable, you can leave it as it is. | 4 2
9 9
10 8
5 3
4 3
| 5 | 4 seconds | 256 megabytes | ['binary search', 'bitmasks', 'brute force', 'dp', 'graphs', '*2000'] |
E. Monotonic Renumerationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. Let's denote monotonic renumeration of array a as an array b consisting of n integers such that all of the following conditions are met: b_1 = 0; for every pair of indices i and j such that 1 \le i, j \le n, if a_i = a_j, then b_i = b_j (note that if a_i \ne a_j, it is still possible that b_i = b_j); for every index i \in [1, n - 1] either b_i = b_{i + 1} or b_i + 1 = b_{i + 1}. For example, if a = [1, 2, 1, 2, 3], then two possible monotonic renumerations of a are b = [0, 0, 0, 0, 0] and b = [0, 0, 0, 0, 1].Your task is to calculate the number of different monotonic renumerations of a. The answer may be large, so print it modulo 998244353.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of elements in a.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).OutputPrint one integer — the number of different monotonic renumerations of a, taken modulo 998244353.ExamplesInput
5
1 2 1 2 3
Output
2
Input
2
100 1
Output
2
Input
4
1 3 3 7
Output
4
| 5
1 2 1 2 3
| 2 | 2 seconds | 256 megabytes | ['combinatorics', 'sortings', '*1700'] |
D. Balanced Ternary Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of exactly n characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.InputThe first line of the input contains one integer n (3 \le n \le 3 \cdot 10^5, n is divisible by 3) — the number of characters in s.The second line contains the string s consisting of exactly n characters '0', '1' and '2'.OutputPrint one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.Because n is divisible by 3 it is obvious that the answer exists. And it is obvious that there is only one possible answer.ExamplesInput
3
121
Output
021
Input
6
000000
Output
001122
Input
6
211200
Output
211200
Input
6
120110
Output
120120
| 3
121
| 021 | 2 seconds | 256 megabytes | ['greedy', 'strings', '*1500'] |
C. Doors Breaking and Repairingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.There are n doors, the i-th door initially has durability equal to a_i.During your move you can try to break one of the doors. If you choose door i and its current durability is b_i then you reduce its durability to max(0, b_i - x) (the value x is given).During Slavik's move he tries to repair one of the doors. If he chooses door i and its current durability is b_i then he increases its durability to b_i + y (the value y is given). Slavik cannot repair doors with current durability equal to 0.The game lasts 10^{100} turns. If some player cannot make his move then he has to skip it.Your goal is to maximize the number of doors with durability equal to 0 at the end of the game. You can assume that Slavik wants to minimize the number of such doors. What is the number of such doors in the end if you both play optimally?InputThe first line of the input contains three integers n, x and y (1 \le n \le 100, 1 \le x, y \le 10^5) — the number of doors, value x and value y, respectively.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^5), where a_i is the initial durability of the i-th door.OutputPrint one integer — the number of doors with durability equal to 0 at the end of the game, if you and Slavik both play optimally.ExamplesInput
6 3 2
2 3 1 3 4 2
Output
6
Input
5 3 3
1 2 4 2 3
Output
2
Input
5 5 6
1 2 6 10 3
Output
2
NoteClarifications about the optimal strategy will be ignored. | 6 3 2
2 3 1 3 4 2
| 6 | 1 second | 256 megabytes | ['games', '*1200'] |
B. Array K-Coloringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integer numbers.You have to color this array in k colors in such a way that: Each element of the array should be colored in some color; For each i from 1 to k there should be at least one element colored in the i-th color in the array; For each i from 1 to k all elements colored in the i-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers c_1, c_2, \dots c_n, where 1 \le c_i \le k and c_i is the color of the i-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 5000) — the length of the array a and the number of colors, respectively.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 5000) — elements of the array a.OutputIf there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers c_1, c_2, \dots c_n, where 1 \le c_i \le k and c_i is the color of the i-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.ExamplesInput
4 2
1 2 2 3
Output
YES
1 1 2 2
Input
5 2
3 2 1 2 3
Output
YES
2 1 1 2 1
Input
5 2
2 1 1 2 1
Output
NO
NoteIn the first example the answer 2~ 1~ 2~ 1 is also acceptable.In the second example the answer 1~ 1~ 1~ 2~ 2 is also acceptable.There exist other acceptable answers for both examples. | 4 2
1 2 2 3
| YES 1 1 2 2 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1400'] |
A. Integer Sequence Dividingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer sequence 1, 2, \dots, n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible.The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^9).OutputPrint one integer — the minimum possible value of |sum(A) - sum(B)| if you divide the initial sequence 1, 2, \dots, n into two sets A and B.ExamplesInput
3
Output
0
Input
5
Output
1
Input
6
Output
1
NoteSome (not all) possible answers to examples:In the first example you can divide the initial sequence into sets A = \{1, 2\} and B = \{3\} so the answer is 0.In the second example you can divide the initial sequence into sets A = \{1, 3, 4\} and B = \{2, 5\} so the answer is 1.In the third example you can divide the initial sequence into sets A = \{1, 4, 5\} and B = \{2, 3, 6\} so the answer is 1. | 3
| 0 | 1 second | 256 megabytes | ['math', '*800'] |
G. (Zero XOR Subset)-lesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n of integer numbers.Your task is to divide the array into the maximum number of segments in such a way that: each element is contained in exactly one segment; each segment contains at least one element; there doesn't exist a non-empty subset of segments such that bitwise XOR of the numbers from them is equal to 0. Print the maximum number of segments the array can be divided into. Print -1 if no suitable division exists.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the size of the array.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9).OutputPrint the maximum number of segments the array can be divided into while following the given constraints. Print -1 if no suitable division exists.ExamplesInput
4
5 5 7 2
Output
2
Input
3
1 2 3
Output
-1
Input
3
3 1 10
Output
3
NoteIn the first example 2 is the maximum number. If you divide the array into \{[5], [5, 7, 2]\}, the XOR value of the subset of only the second segment is 5 \oplus 7 \oplus 2 = 0. \{[5, 5], [7, 2]\} has the value of the subset of only the first segment being 5 \oplus 5 = 0. However, \{[5, 5, 7], [2]\} will lead to subsets \{[5, 5, 7]\} of XOR 7, \{[2]\} of XOR 2 and \{[5, 5, 7], [2]\} of XOR 5 \oplus 5 \oplus 7 \oplus 2 = 5.Let's take a look at some division on 3 segments — \{[5], [5, 7], [2]\}. It will produce subsets: \{[5]\}, XOR 5; \{[5, 7]\}, XOR 2; \{[5], [5, 7]\}, XOR 7; \{[2]\}, XOR 2; \{[5], [2]\}, XOR 7; \{[5, 7], [2]\}, XOR 0; \{[5], [5, 7], [2]\}, XOR 5; As you can see, subset \{[5, 7], [2]\} has its XOR equal to 0, which is unacceptable. You can check that for other divisions of size 3 or 4, non-empty subset with 0 XOR always exists.The second example has no suitable divisions.The third example array can be divided into \{[3], [1], [10]\}. No subset of these segments has its XOR equal to 0. | 4
5 5 7 2
| 2 | 2 seconds | 256 megabytes | ['math', 'matrices', '*2300'] |
F. Trucks and Citiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities along the road, which can be represented as a straight line. The i-th city is situated at the distance of a_i kilometers from the origin. All cities are situated in the same direction from the origin. There are m trucks travelling from one city to another. Each truck can be described by 4 integers: starting city s_i, finishing city f_i, fuel consumption c_i and number of possible refuelings r_i. The i-th truck will spend c_i litres of fuel per one kilometer. When a truck arrives in some city, it can be refueled (but refueling is impossible in the middle of nowhere). The i-th truck can be refueled at most r_i times. Each refueling makes truck's gas-tank full. All trucks start with full gas-tank.All trucks will have gas-tanks of the same size V litres. You should find minimum possible V such that all trucks can reach their destinations without refueling more times than allowed.InputFirst line contains two integers n and m (2 \le n \le 400, 1 \le m \le 250000) — the number of cities and trucks.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9, a_i < a_{i+1}) — positions of cities in the ascending order.Next m lines contains 4 integers each. The i-th line contains integers s_i, f_i, c_i, r_i (1 \le s_i < f_i \le n, 1 \le c_i \le 10^9, 0 \le r_i \le n) — the description of the i-th truck.OutputPrint the only integer — minimum possible size of gas-tanks V such that all trucks can reach their destinations.ExampleInput
7 6
2 5 7 10 14 15 17
1 3 10 0
1 7 12 7
4 5 13 3
4 7 10 1
4 7 10 1
1 5 11 2
Output
55
NoteLet's look at queries in details: the 1-st truck must arrive at position 7 from 2 without refuelling, so it needs gas-tank of volume at least 50. the 2-nd truck must arrive at position 17 from 2 and can be refueled at any city (if it is on the path between starting point and ending point), so it needs gas-tank of volume at least 48. the 3-rd truck must arrive at position 14 from 10, there is no city between, so it needs gas-tank of volume at least 52. the 4-th truck must arrive at position 17 from 10 and can be refueled only one time: it's optimal to refuel at 5-th city (position 14) so it needs gas-tank of volume at least 40. the 5-th truck has the same description, so it also needs gas-tank of volume at least 40. the 6-th truck must arrive at position 14 from 2 and can be refueled two times: first time in city 2 or 3 and second time in city 4 so it needs gas-tank of volume at least 55. | 7 6
2 5 7 10 14 15 17
1 3 10 0
1 7 12 7
4 5 13 3
4 7 10 1
4 7 10 1
1 5 11 2
| 55 | 2 seconds | 256 megabytes | ['binary search', 'dp', '*2400'] |
E. Polycarp's New Jobtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).A bill x \times y fits into some wallet h \times w if either x \le h and y \le w or y \le h and x \le w. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.Now you are asked to perform the queries of two types: +~x~y — Polycarp earns a bill of size x \times y; ?~h~w — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h \times w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.For each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.InputThe first line contains a single integer n (2 \le n \le 5 \cdot 10^5) — the number of queries.Each of the next n lines contains a query of one of these two types: +~x~y (1 \le x, y \le 10^9) — Polycarp earns a bill of size x \times y; ?~h~w (1 \le h, w \le 10^9) — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size h \times w. It is guaranteed that there is at least one query of type 1 before the first query of type 2 and that there is at least one query of type 2 in the input data.OutputFor each query of type 2 print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.ExampleInput
9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
Output
NO
YES
YES
YES
NO
NoteThe queries of type 2 of the example: Neither bill fits; Both bills fit (just checking that you got that bills can overlap); Both bills fit (both bills are actually the same); All bills fit (too much of free space in a wallet is not a problem); Only bill 1 \times 5 fit (all the others don't, thus it's "NO"). | 9
+ 3 2
+ 2 3
? 1 20
? 3 3
? 2 3
+ 1 5
? 10 10
? 1 5
+ 1 1
| NO YES YES YES NO | 3 seconds | 256 megabytes | ['implementation', '*1500'] |
D. GCD Countingtime limit per test4.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let's denote dist(x, y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x, x) = 1 for every vertex x.Your task is calculate the maximum value of dist(x, y) among such pairs of vertices that g(x, y) > 1.InputThe first line contains one integer n — the number of vertices (1 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 2 \cdot 10^5) — the numbers written on vertices.Then n - 1 lines follow, each containing two integers x and y (1 \le x, y \le n, x \ne y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.OutputIf there is no pair of vertices x, y such that g(x, y) > 1, print 0. Otherwise print the maximum value of dist(x, y) among such pairs.ExamplesInput32 3 41 22 3Output1Input32 3 41 32 3Output2Input31 1 11 22 3Output0 | Input32 3 41 22 3 | Output1 | 4.5 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'dp', 'number theory', 'trees', '*2000'] |
C. Division and Uniontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n segments [l_i, r_i] for 1 \le i \le n. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group.To optimize testing process you will be given multitest.InputThe first line contains one integer T (1 \le T \le 50000) — the number of queries. Each query contains description of the set of segments. Queries are independent.First line of each query contains single integer n (2 \le n \le 10^5) — number of segments. It is guaranteed that \sum{n} over all queries does not exceed 10^5.The next n lines contains two integers l_i, r_i per line (1 \le l_i \le r_i \le 2 \cdot 10^5) — the i-th segment.OutputFor each query print n integers t_1, t_2, \dots, t_n (t_i \in \{1, 2\}) — for each segment (in the same order as in the input) t_i equals 1 if the i-th segment will belongs to the first group and 2 otherwise.If there are multiple answers, you can print any of them. If there is no answer, print -1.ExampleInput
3
2
5 5
2 3
3
3 5
2 3
2 3
3
3 3
4 4
5 5
Output
2 1
-1
1 1 2
NoteIn the first query the first and the second segments should be in different groups, but exact numbers don't matter.In the second query the third segment intersects with the first and the second segments, so they should be in the same group, but then the other group becomes empty, so answer is -1.In the third query we can distribute segments in any way that makes groups non-empty, so any answer of 6 possible is correct. | 3
2
5 5
2 3
3
3 5
2 3
2 3
3
3 3
4 4
5 5
| 2 1 -1 1 1 2 | 2 seconds | 256 megabytes | ['sortings', '*1500'] |
B. Accordiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn accordion is a string (yes, in the real world accordions are musical instruments, but let's forget about it for a while) which can be represented as a concatenation of: an opening bracket (ASCII code 091), a colon (ASCII code 058), some (possibly zero) vertical line characters (ASCII code 124), another colon, and a closing bracket (ASCII code 093). The length of the accordion is the number of characters in it.For example, [::], [:||:] and [:|||:] are accordions having length 4, 6 and 7. (:|:), {:||:}, [:], ]:||:[ are not accordions. You are given a string s. You want to transform it into an accordion by removing some (possibly zero) characters from it. Note that you may not insert new characters or reorder existing ones. Is it possible to obtain an accordion by removing characters from s, and if so, what is the maximum possible length of the result?InputThe only line contains one string s (1 \le |s| \le 500000). It consists of lowercase Latin letters and characters [, ], : and |.OutputIf it is not possible to obtain an accordion by removing some characters from s, print -1. Otherwise print maximum possible length of the resulting accordion.ExamplesInput
|[a:b:|]
Output
4
Input
|]:[|:]
Output
-1
| |[a:b:|]
| 4 | 3 seconds | 256 megabytes | ['greedy', 'implementation', '*1300'] |
A. Minimum Integertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given q queries in the following form:Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i].Can you answer all the queries?Recall that a number x belongs to segment [l, r] if l \le x \le r.InputThe first line contains one integer q (1 \le q \le 500) — the number of queries.Then q lines follow, each containing a query given in the format l_i r_i d_i (1 \le l_i \le r_i \le 10^9, 1 \le d_i \le 10^9). l_i, r_i and d_i are integers.OutputFor each query print one integer: the answer to this query.ExampleInput
5
2 4 2
5 10 4
3 10 1
1 2 3
4 6 5
Output
6
4
1
3
10
| 5
2 4 2
5 10 4
3 10 1
1 2 3
4 6 5
| 6 4 1 3 10 | 1 second | 256 megabytes | ['math', '*1000'] |
F. Ivan and Burgerstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan loves burgers and spending money. There are n burger joints on the street where Ivan lives. Ivan has q friends, and the i-th friend suggested to meet at the joint l_i and walk to the joint r_i (l_i \leq r_i). While strolling with the i-th friend Ivan can visit all joints x which satisfy l_i \leq x \leq r_i.For each joint Ivan knows the cost of the most expensive burger in it, it costs c_i burles. Ivan wants to visit some subset of joints on his way, in each of them he will buy the most expensive burger and spend the most money. But there is a small issue: his card broke and instead of charging him for purchases, the amount of money on it changes as follows.If Ivan had d burles before the purchase and he spent c burles at the joint, then after the purchase he would have d \oplus c burles, where \oplus denotes the bitwise XOR operation.Currently Ivan has 2^{2^{100}} - 1 burles and he wants to go out for a walk. Help him to determine the maximal amount of burles he can spend if he goes for a walk with the friend i. The amount of burles he spends is defined as the difference between the initial amount on his account and the final account.InputThe first line contains one integer n (1 \leq n \leq 500\,000) — the number of burger shops.The next line contains n integers c_1, c_2, \ldots, c_n (0 \leq c_i \leq 10^6), where c_i — the cost of the most expensive burger in the burger joint i.The third line contains one integer q (1 \leq q \leq 500\,000) — the number of Ivan's friends.Each of the next q lines contain two integers l_i and r_i (1 \leq l_i \leq r_i \leq n) — pairs of numbers of burger shops between which Ivan will walk. OutputOutput q lines, i-th of which containing the maximum amount of money Ivan can spend with the friend i.ExamplesInput47 2 3 431 42 31 3Output737Input512 14 23 13 7151 11 21 31 41 52 22 32 42 53 33 43 54 44 55 5Output12142727311425263023262913137NoteIn the first test, in order to spend the maximum amount of money with the first and third friends, Ivan just needs to go into the first burger. With a second friend, Ivan just go to the third burger.In the second test for a third friend (who is going to walk from the first to the third burger), there are only 8 options to spend money — 0, 12, 14, 23, 12 \oplus 14 = 2, 14 \oplus 23 = 25, 12 \oplus 23 = 27, 12 \oplus 14 \oplus 23 = 20. The maximum amount of money it turns out to spend, if you go to the first and third burger — 12 \oplus 23 = 27. | Input47 2 3 431 42 31 3 | Output737 | 3 seconds | 256 megabytes | ['data structures', 'divide and conquer', 'greedy', 'math', '*2500'] |
E. Andrew and Taxitime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to insidious taxi drivers.The mayor of the city decided to change the direction of certain roads so that the taxi drivers wouldn't be able to increase the cost of the trip endlessly. More formally, if the taxi driver is on a certain crossroads, they wouldn't be able to reach it again if he performs a nonzero trip. Traffic controllers are needed in order to change the direction the road goes. For every road it is known how many traffic controllers are needed to change the direction of the road to the opposite one. It is allowed to change the directions of roads one by one, meaning that each traffic controller can participate in reversing two or more roads.You need to calculate the minimum number of traffic controllers that you need to hire to perform the task and the list of the roads that need to be reversed.InputThe first line contains two integers n and m (2 \leq n \leq 100\,000, 1 \leq m \leq 100\,000) — the number of crossroads and the number of roads in the city, respectively.Each of the following m lines contain three integers u_{i}, v_{i} and c_{i} (1 \leq u_{i}, v_{i} \leq n, 1 \leq c_{i} \leq 10^9, u_{i} \ne v_{i}) — the crossroads the road starts at, the crossroads the road ends at and the number of traffic controllers required to reverse this road.OutputIn the first line output two integers the minimal amount of traffic controllers required to complete the task and amount of roads k which should be reversed. k should not be minimized.In the next line output k integers separated by spaces — numbers of roads, the directions of which should be reversed. The roads are numerated from 1 in the order they are written in the input. If there are many solutions, print any of them.ExamplesInput5 62 1 15 2 62 3 23 4 34 5 51 5 4Output2 21 3 Input5 72 1 53 2 31 3 32 4 14 3 55 4 11 5 3Output3 33 4 7 NoteThere are two simple cycles in the first example: 1 \rightarrow 5 \rightarrow 2 \rightarrow 1 and 2 \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow 2. One traffic controller can only reverse the road 2 \rightarrow 1 and he can't destroy the second cycle by himself. Two traffic controllers can reverse roads 2 \rightarrow 1 and 2 \rightarrow 3 which would satisfy the condition.In the second example one traffic controller can't destroy the cycle 1 \rightarrow 3 \rightarrow 2 \rightarrow 1 . With the help of three controllers we can, for example, reverse roads 1 \rightarrow 3 , 2 \rightarrow 4, 1 \rightarrow 5. | Input5 62 1 15 2 62 3 23 4 34 5 51 5 4 | Output2 21 3 | 2 seconds | 256 megabytes | ['binary search', 'dfs and similar', 'graphs', '*2200'] |
D. Dasha and Chesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive task.Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.There are 666 black rooks and 1 white king on the chess board of size 999 \times 999. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square (x, y), it can move to the square (nx, ny) if and only \max (|nx - x|, |ny - y|) = 1 , 1 \leq nx, ny \leq 999. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.Each player makes 2000 turns, if the white king wasn't checked by a black rook during those turns, black wins. NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.InputIn the beginning your program will receive 667 lines from input. Each line contains two integers x and y (1 \leq x, y \leq 999) — the piece's coordinates. The first line contains the coordinates of the king and the next 666 contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.OutputAfter getting king checked, you program should terminate immediately without printing anything extra.InteractionTo make a move with the king, output two integers x and y (1 \leq x, y \leq 999) — the square to which the king would be moved. The king cannot move onto the square already occupied by a rook. It is guaranteed that the king would always have a valid move.After each of your turns read the rook's turn in the following format: a single line containing three integers k, x and y (1 \leq k \leq 666, 1 \leq x_i, y_i \leq 999) — the number of the rook that would move and the square it would move to. It is guaranteed that the rook wouldn't move to a square already occupied by another chess piece, but it can move onto the square where it was before the turn so that its position wouldn't change. It is guaranteed that the move does not put your king into a check. If your king got in check, all three integers would be equal to -1 and in that case your program should terminate immediately.After printing your turn do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages.Answer "0 0 0" instead of a correct answer means that you made an invalid query. Exit immediately after receiving "0 0 0" and you will see Wrong answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.Hacks are not allowed for this problem.ExampleInput999 9991 11 22 12 21 32 3<...>26 1326 1426 1526 161 700 8002 1 2<...>-1 -1 -1Output999 998999 997<...>999 26NoteThe example is trimmed. The full initial positions of the rooks in the first test are available at https://pastebin.com/qQCTXgKP. It is not guaranteed that they will behave as in the example. | Input999 9991 11 22 12 21 32 3<...>26 1326 1426 1526 161 700 8002 1 2<...>-1 -1 -1 | Output999 998999 997<...>999 26 | 2 seconds | 256 megabytes | ['constructive algorithms', 'games', 'interactive', '*2500'] |
C. NN and the Optical Illusiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles: It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles n and the radius of the inner circle r. NN thinks that, using this information, you can exactly determine the radius of the outer circles R so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture.InputThe first and the only line of the input file contains two numbers n and r (3 \leq n \leq 100, 1 \leq r \leq 100) — the number of the outer circles and the radius of the inner circle respectively.OutputOutput a single number R — the radius of the outer circle required for building the required picture. Your answer will be accepted if its relative or absolute error does not exceed 10^{-6}.Formally, if your answer is a and the jury's answer is b. Your answer is accepted if and only when \frac{|a-b|}{max(1, |b|)} \le 10^{-6}.ExamplesInput3 1Output6.4641016Input6 1Output1.0000000Input100 100Output3.2429391 | Input3 1 | Output6.4641016 | 2 seconds | 256 megabytes | ['binary search', 'geometry', 'math', '*1200'] |
B. Build a Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady coordinates rounds on some not really famous competitive programming platform. Each round features n problems of distinct difficulty, the difficulties are numbered from 1 to n.To hold a round Arkady needs n new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from 1 to n and puts it into the problems pool.At each moment when Arkady can choose a set of n new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.InputThe first line contains two integers n and m (1 \le n, m \le 10^5) — the number of difficulty levels and the number of problems Arkady created.The second line contains m integers a_1, a_2, \ldots, a_m (1 \le a_i \le n) — the problems' difficulties in the order Arkady created them.OutputPrint a line containing m digits. The i-th digit should be 1 if Arkady held the round after creation of the i-th problem, and 0 otherwise.ExamplesInput
3 11
2 3 1 2 2 2 3 2 2 3 1
Output
00100000001
Input
4 8
4 1 3 3 2 3 3 3
Output
00001000
NoteIn the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem. | 3 11
2 3 1 2 2 2 3 2 2 3 1
| 00100000001 | 1 second | 256 megabytes | ['data structures', 'implementation', '*1300'] |
A. Roman and Browsertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.He decided to accomplish this by closing every k-th (2 \leq k \leq n - 1) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be b) and then close all tabs with numbers c = b + i \cdot k that satisfy the following condition: 1 \leq c \leq n and i is an integer (it may be positive, negative or zero).For example, if k = 3, n = 14 and Roman chooses b = 8, then he will close tabs with numbers 2, 5, 8, 11 and 14.After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it e) and the amount of remaining social network tabs (s). Help Roman to calculate the maximal absolute value of the difference of those values |e - s| so that it would be easy to decide what to do next.InputThe first line contains two integers n and k (2 \leq k < n \leq 100) — the amount of tabs opened currently and the distance between the tabs closed.The second line consists of n integers, each of them equal either to 1 or to -1. The i-th integer denotes the type of the i-th tab: if it is equal to 1, this tab contains information for the test, and if it is equal to -1, it's a social network tab.OutputOutput a single integer — the maximum absolute difference between the amounts of remaining tabs of different types |e - s|.ExamplesInput
4 2
1 1 -1 1
Output
2
Input
14 3
-1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1
Output
9
NoteIn the first example we can choose b = 1 or b = 3. We will delete then one tab of each type and the remaining tabs are then all contain test information. Thus, e = 2 and s = 0 and |e - s| = 2.In the second example, on the contrary, we can leave opened only tabs that have social networks opened in them. | 4 2
1 1 -1 1
| 2 | 1 second | 256 megabytes | ['implementation', '*1000'] |
F. Cookiestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMitya and Vasya are playing an interesting game. They have a rooted tree with n vertices, and the vertices are indexed from 1 to n. The root has index 1. Every other vertex i \ge 2 has its parent p_i, and vertex i is called a child of vertex p_i.There are some cookies in every vertex of the tree: there are x_i cookies in vertex i. It takes exactly t_i time for Mitya to eat one cookie in vertex i. There is also a chip, which is initially located in the root of the tree, and it takes l_i time to move the chip along the edge connecting vertex i with its parent.Mitya and Vasya take turns playing, Mitya goes first. Mitya moves the chip from the vertex, where the chip is located, to one of its children. Vasya can remove an edge from the vertex, where the chip is located, to one of its children. Vasya can also decide to skip his turn. Mitya can stop the game at any his turn. Once he stops the game, he moves the chip up to the root, eating some cookies along his way. Mitya can decide how many cookies he would like to eat in every vertex on his way. The total time spent on descend, ascend and eating cookies should not exceed T. Please note that in the end of the game the chip is always located in the root of the tree: Mitya can not leave the chip in any other vertex, even if he has already eaten enough cookies — he must move the chip back to the root (and every move from vertex v to its parent takes l_v time).Find out what is the maximum number of cookies Mitya can eat, regardless of Vasya's actions.InputThe first line contains two integers n and T — the number of vertices in the tree and the time he has to accomplish his task (2\le n \le 10^5; 1\le T\le10^{18}).The second line contains n integers x_1, x_2, ..., x_n — number of cookies located in the corresponding vertex (1\le x_i\le10^6). The third line contains n integers t_1, t_2, ..., t_n — how much time it takes Mitya to eat one cookie in vertex i (1\le t_i\le10^6).Each of the following n - 1 lines describe the tree. For every i from 2 to n, the corresponding line contains two integers p_i and l_i, where p_i denotes the parent of vertex i and l_i denotes the time it takes Mitya to move the chip along the edge from vertex i to its parent (1\le p_i < i, 0\le l_i \le 10^9).OutputOutput a single integer — maximum number of cookies Mitya can eat.ExamplesInput
5 26
1 5 1 7 7
1 3 2 2 2
1 1
1 1
2 0
2 0
Output
11
Input
3 179
2 2 1
6 6 6
1 3
2 3
Output
4
NoteIn the first example test case, Mitya can start by moving the chip to vertex 2. In this case no matter how Vasya plays, Mitya is able to eat at least 11 cookies. Below you can find the detailed description of the moves: Mitya moves chip to vertex 2. Vasya removes edge to vertex 4. Mitya moves chip to vertex 5. Since vertex 5 has no children, Vasya does not remove any edges. Mitya stops the game and moves the chip towards the root, eating cookies along the way (7 in vertex 5, 3 in vertex 2, 1 in vertex 1). Mitya spend 1+0 time to go down, 0+1 to go up, 7\cdot 2 to eat 7 cookies in vertex 5, 3\cdot 3 to eat 3 cookies in vertex 2, 1\cdot 1 to eat 1 cookie in vertex 1. Total time is 1+0+0+1+7\cdot 2+3\cdot 3+1\cdot 1=26. | 5 26
1 5 1 7 7
1 3 2 2 2
1 1
1 1
2 0
2 0
| 11 | 3 seconds | 512 megabytes | ['binary search', 'data structures', 'dfs and similar', 'dp', 'games', 'trees', '*2400'] |
C. Postcardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrey received a postcard from Irina. It contained only the words "Hello, Andrey!", and a strange string consisting of lowercase Latin letters, snowflakes and candy canes. Andrey thought that this string is an encrypted message, and decided to decrypt it.Andrey noticed that snowflakes and candy canes always stand after the letters, so he supposed that the message was encrypted as follows. Candy cane means that the letter before it can be removed, or can be left. A snowflake means that the letter before it can be removed, left, or repeated several times.For example, consider the following string: This string can encode the message «happynewyear». For this, candy canes and snowflakes should be used as follows: candy cane 1: remove the letter w, snowflake 1: repeat the letter p twice, candy cane 2: leave the letter n, snowflake 2: remove the letter w, snowflake 3: leave the letter e. Please note that the same string can encode different messages. For example, the string above can encode «hayewyar», «happpppynewwwwwyear», and other messages.Andrey knows that messages from Irina usually have a length of k letters. Help him to find out if a given string can encode a message of k letters, and if so, give an example of such a message.InputThe first line contains the string received in the postcard. The string consists only of lowercase Latin letters, as well as the characters «*» and «?», meaning snowflake and candy cone, respectively. These characters can only appear immediately after the letter. The length of the string does not exceed 200.The second line contains an integer number k (1 \leq k \leq 200), the required message length.OutputPrint any message of length k that the given string can encode, or «Impossible» if such a message does not exist.ExamplesInput
hw?ap*yn?eww*ye*ar
12
Output
happynewyear
Input
ab?a
2
Output
aaInput
ab?a
3
Output
abaInput
ababb
5
Output
ababbInput
ab?a
1
Output
Impossible | hw?ap*yn?eww*ye*ar
12
| happynewyear | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1200'] |
B. Squares and Segmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Sofia is in fourth grade. Today in the geometry lesson she learned about segments and squares. On the way home, she decided to draw n squares in the snow with a side length of 1. For simplicity, we assume that Sofia lives on a plane and can draw only segments of length 1, parallel to the coordinate axes, with vertices at integer points.In order to draw a segment, Sofia proceeds as follows. If she wants to draw a vertical segment with the coordinates of the ends (x, y) and (x, y+1). Then Sofia looks if there is already a drawn segment with the coordinates of the ends (x', y) and (x', y+1) for some x'. If such a segment exists, then Sofia quickly draws a new segment, using the old one as a guideline. If there is no such segment, then Sofia has to take a ruler and measure a new segment for a long time. Same thing happens when Sofia wants to draw a horizontal segment, but only now she checks for the existence of a segment with the same coordinates x, x+1 and the differing coordinate y.For example, if Sofia needs to draw one square, she will have to draw two segments using a ruler: After that, she can draw the remaining two segments, using the first two as a guide: If Sofia needs to draw two squares, she will have to draw three segments using a ruler: After that, she can draw the remaining four segments, using the first three as a guide: Sofia is in a hurry, so she wants to minimize the number of segments that she will have to draw with a ruler without a guide. Help her find this minimum number.InputThe only line of input contains a single integer n (1 \le n \le 10^{9}), the number of squares that Sofia wants to draw.OutputPrint single integer, the minimum number of segments that Sofia will have to draw with a ruler without a guide in order to draw n squares in the manner described above.ExamplesInput
1
Output
2
Input
2
Output
3
Input
4
Output
4
| 1
| 2 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'math', '*1100'] |
A. Snowballtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain.Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i, where i — is the current height of snowball, then snowball hits the stone (if it's present at the current height), then snowball moves one meter down. If the snowball reaches height zero, it stops.There are exactly two stones on the mountain. First stone has weight u_1 and is located at height d_1, the second one — u_2 and d_2 respectively. When the snowball hits either of two stones, it loses weight equal to the weight of that stone. If after this snowball has negative weight, then its weight becomes zero, but the snowball continues moving as before. Find the weight of the snowball when it stops moving, that is, it reaches height 0.InputFirst line contains two integers w and h — initial weight and height of the snowball (0 \le w \le 100; 1 \le h \le 100).Second line contains two integers u_1 and d_1 — weight and height of the first stone (0 \le u_1 \le 100; 1 \le d_1 \le h).Third line contains two integers u_2 and d_2 — weight and heigth of the second stone (0 \le u_2 \le 100; 1 \le d_2 \le h; d_1 \ne d_2). Notice that stones always have different heights.OutputOutput a single integer — final weight of the snowball after it reaches height 0.ExamplesInput
4 3
1 1
1 2
Output
8Input
4 3
9 2
0 1
Output
1NoteIn the first example, initially a snowball of weight 4 is located at a height of 3, there are two stones of weight 1, at a height of 1 and 2, respectively. The following events occur sequentially: The weight of the snowball increases by 3 (current height), becomes equal to 7. The snowball moves one meter down, the current height becomes equal to 2. The weight of the snowball increases by 2 (current height), becomes equal to 9. The snowball hits the stone, its weight decreases by 1 (the weight of the stone), becomes equal to 8. The snowball moves one meter down, the current height becomes equal to 1. The weight of the snowball increases by 1 (current height), becomes equal to 9. The snowball hits the stone, its weight decreases by 1 (the weight of the stone), becomes equal to 8. The snowball moves one meter down, the current height becomes equal to 0. Thus, at the end the weight of the snowball is equal to 8. | 4 3
1 1
1 2
| 8 | 1 second | 256 megabytes | ['implementation', '*800'] |
F. Ж-functiontime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe length of the longest common prefix of two strings s=s_1 s_2 \ldots s_n and t = t_1 t_2 \ldots t_m is defined as the maximum k \le \min(n, m) such that s_1 s_2 \ldots s_k equals t_1 t_2 \ldots t_k. Let's denote the longest common prefix of two strings s and t as lcp(s,t).Z-function of a string s_1 s_2 \dots s_n is a sequence of integers z_1, z_2, \ldots, z_n, where z_i = lcp(s_1 s_2 \ldots s_n,\ \ s_i s_{i+1} \dots s_n). Ж-function of a string s is defined as z_1 + z_2 + \ldots + z_n.You're given a string s=s_1 s_2 \ldots s_n and q queries. Each query is described by two integers l_i and r_i, where 1 \le l_i \le r_i \le n. The answer for the query is defined as Ж-function of the string s_{l_i} s_{l_i +1} \ldots s_{r_i}.InputThe first line contains the string s, consisting of lowercase English letters (1 \leq |s| \leq 200\,000). The second line contains one integer q — the number of queries (1 \leq q \leq 200\,000). Each of the following q lines contains two integers l_i and r_i, describing the query (1 \leq l_i \leq r_i \leq |s|).OutputFor every query output one integer: the value of Ж-function of the corresponding substring.ExamplesInput
abbd
4
2 3
1 3
3 3
1 4
Output
3
3
1
4
Input
bbaaa
5
2 4
1 5
1 5
3 3
1 2
Output
3
6
6
1
3
NoteIn the first sample case there are four queries: the first query corresponds to the substring bb, and its Ж-function equals 2 + 1 = 3; the second query corresponds to the substring abb, and its Ж-function equals 3 + 0 + 0 = 3; the third query corresponds to the substring b, and its Ж-function equals 1. the fourth query corresponds to the substring abdd, and its Ж-function equals 4 + 0 + 0 + 0= 4. | abbd
4
2 3
1 3
3 3
1 4
| 3 3 1 4 | 6 seconds | 512 megabytes | ['string suffix structures', 'strings', '*3500'] |
E. Fedya the Pottertime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya loves problems involving data structures. Especially ones about different queries on subsegments. Fedya had a nice array a_1, a_2, \ldots a_n and a beautiful data structure. This data structure, given l and r, 1 \le l \le r \le n, could find the greatest integer d, such that d divides each of a_l, a_{l+1}, ..., a_{r}. Fedya really likes this data structure, so he applied it to every non-empty contiguous subarray of array a, put all answers into the array and sorted it. He called this array b. It's easy to see that array b contains n(n+1)/2 elements.After that, Fedya implemented another cool data structure, that allowed him to find sum b_l + b_{l+1} + \ldots + b_r for given l and r, 1 \le l \le r \le n(n+1)/2. Surely, Fedya applied this data structure to every contiguous subarray of array b, called the result c and sorted it. Help Fedya find the lower median of array c.Recall that for a sorted array of length k the lower median is an element at position \lfloor \frac{k + 1}{2} \rfloor, if elements of the array are enumerated starting from 1. For example, the lower median of array (1, 1, 2, 3, 6) is 2, and the lower median of (0, 17, 23, 96) is 17.InputFirst line contains a single integer n — number of elements in array a (1 \le n \le 50\,000). Second line contains n integers a_1, a_2, \ldots, a_n — elements of the array (1 \le a_i \le 100\,000).OutputPrint a single integer — the lower median of array c.ExamplesInput
2
6 3
Output
6
Input
2
8 8
Output
8
Input
5
19 16 2 12 15
Output
12
NoteIn the first sample array b is equal to {3, 3, 6}, then array c is equal to {3, 3, 6, 6, 9, 12}, so the lower median is 6.In the second sample b is {8, 8, 8}, c is {8, 8, 8, 16, 16, 24}, so the lower median is 8. | 2
6 3
| 6 | 2.5 seconds | 256 megabytes | ['binary search', 'implementation', 'math', 'number theory', '*3400'] |
D. Eelstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is a big fish lover, and his parents gave him an aquarium for the New Year. Vasya does not have a degree in ichthyology, so he thinks that filling a new aquarium with eels is a good idea. Unfortunately, eels are predators, so Vasya decided to find out how dangerous this idea was.Getting into one aquarium, eels fight each other until exactly one fish remains. When two eels fight, the big one eats the smaller one (if their weights are equal, then one of them will still eat the other). Namely, let n eels be initially in an aquarium, and the i-th of them have a weight of x_i. Then n-1 battles will occur between them, as a result of which, only one eel will survive. In a battle of two eels with weights a and b, where a \le b, eel of weight a will be eaten and disappear from the aquarium, and eel of weight b will increase its weight to a+b.A battle between two eels with weights a and b, where a \le b, is considered dangerous if b \le 2 a. For a given set of eels, danger is defined as the maximum number of dangerous battles that can occur among these eels if they are placed in one aquarium.Now Vasya is planning, which eels he wants to put into an aquarium. He has some set of eels (initially empty). He makes a series of operations with this set. With each operation, he either adds one eel in the set, or removes one eel from the set. Vasya asks you to calculate the danger of the current set of eels after each operation.InputThe first line of input contains a single integer q (1 \le q \le 500\,000), the number of operations that Vasya makes. The next q lines describe operations. Each operation has one of two types : + x describes the addition of one eel of weight x to the set (1 \le x \le 10^9). Note that in the set there can be several eels of the same weight. - x describes the removal of one eel of weight x from a set, and it is guaranteed that there is a eel of such weight in the set. OutputFor each operation, output single integer, the danger of the set of eels after this operation.ExamplesInput
2
+ 1
- 1
Output
0
0
Input
4
+ 1
+ 3
+ 7
- 3
Output
0
0
1
0
Input
9
+ 2
+ 2
+ 12
- 2
- 2
+ 4
+ 1
+ 1
- 12
Output
0
1
1
0
0
0
0
3
2
NoteIn the third example, after performing all the operations, the set of eels looks like \{1, 1, 4\}. For this set of eels, there are several possible scenarios, if all of them are placed in one aquarium: The eel of weight 4 eats the eel of weight 1, and then the second eel of weight 1. In this case, none of the battles are dangerous. The eel of weight 1 eats the eel of weight 1, and this battle is dangerous. Now there are two eels in the aquarium, their weights are 4 and 2. The big one eats the small one, and this battle is also dangerous. In this case, the total number of dangerous battles will be 2. Thus, the danger of this set of eels is 2. | 2
+ 1
- 1
| 0 0 | 3 seconds | 256 megabytes | ['data structures', '*2800'] |
C. Construct a treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisha walked through the snowy forest and he was so fascinated by the trees to decide to draw his own tree!Misha would like to construct a rooted tree with n vertices, indexed from 1 to n, where the root has index 1. Every other vertex has a parent p_i, and i is called a child of vertex p_i. Vertex u belongs to the subtree of vertex v iff v is reachable from u while iterating over the parents (u, p_{u}, p_{p_{u}}, ...). Clearly, v belongs to its own subtree, and the number of vertices in the subtree is called the size of the subtree. Misha is only interested in trees where every vertex belongs to the subtree of vertex 1.Below there is a tree with 6 vertices. The subtree of vertex 2 contains vertices 2, 3, 4, 5. Hence the size of its subtree is 4. The branching coefficient of the tree is defined as the maximum number of children in any vertex. For example, for the tree above the branching coefficient equals 2. Your task is to construct a tree with n vertices such that the sum of the subtree sizes for all vertices equals s, and the branching coefficient is minimum possible.InputThe only input line contains two integers n and s — the number of vertices in the tree and the desired sum of the subtree sizes (2 \le n \le 10^5; 1 \le s \le 10^{10}).OutputIf the required tree does not exist, output «No». Otherwise output «Yes» on the first line, and in the next one output integers p_2, p_3, ..., p_n, where p_i denotes the parent of vertex i.ExamplesInput
3 5
Output
Yes
1 1
Input
4 42
Output
No
Input
6 15
Output
Yes
1 2 3 1 5
NoteBelow one can find one of the possible solutions for the first sample case. The sum of subtree sizes equals 3 + 1 + 1 = 5, and the branching coefficient equals 2. Below one can find one of the possible solutions for the third sample case. The sum of subtree sizes equals 6 + 3 + 2 + 1 + 2 + 1 = 15, and the branching coefficient equals 2. | 3 5
| Yes 1 1 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'dfs and similar', 'graphs', 'greedy', 'trees', '*2400'] |
B. Nice tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an n \times m table, consisting of characters «A», «G», «C», «T». Let's call a table nice, if every 2 \times 2 square contains all four distinct characters. Your task is to find a nice table (also consisting of «A», «G», «C», «T»), that differs from the given table in the minimum number of characters.InputFirst line contains two positive integers n and m — number of rows and columns in the table you are given (2 \leq n, m, n \times m \leq 300\,000). Then, n lines describing the table follow. Each line contains exactly m characters «A», «G», «C», «T».OutputOutput n lines, m characters each. This table must be nice and differ from the input table in the minimum number of characters.ExamplesInput
2 2
AG
CT
Output
AG
CT
Input
3 5
AGCAG
AGCAG
AGCAG
Output
TGCAT
CATGC
TGCAT
NoteIn the first sample, the table is already nice. In the second sample, you can change 9 elements to make the table nice. | 2 2
AG
CT
| AG CT | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'math', '*2100'] |
A. Sum in the treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v \ge 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1.Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree.InputThe first line contains one integer n — the number of vertices in the tree (2 \le n \le 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 \le p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 \le s_v \le 10^9), where erased values are replaced by -1.OutputOutput one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist.ExamplesInput
5
1 1 1 1
1 -1 -1 -1 -1
Output
1
Input
5
1 2 3 1
1 -1 2 -1 -1
Output
2
Input
3
1 2
2 -1 1
Output
-1
| 5
1 1 1 1
1 -1 -1 -1 -1
| 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'greedy', 'trees', '*1600'] |
H. Mateusz and an Infinite Sequencetime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA Thue-Morse-Radecki-Mateusz sequence (Thorse-Radewoosh sequence in short) is an infinite sequence constructed from a finite sequence \mathrm{gen} of length d and an integer m, obtained in the following sequence of steps: In the beginning, we define the one-element sequence M_0=(0). In the k-th step, k \geq 1, we define the sequence M_k to be the concatenation of the d copies of M_{k-1}. However, each of them is altered slightly — in the i-th of them (1 \leq i \leq d), each element x is changed to (x+\mathrm{gen}_i) \pmod{m}. For instance, if we pick \mathrm{gen} = (0, \color{blue}{1}, \color{green}{2}) and m = 4: M_0 = (0), M_1 = (0, \color{blue}{1}, \color{green}{2}), M_2 = (0, 1, 2, \color{blue}{1, 2, 3}, \color{green}{2, 3, 0}), M_3 = (0, 1, 2, 1, 2, 3, 2, 3, 0, \color{blue}{1, 2, 3, 2, 3, 0, 3, 0, 1}, \color{green}{2, 3, 0, 3, 0, 1, 0, 1, 2}), and so on. As you can see, as long as the first element of \mathrm{gen} is 0, each consecutive step produces a sequence whose prefix is the sequence generated in the previous step. Therefore, we can define the infinite Thorse-Radewoosh sequence M_\infty as the sequence obtained by applying the step above indefinitely. For the parameters above, M_\infty = (0, 1, 2, 1, 2, 3, 2, 3, 0, 1, 2, 3, 2, 3, 0, 3, 0, 1, \dots).Mateusz picked a sequence \mathrm{gen} and an integer m, and used them to obtain a Thorse-Radewoosh sequence M_\infty. He then picked two integers l, r, and wrote down a subsequence of this sequence A := ((M_\infty)_l, (M_\infty)_{l+1}, \dots, (M_\infty)_r).Note that we use the 1-based indexing both for M_\infty and A.Mateusz has his favorite sequence B with length n, and would like to see how large it is compared to A. Let's say that B majorizes sequence X of length n (let's denote it as B \geq X) if and only if for all i \in \{1, 2, \dots, n\}, we have B_i \geq X_i.He now asks himself how many integers x in the range [1, |A| - n + 1] there are such that B \geq (A_x, A_{x+1}, A_{x+2}, \dots, A_{x+n-1}). As both sequences were huge, answering the question using only his pen and paper turned out to be too time-consuming. Can you help him automate his research?InputThe first line contains two integers d and m (2 \leq d \leq 20, 2 \leq m \leq 60) — the length of the sequence \mathrm{gen} and an integer used to perform the modular operations. The second line contains d integers \mathrm{gen}_i (0 \leq \mathrm{gen}_i < m). It's guaranteed that the first element of the sequence \mathrm{gen} is equal to zero.The third line contains one integer n (1 \leq n \leq 30000) — the length of the sequence B. The fourth line contains n integers B_i (0 \leq B_i < m). The fifth line contains two integers l and r (1 \leq l \leq r \leq 10^{18}, r-l+1 \geq n).OutputPrint a single integer — the answer to the problem.ExamplesInput
2 2
0 1
4
0 1 1 0
2 21
Output
6
Input
3 4
0 1 2
2
0 2
6 11
Output
1
NoteThorse-Radewoosh sequence in the first example is the standard Thue-Morse sequence, so the sequence A is as follows: 11010011001011010010. Here are the places where the sequence B majorizes A: | 2 2
0 1
4
0 1 1 0
2 21
| 6 | 7 seconds | 512 megabytes | ['bitmasks', 'brute force', 'dp', 'strings', '*3400'] |
G. Vladislav and a Great Legendtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA great legend used to be here, but some troll hacked Codeforces and erased it. Too bad for us, but in the troll society he earned a title of an ultimate-greatest-over troll. At least for them, it's something good. And maybe a formal statement will be even better for us?You are given a tree T with n vertices numbered from 1 to n. For every non-empty subset X of vertices of T, let f(X) be the minimum number of edges in the smallest connected subtree of T which contains every vertex from X.You're also given an integer k. You need to compute the sum of (f(X))^k among all non-empty subsets of vertices, that is: \sum\limits_{X \subseteq \{1, 2,\: \dots \:, n\},\, X \neq \varnothing} (f(X))^k. As the result might be very large, output it modulo 10^9 + 7.InputThe first line contains two integers n and k (2 \leq n \leq 10^5, 1 \leq k \leq 200) — the size of the tree and the exponent in the sum above.Each of the following n - 1 lines contains two integers a_i and b_i (1 \leq a_i,b_i \leq n) — the indices of the vertices connected by the corresponding edge.It is guaranteed, that the edges form a tree.OutputPrint a single integer — the requested sum modulo 10^9 + 7.ExamplesInput
4 1
1 2
2 3
2 4
Output
21
Input
4 2
1 2
2 3
2 4
Output
45
Input
5 3
1 2
2 3
3 4
4 5
Output
780
NoteIn the first two examples, the values of f are as follows:f(\{1\}) = 0f(\{2\}) = 0f(\{1, 2\}) = 1f(\{3\}) = 0f(\{1, 3\}) = 2f(\{2, 3\}) = 1f(\{1, 2, 3\}) = 2f(\{4\}) = 0f(\{1, 4\}) = 2f(\{2, 4\}) = 1f(\{1, 2, 4\}) = 2f(\{3, 4\}) = 2f(\{1, 3, 4\}) = 3f(\{2, 3, 4\}) = 2f(\{1, 2, 3, 4\}) = 3 | 4 1
1 2
2 3
2 4
| 21 | 3 seconds | 512 megabytes | ['combinatorics', 'dp', 'trees', '*3000'] |
F. Alex and a TV Showtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex decided to try his luck in TV shows. He once went to the quiz named "What's That Word?!". After perfectly answering the questions "How is a pseudonym commonly referred to in the Internet?" ("Um... a nick?"), "After which famous inventor we name the unit of the magnetic field strength?" ("Um... Nikola Tesla?") and "Which rock band performs "How You Remind Me"?" ("Um... Nickelback?"), he decided to apply to a little bit more difficult TV show: "What's in This Multiset?!".The rules of this TV show are as follows: there are n multisets numbered from 1 to n. Each of them is initially empty. Then, q events happen; each of them is in one of the four possible types: 1 x v — set the x-th multiset to a singleton \{v\}. 2 x y z — set the x-th multiset to a union of the y-th and the z-th multiset. For example: \{1, 3\}\cup\{1, 4, 4\}=\{1, 1, 3, 4, 4\}. 3 x y z — set the x-th multiset to a product of the y-th and the z-th multiset. The product A \times B of two multisets A, B is defined as \{ \gcd(a, b)\, \mid\, a \in A,\, b \in B \}, where \gcd(p, q) is the greatest common divisor of p and q. For example: \{2, 2, 3\} \times \{1, 4, 6\}=\{1, 2, 2, 1, 2, 2, 1, 1, 3\}. 4 x v — the participant is asked how many times number v occurs in the x-th multiset. As the quiz turned out to be too hard in the past, participants should now give the answers modulo 2 only. Note, that x, y and z described above are not necessarily different. In events of types 2 and 3, the sum or the product is computed first, and then the assignment is performed.Alex is confused by the complicated rules of the show. Can you help him answer the requests of the 4-th type?InputThe first line contains two integers n and q (1 \leq n \leq 10^5, 1 \leq q \leq 10^6) — the number of multisets and the number of events.Each of the following q lines describes next event in the format given in statement. It's guaranteed that 1 \leq x,y,z \leq n and 1 \leq v \leq 7000 always holds.It's guaranteed that there will be at least one event of the 4-th type.OutputPrint a string which consists of digits 0 and 1 only, and has length equal to the number of events of the 4-th type. The i-th digit of the string should be equal to the answer for the i-th query of the 4-th type.ExampleInput
4 13
1 1 1
1 2 4
1 3 6
4 4 4
1 4 4
2 2 1 2
2 3 3 4
4 4 4
3 2 2 3
4 2 1
4 2 2
4 2 3
4 2 4
Output
010101
NoteHere is how the multisets look in the example test after each of the events; i is the number of queries processed so far: | 4 13
1 1 1
1 2 4
1 3 6
4 4 4
1 4 4
2 2 1 2
2 3 3 4
4 4 4
3 2 2 3
4 2 1
4 2 2
4 2 3
4 2 4
| 010101 | 3 seconds | 256 megabytes | ['bitmasks', 'combinatorics', 'number theory', '*2500'] |
E. Egor and an RPG gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne Saturday afternoon Egor was playing his favorite RPG game. While discovering new lands and territories, he came across the following sign: Egor is a passionate player, but he is an algorithmician as well. That's why he instantly spotted four common letters in two words on the sign above — if we permute the letters "R", "E", "G", "O" from the first word, we can obtain the letters "O", "G", "R", "E". Egor got inspired by the sign and right away he came up with a problem about permutations.You are given a permutation of length n. You have to split it into some non-empty subsequences so that each element of the permutation belongs to exactly one subsequence. Each subsequence must be monotonic — that is, either increasing or decreasing.Sequence is called to be a subsequence if it can be derived from permutation by deleting some (possibly none) elements without changing the order of the remaining elements.The number of subsequences should be small enough — let f(n) be the minimum integer k such that every permutation of length n can be partitioned into at most k monotonic subsequences.You need to split the permutation into at most f(n) monotonic subsequences.InputThe first line contains one integer t (1 \leq t \leq 10^5) — the number of test cases.You can only use t = 1 in hacks.Next, descriptions of t test cases come, each of them in the following format.The first line of a single test case contains one integer n (1 \leq n \leq 10^5) — the length of the permutation. The second line contains n distinct integers a_i (1 \leq a_i \leq n) — the permutation itself.The sum of the values of n over all test cases doesn't exceed 10^5.OutputFor each test case print the answer in the following format:In the first line print k (1 \leq k \leq f(n)) — the number of the subsequences in the partition. In the next k lines, print the descriptions of found subsequences. Each description should start with a number l_i (1 \leq l_i \leq n) — the length of the corresponding subsequence, followed by l_i integers — the values of this subsequence in the order in which they occur in the permutation.Each subsequence you output must be either increasing or decreasing. In case there are multiple possible answers, print any of them.ExampleInput
3
4
4 3 1 2
6
4 5 6 1 3 2
10
1 2 3 4 5 6 7 8 9 10
Output
2
3 4 3 1
1 2
3
2 4 1
2 5 6
2 3 2
1
10 1 2 3 4 5 6 7 8 9 10
NoteIn the example, we can split: [4, 3, 1, 2] into [4, 3, 1], [2] [4, 5, 6, 1, 3, 2] into [4, 1], [5, 6] and [3, 2] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] into [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Surely, there are many more answers possible. | 3
4
4 3 1 2
6
4 5 6 1 3 2
10
1 2 3 4 5 6 7 8 9 10
| 2 3 4 3 1 1 2 3 2 4 1 2 5 6 2 3 2 1 10 1 2 3 4 5 6 7 8 9 10 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*3400'] |
D. Makoto and a Blackboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMakoto has a big blackboard with a positive integer n written on it. He will perform the following action exactly k times:Suppose the number currently written on the blackboard is v. He will randomly pick one of the divisors of v (possibly 1 and v) and replace v with this divisor. As Makoto uses his famous random number generator (RNG) and as he always uses 58 as his generator seed, each divisor is guaranteed to be chosen with equal probability.He now wonders what is the expected value of the number written on the blackboard after k steps.It can be shown that this value can be represented as \frac{P}{Q} where P and Q are coprime integers and Q \not\equiv 0 \pmod{10^9+7}. Print the value of P \cdot Q^{-1} modulo 10^9+7.InputThe only line of the input contains two integers n and k (1 \leq n \leq 10^{15}, 1 \leq k \leq 10^4).OutputPrint a single integer — the expected value of the number on the blackboard after k steps as P \cdot Q^{-1} \pmod{10^9+7} for P, Q defined above.ExamplesInput
6 1
Output
3
Input
6 2
Output
875000008
Input
60 5
Output
237178099
NoteIn the first example, after one step, the number written on the blackboard is 1, 2, 3 or 6 — each occurring with equal probability. Hence, the answer is \frac{1+2+3+6}{4}=3.In the second example, the answer is equal to 1 \cdot \frac{9}{16}+2 \cdot \frac{3}{16}+3 \cdot \frac{3}{16}+6 \cdot \frac{1}{16}=\frac{15}{8}. | 6 1
| 3 | 2 seconds | 256 megabytes | ['dp', 'math', 'number theory', 'probabilities', '*2200'] |
C. Yuhao and a Parenthesistime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?InputThe first line contains one integer n (1 \leq n \leq 10^5) — the number of bracket sequences.Each of the following n lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")".The sum of lengths of all bracket sequences in the input is at most 5 \cdot 10^5.Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.OutputPrint a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.ExamplesInput
7
)())
)
((
((
(
)
)
Output
2
Input
4
(
((
(((
(())
Output
0
Input
2
(())
()
Output
1
NoteIn the first example, it's optimal to construct two pairs: "(( )())" and "( )". | 7
)())
)
((
((
(
)
)
| 2 | 2 seconds | 256 megabytes | ['greedy', 'implementation', '*1400'] |
B. Petr and a Combination Locktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero: Petr called his car dealer, who instructed him to rotate the lock's wheel exactly n times. The i-th rotation should be a_i degrees, either clockwise or counterclockwise, and after all n rotations the pointer should again point at zero.This confused Petr a little bit as he isn't sure which rotations should be done clockwise and which should be done counterclockwise. As there are many possible ways of rotating the lock, help him and find out whether there exists at least one, such that after all n rotations the pointer will point at zero again.InputThe first line contains one integer n (1 \leq n \leq 15) — the number of rotations.Each of the following n lines contains one integer a_i (1 \leq a_i \leq 180) — the angle of the i-th rotation in degrees.OutputIf it is possible to do all the rotations so that the pointer will point at zero after all of them are performed, print a single word "YES". Otherwise, print "NO". Petr will probably buy a new car in this case.You can print each letter in any case (upper or lower).ExamplesInput
3
10
20
30
Output
YES
Input
3
10
10
10
Output
NO
Input
3
120
120
120
Output
YES
NoteIn the first example, we can achieve our goal by applying the first and the second rotation clockwise, and performing the third rotation counterclockwise.In the second example, it's impossible to perform the rotations in order to make the pointer point at zero in the end.In the third example, Petr can do all three rotations clockwise. In this case, the whole wheel will be rotated by 360 degrees clockwise and the pointer will point at zero again. | 3
10
20
30
| YES | 1 second | 256 megabytes | ['bitmasks', 'brute force', 'dp', '*1200'] |
A. Gennady and a Card Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or Hearts — H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.InputThe first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand.Each string is two characters long. The first character denotes the rank and belongs to the set \{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}. The second character denotes the suit and belongs to the set \{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}.All the cards in the input are different.OutputIf it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO".You can print each letter in any case (upper or lower).ExamplesInput
AS
2H 4C TH JH AD
Output
YES
Input
2H
3D 4C AC KD AS
Output
NO
Input
4D
AS AC AD AH 5H
Output
YES
NoteIn the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.In the second example, you cannot play any card.In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table. | AS
2H 4C TH JH AD
| YES | 1 second | 256 megabytes | ['brute force', 'implementation', '*800'] |
G. Lucky Ticketstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAll bus tickets in Berland have their numbers. A number consists of n digits (n is even). Only k decimal digits d_1, d_2, \dots, d_k can be used to form ticket numbers. If 0 is among these digits, then numbers may have leading zeroes. For example, if n = 4 and only digits 0 and 4 can be used, then 0000, 4004, 4440 are valid ticket numbers, and 0002, 00, 44443 are not.A ticket is lucky if the sum of first n / 2 digits is equal to the sum of remaining n / 2 digits. Calculate the number of different lucky tickets in Berland. Since the answer may be big, print it modulo 998244353.InputThe first line contains two integers n and k (2 \le n \le 2 \cdot 10^5, 1 \le k \le 10) — the number of digits in each ticket number, and the number of different decimal digits that may be used. n is even.The second line contains a sequence of pairwise distinct integers d_1, d_2, \dots, d_k (0 \le d_i \le 9) — the digits that may be used in ticket numbers. The digits are given in arbitrary order.OutputPrint the number of lucky ticket numbers, taken modulo 998244353.ExamplesInput4 21 8Output6Input20 16Output1Input10 56 1 4 0 3Output569725Input1000 75 4 0 1 8 3 2Output460571165NoteIn the first example there are 6 lucky ticket numbers: 1111, 1818, 1881, 8118, 8181 and 8888.There is only one ticket number in the second example, it consists of 20 digits 6. This ticket number is lucky, so the answer is 1. | Input4 21 8 | Output6 | 5 seconds | 256 megabytes | ['divide and conquer', 'dp', 'fft', '*2400'] |
F. Inversion Expectationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.Calculate the expected total number of inversions in the resulting valid permutation.It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q \ne 0. Report the value of P \cdot Q^{-1} \pmod {998244353}.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the sequence.The second line contains n integers p_1, p_2, \dots, p_n (-1 \le p_i \le n, p_i \ne 0) — the initial sequence.It is guaranteed that all elements not equal to -1 are pairwise distinct.OutputPrint a single integer — the expected total number of inversions in the resulting valid permutation.It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q \ne 0. Report the value of P \cdot Q^{-1} \pmod {998244353}.ExamplesInput
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
NoteIn the first example two resulting valid permutations are possible: [3, 1, 2] — 2 inversions; [3, 2, 1] — 3 inversions. The expected value is \frac{2 \cdot 1 + 3 \cdot 1}{2} = 2.5.In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion. | 3
3 -1 -1
| 499122179 | 2 seconds | 256 megabytes | ['dp', 'math', 'probabilities', '*2300'] |
E. The Top Scorertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHasan loves playing games and has recently discovered a game called TopScore. In this soccer-like game there are p players doing penalty shoot-outs. Winner is the one who scores the most. In case of ties, one of the top-scorers will be declared as the winner randomly with equal probability.They have just finished the game and now are waiting for the result. But there's a tiny problem! The judges have lost the paper of scores! Fortunately they have calculated sum of the scores before they get lost and also for some of the players they have remembered a lower bound on how much they scored. However, the information about the bounds is private, so Hasan only got to know his bound.According to the available data, he knows that his score is at least r and sum of the scores is s.Thus the final state of the game can be represented in form of sequence of p integers a_1, a_2, \dots, a_p (0 \le a_i) — player's scores. Hasan is player number 1, so a_1 \ge r. Also a_1 + a_2 + \dots + a_p = s. Two states are considered different if there exists some position i such that the value of a_i differs in these states. Once again, Hasan doesn't know the exact scores (he doesn't know his exact score as well). So he considers each of the final states to be equally probable to achieve.Help Hasan find the probability of him winning.It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q \ne 0, P \le Q. Report the value of P \cdot Q^{-1} \pmod {998244353}.InputThe only line contains three integers p, s and r (1 \le p \le 100, 0 \le r \le s \le 5000) — the number of players, the sum of scores of all players and Hasan's score, respectively.OutputPrint a single integer — the probability of Hasan winning.It can be shown that it is in the form of \frac{P}{Q} where P and Q are non-negative integers and Q \ne 0, P \le Q. Report the value of P \cdot Q^{-1} \pmod {998244353}.ExamplesInput2 6 3Output124780545Input5 20 11Output1Input10 30 10Output85932500NoteIn the first example Hasan can score 3, 4, 5 or 6 goals. If he scores 4 goals or more than he scores strictly more than his only opponent. If he scores 3 then his opponent also scores 3 and Hasan has a probability of \frac 1 2 to win the game. Thus, overall he has the probability of \frac 7 8 to win.In the second example even Hasan's lower bound on goal implies him scoring more than any of his opponents. Thus, the resulting probability is 1. | Input2 6 3 | Output124780545 | 3 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', 'probabilities', '*2500'] |
D. Easy Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length n consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements. Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is 0, and removing i-th character increases the ambiguity by a_i (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still 4 even though you delete it from the string had).Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.InputThe first line contains one integer n (1 \le n \le 10^5) — the length of the statement.The second line contains one string s of length n, consisting of lowercase Latin letters — the statement written by Vasya.The third line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 998244353).OutputPrint minimum possible ambiguity of the statement after Vasya deletes some (possibly zero) characters so the resulting statement is easy.ExamplesInput
6
hhardh
3 2 9 11 7 1
Output
5
Input
8
hhzarwde
3 2 6 9 4 8 7 1
Output
4
Input
6
hhaarr
1 2 3 4 5 6
Output
0
NoteIn the first example, first two characters are removed so the result is ardh.In the second example, 5-th character is removed so the result is hhzawde.In the third example there's no need to remove anything. | 6
hhardh
3 2 9 11 7 1
| 5 | 2 seconds | 256 megabytes | ['dp', '*1800'] |
C. Polygon for the Angletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an angle \text{ang}. The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = \text{ang} or report that there is no such n-gon. If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed 998244353.InputThe first line contains single integer T (1 \le T \le 180) — the number of queries. Each of the next T lines contains one integer \text{ang} (1 \le \text{ang} < 180) — the angle measured in degrees. OutputFor each query print single integer n (3 \le n \le 998244353) — minimal possible number of vertices in the regular n-gon or -1 if there is no such n.ExampleInput
4
54
50
2
178
Output
10
18
90
180
NoteThe answer for the first query is on the picture above.The answer for the second query is reached on a regular 18-gon. For example, \angle{v_2 v_1 v_6} = 50^{\circ}.The example angle for the third query is \angle{v_{11} v_{10} v_{12}} = 2^{\circ}.In the fourth query, minimal possible n is 180 (not 90). | 4
54
50
2
178
| 10 18 90 180 | 2 seconds | 256 megabytes | ['brute force', 'geometry', '*1600'] |
B. Substring Removaltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n consisting only of lowercase Latin letters.A substring of a string is a contiguous subsequence of that string. So, string "forces" is substring of string "codeforces", but string "coder" is not.Your task is to calculate the number of ways to remove exactly one substring from this string in such a way that all remaining characters are equal (the number of distinct characters either zero or one).It is guaranteed that there is at least two different characters in s.Note that you can remove the whole string and it is correct. Also note that you should remove at least one character.Since the answer can be rather large (not very large though) print it modulo 998244353.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains one integer n (2 \le n \le 2 \cdot 10^5) — the length of the string s.The second line of the input contains the string s of length n consisting only of lowercase Latin letters.It is guaranteed that there is at least two different characters in s.OutputPrint one integer — the number of ways modulo 998244353 to remove exactly one substring from s in such way that all remaining characters are equal.ExamplesInput
4
abaa
Output
6
Input
7
aacdeee
Output
6Input
2
az
Output
3NoteLet s[l; r] be the substring of s from the position l to the position r inclusive.Then in the first example you can remove the following substrings: s[1; 2]; s[1; 3]; s[1; 4]; s[2; 2]; s[2; 3]; s[2; 4]. In the second example you can remove the following substrings: s[1; 4]; s[1; 5]; s[1; 6]; s[1; 7]; s[2; 7]; s[3; 7]. In the third example you can remove the following substrings: s[1; 1]; s[1; 2]; s[2; 2]. | 4
abaa
| 6 | 1 second | 256 megabytes | ['combinatorics', 'math', 'strings', '*1300'] |
A. Find Divisibletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a range of positive integers from l to r.Find such a pair of integers (x, y) that l \le x, y \le r, x \ne y and x divides y.If there are multiple answers, print any of them.You are also asked to answer T independent queries.InputThe first line contains a single integer T (1 \le T \le 1000) — the number of queries.Each of the next T lines contains two integers l and r (1 \le l \le r \le 998244353) — inclusive borders of the range.It is guaranteed that testset only includes queries, which have at least one suitable pair.OutputPrint T lines, each line should contain the answer — two integers x and y such that l \le x, y \le r, x \ne y and x divides y. The answer in the i-th line should correspond to the i-th query from the input.If there are multiple answers, print any of them.ExampleInput
3
1 10
3 14
1 10
Output
1 7
3 9
5 10
| 3
1 10
3 14
1 10
| 1 7 3 9 5 10 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', '*800'] |
F. Make It Connectedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph consisting of n vertices. A number is written on each vertex; the number on vertex i is a_i. Initially there are no edges in the graph.You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices x and y is a_x + a_y coins. There are also m special offers, each of them is denoted by three numbers x, y and w, and means that you can add an edge connecting vertices x and y and pay w coins for it. You don't have to use special offers: if there is a pair of vertices x and y that has a special offer associated with it, you still may connect these two vertices paying a_x + a_y coins for it.What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.InputThe first line contains two integers n and m (1 \le n \le 2 \cdot 10^5, 0 \le m \le 2 \cdot 10^5) — the number of vertices in the graph and the number of special offers, respectively.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{12}) — the numbers written on the vertices.Then m lines follow, each containing three integers x, y and w (1 \le x, y \le n, 1 \le w \le 10^{12}, x \ne y) denoting a special offer: you may add an edge connecting vertex x and vertex y, and this edge will cost w coins.OutputPrint one integer — the minimum number of coins you have to pay to make the graph connected.ExamplesInput
3 2
1 3 3
2 3 5
2 1 1
Output
5
Input
4 0
1 3 3 7
Output
16
Input
5 4
1 2 3 4 5
1 2 8
1 3 10
1 4 7
1 5 15
Output
18
NoteIn the first example it is possible to connect 1 to 2 using special offer 2, and then 1 to 3 without using any offers.In next two examples the optimal answer may be achieved without using special offers. | 3 2
1 3 3
2 3 5
2 1 1
| 5 | 2 seconds | 256 megabytes | ['dsu', 'graphs', 'greedy', '*1900'] |
E. Almost Regular Bracket Sequencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a bracket sequence s consisting of n opening '(' and closing ')' brackets.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 "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.You can change the type of some bracket s_i. It means that if s_i = ')' then you can change it to '(' and vice versa.Your task is to calculate the number of positions i such that if you change the type of the i-th bracket, then the resulting bracket sequence becomes regular.InputThe first line of the input contains one integer n (1 \le n \le 10^6) — the length of the bracket sequence.The second line of the input contains the string s consisting of n opening '(' and closing ')' brackets.OutputPrint one integer — the number of positions i such that if you change the type of the i-th bracket, then the resulting bracket sequence becomes regular.ExamplesInput
6
(((())
Output
3
Input
6
()()()
Output
0
Input
1
)
Output
0
Input
8
)))(((((
Output
0
| 6
(((())
| 3 | 3 seconds | 256 megabytes | ['implementation', '*1900'] |
D. Circular Dancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n kids, numbered from 1 to n, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as p_1, p_2, ..., p_n (all these numbers are from 1 to n and are distinct, so p is a permutation). Let the next kid for a kid p_i be kid p_{i + 1} if i < n and p_1 otherwise. After the dance, each kid remembered two kids: the next kid (let's call him x) and the next kid for x. Each kid told you which kids he/she remembered: the kid i remembered kids a_{i, 1} and a_{i, 2}. However, the order of a_{i, 1} and a_{i, 2} can differ from their order in the circle. Example: 5 kids in a circle, p=[3, 2, 4, 1, 5] (or any cyclic shift). The information kids remembered is: a_{1,1}=3, a_{1,2}=5; a_{2,1}=1, a_{2,2}=4; a_{3,1}=2, a_{3,2}=4; a_{4,1}=1, a_{4,2}=5; a_{5,1}=2, a_{5,2}=3. You have to restore the order of the kids in the circle using this information. If there are several answers, you may print any. It is guaranteed that at least one solution exists.If you are Python programmer, consider using PyPy instead of Python when you submit your code.InputThe first line of the input contains one integer n (3 \le n \le 2 \cdot 10^5) — the number of the kids.The next n lines contain 2 integers each. The i-th line contains two integers a_{i, 1} and a_{i, 2} (1 \le a_{i, 1}, a_{i, 2} \le n, a_{i, 1} \ne a_{i, 2}) — the kids the i-th kid remembered, given in arbitrary order.OutputPrint n integers p_1, p_2, ..., p_n — permutation of integers from 1 to n, which corresponds to the order of kids in the circle. If there are several answers, you may print any (for example, it doesn't matter which kid is the first in the circle). It is guaranteed that at least one solution exists.ExamplesInput
5
3 5
1 4
2 4
1 5
2 3
Output
3 2 4 1 5
Input
3
2 3
3 1
1 2
Output
3 1 2
| 5
3 5
1 4
2 4
1 5
2 3
| 3 2 4 1 5 | 3 seconds | 256 megabytes | ['implementation', '*1600'] |
C. Powers Of Twotime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA positive integer x is called a power of two if it can be represented as x = 2^y, where y is a non-negative integer. So, the powers of two are 1, 2, 4, 8, 16, \dots.You are given two positive integers n and k. Your task is to represent n as the sum of exactly k powers of two.InputThe only line of the input contains two integers n and k (1 \le n \le 10^9, 1 \le k \le 2 \cdot 10^5).OutputIf it is impossible to represent n as the sum of k powers of two, print NO.Otherwise, print YES, and then print k positive integers b_1, b_2, \dots, b_k such that each of b_i is a power of two, and \sum \limits_{i = 1}^{k} b_i = n. If there are multiple answers, you may print any of them.ExamplesInput
9 4
Output
YES
1 2 2 4
Input
8 1
Output
YES
8
Input
5 1
Output
NO
Input
3 7
Output
NO
| 9 4
| YES 1 2 2 4 | 4 seconds | 256 megabytes | ['bitmasks', 'greedy', '*1400'] |
B. Array Stabilizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integer numbers.Let instability of the array be the following value: \max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i.You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.InputThe first line of the input contains one integer n (2 \le n \le 10^5) — the number of elements in the array a.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^5) — elements of the array a.OutputPrint one integer — the minimum possible instability of the array if you have to remove exactly one element from the array a.ExamplesInput
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
NoteIn the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly. | 4
1 3 3 7
| 2 | 1 second | 256 megabytes | ['implementation', '*900'] |
A. Repeating Ciphertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp loves ciphers. He has invented his own cipher called repeating.Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} \dots s_{m} (1 \le m \le 10), Polycarp uses the following algorithm: he writes down s_1 ones, he writes down s_2 twice, he writes down s_3 three times, ... he writes down s_m m times. For example, if s="bab" the process is: "b" \to "baa" \to "baabbb". So the encrypted s="bab" is "baabbb".Given string t — the result of encryption of some string s. Your task is to decrypt it, i. e. find the string s.InputThe first line contains integer n (1 \le n \le 55) — the length of the encrypted string. The second line of the input contains t — the result of encryption of some string s. It contains only lowercase Latin letters. The length of t is exactly n.It is guaranteed that the answer to the test exists.OutputPrint such string s that after encryption it equals t.ExamplesInput
6
baabbb
Output
babInput
10
ooopppssss
Output
oopsInput
1
z
Output
z | 6
baabbb
| bab | 1 second | 256 megabytes | ['implementation', '*800'] |
G. Multidimensional Queriestime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a of n points in k-dimensional space. Let the distance between two points a_x and a_y be \sum \limits_{i = 1}^{k} |a_{x, i} - a_{y, i}| (it is also known as Manhattan distance).You have to process q queries of the following two types: 1 i b_1 b_2 ... b_k — set i-th element of a to the point (b_1, b_2, \dots, b_k); 2 l r — find the maximum distance between two points a_i and a_j, where l \le i, j \le r.InputThe first line contains two numbers n and k (1 \le n \le 2 \cdot 10^5, 1 \le k \le 5) — the number of elements in a and the number of dimensions of the space, respectively.Then n lines follow, each containing k integers a_{i, 1}, a_{i, 2}, ..., a_{i, k} (-10^6 \le a_{i, j} \le 10^6) — the coordinates of i-th point.The next line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Then q lines follow, each denoting a query. There are two types of queries: 1 i b_1 b_2 ... b_k (1 \le i \le n, -10^6 \le b_j \le 10^6) — set i-th element of a to the point (b_1, b_2, \dots, b_k); 2 l r (1 \le l \le r \le n) — find the maximum distance between two points a_i and a_j, where l \le i, j \le r.There is at least one query of the second type.OutputPrint the answer for each query of the second type.ExampleInput
5 2
1 2
2 3
3 4
4 5
5 6
7
2 1 5
2 1 3
2 3 5
1 5 -1 -2
2 1 5
1 4 -1 -2
2 1 5
Output
8
4
4
12
10
| 5 2
1 2
2 3
3 4
4 5
5 6
7
2 1 5
2 1 3
2 3 5
1 5 -1 -2
2 1 5
1 4 -1 -2
2 1 5
| 8 4 4 12 10 | 6 seconds | 512 megabytes | ['bitmasks', 'data structures', '*2300'] |
F. Vasya and Arraytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVasya has got an array consisting of n integers, and two integers k and len in addition. All numbers in the array are either between 1 and k (inclusive), or equal to -1. The array is good if there is no segment of len consecutive equal numbers.Vasya will replace each -1 with some number from 1 to k (inclusive) in such a way that the resulting array is good. Tell him the number of ways to do this replacement. Since the answer may be large, print it modulo 998244353.InputThe first line contains three integers n, k and len (1 \le n \le 10^5, 1 \le k \le 100, 1 \le len \le n).The second line contains n numbers — the array. Each number is either -1 or between 1 and k (inclusive).OutputPrint one integer — the number of ways to replace each -1 with some number from 1 to k (inclusive) so the array is good. The answer may be large, so print it modulo 998244353.ExamplesInput
5 2 3
1 -1 1 -1 2
Output
2
Input
6 3 2
1 1 -1 -1 -1 -1
Output
0
Input
10 42 7
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1
Output
645711643
NotePossible answers in the first test: [1, 2, 1, 1, 2]; [1, 2, 1, 2, 2]. There is no way to make the array good in the second test, since first two elements are equal.There are too many answers in the third test, so we won't describe any of them. | 5 2 3
1 -1 1 -1 2
| 2 | 2 seconds | 512 megabytes | ['dp', '*2400'] |
E. Intersection of Permutationstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two permutations a and b, both consisting of n elements. Permutation of n elements is such a integer sequence that each value from 1 to n appears exactly once in it.You are asked to perform two types of queries with them: 1~l_a~r_a~l_b~r_b — calculate the number of values which appear in both segment [l_a; r_a] of positions in permutation a and segment [l_b; r_b] of positions in permutation b; 2~x~y — swap values on positions x and y in permutation b. Print the answer for each query of the first type.It is guaranteed that there will be at least one query of the first type in the input.InputThe first line contains two integers n and m (2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5) — the number of elements in both permutations and the number of queries.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — permutation a. It is guaranteed that each value from 1 to n appears in a exactly once.The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le n) — permutation b. It is guaranteed that each value from 1 to n appears in b exactly once.Each of the next m lines contains the description of a certain query. These are either: 1~l_a~r_a~l_b~r_b (1 \le l_a \le r_a \le n, 1 \le l_b \le r_b \le n); 2~x~y (1 \le x, y \le n, x \ne y). OutputPrint the answers for the queries of the first type, each answer in the new line — the number of values which appear in both segment [l_a; r_a] of positions in permutation a and segment [l_b; r_b] of positions in permutation b.ExampleInput
6 7
5 1 4 2 3 6
2 5 3 1 4 6
1 1 2 4 5
2 2 4
1 1 2 4 5
1 2 3 3 5
1 1 6 1 2
2 4 1
1 4 4 1 3
Output
1
1
1
2
0
NoteConsider the first query of the first example. Values on positions [1; 2] of a are [5, 1] and values on positions [4; 5] of b are [1, 4]. Only value 1 appears in both segments.After the first swap (the second query) permutation b becomes [2, 1, 3, 5, 4, 6].After the second swap (the sixth query) permutation b becomes [5, 1, 3, 2, 4, 6]. | 6 7
5 1 4 2 3 6
2 5 3 1 4 6
1 1 2 4 5
2 2 4
1 1 2 4 5
1 2 3 3 5
1 1 6 1 2
2 4 1
1 4 4 1 3
| 1 1 1 2 0 | 6 seconds | 512 megabytes | ['data structures', '*2400'] |
D. Beautiful Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou 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.InputThe 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.OutputFor 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.ExampleInput
2
2 1
1 2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
4
0
NotePossible 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. | 2
2 1
1 2
4 6
1 2
1 3
1 4
2 3
2 4
3 4
| 4 0 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', '*1700'] |
C. Mishka and the Last Examtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative integer a_i to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of a to help out students like Mishka: a was sorted in non-decreasing order (a_1 \le a_2 \le \dots \le a_n); n was even; the following sequence b, consisting of \frac n 2 elements, was formed and given out to students: b_i = a_i + a_{n - i + 1}. Professor also mentioned that any sequence a, which produces sequence b with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence a of non-negative integers, which produces sequence b with the presented technique. It is guaranteed that there exists at least one correct sequence a, which produces the given sequence b.InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^5) — the length of sequence a. n is always even.The second line contains \frac n 2 integers b_1, b_2, \dots, b_{\frac n 2} (0 \le b_i \le 10^{18}) — sequence b, where b_i = a_i + a_{n - i + 1}.It is guaranteed that there exists at least one correct sequence a, which produces the given sequence b.OutputPrint n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^{18}) in a single line.a_1 \le a_2 \le \dots \le a_n should be satisfied.b_i = a_i + a_{n - i + 1} should be satisfied for all valid i.ExamplesInput
4
5 6
Output
2 3 3 3
Input
6
2 1 2
Output
0 0 1 1 1 2
| 4
5 6
| 2 3 3 3 | 2 seconds | 256 megabytes | ['greedy', '*1300'] |
B. Letters Rearrangingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.You have to answer t independent queries.InputThe first line of the input contains one integer t (1 \le t \le 100) — number of queries.Each of the next t lines contains one string. The i-th line contains a string s_i consisting only of lowercase Latin letter. It is guaranteed that the length of s_i is from 1 to 1000 (inclusive).OutputPrint t lines. In the i-th line print the answer to the i-th query: -1 if it is impossible to obtain a good string by rearranging the letters of s_i and any good string which can be obtained from the given one (by rearranging the letters) otherwise.ExampleInput
3
aa
abacaba
xdd
Output
-1
abaacba
xddNoteIn the first query we cannot rearrange letters to obtain a good string.Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".In the third query we can do nothing to obtain a good string. | 3
aa
abacaba
xdd
| -1 abaacba xdd | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'sortings', 'strings', '*900'] |
A. Dice Rollingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka got a six-faced dice. It has integer numbers from 2 to 7 written on its faces (all numbers on faces are different, so this is an almost usual dice).Mishka wants to get exactly x points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls Mishka makes.Mishka doesn't really care about the number of rolls, so he just wants to know any number of rolls he can make to be able to get exactly x points for them. Mishka is very lucky, so if the probability to get x points with chosen number of rolls is non-zero, he will be able to roll the dice in such a way. Your task is to print this number. It is guaranteed that at least one answer exists.Mishka is also very curious about different number of points to score so you have to answer t independent queries.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of queries.Each of the next t lines contains one integer each. The i-th line contains one integer x_i (2 \le x_i \le 100) — the number of points Mishka wants to get.OutputPrint t lines. In the i-th line print the answer to the i-th query (i.e. any number of rolls Mishka can make to be able to get exactly x_i points for them). It is guaranteed that at least one answer exists.ExampleInput
4
2
13
37
100
Output
1
3
8
27NoteIn the first query Mishka can roll a dice once and get 2 points.In the second query Mishka can roll a dice 3 times and get points 5, 5 and 3 (for example).In the third query Mishka can roll a dice 8 times and get 5 points 7 times and 2 points with the remaining roll.In the fourth query Mishka can roll a dice 27 times and get 2 points 11 times, 3 points 6 times and 6 points 10 times. | 4
2
13
37
100
| 1 3 8 27 | 1 second | 256 megabytes | ['math', '*800'] |
F. Tree with Maximum Costtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is \sum\limits_{i = 1}^{n} dist(i, v) \cdot a_i.Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.InputThe first line contains one integer n, the number of vertices in the tree (1 \le n \le 2 \cdot 10^5).The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 2 \cdot 10^5), where a_i is the value of the vertex i.Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 \le u_i, v_i \le n, u_i \ne v_i).It is guaranteed that the given edges form a tree.OutputPrint one integer — the maximum possible cost of the tree if you can choose any vertex as v.ExamplesInput
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
NotePicture corresponding to the first example: You can choose the vertex 3 as a root, then the answer will be 2 \cdot 9 + 1 \cdot 4 + 0 \cdot 1 + 3 \cdot 7 + 3 \cdot 10 + 4 \cdot 1 + 4 \cdot 6 + 4 \cdot 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.In the second example tree consists only of one vertex so the answer is always 0. | 8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
| 121 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'trees', '*1900'] |
E. Minimal Diameter Foresttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a forest — an undirected graph with n vertices such that each its connected component is a tree.The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in the shortest path between any pair of its vertices.You task is to add some edges (possibly zero) to the graph so that it becomes a tree and the diameter of the tree is minimal possible.If there are multiple correct answers, print any of them.InputThe first line contains two integers n and m (1 \le n \le 1000, 0 \le m \le n - 1) — the number of vertices of the graph and the number of edges, respectively.Each of the next m lines contains two integers v and u (1 \le v, u \le n, v \ne u) — the descriptions of the edges.It is guaranteed that the given graph is a forest.OutputIn the first line print the diameter of the resulting tree.Each of the next (n - 1) - m lines should contain two integers v and u (1 \le v, u \le n, v \ne u) — the descriptions of the added edges.The resulting graph should be a tree and its diameter should be minimal possible.For m = n - 1 no edges are added, thus the output consists of a single integer — diameter of the given tree.If there are multiple correct answers, print any of them.ExamplesInput
4 2
1 2
2 3
Output
2
4 2
Input
2 0
Output
1
1 2
Input
3 2
1 3
2 3
Output
2
NoteIn the first example adding edges (1, 4) or (3, 4) will lead to a total diameter of 3. Adding edge (2, 4), however, will make it 2.Edge (1, 2) is the only option you have for the second example. The diameter is 1.You can't add any edges in the third example. The diameter is already 2. | 4 2
1 2
2 3
| 2 4 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'greedy', 'trees', '*2000'] |
D2. Great Vova Wall (Version 2)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.Vova can only use 2 \times 1 bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks only horizontally on the neighbouring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).Note that Vova can't put bricks vertically.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of parts in the wall.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the initial heights of the parts of the wall.OutputPrint "YES" if Vova can complete the wall using any amount of bricks (possibly zero).Print "NO" otherwise.ExamplesInput
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
NO
Input
2
10 10
Output
YES
NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].In the second example Vova can put no bricks in the wall.In the third example the wall is already complete. | 5
2 1 1 2 5
| YES | 2 seconds | 256 megabytes | ['data structures', 'implementation', '*2200'] |
D1. Great Vova Wall (Version 1)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence a of n integers, with a_i being the height of the i-th part of the wall.Vova can only use 2 \times 1 bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some i the current height of part i is the same as for part i + 1, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part 1 of the wall or to the right of part n of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of parts in the wall.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the initial heights of the parts of the wall.OutputPrint "YES" if Vova can complete the wall using any amount of bricks (possibly zero).Print "NO" otherwise.ExamplesInput
5
2 1 1 2 5
Output
YES
Input
3
4 5 3
Output
YES
Input
2
10 10
Output
YES
Input
3
1 2 3
Output
NO
NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall [2, 2, 2, 2, 5] and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it [5, 5, 5, 5, 5].In the second example Vova can put a brick vertically on part 3 to make the wall [4, 5, 5], then horizontally on parts 2 and 3 to make it [4, 6, 6] and then vertically on part 1 to make it [6, 6, 6].In the third example the wall is already complete. | 5
2 1 1 2 5
| YES | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', '*2200'] |
C. Prefixes and Suffixestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan wants to play a game with you. He picked some string s of length n consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from 1 to n-1), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given 2n-2 strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!InputThe first line of the input contains one integer number n (2 \le n \le 100) — the length of the guessed string s.The next 2n-2 lines are contain prefixes and suffixes, one per line. Each of them is the string of length from 1 to n-1 consisting only of lowercase Latin letters. They can be given in arbitrary order.It is guaranteed that there are exactly 2 strings of each length from 1 to n-1. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length n.OutputPrint one string of length 2n-2 — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The i-th character of this string should be 'P' if the i-th of the input strings is the prefix and 'S' otherwise.If there are several possible answers, you can print any.ExamplesInput
5
ba
a
abab
a
aba
baba
ab
aba
Output
SPPSPSPS
Input
3
a
aa
aa
a
Output
PPSS
Input
2
a
c
Output
PS
NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable. | 5
ba
a
abab
a
aba
baba
ab
aba
| SPPSPSPS | 1 second | 256 megabytes | ['strings', '*1700'] |
B. Teams Formingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students in a university. The number of students is even. The i-th student has programming skill equal to a_i. The coach wants to form \frac{n}{2} teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equal (otherwise they cannot understand each other and cannot form a team).Students can solve problems to increase their skill. One solved problem increases the skill by one.The coach wants to know the minimum total number of problems students should solve to form exactly \frac{n}{2} teams (i.e. each pair of students should form a team). Your task is to find this number.InputThe first line of the input contains one integer n (2 \le n \le 100) — the number of students. It is guaranteed that n is even.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100), where a_i is the skill of the i-th student.OutputPrint one number — the minimum total number of problems students should solve to form exactly \frac{n}{2} teams.ExamplesInput
6
5 10 2 3 14 5
Output
5
Input
2
1 100
Output
99
NoteIn the first example the optimal teams will be: (3, 4), (1, 6) and (2, 5), where numbers in brackets are indices of students. Then, to form the first team the third student should solve 1 problem, to form the second team nobody needs to solve problems and to form the third team the second student should solve 4 problems so the answer is 1 + 4 = 5.In the second example the first student should solve 99 problems to form a team with the second one. | 6
5 10 2 3 14 5
| 5 | 1 second | 256 megabytes | ['sortings', '*800'] |
A. Uniform Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and k.Your task is to construct such a string s of length n that for each i from 1 to k there is at least one i-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minimal frequency of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print any.You have to answer t independent queries.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of queries.The next t lines are contain queries, one per line. The i-th line contains two integers n_i and k_i (1 \le n_i \le 100, 1 \le k_i \le min(n_i, 26)) — the length of the string in the i-th query and the number of characters in the i-th query.OutputPrint t lines. In the i-th line print the answer to the i-th query: any string s_i satisfying the conditions in the problem statement with constraints from the i-th query.ExampleInput
3
7 3
4 4
6 2
Output
cbcacab
abcd
baabab
NoteIn the first example query the maximum possible minimal frequency is 2, it can be easily seen that the better answer doesn't exist. Other examples of correct answers: "cbcabba", "ccbbaaa" (any permutation of given answers is also correct).In the second example query any permutation of first four letters is acceptable (the maximum minimal frequency is 1).In the third example query any permutation of the given answer is acceptable (the maximum minimal frequency is 3). | 3
7 3
4 4
6 2
| cbcacab abcd baabab | 1 second | 256 megabytes | ['implementation', '*800'] |
H. New Year and the Tricolore Recreationtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob play a game on a grid with n rows and infinitely many columns. In each row, there are three tokens, blue, white and red one. Before the game starts and after every move, the following two conditions must hold: Any two tokens are not in the same cell. In each row, the blue token is to the left of the white token, and the red token is to the right of the white token. First, they pick a positive integer f, whose value is valid for the whole game. Second, the starting player is chosen and makes his or her first turn. Then players take alternating turns. The player who is unable to make a move loses. During a move, a player first selects an integer k that is either a prime number or a product of two (not necessarily distinct) primes. The smallest possible values of k are thus 2, 3, 4, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 19, \dots. Furthermore, k must not be equal to the previously picked integer f. Each turn, a move is performed in exactly one of the rows.If it is Alice's turn, she chooses a single blue token and moves it k cells to the right. Alternatively, she may move both the blue and the white token in the same row by the same amount k to the right.On the other hand, Bob selects a single red token and moves it k cells to the left. Similarly, he may also move the white and the red token in the corresponding row by k to the left.Note that Alice may never move a red token, while Bob may never move a blue one. Remember that after a move, the two conditions on relative positions of the tokens must still hold. Both players play optimally. Given the initial state of the board, determine who wins for two games: if Alice starts and if Bob starts. InputThe first line contains a two integers n and f (1 \leq n \leq 10^5, 2 \leq f \leq 2 \cdot 10^5) — the number of rows and the forbidden move, respectively.Each of the next n lines contains three integers b_i, w_i, r_i (-10^5 \leq b_i < w_i < r_i \leq 10^5) — the number of column in which the blue, white and red token lies in the i-th row, respectively. OutputOutput two lines. The first line should contain the name of the winner when Alice starts, and the second line should contain the name of the winner when Bob starts.ExamplesInput
1 6
0 3 9
Output
Alice
Bob
Input
1 2
0 3 9
Output
Alice
Bob
Input
10 133
-248 -193 -187
97 101 202
-72 67 91
23 89 215
-129 -108 232
-223 -59 236
-99 86 242
-137 -109 -45
-105 173 246
-44 228 243
Output
Bob
Alice
NoteThe first example is as follows:When Alice starts, she can win by moving the blue and white token to right by 2 cells, getting into position 2~5~9. Regardless of what Bob does, Alice will have one more move and then the game is over. For instance, he can move both the red and white token by 2 cells to the left, reaching state 2~3~7. Alice can then move blue and white token by 2 to move into 4~5~7, where no more moves are possible.If Bob starts, he gains enough advantage to win. For instance, he may move the red token by 3 to the left, getting into position 0~3~6. Alice can, for example, move the blue token by 2, which is countered by Bob by moving the red token by 2. The game ends in position 2~3~4. In the second example, it is forbidden to move by 2, but this doesn't stop Alice from winning! She can move the blue and white token by 4, getting into position 4~7~9. Now Bob has no move, since moving by 2 is forbidden. | 1 6
0 3 9
| Alice Bob | 4 seconds | 256 megabytes | ['games', '*3200'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.