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
B. Cake Assembly Linetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA cake assembly line in a bakery was once again optimized, and now n cakes are made at a time! In the last step, each of the n cakes should be covered with chocolate.Consider a side view on the conveyor belt, let it be a number line. The i-th cake occupies the segment [a_i - w, a_i + w] on this line, each pair of these segments does not have common points. Above the conveyor, there are n dispensers, and when a common button is pressed, chocolate from the i-th dispenser will cover the conveyor segment [b_i - h, b_i + h]. Each pair of these segments also does not have common points. Cakes and dispensers corresponding to the first example. The calibration of this conveyor belt part has not yet been performed, so you are to make it. Determine if it's possible to shift the conveyor so that each cake has some chocolate on it, and there is no chocolate outside the cakes. You can assume that the conveyour is long enough, so the cakes never fall. Also note that the button can only be pressed once. In the first example we can shift the cakes as shown in the picture. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.The first line of each test case contains three integers n, w, and h (1 \le n \le 10^5; 1 \le w, h \le 10^5; h \le w) — the number of cakes and dispensers, as well as the halfwidths of cakes and segments on which the chocolate is dispensed.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9) — the positions of the cakes centers. It is guaranteed that a_i + w < a_{i + 1} - w for all i.The third line contains n integers b_1, b_2, ..., b_n (1 \le b_i \le 10^9) — the positions of the dispensers. It is guaranteed that b_i + h < b_{i + 1} - h for all i.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case output "YES", if it's possible to shift the conveyor in such a way that each cake ends up with some chocolate, and no chocolate is outside the cakes, and "NO" otherwise.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput 43 10 565 95 16540 65 1455 2 11 6 11 16 214 9 14 19 243 3 213 22 295 16 254 4 127 36 127 13635 50 141 144Output YES YES NO YES NoteThe first example is shown in the figures in the statement.In the second example, we can move the conveyor, for example, so that the centers of the cakes are at 4, 9, 14, 19, 24.In the third example, we can't move the conveyor accordingly.
43 10 565 95 16540 65 1455 2 11 6 11 16 214 9 14 19 243 3 213 22 295 16 254 4 127 36 127 13635 50 141 144
YES YES NO YES
1 second
256 megabytes
['brute force', 'sortings', '*1300']
A2. Alternating Deck (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. In this version, there are two colors of the cards.Alice has n cards, each card is either black or white. The cards are stacked in a deck in such a way that the card colors alternate, starting from a white card. Alice deals the cards to herself and to Bob, dealing at once several cards from the top of the deck in the following order: one card to herself, two cards to Bob, three cards to Bob, four cards to herself, five cards to herself, six cards to Bob, seven cards to Bob, eight cards to herself, and so on. In other words, on the i-th step, Alice deals i top cards from the deck to one of the players; on the first step, she deals the cards to herself and then alternates the players every two steps. When there aren't enough cards at some step, Alice deals all the remaining cards to the current player, and the process stops. First Alice's steps in a deck of many cards. How many cards of each color will Alice and Bob have at the end?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 200). The description of the test cases followsThe only line of each test case contains a single integer n (1 \le n \le 10^6) — the number of cards.OutputFor each test case print four integers — the number of cards in the end for each player — in this order: white cards Alice has, black cards Alice has, white cards Bob has, black cards Bob has.ExampleInput 51061781000000Output 3 2 2 3 1 0 2 3 6 4 3 4 2 1 2 3 250278 249924 249722 250076
51061781000000
3 2 2 3 1 0 2 3 6 4 3 4 2 1 2 3 250278 249924 249722 250076
1 second
256 megabytes
['implementation', '*800']
A1. Non-alternating Deck (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. In this version, all cards have the same color.Alice has n cards, each card is white, and the cards are stacked in a deck. Alice deals the cards to herself and to Bob, dealing at once several cards from the top of the deck in the following order: one card to herself, two cards to Bob, three cards to Bob, four cards to herself, five cards to herself, six cards to Bob, seven cards to Bob, eight cards to herself, and so on. In other words, on the i-th step, Alice deals i top cards from the deck to one of the players; on the first step, she deals the cards to herself and then alternates the players every two steps. When there aren't enough cards at some step, Alice deals all the remaining cards to the current player, and the process stops. First Alice's steps in a deck of many cards. How many cards will Alice and Bob have at the end?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 200). The description of the test cases followsThe only line of each test case contains a single integer n (1 \le n \le 10^6) — the number of cards.OutputFor each test case print two integers — the number of cards in the end for each player — in this order: cards Alice has, cards Bob has.ExampleInput 51061781000000Output 5 5 1 5 10 7 3 5 500202 499798
51061781000000
5 5 1 5 10 7 3 5 500202 499798
1 second
256 megabytes
['implementation', '*800']
F. Minimums or Medianstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVika has a set of all consecutive positive integers from 1 to 2n, inclusive.Exactly k times Vika will choose and perform one of the following two actions: take two smallest integers from her current set and remove them; take two median integers from her current set and remove them. Recall that medians are the integers located exactly in the middle of the set if you write down its elements in increasing order. Note that Vika's set always has an even size, thus the pair of median integers is uniquely defined. For example, two median integers of the set \{1, 5, 6, 10, 15, 16, 18, 23\} are 10 and 15.How many different sets can Vika obtain in the end, after k actions? Print this number modulo 998\,244\,353. Two sets are considered different if some integer belongs to one of them but not to the other.InputThe only line contains two integers n and k (1 \le k \le n \le 10^6).OutputPrint a single integer — the number of sets Vika can obtain in the end, modulo 998\,244\,353.ExamplesInput 3 1 Output 2 Input 3 2 Output 3 Input 3 3 Output 1 Input 7 4 Output 11 Input 23 8 Output 88 Input 100 77 Output 825430474 NoteIn the first example, Vika's initial set is \{1, 2, 3, 4, 5, 6\}. She can remove the minimums from it to obtain \{3, 4, 5, 6\}, or she can remove the medians from it to obtain \{1, 2, 5, 6\}.In the second example, Vika can obtain \{1, 6\}, \{3, 6\}, or \{5, 6\}. For instance, Vika can obtain \{3, 6\} if she removes two smallest integers first (\{1, 2, 3, 4, 5, 6\} \rightarrow \{3, 4, 5, 6\}), and then she removes two median integers (\{3, 4, 5, 6\} \rightarrow \{3, 6\}).In the third example, regardless of Vika's choices, she'll end up with an empty set.
3 1
2
4 seconds
512 megabytes
['*3400']
E. Infinite Gametime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing an infinite game consisting of sets. Each set consists of rounds. In each round, one of the players wins. The first player to win two rounds in a set wins this set. Thus, a set always ends with the score of 2:0 or 2:1 in favor of one of the players.Let's call a game scenario a finite string s consisting of characters 'a' and 'b'. Consider an infinite string formed with repetitions of string s: sss \ldots Suppose that Alice and Bob play rounds according to this infinite string, left to right. If a character of the string sss \ldots is 'a', then Alice wins the round; if it's 'b', Bob wins the round. As soon as one of the players wins two rounds, the set ends in their favor, and a new set starts from the next round.Let's define a_i as the number of sets won by Alice among the first i sets while playing according to the given scenario. Let's also define r as the limit of ratio \frac{a_i}{i} as i \rightarrow \infty. If r > \frac{1}{2}, we'll say that scenario s is winning for Alice. If r = \frac{1}{2}, we'll say that scenario s is tied. If r < \frac{1}{2}, we'll say that scenario s is winning for Bob.You are given a string s consisting of characters 'a', 'b', and '?'. Consider all possible ways of replacing every '?' with 'a' or 'b' to obtain a string consisting only of characters 'a' and 'b'. Count how many of them result in a scenario winning for Alice, how many result in a tied scenario, and how many result in a scenario winning for Bob. Print these three numbers modulo 998\,244\,353.InputThe only line contains a single string s (1 \le |s| \le 200), consisting of characters 'a', 'b', and '?'.OutputPrint three integers: how many ways result in a scenario winning for Alice, how many result in a tied scenario, and how many result in a scenario winning for Bob, modulo 998\,244\,353.ExamplesInput ?? Output 1 2 1 Input ?aa?b Output 1 3 0 Input a???ba Output 4 3 1 Input ???????? Output 121 14 121 Input ba????a?a???abbb? Output 216 57 239 Input a????a??????b??abbababbbb?a?aaa????bb Output 97833 28387 135924 Input ??????????????a????????????????b????? Output 484121060 448940322 484613337 NoteIn the first example, there are four ways to replace the question marks: s = \mathtt{aa}: Alice wins every set 2:0 — the scenario is winning for Alice; s = \mathtt{ab}: Alice and Bob win sets in turns, with the score of 2:1 each — the scenario is tied; s = \mathtt{ba}: Bob and Alice win sets in turns, with the score of 2:1 each — the scenario is tied; s = \mathtt{bb}: Bob wins every set 2:0 — the scenario is winning for Bob.
??
1 2 1
5 seconds
512 megabytes
['brute force', 'combinatorics', 'dp', 'games', 'probabilities', '*3100']
D. Wooden Spoontime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard output2^n people, numbered with distinct integers from 1 to 2^n, are playing in a single elimination tournament. The bracket of the tournament is a full binary tree of height n with 2^n leaves.When two players meet each other in a match, a player with the smaller number always wins. The winner of the tournament is the player who wins all n their matches.A virtual consolation prize "Wooden Spoon" is awarded to a player who satisfies the following n conditions: they lost their first match; the player who beat them lost their second match; the player who beat that player lost their third match; \ldots; the player who beat the player from the previous condition lost the final match of the tournament. It can be shown that there is always exactly one player who satisfies these conditions.Consider all possible (2^n)! arrangements of players into the tournament bracket. For each player, find the number of these arrangements in which they will be awarded the "Wooden Spoon", and print these numbers modulo 998\,244\,353.InputThe only line contains a single integer n (1 \le n \le 20) — the size of the tournament.There are 20 tests in the problem: in the first test, n = 1; in the second test, n = 2; \ldots; in the 20-th test, n = 20.OutputPrint 2^n integers — the number of arrangements in which the "Wooden Spoon" is awarded to players 1, 2, \ldots, 2^n, modulo 998\,244\,353.ExamplesInput 1 Output 0 2 Input 2 Output 0 0 8 16 Input 3 Output 0 0 0 1536 4224 7680 11520 15360 NoteIn the first example, the "Wooden Spoon" is always awarded to player 2.In the second example, there are 8 arrangements where players 1 and 4 meet each other in the first match, and in these cases, the "Wooden Spoon" is awarded to player 3. In the remaining 16 arrangements, the "Wooden Spoon" is awarded to player 4.
1
0 2
4 seconds
512 megabytes
['combinatorics', 'dp', '*2400']
C. Monsters (hard version)time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. In this version, you need to find the answer for every prefix of the monster array.In a computer game, you are fighting against n monsters. Monster number i has a_i health points, all a_i are integers. A monster is alive while it has at least 1 health point.You can cast spells of two types: Deal 1 damage to any single alive monster of your choice. Deal 1 damage to all alive monsters. If at least one monster dies (ends up with 0 health points) as a result of this action, then repeat it (and keep repeating while at least one monster dies every time). Dealing 1 damage to a monster reduces its health by 1.Spells of type 1 can be cast any number of times, while a spell of type 2 can be cast at most once during the game.For every k = 1, 2, \ldots, n, answer the following question. Suppose that only the first k monsters, with numbers 1, 2, \ldots, k, are present in the game. What is the smallest number of times you need to cast spells of type 1 to kill all k monsters?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.Each test case consists of two lines. The first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of monsters.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — monsters' health points.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print n integers. The k-th of these integers must be equal to the smallest number of times you need to cast spells of type 1 to kill all k monsters, if only monsters with numbers 1, 2, \ldots, k are present in the game.ExampleInput 233 1 264 1 5 4 1 1Output 2 1 0 3 2 4 4 4 4 NoteIn the first test case, for k = n, the initial health points of the monsters are [3, 1, 2]. It is enough to cast a spell of type 2: Monsters' health points change to [2, 0, 1]. Since monster number 2 dies, the spell is repeated. Monsters' health points change to [1, 0, 0]. Since monster number 3 dies, the spell is repeated. Monsters' health points change to [0, 0, 0]. Since monster number 1 dies, the spell is repeated. Monsters' health points change to [0, 0, 0]. Since it is possible to use no spells of type 1 at all, the answer is 0.In the second test case, for k = n, the initial health points of the monsters are [4, 1, 5, 4, 1, 1]. Here is one of the optimal action sequences: Using a spell of type 1, deal 1 damage to monster number 1. Monsters' health points change to [3, 1, 5, 4, 1, 1]. Using a spell of type 1, deal 1 damage to monster number 4. Monsters' health points change to [3, 1, 5, 3, 1, 1]. Using a spell of type 1, deal 1 damage to monster number 4 again. Monsters' health points change to [3, 1, 5, 2, 1, 1]. Use a spell of type 2: Monsters' health points change to [2, 0, 4, 1, 0, 0]. Since monsters number 2, 5, and 6 die, the spell is repeated. Monsters' health points change to [1, 0, 3, 0, 0, 0]. Since monster number 4 dies, the spell is repeated. Monsters' health points change to [0, 0, 2, 0, 0, 0]. Since monster number 1 dies, the spell is repeated. Monsters' health points change to [0, 0, 1, 0, 0, 0]. Using a spell of type 1, deal 1 damage to monster number 3. Monsters' health points change to [0, 0, 0, 0, 0, 0]. Spells of type 1 are cast 4 times in total. It can be shown that this is the smallest possible number.
233 1 264 1 5 4 1 1
2 1 0 3 2 4 4 4 4
4 seconds
512 megabytes
['data structures', 'greedy', '*2200']
B. Letter Exchangetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA cooperative game is played by m people. In the game, there are 3m sheets of paper: m sheets with letter 'w', m sheets with letter 'i', and m sheets with letter 'n'.Initially, each person is given three sheets (possibly with equal letters).The goal of the game is to allow each of the m people to spell the word "win" using their sheets of paper. In other words, everyone should have one sheet with letter 'w', one sheet with letter 'i', and one sheet with letter 'n'.To achieve the goal, people can make exchanges. Two people participate in each exchange. Both of them choose exactly one sheet of paper from the three sheets they own and exchange it with each other.Find the shortest sequence of exchanges after which everyone has one 'w', one 'i', and one 'n'.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains a single integer m (2 \le m \le 10^5) — the number of people.The i-th of the next m lines contains a string s_i of length 3 consisting of lowercase English letters 'w', 'i', and 'n', denoting the letters person i has on their sheets of paper at the beginning of the game, in arbitrary order.Each of the letters 'w', 'i', and 'n' appears on the sheets of paper exactly m times in total.It is guaranteed that the sum of m over all test cases does not exceed 10^5.OutputFor each test case, print a non-negative integer k — the smallest number of exchanges people need to make everyone have one 'w', one 'i', and one 'n'.In each of the next k lines print four tokens a_1 c_1 a_2 c_2, describing the exchanges in chronological order (1 \le a_1, a_2 \le m; a_1 \ne a_2; c_1, c_2 are one of \{\mathtt{w}, \mathtt{i}, \mathtt{n}\}): person a_1 gives letter c_1 to person a_2, while person a_2 gives letter c_2 to person a_1 at the same time.If there are multiple solutions, print any.ExampleInput 32nwiinw3innnwwwii4winwwwiiinnnOutput 0 2 2 w 3 i 3 w 1 n 3 2 w 3 i 2 w 4 n 3 i 4 n
32nwiinw3innnwwwii4winwwwiiinnn
0 2 2 w 3 i 3 w 1 n 3 2 w 3 i 2 w 4 n 3 i 4 n
4 seconds
512 megabytes
['constructive algorithms', '*1900']
A. Monsters (easy version)time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. In this version, you only need to find the answer once. In this version, hacks are not allowed.In a computer game, you are fighting against n monsters. Monster number i has a_i health points, all a_i are integers. A monster is alive while it has at least 1 health point.You can cast spells of two types: Deal 1 damage to any single alive monster of your choice. Deal 1 damage to all alive monsters. If at least one monster dies (ends up with 0 health points) as a result of this action, then repeat it (and keep repeating while at least one monster dies every time). Dealing 1 damage to a monster reduces its health by 1.Spells of type 1 can be cast any number of times, while a spell of type 2 can be cast at most once during the game.What is the smallest number of times you need to cast spells of type 1 to kill all monsters?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.Each test case consists of two lines. The first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of monsters.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — monsters' health points.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the smallest number of times you need to cast spells of type 1 to kill all monsters.ExampleInput 233 1 264 1 5 4 1 1Output 0 4 NoteIn the first test case, the initial health points of the monsters are [3, 1, 2]. It is enough to cast a spell of type 2: Monsters' health points change to [2, 0, 1]. Since monster number 2 dies, the spell is repeated. Monsters' health points change to [1, 0, 0]. Since monster number 3 dies, the spell is repeated. Monsters' health points change to [0, 0, 0]. Since monster number 1 dies, the spell is repeated. Monsters' health points change to [0, 0, 0]. Since it is possible to use no spells of type 1 at all, the answer is 0.In the second test case, the initial health points of the monsters are [4, 1, 5, 4, 1, 1]. Here is one of the optimal action sequences: Using a spell of type 1, deal 1 damage to monster number 1. Monsters' health points change to [3, 1, 5, 4, 1, 1]. Using a spell of type 1, deal 1 damage to monster number 4. Monsters' health points change to [3, 1, 5, 3, 1, 1]. Using a spell of type 1, deal 1 damage to monster number 4 again. Monsters' health points change to [3, 1, 5, 2, 1, 1]. Use a spell of type 2: Monsters' health points change to [2, 0, 4, 1, 0, 0]. Since monsters number 2, 5, and 6 die, the spell is repeated. Monsters' health points change to [1, 0, 3, 0, 0, 0]. Since monster number 4 dies, the spell is repeated. Monsters' health points change to [0, 0, 2, 0, 0, 0]. Since monster number 1 dies, the spell is repeated. Monsters' health points change to [0, 0, 1, 0, 0, 0]. Using a spell of type 1, deal 1 damage to monster number 3. Monsters' health points change to [0, 0, 0, 0, 0, 0]. Spells of type 1 are cast 4 times in total. It can be shown that this is the smallest possible number.
233 1 264 1 5 4 1 1
0 4
4 seconds
512 megabytes
['brute force', 'greedy', '*1000']
G. Weighed Tree Radiustime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree of n vertices and n - 1 edges. The i-th vertex has an initial weight a_i.Let the distance d_v(u) from vertex v to vertex u be the number of edges on the path from v to u. Note that d_v(u) = d_u(v) and d_v(v) = 0.Let the weighted distance w_v(u) from v to u be w_v(u) = d_v(u) + a_u. Note that w_v(v) = a_v and w_v(u) \neq w_u(v) if a_u \neq a_v.Analogically to usual distance, let's define the eccentricity e(v) of vertex v as the greatest weighted distance from v to any other vertex (including v itself), or e(v) = \max\limits_{1 \le u \le n}{w_v(u)}.Finally, let's define the radius r of the tree as the minimum eccentricity of any vertex, or r = \min\limits_{1 \le v \le n}{e(v)}.You need to perform m queries of the following form: v_j x_j — assign a_{v_j} = x_j. After performing each query, print the radius r of the current tree.InputThe first line contains the single integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.The second line contains n integers a_1, \dots, a_n (0 \le a_i \le 10^6) — the initial weights of vertices.Next n - 1 lines contain edges of tree. The i-th line contains two integers u_i and v_i (1 \le u_i, v_i \le n; u_i \neq v_i) — the corresponding edge. The given edges form a tree.The next line contains the single integer m (1 \le m \le 10^5) — the number of queries.Next m lines contain queries — one query per line. The j-th query contains two integers v_j and x_j (1 \le v_j \le n; 0 \le x_j \le 10^6) — a vertex and it's new weight.OutputPrint m integers — the radius r of the tree after performing each query.ExampleInput 6 1 3 3 7 0 1 2 1 1 3 1 4 5 4 4 6 5 4 7 4 0 2 5 5 10 5 5 Output 7 4 5 10 7 NoteAfter the first query, you have the following tree: The marked vertex in the picture is the vertex with minimum e(v), or r = e(4) = 7. The eccentricities of the other vertices are the following: e(1) = 8, e(2) = 9, e(3) = 9, e(5) = 8, e(6) = 8.The tree after the second query: The radius r = e(1) = 4.After the third query, the radius r = e(2) = 5:
6 1 3 3 7 0 1 2 1 1 3 1 4 5 4 4 6 5 4 7 4 0 2 5 5 10 5 5
7 4 5 10 7
6 seconds
512 megabytes
['data structures', 'divide and conquer', 'implementation', 'trees', '*2800']
F. Double Sort IItime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two permutations a and b, both of size n. A permutation of size n is an array of n elements, where each integer from 1 to n appears exactly once. The elements in each permutation are indexed from 1 to n.You can perform the following operation any number of times: choose an integer i from 1 to n; let x be the integer such that a_x = i. Swap a_i with a_x; let y be the integer such that b_y = i. Swap b_i with b_y. Your goal is to make both permutations sorted in ascending order (i. e. the conditions a_1 < a_2 < \dots < a_n and b_1 < b_2 < \dots < b_n must be satisfied) using minimum number of operations. Note that both permutations must be sorted after you perform the sequence of operations you have chosen.InputThe first line contains one integer n (2 \le n \le 3000).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n; all a_i are distinct).The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le n; all b_i are distinct).OutputFirst, print one integer k (0 \le k \le 2n) — the minimum number of operations required to sort both permutations. Note that it can be shown that 2n operations are always enough.Then, print k integers op_1, op_2, \dots, op_k (1 \le op_j \le n), where op_j is the value of i you choose during the j-th operation.If there are multiple answers, print any of them.ExamplesInput 5 1 3 2 4 5 2 1 3 4 5 Output 1 2 Input 2 1 2 1 2 Output 0 Input 4 1 3 4 2 4 3 2 1 Output 2 3 4
5 1 3 2 4 5 2 1 3 4 5
1 2
2 seconds
512 megabytes
['dfs and similar', 'flows', 'graph matchings', 'graphs', '*2500']
E. Game of the Yeartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp and Polycarp are playing a computer game. This game features n bosses for the playing to kill, numbered from 1 to n.They will fight each boss the following way: Monocarp makes k attempts to kill the boss; Polycarp makes k attempts to kill the boss; Monocarp makes k attempts to kill the boss; Polycarp makes k attempts to kill the boss; ... Monocarp kills the i-th boss on his a_i-th attempt. Polycarp kills the i-th boss on his b_i-th attempt. After one of them kills the i-th boss, they move on to the (i+1)-st boss. The attempt counters reset for both of them. Once one of them kills the n-th boss, the game ends.Find all values of k from 1 to n such that Monocarp kills all bosses.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of bosses.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the index of attempt Monocarp kills each boss on.The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le n) — the index of attempt Polycarp kills each boss on.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print two lines. The first line should contain a single integer \mathit{cnt} — the number of values of k from 1 to n such that Monocarp kills all bosses. The second line should contain \mathit{cnt} distinct integers — the values of k themselves.ExampleInput 331 1 12 3 111141 4 3 23 3 4 1Output 3 1 2 3 1 1 2 2 4 NoteConsider the last testcase of the example.Let k = 1. First, Monocarp makes one attempt to kill the first boss. It's successful, since a_1 = 1. Then, Monocarp makes one attempt to kill the second boss. It's unsuccessful, since a_2 > 1. So, Polycarp makes an attempt then. It's also unsuccessful, since b_2 > 1. Then, Monocarp makes another attempt. It's still unsuccessful, since a_2 > 2. This goes on until Polycarp finally kills the boss on his third attempt. Monocarp didn't kill this boss, thus, k = 1 isn't the answer.Let k = 2. Monocarp still kills the first boss on his first attempt. Then, he makes two unsuccessful attempts for the second boss. Then, Polycarp makes two unsuccessful attempts. Then, Monocarp makes two more attempts and kills the boss on his fourth attempt. The third boss is similar. First, two unsuccessful attempts by Monocarp. Then, two unsuccessful attempts by Polycarp. Then, Monocarp has two more attempts, but even his first one is successful, since a_3 = 3. The fourth boss is also killed by Monocarp. Thus, k = 2 is the answer.
331 1 12 3 111141 4 3 23 3 4 1
3 1 2 3 1 1 2 2 4
2 seconds
256 megabytes
['brute force', 'data structures', 'math', 'number theory', '*2300']
D. Different Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers.You have to perform the sequence of n-2 operations on this array: during the first operation, you either add a_2 to a_1 and subtract a_2 from a_3, or add a_2 to a_3 and subtract a_2 from a_1; during the second operation, you either add a_3 to a_2 and subtract a_3 from a_4, or add a_3 to a_4 and subtract a_3 from a_2; ... during the last operation, you either add a_{n-1} to a_{n-2} and subtract a_{n-1} from a_n, or add a_{n-1} to a_n and subtract a_{n-1} from a_{n-2}. So, during the i-th operation, you add the value of a_{i+1} to one of its neighbors, and subtract it from the other neighbor.For example, if you have the array [1, 2, 3, 4, 5], one of the possible sequences of operations is: subtract 2 from a_3 and add it to a_1, so the array becomes [3, 2, 1, 4, 5]; subtract 1 from a_2 and add it to a_4, so the array becomes [3, 1, 1, 5, 5]; subtract 5 from a_3 and add it to a_5, so the array becomes [3, 1, -4, 5, 10]. So, the resulting array is [3, 1, -4, 5, 10].An array is reachable if it can be obtained by performing the aforementioned sequence of operations on a. You have to calculate the number of reachable arrays, and print it modulo 998244353.InputThe first line contains one integer n (3 \le n \le 300).The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 300).OutputPrint one integer — the number of reachable arrays. Since the answer can be very large, print its remainder modulo 998244353.ExamplesInput 4 1 1 1 1 Output 3 Input 5 1 2 3 5 0 Output 7
4 1 1 1 1
3
2 seconds
512 megabytes
['brute force', 'dp', 'implementation', '*2000']
C. Yet Another Tournamenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are participating in Yet Another Tournament. There are n + 1 participants: you and n other opponents, numbered from 1 to n.Each two participants will play against each other exactly once. If the opponent i plays against the opponent j, he wins if and only if i > j.When the opponent i plays against you, everything becomes a little bit complicated. In order to get a win against opponent i, you need to prepare for the match for at least a_i minutes — otherwise, you lose to that opponent.You have m minutes in total to prepare for matches, but you can prepare for only one match at one moment. In other words, if you want to win against opponents p_1, p_2, \dots, p_k, you need to spend a_{p_1} + a_{p_2} + \dots + a_{p_k} minutes for preparation — and if this number is greater than m, you cannot achieve a win against all of these opponents at the same time.The final place of each contestant is equal to the number of contestants with strictly more wins + 1. For example, if 3 contestants have 5 wins each, 1 contestant has 3 wins and 2 contestants have 1 win each, then the first 3 participants will get the 1-st place, the fourth one gets the 4-th place and two last ones get the 5-th place.Calculate the minimum possible place (lower is better) you can achieve if you can't prepare for the matches more than m minutes in total.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains two integers n and m (1 \le n \le 5 \cdot 10^5; 0 \le m \le \sum\limits_{i=1}^{n}{a_i}) — the number of your opponents and the total time you have for preparation.The second line of each test case contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 1000), where a_i is the time you need to prepare in order to win against the i-th opponent.It's guaranteed that the total sum of n over all test cases doesn't exceed 5 \cdot 10^5.OutputFor each test case, print the minimum possible place you can take if you can prepare for the matches no more than m minutes in total.ExampleInput 54 401100 100 200 13 21 2 35 01 1 1 1 14 00 1 1 14 41 2 2 1Output 1 2 6 4 1 NoteIn the first test case, you can prepare to all opponents, so you'll win 4 games and get the 1-st place, since all your opponents win no more than 3 games.In the second test case, you can prepare against the second opponent and win. As a result, you'll have 1 win, opponent 1 — 1 win, opponent 2 — 1 win, opponent 3 — 3 wins. So, opponent 3 will take the 1-st place, and all other participants, including you, get the 2-nd place.In the third test case, you have no time to prepare at all, so you'll lose all games. Since each opponent has at least 1 win, you'll take the last place (place 6).In the fourth test case, you have no time to prepare, but you can still win against the first opponent. As a result, opponent 1 has no wins, you have 1 win and all others have at least 2 wins. So your place is 4.
54 401100 100 200 13 21 2 35 01 1 1 1 14 00 1 1 14 41 2 2 1
1 2 6 4 1
2 seconds
256 megabytes
['binary search', 'greedy', 'sortings', '*1700']
B. Matrix of Differencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a square matrix of integers of size n \times n, let's define its beauty as follows: for each pair of side-adjacent elements x and y, write out the number |x-y|, and then find the number of different numbers among them.For example, for the matrix \begin{pmatrix} 1 & 3\\ 4 & 2 \end{pmatrix} the numbers we consider are |1-3|=2, |1-4|=3, |3-2|=1 and |4-2|=2; there are 3 different numbers among them (2, 3 and 1), which means that its beauty is equal to 3.You are given an integer n. You have to find a matrix of size n \times n, where each integer from 1 to n^2 occurs exactly once, such that its beauty is the maximum possible among all such matrices.InputThe first line contains a single integer t (1 \le t \le 49) – the number of test cases.The first (and only) line of each test case contains a single integer n (2 \le n \le 50).OutputFor each test case, print n rows of n integers — a matrix of integers of size n \times n, where each number from 1 to n^2 occurs exactly once, such that its beauty is the maximum possible among all such matrices. If there are multiple answers, print any of them.ExampleInput 223Output 1 3 4 2 1 3 4 9 2 7 5 8 6
223
1 3 4 2 1 3 4 9 2 7 5 8 6
2 seconds
256 megabytes
['constructive algorithms', 'math', '*1100']
A. Make it Beautifultime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAn array a is called ugly if it contains at least one element which is equal to the sum of all elements before it. If the array is not ugly, it is beautiful.For example: the array [6, 3, 9, 6] is ugly: the element 9 is equal to 6 + 3; the array [5, 5, 7] is ugly: the element 5 (the second one) is equal to 5; the array [8, 4, 10, 14] is beautiful: 8 \ne 0, 4 \ne 8, 10 \ne 8 + 4, 14 \ne 8 + 4 + 10, so there is no element which is equal to the sum of all elements before it. You are given an array a such that 1 \le a_1 \le a_2 \le \dots \le a_n \le 100. You have to reorder the elements of a in such a way that the resulting array is beautiful. Note that you are not allowed to insert new elements or erase existing ones, you can only change the order of elements of a. You are allowed to keep the array a unchanged, if it is beautiful.InputThe first line contains one integer t (1 \le t \le 2000) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (2 \le n \le 50). The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_1 \le a_2 \le \dots \le a_n \le 100).OutputFor each test case, print the answer as follows: if it is impossible to reorder the elements of a in such a way that it becomes beautiful, print NO; otherwise, in the first line, print YES. In the second line, print n integers — any beautiful array which can be obtained from a by reordering its elements. If there are multiple such arrays, print any of them. ExampleInput 443 3 6 6210 1051 2 3 4 531 4 4Output YES 3 6 3 6 NO YES 2 4 1 5 3 YES 1 4 4
443 3 6 6210 1051 2 3 4 531 4 4
YES 3 6 3 6 NO YES 2 4 1 5 3 YES 1 4 4
3 seconds
512 megabytes
['constructive algorithms', 'math', 'sortings', '*800']
H2. Window Signals (hard version)time limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. In this version, the constraints on h and w are higher.A house at the sea has h floors, all of the same height. The side of the house facing the sea has w windows at equal distances from each other on every floor. Thus, the windows are positioned in cells of a rectangular grid of size h \times w.In every window, the light can be turned either on or off, except for the given k (at most 2) windows. In these k windows the light can not be turned on, because it is broken.In the dark, we can send a signal to a ship at sea using a configuration of lights turned on and off. However, the ship can not see the position of the lights with respect to the house. Thus, if one configuration of windows with lights on can be transformed into another using parallel translation, these configurations are considered equal. Note that only parallel translation is allowed, but neither rotations nor flips are. Moreover, a configuration without any light at all is not considered valid.Find how many different signals the ship can receive and print this number modulo 998\,244\,353.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). The description of the test cases follows.The first line of each test case contains three integers h, w, and k (1 \le h, w \le 200; 0 \le k \le \min(h \cdot w, 2)) — the height of the house, the number of windows on each floor, and the number of windows with broken lights.If k > 0, each of the next k lines contains two integers r_i and c_i (1 \le r_i \le h; 1 \le c_i \le w) — the floor number and the window number with the broken light. The floors are numbered 1 to h from bottom to top, and the windows are numbered 1 to w from left to right. If k = 2, then either r_1 \ne r_2 or c_1 \ne c_2.It is guaranteed that the sum of h \cdot w over all test cases does not exceed 40\,000.OutputFor each test case, print a single integer — the number of signals the ship can receive, modulo 998\,244\,353.ExampleInput 101 3 02 2 03 2 04 5 012 7 01 1 11 11 3 11 23 4 13 42 3 21 12 14 5 22 34 2Output 4 10 44 954368 34903934 0 2 1696 10 253144 NoteIn the first test case, the ship can receive four different signals: all lights on; lights on in two neighboring windows; lights on in the leftmost and the rightmost windows; or light on in any single window.
101 3 02 2 03 2 04 5 012 7 01 1 11 11 3 11 23 4 13 42 3 21 12 14 5 22 34 2
4 10 44 954368 34903934 0 2 1696 10 253144
7 seconds
512 megabytes
['*3500']
H1. Window Signals (easy version)time limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. In this version, the constraints on h and w are lower.A house at the sea has h floors, all of the same height. The side of the house facing the sea has w windows at equal distances from each other on every floor. Thus, the windows are positioned in cells of a rectangular grid of size h \times w.In every window, the light can be turned either on or off, except for the given k (at most 2) windows. In these k windows the light can not be turned on, because it is broken.In the dark, we can send a signal to a ship at sea using a configuration of lights turned on and off. However, the ship can not see the position of the lights with respect to the house. Thus, if one configuration of windows with lights on can be transformed into another using parallel translation, these configurations are considered equal. Note that only parallel translation is allowed, but neither rotations nor flips are. Moreover, a configuration without any light at all is not considered valid.Find how many different signals the ship can receive and print this number modulo 998\,244\,353.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). The description of the test cases follows.The first line of each test case contains three integers h, w, and k (1 \le h, w \le 40; 0 \le k \le \min(h \cdot w, 2)) — the height of the house, the number of windows on each floor, and the number of windows with broken lights.If k > 0, each of the next k lines contains two integers r_i and c_i (1 \le r_i \le h; 1 \le c_i \le w) — the floor number and the window number with the broken light. The floors are numbered 1 to h from bottom to top, and the windows are numbered 1 to w from left to right. If k = 2, then either r_1 \ne r_2 or c_1 \ne c_2.It is guaranteed that the sum of h \cdot w over all test cases does not exceed 1600.OutputFor each test case, print a single integer — the number of signals the ship can receive, modulo 998\,244\,353.ExampleInput 101 3 02 2 03 2 04 5 012 7 01 1 11 11 3 11 23 4 13 42 3 21 12 14 5 22 34 2Output 4 10 44 954368 34903934 0 2 1696 10 253144 NoteIn the first test case, the ship can receive four different signals: all lights on; lights on in two neighboring windows; lights on in the leftmost and the rightmost windows; or light on in any single window.
101 3 02 2 03 2 04 5 012 7 01 1 11 11 3 11 23 4 13 42 3 21 12 14 5 22 34 2
4 10 44 954368 34903934 0 2 1696 10 253144
7 seconds
512 megabytes
['*3200']
G. Diverse Coloringtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn this problem, we will be working with rooted binary trees. A tree is called a rooted binary tree if it has a fixed root and every vertex has at most two children.Let's assign a color — white or blue — to each vertex of the tree, and call this assignment a coloring of the tree. Let's call a coloring diverse if every vertex has a neighbor (a parent or a child) colored into an opposite color compared to this vertex. It can be shown that any tree with at least two vertices allows a diverse coloring.Let's define the disbalance of a coloring as the absolute value of the difference between the number of white vertices and the number of blue vertices.Now to the problem. Initially, the tree consists of a single vertex with the number 1 which is its root. Then, for each i from 2 to n, a new vertex i appears in the tree, and it becomes a child of vertex p_i. It is guaranteed that after each step the tree will keep being a binary tree rooted at vertex 1, that is, each vertex will have at most two children.After every new vertex is added, print the smallest value of disbalance over all possible diverse colorings of the current tree. Moreover, after adding the last vertex with the number n, also print a diverse coloring with the smallest possible disbalance as well.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices in the final tree.The second line contains n-1 integers p_2, p_3, \ldots, p_n (1 \le p_i \le i - 1) — the numbers of parents of vertices 2, 3, \ldots, n. No integer appears more than twice among p_2, p_3, \ldots, p_n.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print n-1 integers — the smallest value of disbalance over all possible diverse colorings of the tree after adding vertices 2, 3, \ldots, n.Then print a string of n characters 'w' and 'b', describing a diverse coloring with the smallest possible disbalance for the whole tree after adding vertex n: the i-th character must be equal to 'w' if vertex i is colored white, and 'b' if it's colored blue. The absolute value of the difference between the numbers of 'w' and 'b' characters must be equal to the last printed integer. Each vertex must have a parent or a child colored into the color opposite to the vertex's color.ExampleInput 271 2 2 1 5 581 2 3 4 5 6 7Output 0 1 2 1 0 1 wbwwwbb 0 1 0 1 0 1 0 wbwbwbwb NoteIn the first test case, examples of diverse colorings with the smallest possible disbalances for all intermediate trees are illustrated below:
271 2 2 1 5 581 2 3 4 5 6 7
0 1 2 1 0 1 wbwwwbb 0 1 0 1 0 1 0 wbwbwbwb
4 seconds
512 megabytes
['constructive algorithms', 'trees', '*3200']
F. Bracket Insertiontime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVika likes playing with bracket sequences. Today she wants to create a new bracket sequence using the following algorithm. Initially, Vika's sequence is an empty string, and then she will repeat the following actions n times: Choose a place in the current bracket sequence to insert new brackets uniformly at random. If the length of the current sequence is k, then there are k+1 such places: before the first bracket, between the first and the second brackets, \ldots, after the k-th bracket. In particular, there is one such place in an empty bracket sequence. Choose string "()" with probability p or string ")(" with probability 1 - p and insert it into the chosen place. The length of the bracket sequence will increase by 2. A bracket sequence is called regular if it is possible to obtain a correct arithmetic expression by inserting characters '+' and '1' into it. For example, sequences "(())()", "()", and "(()(()))" are regular, while ")(", "(()", and "(()))(" are not.Vika wants to know the probability that her bracket sequence will be a regular one at the end. Help her and find this probability modulo 998\,244\,353 (see Output section).InputThe only line contains two integers n and q (1 \le n \le 500; 0 \le q \le 10^4). Here n is equal to the number of bracket insertion operations, and the probability that Vika chooses string "()" on every step of the algorithm is equal to p = q \cdot 10^{-4}.OutputPrint the probability that Vika's final bracket sequence will be regular, modulo 998\,244\,353.Formally, let M = 998\,244\,353. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExamplesInput 1 7500 Output 249561089 Input 2 6000 Output 519087064 Input 5 4000 Output 119387743 NoteIn the first example, Vika will get a regular bracket sequence () with probability p = \frac{3}{4}, and she will get an irregular bracket sequence )( with probability 1 - p = \frac{1}{4}. The sought probability is \frac{3}{4}, and 249\,561\,089 \cdot 4 \equiv 3 \pmod{998\,244\,353}.In the second example, the sought probability is \frac{11}{25}.
1 7500
249561089
4 seconds
512 megabytes
['combinatorics', 'dp', 'math', 'trees', '*2700']
E. Rectangle Shrinkingtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a rectangular grid of height 2 and width 10^9 consisting of unit cells. There are n rectangles placed on this grid, and the borders of these rectangles pass along cell borders. The i-th rectangle covers all cells in rows from u_i to d_i inclusive and columns from l_i to r_i inclusive (1 \le u_i \le d_i \le 2; 1 \le l_i \le r_i \le 10^9). The initial rectangles can intersect, be nested, and coincide arbitrarily.You should either remove each rectangle, or replace it with any of its non-empty subrectangles. In the latter case, the new subrectangle must lie inside the initial rectangle, and its borders must still pass along cell borders. In particular, it is allowed for the subrectangle to be equal to the initial rectangle.After that replacement, no two (non-removed) rectangles are allowed to have common cells, and the total area covered with the new rectangles must be as large as possible. Illustration for the first test case. The initial rectangles are given at the top, the new rectangles are given at the bottom. Rectangle number 4 is removed. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of rectangles.Each of the next n lines contains four integers u_i, l_i, d_i, r_i (1 \le u_i \le d_i \le 2; 1 \le l_i \le r_i \le 10^9) — the coordinates of cells located in the top-left and the bottom-right corners of the rectangle, respectively.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, first print an integer s — the largest possible covered by new rectangles area. Then print n lines with your solution to cover this area.In the i-th of these lines print four integers u'_i, l'_i, d'_i, r'_i. If you remove the i-th rectangle, print u'_i = l'_i = d'_i = r'_i = 0. Otherwise, these numbers denote the new coordinates of the top-left and the bottom-right corners of the i-th rectangle, satisfying u_i \le u'_i \le d'_i \le d_i; l_i \le l'_i \le r'_i \le r_i.If there are multiple solutions, print any.ExampleInput 851 2 2 42 4 2 81 4 2 71 2 1 21 9 1 1021 1 1 101 5 1 1521 1 1 101 1 1 1051 3 1 71 3 1 81 1 1 41 2 1 71 10 1 1121 1 2 101 5 1 821 5 2 101 2 1 721 5 2 102 2 2 1552 6 2 71 4 2 51 5 1 91 7 2 101 2 1 6Output 15 1 2 2 4 2 5 2 8 1 5 1 7 0 0 0 0 1 9 1 10 15 1 1 1 10 1 11 1 15 10 1 1 1 10 0 0 0 0 10 0 0 0 0 1 8 1 8 1 1 1 4 1 5 1 7 1 10 1 11 20 1 1 2 10 0 0 0 0 15 1 5 2 10 1 2 1 4 20 1 5 1 10 2 2 2 15 16 2 6 2 6 2 4 2 5 0 0 0 0 1 7 2 10 1 2 1 6 NoteThe picture in the statement illustrates the first test case.
851 2 2 42 4 2 81 4 2 71 2 1 21 9 1 1021 1 1 101 5 1 1521 1 1 101 1 1 1051 3 1 71 3 1 81 1 1 41 2 1 71 10 1 1121 1 2 101 5 1 821 5 2 101 2 1 721 5 2 102 2 2 1552 6 2 71 4 2 51 5 1 91 7 2 101 2 1 6
15 1 2 2 4 2 5 2 8 1 5 1 7 0 0 0 0 1 9 1 10 15 1 1 1 10 1 11 1 15 10 1 1 1 10 0 0 0 0 10 0 0 0 0 1 8 1 8 1 1 1 4 1 5 1 7 1 10 1 11 20 1 1 2 10 0 0 0 0 15 1 5 2 10 1 2 1 4 20 1 5 1 10 2 2 2 15 16 2 6 2 6 2 4 2 5 0 0 0 0 1 7 2 10 1 2 1 6
4 seconds
512 megabytes
['binary search', 'brute force', 'data structures', 'greedy', 'implementation', 'two pointers', '*2300']
D. Many Perfect Squarestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a set a_1, a_2, \ldots, a_n of distinct positive integers.We define the squareness of an integer x as the number of perfect squares among the numbers a_1 + x, a_2 + x, \ldots, a_n + x.Find the maximum squareness among all integers x between 0 and 10^{18}, inclusive.Perfect squares are integers of the form t^2, where t is a non-negative integer. The smallest perfect squares are 0, 1, 4, 9, 16, \ldots.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 50). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 50) — the size of the set.The second line contains n distinct integers a_1, a_2, \ldots, a_n in increasing order (1 \le a_1 < a_2 < \ldots < a_n \le 10^9) — the set itself.It is guaranteed that the sum of n over all test cases does not exceed 50.OutputFor each test case, print a single integer — the largest possible number of perfect squares among a_1 + x, a_2 + x, \ldots, a_n + x, for some 0 \le x \le 10^{18}.ExampleInput 451 2 3 4 551 6 13 22 97110052 5 10 17 26Output 2 5 1 2 NoteIn the first test case, for x = 0 the set contains two perfect squares: 1 and 4. It is impossible to obtain more than two perfect squares.In the second test case, for x = 3 the set looks like 4, 9, 16, 25, 100, that is, all its elements are perfect squares.
451 2 3 4 551 6 13 22 97110052 5 10 17 26
2 5 1 2
4 seconds
512 megabytes
['brute force', 'math', 'number theory', '*1800']
C. Equal Frequenciestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's call a string balanced if all characters that are present in it appear the same number of times. For example, "coder", "appall", and "ttttttt" are balanced, while "wowwow" and "codeforces" are not.You are given a string s of length n consisting of lowercase English letters. Find a balanced string t of the same length n consisting of lowercase English letters that is different from the string s in as few positions as possible. In other words, the number of indices i such that s_i \ne t_i should be as small as possible.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.Each test case consists of two lines. The first line contains a single integer n (1 \le n \le 10^5) — the length of the string s.The second line contains the string s of length n consisting of lowercase English letters.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print the smallest number of positions where string s and a balanced string t can differ, followed by such a string t.If there are multiple solutions, print any. It can be shown that at least one balanced string always exists.ExampleInput 45hello10codeforces5eevee6appallOutput 1 helno 2 codefofced 1 eeeee 0 appall NoteIn the first test case, the given string "hello" is not balanced: letters 'h', 'e', and 'o' appear in it once, while letter 'l' appears twice. On the other hand, string "helno" is balanced: five distinct letters are present in it, and each of them appears exactly once. Strings "hello" and "helno" differ in just one position: the fourth character. Other solutions are possible too.In the second test case, string "codefofced" is balanced since only letters 'c', 'o', 'd', 'e', and 'f' are present in it, and each of them appears exactly twice.In the third test case, string "eeeee" is balanced since only letter 'e' is present in it.In the fourth test case, the given string "appall" is already balanced.
45hello10codeforces5eevee6appall
1 helno 2 codefofced 1 eeeee 0 appall
2 seconds
512 megabytes
['brute force', 'constructive algorithms', 'greedy', 'implementation', 'sortings', 'strings', '*1600']
B. Going to the Cinematime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA company of n people is planning a visit to the cinema. Every person can either go to the cinema or not. That depends on how many other people will go. Specifically, every person i said: "I want to go to the cinema if and only if at least a_i other people will go, not counting myself". That means that person i will become sad if: they go to the cinema, and strictly less than a_i other people go; or they don't go to the cinema, and at least a_i other people go. In how many ways can a set of people going to the cinema be chosen so that nobody becomes sad?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.Each test case consists of two lines. The first line contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of people in the company.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le n - 1) — integers from peoples' claims.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the number of different ways to choose a set of people going to the cinema so that nobody becomes sad.ExampleInput 421 170 1 2 3 4 5 686 0 3 3 6 7 2 753 0 0 3 3Output 2 1 3 2 NoteIn the first test case, both people want to go to the cinema if and only if the other person goes. There are two valid options: either both people go, or neither of them goes. However, if just one of them goes, both will be sad.In the second test case, everyone has to go to the cinema. In any other case, someone will be sad.In the third test case, there are three valid options: person number 2 goes to the cinema; or persons with indices 2, 3, 4, 7 go; or all eight people go.
421 170 1 2 3 4 5 686 0 3 3 6 7 2 753 0 0 3 3
2 1 3 2
2 seconds
512 megabytes
['brute force', 'greedy', 'sortings', '*1000']
A. Parallel Projectiontime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputVika's house has a room in a shape of a rectangular parallelepiped (also known as a rectangular cuboid). Its floor is a rectangle of size w \times d, and the ceiling is right above at the constant height of h. Let's introduce a coordinate system on the floor so that its corners are at points (0, 0), (w, 0), (w, d), and (0, d).A laptop is standing on the floor at point (a, b). A projector is hanging on the ceiling right above point (f, g). Vika wants to connect the laptop and the projector with a cable in such a way that the cable always goes along the walls, ceiling, or floor (i. e. does not go inside the cuboid). Additionally, the cable should always run parallel to one of the cuboid's edges (i. e. it can not go diagonally).What is the minimum length of a cable that can connect the laptop to the projector? Illustration for the first test case. One of the optimal ways to put the cable is shown in green. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains three integers w, d, and h (2 \le w, d, h \le 1000) — the size of the room.The second line contains four integers a, b, f, g (0 < a, f < w; 0 < b, g < d): the laptop is located on the floor at point (a, b), while the projector is hanging on the ceiling right above point (f, g).OutputFor each test case, print a single integer — the minimum length of the cable connecting the laptop and the projector that runs only along the walls, floor, and ceiling parallel to cuboid's edges.ExampleInput 555 20 2923 10 18 320 10 51 5 2 515 15 47 13 10 102 1000 21 1 1 99910 4 107 1 2 1Output 47 8 14 1002 17 NoteThe picture in the statement illustrates the first test case.
555 20 2923 10 18 320 10 51 5 2 515 15 47 13 10 102 1000 21 1 1 99910 4 107 1 2 1
47 8 14 1002 17
1 second
512 megabytes
['geometry', 'math', '*800']
G. Delicious Desserttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputToday is an important day for chef Tonio — an auditor has arrived in his hometown of Morioh. He has also arrived at Tonio's restaurant and ordered dessert. Tonio has not been prepared for this turn of events.As you know, dessert is a string of lowercase English letters. Tonio remembered the rule of desserts — a string s of length n. Any dessert t is delicious if the number of occurrences of t in s as a substring is divisible by the length of t.Now Tonio wants to know the number of delicious substrings of s. If the substring occurs several times in the string s, then all occurrences must be taken into account.InputThe first line contains an integer n (1 \leq n \leq 10^6) — the length of the rule s.The second line contains the string s of length n — the rule. The rule consists only of lowercase English letters.OutputIn a single line print the number of delicious substrings of s.ExamplesInput 7 abacaba Output 11 Input 8 abaababa Output 11 Input 10 deadinside Output 12 Input 5 aaaaa Output 12 NoteIn the first sample, there are many delicious substrings. 7 of them are substrings of length 1 (because any number is divisible by 1). Consider other delicious substrings: "ab" occurs in s 2 times, which is divisible by the length of the substring. "ba" also occurs 2 times. Therefore, the answer is 7 + 2 + 2 = 11.Note that the answer includes both occurrences of "ab" and "ba".
7 abacaba
11
3 seconds
512 megabytes
['binary search', 'dsu', 'hashing', 'math', 'number theory', 'string suffix structures', '*2400']
F. Three Chairstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Kira found n friends from Morioh and decided to gather them around a table to have a peaceful conversation. The height of friend i is equal to a_i. It so happened that the height of each of the friends is unique.Unfortunately, there were only 3 chairs in Kira's house, and obviously, it will not be possible to seat all friends! So, Kira has to invite only 3 of his friends.But everything is not so simple! If the heights of the lowest and the tallest of the invited friends are not coprime, then the friends will play tricks on each other, which will greatly anger Kira.Kira became interested, how many ways are there to choose 3 of his friends so that they don't play tricks? Two ways are considered different if there is a friend invited in one way, but not in the other.Formally, if Kira invites friends i, j, and k, then the following should be true: \gcd(\min(a_i, a_j, a_k), \max(a_i, a_j, a_k)) = 1, where \gcd(x, y) denotes the greatest common divisor (GCD) of the numbers x and y.Kira is not very strong in computer science, so he asks you to count the number of ways to invide friends.InputThe first line contains the number n (3 \le n \le 3\cdot10^5) — the number of Kira's friends.The next line contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i \le 3\cdot10^5) — heights of Kira's friends.OutputIn a single line output the number of ways to invite three friends.ExamplesInput 3 1 2 3 Output 1 Input 4 1 6 2 3 Output 3 Input 4 16 4 8 2 Output 0 Input 10 10 1 6 7 9 8 4 3 5 2 Output 77 NoteIn the first example, only one way is suitable: invite friends 1, 2, and 3. Here 1 < 2 < 3, and the numbers 1 and 3 are coprime.
3 1 2 3
1
1 second
256 megabytes
['bitmasks', 'brute force', 'combinatorics', 'data structures', 'dp', 'number theory', 'sortings', '*2300']
E. Josuke and Complete Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJosuke received a huge undirected weighted complete^\dagger graph G as a gift from his grandfather. The graph contains 10^{18} vertices. The peculiarity of the gift is that the weight of the edge between the different vertices u and v is equal to \gcd(u, v)^\ddagger. Josuke decided to experiment and make a new graph G'. To do this, he chooses two integers l \le r and deletes all vertices except such vertices v that l \le v \le r, and also deletes all the edges except between the remaining vertices.Now Josuke is wondering how many different weights are there in G'. Since their count turned out to be huge, he asks for your help.^\dagger A complete graph is a simple undirected graph in which every pair of distinct vertices is adjacent.^\ddagger \gcd(x, y) denotes the greatest common divisor (GCD) of the numbers x and y.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains two numbers l, r (1 \le l \le r \le 10^{18}, l \le 10^9).OutputFor each test case print a single number — the number of different weights among the remaining edges.ExampleInput 72 416 242 61 103 32562 2568125 100090Output 2 6 3 5 0 5 50045 Note The graph G' for the first test case. The picture above shows that the graph has 2 different weights.In the fifth test case, there is only one vertex from which no edges originate, so the answer is 0.
72 416 242 61 103 32562 2568125 100090
2 6 3 5 0 5 50045
2 seconds
256 megabytes
['binary search', 'brute force', 'data structures', 'math', 'number theory', '*2400']
D. Bit Guessing Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Kira has a hidden positive integer n, and Hayato needs to guess it.Initially, Kira gives Hayato the value \mathrm{cnt} — the number of unit bits in the binary notation of n. To guess n, Hayato can only do operations of one kind: choose an integer x and subtract it from n. Note that after each operation, the number n changes. Kira doesn't like bad requests, so if Hayato tries to subtract a number x greater than n, he will lose to Kira. After each operation, Kira gives Hayato the updated value \mathrm{cnt} — the number of unit bits in the binary notation of the updated value of n.Kira doesn't have much patience, so Hayato must guess the original value of n after no more than 30 operations.Since Hayato is in elementary school, he asks for your help. Write a program that guesses the number n. Kira is an honest person, so he chooses the initial number n before all operations and does not change it afterward.InputThe input data contains several test cases. The first line contains one integer t (1 \le t \le 500) — the number of test cases. The description of the test cases follows.The first line of each test case contains the number \mathrm{cnt} — the initial number of unit bits in the binary notation n.The hidden integer n satisfies the following constraint: 1 \le n \le 10^9.InteractionTo guess n, you can perform the operation at most 30 times. To do that, print a line with the following format: "- x" (1 \le x \le 10^9).After this operation, the number x is subtracted from n, and therefore n is changed. If the number x is greater than the current value of n, then the request is considered invalid.After the operation read a line containing a single non-negative integer \mathrm{cnt} — the number of unit bits in the binary notation of the current n after the operation.When you know the initial value of n, print one line in the following format: "! n" (1 \le n \le 10^9).After that, move on to the next test case, or terminate the program if there are none.If your program performs more than 30 operations for one test case, subtracts a number x greater than n, or makes an incorrect request, then response to the request will be -1, after receiving such response, your program must exit immediately to receive the Wrong Answer verdict. Otherwise, you can get any other verdict.After printing a query or the answer, do not forget to output the 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. HacksTo make a hack, use the following format.The first line should contain a single integer t (1 \leq t \leq 500).Each test case should contain one integer n (1 \leq n \leq 10^9) on a separate line.ExampleInput 3 1 0 1 1 0 2 1 0Output - 1 ! 1 - 1 - 1 ! 2 - 2 - 1 ! 3NoteFor example, the number of unit bits in number 6 is 2, because binary notation of 6 is 110. For 13 the number of unit bits is 3, because 13_{10} = 1101_2.In the first test case, n = 1, so the input is the number 1. After subtracting one from n, it becomes zero, so the number of unit bits in it is 0.In the third test case, n = 3, which in binary representation looks like 3_{10} = 11_2, so the input is the number of ones, that is 2. After subtracting 2, n = 1, so the number of unit bits is now 1. After subtracting one from n, it becomes equal to zero.Note that the blank lines in the input and output examples are shown for clarity and are not present in the actual interaction.
3 1 0 1 1 0 2 1 0
- 1 ! 1 - 1 - 1 ! 2 - 2 - 1 ! 3
1 second
256 megabytes
['binary search', 'bitmasks', 'constructive algorithms', 'interactive', '*1800']
B. GCD Partitiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile at Kira's house, Josuke saw a piece of paper on the table with a task written on it.The task sounded as follows. There is an array a of length n. On this array, do the following: select an integer k > 1; split the array into k subsegments ^\dagger; calculate the sum in each of k subsegments and write these sums to another array b (where the sum of the subsegment (l, r) is {\sum_{j = l}^{r}a_j}); the final score of such a split will be \gcd(b_1, b_2, \ldots, b_k)^\ddagger. The task is to find such a partition that the score is maximum possible. Josuke is interested in this task but is not strong in computer science. Help him to find the maximum possible score.^\dagger A division of an array into k subsegments is k pairs of numbers (l_1, r_1), (l_2, r_2), \ldots, (l_k, r_k) such that l_i \le r_i and for every 1 \le j \le k - 1 l_{j + 1} = r_j + 1, also l_1 = 1 and r_k = n. These pairs represent the subsegments.^\ddagger \gcd(b_1, b_2, \ldots, b_k) stands for the greatest common divisor (GCD) of the array b.InputThe first line contains a single number t (1 \le t \le 10^4) — the number of test cases.For each test case, the first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the length of the array a.The second line contains n integers a_1, a_2, a_3, \ldots, a_n (1 \le a_i \le 10^9 ) — the array a itself.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print a single integer — the maximum score for the optimal partition.ExampleInput 642 2 1 321 231 4 561 2 1 1 1 31012 30 37 88 12 78 89 17 2 1267 7 7 7 7 7Output 4 1 5 3 1 21 NoteIn the first test case, you can choose k = 2 and split the array into subsegments (1, 2) and (3, 4).Then the score of such a partition will be equal to \gcd(a_1 + a_2, a_3 + a_4) = \gcd(2 + 2, 1 + 3) = \gcd(4, 4) = 4.In the fourth test case, you can choose k = 3 and split the array into subsegments (1, 2), (3, 5), (6, 6).The split score is \gcd(1 + 2, 1 + 1 + 1, 3) = 3.
642 2 1 321 231 4 561 2 1 1 1 31012 30 37 88 12 78 89 17 2 1267 7 7 7 7 7
4 1 5 3 1 21
1 second
256 megabytes
['brute force', 'greedy', 'math', 'number theory', '*1100']
A. Hayato and Schooltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Hayato came home from school with homework.In the assignment, Hayato was given an array a of length n. The task was to find 3 numbers in this array whose sum is odd. At school, he claimed that there are such 3 numbers, but Hayato was not sure, so he asked you for help.Answer if there are such three numbers, and if so, output indices i, j, and k such that a_i + a_j + a_k is odd.The odd numbers are integers that are not divisible by 2: 1, 3, 5, and so on.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.For each test case, the first line contains one integer n (3 \le n \le 300) — the length of a.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^5) — the array a.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case, in the first line print one word "YES" (without quotes) if there are 3 numbers with an odd sum or "NO" (without quotes) if there are no such 3 numbers.If the answer exists, then on the second line print 3 distinct integers i, j, k (1 \le i, j, k \le n) — the indices of the numbers. If there are several answers, output any.ExampleInput 631 1 141 1 2 231 2 351 4 5 1 242 6 2 455 6 3 2 1Output YES 1 2 3 YES 3 4 1 NO YES 1 3 4 NO YES 1 3 5 NoteIn the first test case, there is one way to choose 3 numbers, and since 1 + 1 + 1 = 3, this triple is fine for us.In the second test case, you need to choose the numbers 1, 2, 2, since 1 + 2 + 2 = 5.In the third test case, there is one way to choose three numbers, but 1 + 2 + 3 = 6 is an even number, so the required triple does not exist.In the fifth test case, no matter what three numbers we choose, their sum is even.
631 1 141 1 2 231 2 351 4 5 1 242 6 2 455 6 3 2 1
YES 1 2 3 YES 3 4 1 NO YES 1 3 4 NO YES 1 3 5
1 second
256 megabytes
['constructive algorithms', 'greedy', '*800']
H. Olympic Team Buildingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIron and Werewolf are participating in a chess Olympiad, so they want to practice team building. They gathered n players, where n is a power of 2, and they will play sports. Iron and Werewolf are among those n people.One of the sports is tug of war. For each 1\leq i \leq n, the i-th player has strength s_i. Elimination rounds will be held until only one player remains — we call that player the absolute winner.In each round: Assume that m>1 players are still in the game, where m is a power of 2. The m players are split into two teams of equal sizes (i. e., with m/2 players in each team). The strength of a team is the sum of the strengths of its players. If the teams have equal strengths, Iron chooses who wins; otherwise, the stronger team wins. Every player in the losing team is eliminated, so m/2 players remain. Iron already knows each player's strength and is wondering who can become the absolute winner and who can't if he may choose how the teams will be formed in each round, as well as the winning team in case of equal strengths.InputThe first line contains a single integer n (4 \leq n \leq 32) — the number of players participating in tug of war. It is guaranteed that n is a power of 2.The second line consists of a sequence s_1,s_2, \ldots, s_n of integers (1 \leq s_i \leq 10^{15}) — the strengths of the players.OutputIn a single line output a binary string s of length n — the i-th character of s should be 1 if the i-th player can become the absolute winner and it should be 0 otherwise.ExamplesInput 4 60 32 59 87 Output 1001 Input 4 100 100 100 100 Output 1111 Input 8 8 8 8 8 4 4 4 4 Output 11110000 Input 32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Output 00000000000000001111111111111111 Input 16 1 92875987325987 1 1 92875987325986 92875987325985 1 92875987325988 92875987325990 92875987325989 1 1 92875987325984 92875987325983 1 1 Output 0100110111001000 NoteIn the first example, players 1 and 4 with their respective strengths of 60 and 87 can become the absolute winners.Let's describe the process for player 1. Firstly, we divide the players into teams [1,3] and [2,4]. Strengths of those two teams are 60+59=119 and 32+87=119. They they are equal, Iron can choose to disqualify any of the two teams. Let his choice be the second team.We are left with players 1 and 3. Since 1 has greater strength (60>59) they win and are declared the absolute winner as they are the last remaining player.In the third example, the strengths of the remaining players may look like [8,8,8,8,4,4,4,4] \rightarrow [8,8,4,4] \rightarrow [8,4] \rightarrow [8]. Each person with strength 8 can become the absolute winner and it can be proved that others can't.
4 60 32 59 87
1001
2 seconds
256 megabytes
['brute force', 'meet-in-the-middle', '*3500']
G. The Game of the Centurytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe time has finally come, MKnez and Baltic are to host The Game of the Century. For that purpose, they built a village to lodge its participants.The village has the shape of an equilateral triangle delimited by three roads of length n. It is cut into n^2 smaller equilateral triangles, of side length 1, by 3n-3 additional roads which run parallel to the sides. See the figure for n=3. Each of the 3n roads is made of multiple (possibly 1) road segments of length 1 which connect adjacent intersections. The direction has already been chosen for each of the 3n roads (so, for each road, the same direction is assigned to all its road segments). Traffic can only go in the specified directions (i. e. the roads are monodirectional).You are tasked with making adjustments to the traffic plan so that from each intersection it is possible to reach every other intersection. Specifically, you can invert the traffic direction of any number of road segments of length 1. What is the minimal number of road segments for which you need to invert the traffic direction?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10\,000). The description of the test cases follows.The first line of each test case contains a positive integer n (1\leq n\leq 10^5)  — the size of the triangular village's sides.Three lines follow, each containing a binary string of length n which describes the traffic directions of the roads. The i-th of the following three lines contains a binary string s_i of length n representing the direction of each road parallel to the road segment denoted by i in the picture above. In particular, the j-th character of s_i is "1" if the j-th shortest road (parallel to the road segment denoted by i in the picture) has the same direction of the road segment denoted by i in the picture, while it is "0" if it has the opposite direction. So the first character of s_i describes the direction of the road containing only 1 road segment, while the last character describes the direction of the road containing n road segments.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print the minimum number of road segments for which you need to invert the traffic direction.ExampleInput 3300100101010003111011100Output 2 0 3 NoteThe first example corresponds to the picture in the statement. There exist multiple solutions that invert the traffic direction of exactly 2 road segments, but inverting only 1 road segment never makes it possible to reach every intersection from any other. One of the possible solutions is shown in the picture below in which the inverted road segments are highlighted in blue. In the second example, the answer is 0 since it is already possible to reach every intersection from any other.
3300100101010003111011100
2 0 3
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'shortest paths', '*3000']
F. Xorcerer's Stonestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMisha had been banned from playing chess for good since he was accused of cheating with an engine. Therefore, he retired and decided to become a xorcerer.One day, while taking a walk in a park, Misha came across a rooted tree with nodes numbered from 1 to n. The root of the tree is node 1. For each 1\le i\le n, node i contains a_i stones in it. Misha has recently learned a new spell in his xorcery class and wants to test it out. A spell consists of: Choose some node i (1 \leq i \leq n). Calculate the bitwise XOR x of all a_j such that node j is in the subtree of i (i belongs to its own subtree). Set a_j equal to x for all nodes j in the subtree of i. Misha can perform at most 2n spells and he wants to remove all stones from the tree. More formally, he wants a_i=0 to hold for each 1\leq i \leq n. Can you help him perform the spells?A tree with n nodes is a connected acyclic graph which contains n-1 edges. The subtree of node i is the set of all nodes j such that i lies on the simple path from 1 (the root) to j. We consider i to be contained in its own subtree.InputThe first line contains a single integer n (2 \leq n \leq 2\cdot 10^5) — the size of the treeThe second line contains an array of integers a_1,a_2,\ldots, a_n (0 \leq a_i \leq 31), describing the number of stones in each node initially.The third line contains an array of integers p_2,p_3,\ldots, p_n (1 \leq p_i \leq i-1), where p_i means that there is an edge connecting p_i and i.OutputIf there is not a valid sequence of spells, output -1.Otherwise, output a single integer q (0 \leq q \leq 2n) in the first line — the number of performed spells.In the second line output a sequence of integers v_1,v_2,\ldots,v_q (1 \leq v_i \leq n) — the i-th spell will be performed on the subtree of node v_i. Please note that order matters.If multiple solutions exist, output any. You don't have to minimize the number of operations.ExamplesInput 2 13 13 1 Output 1 1 Input 7 5 2 8 3 4 1 31 1 1 2 2 3 3 Output -1 Input 9 3 31 1 2 7 30 7 3 1 1 1 1 2 5 5 3 4 Output 6 3 2 3 1 2 2NotePlease refer to the following pictures for an explanation of the third test. Only the first 4 spells are shown since the last 2 do nothing. The first picture represents the tree initially with the number of stones for each node written above it in green. Changes applied by the current spell are highlighted in red.
2 13 13 1
1 1
4 seconds
512 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'trees', '*2500']
E. Anya's Simultaneous Exhibitiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Anya has gathered n chess experts numbered from 1 to n for which the following properties hold: For any pair of players one of the players wins every game against the other (and no draws ever occur); Transitivity does not necessarily hold — it might happen that A always beats B, B always beats C and C always beats A. Anya does not know, for each pair, who is the player who beats the other.To organize a tournament, Anya hosts n-1 games. In each game, she chooses two players. One of them wins and stays, while the other one is disqualified. After all the games are hosted only one player will remain. A player is said to be a candidate master if they can win a tournament (notice that the winner of a tournament may depend on the players selected by Anya in the n-1 games).Since Anya is a curious girl, she is interested in finding the candidate masters. Unfortunately, she does not have much time. To speed up the process, she will organize up to 2n simuls (short for "simultaneous exhibition", in which one player plays against many).In one simul, Anya chooses exactly one player who will play against some (at least one) of the other players. The chosen player wins all games they would win in a regular game, and the same holds for losses. After the simul finishes, Anya is only told the total number of games won by the chosen player (but not which ones). Nobody is disqualified during a simul.Can you help Anya host simuls and determine the candidate masters?The winning players in each pair could be changed between the simuls, but only in a way that preserves the results of all previous simuls. These changes may depend on your queries.InteractionFirstly, the jury sends one integer n (3 \leq n \leq 250) which should be read — the number of players. After that, your program may ask queries or report an answer.To ask a query, print "? i \; s_1 s_2 \ldots s_n" (without quotes), where i is the index of the player who will play against some of the other players in the simul. s is a binary string that denotes the players they play against. i plays against every player j for which s_j = 1 holds (and s_j = 1 should hold for at least one 1 \leq j \leq n). Please note that s_i = 0 must hold since a player cannot play against themselves, otherwise, the query is considered to be incorrect.After this, you should read an integer — the number of games player i has won.When you have identified the answer, you must print "! c_1 c_2 \ldots c_n" (without quotes) and terminate your program. c is a binary string which represents the candidate masters. Player i is a candidate master if c_i=1 holds, otherwise, they are not.If you ask more than 2n queries or if one of the queries is malformed, the interaction terminates immediately and your program receives verdict Wrong Answer.After printing a query do not forget to output the 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 the documentation for other languages. Hacks are disabled in this problem.ExamplesInput 3 1 1 1 Output ? 1 010 ? 2 001 ? 3 100 ! 111 Input 5 0 3 4Output ? 5 10110 ? 2 10111 ? 1 01111 ! 10000 NoteIn the first example, the first query describes a simul in which player 1 plays against player 2 (and no one else). The answer to the query is 1, meaning that player 1 won the only game they played. We can conclude that 1 beats 2. Similarly, the second query tells us that 2 beats 3 and the third query tells us that 3 beats 1. All players are candidate masters in this case as Player 1 can win the tournament if 2 and 3 play first. 3 loses and leaves, while 2 stays. 1 then plays against 2 and wins; Other players can win in the same fashion. In the second example, the third query describes a simul in which player 1 plays against every other player. The answer to the query is 4, meaning that they won every game they played. It can be concluded that player 1 also beats every other player. They can never lose, hence they are the only player who can remain at the end of every possible tournament, and the only possible candidate master.
3 1 1 1
? 1 010 ? 2 001 ? 3 100 ! 111
1 second
256 megabytes
['constructive algorithms', 'graphs', 'greedy', 'interactive', 'sortings', '*2400']
D. Boris and His Amazing Haircuttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBoris thinks that chess is a tedious game. So he left his tournament early and went to a barber shop as his hair was a bit messy.His current hair can be described by an array a_1,a_2,\ldots, a_n, where a_i is the height of the hair standing at position i. His desired haircut can be described by an array b_1,b_2,\ldots, b_n in a similar fashion.The barber has m razors. Each has its own size and can be used at most once. In one operation, he chooses a razor and cuts a segment of Boris's hair. More formally, an operation is: Choose any razor which hasn't been used before, let its size be x; Choose a segment [l,r] (1\leq l \leq r \leq n); Set a_i := \min (a_i,x) for each l\leq i \leq r; Notice that some razors might have equal sizes — the barber can choose some size x only as many times as the number of razors with size x. He may perform as many operations as he wants, as long as any razor is used at most once and a_i = b_i for each 1 \leq i \leq n at the end. He does not have to use all razors.Can you determine whether the barber can give Boris his desired haircut?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 20\,000). The description of the test cases follows.The first line of each test case contains a positive integer n (3\leq n\leq 2\cdot 10^5) — the length of arrays a and b.The second line of each test case contains n positive integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9)  — Boris's current hair.The third line of each test case contains n positive integers b_1, b_2, \ldots, b_n (1 \leq b_i \leq 10^9)  — Boris's desired hair.The fourth line of each test case contains a positive integer m (1 \leq m \leq 2\cdot 10^5)  — the number of razors.The fifth line of each test case contains m positive integers x_1,x_2, \ldots, x_m (1 \leq x_i \leq 10^9)  — the sizes of the razors.It is guaranteed that the sum of n and the sum of m over all test cases do not exceed 2\cdot 10^5.OutputFor each test case, print "YES" if the barber can cut Boris's hair as desired. Otherwise, print "NO".You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput 733 3 32 1 221 263 4 4 6 3 43 1 2 3 2 333 2 3101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 10101 2 3 4 5 6 7 8 9 1031 1 11 1 2124 2 4 3 1 5 6 3 5 6 2 1137 9 4 5 3 3 3 6 8 10 3 2 55 3 1 5 3 2 2 5 8 5 1 1 581 5 3 5 4 2 3 1137 9 4 5 3 3 3 6 8 10 3 2 55 3 1 5 3 2 2 5 8 5 1 1 571 5 3 4 2 3 1319747843 2736467 9385783972039844 2039844 203984412039844Output YES NO YES NO YES NO YES NoteIn the first test case, Boris's hair is initially [3,3,3]. Let us describe a sequence of 2 operations the barber can perform: The barber uses the razor with size 1 on the segment [2,2]; hence Boris's hair becomes [3,1,3]. The barber uses the razor with size 2 on the segment [1,3]; hence Boris's hair becomes [2,1,2] which is the desired haircut. In the third test case, no operation has to be done since Boris's hair is already as desired.In the fourth test case, no cuts will be able to increase the third element in [1,1,1] in a way that the array becomes [1,1,2].
733 3 32 1 221 263 4 4 6 3 43 1 2 3 2 333 2 3101 2 3 4 5 6 7 8 9 101 2 3 4 5 6 7 8 9 10101 2 3 4 5 6 7 8 9 1031 1 11 1 2124 2 4 3 1 5 6 3 5 6 2 1137 9 4 5 3 3 3 6 8 10 3 2 55 3 1 5 3 2 2 5 8 5 1 1 581 5 3 5 4 2 3 1137 9 4 5 3 3 3 6 8 10 3 2 55 3 1 5 3 2 2 5 8 5 1 1 571 5 3 4 2 3 1319747843 2736467 9385783972039844 2039844 203984412039844
YES NO YES NO YES NO YES
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'dp', 'dsu', 'greedy', 'sortings', '*1700']
C. Least Prefix Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBaltic, a famous chess player who is also a mathematician, has an array a_1,a_2, \ldots, a_n, and he can perform the following operation several (possibly 0) times: Choose some index i (1 \leq i \leq n); multiply a_i with -1, that is, set a_i := -a_i. Baltic's favorite number is m, and he wants a_1 + a_2 + \cdots + a_m to be the smallest of all non-empty prefix sums. More formally, for each k = 1,2,\ldots, n it should hold that a_1 + a_2 + \cdots + a_k \geq a_1 + a_2 + \cdots + a_m.Please note that multiple smallest prefix sums may exist and that it is only required that a_1 + a_2 + \cdots + a_m is one of them.Help Baltic find the minimum number of operations required to make a_1 + a_2 + \cdots + a_m the least of all prefix sums. It can be shown that a valid sequence of operations always exists.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10\,000). The description of the test cases follows.The first line of each test case contains two integers n and m (1 \leq m \leq n \leq 2\cdot 10^5) — the size of Baltic's array and his favorite number.The second line contains n integers a_1,a_2, \ldots, a_n (-10^9 \leq a_i \leq 10^9) — the array.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, print a single integer — the minimum number of required operations.ExampleInput 64 3-1 -2 -3 -44 31 2 3 41 115 5-2 3 -5 1 -205 2-2 3 -5 -5 -2010 4345875723 -48 384678321 -375635768 -35867853 -35863586 -358683842 -81725678 38576 -357865873Output 1 1 0 0 3 4 NoteIn the first example, we perform the operation a_4 := -a_4. The array becomes [-1,-2,-3,4] and the prefix sums, [a_1, \ a_1+a_2, \ a_1+a_2+a_3, \ a_1+a_2+a_3+a_4], are equal to [-1,-3,-6,-2]. Thus a_1 + a_2 + a_3=-6 is the smallest of all prefix sums.In the second example, we perform the operation a_3 := -a_3. The array becomes [1,2,-3,4] with prefix sums equal to [1,3,0,4].In the third and fourth examples, a_1 + a_2 + \cdots + a_m is already the smallest of the prefix sums — no operation needs to be performed.In the fifth example, a valid sequence of operations is: a_3 := -a_3, a_2 := -a_2, a_5 := -a_5. The array becomes [-2,-3,5,-5,20] and its prefix sums are [-2,-5,0,-5,15]. Note that a_1+a_2=-5 and a_1+a_2+a_3+a_4=-5 are both the smallest of the prefix sums (and this is a valid solution).
64 3-1 -2 -3 -44 31 2 3 41 115 5-2 3 -5 1 -205 2-2 3 -5 -5 -2010 4345875723 -48 384678321 -375635768 -35867853 -35863586 -358683842 -81725678 38576 -357865873
1 1 0 0 3 4
2 seconds
256 megabytes
['data structures', 'greedy', '*1600']
B. MKnez's ConstructiveForces Tasktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMKnez wants to construct an array s_1,s_2, \ldots , s_n satisfying the following conditions: Each element is an integer number different from 0; For each pair of adjacent elements their sum is equal to the sum of the whole array. More formally, s_i \neq 0 must hold for each 1 \leq i \leq n. Moreover, it must hold that s_1 + s_2 + \cdots + s_n = s_i + s_{i+1} for each 1 \leq i < n.Help MKnez to construct an array with these properties or determine that it does not exist.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 100). The description of the test cases follows.The only line of each test case contains a single integer n (2 \leq n \leq 1000) — the length of the array.OutputFor each test case, print "YES" if an array of length n satisfying the conditions exists. Otherwise, print "NO". If the answer is "YES", on the next line print a sequence s_1,s_2, \ldots, s_n satisfying the conditions. Each element should be a non-zero integer in the range [-5000,5000], i. e. -5000 \leq s_i \leq 5000 and s_i \neq 0 should hold for each 1 \leq i \leq n.It can be proved that if a solution exists then there also exists one which satisfies the additional constraints on the range.If there are several correct answers, print any of them. ExampleInput 2 2 3 Output YES 9 5 NO NoteIn the first test case, [9,5] is a valid answer since 9+5 (the sum of the two adjacent elements s_1+s_2) is equal to 9+5 (the sum of all elements). Other solutions include [6,-9], [-1,-2], [-5000,5000], \ldotsFor the second test case, let us show why some arrays do not satisfy the constraints: [1,1,1]  — s_1+s_2 = 1+1 = 2 and s_1+s_2+s_3=1+1+1 = 3 differ; [1,-1,1]  — s_1+s_2=1+(-1)=0 and s_1+s_2+s_3=1+(-1)+1 = 1 differ; [0,0,0]  — The array s cannot contain a 0. This is not a proof, but it can be shown that the answer is "NO".
2 2 3
YES 9 5 NO
1 second
256 megabytes
['constructive algorithms', 'math', '*900']
A. Hall of Fametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThalia is a Legendary Grandmaster in chess. She has n trophies in a line numbered from 1 to n (from left to right) and a lamp standing next to each of them (the lamps are numbered as the trophies).A lamp can be directed either to the left or to the right, and it illuminates all trophies in that direction (but not the one it is next to). More formally, Thalia has a string s consisting only of characters 'L' and 'R' which represents the lamps' current directions. The lamp i illuminates: trophies 1,2,\ldots, i-1 if s_i is 'L'; trophies i+1,i+2,\ldots, n if s_i is 'R'. She can perform the following operation at most once: Choose an index i (1 \leq i < n); Swap the lamps i and i+1 (without changing their directions). That is, swap s_i with s_{i+1}. Thalia asked you to illuminate all her trophies (make each trophy illuminated by at least one lamp), or to tell her that it is impossible to do so. If it is possible, you can choose to perform an operation or to do nothing. Notice that lamps cannot change direction, it is only allowed to swap adjacent ones.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10\,000). The description of the test cases follows.The first line of each test case contains a positive integer n (2 \leq n \leq 100\,000)  — the number of trophies.The second line of each test case contains a string s of length n consisting only of characters 'L' and 'R'  — the i-th character describes the direction of the i-th lamp.It is guaranteed that the sum of n over all test cases does not exceed 100\,000.OutputFor each test case print -1 if it is impossible to illuminate all trophies by performing one operation (or doing nothing). Otherwise, print 0 if you choose not to perform the operation (i.e., the trophies are illuminated by the initial positioning of the lamps), or an index i (1 \leq i < n) if you choose to swap lamps i and i+1.If there are multiple answers, print any.ExampleInput 6 2 LL 2 LR 2 RL 2 RR 7 LLRLLLR 7 RRLRRRL Output -1 1 0 -1 3 6 NoteIn the first example, it is possible to swap lamps 1 and 2, or do nothing. In any case, the string "LL" is obtained. Not all trophies are illuminated since trophy 2 is not illuminated by any lamp  — lamp 1 illuminates nothing and lamp 2 illuminates only the trophy 1.In the second example, it is necessary to swap lamps 1 and 2. The string becomes "RL". Trophy 1 is illuminated by lamp 2 and trophy 2 is illuminated by lamp 1, hence it is possible to illuminate all trophies.In the third example, all trophies are initially illuminated  — hence, not performing any operation is a valid solution.In the last two examples performing swaps is not necessary as all trophies are illuminated initially. But, the presented solutions are also valid.
6 2 LL 2 LR 2 RL 2 RR 7 LLRLLLR 7 RRLRRRL
-1 1 0 -1 3 6
1 second
256 megabytes
['constructive algorithms', 'greedy', 'strings', '*800']
F. Maximizing Roottime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree consisting of n vertices numbered from 1 to n. Vertex 1 is the root of the tree. Each vertex has an integer value. The value of i-th vertex is a_i. You can do the following operation at most k times. Choose a vertex v that has not been chosen before and an integer x such that x is a common divisor of the values of all vertices of the subtree of v. Multiply by x the value of each vertex in the subtree of v. What is the maximum possible value of the root node 1 after at most k operations? Formally, you have to maximize the value of a_1.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. The subtree of a node u is the set of all nodes y such that the simple path from y to the root passes through u. Note that u is in the subtree of u.InputThe first line contains an integer t (1 \leq t \leq 50\,000) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and k (2 \leq n \leq 10^5, 0 \leq k \leq n) — the number of vertices in the tree and the number of operations.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 1000), where a_i denotes the value of vertex i.Each of the next n - 1 lines contains two integers u_i and v_i (1 \leq u_i, v_i \leq n, u_i \neq v_i), denoting the edge of the tree between vertices u_i and v_i. It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the maximum value of the root after performing at most k operations.ExampleInput 25 224 12 24 6 121 21 32 42 55 324 12 24 6 121 21 32 42 5Output 288 576 NoteBoth examples have the same tree: For the first test case, you can do two operations as follows: Choose the subtree of vertex 4 and x = 2. After this operation, the node values become \{24, 12, 24, 12, 12\}. Choose the subtree of vertex 1 and x = 12. After this operation, the node values become \{288, 144, 288, 144, 144\}. The value of the root is 288 and it is the maximum.For the second test case, you can do three operations as follows: Choose the subtree of vertex 4 and x = 2. After this operation, the node values become \{24, 12, 24, 12, 12\}. Choose the subtree of vertex 2 and x = 4. After this operation, the node values become \{24, 48, 24, 48, 48\}. Choose the subtree of vertex 1 and x = 24. After this operation, the node values become \{576, 1152, 576, 1152, 1152\}. The value of the root is 576 and it is the maximum.
25 224 12 24 6 121 21 32 42 55 324 12 24 6 121 21 32 42 5
288 576
2 seconds
1024 megabytes
['dfs and similar', 'dp', 'graphs', 'math', 'number theory', 'trees', '*2600']
E. The Tree Has Fallen!time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently, a tree has fallen on Bob's head from the sky. The tree has n nodes. Each node u of the tree has an integer number a_u written on it. But the tree has no fixed root, as it has fallen from the sky.Bob is currently studying the tree. To add some twist, Alice proposes a game. First, Bob chooses some node r to be the root of the tree. After that, Alice chooses a node v and tells him. Bob then can pick one or more nodes from the subtree of v. His score will be the bitwise XOR of all the values written on the nodes picked by him. Bob has to find the maximum score he can achieve for the given r and v.As Bob is not a good problem-solver, he asks you to help him find the answer. Can you help him? You need to find the answers for several combinations of r and v for the same tree.Recall that a tree is a connected undirected graph without cycles. The subtree of a node u is the set of all nodes y such that the simple path from y to the root passes through u. Note that u is in the subtree of u.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.The first line contains an integer n (2\leq n\leq 2 \cdot 10^5) — the number of nodes of the tree. The next line contains n space-separated integers a_1, a_2, \dots, a_n (1\leq a_i\leq 10^9) — the values written on the nodes. Each of the next n-1 lines contain two integers u and v (1\leq u, v\leq n; u\neq v), denoting there is an undirected edge between node u and node v. It is guaranteed that the given edges form a tree.The next line contains an integer q (1\leq q\leq 2 \cdot 10^5) — the number of queries. Each of the next q lines contains two integers r and v (1\leq r, v\leq n) — the root node Bob defines, and the node Alice chooses.It is guaranteed that the sum of n and the sum of q over all test cases don't exceed 2 \cdot 10^5.OutputFor each test case, in each query, print a line containing an integer denoting the maximum score Bob can achieve.ExampleInput 3612 12 8 25 6 11 51 22 62 32 434 23 51 223 81 242 22 11 21 133 8 71 22 322 22 1Output 15 6 29 11 3 8 11 15 3 NoteIn each of the below figures, the green-colored node is the node picked by Bob, and the red-colored node is the node picked by Alice. The values of the nodes are placed in the blue boxes beside the nodes.Consider the first example. In the first query, if we put the root node 4 at the top of the tree, the tree looks like the below figure: Tree with root node 4 in the first query. The nodes in the subtree of the node 2 are [2,1,5,6,3]. Among them, Bob can pick node 3, node 5, and node 6. His score will be a_3 \oplus a_5 \oplus a_6 = 8 \oplus 6 \oplus 1 = 15. He can't achieve any score more than this.In the second query, if the root node 3 is placed at the top of the tree, the tree looks like the below figure: Tree with root node 3 in the second query. The only node in the subtree of the node 5 is 5. Bob can only pick the node 5. His score will be a_5 = 6.In the third query, if the root node 1 is placed at the top of the tree, the tree looks like this: Tree with root node 1 in the third query. The nodes in the subtree of the node 2 are [2,3,6,4]. Among them, Bob can pick node 2, node 3, and node 4. His score will be a_2 \oplus a_3 \oplus a_4 = 12 \oplus 8 \oplus 25 = 29. He is not able to score higher than that.
3612 12 8 25 6 11 51 22 62 32 434 23 51 223 81 242 22 11 21 133 8 71 22 322 22 1
15 6 29 11 3 8 11 15 3
3 seconds
512 megabytes
['bitmasks', 'dfs and similar', 'math', 'trees', '*2500']
D. Flexible String Revisittime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two binary strings a and b of length n. In each move, the string a is modified in the following way. An index i (1 \leq i \leq n) is chosen uniformly at random. The character a_i will be flipped. That is, if a_i is 0, it becomes 1, and if a_i is 1, it becomes 0. What is the expected number of moves required to make both strings equal for the first time?A binary string is a string, in which the character is either \tt{0} or \tt{1}.InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 10^6) — the length of the strings.The second line of each test case contains the binary string a of length n.The third line of each test case contains the binary string b of length n.It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case, output a single line containing the expected number of moves modulo 998\,244\,353.Formally, let M = 998\,244\,353. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExampleInput 41012000041000111050100110111Output 1 0 665496254 665496277 NoteIn the first test case, index 1 is chosen randomly and a_1 is flipped. After the move, the strings a and b are equal. The expected number of moves is 1.The strings a and b are already equal in the second test case. So, the expected number of moves is 0.The expected number of moves for the third and fourth test cases are \frac{56}{3} and \frac{125}{3} respectively.
41012000041000111050100110111
1 0 665496254 665496277
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'probabilities', '*2100']
C. Flexible Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string a and a string b. Both of the strings have length n. There are at most 10 different characters in the string a. You also have a set Q. Initially, the set Q is empty. You can apply the following operation on the string a any number of times: Choose an index i (1\leq i \leq n) and a lowercase English letter c. Add a_i to the set Q and then replace a_i with c. For example, Let the string a be "\tt{abecca}". We can do the following operations: In the first operation, if you choose i = 3 and c = \tt{x}, the character a_3 = \tt{e} will be added to the set Q. So, the set Q will be \{\tt{e}\}, and the string a will be "\tt{ab\underline{x}cca}". In the second operation, if you choose i = 6 and c = \tt{s}, the character a_6 = \tt{a} will be added to the set Q. So, the set Q will be \{\tt{e}, \tt{a}\}, and the string a will be "\tt{abxcc\underline{s}}". You can apply any number of operations on a, but in the end, the set Q should contain at most k different characters. Under this constraint, you have to maximize the number of integer pairs (l, r) (1\leq l\leq r \leq n) such that a[l,r] = b[l,r]. Here, s[l,r] means the substring of string s starting at index l (inclusively) and ending at index r (inclusively).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line contains two integers n and k (1\leq n \leq 10^5, 0\leq k\leq 10) — the length of the two strings and the limit on different characters in the set Q. The second line contains the string a of length n. There is at most 10 different characters in the string a.The last line contains the string b of length n. Both of the strings a and b contain only lowercase English letters. The sum of n over all test cases doesn't exceed 10^5.OutputFor each test case, print a single integer in a line, the maximum number of pairs (l, r) satisfying the constraints.ExampleInput 63 1abcabd3 0abcabd3 1xbbxcd4 1abcdaxcb3 10abcabd10 3lkwhbahuqaqoiujoncjbOutput 6 3 6 6 6 11 NoteIn the first case, we can select index i = 3 and replace it with character c = \tt{d}. All possible pairs (l,r) will be valid.In the second case, we can't perform any operation. The 3 valid pairs (l,r) are: a[1,1] = b[1,1] = "\tt{a}", a[1,2] = b[1,2] = "\tt{ab}", a[2,2] = b[2,2] = "\tt{b}". In the third case, we can choose index 2 and index 3 and replace them with the characters \tt{c} and \tt{d} respectively. The final set Q will be \{\tt{b}\} having size 1 that satisfies the value of k. All possible pairs (l,r) will be valid.
63 1abcabd3 0abcabd3 1xbbxcd4 1abcdaxcb3 10abcabd10 3lkwhbahuqaqoiujoncjb
6 3 6 6 6 11
2 seconds
256 megabytes
['bitmasks', 'brute force', 'strings', '*1600']
B. The Forbidden Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of length n, an array of m distinct integers a_1, a_2, \ldots, a_m (1 \le a_i \le n), and an integer d.Let \mathrm{pos}(x) be the index of x in the permutation p. The array a is not good if \mathrm{pos}(a_{i}) < \mathrm{pos}(a_{i + 1}) \le \mathrm{pos}(a_{i}) + d for all 1 \le i < m. For example, with the permutation p = [4, 2, 1, 3, 6, 5] and d = 2: a = [2, 3, 6] is a not good array. a = [2, 6, 5] is good because \mathrm{pos}(a_1) = 2, \mathrm{pos}(a_2) = 5, so the condition \mathrm{pos}(a_2) \le \mathrm{pos}(a_1) + d is not satisfied. a = [1, 6, 3] is good because \mathrm{pos}(a_2) = 5, \mathrm{pos}(a_3) = 4, so the condition \mathrm{pos}(a_2) < \mathrm{pos}(a_3) is not satisfied. In one move, you can swap two adjacent elements of the permutation p. What is the minimum number of moves needed such that the array a becomes good? It can be shown that there always exists a sequence of moves so that the array a becomes good.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3, but there is 4 in the array).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains three integers n, m and d (2\leq n \leq 10^5, 2\leq m\leq n, 1 \le d \le n), the length of the permutation p, the length of the array a and the value of d. The second line contains n integers p_1, p_2, \ldots, p_n (1\leq p_i \leq n, p_i \ne p_j for i \ne j). The third line contains m distinct integers a_1, a_2, \ldots, a_m (1\leq a_i \leq n, a_i \ne a_j for i \ne j).The sum of n over all test cases doesn't exceed 5 \cdot 10^5.OutputFor each test case, print the minimum number of moves needed such that the array a becomes good.ExampleInput 54 2 21 2 3 41 35 2 45 4 3 2 15 25 3 33 4 1 5 23 1 22 2 11 22 16 2 41 2 3 4 5 62 5Output 1 3 2 0 2 NoteIn the first case, pos(a_1)=1, pos(a_2)=3. To make the array good, one way is to swap p_3 and p_4. After that, the array a will be good because the condition \mathrm{pos}(a_2) \le \mathrm{pos}(a_1) + d won't be satisfied.In the second case, pos(a_1)=1, pos(a_2)=4. The 3 moves could be: Swap p_3 and p_4. Swap p_2 and p_3. Swap p_1 and p_2. After these moves, the permutation p will be [2,5,4,3,1]. The array a will be good because the condition \mathrm{pos}(a_1) < \mathrm{pos}(a_2) won't be satisfied. It can be shown that you can't make the array a good with fewer moves.In the third case, pos(a_1)=1, pos(a_2)=3, pos(a_3)=5. The 2 moves can be: Swap p_4 and p_5. Swap p_3 and p_4. After these moves, the permutation p will be [3,4,2,1,5]. The array a will be good because the condition \mathrm{pos}(a_2) < \mathrm{pos}(a_3) won't be satisfied. It can be shown that you can't make the array a good with fewer moves.In the fourth case, pos(a_1)=2, pos(a_2)=1. The array a is already good.In the fifth case, pos(a_1)=2, pos(a_2)=5. The 2 moves are: Swap p_1 and p_2. Swap p_5 and p_6.
54 2 21 2 3 41 35 2 45 4 3 2 15 25 3 33 4 1 5 23 1 22 2 11 22 16 2 41 2 3 4 5 62 5
1 3 2 0 2
2 seconds
256 megabytes
['greedy', 'math', '*1300']
A. Flip Flop Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers a_1, a_2, \ldots, a_n. The integers are either 1 or -1. You have to perform the following operation exactly once on the array a: Choose an index i (1 \leq i < n) and flip the signs of a_i and a_{i+1}. Here, flipping the sign means -1 will be 1 and 1 will be -1. What is the maximum possible value of a_1 + a_2 + \ldots + a_n after applying the above operation?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). Description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 10^5), the length of the array a.The next line contains n integers a_1, a_2, \ldots, a_n (a_i = 1 or a_i = -1).The sum of n over all cases doesn't exceed 10^5.OutputFor each test case, print the maximum possible sum of the array a you can get in a separate line.ExampleInput 45-1 1 1 -1 -151 1 -1 -1 -121 141 -1 -1 1Output 3 3 -2 4 NoteIn the first case, we can choose index 4 and flip the signs of a_4 and a_5. After this operation, the sum will be -1+1+1+1+1 = 3. We can't make the sum larger than this.In the third case, the only option is to choose the index 1.
45-1 1 1 -1 -151 1 -1 -1 -121 141 -1 -1 1
3 3 -2 4
1 second
256 megabytes
['greedy', 'implementation', '*800']
F. Comfortably Numbtime limit per test8 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n non-negative integers.The numbness of a subarray a_l, a_{l+1}, \ldots, a_r (for arbitrary l \leq r) is defined as \max(a_l, a_{l+1}, \ldots, a_r) \oplus (a_l \oplus a_{l+1} \oplus \ldots \oplus a_r), where \oplus denotes the bitwise XOR operation.Find the maximum numbness over all subarrays.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the maximum numbness over all subarrays of the given array.ExampleInput 251 2 3 4 5310 47 52Output 7 47 NoteFor the first test case, for the subarray [3, 4, 5], its maximum value is 5. Hence, its numbness is 3 \oplus 4 \oplus 5 \oplus 5 = 7. This is the maximum possible numbness in this array.In the second test case the subarray [47, 52] provides the maximum numbness.
251 2 3 4 5310 47 52
7 47
8 seconds
1024 megabytes
['bitmasks', 'data structures', 'divide and conquer', 'strings', 'trees', '*2400']
E. Edge Reversetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou will be given a weighted directed graph of n nodes and m directed edges, where the i-th edge has a weight of w_i (1 \le i \le m).You need to reverse some edges of this graph so that there is at least one node in the graph from which every other node is reachable. The cost of these reversals is equal to the maximum weight of all reversed edges. If no edge reversal is required, assume the cost to be 0.It is guaranteed that no self-loop or duplicate edge exists.Find the minimum cost required for completing the task. If there is no solution, print a single integer -1.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.Each test case begins with a line containing two integers n and m (2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5) — the number of nodes in the graph and the number of edges in the graph.The next m lines of each test case contain 3 integers each — u, v, w (1 \le u, v \le n, 1 \le w \le 10^9), indicating an edge from u to v with a weight of w. It is guaranteed that no edge connects a vertex to itself, and no pair of edges share the same origin and destination simultaneously.It is guaranteed that the sum of n and the sum of m over all test cases do not exceed 2 \cdot 10^5.OutputFor each test case, output the minimum cost. If there is no solution, print -1.ExampleInput 42 11 2 35 41 2 102 3 103 1 104 5 104 51 2 100002 3 200001 3 300004 2 5004 3 204 51 2 100002 3 200001 3 300004 2 54 3 20Output 0 -1 20 5 NoteIn the first test case, an edge exists from 1 to 2, so all nodes are reachable (from 1).In the second test case, no nodes are reachable from any node no matter what edges we reverse, so the answer is -1.In the third test case, reversing the 4-th or 5-th edge allows all nodes to be reachable from 1. We choose the 5-th edge here because its weight is smaller.
42 11 2 35 41 2 102 3 103 1 104 5 104 51 2 100002 3 200001 3 300004 2 5004 3 204 51 2 100002 3 200001 3 300004 2 54 3 20
0 -1 20 5
4 seconds
512 megabytes
['binary search', 'dfs and similar', 'graphs', 'trees', '*2200']
D. Score of a Treetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree of n nodes, rooted at 1. Every node has a value of either 0 or 1 at time t=0.At any integer time t>0, the value of a node becomes the bitwise XOR of the values of its children at time t - 1; the values of leaves become 0 since they don't have any children.Let S(t) denote the sum of values of all nodes at time t. Let F(A) denote the sum of S(t) across all values of t such that 0 \le t \le 10^{100}, where A is the initial assignment of 0s and 1s in the tree.The task is to find the sum of F(A) for all 2^n initial configurations of 0s and 1s in the tree. Print the sum modulo 10^9+7.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.The first line of each test case contains n (1 \le n \le 2 \cdot 10^5) — the number of nodes in the tree.The next n-1 lines of each test case contain two integers each — u, v indicating an edge between u and v (1 \le u, v \le n).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputOutput the sum modulo 10^9+7 for each test case.ExampleInput 161 21 33 43 53 6Output 288 NoteLet us find F(A) for the configuration A = [0,1,0,0,1,1] (A[i] denotes the value of node i). Initially (at t = 0) our tree is as shown in the picture below. In each node, two values are shown: the number and the value of this node. S(0) for this configuration is 3. At t = 1 the configuration changes to [1,0,0,0,0,0]. The tree looks as shown below. S(1) = 1. At t = 2 the configuration changes to [0,0,0,0,0,0]. The tree looks as shown below. S(2) = 0. For all t>2, the graph remains unchanged, so S(t)=0 for all t > 2. So, for the initial configuration A = [0,1,0,0,1,1], the value of F(A) = 3 + 1 = 4.Doing this process for all possible 2^{6} configurations yields us an answer of \textbf{288}.
161 21 33 43 53 6
288
2 seconds
512 megabytes
['bitmasks', 'combinatorics', 'dfs and similar', 'dp', 'math', 'probabilities', 'trees', '*1900']
C. Quiz Mastertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA school has to decide on its team for an international quiz. There are n students in the school. We can describe the students using an array a where a_i is the smartness of the i-th (1 \le i \le n) student. There are m topics 1, 2, 3, \ldots, m from which the quiz questions will be formed. The i-th student is considered proficient in a topic T if (a_i \bmod T) = 0. Otherwise, he is a rookie in that topic. We say that a team of students is collectively proficient in all the topics if for every topic there is a member of the team proficient in this topic.Find a team that is collectively proficient in all the topics such that the maximum difference between the smartness of any two students in that team is minimized. Output this difference.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains n and m (1 \le n,m \le 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^5).It is guaranteed that the sum of n over all test cases does not exceed 10^5.It is guaranteed that the sum of m over all test cases does not exceed 10^5.OutputFor each test case, print the answer on a new line. If there is no solution, output -1.ExampleInput 32 43 74 23 7 2 95 76 4 3 5 7Output -1 0 3 NoteIn the first test case, we have participants with smartnesses 3 and 7, and m = 4. Thus, there is no student with smartness divisible by 2. Since 2 \leq m, there is no way to choose a team.In the second test case, we can select the participant with smartness 2 to be the only one on the team. This way the team will be collectively proficient in both topics 1 and 2.In the third test case, consider the team with participants of smartnesses 4, 5, 6, 7. This way the team will be collectively proficient in all topics 1, 2, \ldots, 7.
32 43 74 23 7 2 95 76 4 3 5 7
-1 0 3
2 seconds
256 megabytes
['binary search', 'math', 'number theory', 'sortings', 'two pointers', '*1700']
B. Emordnilaptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). There are n! = n \cdot (n-1) \cdot (n - 2) \cdot \ldots \cdot 1 different permutations of length n.Given a permutation p of n numbers, we create an array a consisting of 2n numbers, which is equal to p concatenated with its reverse. We then define the beauty of p as the number of inversions in a.The number of inversions in the array a is the number of pairs of indices i, j such that i < j and a_i > a_j.For example, for permutation p = [1, 2], a would be [1, 2, 2, 1]. The inversions in a are (2, 4) and (3, 4) (assuming 1-based indexing). Hence, the beauty of p is 2.Your task is to find the sum of beauties of all n! permutations of size n. Print the remainder we get when dividing this value by 1\,000\,000\,007 (10^9 + 7).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.Each test case has only one line — the integer n (1 \leq n \leq 10^5).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print one integer — the sum of beauties of all permutations of size n modulo 1\,000\,000\,007 (10^9 + 7).ExampleInput 312100Output 0 4 389456655 NoteFor the first test case of the example, p = [1] is the only permutation. a = [1, 1] has 0 inversions.For the second test case of the example, the permutations are [1, 2] and [2, 1]. Their respective a arrays are [1, 2, 2, 1] and [2, 1, 1, 2], both of which have 2 inversions.
312100
0 4 389456655
1 second
256 megabytes
['combinatorics', 'greedy', 'math', '*900']
A. Everybody Likes Good Arrays!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array a is good if for all pairs of adjacent elements, a_i and a_{i+1} (1\le i \lt n) are of different parity. Note that an array of size 1 is trivially good.You are given an array of size n. In one operation you can select any pair of adjacent elements in which both elements are of the same parity, delete them, and insert their product in the same position.Find the minimum number of operations to form a good array.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). The description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 100).The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le 10^{9}).OutputFor each test case print an integer, the minimum number of operations required to form a good array.ExampleInput 351 7 11 2 1341 2 3 461 1 1 2 2 3Output 2 0 3 NoteConsider the first test case. Select the 2-nd and the 3-rd integers and apply the operation on them. The array changes from [1, \color{red}{7}, \color{red}{11}, 2, 13] to [1, \color{red}{77}, 2, 13]. Next, select the 1-st and the 2-nd integers, array changes from [\color{red}{1}, \color{red}{77}, 2, 13] to [\color{red}{77}, 2, 13]. Thus we require 2 operations. It can be proved that this is the minimum number of operations.In the second test case, the given array is already good. So we require 0 operations.
351 7 11 2 1341 2 3 461 1 1 2 2 3
2 0 3
1 second
256 megabytes
['greedy', 'math', '*800']
N. Count Permutationstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s with length n-1 whose characters are either \texttt{<} or \texttt{>}.Count the permutations p_1, \, p_2, \, \dots, \, p_n of 1, \, 2, \, \dots, \, n such that, for all i = 1, \, 2, \, \dots, \, n - 1, if s_i is \texttt{<} then p_i < p_{i+1} and if s_i is \texttt{>} then p_i > p_{i+1}.Since this number can be very large, compute its logarithm in base 2.InputThe first line contains a single integer n (2 \le n \le 100\,000).The second line contains a string s of length n-1; each character of s is either \texttt{<} or \texttt{>}.OutputPrint the logarithm in base 2 of the number of permutations satisfying the constraints described in the statement.Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}. Formally, let your answer be x and let the correct answer be y. Your answer is accepted if and only if \frac{|x - y|}{\max{(1, |y|)}} \le 10^{-6}.ExamplesInput 2 < Output 0.0000000000 Input 3 <> Output 1.0000000000 Input 5 ><<< Output 2.0000000000 Input 10 <><<<<<>> Output 9.8281364842 NoteIn the first sample, there is only one valid permutation, that is [2, 1]. Since \log_2(1)=0, the correct output is 0.In the second sample, there are 2 valid permutations, that are [3, 1, 2] and [2, 1, 3]. Since \log_2(2)=1, the correct output is 1.In the third sample, there are 4 valid permutations, that are [1, 5, 4, 3, 2], [2, 5, 4, 3, 1], [3, 5, 4, 2, 1], [4, 5, 3, 2, 1]. Since \log_2(4)=2, the correct output is 2.In the fourth sample, there are 909 valid permutations. Notice that \log_2(909)=9.828136484194\ldots
2 <
0.0000000000
5 seconds
256 megabytes
['math', '*3500']
M. Parmigiana With Seafoodtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe "Parmigiana di melanzane" is a typical Italian dish. Alessandro and Bianca have very different tastes when it comes to it: Alessandro loves to eat Parmigiana with seafood, but Bianca thinks it is an atrocity! To decide which ingredients to include in the dish they prepare, they play the following game.There are n possible ingredients, labeled from 1 to n. The higher the label, the closer the ingredient is to being seafood. The ingredients are connected by n - 1 edges, in such a way as to form a tree. Alessandro and Bianca take turns, with Alessandro going first. They alternately choose a terminal ingredient x, that is an ingredient currently connected to at most one other ingredient, and remove it from the tree. If the terminal ingredient x was chosen by Alessandro, it goes in the recipe; if it was chosen by Bianca, it is discarded.The taste of the Parmigiana is measured as the maximum label of an ingredient in the recipe. Alessandro wants to maximize the taste, while Bianca wants to minimize the taste. If both play optimally, what is the taste of the Parmigiana?InputThe first line contains an integer n (2\le n \le 100\,000) — the number of ingredients.Each of the following n-1 lines contain two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \ne v_i) — the ingredients that the i-th edge connects.It is guaranteed that the edges form a tree (i.e., any pair of ingredients is connected by the edges, possibly indirectly).OutputPrint the value of the taste if both Alessandro and Bianca play optimally. ExamplesInput 4 1 2 1 3 1 4 Output 4 Input 5 1 5 5 3 3 4 4 2 Output 3 NoteIn the first sample, Alessandro can choose terminal ingredient 4 in the first turn. This ingredient is added to the recipe. Since 4 is the maximum label of an ingredient, the taste is 4 regardless of the choices that follow. In the second sample, Bianca can make sure that neither ingredient 4 nor 5 are included in the recipe, in which case Alessandro can include 3. Thus, the taste is 3.
4 1 2 1 3 1 4
4
2 seconds
256 megabytes
['binary search', 'dp', 'greedy', 'trees', '*3000']
L. Controllerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are at your grandparents' house and you are playing an old video game on a strange console. Your controller has only two buttons and each button has a number written on it.Initially, your score is 0. The game is composed of n rounds. For each 1\le i\le n, the i-th round works as follows.On the screen, a symbol s_i appears, which is either \texttt{+} (plus) or \texttt{-} (minus). Then you must press one of the two buttons on the controller once. Suppose you press a button with the number x written on it: your score will increase by x if the symbol was \texttt{+} and will decrease by x if the symbol was \texttt{-}. After you press the button, the round ends. After you have played all n rounds, you win if your score is 0.Over the years, your grandparents bought many different controllers, so you have q of them. The two buttons on the j-th controller have the numbers a_j and b_j written on them. For each controller, you must compute whether you can win the game playing with that controller.InputThe first line contains a single integer n (1 \le n \le 2\cdot 10^5) — the number of rounds.The second line contains a string s of length n — where s_i is the symbol that will appear on the screen in the i-th round. It is guaranteed that s contains only the characters \texttt{+} and \texttt{-}.The third line contains an integer q (1 \le q \le 10^5) — the number of controllers.The following q lines contain two integers a_j and b_j each (1 \le a_j, b_j \le 10^9) — the numbers on the buttons of controller j. OutputOutput q lines. On line j print \texttt{YES} if the game is winnable using controller j, otherwise print \texttt{NO}.ExamplesInput 8 +-+---+- 5 2 1 10 3 7 9 10 10 5 3 Output YES NO NO NO YES Input 6 +-++-- 2 9 7 1 1 Output YES YES Input 20 +-----+--+--------+- 2 1000000000 99999997 250000000 1000000000 Output NO YES NoteIn the first sample, one possible way to get score 0 using the first controller is by pressing the button with numnber 1 in rounds 1, 2, 4, 5, 6 and 8, and pressing the button with number 2 in rounds 3 and 7. It is possible to show that there is no way to get a score of 0 using the second controller.
8 +-+---+- 5 2 1 10 3 7 9 10 10 5 3
YES NO NO NO YES
2 seconds
256 megabytes
['binary search', 'math', '*1500']
K. Uniform Chemistrytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a parallel universe there are n chemical elements, numbered from 1 to n. The element number n has not been discovered so far, and its discovery would be a pinnacle of research and would bring the person who does it eternal fame and the so-called SWERC prize.There are m independent researchers, numbered from 1 to m, that are trying to discover it. Currently, the i-th researcher has a sample of the element s_i. Every year, each researcher independently does one fusion experiment. In a fusion experiment, if the researcher currently has a sample of element a, they produce a sample of an element b that is chosen uniformly at random between a+1 and n, and they lose the sample of element a. The elements discovered by different researchers or in different years are completely independent.The first researcher to discover element n will get the SWERC prize. If several researchers discover the element in the same year, they all get the prize. For each i = 1, \, 2, \, \dots, \, m, you need to compute the probability that the i-th researcher wins the prize.InputThe first line contains two integers n and m (2 \le n \le 10^{18}, 1 \le m \le 100) — the number of elements and the number of researchers.The second line contains m integers s_1, \, s_2, \, \dots, \, s_m (1 \le s_i < n) — the elements that the researchers currently have.OutputPrint m floating-point numbers. The i-th number should be the probability that the i-th researcher wins the SWERC prize. Your answer is accepted if each number differs from the correct number by at most 10^{-8}.ExamplesInput 2 3 1 1 1 Output 1.0 1.0 1.0 Input 3 3 1 1 2 Output 0.5 0.5 1.0 Input 3 3 1 1 1 Output 0.625 0.625 0.625 Input 100 7 1 2 4 8 16 32 64 Output 0.178593469 0.179810455 0.182306771 0.187565366 0.199300430 0.229356322 0.348722518 NoteIn the first sample, all researchers will discover element 2 in the first year and win the SWERC prize.In the second sample, the last researcher will definitely discover element 3 in the first year and win the SWERC prize. The first two researchers have a 50\% chance of discovering element 2 and a 50\% chance of discovering element 3, and only element 3 will bring them the prize.In the third sample, each researcher has an independent 50\% chance of discovering element 3 in the first year, in which case they definitely win the SWERC prize. Additionally, if they all discover element 2 in the first year, which is a 12.5\% chance, then they will all discover element 3 in the second year and all win the prize.
2 3 1 1 1
1.0 1.0 1.0
2 seconds
256 megabytes
['dp', 'math', '*3200']
J. Italian Data Centerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn Italian data center consists of a set of servers, each colored green, white, or red, and a set of wires connecting them. Each wire connects two distinct servers and two servers are connected by at most one wire. Additionally, the data center is connected, i.e. there is a way to transmit information between any two servers through a sequence of wires.To judge all of the contestant submissions, SWERC has an Italian data center. Since every year the number of contestants doubles, the data center needs to grow to adapt to the extra load. To address this, SWERC builds a new data center based on the previous year's one by following these steps: For each server s in the old data center, the new data center contains two servers s_1 and s_2 of the same color as s. A wire is placed connecting the two servers s_1 and s_2. For each wire connecting servers s and t in the old data center: if s and t have the same color, then a wire is placed in the new data center connecting s_1 and t_1 and another wire connecting s_2 and t_2; otherwise, a wire is placed in the new data center connecting s_1 and t_2 and another one connecting s_2 and t_1. One can show that if the old data center is connected than the new data center is also connected.You are given the Italian data center that SWERC currently has, which contains n servers (indexed by 1, \, 2, \, \dots, \, n) and m wires connecting them. The organization wants to know how good their data center will be after k years, so you should determine the diameter of the data center SWERC will have in k years. The diameter of the data center is the largest distance between any two servers, i.e. the shortest number of wires that have to be used to transmit something between the two servers.InputThe first line contains three integers n, m and k (2 \leq n \leq 100, n - 1 \leq m \leq n (n - 1) / 2, 0 \leq k \leq 100) — the number of servers, the number of wires, and the number of years to consider.The second line contains n integers c_1, \, c_2, \, \dots, \, c_n (1 \leq c_i \leq 3) — c_i is the color of server i (where 1 stands for green, 2 for white and 3 for red).Each of the next m lines contains two integers s_i and t_i (1 \leq s_i, t_i \leq n) — the two servers the i-th wire connects.It is guaranteed that the data center is connected, the endpoints of each wire are distinct, and that there are no repeated wires.OutputPrint the diameter of SWERC's data center after k years.ExamplesInput 3 3 0 1 2 3 1 2 2 3 3 1 Output 1 Input 3 3 1 1 2 3 1 2 2 3 3 1 Output 2 Input 3 3 2 1 2 1 1 2 2 3 3 1 Output 3 Input 8 14 100 3 3 2 2 1 2 2 1 2 7 1 5 7 8 4 6 2 8 1 8 2 6 6 7 1 6 1 4 3 5 1 3 4 5 5 7 Output 53 NoteIn the first sample, the Italian data center is the following: The distance between any pair of servers is 1 so the diameter is 1.In the second sample, the initial Italian data center is the one from the first sample.After one year we obtain the following (where the numbers indicate which copy the server refers to): Consider the highlighted servers. The distance between them is 2 and there is no pair of servers with greater distance, so the diameter is 2.In the third sample, the data center after one year is the following: After one more year: Consider the highlighted servers. The distance between them is 3 and there is no pair of servers with greater distance, so the diameter is 3.
3 3 0 1 2 3 1 2 2 3 3 1
1
2 seconds
256 megabytes
['graphs', 'shortest paths', '*2500']
I. Spinach Pizzatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe two siblings Alberto and Beatrice have to eat a spinach pizza together. However, none of them likes spinach, so they both want to eat as little as possible.The pizza has the shape of a strictly convex polygon with n vertices located at integer coordinates (x_1, y_1), \, (x_2, y_2), \, \dots, \, (x_n, y_n) of the plane.The siblings have decided to eat the pizza in the following way: taking turns, starting with Alberto, each sibling chooses a vertex of the remaining part of the pizza and eats out the triangle determined by its two neighboring edges. In this way, after each of the first n - 3 turns the pizza will have one less vertex. The game ends after the (n - 2)-th turn, when all the pizza has been eaten.Assuming that Alberto and Beatrice choose the slices to eat optimally, which of the siblings manages to eat at most half of the pizza? You should identify a sibling that has a strategy to do so and help them choose the slices appropriately. Note that it is possible that both Alberto and Beatrice end up eating exactly half of the area if they choose their slices optimally.InputThe first line contains a single integer n (4 \le n \le 100) — the number of vertices.The next n lines contain two integers x_i and y_i each (-10^6 \le x_i, y_i \le 10^6) — the coordinates of the i-th vertex of the polygon representing the initial shape of the pizza.It is guaranteed that the polygon is strictly convex and that its vertices are given in counterclockwise order.InteractionFirst, you should print a line containing either the string \texttt{Alberto} or the string \texttt{Beatrice} — the sibling that you will help to win.Then, for the next n - 2 turns, you will alternate with the judge in choosing a slice of the pizza and removing it, starting with you if you chose to help Alberto, or starting with the judge if you chose to help Beatrice. When it is your turn, print a single line containing an integer p (1 \leq p \leq n) that has not been chosen before, indicating that you want to eat the slice determined by the vertex located at (x_p, y_p). When it is the judge's turn, read an integer q (1 \leq q \leq n), indicating that the other player eats the slice determined by the vertex located at (x_q, y_q). It is guaranteed that q has not been chosen before. If one of your interactions is malformed, the interactor terminates immediately and your program receives the verdict \texttt{WRONG-ANSWER}. Otherwise, you will receive \texttt{CORRECT} if at the end your player has eaten at most half of the pizza, and \texttt{WRONG-ANSWER} otherwise.After printing a line do not forget to end the line and flush the output. Otherwise, you will get the verdict \texttt{TIMELIMIT}. To flush the output, use: \texttt{fflush(stdout)} in C; \texttt{fflush(stdout)}, \texttt{cout <}\texttt{< flush} or \texttt{cout.flush()} in C++; \texttt{System.out.flush()} in Java and Kotlin; \texttt{sys.stdout.flush()} in Python. ExamplesInput 4 0 0 6 1 5 3 1 4 Output -Input 6 0 0 2 0 3 2 2 4 0 4 -1 2 Output -Input 7 0 0 2 0 5 2 4 5 1 5 -1 4 -1 2 Output -NoteIn the first sample, the pizza has area 15. Alberto can eat less than half of the pizza by eating the slice around vertex 2 (which has area 6.5) or around vertex 3 (which has area 3.5). In the second sample, it can be proved that both players will eat exactly half of the pizza if they eat optimally. Therefore it is possible to choose to help either Alberto or Beatrice.In the third sample, it is possible to show that only Beatrice has a strategy to eat at most half of the pizza. The following is an example of a valid interaction (after reading the input): \begin{array}{|c|c|c|} \hline \textbf{Contestant} & \textbf{Judge} & \textbf{Explanation} \\ \hline \texttt{Beatrice} & & \text{The contestant will help Beatrice} \\ \hline & \texttt{7} & \text{Alberto eats the triangle with vertices $6$, $7$, $1$ and area $1$} \\ \hline \texttt{2} & & \text{Beatrice eats the triangle with vertices $1$, $2$, $3$ and area $2$} \\ \hline & \texttt{5} & \text{Alberto eats the triangle with vertices $4$, $5$, $6$ and area $1.5$} \\ \hline \texttt{4} & & \text{Beatrice eats the triangle with vertices $3$, $4$, $6$ and area $8$} \\ \hline & \texttt{6} & \text{Alberto eats the triangle with vertices $3$, $6$, $1$ and area $11$} \\ \hline \end{array} The total area eaten by Alberto is 13.5 and the total area eaten by Beatrice is 10, which is less than half the area of the whole pizza. The actions performed by the contestant and the judge in this example of interaction may be non-optimal. The process is illustrated below:
4 0 0 6 1 5 3 1 4
-
2 seconds
256 megabytes
['games', 'geometry', 'greedy', 'interactive', '*2500']
H. Beppa and SwerChattime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeppa and her circle of geek friends keep up to date on a group chat in the instant messaging app SwerChat^{\text{TM}}.The group has n members, excluding Beppa. Each of those members has a unique ID between 1 and n. When a user opens a group chat, SwerChat^{\text{TM}} displays the list of other members of that group, sorted by decreasing times of last seen online (so the member who opened the chat most recently is the first of the list). However, the times of last seen are not displayed.Today, Beppa has been busy all day: she has only opened the group chat twice, once at 9:00 and once at 22:00. Both times, she wrote down the list of members in the order they appeared at that time. Now she wonders: what is the minimum number of other members that must have been online at least once between 9:00 and 22:00?Beppa is sure that no two members are ever online at the same time and no members are online when Beppa opens the group chat at 9:00 and 22:00.InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 10\,000) — the number of test cases. The descriptions of the t test cases follow.The first line of each test case contains an integer n (1 \leq n \leq 10^5) — the number of members of the group excluding Beppa.The second line contains n integers a_1, \, a_2, \, \dots, \, a_n (1 \le a_i \le n) — the list of IDs of the members, sorted by decreasing times of last seen online at 9:00.The third line contains n integers b_1, \, b_2, \, \dots, \, b_n (1 \le b_i \le n) — the list of IDs of the members, sorted by decreasing times of last seen online at 22:00.For all 1\le i < j\le n, it is guaranteed that a_i \ne a_j and b_i \ne b_j.It is also guaranteed that the sum of the values of n over all test cases does not exceed 10^5.OutputFor each test case, print the minimum number of members that must have been online between 9:00 and 22:00.ExampleInput 451 4 2 5 34 5 1 2 361 2 3 4 5 61 2 3 4 5 688 2 4 7 1 6 5 35 6 1 4 8 2 7 3111Output 2 0 4 0 NoteIn the first test case, members 4, 5 must have been online between 9:00 and 22:00.In the second test case, it is possible that nobody has been online between 9:00 and 22:00.
451 4 2 5 34 5 1 2 361 2 3 4 5 61 2 3 4 5 688 2 4 7 1 6 5 35 6 1 4 8 2 7 3111
2 0 4 0
2 seconds
256 megabytes
['two pointers', '*1300']
G. Another Wine Tasting Eventtime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the first successful edition, Gabriella has been asked to organize a second wine tasting event. There will be 2n - 1 bottles of wine arranged in a row, each of which is either red wine or white wine.This time, Gabriella has already chosen the type and order of all the bottles. The types of the wines are represented by a string s of length 2n - 1. For each 1 \le i \le 2n - 1, it holds that s_i = \texttt{R} if the i-th bottle is red wine, and s_i = \texttt{W} if the i-th bottle is white wine.Exactly n critics have been invited to attend. The critics are numbered from 1 to n. Just like last year, each critic j wants to taste an interval of wines, that is, the bottles at positions a_j, \, a_j + 1, \, \dots, \, b_j for some 1 \le a_j \le b_j \le 2n - 1. Moreover, they have the following additional requirements: each of them wants to taste at least n wines, that is, it must hold that b_j - a_j + 1 \ge n; no two critics must taste exactly the same wines, that is, if j \ne k it must hold that a_j \ne a_k or b_j \ne b_k. Gabriella knows that, since the event is held in a coastal region of Italy, critics are especially interested in the white wines, and don't care much about the red ones. (Indeed, white wine is perfect to accompany seafood.) Thus, to ensure fairness, she would like that all critics taste the same number of white wines.Help Gabriella find an integer x (with 0 \le x \le 2n - 1) such that there exists a valid assignment of intervals to critics where each critic tastes exactly x white wines. It can be proved that at least one such x always exists.InputThe first line contains the integer n (1 \le n \le 10^6) — where 2n - 1 is the number of bottles, and n is the number of critics.The second line contains a string s of length 2n - 1 that represents the arrangement of the wines — the i-th character of s (1 \le i \le 2n - 1) is \texttt{R} for a red wine and \texttt{W} for a white wine.OutputPrint an integer x — the number of white wines that each critic will taste.It can be proved that at least one solution exists. If multiple solutions exist, any of them will be accepted.ExamplesInput 5 RWWRRRWWW Output 2 Input 1 R Output 0 NoteIn the first sample, there are 5 critics and 2 \cdot 5 - 1 = 9 bottles of wine. A possible set of intervals that makes each critic taste 2 white wines is the following: [2, 6], [1, 6], [4, 8], [1, 5], [3, 7]. Note that all intervals contain at least 5 bottles.In the second sample, there is 1 critic and 2 \cdot 1 - 1 = 1 bottle of wine. The only possible interval is [1, 1], which gives x = 0.
5 RWWRRRWWW
2
0.5 seconds
256 megabytes
['combinatorics', 'constructive algorithms', 'math', 'strings', '*2100']
F. Train Splittingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n big cities in Italy, and there are m train routes between pairs of cities. Each route connects two different cities bidirectionally. Moreover, using the trains one can reach every city starting from any other city.Right now, all the routes are operated by the government-owned Italian Carriage Passenger Company, but the government wants to privatize the routes. The government does not want to give too much power to a single company, but it also does not want to make people buy a lot of different subscriptions. Also, it would like to give a fair chance to all companies. In order to formalize all these wishes, the following model was proposed.There will be k \ge 2 private companies indexed by 1, \, 2, \, \dots, \, k. Each train route will be operated by exactly one of the k companies. Then: For any company, there should exist two cities such that it is impossible to reach one from the other using only routes operated by that company. On the other hand, for any two companies, it should be possible to reach every city from any other city using only routes operated by these two companies. Find a plan satisfying all these criteria. It can be shown that a viable plan always exists. Please note that you can choose the number k and you do not have to minimize or maximize it.InputEach test contains multiple test cases. The first line contains an integer t (1 \le t \le 1000) — the number of test cases. The descriptions of the t test cases follow.The first line of each test case contains two integers n and m (3 \le n \le 50, n-1 \le m \le n(n-1)/2) — the number of cities and the number of train routes.The next m lines contain two integers u_i and v_i each (1 \le u_i, v_i \le n, u_i \ne v_i) — the i-th train route connects cities u_i and v_i.It is guaranteed that the routes connect m distinct pairs of cities. It is guaranteed that using the trains one can reach every city starting from any other city.The sum of the values of n over all test cases does not exceed 5000.OutputFor each test case, on the first line print an integer k (2 \le k \le m) — the number of companies in your plan; on the second line print m integers c_1, \, c_2, \, \dots, \, c_m (1 \le c_i \le k) — in your plan company c_i operates the i-th route.If there are multiple valid plans, you may print any of them.ExampleInput 25 91 21 31 41 52 32 42 53 43 53 31 23 12 3Output 4 1 2 3 1 4 2 2 4 3 3 2 3 1 NoteIn the first test case, the output is illustrated in the following picture, where different colors correspond to different companies (blue for 1, red for 2, green for 3, and yellow for 4): If we consider, for example, only companies 2 and 3, we can see that from any city it is possible to reach every other city (picture on the left below). However, if we restrict to company 2 alone, it becomes impossible to reach city 5 from city 1 (picture on the right). In the second test case, the output is illustrated in the following picture:
25 91 21 31 41 52 32 42 53 43 53 31 23 12 3
4 1 2 3 1 4 2 2 4 3 3 2 3 1
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'greedy', '*1700']
E. Crossing the Railwaystime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIsona is in a train station. This station has two platforms, and between them there are m parallel railways that can be viewed as infinite straight lines. Each railway is identified with an integer from 1 to m, railway 1 being the closest to the first platform and railway m being the farthest. There is a 1 meter distance between consecutive railways, as well as between each platform and its closest railway.Isona is standing on the inner border of the first platform, when she realizes that she forgot to validate her ticket! There is a validating machine on the second platform, exactly opposite her current position (thus, the distance between Isona and the validating machine is m + 1 meters). There are only s seconds left to validate the ticket and the bridge designated to cross the railways is too far from the validating machine. Therefore, Isona (who is very brave and a little bit careless) will cross the railways running in a straight line perpendicular to the railways themselves. Isona can only run forward (not backward) and she can stay still. When she runs at maximum speed, she needs v seconds to traverse 1 meter. She can run at any speed less than or equal to her maximum speed.There is only one problem: n trains are programmed to transit through the railways. The i-th train will use the railway r_i. It will start crossing the straight line between Isona and the validating machine a_i seconds from now and it will end b_i seconds from now. Of course, Isona cannot cross a railway when a train is passing. Formally, for every i = 1, \, 2, \, \dots, \, n, Isona is not allowed to be on railway r_i at any time t with a_i < t < b_i (but she is allowed to cross at times a_i or b_i).The following picture summarizes the situation. In the picture there are m = 4 railways and two trains are visible; the train going through railway 3 is currently crossing the line between Isona and the validating machine. Isona is a really good runner, but she gets tired every time she has to change her running speed. What is the minimum number of speed changes she has to perform to get to the validating machine on the other platform within s seconds from now? Note that at the beginning Isona is not running. She can start to run anytime. The instant she starts to run (i.e. her speed becomes positive) is not counted as a speed change.InputThe first line of the input contains four integers n, m, s, v (1 \leq n \leq 500, 1 \leq m \leq 10, 1 \leq s, v \leq 10^9) — the number of trains, the number of railways, the maximum time in seconds Isona can spend crossing the railways, and the number of seconds she needs to traverse 1 meter at maximum speed.Each of the next n lines contains three integers a_i, b_i, r_i (1 \leq a_i < b_i \leq 10^9, 1 \leq r_i \leq m) — the start and end times of the i-th train crossing the straight line between Isona and the validating machine, and the railway it will be using.It is guaranteed that, for any two trains i and j that go through the same railway (i.e. r_i = r_j), there is at least 1 second between them (that is, either a_j \ge b_i + 1 or a_i \ge b_j + 1).OutputPrint the minimum number of speed changes Isona has to perform to get to the validating machine in time. If this is impossible, print -1.ExamplesInput 4 3 5 1 1 2 1 3 4 1 2 3 2 3 4 3 Output 0 Input 3 3 12 2 2 10 1 1 6 2 8 12 3 Output 2 Input 8 4 13 2 1 4 1 5 13 1 1 5 2 6 13 2 1 9 3 10 13 3 1 10 4 11 13 4 Output 2 Input 1 1 2 2 1 2 1 Output -1 NoteIn the first sample, if Isona starts running at time t=0 at maximum speed (1 m/s), she will cross each railway just when a train is about to traverse it, and she will arrive at the other platform at time 4 = s - 1 without changing speed.In the second sample, a possible solution with 2 speed changes is the following: for the first 2 seconds Isona goes at maximum speed (0.5 m/s), then she slows down to 0.25 m/s for 4 seconds until she reaches the second railway. At that point, she goes at maximum speed again until she reaches the other platform.In the third sample, Isona can wait 2 seconds before starting running. She then runs for 5 seconds at maximum speed (0.5 m/s). After that, she waits for 1 second not running (or running at 0 m/s), and finally she runs again at maximum speed for the last 5 seconds. Overall, she changes speed twice.
4 3 5 1 1 2 1 3 4 1 2 3 2 3 4 3
0
4 seconds
1024 megabytes
['data structures', 'dp', '*3500']
D. Teamworktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs soon as SWERC starts, your experienced 3-person team immediately realizes that the contest features a easy problems, b medium problems, and c hard problems. Solving a problem will take any of you 2, 3, or 4 time units, depending on whether the problem is easy, medium, or hard. Regardless of the difficulty of the problem, the last time unit spent to solve it has to be spent using your shared computer.You organize your efforts so that each of you starts (and ends) solving problems at integer time units. Any given problem can be solved by only one contestant; it requires a contiguous amount of time (which depends on the difficulty of the problem). None of the 3 of you can solve more than one problem at a time, but you can start solving a new problem immediately after finishing one. Similarly, the shared computer cannot be used by more than one of you at a time, but any of you can start using the computer (to complete the problem currently being solved) immediately after someone else stops using it.Given that the contest lasts l time units, find the maximum number of problems that your team can solve. Additionally, find one way to solve the maximum number of problems.InputThe input has a single line. It contains four integers a, b, c, l (0 \leq a, b, c, \leq 10^4, 0 \le l \le 10^5) — the number of easy, medium, and hard problems, and the duration of the contest.OutputOn the first line, print a single integer n — the maximum number of problems that your team can solve.Then, on the j-th of the following n lines, print three integers x_j, p_j, q_j (1 \leq x \leq 3, 0 \leq p_j < q_j \leq l) — the contestant that solves the j-th problem, and the start and end time for solving the j-th problem (measured as time units elapsed from the beginning of the contest). The difference q_j - p_j is 2, 3, or 4, depending on the difficulty of the problem.The last n lines are to be provided in increasing order of end time: q_1 < q_2 < \cdots < q_n. If there are multiple ways to solve n problems, output any of them.ExamplesInput 2 1 1 3 Output 2 1 0 2 2 0 3 Input 1 2 3 5 Output 4 1 0 2 2 0 3 3 0 4 1 2 5 Input 0 1 2 2 Output 0 NoteIn the first sample, the first contestant solves an easy problem between time 0 and time 2 while the second contestant solves a medium problem between time 0 and time 3.In the second sample, the first contestant solves an easy problem between time 0 and time 2, and then also solves a medium problem between time 2 and time 5. In the meantime, the second contestant solves another medium problem between time 0 and time 3, while the third contestant solves a hard problem between time 0 and time 4.In the third sample, the contest only has medium and hard problems, and there is not enough time to solve any of them.
2 1 1 3
2 1 0 2 2 0 3
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*2800']
C. Library gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlessia and Bernardo are discovering the world of competitive programming through the books of their university library.The library consists of m sections numbered from 1 to m. Each section contains only books dedicated to a particular subject and different sections correspond to different subjects. In order to prevent the students from wandering in the library, the university has established a system of passes. Each pass has a length y associated to it and allows access to an interval of y consecutive sections in the library. During a visit, the student must choose exactly one book from one of these sections and leave the library. Each pass can be used only once.At the moment Alessia and Bernardo have n passes of lengths x_1, \, x_2, \, \dots, \, x_n. They have different opinions on the best way to improve: Alessia thinks that it is important to study many different topics, while Bernardo believes that it is important to study deeply at least one topic. So, Alessia wants to use the n passes to get n books on distinct topics, while Bernardo would like to get at least two books on the same topic.They have reached the following agreement: for each of the following n days, Alessia will choose a pass of length y among those which are still available and an interval of y sections in the library, and Bernardo will go into the library and will take exactly one book from one of those sections.Can Bernardo manage to get at least two books on the same subject, or will Alessia be able to avoid it?You should decide whether you want to be Alessia or Bernardo, and you have to fulfill the goal of your chosen character. The judge will impersonate the other character. Note that, even if at some moment Bernardo has already taken two books on the same subject, the interaction should go on until the end of the n days.InputThe first line contains two integers n and m (1 \le n \le 100, n \le m \le 5000) — the number of passes and the number of sections.The second line contains n integers x_1, \, x_2, \, \dots, \, x_n (1 \le x_i \le m) — the lengths of the passes available.InteractionFirst, you should print a line containing either the string \texttt{Alessia} or the string \texttt{Bernardo} — the character that you want to impersonate. Then, for each of the n turns: If you are taking the role of Alessia, print a single line consisting of two integers y and a (1 \le a \le m - y + 1) — you are choosing a pass of length y and the interval of sections [a, a + y - 1]. Note that at least one pass of length y must still be available. After this, read a single integer b (a \le b \le a + y - 1) — the subject of the book selected by Bernardo. If you are taking the role of Bernardo, read two integers y and a (1 \le a \le m - y + 1) — the length of the pass chosen by Alessia and the index of the first section of the interval. It is guaranteed that there is at least one pass of length y available. Then, print a line consisting of a single integer b (a \le b \le a + y - 1) — the subject from which you choose to take a book. If one of your interactions is malformed, the interactor terminates immediately and your program receives the verdict \texttt{WRONG-ANSWER}. Otherwise, you will receive the verdict according to the game's criteria described above.After printing a line do not forget to end the line and flush the output. Otherwise, you will get the verdict \texttt{TIMELIMIT}. To flush the output, use: \texttt{fflush(stdout)} in C; \texttt{fflush(stdout)}, \texttt{cout <}\texttt{< flush} or \texttt{cout.flush()} in C++; \texttt{System.out.flush()} in Java and Kotlin; \texttt{sys.stdout.flush()} in Python. ExamplesInput 5 14 3 7 2 3 10 Output -Input 4 10 4 1 6 4 Output -NoteIn the first sample, it can be shown that Alessia can accomplish her goal. An example of interaction (after reading the input) follows: \begin{array}{|c|c|c|} \hline \textbf{Contestant} & \textbf{Judge} & \textbf{Explanation} \\ \hline \texttt{Alessia} & & \text{The program will act as Alessia} \\ \hline 3 \quad 11 & & \text{Choose $y = 3$ and $a = 11$} \\ \hline & 13 & \text{Judge selects $b = 13$} \\ \hline 10 \quad 2 & & \text{Choose $y = 10$ and $a = 2$} \\ \hline & 9 & \text{Judge selects $b = 9$} \\ \hline 7 \quad 1 & & \text{Choose $y = 7$ and $a = 1$} \\ \hline & 4 & \text{Judge selects $b = 4$} \\ \hline 2 \quad 10 & & \text{Choose $y = 2$ and $a = 10$} \\ \hline & 10 & \text{Judge selects $b = 10$} \\ \hline 3 \quad 6 & & \text{Choose $y = 3$ and $a = 6$} \\ \hline & 7 & \text{Judge selects $b = 7$} \\ \hline \end{array} The program of the contestant wins because all the books chosen by Bernardo pertain to different topics. The actions performed by the contestant and the judge in this example of interaction may be non-optimal.In the second sample, it can be shown that Bernardo can manage to fulfil his goal. An example of interaction (after reading the input) follows: \begin{array}{|c|c|c|} \hline \textbf{Contestant} & \textbf{Judge} & \textbf{Explanation} \\ \hline \texttt{Bernardo} & & \text{The program will act as Bernardo} \\ \hline & 4 \quad 1 & \text{Judge chooses $y = 4$ and $a = 1$} \\ \hline 4 & & \text{Select $b = 4$} \\ \hline & 1 \quad 10 & \text{Judge chooses $y = 1$ and $a = 10$} \\ \hline 10 & & \text{Select $b = 10$} \\ \hline & 6 \quad 3 & \text{Judge chooses $y = 6$ and $a = 3$} \\ \hline 4 & & \text{Select $b = 4$} \\ \hline & 4 \quad 5 & \text{Judge chooses $y = 4$ and $a = 5$} \\ \hline 8 & & \text{Select $b = 8$} \\ \hline \end{array} The program of the contestant wins because Bernardo has selected two books on topic number 4. The actions performed by the contestant and the judge in this example of interaction may be non-optimal.
5 14 3 7 2 3 10
-
2 seconds
256 megabytes
['games', 'greedy', 'interactive', 'sortings', '*2500']
B. Vittorio Plays with LEGO Brickstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVittorio is playing with his new LEGO Duplo bricks. All the bricks have the shape of a square cuboid with a 2 \times 2 square base and a height of 1. They can be arranged in the 3D space to build structures, provided that the following rules are met: No two bricks can intersect, but they can touch on their faces. The corners of every brick must have integer coordinates (so bricks are axis-aligned) and the z coordinates of all corners must be non-negative. The square bases of every brick must be parallel to the ground (i.e. the plane z=0). The lower base of any brick that is not touching the ground must touch the upper base of some other brick in a region of positive area (when this happens, the two bricks stay attached to each other thanks to small studs).For example, this is a valid structure: Vittorio wants to build a structure that includes purple bricks in the following n positions: (x_1, 0, h), (x_2, 0, h), \dots, (x_n, 0, h) — these are the coordinates of the centers of their lower bases; note that all of these bricks have y coordinate equal to 0 and z coordinate equal to h. Vittorio will use additional bricks of other colors to support the purple bricks. He is willing to place bricks only in positions where the center of the lower base has y coordinate equal to 0. What is the minimum number of additional bricks needed?It can be shown that a valid construction always exists.InputThe first line contains two integers n and h (1 \le n \le 300, 0 \le h \le 10^9) — the number of purple bricks and their common z coordinate.The second line contains n integers x_1, \, x_2, \, \dots, \, x_n (1 \le x_i \le 10^9, x_i + 1 < x_{i+1}) — the x coordinates of the purple bricks (centers of the bases), given in increasing order.OutputPrint the minimum number of additional bricks needed.ExamplesInput 4 0 2 7 11 13 Output 0 Input 4 1 2 7 11 13 Output 3 Input 4 100 2 7 11 13 Output 107 Input 4 3 2 5 8 11 Output 8 NoteIn the first sample, all the purple bricks lie on the ground, so no additional bricks are needed.In the second sample, Vittorio will have to place supporting bricks under the purple bricks, and he can use a single brick to support both the third and the fourth purple bricks. For example, he can place additional bricks at positions (3, 0, 0), (7, 0, 0) and (12, 0, 0). It can be shown that it is impossible to build a valid construction using less than 3 additional bricks.In the fourth sample, a possible structure that minimizes the number of additional bricks is shown in the problem description.
4 0 2 7 11 13
0
2 seconds
256 megabytes
['dp', 'geometry', '*2200']
A. Walking Boytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne of the SWERC judges has a dog named Boy. Besides being a good competitive programmer, Boy loves fresh air, so she wants to be walked at least twice a day. Walking Boy requires 120 consecutive minutes. Two walks cannot overlap, but one can start as soon as the previous one has finished. Boy before and after getting ACCEPTED on this problem. Today, the judge sent n messages to the SWERC Discord server. The i-th message was sent a_i minutes after midnight. You know that, when walking Boy, the judge does not send any messages, but he can send a message right before or right after a walk. Is it possible that the judge walked Boy at least twice today?Note that a day has 1440 minutes, and a walk is considered to happen today if it starts at a minute s \ge 0 and ends right before a minute e \le 1440. In that case, it must hold that e - s = 120 and, for every i = 1, \, 2 \, \dots, \, n, either a_i \le s or a_i \ge e.InputEach test contains multiple test cases. The first line contains an integer t (1 \le t \le 100) — the number of test cases. The descriptions of the t test cases follow.The first line of each test case contains an integer n (1 \le n \le 100) — the number of messages sent by the judge.The second line of each test case contains n integers a_1, \, a_2, \, \dots, \, a_n (0 \le a_1 < a_2 < \cdots < a_n < 1440) — the times at which the messages have been sent (in minutes elapsed from midnight).OutputFor each test case, output one line containing \texttt{YES} if it is possible that Boy has been walked at least twice, and \texttt{NO} otherwise.ExampleInput 614100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 140012100 200 300 400 600 700 800 900 1100 1200 1300 140013100 200 300 400 500 600 700 800 900 1100 1200 1300 140013101 189 272 356 463 563 659 739 979 1071 1170 1274 135814250 1 2 3 4Output NO YES NO YES YES YES NoteIn the first test case, the judge has sent a message at each time multiple of 100 (excluding 0). It is impossible that he has walked Boy even once.In the second test case, the times are the same as above, but 500 and 1000 are missing. The judge could have walked Boy, for instance, during the time intervals [440, 560] and [980, 1100]. The situation is illustrated in the picture below, where the walks are represented by green intervals. In the third test case, the times are the same as in the first test case, but 1000 is missing. The judge could have walked Boy at most once.In the fourth test case, Boy could have been walked during the time intervals [739, 859] and [859, 979].
614100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 140012100 200 300 400 600 700 800 900 1100 1200 1300 140013100 200 300 400 500 600 700 800 900 1100 1200 1300 140013101 189 272 356 463 563 659 739 979 1071 1170 1274 135814250 1 2 3 4
NO YES NO YES YES YES
2 seconds
256 megabytes
['greedy', '*800']
F. Laboratory on Plutotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you know, Martian scientists are actively engaged in space research. One of the highest priorities is Pluto. In order to study this planet in more detail, it was decided to build a laboratory on Pluto.It is known that the lab will be built of n square blocks of equal size. For convenience, we will assume that Pluto's surface is a plane divided by vertical and horizontal lines into unit squares. Each square is either occupied by a lab block or not, and only n squares are occupied.Since each block is square, it has four walls. If a wall is adjacent to another block, it is considered inside, otherwise — outside.Pluto is famous for its extremely cold temperatures, so the outside walls of the lab must be insulated. One unit of insulation per exterior wall would be required. Thus, the greater the total length of the outside walls of the lab (i. e., its perimeter), the more insulation will be needed.Consider the lab layout in the figure below. It shows that the lab consists of n = 33 blocks, and all the blocks have a total of 24 outside walls, i. e. 24 units of insulation will be needed.You should build the lab optimally, i. e., minimize the amount of insulation. On the other hand, there may be many optimal options, so scientists may be interested in the number of ways to build the lab using the minimum amount of insulation, modulo a prime number m.Two ways are considered the same if they are the same when overlapping without turning. Thus, if a lab plan is rotated by 90^{\circ}, such a new plan can be considered a separate way.To help scientists explore Pluto, you need to write a program that solves these difficult problems. InputThe first line contains two integers t and u (1 \le t \le 2\cdot 10^5, 1 \le u \le 2) — the number of test cases and the test type. If u=1, you need to find any way to build the lab in an optimal way, and if u=2, you need to calculate the number of ways to do it.If u=2, then in the following line of input there is a prime integer m (10^8 \le m \le 10^9 + 9), modulo which you need to calculate the number of ways.Each of the following t lines of input contains a description of a test case consisting of one integer n (1 \le n \le 4\cdot 10^5) — the number of blocks the lab should consist of.It is guaranteed that if u=1, then the sum of n on all test cases does not exceed 8\cdot10^5.OutputFor each test case, output the answers in the format below, separating them with a newline. The output format depends on u in the input data.If u=1, in the first line you need to print two integers h and w —the height and width of the area in which the lab should be built. Then, in each of the following h lines, you must output a line s_i consisting of w characters "#" and ".". If the j-th character of the row s_i is "#", then the corresponding square must contain a block of laboratory, otherwise, it is considered empty. Thus, we get a matrix of symbols. The condition must also be met that the first and last rows of the matrix, as well as the first and last columns, must have at least one character "#", otherwise we could output the same lab layout, but with smaller h and w. If there are many options to build an optimal lab, you can print any of them.If u=2, you need to print two integers p and c — the number of outside walls in an optimal lab, and the remainder of the number of ways by prime modulo m.ExamplesInput 3 1127Output 1 1 # 1 2 ## 2 4 .### #### Input 3 21000000007127Output 4 1 6 2 12 22 NoteConsider the second example.If n=1, the only way to build a lab is to place a single block. In this case, the perimeter will be equal to four.When n=2, you must place two blocks side by side. This can be done either vertically or horizontally, so there are two ways. It is easy to see that the lab has six outside walls in this case.For n=7, all the 22 optimal plans are shown in the picture below.
3 1127
1 1 # 1 2 ## 2 4 .### ####
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', 'math', '*2500']
E. The Human Equationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and his friend, the robot Petya++, went to BFDMONCON, where the costume contest is taking place today. While walking through the festival, they came across a scientific stand named after Professor Oak and Golfball, where they were asked to solve an interesting problem.Given a sequence of numbers a_1, a_2, \dots, a_n you can perform several operations on this sequence.Each operation should look as follows. You choose some subsequence^\dagger. Then you call all the numbers at odd positions in this subsequence northern, and all the numbers at even positions in this subsequence southern. In this case, only the position of the number in the subsequence is taken into account, not in the original sequence.For example, consider the sequence 1, 4, 2, 8, 5, 7, 3, 6, 9 and its subsequence (shown in bold) 1, \mathbf{4}, \mathbf{2}, 8, \mathbf{5}, 7, 3, \mathbf{6}, 9. Then the numbers 4 and 5 are northern, and the numbers 2 and 6 are southern.After that, you can do one of the following: add 1 to all northern numbers and subtract 1 from all south numbers; or add 1 to all southern numbers and subtract 1 from all northern numbers. Thus, from the sequence 1, \mathbf{4}, \mathbf{2}, 8, \mathbf{5}, 7, 3, \mathbf{6}, 9, if you choose the subsequence shown in bold, you can get either 1, \mathbf{5}, \mathbf{1}, 8, \mathbf{6}, 7, 3, \mathbf{5}, 9 or 1, \mathbf{3}, \mathbf{3}, 8, \mathbf{4}, 7, 3, \mathbf{7}, 9.Then the operation ends. Note also that all operations are independent, i. e. the numbers are no longer called northern or southern when one operation ends.It is necessary to turn all the numbers of the sequence into zeros using the operations described above. Since there is very little time left before the costume contest, the friends want to know, what is the minimum number of operations required for this.The friends were unable to solve this problem, so can you help them?^\dagger A sequence c is a subsequence of a sequence d if c can be obtained from d by the deletion of several (possibly, zero or all) elements.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 2\cdot 10^5) — the length of the sequence.The second line contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9) — the description of the sequence itself.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, print one integer in a single line — the minimum number of operations it takes to turn all the numbers into zeros.ExampleInput 531 2 -351 0 0 -1 -162 -4 3 -5 4 151 -1 1 -1 170 0 0 0 0 0 0Output 3 2 6 1 0 NoteIn the first test case, the sequence of operations is as follows: \mathbf{1}, 2, \mathbf{-3} \longrightarrow 0, \mathbf{2}, \mathbf{-2} \longrightarrow 0, \mathbf{1}, \mathbf{-1} \longrightarrow 0, 0, 0.In the second test case, the sequence looks like this: \mathbf{1}, 0, 0, \mathbf{-1}, -1 \longrightarrow 0, 0, 0, 0, \mathbf{-1} \longrightarrow 0, 0, 0, 0, 0.In the fourth test case, simply select the entire sequence as a subsequence, then subtract one from the northern numbers and add one to the southern numbers. Thus, the sequence will be nulled in one operation.In the fifth test case, you don't need to do any operations, since the sequence already consists of zeros.
531 2 -351 0 0 -1 -162 -4 3 -5 4 151 -1 1 -1 170 0 0 0 0 0 0
3 2 6 1 0
1 second
256 megabytes
['greedy', 'implementation', '*2100']
D. Friendly Spiderstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMars is home to an unusual species of spiders — Binary spiders.Right now, Martian scientists are observing a colony of n spiders, the i-th of which has a_i legs.Some of the spiders are friends with each other. Namely, the i-th and j-th spiders are friends if \gcd(a_i, a_j) \ne 1, i. e., there is some integer k \ge 2 such that a_i and a_j are simultaneously divided by k without a remainder. Here \gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.Scientists have discovered that spiders can send messages. If two spiders are friends, then they can transmit a message directly in one second. Otherwise, the spider must pass the message to his friend, who in turn must pass the message to his friend, and so on until the message reaches the recipient.Let's look at an example.Suppose a spider with eight legs wants to send a message to a spider with 15 legs. He can't do it directly, because \gcd(8, 15) = 1. But he can send a message through the spider with six legs because \gcd(8, 6) = 2 and \gcd(6, 15) = 3. Thus, the message will arrive in two seconds.Right now, scientists are observing how the s-th spider wants to send a message to the t-th spider. The researchers have a hypothesis that spiders always transmit messages optimally. For this reason, scientists would need a program that could calculate the minimum time to send a message and also deduce one of the optimal routes. InputThe first line of input contains an integer n (2 \le n \le 3\cdot10^5) — the number of spiders in the colony.The second line of input contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 3\cdot10^5) — the number of legs the spiders have.The third line of input contains two integers s and t (1 \le s, t \le n) —the spiders between which the message must be sent.OutputIf it is impossible to transmit a message between the given pair of spiders, print -1.Otherwise, in the first line of the output print the integer t (t \ge 1) — the number of spiders that participate in the message transmission (i. e. the minimum time of message delivery in seconds plus one). In the second line, print t different integers b_1, b_2, \ldots, b_t (1 \le b_i \le n) — the ids of the spiders through which the message should follow, in order from sender to receiver.If there are several optimal routes for the message, output any of them.ExamplesInput 7 2 14 9 6 8 15 11 5 6 Output 3 5 4 6 Input 7 2 14 9 6 8 15 11 5 7 Output -1Input 7 2 14 9 6 8 15 11 5 5 Output 1 5 NoteThe first example is shown above. It shows that the message from the 5-th spider (with eight legs) to the 6-th spider (with 15 legs) is optimal to pass through the 4-th spider (with six legs).In the second example, the spider number 7 (with 11 legs) is not friends with anyone, so it is impossible to send him a message.
7 2 14 9 6 8 15 11 5 6
3 5 4 6
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'math', 'number theory', 'shortest paths', '*1800']
C. Interesting Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya and his friend, robot Petya++, like to solve exciting math problems.One day Petya++ came up with the numbers n and x and wrote the following equality on the board: n\ \&\ (n+1)\ \&\ \dots\ \&\ m = x, where \& denotes the bitwise AND operation. Then he suggested his friend Petya find such a minimal m (m \ge n) that the equality on the board holds.Unfortunately, Petya couldn't solve this problem in his head and decided to ask for computer help. He quickly wrote a program and found the answer.Can you solve this difficult problem? InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 2000). The description of the test cases follows.The only line of each test case contains two integers n, x (0\le n, x \le 10^{18}).OutputFor every test case, output the smallest possible value of m such that equality holds.If the equality does not hold for any m, print -1 instead.We can show that if the required m exists, it does not exceed 5 \cdot 10^{18}.ExampleInput 510 810 1010 4220 161000000000000000000 0Output 12 10 -1 24 1152921504606846976 NoteIn the first example, 10\ \&\ 11 = 10, but 10\ \&\ 11\ \&\ 12 = 8, so the answer is 12.In the second example, 10 = 10, so the answer is 10.In the third example, we can see that the required m does not exist, so we have to print -1.
510 810 1010 4220 161000000000000000000 0
12 10 -1 24 1152921504606846976
1 second
256 megabytes
['bitmasks', 'math', '*1600']
B. Gardener and the Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe gardener Kazimir Kazimirovich has an array of n integers c_1, c_2, \dots, c_n.He wants to check if there are two different subsequences a and b of the original array, for which f(a) = f(b), where f(x) is the bitwise OR of all of the numbers in the sequence x.A sequence q is a subsequence of p if q can be obtained from p by deleting several (possibly none or all) elements.Two subsequences are considered different if the sets of indexes of their elements in the original sequence are different, that is, the values of the elements are not considered when comparing the subsequences. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.The first line of each test case contains one integer n (1 \le n \le 10^5) — the size of the array c.The description of the array c in this problem is given implicitly to speed up input.The (i + 1)-st of the following n lines of the test case begins with an integer k_i (1 \le k_i \le 10^5) — the number of set bits in the number c_i. Next follow k_i distinct integers p_{i, 1}, p_{i, 2}, \dots, p_{i, k_i} (1 \le p_i \le 2 \cdot 10^5) —the numbers of bits that are set to one in number c_i. In other words, c_i = 2^{p_{i, 1}} + 2^{p_{i, 2}} + \ldots + 2^{p_{i, k_i}}.It is guaranteed that the total sum of k_i in all tests does not exceed 10^5.OutputFor each set of input, print "Yes" if there exist two different subsequences for which f(a) = f(b), and "No" otherwise.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput 532 1 52 2 42 2 322 1 21 243 1 2 42 2 44 1 2 5 62 2 553 3 1 23 2 5 35 7 2 3 1 45 1 2 6 3 53 2 6 321 11 2Output No Yes Yes Yes No NoteIt can be proven that in the first test case there are no two different subsequences a and b for which f(a) = f(b).In the second test case, one of the possible answers are following subsequences: the subsequence a formed by the element at position 1, and the subsequence b formed by the elements at positions 1 and 2.In the third test case, one of the possible answers are following subsequences: the subsequence a formed by elements at positions 1, 2, 3 and 4, and the subsequence b formed by elements at positions 2, 3 and 4.
532 1 52 2 42 2 322 1 21 243 1 2 42 2 44 1 2 5 62 2 553 3 1 23 2 5 35 7 2 3 1 45 1 2 6 3 53 2 6 321 11 2
No Yes Yes Yes No
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', '*1300']
A2. Gardener and the Capybaras (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an hard version of the problem. The difference between the versions is that the string can be longer than in the easy version. You can only do hacks if both versions of the problem are passed.Kazimir Kazimirovich is a Martian gardener. He has a huge orchard of binary balanced apple trees.Recently Casimir decided to get himself three capybaras. The gardener even came up with their names and wrote them down on a piece of paper. The name of each capybara is a non-empty line consisting of letters "a" and "b".Denote the names of the capybaras by the lines a, b, and c. Then Casimir wrote the nonempty lines a, b, and c in a row without spaces. For example, if the capybara's name was "aba", "ab", and "bb", then the string the gardener wrote down would look like "abaabbb".The gardener remembered an interesting property: either the string b is lexicographically not smaller than the strings a and c at the same time, or the string b is lexicographically not greater than the strings a and c at the same time. In other words, either a \le b and c \le b are satisfied, or b \le a and b \le c are satisfied (or possibly both conditions simultaneously). Here \le denotes the lexicographic "less than or equal to" for strings. Thus, a \le b means that the strings must either be equal, or the string a must stand earlier in the dictionary than the string b. For a more detailed explanation of this operation, see "Notes" section.Today the gardener looked at his notes and realized that he cannot recover the names because they are written without spaces. He is no longer sure if he can recover the original strings a, b, and c, so he wants to find any triplet of names that satisfy the above property. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The only line of a test case contains the string s (3 \le |s| \le 2 \cdot 10^5) — the names of the capybaras, written together. The string consists of English letters 'a' and 'b' only.It is guaranteed that the sum of string lengths over all test cases does not exceed 4 \cdot 10^5.OutputFor each test case, print three strings a, b and c on a single line, separated by spaces — names of capybaras, such that writing them without spaces results in a line s. Either a \le b and c \le b, or b \le a and b \le c must be satisfied.If there are several ways to restore the names, print any of them. If the names cannot be recovered, print ":(" (without quotes).ExampleInput 5bbbaabaaaaabbaabbbOutput b bb a a b a a a a ab b a a bb bNoteA string x is lexicographically smaller than a string y if and only if one of the following holds: x is a prefix of y, but x \ne y; in the first position where x and y differ, the string x has the letter 'a', and the string y has the letter 'b'. Now let's move on to the examples.In the first test case, one of the possible ways to split the line s into three lines —is "b", "bb", "a".In the third test case, we can see that the split satisfies two conditions at once (i.e., a \le b, c \le b, b \le a and b \le c are true simultaneously).
5bbbaabaaaaabbaabbb
b bb a a b a a a a ab b a a bb b
1 second
256 megabytes
['constructive algorithms', 'greedy', '*900']
A1. Gardener and the Capybaras (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The difference between the versions is that the string can be longer than in the easy version. You can only do hacks if both versions of the problem are passed.Kazimir Kazimirovich is a Martian gardener. He has a huge orchard of binary balanced apple trees.Recently Casimir decided to get himself three capybaras. The gardener even came up with their names and wrote them down on a piece of paper. The name of each capybara is a non-empty line consisting of letters "a" and "b".Denote the names of the capybaras by the lines a, b, and c. Then Casimir wrote the nonempty lines a, b, and c in a row without spaces. For example, if the capybara's name was "aba", "ab", and "bb", then the string the gardener wrote down would look like "abaabbb".The gardener remembered an interesting property: either the string b is lexicographically not smaller than the strings a and c at the same time, or the string b is lexicographically not greater than the strings a and c at the same time. In other words, either a \le b and c \le b are satisfied, or b \le a and b \le c are satisfied (or possibly both conditions simultaneously). Here \le denotes the lexicographic "less than or equal to" for strings. Thus, a \le b means that the strings must either be equal, or the string a must stand earlier in the dictionary than the string b. For a more detailed explanation of this operation, see "Notes" section.Today the gardener looked at his notes and realized that he cannot recover the names because they are written without spaces. He is no longer sure if he can recover the original strings a, b, and c, so he wants to find any triplet of names that satisfy the above property. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). The description of the test cases follows.The only line of a test case contains the string s (3 \le |s| \le 100) — the names of the capybaras, written together. The string consists of English letters 'a' and 'b' only.It is guaranteed that the sum of string lengths over all test cases does not exceed 500.OutputFor each test case, print three strings a, b and c on a single line, separated by spaces — names of capybaras, such that writing them without spaces results in a line s. Either a \le b and c \le b, or b \le a and b \le c must be satisfied.If there are several ways to restore the names, print any of them. If the names cannot be recovered, print ":(" (without quotes).ExampleInput 5bbbaabaaaaabbaabbbOutput b bb a a b a a a a ab b a a bb bNoteA string x is lexicographically smaller than a string y if and only if one of the following holds: x is a prefix of y, but x \ne y; in the first position where x and y differ, the string x has the letter 'a', and the string y has the letter 'b'. Now let's move on to the examples.In the first test case, one of the possible ways to split the line s into three lines — "b", "bb", "a".In the third test case, we can see that the split satisfies two conditions at once (i. e., a \le b, c \le b, b \le a, and b \le c are true simultaneously).
5bbbaabaaaaabbaabbb
b bb a a b a a a a ab b a a bb b
1 second
256 megabytes
['brute force', 'constructive algorithms', 'implementation', '*800']
H. Maximum Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEcrade bought a deck of cards numbered from 1 to n. Let the value of a permutation a of length n be \min\limits_{i = 1}^{n - k + 1}\ \sum\limits_{j = i}^{i + k - 1}a_j.Ecrade wants to find the most valuable one among all permutations of the cards. However, it seems a little difficult, so please help him! InputThe first line contains a single integer t (1 \leq t \leq 2 \cdot 10^4)  — the number of test cases. The description of test cases follows.The only line of each test case contains two integers n,k (4 \leq k < n \leq 10^5).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^6.OutputFor each test case, output the largest possible value in the first line. Then in the second line, print n integers a_1,a_2,\dots,a_n (1 \le a_i \le n, all a_i are distinct)  — the elements of the permutation that has the largest value.If there are multiple such permutations, output any of them.ExampleInput 2 5 4 8 4 Output 13 1 4 5 3 2 18 4 2 5 7 8 3 1 6NoteIn the first test case, [1,4,5,3,2] has a value of 13. It can be shown that no permutations of length 5 have a value greater than 13 when k = 4.In the second test case, [4,2,5,7,8,3,1,6] has a value of 18. It can be shown that no permutations of length 8 have a value greater than 18 when k = 4.
2 5 4 8 4
13 1 4 5 3 2 18 4 2 5 7 8 3 1 6
2 seconds
256 megabytes
['constructive algorithms', '*3500']
G. Segment Coveringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputChthollyNotaSeniorious gives DataStructures a number axis with m distinct segments on it. Let f(l,r) be the number of ways to choose an even number of segments such that the union of them is exactly [l,r], and g(l,r) be the number of ways to choose an odd number of segments such that the union of them is exactly [l,r].ChthollyNotaSeniorious asked DataStructures q questions. In each query, ChthollyNotaSeniorious will give DataStructures two numbers l, r, and now he wishes that you can help him find the value f(l,r)-g(l,r) modulo 998\,244\,353 so that he wouldn't let her down. InputThe first line of input contains two integers m (1 \leq m \leq 2 \cdot 10^5) and q (1 \leq q \leq 2 \cdot 10^5)  — the number of segments and queries, correspondingly.The i-th of the next m lines contains two integers x_i and y_i (1 \leq x_i < y_i \leq 10^9), denoting a segment [x_i, y_i]. It is guaranteed that all segments are distinct. More formally, there do not exist two numbers i, j with 1 \le i < j \le m such that x_i = x_j and y_i = y_j.The i-th of the next q lines contains two integers l_i and r_i (1 \leq l_i < r_i \leq 10^9), describing a query.OutputFor each query, output a single integer  — f(l_i,r_i)-g(l_i,r_i) modulo 998\,244\,353.ExampleInput 4 2 1 3 4 6 2 4 3 5 1 4 1 5 Output 1 0 NoteIn the first query, we have to find f(1, 4) - g(1, 4). The only subset of segments with union [1, 4] is \{[1, 3], [2, 4]\}, so f(1, 4) = 1, g(1, 4) = 0.In the second query, we have to find f(1, 5) - g(1, 5). The only subsets of segments with union [1, 5] are \{[1, 3], [2, 4], [3, 5]\} and \{[1, 3], [3, 5]\}, so f(1, 5) = 1, g(1, 5) = 1.
4 2 1 3 4 6 2 4 3 5 1 4 1 5
1 0
2 seconds
256 megabytes
['brute force', 'combinatorics', 'constructive algorithms', 'data structures', 'dp', 'trees', '*3200']
F2. Magician and Pigs (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between the two versions is the constraint on n and x. You can make hacks only if both versions of the problem are solved.Little09 has been interested in magic for a long time, and it's so lucky that he meets a magician! The magician will perform n operations, each of them is one of the following three: 1\ x: Create a pig with x Health Points. 2\ x: Reduce the Health Point of all living pigs by x. 3: Repeat all previous operations. Formally, assuming that this is the i-th operation in the operation sequence, perform the first i-1 operations (including "Repeat" operations involved) in turn.A pig will die when its Health Point is less than or equal to 0. Little09 wants to know how many living pigs there are after all the operations. Please, print the answer modulo 998\,244\,353.InputThe first line contains a single integer n (1\leq n\leq 8\cdot 10^5)  — the number of operations.Each of the following n lines contains an operation given in the form described in the problem statement. It's guaranteed that 1\leq x\leq 10^9 in operations of the first two types.OutputPrint a single integer  — the number of living pigs after all the operations, modulo 998\,244\,353.ExamplesInput 4 1 8 2 3 3 3 Output 2Input 6 1 5 1 6 2 2 3 1 4 3 Output 5Input 12 2 1 1 15 1 9 3 1 12 2 2 1 13 3 2 1 1 9 1 8 3 Output 17NoteIn the first example, the operations are equivalent to repeating four times: create a pig with 8 Health Points and then reduce the Health Points of all living pigs by 3. It is easy to find that there are two living pigs in the end with 2 and 5 Health Points.
4 1 8 2 3 3 3
2
2 seconds
256 megabytes
['binary search', 'brute force', 'data structures', 'implementation', '*2700']
F1. Magician and Pigs (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between the two versions is the constraint on n and x. You can make hacks only if both versions of the problem are solved.Little09 has been interested in magic for a long time, and it's so lucky that he meets a magician! The magician will perform n operations, each of them is one of the following three: 1\ x: Create a pig with x Health Points. 2\ x: Reduce the Health Point of all living pigs by x. 3: Repeat all previous operations. Formally, assuming that this is the i-th operation in the operation sequence, perform the first i-1 operations (including "Repeat" operations involved) in turn.A pig will die when its Health Point is less than or equal to 0. Little09 wants to know how many living pigs there are after all the operations. Please, print the answer modulo 998\,244\,353.InputThe first line contains a single integer n (1\leq n\leq 2\cdot 10^5)  — the number of operations.Each of the following n lines contains an operation given in the form described in the problem statement. It's guaranteed that 1\leq x\leq 2\cdot 10^5 in operations of the first two types.OutputPrint a single integer  — the number of living pigs after all the operations, modulo 998\,244\,353.ExamplesInput 4 1 8 2 3 3 3 Output 2 Input 6 1 5 1 6 2 2 3 1 4 3 Output 5 Input 12 2 1 1 15 1 9 3 1 12 2 2 1 13 3 2 1 1 9 1 8 3 Output 17 NoteIn the first example, the operations are equivalent to repeating four times: create a pig with 8 Health Points and then reduce the Health Points of all living pigs by 3. It is easy to find that there are two living pigs in the end with 2 and 5 Health Points.
4 1 8 2 3 3 3
2
2 seconds
256 megabytes
['brute force', 'data structures', 'implementation', '*2400']
E. Two Chess Piecestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCirno_9baka has a tree with n nodes. He is willing to share it with you, which means you can operate on it.Initially, there are two chess pieces on the node 1 of the tree. In one step, you can choose any piece, and move it to the neighboring node. You are also given an integer d. You need to ensure that the distance between the two pieces doesn't ever exceed d.Each of these two pieces has a sequence of nodes which they need to pass in any order, and eventually, they have to return to the root. As a curious boy, he wants to know the minimum steps you need to take.InputThe first line contains two integers n and d (2 \le d \le n \le 2\cdot 10^5).The i-th of the following n - 1 lines contains two integers u_i, v_i (1 \le u_i, v_i \le n), denoting the edge between the nodes u_i, v_i of the tree.It's guaranteed that these edges form a tree.The next line contains an integer m_1 (1 \le m_1 \le n) and m_1 integers a_1, a_2, \ldots, a_{m_1} (1 \le a_i \le n, all a_i are distinct)  — the sequence of nodes that the first piece needs to pass.The second line contains an integer m_2 (1 \le m_2 \le n) and m_2 integers b_1, b_2, \ldots, b_{m_2} (1 \le b_i \le n, all b_i are distinct)  — the sequence of nodes that the second piece needs to pass.OutputOutput a single integer  — the minimum steps you need to take.ExamplesInput 4 2 1 2 1 3 2 4 1 3 1 4 Output 6Input 4 2 1 2 2 3 3 4 4 1 2 3 4 1 1 Output 8NoteIn the first sample, here is one possible sequence of steps of length 6. The second piece moves by the route 1 \to 2 \to 4 \to 2 \to 1.Then, the first piece moves by the route 1 \to 3 \to 1.In the second sample, here is one possible sequence of steps of length 8:The first piece moves by the route 1 \to 2 \to 3.Then, the second piece moves by the route 1 \to 2.Then, the first piece moves by the route 3 \to 4 \to 3 \to 2 \to 1.Then, the second piece moves by the route 2 \to 1.
4 2 1 2 1 3 2 4 1 3 1 4
6
2 seconds
256 megabytes
['dfs and similar', 'dp', 'greedy', 'trees', '*1900']
D. Same Count Onetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputChthollyNotaSeniorious received a special gift from AquaMoon: n binary arrays of length m. AquaMoon tells him that in one operation, he can choose any two arrays and any position pos from 1 to m, and swap the elements at positions pos in these arrays.He is fascinated with this game, and he wants to find the minimum number of operations needed to make the numbers of 1s in all arrays the same. He has invited you to participate in this interesting game, so please try to find it!If it is possible, please output specific exchange steps in the format described in the output section. Otherwise, please output -1.InputThe first line of the input contains a single integer t (1 \leq t \leq 2\cdot 10^4)  — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and m (2 \leq n \leq 10^5, 2 \leq m \leq 10^5).The i-th of the following n lines contains m integers a_{i, 1}, a_{i, 2}, \ldots, a_{i, m} (0 \le a_{i, j} \le 1)  — the elements of the i-th array. It is guaranteed that the sum of n \cdot m over all test cases does not exceed 10^6.OutputFor each test case, if the objective is not achievable, output -1. Otherwise, in the first line output k (0 \le k \le mn)  — the minimum number of operations required.The i-th of the following k lines should contain 3 integers, x_i, y_i, z_i (1 \le x_i, y_i \le n, 1 \le z_i \le m), which describe an operation that swap a_{x_i, z_i}, a_{y_i, z_i}: swap the z_i-th number of the x_i-th and y_i-th arrays.ExampleInput 33 41 1 1 00 0 1 01 0 0 14 31 0 00 1 10 0 10 0 02 20 00 1Output 1 2 1 1 1 4 2 2 -1 NoteIn the first test case, it's enough to do a single operation: to swap the first element in the second and the first rows. The arrays will become [0, 1, 1, 0], [1, 0, 1, 0], [1, 0, 0, 1], each of them contains exactly two 1s.
33 41 1 1 00 0 1 01 0 0 14 31 0 00 1 10 0 10 0 02 20 00 1
1 2 1 1 1 4 2 2 -1
2 seconds
512 megabytes
['brute force', 'constructive algorithms', 'greedy', 'implementation', 'two pointers', '*1600']
C. Ice and Firetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle09 and his friends are playing a game. There are n players, and the temperature value of the player i is i. The types of environment are expressed as 0 or 1. When two players fight in a specific environment, if its type is 0, the player with a lower temperature value in this environment always wins; if it is 1, the player with a higher temperature value in this environment always wins. The types of the n-1 environments form a binary string s with a length of n-1.If there are x players participating in the game, there will be a total of x-1 battles, and the types of the x-1 environments will be the first x-1 characters of s. While there is more than one player left in the tournament, choose any two remaining players to fight. The player who loses will be eliminated from the tournament. The type of the environment of battle i is s_i.For each x from 2 to n, answer the following question: if all players whose temperature value does not exceed x participate in the game, how many players have a chance to win?InputEach test contains multiple test cases. The first line contains a single integer t (1\le t \le 10^3)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2\leq n\leq 2\cdot 10^5)  — the number of players.The second line of each test case contains a binary string s with a length n-1.It is guaranteed that the sum of n over all test cases does not exceed 3\cdot 10^5.OutputFor each test case output n-1 integers  — for each x from 2 to n, output the number of players that have a chance to win.ExampleInput 240014101Output 1 1 3 1 2 3 NoteIn the first test case, for x=2 and x=3, only the player whose temperature value is 1 can be the winner. For x=4, the player whose temperature value is 2,3,4 can be the winner.
240014101
1 1 3 1 2 3
1 second
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*1300']
B. Coloringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCirno_9baka has a paper tape with n cells in a row on it. As he thinks that the blank paper tape is too dull, he wants to paint these cells with m kinds of colors. For some aesthetic reasons, he thinks that the i-th color must be used exactly a_i times, and for every k consecutive cells, their colors have to be distinct. Help Cirno_9baka to figure out if there is such a way to paint the cells.InputThe first line contains a single integer t (1 \leq t \leq 10\,000)  — the number of test cases. The description of test cases follows.The first line of each test case contains three integers n, m, k (1 \leq k \leq n \leq 10^9, 1 \leq m \leq 10^5, m \leq n). Here n denotes the number of cells, m denotes the number of colors, and k means that for every k consecutive cells, their colors have to be distinct.The second line of each test case contains m integers a_1, a_2, \cdots , a_m (1 \leq a_i \leq n)  — the numbers of times that colors have to be used. It's guaranteed that a_1 + a_2 + \ldots + a_m = n.It is guaranteed that the sum of m over all test cases does not exceed 10^5.OutputFor each test case, output "YES" if there is at least one possible coloring scheme; otherwise, output "NO".You may print each letter in any case (for example, "YES", "Yes", "yes", and "yEs" will all be recognized as positive answers).ExampleInput 212 6 21 1 1 1 1 712 6 22 2 2 2 2 2Output NO YES NoteIn the first test case, there is no way to color the cells satisfying all the conditions.In the second test case, we can color the cells as follows: (1, 2, 1, 2, 3, 4, 3, 4, 5, 6, 5, 6). For any 2 consecutive cells, their colors are distinct.
212 6 21 1 1 1 1 712 6 22 2 2 2 2 2
NO YES
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1500']
A. Add Plus Minus Signtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAquaMoon has a string a consisting of only 0 and 1. She wants to add + and - between all pairs of consecutive positions to make the absolute value of the resulting expression as small as possible. Can you help her?InputThe first line contains a single integer t (1 \leq t \leq 2\,000)  – the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 100) — the length of a.The second line of each test case contains a string a of length n, consisting of only 0 and 1.OutputFor each test case, output a string of length n - 1 consisting of - and + on a separate line. If there is more than one assignment of signs that produces the smallest possible absolute value, any of them is accepted.ExampleInput 3211501101510001Output - +-++ +++- NoteIn the first test case, we can get the expression 1 - 1 = 0, with absolute value 0.In the second test case, we can get the expression 0 + 1 - 1 + 0 + 1 = 1, with absolute value 1.In the third test case, we can get the expression 1 + 0 + 0 + 0 - 1 = 0, with absolute value 0.
3211501101510001
- +-++ +++-
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
L. Lisa's Sequencestime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputLisa loves playing with the sequences of integers. When she gets a new integer sequence a_i of length n, she starts looking for all monotone subsequences. A monotone subsequence [l, r] is defined by two indices l and r (1 \le l < r \le n) such that \forall i = l, l+1, \ldots, r-1: a_i \le a_{i+1} or \forall i = l, l+1, \ldots, r-1: a_i \ge a_{i+1}. Lisa considers a sequence a_i to be boring if there is a monotone subsequence [l, r] that is as long as her boredom threshold k, that is when r - l + 1 = k.Lucas has a sequence b_i that he wants to present to Lisa, but the sequence might be boring for Lisa. So, he wants to change some elements of his sequence b_i, so that Lisa does not get bored playing with it. However, Lucas is lazy and wants to change as few elements of the sequence b_i as possible. Your task is to help Lucas find the required changes. InputThe first line of the input contains two integers n and k (3 \le k \le n \le 10^6) — the length of the sequence and Lisa's boredom threshold. The second line contains n integers b_i (1 \le b_i \le 99\,999) — the original sequence that Lucas has.OutputOn the first line output an integer m — the minimal number of elements in b_i that needs to be changed to make the sequence not boring for Lisa. On the second line output n integers a_i (0 \le a_i \le 100\,000), so that the sequence of integers a_i is not boring for Lisa and is different from the original sequence b_i in exactly m positions.ExamplesInput 5 3 1 2 3 4 5 Output 2 1 0 3 0 5 Input 6 3 1 1 1 1 1 1 Output 3 1 100000 0 1 0 1 Input 6 4 1 1 4 4 1 1 Output 1 1 1 4 0 1 1 Input 6 4 4 4 4 2 2 2 Output 2 4 4 0 2 0 2 Input 6 4 4 4 4 3 4 4 Output 1 4 4 100000 3 4 4 Input 8 4 2 1 1 3 3 1 1 2 Output 2 2 1 1 3 0 1 0 2 Input 10 4 1 1 1 2 2 1 1 2 2 1 Output 2 1 1 100000 2 2 100000 1 2 2 1 Input 7 5 5 4 4 3 4 4 4 Output 0 5 4 4 3 4 4 4 Input 10 10 1 1 1 1 1 1 1 1 1 1 Output 1 1 1 1 1 1 1 1 1 0 1
5 3 1 2 3 4 5
2 1 0 3 0 5
5 seconds
1024 megabytes
['dp', '*3500']
J. Jumbled Treestime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given an undirected connected graph with n vertices and m edges. Each edge has an associated counter, initially equal to 0. In one operation, you can choose an arbitrary spanning tree and add any value v to all edges of this spanning tree. Determine if it's possible to make every counter equal to its target value x_i modulo prime p, and provide a sequence of operations that achieves it.InputThe first line contains three integers n, m, and p — the number of vertices, the number of edges, and the prime modulus (1 \le n \le 500; 1 \le m \le 1000; 2 \le p \le 10^9, p is prime).Next m lines contain three integers u_i, v_i, x_i each — the two endpoints of the i-th edge and the target value of that edge's counter (1 \le u_i, v_i \le n; 0 \le x_i < p; u_i \neq v_i). The graph is connected. There are no loops, but there may be multiple edges between the same two vertices.OutputIf the target values on counters cannot be achieved, print -1. Otherwise, print t — the number of operations, followed by t lines, describing the sequence of operations. Each line starts with integer v (0 \le v < p) — the counter increment for this operation. Then, in the same line, followed by n - 1 integers e_1, e_2, ... e_{n - 1} (1 \le e_i \le m) — the edges of the spanning tree.The number of operations t should not exceed 2m. You don't need to minimize t. Any correct answer within the 2m bound is accepted. You are allowed to repeat spanning trees.ExamplesInput 3 3 101 1 2 30 2 3 40 3 1 50 Output 3 10 1 2 20 1 3 30 2 3Input 2 2 37 1 2 8 1 2 15 Output 2 8 1 15 2Input 5 4 5 1 3 1 2 3 2 2 5 3 4 1 4 Output -1
3 3 101 1 2 30 2 3 40 3 1 50
3 10 1 2 20 1 3 30 2 3
3 seconds
1024 megabytes
['constructive algorithms', 'math', '*2900']
I. Interactive Factorial Guessingtime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputOh no, this wicked jury hides something from you again, and you need to guess it interactively. This time, you need to find an integer n. To do that, you can make at most 10 queries of the form "What is the k-th decimal digit of the product of all integers from 1 to n (also known as factorial and denoted as n!)?". InteractionIn the first line, there is an integer t (1 \le t \le 100) — the number of tests you shall process. For each test, the integer n is chosen in advance. The length of n! is at most 20\,000, so 1 \le n \le 5982.You can make at most 10 queries of the form "? k" (0 \le k < 20\,000). In response to the query, you will get a single digit — the k-th decimal digit of n! (the response is between 0 and 9 inclusive). Digits are numbered from 0, starting with the least significant digit. If n! is too short, and there is no k-th digit, then 0 is returned. After your program finds the value of n it shall answer with "! n". If the answer is correct, then you will receive "YES" and should proceed to the next test or terminate if it was the last one. If the answer is not correct, or you are trying to guess, and there are several possible answers consistent with the information you have received, you will get "NO". In that case, your submission will receive "Wrong answer" verdict and your code shall terminate immediately. ExampleInput 2 1 YES 0 2 YES Output ? 0 ! 1 ? 0 ? 19997 ! 5982
2 1 YES 0 2 YES
? 0 ! 1 ? 0 ? 19997 ! 5982
3 seconds
1024 megabytes
['brute force', 'games', 'implementation', 'interactive', '*2500']
H. Hot and Coldtime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After emigrating to another country, little Hanna came across the fact that playing "Hot and cold" became more difficult: she does not understand the hint phrases! You are to write a helping program for her.The playground where the game happens is a rectangle, and the treasure is hidden in some point with integer coordinates between 0 and 10^6, inclusive. Hanna visits several points with valid coordinates. If the visited point contains the hidden treasure, she receives the phrase "Found!" in the local language. Fortunately, the intonations allow her to recognize this phrase — in this problem it will be denoted by an exclamation mark.Otherwise, for each visited point except for the first one, Hanna receives a phrase in the local language stating whether she is now "Closer", "Further", or "At the same distance" from the treasure, compared to the previous point. The distances are measured in Euclidean metric. After the first visited point, in case of no treasure there, Hanna receives the phrase "Not found" in the local language.Your program must help Hanna find the treasure by visiting at most 64 points.InteractionYour program should print each visited point in a line with two coordinates between 0 and 10^6, inclusive, and flush the output after each one.For each visited point, the testing system writes one of the phrases: "Found!", "Closer", "Further", "At the same distance", or "Not found" in some language, consistent throughout the game. The first phrase ends with an exclamation mark, all other phrases do not contain exclamation marks. All phrases contain only Latin letters, spaces and exclamation marks, have lengths between 2 and 30, inclusive, don't start or end with a space, and are pairwise distinct. The phrases are not necessarily coming from any real human language. After receiving a phrase with an exclamation mark, your program must halt without printing anything else. Visiting points more than once is allowed, and each such visit counts towards the limit of 64 queries.ExamplesInput Tabilmadi Daha yakin Daha yakin Sama distanco Dalej Znaydeno!Output 500 200 560 230 566 240 566 238 30 239 566 239Input You are lucky today! Output 777777 777777
Tabilmadi Daha yakin Daha yakin Sama distanco Dalej Znaydeno!
500 200 560 230 566 240 566 238 30 239 566 239
3 seconds
1024 megabytes
['binary search', 'interactive', '*2600']
G. Game of Questionstime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputGenie is taking part in an intellectual game. The game consists of n questions, and there are m participants numbered from 1 to m. Genie is the participant number 1.For each question i and participant j, it is known whether the participant will answer the question correctly or not.The goal of the game is to be the last participant staying in the game.The game is conducted as follows. First, all n questions get shuffled uniformly at random (all n! permutations are equally likely). Then, the questions are asked one by one. Each participant answers the question. If all participants still in the game answer the question correctly, or if all of them answer the question incorrectly, nothing happens. Otherwise, those participants who answer the question incorrectly lose and leave the game.After all n questions are asked, all participants who are still in the game are declared to be the winners.What is the probability that Genie will win the game?InputThe first line contains two integers n and m — the number of questions and the number of participants (1 \le n \le 2 \cdot 10^5; 2 \le m \le 17).The i-th of the next n lines contains m characters s_{i, 1}, s_{i, 2}, \ldots, s_{i, m}. Character s_{i, j} is '1' if participant j answers question i correctly or '0' otherwise.OutputPrint the probability that Genie will win the game. Your answer will be considered correct if its absolute or relative error does not exceed 10^{-9}.ExamplesInput 1 5 11010 Output 1.0000000000000000 Input 3 3 011 101 110 Output 0.3333333333333333 Input 6 4 1011 0110 1111 0110 0000 1101 Output 0.1666666666666667 NoteIn the first example, there is a single question and Genie will answer it correctly, thus winning the game (along with participants 2 and 4).In the second example, one participant will leave after the first asked question, and another participant will leave after the second asked question. Each participant will win with probability \frac{1}{3}.
1 5 11010
1.0000000000000000
5 seconds
1024 megabytes
['bitmasks', 'combinatorics', 'dp', 'fft', 'math', 'probabilities', '*2800']
F. Footballtime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputScientists are researching an impact of football match results on the mood of football fans. They have a hypothesis that there is a correlation between the number of draws and fans' desire to watch football matches in the future.In football, two teams play a match. The teams score goals throughout a match. A score "x:y" means that the team we observe scored x goals and conceded y goals. If x = y, then the match ends in a draw. If x > y, then the observed team wins, and if x < y, then it loses.To find out if there is a correlation, the scientists gathered information about the results of teams in lower leagues. The information they found is the number of matches played by the team (n), the number of goals scored in these matches (a), and the number of goals conceded in these matches (b). You are given this information for a single team. You are asked to calculate the minimum number of draws that could have happened during the team's matches and provide a list of match scores with the minimum number of draws.InputThe first line contains an integer n — the number of matches played by the team (1 \le n \le 100). The second line contains an integer a — the total number of goals scored by the team in all n matches (0 \le a \le 1000). The third line contains an integer b — the total number of goals conceded by the team in all n matches (0 \le b \le 1000).OutputIn the first line, print a single integer d — the minimum number of draws.In the following n lines, print a list of match scores, each line in the format "x:y", where x is the number of goals scored in the match, and y – the number of goals conceded, so that exactly d of these matches have ended in a draw. In case multiple such lists of match scores exist, print any of them.ExamplesInput 3 2 4 Output 0 1:0 1:2 0:2 Input 1 2 2 Output 1 2:2 Input 4 0 7 Output 0 0:1 0:2 0:1 0:3 Input 6 3 1 Output 2 0:0 1:0 0:0 0:1 1:0 1:0
3 2 4
0 1:0 1:2 0:2
3 seconds
1024 megabytes
['constructive algorithms', '*800']
E. Easy Assemblytime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputEmma loves playing with blocks. She has several cubic blocks of the same size that are numbered with distinct integers written on them. She assembles towers from those blocks by stacking them vertically. A configuration of her game is a set of towers that she has assembled from the blocks. Emma can perform two kinds of operations on a configuration of towers: Split any tower with more than one block in it by taking any number of blocks from the top of the tower and moving them to a new tower keeping their order, so that the top block of the old tower becomes the top block of the new tower. As a result of this operation, the number of towers increases by one. Combine any two towers by moving blocks from one tower on top of the other tower in the same order. As a result of this operation, the number of towers decreases by one.Emma wants to stack all the blocks into a single tower so that all blocks come in order sorted by the numbers — from the block with the minimal number at the top to the block with the maximal number at the bottom. Emma wants to do as little of splitting and combining operations as possible. Your task is to find the minimal number of operations she has to make and output how many splits and combines are needed. InputThe first line of the input file contains an integer n (1 \le n \le 10\,000) — the number of towers in the initial configuration. Next n lines describe towers. Each tower i is described by a line that starts with the number k_i (k_i \ge 1; \sum_1^n{k_i} \le 10\,000) — the number of blocks in the tower, followed by k_i numbers b_{i,j} (1 \le b_{i,j} \le 10^9) — numbers written on the blocks in the i-th tower, listed from top to bottom. All block numbers listed in the input are different. OutputOutput a line with two integers s and c — the number of split and combine operations Emma should make to get a single tower with blocks sorted by their numbers, so that the total number of operations is minimized.ExampleInput 2 3 3 5 8 2 9 2 Output 1 2 NoteThe example needs the following operations (1 split and 2 combines).InitialSplit lastCombined 2nd onto 1stCombined 1st onto 2nd
2 3 3 5 8 2 9 2
1 2
3 seconds
1024 megabytes
['greedy', 'sortings', '*1400']
D. Dominoestime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDora likes to play with dominoes. She takes n \times m table, marks some cells as occupied, and then tries to fill all unoccupied cells with 2 \times 1 dominoes. Her little brother Dani loves to play pranks on his older sister. So when she is away, he marks two more unoccupied cells as occupied. He wants to do it in such a way that it will be impossible to fill all unoccupied cells with dominoes.Help Dani to count the number of ways he can select these two cells. Since Dani can only count to one million, if this number of ways is x, output \min(x, 10^6).InputThe first line contains integers n and m (1\le n, m\le 1000). Next n lines contain m characters each — the initial state of the table. Character "#" corresponds to an occupied cell, and character "." corresponds to an unoccupied cell. It is guaranteed that there are at least two unoccupied cells, and that it is possible to fill all unoccupied cells with dominoes.OutputLet x be the number of ways Dani can mark two cells in such a way that it will be impossible to fill all unoccupied cells with dominoes. Print one integer \min(x, 10^6).ExamplesInput 3 6 ...#.. ...... #...## Output 52 Input 2 2 .. .. Output 2 Input 2 2 #. #. Output 0
3 6 ...#.. ...... #...##
52
3 seconds
1024 megabytes
['combinatorics', 'flows', 'graph matchings', 'greedy', '*2600']
B. BinCointime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThere are n employees in the BinCoin company numbered from 1 to n. The subordination structure in this company is a rooted tree. In other words: There is one CEO in the company — the main boss. Each other employee has exactly one direct superior. There are no cycles in the subordination structure. Moreover, due to the inexplicable love of the CEO of BinCoin for all the binary stuff, the subordination structure in the company is a binary rooted tree. That means each employee is directly superior to exactly zero or two other employees.In the CEO's opinion, working in this company is almost as dangerous as in mines. So, employees should sign the waiver of claims sometimes. This process happens in the following way. Initially, CEO takes the journal, then recursively the following procedure is performed: If an employee that holds the journal does not have any subordinates, they sign the waiver in the journal and give it back to their superior. The procedure stops if that was the CEO, who has no superior. Otherwise they choose one of two of their direct subordinates uniformly at random and give the journal to one of them; when they get the journal back, they sign it; and then they give it to another direct subordinate; when they get it back again, they give it back to their superior. The procedure stops if that was the CEO, who has no superior. All random choices are independent.One day, the CEO realized that they could not remember the subordination tree. Fortunately, they have the journal with k records. Each record is a sequence of employees in the order they've signed in a journal.Help CEO restore the subordination tree.InputThe first line contains two integers n and k — the number of employees and the number of records in the journal (1 \le n \le 999; 50 \le k \le 100).Each of the next k lines contains a permutation of integers from 1 to n — the order of employees in the corresponding record.It is guaranteed that the input was obtained as described in the statement with a real random choice.OutputOutput n integers p_i. If i is a CEO, then p_i should be -1. Otherwise, p_i should be the index of the direct superior of i-th employee.Your output should correspond to a binary rooted tree. If there are several trees satisfying the input, you can output any one of them.ExamplesInput 3 50 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 1 2 3 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 1 2 3 3 2 1 1 2 3 1 2 3 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 3 2 1 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 3 2 1 3 2 1 1 2 3 1 2 3 3 2 1 3 2 1 Output 2 -1 2 Input 5 60 2 4 3 5 1 1 5 2 4 3 1 5 2 4 3 1 5 2 4 3 1 5 3 4 2 1 5 3 4 2 1 5 3 4 2 1 5 3 4 2 1 5 3 4 2 3 4 2 5 1 2 4 3 5 1 1 5 2 4 3 3 4 2 5 1 2 4 3 5 1 2 4 3 5 1 1 5 2 4 3 3 4 2 5 1 3 4 2 5 1 1 5 2 4 3 2 4 3 5 1 1 5 2 4 3 1 5 3 4 2 3 4 2 5 1 1 5 3 4 2 1 5 2 4 3 1 5 3 4 2 1 5 2 4 3 2 4 3 5 1 2 4 3 5 1 2 4 3 5 1 2 4 3 5 1 2 4 3 5 1 1 5 2 4 3 1 5 3 4 2 1 5 2 4 3 3 4 2 5 1 1 5 3 4 2 3 4 2 5 1 3 4 2 5 1 1 5 2 4 3 2 4 3 5 1 1 5 2 4 3 1 5 3 4 2 2 4 3 5 1 2 4 3 5 1 1 5 2 4 3 1 5 2 4 3 1 5 2 4 3 1 5 2 4 3 1 5 2 4 3 3 4 2 5 1 3 4 2 5 1 3 4 2 5 1 1 5 2 4 3 1 5 3 4 2 1 5 3 4 2 2 4 3 5 1 3 4 2 5 1 1 5 2 4 3 3 4 2 5 1Output 5 4 4 5 -1 NoteIn order to fit on the page, several consecutive lines in the examples were joined into one. The real inputs follow the input description.
3 50 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 1 2 3 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 1 2 3 1 2 3 3 2 1 1 2 3 1 2 3 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 3 2 1 1 2 3 3 2 1 1 2 3 3 2 1 3 2 1 1 2 3 1 2 3 3 2 1 1 2 3 3 2 1 3 2 1 3 2 1 1 2 3 1 2 3 3 2 1 3 2 1
2 -1 2
3 seconds
1024 megabytes
['binary search', 'divide and conquer', 'hashing', 'implementation', 'probabilities', 'trees', '*2200']
A. Amazing Tricktime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputAlice is a magician and she creates a new trick. She has n cards with different numbers from 1 to n written on them. First, she asks an audience member to shuffle the deck and put cards in a row. Let's say the i-th card from the left has the number a_i on it. Then Alice picks two permutations p and q. There is a restriction on p and q — permutations can't have fixed points. Which means \forall i: p_i \ne i\ and\ q_i \ne i.After permutations are chosen, Alice shuffles the cards according to them. Now the i-th card from the left is the card a[p[q[i]]. The trick is considered successful if i-th card from the left has the number i on it after the shuffles.Help Alice pick the permutations p and q or say it is not possible for the specific starting permutation a. InputThe first line of the input contains the number of tests t (1 \leq t \leq 10^5). Each test is described in two lines. The first line contains one integer n — the number of cards (1 \leq n \leq 10^5). The second line contains n integers a_i — the initial permutation of the cards (1 \leq a_i \leq n; \forall i \neq j: a_i \neq a_j). It is guaranteed that the sum of n over all tests does not exceed 10^5.OutputPrint the answer for each test case in the same order the cases appear in the input.For each test case, print "Impossible" in a single line, if no solution exists.Otherwise, print "Possible" in the first line, and in the following two lines print permutations p and q.ExampleInput 422 131 2 342 1 4 355 1 4 2 3Output Impossible Possible 3 1 2 2 3 1 Possible 3 4 2 1 3 4 2 1 Possible 4 1 2 5 3 3 1 4 5 2
422 131 2 342 1 4 355 1 4 2 3
Impossible Possible 3 1 2 2 3 1 Possible 3 4 2 1 3 4 2 1 Possible 4 1 2 5 3 3 1 4 5 2
3 seconds
1024 megabytes
['constructive algorithms', 'graph matchings', 'math', 'probabilities', '*1900']
G. Gaining Ratingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing chess on one popular website. He has n opponents he can play with. The i-th opponent has rating equal to a_i. Monocarp's initial rating is x. Monocarp wants to raise his rating to the value y (y > x).When Monocarp is playing against one of the opponents, he will win if his current rating is bigger or equal to the opponent's rating. If Monocarp wins, his rating is increased by 1, otherwise it is decreased by 1. The rating of his opponent does not change.Monocarp wants to gain rating y playing as few games as possible. But he can't just grind it, playing against weak opponents. The website has a rule that you should play against all opponents as evenly as possible. Speaking formally, if Monocarp wants to play against an opponent i, there should be no other opponent j such that Monocarp has played more games against i than against j.Calculate the minimum possible number of games Monocarp needs to gain rating y or say it's impossible. Note that ratings of Monocarp's opponents don't change, while Monocarp's rating does change.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains three integers n, x and y (1 \le n \le 2 \cdot 10^5; 1 \le x < y \le 10^{12}) — the number of Monocarp's opponents, his initial and desired ratings.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^{12}) — ratings of Monocarp's opponents.Additional constraint on the input: the total sum of n over all t test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the minimum number of games Monocarp needs to play to gain rating y, or -1 if it's impossible.ExampleInput 37 2 103 1 9 2 5 20 87 1 103 1 9 2 5 20 85 10 12100 1 200 11 300Output 20 -1 2 NoteIn the first test case, Monocarp can use the following strategy: Monocarp plays against the 2-nd opponent to increase rating (2 \to 3); Monocarp plays against the 1-st opponent to increase rating (3 \to 4); Monocarp plays against the 4-th opponent to increase rating (4 \to 5); Monocarp plays against the 5-th opponent to increase rating (5 \to 6); Now Monocarp have to play with remaining three opponents. So, he will lose 3 times and get rating 3 (6 \to 5 \to 4 \to 3); After that, Monocarp will repeat steps 1-5 again. After 14 games, he has played twice with each opponent and get final rating 4. Monocarp plays against the 1-st opponent to increase rating (4 \to 5); Monocarp plays against the 2-nd opponent to increase rating (5 \to 6); Monocarp plays against the 4-th opponent to increase rating (6 \to 7); Monocarp plays against the 5-th opponent to increase rating (7 \to 8); Monocarp plays against the 7-th opponent to increase rating (8 \to 9); Monocarp plays against the 3-rd opponent to increase rating (9 \to 10); In total, Monocarp, played twice against the 6-th opponent and three times against other opponents and got rating 10 in 14 + 6 = 20 games.In the second test case, it can be proven that whichever games Monocarp plays, he can't get his rating higher than 4.
37 2 103 1 9 2 5 20 87 1 103 1 9 2 5 20 85 10 12100 1 200 11 300
20 -1 2
2 seconds
256 megabytes
['binary search', 'greedy', 'implementation', 'math', 'sortings', 'two pointers', '*2200']
F. Copy of a Copy of a Copytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt all started with a black-and-white picture, that can be represented as an n \times m matrix such that all its elements are either 0 or 1. The rows are numbered from 1 to n, the columns are numbered from 1 to m.Several operations were performed on the picture (possibly, zero), each of one of the two kinds: choose a cell such that it's not on the border (neither row 1 or n, nor column 1 or m) and it's surrounded by four cells of the opposite color (four zeros if it's a one and vice versa) and paint it the opposite color itself; make a copy of the current picture. Note that the order of operations could be arbitrary, they were not necessarily alternating.You are presented with the outcome: all k copies that were made. Additionally, you are given the initial picture. However, all k+1 pictures are shuffled.Restore the sequence of the operations. If there are multiple answers, print any of them. The tests are constructed from the real sequence of operations, i. e. at least one answer always exists.InputThe first line contains three integers n, m and k (3 \le n, m \le 30; 0 \le k \le 100) — the number of rows and columns of the pictures and the number of copies made, respectively.Then k+1 pictures follow — k copies and the initial picture. Their order is arbitrary.Each picture consists of n lines, each consisting of m characters, each character is either 0 or 1. There is an empty line before each picture.OutputIn the first line, print a single integer — the index of the initial picture. The pictures are numbered from 1 to k+1 in the order they appear in the input.In the second line, print a single integer q — the number of operations.Each of the next q lines should contain an operation. The operations should be listed in order they were applied. Each operation is one of two types: 1 x y — recolor a cell (x, y) (the y-th cell in the x-th row, it should not be on the border and it should be surrounded by four cells of opposite color to itself); 2 i — make a copy of the current picture and assign it index i (picture with index the i should be equal to the current picture). Each index from 1 to k+1 should appear in the output exactly once — one of them is the index of the initial picture, the remaining k are arguments of the operations of the second kind.If there are multiple answers, print any of them. The tests are constructed from the real sequence of operations, i. e. at least one answer always exists.ExamplesInput 3 3 1 010 111 010 010 101 010 Output 2 2 1 2 2 2 1 Input 4 5 3 00000 01000 11100 01000 00000 01000 10100 01000 00000 01010 10100 01000 00000 01000 10100 01000 Output 3 5 1 2 4 2 2 2 4 1 3 2 2 1 Input 5 3 0 110 010 001 011 001 Output 1 0
3 3 1 010 111 010 010 101 010
2 2 1 2 2 2 1
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'implementation', 'sortings', '*2000']
E. Permutation Gametime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo players are playing a game. They have a permutation of integers 1, 2, ..., n (a permutation is an array where each element from 1 to n occurs exactly once). The permutation is not sorted in either ascending or descending order (i. e. the permutation does not have the form [1, 2, \dots, n] or [n, n-1, \dots, 1]).Initially, all elements of the permutation are colored red. The players take turns. On their turn, the player can do one of three actions: rearrange the elements of the permutation in such a way that all red elements keep their positions (note that blue elements can be swapped with each other, but it's not obligatory); change the color of one red element to blue; skip the turn. The first player wins if the permutation is sorted in ascending order (i. e. it becomes [1, 2, \dots, n]). The second player wins if the permutation is sorted in descending order (i. e. it becomes [n, n-1, \dots, 1]). If the game lasts for 100^{500} turns and nobody wins, it ends in a draw.Your task is to determine the result of the game if both players play optimally.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.The first line of each test case contains a single integer n (3 \le n \le 5 \cdot 10^5) — the size of the permutation.The second line contains n integers p_1, p_2, \dots, p_n — the permutation itself. The permutation p is not sorted in either ascending or descending order.The sum of n over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, print First if the first player wins, Second if the second player wins, and Tie if the result is a draw.ExampleInput 441 2 4 332 3 153 4 5 2 161 5 6 3 2 4Output First Tie Second Tie NoteLet's show how the first player wins in the first example.They should color the elements 3 and 4 blue during their first two turns, and then they can reorder the blue elements in such a way that the permutation becomes [1, 2, 3, 4]. The second player can neither interfere with this strategy nor win faster.
441 2 4 332 3 153 4 5 2 161 5 6 3 2 4
First Tie Second Tie
4 seconds
256 megabytes
['games', '*1700']
D. Absolute Sortingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers. The array is sorted if a_1 \le a_2 \le \dots \le a_n.You want to make the array a sorted by applying the following operation exactly once: choose an integer x, then for every i \in [1, n], replace a_i by |a_i - x|. Find any value of x that will make the array sorted, or report that there is no such value.InputThe first line contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (2 \le n \le 2 \cdot 10^5). The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^8).Additional constraint on the input: the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print any integer x (0 \le x \le 10^9) that makes the array sorted. It can be shown that if such an integer x exists, there is at least one such integer between 0 and 10^9.If there is no such integer, then print -1. If there are multiple suitable values of x, print any of them.ExampleInput 855 3 3 3 545 3 4 581 2 3 4 5 6 7 8610 5 4 3 2 133 3 1342 43 422100000000 99999999629613295 52036613 75100585 78027446 81409090 73215Output 4 -1 0 42 2 -1 100000000 40741153 NoteIn the first test case, after using x = 4, the array becomes [1, 1, 1, 1, 1].In the third test case, after using x = 0, the array becomes [1, 2, 3, 4, 5, 6, 7, 8].In the fourth test case, after using x = 42, the array becomes [32, 37, 38, 39, 40, 41].
855 3 3 3 545 3 4 581 2 3 4 5 6 7 8610 5 4 3 2 133 3 1342 43 422100000000 99999999629613295 52036613 75100585 78027446 81409090 73215
4 -1 0 42 2 -1 100000000 40741153
2 seconds
512 megabytes
['constructive algorithms', 'math', '*1400']
C. Different Differencestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAn array a consisting of k integers is strictly increasing if a_1 < a_2 < \dots < a_k. For example, the arrays [1, 3, 5], [1, 2, 3, 4], [3, 5, 6] are strictly increasing; the arrays [2, 2], [3, 7, 5], [7, 4, 3], [1, 2, 2, 3] are not.For a strictly increasing array a of k elements, let's denote the characteristic as the number of different elements in the array [a_2 - a_1, a_3 - a_2, \dots, a_k - a_{k-1}]. For example, the characteristic of the array [1, 3, 4, 7, 8] is 3 since the array [2, 1, 3, 1] contains 3 different elements: 2, 1 and 3.You are given two integers k and n (k \le n). Construct an increasing array of k integers from 1 to n with maximum possible characteristic.InputThe first line contains one integer t (1 \le t \le 819) — the number of test cases.Each test case consists of one line containing two integers k and n (2 \le k \le n \le 40).OutputFor each test case, print k integers — the elements of the strictly increasing array a with the maximum possible characteristic. If there are multiple answers, print any of them.ExampleInput 75 94 123 33 44 44 68 11Output 1 3 4 7 8 2 4 7 12 1 2 3 1 3 4 1 2 3 4 2 4 5 6 1 2 3 5 6 7 8 11
75 94 123 33 44 44 68 11
1 3 4 7 8 2 4 7 12 1 2 3 1 3 4 1 2 3 4 2 4 5 6 1 2 3 5 6 7 8 11
2 seconds
512 megabytes
['constructive algorithms', 'greedy', 'math', '*1000']
B. Matrix Rotationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have a matrix 2 \times 2 filled with distinct integers. You want your matrix to become beautiful. The matrix is beautiful if the following two conditions are satisfied: in each row, the first element is smaller than the second element; in each column, the first element is smaller than the second element. You can perform the following operation on the matrix any number of times: rotate it clockwise by 90 degrees, so the top left element shifts to the top right cell, the top right element shifts to the bottom right cell, and so on: Determine if it is possible to make the matrix beautiful by applying zero or more operations.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of two lines. Each of those lines contains two integers — the elements of the corresponding row of the matrix. In each matrix, all four elements are distinct integers from 1 to 100.OutputFor each test case, print YES if the matrix can become beautiful, or NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).ExampleInput 61 35 78 103 48 104 36 19 27 54 21 24 3Output YES YES NO YES YES NO
61 35 78 103 48 104 36 19 27 54 21 24 3
YES YES NO YES YES NO
2 seconds
512 megabytes
['brute force', 'implementation', '*800']
A. A+B?time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an expression of the form a{+}b, where a and b are integers from 0 to 9. You have to evaluate it and print the result.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.Each test case consists of one line containing an expression of the form a{+}b (0 \le a, b \le 9, both a and b are integers). The integers are not separated from the + sign.OutputFor each test case, print one integer — the result of the expression.ExampleInput 44+20+03+78+9Output 6 0 10 17
44+20+03+78+9
6 0 10 17
2 seconds
512 megabytes
['implementation', '*800']
F. Hossam and Range Minimum Querytime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHossam gives you a sequence of integers a_1, \, a_2, \, \dots, \, a_n of length n. Moreover, he will give you q queries of type (l, \, r). For each query, consider the elements a_l, \, a_{l + 1}, \, \dots, \, a_r. Hossam wants to know the smallest number in this sequence, such that it occurs in this sequence an odd number of times.You need to compute the answer for each query before process the next query.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5), the length of the sequence.The second line contains n integers a_1, \, a_2, \, \dots, \, a_n (1 \le a_i \le 10^9).The third line contains one integer q (1 \le q \le 2 \cdot 10^5), the number of queries.Each of the next q lines contains two integers a and b (0 \le a, \, b \le 2 \cdot 10^9), the numbers used to encode the queries. Let \mathrm{ans}_i be the answer on the i-th query, and \mathrm{ans}_0 be zero. Then l_i = a_i \oplus \mathrm{ans}_{i - 1}, r_i = b_i \oplus \mathrm{ans}_{i - 1}, where l_i, \, r_i are parameters of the i-th query and \oplus means the bitwise exclusive or operation. It is guaranteed that 1 \le l \le r \le n.OutputFor each query, print the smallest number that occurs an odd number of times on the given segment of the sequence.If there is no such number, print 0.ExamplesInput 5 1 2 1 2 2 6 1 2 0 2 0 6 0 5 2 2 3 7 Output 1 2 1 0 2 2 Input 10 51 43 69 48 23 52 48 76 19 55 10 1 1 57 57 54 62 20 27 56 56 79 69 16 21 18 30 25 25 62 61 Output 51 55 19 48 76 19 23 19 55 19 NoteIn the example,l_1 = 1, \, r_1 = 2, l_2 = 1, \, r_2 = 3, l_3 = 2, \, r_3 = 4, l_4 = 1, \, r_4 = 4, l_5 = 2, \, r_5 = 2, l_6 = 1, \, r_6 = 5.
5 1 2 1 2 2 6 1 2 0 2 0 6 0 5 2 2 3 7
1 2 1 0 2 2
1.5 seconds
256 megabytes
['binary search', 'bitmasks', 'data structures', 'hashing', 'probabilities', 'strings', 'trees', '*2500']
E. Hossam and a Lettertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHossam bought a new piece of ground with length n and width m, he divided it into an n \cdot m grid, each cell being of size 1\times1.Since Hossam's name starts with the letter 'H', he decided to draw the capital letter 'H' by building walls of size 1\times1 on some squares of the ground. Each square 1\times1 on the ground is assigned a quality degree: perfect, medium, or bad.The process of building walls to form up letter 'H' has the following constraints: The letter must consist of one horizontal and two vertical lines. The vertical lines must not be in the same or neighboring columns. The vertical lines must start in the same row and end in the same row (and thus have the same length). The horizontal line should connect the vertical lines, but must not cross them. The horizontal line can be in any row between the vertical lines (not only in the middle), except the top and the bottom one. (With the horizontal line in the top row the letter looks like 'n', and in the bottom row like 'U'.) It is forbidden to build walls in cells of bad quality. You can use at most one square of medium quality. You can use any number of squares of perfect quality. Find the maximum number of walls that can be used to draw the letter 'H'.Check the note for more clarification.InputThe first line of the input contains two integer numbers n, m (1 \le n, m \le 400).The next n lines of the input contain m characters each, describing the grid. The character '.' stands for a perfect square, the character 'm' stands for a medium square, and the character '#' stands for a bad square.OutputPrint a single integer — the maximum number of walls that form a capital letter 'H'.If it is not possible to draw any letter 'H', print 0.ExamplesInput 2 3 #m. .#. Output 0 Input 7 8 ...#.m.. ..m...m. .#..#.m# ...m..m. m....... ..#.m.mm ......m. Output 16 NoteIn the first test case, we can't build the letter 'H'.For the second test case, the figure below represents the grid and some of the valid letters 'H'. Perfect, medium, and bad squares are represented with white, yellow, and black colors respectively.
2 3 #m. .#.
0
2 seconds
256 megabytes
['brute force', 'dp', 'implementation', 'two pointers', '*2500']