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
|
---|---|---|---|---|---|
E1. Chiori and Doll Picking (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between easy and hard versions is the constraint of m. You can make hacks only if both versions are solved.Chiori loves dolls and now she is going to decorate her bedroom! As a doll collector, Chiori has got n dolls. The i-th doll has a non-negative integer value a_i (a_i < 2^m, m is given). Chiori wants to pick some (maybe zero) dolls for the decoration, so there are 2^n different picking ways.Let x be the bitwise-xor-sum of values of dolls Chiori picks (in case Chiori picks no dolls x = 0). The value of this picking way is equal to the number of 1-bits in the binary representation of x. More formally, it is also equal to the number of indices 0 \leq i < m, such that \left\lfloor \frac{x}{2^i} \right\rfloor is odd.Tell her the number of picking ways with value i for each integer i from 0 to m. Due to the answers can be very huge, print them by modulo 998\,244\,353.InputThe first line contains two integers n and m (1 \le n \le 2 \cdot 10^5, 0 \le m \le 35) — the number of dolls and the maximum value of the picking way.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i < 2^m) — the values of dolls.OutputPrint m+1 integers p_0, p_1, \ldots, p_m — p_i is equal to the number of picking ways with value i by modulo 998\,244\,353.ExamplesInput
4 4
3 5 8 14
Output
2 2 6 6 0 Input
6 7
11 45 14 9 19 81
Output
1 2 11 20 15 10 5 0 | 4 4
3 5 8 14
| 2 2 6 6 0 | 3 seconds | 512 megabytes | ['bitmasks', 'brute force', 'combinatorics', 'math', '*2700'] |
D. Yui and Mahjong Settime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Yui is a girl who enjoys playing Mahjong. She has a mysterious set which consists of tiles (this set can be empty). Each tile has an integer value between 1 and n, and at most n tiles in the set have the same value. So the set can contain at most n^2 tiles.You want to figure out which values are on the tiles. But Yui is shy, she prefers to play a guessing game with you.Let's call a set consisting of three tiles triplet if their values are the same. For example, \{2,\,2,\,2\} is a triplet, but \{2,\,3,\,3\} is not.Let's call a set consisting of three tiles straight if their values are consecutive integers. For example, \{2,\,3,\,4\} is a straight, but \{1,\,3,\,5\} is not.At first, Yui gives you the number of triplet subsets and straight subsets of the initial set respectively. After that, you can insert a tile with an integer value between 1 and n into the set at most n times. Every time you insert a tile, you will get the number of triplet subsets and straight subsets of the current set as well.Note that two tiles with the same value are treated different. In other words, in the set \{1,\,1,\,2,\,2,\,3\} you can find 4 subsets \{1,\,2,\,3\}.Try to guess the number of tiles in the initial set with value i for all integers i from 1 to n.InputThe first line contains a single integer n (4 \le n \le 100).The second line contains two integers which represent the number of triplet subsets and straight subsets of the initial set respectively.OutputWhen you are ready to answer, print a single line of form "! a_1 a_2 \ldots a_n" (0 \le a_i \le n), where a_i is equal to the number of tiles in the initial set with value i.InteractionTo insert a tile, print a single line of form "+ x" (1 \le x \le n), where x is the value of the tile you insert. Then you should read two integers which represent the number of triplet subsets and straight subsets of the current set respectively.After printing a line, do not forget to 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. You will get Wrong answer if you insert more than n tiles.HacksTo make a hack you should provide a test in such format:The first line contains a single integer n (4 \le n \le 100).The second line contains n integers a_1,a_2,\ldots,a_n (0 \le a_i \le n) — a_i is equal to the number of tiles with value i in the set.ExampleInput
5
1 6
2 9
5 12
5 24
6 24
Output
+ 1
+ 1
+ 2
+ 5
! 2 1 3 0 2
NoteIn the first test, the initial set of tiles is \{1, 1, 2, 3, 3, 3, 5, 5\}. It has only one triplet subset \{3, 3, 3\} and six straight subsets, all equal to \{1, 2, 3\}. After inserting a tile with value 1 the set of tiles will be \{1, 1, 1, 2, 3, 3, 3, 5, 5\} and will have two triplet subsets \{1, 1, 1\}, \{3, 3, 3\} and nine straight subsets, all equal to \{1, 2, 3\}. | 5
1 6
2 9
5 12
5 24
6 24
| + 1 + 1 + 2 + 5 ! 2 1 3 0 2 | 1 second | 256 megabytes | ['constructive algorithms', 'interactive', '*3200'] |
C. Kaavi and Magic Spelltime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. Kaavi has a string T of length m and all the strings with the prefix T are magic spells. Kaavi also has a string S of length n and an empty string A.During the divination, Kaavi needs to perform a sequence of operations. There are two different operations: Delete the first character of S and add it at the front of A. Delete the first character of S and add it at the back of A.Kaavi can perform no more than n operations. To finish the divination, she wants to know the number of different operation sequences to make A a magic spell (i.e. with the prefix T). As her assistant, can you help her? The answer might be huge, so Kaavi only needs to know the answer modulo 998\,244\,353.Two operation sequences are considered different if they are different in length or there exists an i that their i-th operation is different. A substring is a contiguous sequence of characters within a string. A prefix of a string S is a substring of S that occurs at the beginning of S.InputThe first line contains a string S of length n (1 \leq n \leq 3000).The second line contains a string T of length m (1 \leq m \leq n).Both strings contain only lowercase Latin letters.OutputThe output contains only one integer — the answer modulo 998\,244\,353.ExamplesInput
abab
ba
Output
12Input
defineintlonglong
signedmain
Output
0Input
rotator
rotator
Output
4Input
cacdcdbbbb
bdcaccdbbb
Output
24NoteThe first test:The red ones are the magic spells. In the first operation, Kaavi can either add the first character "a" at the front or the back of A, although the results are the same, they are considered as different operations. So the answer is 6\times2=12. | abab
ba
| 12 | 2 seconds | 512 megabytes | ['dp', 'strings', '*2200'] |
B. Xenia and Colorful Gemstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputXenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight.Now, she is going to pick three gems.Xenia loves colorful things, so she will pick exactly one gem of each color.Xenia loves balance, so she will try to pick gems with little difference in weight.Specifically, supposing the weights of the picked gems are x, y and z, Xenia wants to find the minimum value of (x-y)^2+(y-z)^2+(z-x)^2. As her dear friend, can you help her?InputThe first line contains a single integer t (1\le t \le 100) — the number of test cases. Then t test cases follow.The first line of each test case contains three integers n_r,n_g,n_b (1\le n_r,n_g,n_b\le 10^5) — the number of red gems, green gems and blue gems respectively.The second line of each test case contains n_r integers r_1,r_2,\ldots,r_{n_r} (1\le r_i \le 10^9) — r_i is the weight of the i-th red gem.The third line of each test case contains n_g integers g_1,g_2,\ldots,g_{n_g} (1\le g_i \le 10^9) — g_i is the weight of the i-th green gem.The fourth line of each test case contains n_b integers b_1,b_2,\ldots,b_{n_b} (1\le b_i \le 10^9) — b_i is the weight of the i-th blue gem.It is guaranteed that \sum n_r \le 10^5, \sum n_g \le 10^5, \sum n_b \le 10^5 (the sum for all test cases).OutputFor each test case, print a line contains one integer — the minimum value which Xenia wants to find. ExampleInput
5
2 2 3
7 8
6 3
3 1 4
1 1 1
1
1
1000000000
2 2 2
1 2
5 4
6 7
2 2 2
1 2
3 4
6 7
3 4 1
3 2 1
7 3 3 4
6
Output
14
1999999996000000002
24
24
14
NoteIn the first test case, Xenia has the following gems:If she picks the red gem with weight 7, the green gem with weight 6, and the blue gem with weight 4, she will achieve the most balanced selection with (x-y)^2+(y-z)^2+(z-x)^2=(7-6)^2+(6-4)^2+(4-7)^2=14. | 5
2 2 3
7 8
6 3
3 1 4
1 1 1
1
1
1000000000
2 2 2
1 2
5 4
6 7
2 2 2
1 2
3 4
6 7
3 4 1
3 2 1
7 3 3 4
6
| 14 1999999996000000002 24 24 14 | 3 seconds | 256 megabytes | ['binary search', 'greedy', 'math', 'sortings', 'two pointers', '*1700'] |
A. Linova and Kingdomtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWriting light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it. There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?InputThe first line contains two integers n and k (2\le n\le 2 \cdot 10^5, 1\le k< n) — the number of cities and industry cities respectively.Each of the next n-1 lines contains two integers u and v (1\le u,v\le n), denoting there is a road connecting city u and city v.It is guaranteed that from any city, you can reach any other city by the roads.OutputPrint the only line containing a single integer — the maximum possible sum of happinesses of all envoys.ExamplesInput
7 4
1 2
1 3
1 4
3 5
3 6
4 7
Output
7Input
4 1
1 2
1 3
2 4
Output
2Input
8 5
7 5
1 7
6 1
3 7
8 3
2 1
4 5
Output
9NoteIn the first example, Linova can choose cities 2, 5, 6, 7 to develop industry, then the happiness of the envoy from city 2 is 1, the happiness of envoys from cities 5, 6, 7 is 2. The sum of happinesses is 7, and it can be proved to be the maximum one.In the second example, choosing cities 3, 4 developing industry can reach a sum of 3, but remember that Linova plans to choose exactly k cities developing industry, then the maximum sum is 2. | 7 4
1 2
1 3
1 4
3 5
3 6
4 7
| 7 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'greedy', 'sortings', 'trees', '*1600'] |
F. Robots on a Gridtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a rectangular grid of size n \times m. Each cell of the grid is colored black ('0') or white ('1'). The color of the cell (i, j) is c_{i, j}. You are also given a map of directions: for each cell, there is a direction s_{i, j} which is one of the four characters 'U', 'R', 'D' and 'L'. If s_{i, j} is 'U' then there is a transition from the cell (i, j) to the cell (i - 1, j); if s_{i, j} is 'R' then there is a transition from the cell (i, j) to the cell (i, j + 1); if s_{i, j} is 'D' then there is a transition from the cell (i, j) to the cell (i + 1, j); if s_{i, j} is 'L' then there is a transition from the cell (i, j) to the cell (i, j - 1). It is guaranteed that the top row doesn't contain characters 'U', the bottom row doesn't contain characters 'D', the leftmost column doesn't contain characters 'L' and the rightmost column doesn't contain characters 'R'.You want to place some robots in this field (at most one robot in a cell). The following conditions should be satisfied. Firstly, each robot should move every time (i.e. it cannot skip the move). During one move each robot goes to the adjacent cell depending on the current direction. Secondly, you have to place robots in such a way that there is no move before which two different robots occupy the same cell (it also means that you cannot place two robots in the same cell). I.e. if the grid is "RL" (one row, two columns, colors does not matter there) then you can place two robots in cells (1, 1) and (1, 2), but if the grid is "RLL" then you cannot place robots in cells (1, 1) and (1, 3) because during the first second both robots will occupy the cell (1, 2). The robots make an infinite number of moves.Your task is to place the maximum number of robots to satisfy all the conditions described above and among all such ways, you have to choose one where the number of black cells occupied by robots before all movements is the maximum possible. Note that you can place robots only before all movements.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 5 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains two integers n and m (1 < nm \le 10^6) — the number of rows and the number of columns correspondingly.The next n lines contain m characters each, where the j-th character of the i-th line is c_{i, j} (c_{i, j} is either '0' if the cell (i, j) is black or '1' if the cell (i, j) is white).The next n lines also contain m characters each, where the j-th character of the i-th line is s_{i, j} (s_{i, j} is 'U', 'R', 'D' or 'L' and describes the direction of the cell (i, j)).It is guaranteed that the sum of the sizes of fields does not exceed 10^6 (\sum nm \le 10^6).OutputFor each test case, print two integers — the maximum number of robots you can place to satisfy all the conditions described in the problem statement and the maximum number of black cells occupied by robots before all movements if the number of robots placed is maximized. Note that you can place robots only before all movements.ExampleInput
3
1 2
01
RL
3 3
001
101
110
RLL
DLD
ULL
3 3
000
000
000
RRD
RLD
ULL
Output
2 1
4 3
2 2
| 3
1 2
01
RL
3 3
001
101
110
RLL
DLD
ULL
3 3
000
000
000
RRD
RLD
ULL
| 2 1 4 3 2 2 | 3 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'matrices', '*2200'] |
E2. Three Blocks Palindrome (hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.You are given a sequence a consisting of n positive integers.Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]. There x, y are integers greater than or equal to 0. For example, sequences [], [2], [1, 1], [1, 2, 1], [1, 2, 2, 1] and [1, 1, 2, 1, 1] are three block palindromes but [1, 2, 3, 2, 1], [1, 2, 1, 2, 1] and [1, 2] are not.Your task is to choose the maximum by length subsequence of a that is a three blocks palindrome.You have to answer t independent test cases.Recall that the sequence t is a a subsequence of the sequence s if t can be derived from s by removing zero or more elements without changing the order of the remaining elements. For example, if s=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of a. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 200), where a_i is the i-th element of a. Note that the maximum value of a_i can be up to 200.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the maximum possible length of some subsequence of a that is a three blocks palindrome.ExampleInput
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1
Output
7
2
4
1
1
3
| 6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1
| 7 2 4 1 1 3 | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'dp', 'two pointers', '*1800'] |
E1. Three Blocks Palindrome (easy version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is constraints.You are given a sequence a consisting of n positive integers.Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, \dots, a}_{x}, \underbrace{b, b, \dots, b}_{y}, \underbrace{a, a, \dots, a}_{x}]. There x, y are integers greater than or equal to 0. For example, sequences [], [2], [1, 1], [1, 2, 1], [1, 2, 2, 1] and [1, 1, 2, 1, 1] are three block palindromes but [1, 2, 3, 2, 1], [1, 2, 1, 2, 1] and [1, 2] are not.Your task is to choose the maximum by length subsequence of a that is a three blocks palindrome.You have to answer t independent test cases.Recall that the sequence t is a a subsequence of the sequence s if t can be derived from s by removing zero or more elements without changing the order of the remaining elements. For example, if s=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].InputThe first line of the input contains one integer t (1 \le t \le 2000) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2000) — the length of a. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 26), where a_i is the i-th element of a. Note that the maximum value of a_i can be up to 26.It is guaranteed that the sum of n over all test cases does not exceed 2000 (\sum n \le 2000).OutputFor each test case, print the answer — the maximum possible length of some subsequence of a that is a three blocks palindrome.ExampleInput
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1
Output
7
2
4
1
1
3
| 6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1
| 7 2 4 1 1 3 | 3 seconds | 256 megabytes | ['binary search', 'brute force', 'data structures', 'dp', 'two pointers', '*1700'] |
D. Anti-Sudokutime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it here.The picture showing the correct sudoku solution:Blocks are bordered with bold black color.Your task is to change at most 9 elements of this field (i.e. choose some 1 \le i, j \le 9 and change the number at the position (i, j) to any other number in range [1; 9]) to make it anti-sudoku. The anti-sudoku is the 9 \times 9 field, in which: Any number in this field is in range [1; 9]; each row contains at least two equal elements; each column contains at least two equal elements; each 3 \times 3 block (you can read what is the block in the link above) contains at least two equal elements. It is guaranteed that the answer exists.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.Each test case consists of 9 lines, each line consists of 9 characters from 1 to 9 without any whitespaces — the correct solution of the sudoku puzzle.OutputFor each test case, print the answer — the initial field with at most 9 changed elements so that the obtained field is anti-sudoku. If there are several solutions, you can print any. It is guaranteed that the answer exists.ExampleInput
1
154873296
386592714
729641835
863725149
975314628
412968357
631457982
598236471
247189563
Output
154873396
336592714
729645835
863725145
979314628
412958357
631457992
998236471
247789563
| 1
154873296
386592714
729641835
863725149
975314628
412968357
631457982
598236471
247189563
| 154873396 336592714 729645835 863725145 979314628 412958357 631457992 998236471 247789563 | 2 seconds | 256 megabytes | ['constructive algorithms', 'implementation', '*1300'] |
C. Two Teams Composingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).So, about the teams. Firstly, these two teams should have the same size. Two more constraints: The first team should consist of students with distinct skills (i.e. all skills in the first team are unique). The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team.Consider some examples (skills are given): [1, 2, 3], [4, 4] is not a good pair of teams because sizes should be the same; [1, 1, 2], [3, 3, 3] is not a good pair of teams because the first team should not contain students with the same skills; [1, 2, 3], [3, 4, 4] is not a good pair of teams because the second team should contain students with the same skills; [1, 2, 3], [3, 3, 3] is a good pair of teams; [5], [6] is a good pair of teams. Your task is to find the maximum possible size x for which it is possible to compose a valid pair of teams, where each team size is x (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of students. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n), where a_i is the skill of the i-th student. Different students can have the same skills.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the maximum possible size x for which it is possible to compose a valid pair of teams, where each team size is x.ExampleInput
4
7
4 2 4 1 4 3 4
5
2 1 5 4 3
1
1
4
1 1 1 3
Output
3
1
0
2
NoteIn the first test case of the example, it is possible to construct two teams of size 3: the first team is [1, 2, 4] and the second team is [4, 4, 4]. Note, that there are some other ways to construct two valid teams of size 3. | 4
7
4 2 4 1 4 3 4
5
2 1 5 4 3
1
1
4
1 1 1 3
| 3 1 0 2 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'implementation', 'sortings', '*1100'] |
B. Construct the Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists.You have to answer t independent test cases.Recall that the substring s[l \dots r] is the string s_l, s_{l+1}, \dots, s_{r} and its length is r - l + 1. In this problem you are only interested in substrings of length a.InputThe first line of the input contains one integer t (1 \le t \le 2000) — the number of test cases. Then t test cases follow.The only line of a test case contains three space-separated integers n, a and b (1 \le a \le n \le 2000, 1 \le b \le \min(26, a)), where n is the length of the required string, a is the length of a substring and b is the required number of distinct letters in each substring of length a.It is guaranteed that the sum of n over all test cases does not exceed 2000 (\sum n \le 2000).OutputFor each test case, print the answer — such a string s of length n consisting of lowercase Latin letters that each substring of length a has exactly b distinct letters. If there are multiple valid answers, print any of them. It is guaranteed that the answer exists.ExampleInput
4
7 5 3
6 1 1
6 6 1
5 2 2
Output
tleelte
qwerty
vvvvvv
abcde
NoteIn the first test case of the example, consider all the substrings of length 5: "tleel": it contains 3 distinct (unique) letters, "leelt": it contains 3 distinct (unique) letters, "eelte": it contains 3 distinct (unique) letters. | 4
7 5 3
6 1 1
6 6 1
5 2 2
| tleelte qwerty vvvvvv abcde | 2 seconds | 256 megabytes | ['constructive algorithms', '*900'] |
A. Candies and Two Sisterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: Alice will get a (a > 0) candies; Betty will get b (b > 0) candies; each sister will get some integer number of candies; Alice will get a greater amount of candies than Betty (i.e. a > b); all the candies will be given to one of two sisters (i.e. a+b=n). Your task is to calculate the number of ways to distribute exactly n candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent n as the sum of n=a+b, where a and b are positive integers and a>b.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The only line of a test case contains one integer n (1 \le n \le 2 \cdot 10^9) — the number of candies you have.OutputFor each test case, print the answer — the number of ways to distribute exactly n candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print 0.ExampleInput
6
7
1
2
3
2000000000
763243547
Output
3
0
0
1
999999999
381621773
NoteFor the test case of the example, the 3 possible ways to distribute candies are: a=6, b=1; a=5, b=2; a=4, b=3. | 6
7
1
2
3
2000000000
763243547
| 3 0 0 1 999999999 381621773 | 1 second | 256 megabytes | ['math', '*800'] |
G. Substring Searchtime limit per test1.25 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a permutation p consisting of exactly 26 integers from 1 to 26 (since it is a permutation, each integer from 1 to 26 occurs in p exactly once) and two strings s and t consisting of lowercase Latin letters.A substring t' of string t is an occurence of string s if the following conditions are met: |t'| = |s|; for each i \in [1, |s|], either s_i = t'_i, or p_{idx(s_i)} = idx(t'_i), where idx(c) is the index of character c in Latin alphabet (idx(\text{a}) = 1, idx(\text{b}) = 2, idx(\text{z}) = 26). For example, if p_1 = 2, p_2 = 3, p_3 = 1, s = \text{abc}, t = \text{abcaaba}, then three substrings of t are occurences of s (they are t' = \text{abc}, t' = \text{bca} and t' = \text{aba}).For each substring of t having length equal to |s|, check if it is an occurence of s.InputThe first line contains 26 integers p_1, p_2, ..., p_{26} (1 \le p_i \le 26, all these integers are pairwise distinct).The second line contains one string s, and the third line contains one string t (2 \le |s| \le |t| \le 2 \cdot 10^5) both consisting of lowercase Latin letters.OutputPrint a string of |t| - |s| + 1 characters, each character should be either 0 or 1. The i-th character should be 1 if and only if the substring of t starting with the i-th character and ending with the (i + |s| - 1)-th character (inclusive) is an occurence of s.ExampleInput
2 3 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
abc
abcaaba
Output
11001 | 2 3 1 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
abc
abcaaba
| 11001 | 1.25 seconds | 512 megabytes | ['bitmasks', 'brute force', 'fft', '*2900'] |
F. Strange Functiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's denote the following function f. This function takes an array a of length n and returns an array. Initially the result is an empty array. For each integer i from 1 to n we add element a_i to the end of the resulting array if it is greater than all previous elements (more formally, if a_i > \max\limits_{1 \le j < i}a_j). Some examples of the function f: if a = [3, 1, 2, 7, 7, 3, 6, 7, 8] then f(a) = [3, 7, 8]; if a = [1] then f(a) = [1]; if a = [4, 1, 1, 2, 3] then f(a) = [4]; if a = [1, 3, 1, 2, 6, 8, 7, 7, 4, 11, 10] then f(a) = [1, 3, 6, 8, 11]. You are given two arrays: array a_1, a_2, \dots , a_n and array b_1, b_2, \dots , b_m. You can delete some elements of array a (possibly zero). To delete the element a_i, you have to pay p_i coins (the value of p_i can be negative, then you get |p_i| coins, if you delete this element). Calculate the minimum number of coins (possibly negative) you have to spend for fulfilling equality f(a) = b.InputThe first line contains one integer n (1 \le n \le 5 \cdot 10^5) — the length of array a.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n) — the array a.The third line contains n integers p_1, p_2, \dots, p_n (|p_i| \le 10^9) — the array p.The fourth line contains one integer m (1 \le m \le n) — the length of array b.The fifth line contains m integers b_1, b_2, \dots, b_m (1 \le b_i \le n, b_{i-1} < b_i) — the array b.OutputIf the answer exists, in the first line print YES. In the second line, print the minimum number of coins you have to spend for fulfilling equality f(a) = b.Otherwise in only line print NO.ExamplesInput
11
4 1 3 3 7 8 7 9 10 7 11
3 5 0 -2 5 3 6 7 8 2 4
3
3 7 10
Output
YES
20
Input
6
2 1 5 3 6 5
3 -9 0 16 22 -14
4
2 3 5 6
Output
NO
| 11
4 1 3 3 7 8 7 9 10 7 11
3 5 0 -2 5 3 6 7 8 2 4
3
3 7 10
| YES 20 | 3 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', '*2500'] |
E. Divisor Pathstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer D. Let's build the following graph from it: each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included); two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime; the weight of an edge is the number of divisors of x that are not divisors of y. For example, here is the graph for D=12: Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12].There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because \frac{12}{3}=4 is not a prime.Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0.So the shortest path between two vertices v and u is the path that has the minimal possible length.Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges.You are given q queries of the following form: v u — calculate the number of the shortest paths between vertices v and u. The answer for each query might be large so print it modulo 998244353.InputThe first line contains a single integer D (1 \le D \le 10^{15}) — the number the graph is built from.The second line contains a single integer q (1 \le q \le 3 \cdot 10^5) — the number of queries.Each of the next q lines contains two integers v and u (1 \le v, u \le D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D).OutputPrint q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353.ExamplesInput
12
3
4 4
12 1
3 4
Output
1
3
1
Input
1
1
1 1
Output
1
Input
288807105787200
4
46 482955026400
12556830686400 897
414 12556830686400
4443186242880 325
Output
547558588
277147129
457421435
702277623
NoteIn the first example: The first query is only the empty path — length 0; The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5). The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3). | 12
3
4 4
12 1
3 4
| 1 3 1 | 3 seconds | 256 megabytes | ['combinatorics', 'graphs', 'greedy', 'math', 'number theory', '*2200'] |
D. Minimum Euler Cycletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a complete directed graph K_n with n vertices: each pair of vertices u \neq v in K_n have both directed edges (u, v) and (v, u); there are no self-loops.You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of n(n - 1) + 1 vertices v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1 — a visiting order, where each (v_i, v_{i + 1}) occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its [l, r] segment, in other words, v_l, v_{l + 1}, \dots, v_r.InputThe first line contains the single integer T (1 \le T \le 100) — the number of test cases.Next T lines contain test cases — one per line. The first and only line of each test case contains three integers n, l and r (2 \le n \le 10^5, 1 \le l \le r \le n(n - 1) + 1, r - l + 1 \le 10^5) — the number of vertices in K_n, and segment of the cycle to print.It's guaranteed that the total sum of n doesn't exceed 10^5 and the total sum of r - l + 1 doesn't exceed 10^5.OutputFor each test case print the segment v_l, v_{l + 1}, \dots, v_r of the lexicographically smallest cycle that visits every edge exactly once.ExampleInput
3
2 1 3
3 3 6
99995 9998900031 9998900031
Output
1 2 1
1 3 2 3
1
NoteIn the second test case, the lexicographically minimum cycle looks like: 1, 2, 1, 3, 2, 3, 1.In the third test case, it's quite obvious that the cycle should start and end in vertex 1. | 3
2 1 3
3 3 6
99995 9998900031 9998900031
| 1 2 1 1 3 2 3 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'greedy', 'implementation', '*1800'] |
C. Circle of Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing another computer game, and now you have to slay n monsters. These monsters are standing in a circle, numbered clockwise from 1 to n. Initially, the i-th monster has a_i health.You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by 1 (deals 1 damage to it). Furthermore, when the health of some monster i becomes 0 or less than 0, it dies and explodes, dealing b_i damage to the next monster (monster i + 1, if i < n, or monster 1, if i = n). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.You have to calculate the minimum number of bullets you have to fire to kill all n monsters in the circle.InputThe first line contains one integer T (1 \le T \le 150000) — the number of test cases.Then the test cases follow, each test case begins with a line containing one integer n (2 \le n \le 300000) — the number of monsters. Then n lines follow, each containing two integers a_i and b_i (1 \le a_i, b_i \le 10^{12}) — the parameters of the i-th monster in the circle.It is guaranteed that the total number of monsters in all test cases does not exceed 300000.OutputFor each test case, print one integer — the minimum number of bullets you have to fire to kill all of the monsters.ExampleInput
1
3
7 15
2 14
5 3
Output
6
| 1
3
7 15
2 14
5 3
| 6 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'math', '*1600'] |
B. Middle Classtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMany years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles.The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that: the government chooses some subset of people (maybe all of them); the government takes all savings from the chosen people and redistributes the savings among the chosen people equally. For example, consider the savings as list [5, 1, 2, 1]: if the government chose the 1-st and the 3-rd persons then it, at first, will take all 5 + 2 = 7 burles and after that will return 3.5 burles to the chosen people. As a result, the savings will become [3.5, 1, 3.5, 1].A lot of data was lost from that time, so we don't know how many reforms were implemented and to whom. All we can do is ask you to calculate the maximum possible number of wealthy people after several (maybe zero) reforms.InputThe first line contains single integer T (1 \le T \le 1000) — the number of test cases.Next 2T lines contain the test cases — two lines per test case. The first line contains two integers n and x (1 \le n \le 10^5, 1 \le x \le 10^9) — the number of people and the minimum amount of money to be considered as wealthy.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the initial savings of each person.It's guaranteed that the total sum of n doesn't exceed 10^5.OutputPrint T integers — one per test case. For each test case print the maximum possible number of wealthy people after several (maybe zero) reforms.ExampleInput
4
4 3
5 1 2 1
4 10
11 9 11 9
2 5
4 3
3 7
9 4 9
Output
2
4
0
3
NoteThe first test case is described in the statement.In the second test case, the government, for example, could carry out two reforms: [\underline{11}, \underline{9}, 11, 9] \rightarrow [10, 10, \underline{11}, \underline{9}] \rightarrow [10, 10, 10, 10].In the third test case, the government couldn't make even one person wealthy.In the fourth test case, the government could choose all people to carry out a reform: [\underline{9}, \underline{4}, \underline{9}] \rightarrow [7\frac{1}{3}, 7\frac{1}{3}, 7\frac{1}{3}]. | 4
4 3
5 1 2 1
4 10
11 9 11 9
2 5
4 3
3 7
9 4 9
| 2 4 0 3 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1100'] |
A. Level Statisticstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by 1. If he manages to finish the level successfully then the number of clears increases by 1 as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.So he peeked at the stats n times and wrote down n pairs of integers — (p_1, c_1), (p_2, c_2), \dots, (p_n, c_n), where p_i is the number of plays at the i-th moment of time and c_i is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.Help him to check the correctness of his records.For your convenience you have to answer multiple independent test cases.InputThe first line contains a single integer T (1 \le T \le 500) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 100) — the number of moments of time Polycarp peeked at the stats.Each of the next n lines contains two integers p_i and c_i (0 \le p_i, c_i \le 1000) — the number of plays and the number of clears of the level at the i-th moment of time.Note that the stats are given in chronological order.OutputFor each test case print a single line.If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print "YES".Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInput
6
3
0 0
1 1
1 2
2
1 0
1000 3
4
10 1
15 2
10 2
15 2
1
765 432
2
4 4
4 3
5
0 0
1 0
1 0
1 0
1 0
Output
NO
YES
NO
YES
NO
YES
NoteIn the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.The second test case is a nice example of a Super Expert level.In the third test case the number of plays decreased, which is impossible.The fourth test case is probably an auto level with a single jump over the spike.In the fifth test case the number of clears decreased, which is also impossible.Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it. | 6
3
0 0
1 1
1 2
2
1 0
1000 3
4
10 1
15 2
10 2
15 2
1
765 432
2
4 4
4 3
5
0 0
1 0
1 0
1 0
1 0
| NO YES NO YES NO YES | 2 seconds | 256 megabytes | ['implementation', 'math', '*1200'] |
F. Kate and imperfectiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKate has a set S of n integers \{1, \dots, n\} . She thinks that imperfection of a subset M \subseteq S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a \neq b. Kate is a very neat girl and for each k \in \{2, \dots, n\} she wants to find a subset that has the smallest imperfection among all subsets in S of size k. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size k, will name it I_k. Please, help Kate to find I_2, I_3, ..., I_n.InputThe first and only line in the input consists of only one integer n (2\le n \le 5 \cdot 10^5) — the size of the given set S.OutputOutput contains only one line that includes n - 1 integers: I_2, I_3, ..., I_n.ExamplesInput
2
Output
1 Input
3
Output
1 1 NoteFirst sample: answer is 1, because gcd(1, 2) = 1.Second sample: there are subsets of S with sizes 2, 3 with imperfection equal to 1. For example, \{2,3\} and \{1, 2, 3\}. | 2
| 1 | 1 second | 256 megabytes | ['greedy', 'implementation', 'math', 'number theory', 'sortings', 'two pointers', '*2200'] |
E. Road to 1600time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEgor wants to achieve a rating of 1600 points on the well-known chess portal ChessForces and he needs your help!Before you start solving the problem, Egor wants to remind you how the chess pieces move. Chess rook moves along straight lines up and down, left and right, as many squares as it wants. And when it wants, it can stop. The queen walks in all directions vertically and diagonally at any distance. You can see the examples below. To reach the goal, Egor should research the next topic:There is an N \times N board. Each cell of the board has a number from 1 to N ^ 2 in it and numbers in all cells are distinct.In the beginning, some chess figure stands in the cell with the number 1. Note that this cell is already considered as visited. After that every move is determined by the following rules: Among all not visited yet cells to which the figure can get in one move, it goes to the cell that has minimal number. If all accessible cells were already visited and some cells are not yet visited, then the figure is teleported to the not visited cell that has minimal number. If this step happens, the piece pays a fee of 1 vun. If all cells are already visited, the process is stopped. Egor should find an N \times N board on which the rook pays strictly less vuns than the queen during the round with this numbering. Help him to find such N \times N numbered board, or tell that it doesn't exist.InputThe only line contains one integer N — the size of the board, 1\le N \le 500.OutputThe output should contain N lines.In i-th line output N numbers — numbers on the i-th row of the board. All numbers from 1 to N \times N must be used exactly once.On your board rook must pay strictly less vuns than the queen.If there are no solutions, print -1.If there are several solutions, you can output any of them. ExamplesInput
1
Output
-1Input
4
Output
4 3 6 12
7 5 9 15
14 1 11 10
13 8 16 2
NoteIn case we have 1 \times 1 board, both rook and queen do not have a chance to pay fees.In second sample rook goes through cells 1 \to 3 \to 4 \to 6 \to 9 \to 5 \to 7 \to 13 \to 2 \to 8 \to 16 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14. Queen goes through 1 \to 3 \to 4 \to 2 \to 5 \to 6 \to 9 \to 7 \to 13 \to 8 \to 11 \to 10 \to 12 \to 15 \to \textbf{(1 vun)} \to 14 \to \textbf{(1 vun)} \to 16.As a result rook pays 1 vun and queen pays 2 vuns. | 1
| -1 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', '*2400'] |
D. Challenges in school №41time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move.For instance, for the configuration shown below and k = 2 children can do the following steps: At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. It is guaranteed that if the solution exists, it takes not more than n^2 "headturns".InputThe first line of input contains two integers n and k (2 \le n \le 3000, 1 \le k \le 3000000) — the number of children and required number of moves.The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. OutputIf there is no solution, print a single line with number -1.Otherwise, output k lines. Each line has to start with a number n_i (1\le n_i \le \frac{n}{2}) — the number of pairs of children, who turn at this move. After that print n_i distinct integers — the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other.If there are many solutions, print any of them.ExamplesInput
2 1
RL
Output
1 1
Input
2 1
LR
Output
-1Input
4 2
RLRL
Output
2 1 3
1 2
NoteThe first sample contains a pair of children who look at each other. After one move, they can finish the process.In the second sample, children can't make any move. As a result, they can't end in k>0 moves.The third configuration is described in the statement. | 2 1
RL
| 1 1 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'games', 'graphs', 'greedy', 'implementation', 'sortings', '*2100'] |
C. Eugene and an arraytime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEugene likes working with arrays. And today he needs your help in solving one challenging task.An array c is a subarray of an array b if c can be obtained from b by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array [-1, 2, -3] is good, as all arrays [-1], [-1, 2], [-1, 2, -3], [2], [2, -3], [-3] have nonzero sums of elements. However, array [-1, 2, -1, -3] isn't good, as his subarray [-1, 2, -1] has sum of elements equal to 0.Help Eugene to calculate the number of nonempty good subarrays of a given array a.InputThe first line of the input contains a single integer n (1 \le n \le 2 \times 10^5) — the length of array a.The second line of the input contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9) — the elements of a. OutputOutput a single integer — the number of good subarrays of a.ExamplesInput
3
1 2 -3
Output
5
Input
3
41 -41 41
Output
3
NoteIn the first sample, the following subarrays are good: [1], [1, 2], [2], [2, -3], [-3]. However, the subarray [1, 2, -3] isn't good, as its subarray [1, 2, -3] has sum of elements equal to 0.In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray [41, -41, 41] isn't good, as its subarray [41, -41] has sum of elements equal to 0. | 3
1 2 -3
| 5 | 1.5 seconds | 256 megabytes | ['binary search', 'data structures', 'implementation', 'two pointers', '*1700'] |
B. Kind Antontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}.Anton can perform the following sequence of operations any number of times: Choose any pair of indexes (i, j) such that 1 \le i < j \le n. It is possible to choose the same pair (i, j) more than once. Add a_i to a_j. In other words, j-th element of the array becomes equal to a_i + a_j. For example, if you are given array [1, -1, 0], you can transform it only to [1, -1, -1], [1, 0, 0] and [1, -1, 1] by one operation.Anton wants to predict if it is possible to apply some number (zero or more) of these operations to the array a so that it becomes equal to array b. Can you help him?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10000). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the length of arrays.The second line of each test case contains n integers a_1, a_2, \dots, a_n (-1 \le a_i \le 1) — elements of array a. There can be duplicates among elements.The third line of each test case contains n integers b_1, b_2, \dots, b_n (-10^9 \le b_i \le 10^9) — elements of array b. There can be duplicates among elements.It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.OutputFor each test case, output one line containing "YES" if it's possible to make arrays a and b equal by performing the described operations, or "NO" if it's impossible.You can print each letter in any case (upper or lower).ExampleInput
5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
Output
YES
NO
YES
YES
NO
NoteIn the first test-case we can choose (i, j)=(2, 3) twice and after that choose (i, j)=(1, 2) twice too. These operations will transform [1, -1, 0] \to [1, -1, -2] \to [1, 1, -2]In the second test case we can't make equal numbers on the second position.In the third test case we can choose (i, j)=(1, 2) 41 times. The same about the fourth test case.In the last lest case, it is impossible to make array a equal to the array b. | 5
3
1 -1 0
1 1 -2
3
0 1 1
0 2 2
2
1 0
1 41
2
-1 0
-1 -41
5
0 1 -1 1 -1
1 1 -1 1 -1
| YES NO YES YES NO | 1 second | 256 megabytes | ['greedy', 'implementation', '*1100'] |
A. Little Artemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYoung boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.Artem wants to paint an n \times m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adjacent by the side. Let W be the number of white cells that have at least one black neighbor adjacent by the side. A coloring is called good if B = W + 1. The first coloring shown below has B=5 and W=4 (all cells have at least one neighbor with the opposite color). However, the second coloring is not good as it has B=4, W=4 (only the bottom right cell doesn't have a neighbor with the opposite color). Please, help Medina to find any good coloring. It's guaranteed that under given constraints the solution always exists. If there are several solutions, output any of them.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 20). Each of the next t lines contains two integers n, m (2 \le n,m \le 100) — the number of rows and the number of columns in the grid.OutputFor each test case print n lines, each of length m, where i-th line is the i-th row of your colored matrix (cell labeled with 'B' means that the cell is black, and 'W' means white). Do not use quotes.It's guaranteed that under given constraints the solution always exists.ExampleInput
2
3 2
3 3
Output
BW
WB
BB
BWB
BWW
BWBNoteIn the first testcase, B=3, W=2.In the second testcase, B=5, W=4. You can see the coloring in the statement. | 2
3 2
3 3
| BW WB BB BWB BWW BWB | 1 second | 256 megabytes | ['constructive algorithms', '*1000'] |
G. No Monotone Triplestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGiven a sequence of integers a of length n, a tuple (i,j,k) is called monotone triples if 1 \le i<j<k\le n; a_i \le a_j \le a_k or a_i \ge a_j \ge a_k is satisfied. For example, a=[5,3,4,5], then (2,3,4) is monotone triples for sequence a while (1,3,4) is not.Bob is given a sequence of integers a of length n in a math exam. The exams itself contains questions of form L, R, for each of them he is asked to find any subsequence b with size greater than 2 (i.e. |b| \ge 3) of sequence a_L, a_{L+1},\ldots, a_{R}.Recall that an sequence b is a subsequence of sequence a if b can be obtained by deletion of several (possibly zero, or all) elements.However, he hates monotone stuff, and he wants to find a subsequence free from monotone triples. Besides, he wants to find one subsequence with the largest length among all subsequences free from monotone triples for every query.Please help Bob find out subsequences meeting the above constraints.InputThe first line contains two integers n, q (3 \le n \le 2 \cdot 10^5, 1 \le q \le 2 \cdot 10^5) — the length of sequence a and the number of queries.The second line contains n integers a_1,a_2,\ldots, a_n (1 \le a_i \le 10^{9}), representing the sequence a.Then each of the following q lines contains two integers L, R (1 \le L,R \le n, R-L\ge 2).OutputFor each query, output 0 if there is no subsequence b satisfying the constraints mentioned in the legend. You can print the empty line after but that's not mandatory.Otherwise, output one integer k (k > 2) denoting the length of sequence b, then output k integers i_1, i_2, \ldots, i_k (L \le i_1 < i_2<\ldots<i_k\le R) satisfying that b_j = a_{i_j} for 1 \le j \le k.If there are multiple answers with the maximum length, print any of them.ExampleInput
6 2
3 1 4 1 5 9
1 3
4 6
Output
3
1 2 3
0
NoteFor the first query, the given sequence itself is monotone triples free.For the second query, it can be shown that there is no subsequence b with length greater than 2 such that b is monotone triples free. | 6 2
3 1 4 1 5 9
1 3
4 6
| 3 1 2 3 0 | 2 seconds | 512 megabytes | ['data structures', '*3100'] |
F. Independent Settime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputEric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.Given a graph G=(V,E), an independent set is a subset of vertices V' \subset V such that for every pair u,v \in V', (u,v) \not \in E (i.e. no edge in E connects two vertices from V').An edge-induced subgraph consists of a subset of edges E' \subset E and all the vertices in the original graph that are incident on at least one edge in the subgraph.Given E' \subset E, denote G[E'] the edge-induced subgraph such that E' is the edge set of the subgraph. Here is an illustration of those definitions: In order to help his students get familiar with those definitions, he leaves the following problem as an exercise:Given a tree G=(V,E), calculate the sum of w(H) over all except null edge-induced subgraph H of G, where w(H) is the number of independent sets in H. Formally, calculate \sum \limits_{\emptyset \not= E' \subset E} w(G[E']).Show Eric that you are smarter than his students by providing the correct answer as quickly as possible. Note that the answer might be large, you should output the answer modulo 998,244,353.InputThe first line contains a single integer n (2 \le n \le 3 \cdot 10^5), representing the number of vertices of the graph G.Each of the following n-1 lines contains two integers u and v (1 \le u,v \le n, u \not= v), describing edges of the given tree.It is guaranteed that the given edges form a tree.OutputOutput one integer, representing the desired value modulo 998,244,353.ExamplesInput
2
2 1
Output
3
Input
3
1 2
3 2
Output
11
NoteFor the second example, all independent sets are listed below. | 2
2 1
| 3 | 2 seconds | 512 megabytes | ['dfs and similar', 'dp', 'trees', '*2500'] |
E. Height All the Sametime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice has got addicted to a game called Sirtet recently.In Sirtet, player is given an n \times m grid. Initially a_{i,j} cubes are stacked up in the cell (i,j). Two cells are called adjacent if they share a side. Player can perform the following operations: stack up one cube in two adjacent cells; stack up two cubes in one cell. Cubes mentioned above are identical in height.Here is an illustration of the game. States on the right are obtained by performing one of the above operations on the state on the left, and grey cubes are added due to the operation. Player's goal is to make the height of all cells the same (i.e. so that each cell has the same number of cubes in it) using above operations. Alice, however, has found out that on some starting grids she may never reach the goal no matter what strategy she uses. Thus, she is wondering the number of initial grids such that L \le a_{i,j} \le R for all 1 \le i \le n, 1 \le j \le m; player can reach the goal using above operations. Please help Alice with it. Notice that the answer might be large, please output the desired value modulo 998,244,353.InputThe only line contains four integers n, m, L and R (1\le n,m,L,R \le 10^9, L \le R, n \cdot m \ge 2).OutputOutput one integer, representing the desired answer modulo 998,244,353.ExamplesInput
2 2 1 1
Output
1
Input
1 2 1 2
Output
2
NoteIn the first sample, the only initial grid that satisfies the requirements is a_{1,1}=a_{2,1}=a_{1,2}=a_{2,2}=1. Thus the answer should be 1.In the second sample, initial grids that satisfy the requirements are a_{1,1}=a_{1,2}=1 and a_{1,1}=a_{1,2}=2. Thus the answer should be 2. | 2 2 1 1
| 1 | 2 seconds | 512 megabytes | ['combinatorics', 'constructive algorithms', 'math', 'matrices', '*2100'] |
D. Walk on Matrixtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBob is playing a game named "Walk on Matrix".In this game, player is given an n \times m matrix A=(a_{i,j}), i.e. the element in the i-th row in the j-th column is a_{i,j}. Initially, player is located at position (1,1) with score a_{1,1}. To reach the goal, position (n,m), player can move right or down, i.e. move from (x,y) to (x,y+1) or (x+1,y), as long as player is still on the matrix.However, each move changes player's score to the bitwise AND of the current score and the value at the position he moves to.Bob can't wait to find out the maximum score he can get using the tool he recently learnt — dynamic programming. Here is his algorithm for this problem. However, he suddenly realize that the algorithm above fails to output the maximum score for some matrix A. Thus, for any given non-negative integer k, he wants to find out an n \times m matrix A=(a_{i,j}) such that 1 \le n,m \le 500 (as Bob hates large matrix); 0 \le a_{i,j} \le 3 \cdot 10^5 for all 1 \le i\le n,1 \le j\le m (as Bob hates large numbers); the difference between the maximum score he can get and the output of his algorithm is exactly k. It can be shown that for any given integer k such that 0 \le k \le 10^5, there exists a matrix satisfying the above constraints.Please help him with it!InputThe only line of the input contains one single integer k (0 \le k \le 10^5).OutputOutput two integers n, m (1 \le n,m \le 500) in the first line, representing the size of the matrix. Then output n lines with m integers in each line, a_{i,j} in the (i+1)-th row, j-th column.ExamplesInput
0
Output
1 1
300000Input
1
Output
3 4
7 3 3 1
4 8 3 6
7 7 7 3NoteIn the first example, the maximum score Bob can achieve is 300000, while the output of his algorithm is 300000.In the second example, the maximum score Bob can achieve is 7\&3\&3\&3\&7\&3=3, while the output of his algorithm is 2. | 0
| 1 1 300000 | 2 seconds | 512 megabytes | ['bitmasks', 'constructive algorithms', 'math', '*1700'] |
C. K-Complete Wordtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWord s of length n is called k-complete if s is a palindrome, i.e. s_i=s_{n+1-i} for all 1 \le i \le n; s has a period of k, i.e. s_i=s_{k+i} for all 1 \le i \le n-k. For example, "abaaba" is a 3-complete word, while "abccba" is not.Bob is given a word s of length n consisting of only lowercase Latin letters and an integer k, such that n is divisible by k. He wants to convert s to any k-complete word.To do this Bob can choose some i (1 \le i \le n) and replace the letter at position i with some other lowercase Latin letter.So now Bob wants to know the minimum number of letters he has to replace to convert s to any k-complete word.Note that Bob can do zero changes if the word s is already k-complete.You are required to answer t test cases independently.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 two integers n and k (1 \le k < n \le 2 \cdot 10^5, n is divisible by k).The second line of each test case contains a word s of length n.It is guaranteed that word s only contains lowercase Latin letters. And it is guaranteed that the sum of n over all test cases will not exceed 2 \cdot 10^5.OutputFor each test case, output one integer, representing the minimum number of characters he has to replace to convert s to any k-complete word.ExampleInput
4
6 2
abaaba
6 3
abaaba
36 9
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp
Output
2
0
23
16
NoteIn the first test case, one optimal solution is aaaaaa.In the second test case, the given word itself is k-complete. | 4
6 2
abaaba
6 3
abaaba
36 9
hippopotomonstrosesquippedaliophobia
21 7
wudixiaoxingxingheclp
| 2 0 23 16 | 2 seconds | 512 megabytes | ['dfs and similar', 'dsu', 'greedy', 'implementation', 'strings', '*1500'] |
B. Composite Coloringtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97.Alice is given a sequence of n composite numbers a_1,a_2,\ldots,a_n.She wants to choose an integer m \le 11 and color each element one of m colors from 1 to m so that: for each color from 1 to m there is at least one element of this color; each element is colored and colored exactly one color; the greatest common divisor of any two elements that are colored the same color is greater than 1, i.e. \gcd(a_i, a_j)>1 for each pair i, j if these elements are colored the same color. Note that equal elements can be colored different colors — you just have to choose one of m colors for each of the indices from 1 to n.Alice showed already that if all a_i \le 1000 then she can always solve the task by choosing some m \le 11.Help Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some m from 1 to 11.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Then the descriptions of the test cases follow.The first line of the test case contains a single integer n (1 \le n \le 1000) — the amount of numbers in a sequence a.The second line of the test case contains n composite integers a_1,a_2,\ldots,a_n (4 \le a_i \le 1000).It is guaranteed that the sum of n over all test cases doesn't exceed 10^4.OutputFor each test case print 2 lines. The first line should contain a single integer m (1 \le m \le 11) — the number of used colors. Consider colors to be numbered from 1 to m. The second line should contain any coloring that satisfies the above conditions. Print n integers c_1, c_2, \dots, c_n (1 \le c_i \le m), where c_i is the color of the i-th element. If there are multiple solutions then you can print any of them. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some m from 1 to 11.Remember that each color from 1 to m should be used at least once. Any two elements of the same color should not be coprime (i.e. their GCD should be greater than 1).ExampleInput
3
3
6 10 15
2
4 9
23
437 519 865 808 909 391 194 291 237 395 323 365 511 497 781 737 871 559 731 697 779 841 961
Output
1
1 1 1
2
2 1
11
4 7 8 10 7 3 10 7 7 8 3 1 1 5 5 9 2 2 3 3 4 11 6
NoteIn the first test case, \gcd(6,10)=2, \gcd(6,15)=3 and \gcd(10,15)=5. Therefore, it's valid to color all elements the same color. Note that there are other colorings which satisfy Alice's requirement in this test case.In the second test case there is only one element of each color, so the coloring definitely satisfies Alice's requirement. | 3
3
6 10 15
2
4 9
23
437 519 865 808 909 391 194 291 237 395 323 365 511 497 781 737 871 559 731 697 779 841 961
| 1 1 1 1 2 2 1 11 4 7 8 10 7 3 10 7 7 8 3 1 1 5 5 9 2 2 3 3 4 11 6 | 2 seconds | 512 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'math', 'number theory', '*1400'] |
A. Exercising Walktime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move: exactly a steps left: from (u,v) to (u-1,v); exactly b steps right: from (u,v) to (u+1,v); exactly c steps down: from (u,v) to (u,v-1); exactly d steps up: from (u,v) to (u,v+1). Note that the moves can be performed in an arbitrary order. For example, if the cat has to move 1 step left, 3 steps right and 2 steps down, then the walk right, down, left, right, right, down is valid.Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area [x_1,x_2]\times [y_1,y_2], i.e. for every cat's position (u,v) of a walk x_1 \le u \le x_2 and y_1 \le v \le y_2 holds.Also, note that the cat can visit the same cell multiple times.Can you help Alice find out if there exists a walk satisfying her wishes?Formally, the walk should contain exactly a+b+c+d unit moves (a to the left, b to the right, c to the down, d to the up). Alice can do the moves in any order. Her current position (u, v) should always satisfy the constraints: x_1 \le u \le x_2, y_1 \le v \le y_2. The staring point is (x, y).You are required to answer t test cases independently.InputThe first line contains a single integer t (1 \le t \le 10^3) — the number of testcases. The first line of each test case contains four integers a, b, c, d (0 \le a,b,c,d \le 10^8, a+b+c+d \ge 1).The second line of the test case contains six integers x, y, x_1, y_1, x_2, y_2 (-10^8 \le x_1\le x \le x_2 \le 10^8, -10^8 \le y_1 \le y \le y_2 \le 10^8).OutputFor each test case, output "YES" in a separate line, if there exists a walk satisfying her wishes. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExampleInput
6
3 2 2 2
0 0 -2 -2 2 2
3 1 4 1
0 0 -1 -1 1 1
1 1 1 1
1 1 1 1 1 1
0 0 0 1
0 0 0 0 0 1
5 1 1 1
0 0 -100 -100 0 100
1 1 5 1
0 0 -100 -100 100 0
Output
Yes
No
No
Yes
Yes
Yes
NoteIn the first test case, one valid exercising walk is (0,0)\rightarrow (-1,0) \rightarrow (-2,0)\rightarrow (-2,1) \rightarrow (-2,2)\rightarrow (-1,2)\rightarrow(0,2)\rightarrow (0,1)\rightarrow (0,0) \rightarrow (-1,0) | 6
3 2 2 2
0 0 -2 -2 2 2
3 1 4 1
0 0 -1 -1 1 1
1 1 1 1
1 1 1 1 1 1
0 0 0 1
0 0 0 0 0 1
5 1 1 1
0 0 -100 -100 0 100
1 1 5 1
0 0 -100 -100 100 0
| Yes No No Yes Yes Yes | 2 seconds | 512 megabytes | ['greedy', 'implementation', 'math', '*1100'] |
H. It's showtimetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a mysterious language (codenamed "UnknownX") available in "Custom Test" tab. Find out what this language is, and use it to solve the following problem.You are given an integer input = 1000 * n + mod (1 \le n, mod \le 999). Calculate double factorial of n modulo mod.InputThe input contains a single integer input (1001 \le input \le 999999). You are guaranteed that input \mod 1000 \neq 0.OutputOutput a single number.ExamplesInput
6100
Output
48
Input
9900
Output
45
Input
100002
Output
0
Input
123456
Output
171
NoteIn the first test case you need to calculate 6!! \mod 100; 6!! = 6 * 4 * 2 = 48.In the second test case you need to calculate 9!! \mod 900; 9!! = 9 * 7 * 5 * 3 = 945.In the third test case you need to calculate 100!! \mod 2; you can notice that 100!! is a multiple of 100 and thus is divisible by 2. | 6100
| 48 | 1 second | 256 megabytes | ['*special problem'] |
G. Lingua Romanatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputper nextum in unam tum XI conscribementis fac sic vestibulo perlegementum da varo. morde varo. seqis cumula varum.cisper nextum in unam tum XI conscribementis fac sic seqis decumulamenta da varo. varum privamentum fodementum da aresulto. varum tum III elevamentum tum V multiplicamentum da bresulto. aresultum tum bresultum addementum da resulto. si CD tum resultum non praestantiam fac sic dictum sic f(%d) = %.2f cis tum varum tum resultum egresso describe. novumversum egresso scribe. cis si CD tum resultum praestantiam fac sic dictum sic f(%d) = MAGNA NIMIS! cis tum varum egresso describe. novumversum egresso scribe. ciscisInputThe input consists of several integers, one per line. Each integer is between -50 and 50, inclusive.OutputAs described in the problem statement.ExampleInput
0
1
-2
-3
-4
-5
-6
-7
-8
-9
10
Output
f(10) = MAGNA NIMIS!
f(-9) = -3642.00
f(-8) = -2557.17
f(-7) = -1712.35
f(-6) = -1077.55
f(-5) = -622.76
f(-4) = -318.00
f(-3) = -133.27
f(-2) = -38.59
f(1) = 6.00
f(0) = 0.00
| 0
1
-2
-3
-4
-5
-6
-7
-8
-9
10
| f(10) = MAGNA NIMIS! f(-9) = -3642.00 f(-8) = -2557.17 f(-7) = -1712.35 f(-6) = -1077.55 f(-5) = -622.76 f(-4) = -318.00 f(-3) = -133.27 f(-2) = -38.59 f(1) = 6.00 f(0) = 0.00 | 1 second | 256 megabytes | ['*special problem'] |
F. Elementary!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe input consists of a single string of uppercase letters A-Z. The length of the string is between 1 and 10 characters, inclusive.OutputOutput "YES" or "NO".ExamplesInput
GENIUS
Output
YES
Input
DOCTOR
Output
NO
Input
IRENE
Output
YES
Input
MARY
Output
NO
Input
SMARTPHONE
Output
NO
Input
REVOLVER
Output
YES
Input
HOLMES
Output
NO
Input
WATSON
Output
YES
| GENIUS
| YES | 1 second | 256 megabytes | ['*special problem', 'brute force', 'dp', 'strings'] |
E. Jordan Smileytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output InputThe input contains two integers row, col (0 \le row, col \le 63), separated by a single space.OutputOutput "IN" or "OUT".ExamplesInput
0 0
Output
OUT
Input
27 0
Output
IN
Input
0 27
Output
OUT
Input
27 27
Output
IN
| 0 0
| OUT | 1 second | 256 megabytes | ['*special problem', 'dfs and similar', 'geometry', 'implementation'] |
D. Again?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.OutputOutput a single integer.ExamplesInput
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A144045
Output
1
| A278832
| 0 | 1 second | 256 megabytes | ['*special problem', 'implementation'] |
C. ...And after happily lived ever theytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInputThe input contains a single integer a (0 \le a \le 63).OutputOutput a single number.ExamplesInput
2
Output
2
Input
5
Output
24
Input
35
Output
50
| 2
| 2 | 1 second | 256 megabytes | ['*special problem', 'bitmasks'] |
B. Limerickstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere was once young lass called Mary, Whose jokes were occasionally scary. On this April's Fool Fixed limerick rules Allowed her to trip the unwary.Can she fill all the linesTo work at all times?On juggling the wordsRight around two-thirdsShe nearly ran out of rhymes.InputThe input contains a single integer a (4 \le a \le 998). Not every integer in the range is a valid input for the problem; you are guaranteed that the input will be a valid integer.OutputOutput a single number.ExamplesInput
35
Output
57
Input
57
Output
319
Input
391
Output
1723
| 35
| 57 | 1 second | 256 megabytes | ['*special problem', 'math', 'number theory'] |
B. Dreamoon Likes Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe sequence of m integers is called the permutation if it contains all integers from 1 to m exactly once. The number m is called the length of the permutation.Dreamoon has two permutations p_1 and p_2 of non-zero lengths l_1 and l_2.Now Dreamoon concatenates these two permutations into another sequence a of length l_1 + l_2. First l_1 elements of a is the permutation p_1 and next l_2 elements of a is the permutation p_2. You are given the sequence a, and you need to find two permutations p_1 and p_2. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)InputThe first line contains an integer t (1 \le t \le 10\,000) denoting the number of test cases in the input.Each test case contains two lines. The first line contains one integer n (2 \leq n \leq 200\,000): the length of a. The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n-1).The total sum of n is less than 200\,000.OutputFor each test case, the first line of output should contain one integer k: the number of ways to divide a into permutations p_1 and p_2.Each of the next k lines should contain two integers l_1 and l_2 (1 \leq l_1, l_2 \leq n, l_1 + l_2 = n), denoting, that it is possible to divide a into two permutations of length l_1 and l_2 (p_1 is the first l_1 elements of a, and p_2 is the last l_2 elements of a). You can print solutions in any order.ExampleInput
6
5
1 4 3 2 1
6
2 4 1 3 2 1
4
2 1 1 3
4
1 3 3 1
12
2 1 3 4 5 6 7 8 9 1 10 2
3
1 1 1
Output
2
1 4
4 1
1
4 2
0
0
1
2 10
0
NoteIn the first example, two possible ways to divide a into permutations are \{1\} + \{4, 3, 2, 1\} and \{1,4,3,2\} + \{1\}.In the second example, the only way to divide a into permutations is \{2,4,1,3\} + \{2,1\}.In the third example, there are no possible ways. | 6
5
1 4 3 2 1
6
2 4 1 3 2 1
4
2 1 1 3
4
1 3 3 1
12
2 1 3 4 5 6 7 8 9 1 10 2
3
1 1 1
| 2 1 4 4 1 1 4 2 0 0 1 2 10 0 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1400'] |
A. Dreamoon and Ranking Collectiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon is a big fan of the Codeforces contests.One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing!Based on this, you come up with the following problem:There is a person who participated in n Codeforces rounds. His place in the first round is a_1, his place in the second round is a_2, ..., his place in the n-th round is a_n.You are given a positive non-zero integer x.Please, find the largest v such that this person can collect all the places from 1 to v after x more rated contests.In other words, you need to find the largest v, such that it is possible, that after x more rated contests, for each 1 \leq i \leq v, there will exist a contest where this person took the i-th place.For example, if n=6, x=2 and a=[3,1,1,5,7,10] then answer is v=5, because if on the next two contest he will take places 2 and 4, then he will collect all places from 1 to 5, so it is possible to get v=5.InputThe first line contains an integer t (1 \leq t \leq 5) denoting the number of test cases in the input.Each test case contains two lines. The first line contains two integers n, x (1 \leq n, x \leq 100). The second line contains n positive non-zero integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 100).OutputFor each test case print one line containing the largest v, such that it is possible that after x other contests, for each 1 \leq i \leq v, there will exist a contest where this person took the i-th place.ExampleInput
5
6 2
3 1 1 5 7 10
1 100
100
11 1
1 1 1 1 1 1 1 1 1 1 1
1 1
1
4 57
80 60 40 20
Output
5
101
2
2
60
NoteThe first test case is described in the statement.In the second test case, the person has one hundred future contests, so he can take place 1,2,\ldots,99 and place 101 on them in some order, to collect places 1,2,\ldots,101. | 5
6 2
3 1 1 5 7 10
1 100
100
11 1
1 1 1 1 1 1 1 1 1 1 1
1 1
1
4 57
80 60 40 20
| 5 101 2 2 60 | 1 second | 256 megabytes | ['implementation', '*900'] |
E. Dreamoon Loves AAtime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a string of length n+1 of characters 'A' and 'B'. The first character and last character of the string are equal to 'A'.You are given m indices p_1, p_2, \ldots, p_m (0-indexation) denoting the other indices of characters 'A' in the string. Let's denote the minimum distance between two neighboring 'A' as l, and maximum distance between neighboring 'A' as r.For example, (l,r) of string "ABBAABBBA" is (1,4).And let's denote the balance degree of a string as the value of r-l.Now Dreamoon wants to change exactly k characters from 'B' to 'A', and he wants to make the balance degree of the string as small as possible.Please calculate the required minimum possible value of balance degree.InputThe first line contains one integer t denoting the number of test cases (1 \leq t \leq 400\,000).For each test case, the first line contains three integers n, m and k (1 \leq n \leq 10^{15}, 0 \leq m \leq 400\,000, 0 \leq k < n - m).The second line contains m integers p_1, p_2, \ldots, p_m, (0 < p_1 < p_2 < \ldots < p_m < n).The total sum of m is at most 400\,000.OutputFor each test case, print one integer: the smallest possible value of balance degree after k changes of 'B' to 'A'.ExampleInput
5
80 3 5
11 24 50
81 7 12
4 10 17 26 37 48 61
25 10 14
3 4 7 12 13 15 17 19 21 23
1 0 0
10 2 0
2 4
Output
5
2
0
0
4
| 5
80 3 5
11 24 50
81 7 12
4 10 17 26 37 48 61
25 10 14
3 4 7 12 13 15 17 19 21 23
1 0 0
10 2 0
2 4
| 5 2 0 0 4 | 3.5 seconds | 256 megabytes | ['binary search', 'greedy', '*3300'] |
D. Dreamoon Likes Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon likes strings. Today he created a game about strings:String s_1, s_2, \ldots, s_n is beautiful if and only if for each 1 \le i < n, s_i \ne s_{i+1}.Initially, Dreamoon has a string a. In each step Dreamoon can choose a beautiful substring of a and remove it. Then he should concatenate the remaining characters (in the same order).Dreamoon wants to use the smallest number of steps to make a empty. Please help Dreamoon, and print any sequence of the smallest number of steps to make a empty.InputThe first line contains an integer t (1 \leq t \leq 200\,000), denoting the number of test cases in the input.For each test case, there's one line with a non-empty string of lowercase Latin letters a.The total sum of lengths of strings in all test cases is at most 200\,000.OutputFor each test case, in the first line, you should print m: the smallest number of steps to make a empty. Each of the following m lines should contain two integers l_i, r_i (1 \leq l_i \leq r_i \leq |a|), denoting, that the i-th step is removing the characters from index l_i to r_i in the current string. (indices are numbered starting from 1). Note that after the deletion of the substring, indices of remaining characters may change, and r_i should be at most the current length of a.If there are several possible solutions, you can print any.ExampleInput
4
aabbcc
aaabbb
aaa
abacad
Output
3
3 3
2 4
1 2
3
3 4
2 3
1 2
3
1 1
1 1
1 1
1
1 6 | 4
aabbcc
aaabbb
aaa
abacad
| 3 3 3 2 4 1 2 3 3 4 2 3 1 2 3 1 1 1 1 1 1 1 1 6 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', '*3100'] |
C. Drazil Likes Heaptime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDrazil likes heap very much. So he created a problem with heap:There is a max heap with a height h implemented on the array. The details of this heap are the following:This heap contains exactly 2^h - 1 distinct positive non-zero integers. All integers are distinct. These numbers are stored in the array a indexed from 1 to 2^h-1. For any 1 < i < 2^h, a[i] < a[\left \lfloor{\frac{i}{2}}\right \rfloor].Now we want to reduce the height of this heap such that the height becomes g with exactly 2^g-1 numbers in heap. To reduce the height, we should perform the following action 2^h-2^g times:Choose an index i, which contains an element and call the following function f in index i:Note that we suppose that if a[i]=0, then index i don't contain an element.After all operations, the remaining 2^g-1 element must be located in indices from 1 to 2^g-1. Now Drazil wonders what's the minimum possible sum of the remaining 2^g-1 elements. Please find this sum and find a sequence of the function calls to achieve this value.InputThe first line of the input contains an integer t (1 \leq t \leq 70\,000): the number of test cases.Each test case contain two lines. The first line contains two integers h and g (1 \leq g < h \leq 20). The second line contains n = 2^h-1 distinct positive integers a[1], a[2], \ldots, a[n] (1 \leq a[i] < 2^{20}). For all i from 2 to 2^h - 1, a[i] < a[\left \lfloor{\frac{i}{2}}\right \rfloor].The total sum of n is less than 2^{20}.OutputFor each test case, print two lines.The first line should contain one integer denoting the minimum sum after reducing the height of heap to g. The second line should contain 2^h - 2^g integers v_1, v_2, \ldots, v_{2^h-2^g}. In i-th operation f(v_i) should be called.ExampleInput
2
3 2
7 6 3 5 4 2 1
3 2
7 6 5 4 3 2 1
Output
10
3 2 3 1
8
2 1 3 1
| 2
3 2
7 6 3 5 4 2 1
3 2
7 6 5 4 3 2 1
| 10 3 2 3 1 8 2 1 3 1 | 1.5 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'greedy', 'implementation', '*2400'] |
B. Dreamoon Likes Sequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS: You are given two integers d, m, find the number of arrays a, satisfying the following constraints: The length of a is n, n \ge 1 1 \le a_1 < a_2 < \dots < a_n \le d Define an array b of length n as follows: b_1 = a_1, \forall i > 1, b_i = b_{i - 1} \oplus a_i, where \oplus is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < \dots < b_{n - 1} < b_n should hold. Since the number of possible arrays may be too large, you need to find the answer modulo m.InputThe first line contains an integer t (1 \leq t \leq 100) denoting the number of test cases in the input.Each of the next t lines contains two integers d, m (1 \leq d, m \leq 10^9).Note that m is not necessary the prime!OutputFor each test case, print the number of arrays a, satisfying all given constrains, modulo m.ExampleInput
10
1 1000000000
2 999999999
3 99999998
4 9999997
5 999996
6 99995
7 9994
8 993
9 92
10 1
Output
1
3
5
11
17
23
29
59
89
0
| 10
1 1000000000
2 999999999
3 99999998
4 9999997
5 999996
6 99995
7 9994
8 993
9 92
10 1
| 1 3 5 11 17 23 29 59 89 0 | 1 second | 256 megabytes | ['bitmasks', 'combinatorics', 'math', '*1700'] |
A. Dreamoon Likes Coloringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDreamoon likes coloring cells very much.There is a row of n cells. Initially, all cells are empty (don't contain any color). Cells are numbered from 1 to n.You are given an integer m and m integers l_1, l_2, \ldots, l_m (1 \le l_i \le n)Dreamoon will perform m operations.In i-th operation, Dreamoon will choose a number p_i from range [1, n-l_i+1] (inclusive) and will paint all cells from p_i to p_i+l_i-1 (inclusive) in i-th color. Note that cells may be colored more one than once, in this case, cell will have the color from the latest operation.Dreamoon hopes that after these m operations, all colors will appear at least once and all cells will be colored. Please help Dreamoon to choose p_i in each operation to satisfy all constraints.InputThe first line contains two integers n,m (1 \leq m \leq n \leq 100\,000).The second line contains m integers l_1, l_2, \ldots, l_m (1 \leq l_i \leq n).OutputIf it's impossible to perform m operations to satisfy all constraints, print "'-1" (without quotes).Otherwise, print m integers p_1, p_2, \ldots, p_m (1 \leq p_i \leq n - l_i + 1), after these m operations, all colors should appear at least once and all cells should be colored.If there are several possible solutions, you can print any.ExamplesInput
5 3
3 2 2
Output
2 4 1
Input
10 1
1
Output
-1
| 5 3
3 2 2
| 2 4 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', 'math', '*1800'] |
F. Make k Equaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the array a consisting of n elements and the integer k \le n.You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations: Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of a is mn then you choose such index i that a_i = mn and set a_i := a_i + 1); take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of a is mx then you choose such index i that a_i = mx and set a_i := a_i - 1). Your task is to calculate the minimum number of moves required to obtain at least k equal elements in the array.InputThe first line of the input contains two integers n and k (1 \le k \le n \le 2 \cdot 10^5) — the number of elements in a and the required number of equal elements.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the i-th element of a.OutputPrint one integer — the minimum number of moves required to obtain at least k equal elements in the array.ExamplesInput
6 5
1 2 2 4 2 3
Output
3
Input
7 5
3 3 2 1 1 1 3
Output
4
| 6 5
1 2 2 4 2 3
| 3 | 2 seconds | 256 megabytes | ['greedy', '*2200'] |
E. Tree Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.A tree is a connected undirected graph with n-1 edges.You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], \dots, v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.InputThe first line of the input contains two integers n and m (2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5) — the number of vertices in the tree and the number of queries.Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 \le u_i, v_i \le n, u_i \ne v_i).It is guaranteed that the given edges form a tree.The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 \le k_i \le n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], \dots, v_i[k_i] (1 \le v_i[j] \le n), where v_i[j] is the j-th vertex of the i-th query.It is guaranteed that all vertices in a single query are distinct.It is guaranteed that the sum of k_i does not exceed 2 \cdot 10^5 (\sum\limits_{i=1}^{m} k_i \le 2 \cdot 10^5).OutputFor each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.ExampleInput
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
NoteThe picture corresponding to the example:Consider the queries.The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u. | 10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
| YES YES YES YES NO NO | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'trees', '*1900'] |
D. Carouseltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe round carousel consists of n figures of animals. Figures are numbered from 1 to n in order of the carousel moving. Thus, after the n-th figure the figure with the number 1 follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the i-th figure equals t_i. The example of the carousel for n=9 and t=[5, 5, 1, 15, 1, 5, 5, 1, 1]. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly k distinct colors, then the colors of figures should be denoted with integers from 1 to k.InputThe input contains one or more test cases.The first line contains one integer q (1 \le q \le 10^4) — the number of test cases in the test. Then q test cases follow. One test case is given on two lines.The first line of the test case contains one integer n (3 \le n \le 2 \cdot 10^5) — the number of figures in the carousel. Figures are numbered from 1 to n in order of carousel moving. Assume that after the n-th figure the figure 1 goes.The second line of the test case contains n integers t_1, t_2, \dots, t_n (1 \le t_i \le 2 \cdot 10^5), where t_i is the type of the animal of the i-th figure.The sum of n over all test cases does not exceed 2\cdot10^5.OutputPrint q answers, for each test case print two lines.In the first line print one integer k — the minimum possible number of distinct colors of figures.In the second line print n integers c_1, c_2, \dots, c_n (1 \le c_i \le k), where c_i is the color of the i-th figure. If there are several answers, you can print any.ExampleInput
4
5
1 2 1 2 2
6
1 2 2 1 2 2
5
1 2 1 2 3
3
10 10 10
Output
2
1 2 1 2 2
2
2 1 2 1 2 1
3
2 3 2 3 1
1
1 1 1
| 4
5
1 2 1 2 2
6
1 2 2 1 2 2
5
1 2 1 2 3
3
10 10 10
| 2 1 2 1 2 2 2 2 1 2 1 2 1 3 2 3 2 3 1 1 1 1 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dp', 'graphs', 'greedy', 'math', '*1800'] |
C. Ternary XORtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.Let's define the ternary XOR operation \odot of two ternary numbers a and b (both of length n) as a number c = a \odot b of length n, where c_i = (a_i + b_i) \% 3 (where \% is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by 3. For example, 10222 \odot 11021 = 21210.Your task is to find such ternary numbers a and b both of length n and both without leading zeros that a \odot b = x and max(a, b) is the minimum possible.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 \le n \le 5 \cdot 10^4) — the length of x. The second line of the test case contains ternary number x consisting of n digits 0, 1 or 2. It is guaranteed that the first digit of x is 2. It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^4 (\sum n \le 5 \cdot 10^4).OutputFor each test case, print the answer — two ternary integers a and b both of length n and both without leading zeros such that a \odot b = x and max(a, b) is the minimum possible. If there are several answers, you can print any.ExampleInput
4
5
22222
5
21211
1
2
9
220222021
Output
11111
11111
11000
10211
1
1
110111011
110111010
| 4
5
22222
5
21211
1
2
9
220222021
| 11111 11111 11000 10211 1 1 110111011 110111010 | 1 second | 256 megabytes | ['greedy', 'implementation', '*1200'] |
B. K-th Beautiful Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor the given integer n (n > 2) let's write down all the strings of length n which contain n-2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order.Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1 \le i \le n), that s_i < t_i, and for any j (1 \le j < i) s_j = t_j. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.For example, if n=5 the strings are (the order does matter): aaabb aabab aabba abaab ababa abbaa baaab baaba babaa bbaaa It is easy to show that such a list of strings will contain exactly \frac{n \cdot (n-1)}{2} strings.You are given n (n > 2) and k (1 \le k \le \frac{n \cdot (n-1)}{2}). Print the k-th string from the list.InputThe input contains one or more test cases.The first line contains one integer t (1 \le t \le 10^4) — the number of test cases in the test. Then t test cases follow.Each test case is written on the the separate line containing two integers n and k (3 \le n \le 10^5, 1 \le k \le \min(2\cdot10^9, \frac{n \cdot (n-1)}{2}).The sum of values n over all test cases in the test doesn't exceed 10^5.OutputFor each test case print the k-th string from the list of all described above strings of length n. Strings in the list are sorted lexicographically (alphabetically).ExampleInput
7
5 1
5 2
5 8
5 10
3 1
3 2
20 100
Output
aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa
| 7
5 1
5 2
5 8
5 10
3 1
3 2
20 100
| aaabb aabab baaba bbaaa abb bab aaaaabaaaaabaaaaaaaa | 1 second | 256 megabytes | ['binary search', 'brute force', 'combinatorics', 'implementation', 'math', '*1300'] |
A. Divisibility Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The only line of the test case contains two integers a and b (1 \le a, b \le 10^9).OutputFor each test case print the answer — the minimum number of moves you need to do in order to make a divisible by b.ExampleInput
5
10 4
13 9
100 13
123 456
92 46
Output
2
5
4
333
0
| 5
10 4
13 9
100 13
123 456
92 46
| 2 5 4 333 0 | 1 second | 256 megabytes | ['math', '*800'] |
G. Letters and Question Markstime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a string S and an array of strings [t_1, t_2, \dots, t_k]. Each string t_i consists of lowercase Latin letters from a to n; S consists of lowercase Latin letters from a to n and no more than 14 question marks.Each string t_i has its cost c_i — an integer number. The value of some string T is calculated as \sum\limits_{i = 1}^{k} F(T, t_i) \cdot c_i, where F(T, t_i) is the number of occurences of string t_i in T as a substring. For example, F(\text{aaabaaa}, \text{aa}) = 4.You have to replace all question marks in S with pairwise distinct lowercase Latin letters from a to n so the value of S is maximum possible.InputThe first line contains one integer k (1 \le k \le 1000) — the number of strings in the array [t_1, t_2, \dots, t_k].Then k lines follow, each containing one string t_i (consisting of lowercase Latin letters from a to n) and one integer c_i (1 \le |t_i| \le 1000, -10^6 \le c_i \le 10^6). The sum of lengths of all strings t_i does not exceed 1000.The last line contains one string S (1 \le |S| \le 4 \cdot 10^5) consisting of lowercase Latin letters from a to n and question marks. The number of question marks in S is not greater than 14.OutputPrint one integer — the maximum value of S after replacing all question marks with pairwise distinct lowercase Latin letters from a to n.ExamplesInput
4
abc -10
a 1
b 1
c 3
?b?
Output
5
Input
2
a 1
a 1
?
Output
2
Input
3
a 1
b 3
ab 4
ab
Output
8
Input
1
a -1
?????????????
Output
0
Input
1
a -1
??????????????
Output
-1
| 4
abc -10
a 1
b 1
c 3
?b?
| 5 | 4 seconds | 1024 megabytes | ['bitmasks', 'dp', 'string suffix structures', '*2800'] |
F. AND Segmentstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers n, k, m and m conditions (l_1, r_1, x_1), (l_2, r_2, x_2), \dots, (l_m, r_m, x_m).Calculate the number of distinct arrays a, consisting of n integers such that: 0 \le a_i < 2^k for each 1 \le i \le n; bitwise AND of numbers a[l_i] \& a[l_i + 1] \& \dots \& a[r_i] = x_i for each 1 \le i \le m. Two arrays a and b are considered different if there exists such a position i that a_i \neq b_i. The number can be pretty large so print it modulo 998244353.InputThe first line contains three integers n, k and m (1 \le n \le 5 \cdot 10^5, 1 \le k \le 30, 0 \le m \le 5 \cdot 10^5) — the length of the array a, the value such that all numbers in a should be smaller than 2^k and the number of conditions, respectively.Each of the next m lines contains the description of a condition l_i, r_i and x_i (1 \le l_i \le r_i \le n, 0 \le x_i < 2^k) — the borders of the condition segment and the required bitwise AND value on it.OutputPrint a single integer — the number of distinct arrays a that satisfy all the above conditions modulo 998244353.ExamplesInput
4 3 2
1 3 3
3 4 6
Output
3
Input
5 2 3
1 3 2
2 5 0
3 3 3
Output
33
NoteYou can recall what is a bitwise AND operation here.In the first example, the answer is the following arrays: [3, 3, 7, 6], [3, 7, 7, 6] and [7, 3, 7, 6]. | 4 3 2
1 3 3
3 4 6
| 3 | 3 seconds | 256 megabytes | ['bitmasks', 'combinatorics', 'data structures', 'dp', 'two pointers', '*2500'] |
E. Count The Blockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou wrote down all integers from 0 to 10^n - 1, padding them with leading zeroes so their lengths are exactly n. For example, if n = 3 then you wrote out 000, 001, ..., 998, 999.A block in an integer x is a consecutive segment of equal digits that cannot be extended to the left or to the right.For example, in the integer 00027734000 there are three blocks of length 1, one block of length 2 and two blocks of length 3.For all integers i from 1 to n count the number of blocks of length i among the written down integers.Since these integers may be too large, print them modulo 998244353.InputThe only line contains one integer n (1 \le n \le 2 \cdot 10^5).OutputIn the only line print n integers. The i-th integer is equal to the number of blocks of length i.Since these integers may be too large, print them modulo 998244353.ExamplesInput
1
Output
10
Input
2
Output
180 10
| 1
| 10 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', '*1800'] |
D. Infinite Pathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a colored permutation p_1, p_2, \dots, p_n. The i-th element of the permutation has color c_i.Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] \dots where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = \dots).We can also define a multiplication of permutations a and b as permutation c = a \times b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}.Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).It can be proved that the answer always exists.InputThe first line contains single integer T (1 \le T \le 10^4) — the number of test cases.Next 3T lines contain test cases — one per three lines. The first line contains single integer n (1 \le n \le 2 \cdot 10^5) — the size of the permutation.The second line contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n, p_i \neq p_j for i \neq j) — the permutation p.The third line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le n) — the colors of elements of the permutation.It is guaranteed that the total sum of n doesn't exceed 2 \cdot 10^5.OutputPrint T integers — one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.ExampleInput
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
NoteIn the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, \dots is an infinite path.In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, \dots is an infinite path since c_4 = c_8 = 4. | 3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
| 1 5 2 | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'graphs', 'math', 'number theory', '*2200'] |
C. Game with Chipstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has a rectangular Board of size n \times m. Initially, k chips are placed on the board, i-th chip is located in the cell at the intersection of sx_i-th row and sy_i-th column.In one action, Petya can move all the chips to the left, right, down or up by 1 cell.If the chip was in the (x, y) cell, then after the operation: left, its coordinates will be (x, y - 1); right, its coordinates will be (x, y + 1); down, its coordinates will be (x + 1, y); up, its coordinates will be (x - 1, y). If the chip is located by the wall of the board, and the action chosen by Petya moves it towards the wall, then the chip remains in its current position.Note that several chips can be located in the same cell.For each chip, Petya chose the position which it should visit. Note that it's not necessary for a chip to end up in this position.Since Petya does not have a lot of free time, he is ready to do no more than 2nm actions.You have to find out what actions Petya should do so that each chip visits the position that Petya selected for it at least once. Or determine that it is not possible to do this in 2nm actions.InputThe first line contains three integers n, m, k (1 \le n, m, k \le 200) — the number of rows and columns of the board and the number of chips, respectively.The next k lines contains two integers each sx_i, sy_i ( 1 \le sx_i \le n, 1 \le sy_i \le m) — the starting position of the i-th chip.The next k lines contains two integers each fx_i, fy_i ( 1 \le fx_i \le n, 1 \le fy_i \le m) — the position that the i-chip should visit at least once.OutputIn the first line print the number of operations so that each chip visits the position that Petya selected for it at least once.In the second line output the sequence of operations. To indicate operations left, right, down, and up, use the characters L, R, D, U respectively.If the required sequence does not exist, print -1 in the single line.ExamplesInput
3 3 2
1 2
2 1
3 3
3 2
Output
3
DRDInput
5 4 3
3 4
3 1
3 3
5 3
1 3
1 4
Output
9
DDLUUUURR | 3 3 2
1 2
2 1
3 3
3 2
| 3 DRD | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1600'] |
B. Princesses and Princestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe King of Berland Polycarp LXXXIV has n daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are n other kingdoms as well.So Polycarp LXXXIV has enumerated his daughters from 1 to n and the kingdoms from 1 to n. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.For the first daughter he takes the kingdom with the lowest number from her list and marries the daughter to their prince. For the second daughter he takes the kingdom with the lowest number from her list, prince of which hasn't been taken already. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the n-th daughter.For example, let there be 4 daughters and kingdoms, the lists daughters have are [2, 3], [1, 2], [3, 4], [3], respectively. In that case daughter 1 marries the prince of kingdom 2, daughter 2 marries the prince of kingdom 1, daughter 3 marries the prince of kingdom 3, leaving daughter 4 nobody to marry to.Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. Note that this kingdom should not be present in the daughter's list.Polycarp LXXXIV wants to increase the number of married couples.Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.For your and our convenience you are asked to answer t independent test cases.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.Then t test cases follow.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the number of daughters and the number of kingdoms.Each of the next n lines contains the description of each daughter's list. The first integer k (0 \le k \le n) is the number of entries in the i-th daughter's list. After that k distinct integers follow g_i[1], g_i[2], \dots, g_i[k] (1 \le g_i[j] \le n) — the indices of the kingdoms in the list in the increasing order (g_i[1] < g_i[2] < \dots < g_i[k]).It's guaranteed that the total number of daughters over all test cases does not exceed 10^5.It's also guaranteed that the total number of kingdoms in lists over all test cases does not exceed 10^5.OutputFor each test case print the answer to it.Print "IMPROVE" in the first line if Polycarp LXXXIV can add some kingdom to some of his daughter's list so that the total number of married couples increases. The second line then should contain two integers — the index of the daughter and the index of the kingdom Polycarp LXXXIV should add to that daughter's list.If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.Otherwise the only line should contain one word "OPTIMAL".ExampleInput
5
4
2 2 3
2 1 2
2 3 4
1 3
2
0
0
3
3 1 2 3
3 1 2 3
3 1 2 3
1
1 1
4
1 1
1 2
1 3
1 4
Output
IMPROVE
4 4
IMPROVE
1 1
OPTIMAL
OPTIMAL
OPTIMAL
NoteThe first test case is depicted in the statement. Adding the fourth kingdom to the list of the fourth daughter makes her marry the prince of the fourth kingdom.In the second test case any new entry will increase the number of marriages from 0 to 1.In the third and the fourth test cases there is no way to add an entry.In the fifth test case there is no way to change the marriages by adding any entry. | 5
4
2 2 3
2 1 2
2 3 4
1 3
2
0
0
3
3 1 2 3
3 1 2 3
3 1 2 3
1
1 1
4
1 1
1 2
1 3
1 4
| IMPROVE 4 4 IMPROVE 1 1 OPTIMAL OPTIMAL OPTIMAL | 2 seconds | 256 megabytes | ['brute force', 'graphs', 'greedy', '*1200'] |
A. Sum of Odd Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^5) — the number of test cases.The next t lines describe test cases. The only line of the test case contains two integers n and k (1 \le n, k \le 10^7).OutputFor each test case, print the answer — "YES" (without quotes) if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers and "NO" otherwise.ExampleInput
6
3 1
4 2
10 3
10 2
16 4
16 5
Output
YES
YES
NO
YES
YES
NO
NoteIn the first test case, you can represent 3 as 3.In the second test case, the only way to represent 4 is 1+3.In the third test case, you cannot represent 10 as the sum of three distinct positive odd integers.In the fourth test case, you can represent 10 as 3+7, for example.In the fifth test case, you can represent 16 as 1+3+5+7.In the sixth test case, you cannot represent 16 as the sum of five distinct positive odd integers. | 6
3 1
4 2
10 3
10 2
16 4
16 5
| YES YES NO YES YES NO | 2 seconds | 256 megabytes | ['math', '*1100'] |
G. Spiderweb Treestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a graph with n vertices, each of which has it's own point A_i = (x_i, y_i) with integer coordinates, a planar tree if: All points A_1, A_2, \ldots, A_n are different and no three points lie on the same line. The graph is a tree, i.e. there are exactly n-1 edges there exists a path between any pair of vertices. For all pairs of edges (s_1, f_1) and (s_2, f_2), such that s_1 \neq s_2, s_1 \neq f_2, f_1 \neq s_2, and f_1 \neq f_2, the segments A_{s_1} A_{f_1} and A_{s_2} A_{f_2} don't intersect. Imagine a planar tree with n vertices. Consider the convex hull of points A_1, A_2, \ldots, A_n. Let's call this tree a spiderweb tree if for all 1 \leq i \leq n the following statements are true: All leaves (vertices with degree \leq 1) of the tree lie on the border of the convex hull. All vertices on the border of the convex hull are leaves. An example of a spiderweb tree: The points A_3, A_6, A_7, A_4 lie on the convex hull and the leaf vertices of the tree are 3, 6, 7, 4.Refer to the notes for more examples.Let's call the subset S \subset \{1, 2, \ldots, n\} of vertices a subtree of the tree if for all pairs of vertices in S, there exists a path that contains only vertices from S. Note that any subtree of the planar tree is a planar tree.You are given a planar tree with n vertexes. Let's call a partition of the set \{1, 2, \ldots, n\} into non-empty subsets A_1, A_2, \ldots, A_k (i.e. A_i \cap A_j = \emptyset for all 1 \leq i < j \leq k and A_1 \cup A_2 \cup \ldots \cup A_k = \{1, 2, \ldots, n\}) good if for all 1 \leq i \leq k, the subtree A_i is a spiderweb tree. Two partitions are different if there exists some set that lies in one parition, but not the other.Find the number of good partitions. Since this number can be very large, find it modulo 998\,244\,353.InputThe first line contains an integer n (1 \leq n \leq 100) — the number of vertices in the tree.The next n lines each contain two integers x_i, y_i (-10^9 \leq x_i, y_i \leq 10^9) — the coordinates of i-th vertex, A_i.The next n-1 lines contain two integers s, f (1 \leq s, f \leq n) — the edges (s, f) of the tree.It is guaranteed that all given points are different and that no three of them lie at the same line. Additionally, it is guaranteed that the given edges and coordinates of the points describe a planar tree.OutputPrint one integer — the number of good partitions of vertices of the given planar tree, modulo 998\,244\,353.ExamplesInput
4
0 0
0 1
-1 -1
1 -1
1 2
1 3
1 4
Output
5
Input
5
3 2
0 -3
-5 -3
5 -5
4 5
4 2
4 1
5 2
2 3
Output
8
Input
6
4 -5
0 1
-2 8
3 -10
0 -1
-4 -5
2 5
3 2
1 2
4 6
4 2
Output
13
Input
8
0 0
-1 2
-2 5
-5 1
1 3
0 3
2 4
-1 -4
1 2
3 2
5 6
4 2
1 5
5 7
5 8
Output
36
Note The picture for the first sample. In the first test case, all good partitions are: \{1\}, \{2\}, \{3\}, \{4\}; \{1, 2\}, \{3\}, \{4\}; \{1, 3\}, \{2\}, \{4\}; \{1, 4\}, \{2\}, \{3\}; \{1, 2, 3, 4\}. The partition \{1, 2, 3\}, \{4\} isn't good, because the subtree \{1, 2, 3\} isn't spiderweb tree, since the non-leaf vertex 1 lies on the convex hull.The partition \{2, 3, 4\}, \{1\} isn't good, because the subset \{2, 3, 4\} isn't a subtree. The picture for the second sample. In the second test case, the given tree isn't a spiderweb tree, because the leaf vertex 1 doesn't lie on the convex hull. However, the subtree \{2, 3, 4, 5\} is a spiderweb tree. The picture for the third sample. The picture for the fourth sample. In the fourth test case, the partition \{1, 2, 3, 4\}, \{5, 6, 7, 8\} is good because all subsets are spiderweb subtrees. | 4
0 0
0 1
-1 -1
1 -1
1 2
1 3
1 4
| 5 | 1 second | 256 megabytes | ['dp', 'geometry', 'trees', '*3500'] |
F2. Wise Men (Hard Version)time limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved.n wise men live in a beautiful city. Some of them know each other.For each of the n! possible permutations p_1, p_2, \ldots, p_n of the wise men, let's generate a binary string of length n-1: for each 1 \leq i < n set s_i=1 if p_i and p_{i+1} know each other, and s_i=0 otherwise. For all possible 2^{n-1} binary strings, find the number of permutations that produce this binary string.InputThe first line of input contains one integer n (2 \leq n \leq 18) — the number of wise men in the city.The next n lines contain a binary string of length n each, such that the j-th character of the i-th string is equal to '1' if wise man i knows wise man j, and equals '0' otherwise.It is guaranteed that if the i-th man knows the j-th man, then the j-th man knows i-th man and no man knows himself.OutputPrint 2^{n-1} space-separated integers. For each 0 \leq x < 2^{n-1}: Let's consider a string s of length n-1, such that s_i = \lfloor \frac{x}{2^{i-1}} \rfloor \bmod 2 for all 1 \leq i \leq n - 1. The (x+1)-th number should be equal to the required answer for s. ExamplesInput
3
011
101
110
Output
0 0 0 6
Input
4
0101
1000
0001
1010
Output
2 2 6 2 2 6 2 2
NoteIn the first test, each wise man knows each other, so every permutation will produce the string 11.In the second test: If p = \{1, 2, 3, 4\}, the produced string is 101, because wise men 1 and 2 know each other, 2 and 3 don't know each other, and 3 and 4 know each other; If p = \{4, 1, 2, 3\}, the produced string is 110, because wise men 1 and 4 know each other, 1 and 2 know each other and 2, and 3 don't know each other; If p = \{1, 3, 2, 4\}, the produced string is 000, because wise men 1 and 3 don't know each other, 3 and 2 don't know each other, and 2 and 4 don't know each other. | 3
011
101
110
| 0 0 0 6 | 4 seconds | 512 megabytes | ['bitmasks', 'dp', 'math', '*3200'] |
F1. Wise Men (Easy Version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved.n wise men live in a beautiful city. Some of them know each other.For each of the n! possible permutations p_1, p_2, \ldots, p_n of the wise men, let's generate a binary string of length n-1: for each 1 \leq i < n set s_i=1 if p_i and p_{i+1} know each other, and s_i=0 otherwise. For all possible 2^{n-1} binary strings, find the number of permutations that produce this binary string.InputThe first line of input contains one integer n (2 \leq n \leq 14) — the number of wise men in the city.The next n lines contain a binary string of length n each, such that the j-th character of the i-th string is equal to '1' if wise man i knows wise man j, and equals '0' otherwise.It is guaranteed that if the i-th man knows the j-th man, then the j-th man knows i-th man and no man knows himself.OutputPrint 2^{n-1} space-separated integers. For each 0 \leq x < 2^{n-1}: Let's consider a string s of length n-1, such that s_i = \lfloor \frac{x}{2^{i-1}} \rfloor \bmod 2 for all 1 \leq i \leq n - 1. The (x+1)-th number should be equal to the required answer for s. ExamplesInput
3
011
101
110
Output
0 0 0 6
Input
4
0101
1000
0001
1010
Output
2 2 6 2 2 6 2 2
NoteIn the first test, each wise man knows each other, so every permutation will produce the string 11.In the second test: If p = \{1, 2, 3, 4\}, the produced string is 101, because wise men 1 and 2 know each other, 2 and 3 don't know each other, and 3 and 4 know each other; If p = \{4, 1, 2, 3\}, the produced string is 110, because wise men 1 and 4 know each other, 1 and 2 know each other and 2, and 3 don't know each other; If p = \{1, 3, 2, 4\}, the produced string is 000, because wise men 1 and 3 don't know each other, 3 and 2 don't know each other, and 2 and 4 don't know each other. | 3
011
101
110
| 0 0 0 6 | 2 seconds | 512 megabytes | ['bitmasks', 'brute force', 'dp', 'meet-in-the-middle', '*2600'] |
E. Bombstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation, p_1, p_2, \ldots, p_n.Imagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb.For some fixed configuration of bombs, consider the following process. Initially, there is an empty set, A.For each i from 1 to n: Add p_i to A. If the i-th position contains a bomb, remove the largest element in A.After the process is completed, A will be non-empty. The cost of the configuration of bombs equals the largest element in A.You are given another permutation, q_1, q_2, \ldots, q_n.For each 1 \leq i \leq n, find the cost of a configuration of bombs such that there exists a bomb in positions q_1, q_2, \ldots, q_{i-1}. For example, for i=1, you need to find the cost of a configuration without bombs, and for i=n, you need to find the cost of a configuration with bombs in positions q_1, q_2, \ldots, q_{n-1}.InputThe first line contains a single integer, n (2 \leq n \leq 300\,000).The second line contains n distinct integers p_1, p_2, \ldots, p_n (1 \leq p_i \leq n).The third line contains n distinct integers q_1, q_2, \ldots, q_n (1 \leq q_i \leq n).OutputPrint n space-separated integers, such that the i-th of them equals the cost of a configuration of bombs in positions q_1, q_2, \ldots, q_{i-1}.ExamplesInput
3
3 2 1
1 2 3
Output
3 2 1 Input
6
2 3 6 1 5 4
5 2 1 4 6 3
Output
6 5 5 5 4 1 NoteIn the first test: If there are no bombs, A is equal to \{1, 2, 3\} at the end of the process, so the cost of the configuration is 3. If there is one bomb in position 1, A is equal to \{1, 2\} at the end of the process, so the cost of the configuration is 2; If there are two bombs in positions 1 and 2, A is equal to \{1\} at the end of the process, so the cost of the configuration is 1. In the second test:Let's consider the process for i = 4. There are three bombs on positions q_1 = 5, q_2 = 2, and q_3 = 1.At the beginning, A = \{\}. Operation 1: Add p_1 = 2 to A, so A is equal to \{2\}. There exists a bomb in position 1, so we should delete the largest element from A. A is equal to \{\}. Operation 2: Add p_2 = 3 to A, so A is equal to \{3\}. There exists a bomb in position 2, so we should delete the largest element from A. A is equal to \{\}. Operation 3: Add p_3 = 6 to A, so A is equal to \{6\}. There is no bomb in position 3, so we do nothing. Operation 4: Add p_4 = 1 to A, so A is equal to \{1, 6\}. There is no bomb in position 4, so we do nothing. Operation 5: Add p_5 = 5 to A, so A is equal to \{1, 5, 6\}. There exists a bomb in position 5, so we delete the largest element from A. Now, A is equal to \{1, 5\}. Operation 6: Add p_6 = 4 to A, so A is equal to \{1, 4, 5\}. There is no bomb in position 6, so we do nothing. In the end, we have A = \{1, 4, 5\}, so the cost of the configuration is equal to 5. | 3
3 2 1
1 2 3
| 3 2 1 | 3 seconds | 256 megabytes | ['data structures', 'two pointers', '*2400'] |
D2. Prefix-Suffix Palindrome (Hard version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions: The length of t does not exceed the length of s. t is a palindrome. There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s. InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^5), the number of test cases. The next t lines each describe a test case.Each test case is a non-empty string s, consisting of lowercase English letters.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 10^6.OutputFor each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.ExampleInput
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
NoteIn the first test, the string s = "a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because: Its length is 9, which does not exceed the length of the string s, which equals 11. It is a palindrome. "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s". | 5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
| a abcdfdcba xyzyx c abba | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'hashing', 'string suffix structures', 'strings', '*1800'] |
D1. Prefix-Suffix Palindrome (Easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions: The length of t does not exceed the length of s. t is a palindrome. There exists two strings a and b (possibly empty), such that t = a + b ( "+" represents concatenation), and a is prefix of s while b is suffix of s. InputThe input consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 1000), the number of test cases. The next t lines each describe a test case.Each test case is a non-empty string s, consisting of lowercase English letters.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 5000.OutputFor each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.ExampleInput
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
Output
a
abcdfdcba
xyzyx
c
abba
NoteIn the first test, the string s = "a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because: Its length is 9, which does not exceed the length of the string s, which equals 11. It is a palindrome. "abcdfdcba" = "abcdfdc" + "ba", and "abcdfdc" is a prefix of s while "ba" is a suffix of s. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" = "c" + "" and a or b can be empty. The other possible solution for this test is "s". | 5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
| a abcdfdcba xyzyx c abba | 2 seconds | 256 megabytes | ['hashing', 'string suffix structures', 'strings', '*1500'] |
C. Permutation Partitionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_1, p_2, \ldots, p_n of integers from 1 to n and an integer k, such that 1 \leq k \leq n. A permutation means that every number from 1 to n is contained in p exactly once.Let's consider all partitions of this permutation into k disjoint segments. Formally, a partition is a set of segments \{[l_1, r_1], [l_2, r_2], \ldots, [l_k, r_k]\}, such that: 1 \leq l_i \leq r_i \leq n for all 1 \leq i \leq k; For all 1 \leq j \leq n there exists exactly one segment [l_i, r_i], such that l_i \leq j \leq r_i. Two partitions are different if there exists a segment that lies in one partition but not the other.Let's calculate the partition value, defined as \sum\limits_{i=1}^{k} {\max\limits_{l_i \leq j \leq r_i} {p_j}}, for all possible partitions of the permutation into k disjoint segments. Find the maximum possible partition value over all such partitions, and the number of partitions with this value. As the second value can be very large, you should find its remainder when divided by 998\,244\,353.InputThe first line contains two integers, n and k (1 \leq k \leq n \leq 200\,000) — the size of the given permutation and the number of segments in a partition.The second line contains n different integers p_1, p_2, \ldots, p_n (1 \leq p_i \leq n) — the given permutation.OutputPrint two integers — the maximum possible partition value over all partitions of the permutation into k disjoint segments and the number of such partitions for which the partition value is equal to the maximum possible value, modulo 998\,244\,353.Please note that you should only find the second value modulo 998\,244\,353.ExamplesInput
3 2
2 1 3
Output
5 2
Input
5 5
2 1 5 3 4
Output
15 1
Input
7 3
2 7 3 1 5 4 6
Output
18 6
NoteIn the first test, for k = 2, there exists only two valid partitions: \{[1, 1], [2, 3]\} and \{[1, 2], [3, 3]\}. For each partition, the partition value is equal to 2 + 3 = 5. So, the maximum possible value is 5 and the number of partitions is 2.In the third test, for k = 3, the partitions with the maximum possible partition value are \{[1, 2], [3, 5], [6, 7]\}, \{[1, 3], [4, 5], [6, 7]\}, \{[1, 4], [5, 5], [6, 7]\}, \{[1, 2], [3, 6], [7, 7]\}, \{[1, 3], [4, 6], [7, 7]\}, \{[1, 4], [5, 6], [7, 7]\}. For all of them, the partition value is equal to 7 + 5 + 6 = 18. The partition \{[1, 2], [3, 4], [5, 7]\}, however, has the partition value 7 + 3 + 6 = 16. This is not the maximum possible value, so we don't count it. | 3 2
2 1 3
| 5 2 | 1 second | 256 megabytes | ['combinatorics', 'greedy', 'math', '*1300'] |
B. Maximumstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlicia has an array, a_1, a_2, \ldots, a_n, of non-negative integers. For each 1 \leq i \leq n, she has found a non-negative integer x_i = max(0, a_1, \ldots, a_{i-1}). Note that for i=1, x_i = 0.For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.Then, she calculated an array, b_1, b_2, \ldots, b_n: b_i = a_i - x_i.For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, b = \{0-0, 1-0, 2-1, 0-2, 3-2\} = \{0, 1, 1, -2, 1\}.Alicia gives you the values b_1, b_2, \ldots, b_n and asks you to restore the values a_1, a_2, \ldots, a_n. Can you help her solve the problem?InputThe first line contains one integer n (3 \leq n \leq 200\,000) – the number of elements in Alicia's array.The next line contains n integers, b_1, b_2, \ldots, b_n (-10^9 \leq b_i \leq 10^9).It is guaranteed that for the given array b there is a solution a_1, a_2, \ldots, a_n, for all elements of which the following is true: 0 \leq a_i \leq 10^9.OutputPrint n integers, a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9), such that if you calculate x according to the statement, b_1 will be equal to a_1 - x_1, b_2 will be equal to a_2 - x_2, ..., and b_n will be equal to a_n - x_n.It is guaranteed that there exists at least one solution for the given tests. It can be shown that the solution is unique.ExamplesInput
5
0 1 1 -2 1
Output
0 1 2 0 3 Input
3
1000 999999000 -1000000000
Output
1000 1000000000 0 Input
5
2 1 2 2 3
Output
2 3 5 7 10 NoteThe first test was described in the problem statement.In the second test, if Alicia had an array a = \{1000, 1000000000, 0\}, then x = \{0, 1000, 1000000000\} and b = \{1000-0, 1000000000-1000, 0-1000000000\} = \{1000, 999999000, -1000000000\}. | 5
0 1 1 -2 1
| 0 1 2 0 3 | 1 second | 256 megabytes | ['implementation', 'math', '*900'] |
A. Bad Ugly Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers:In the decimal representation of s: s > 0, s consists of n digits, no digit in s equals 0, s is not divisible by any of it's digits. InputThe input consists of multiple test cases. The first line of the input contains a single integer t (1 \leq t \leq 400), the number of test cases. The next t lines each describe a test case.Each test case contains one positive integer n (1 \leq n \leq 10^5).It is guaranteed that the sum of n for all test cases does not exceed 10^5.OutputFor each test case, print an integer s which satisfies the conditions described above, or "-1" (without quotes), if no such number exists. If there are multiple possible solutions for s, print any solution.ExampleInput
4
1
2
3
4
Output
-1
57
239
6789
NoteIn the first test case, there are no possible solutions for s consisting of one digit, because any such solution is divisible by itself.For the second test case, the possible solutions are: 23, 27, 29, 34, 37, 38, 43, 46, 47, 49, 53, 54, 56, 57, 58, 59, 67, 68, 69, 73, 74, 76, 78, 79, 83, 86, 87, 89, 94, 97, and 98.For the third test case, one possible solution is 239 because 239 is not divisible by 2, 3 or 9 and has three digits (none of which equals zero). | 4
1
2
3
4
| -1 57 239 6789 | 1 second | 256 megabytes | ['constructive algorithms', 'number theory', '*1000'] |
F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph, and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with n vertices, you can choose to either: find an independent set that has exactly \lceil\sqrt{n}\rceil vertices. find a simple cycle of length at least \lceil\sqrt{n}\rceil. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers n and m (5 \le n \le 10^5, n-1 \le m \le 2 \cdot 10^5) — the number of vertices and edges in the graph.Each of the next m lines contains two space-separated integers u and v (1 \le u,v \le n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing \lceil\sqrt{n}\rceil distinct integers not exceeding n, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInput
6 6
1 3
3 4
4 2
2 6
5 6
5 1
Output
1
1 6 4Input
6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
Output
2
4
1 5 2 4Input
5 4
1 2
1 3
2 4
2 5
Output
1
3 4 5 NoteIn the first sample:Notice that you can solve either problem, so printing the cycle 2-4-3-1-5-6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2-5-6, for example, is acceptable.In the third sample: | 6 6
1 3
3 4
4 2
2 6
5 6
5 1
| 1 1 6 4 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', '*2500'] |
E. Ehab's REAL Number Theory Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square.A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements.InputThe first line contains an integer n (1 \le n \le 10^5) — the length of a.The second line contains n integers a_1, a_2, \ldots, a_{n} (1 \le a_i \le 10^6) — the elements of the array a.OutputOutput the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1".ExamplesInput
3
1 4 6
Output
1Input
4
2 3 6 6
Output
2Input
3
6 15 10
Output
3Input
4
2 3 5 7
Output
-1NoteIn the first sample, you can choose a subsequence [1].In the second sample, you can choose a subsequence [6, 6].In the third sample, you can choose a subsequence [6, 15, 10].In the fourth sample, there is no such subsequence. | 3
1 4 6
| 1 | 3 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'graphs', 'number theory', 'shortest paths', '*2600'] |
D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers u and v, find the shortest array such that bitwise-xor of its elements is u, and the sum of its elements is v.InputThe only line contains 2 integers u and v (0 \le u,v \le 10^{18}).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, n, representing the length of the desired array. The next line should contain n positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInput
2 4
Output
2
3 1Input
1 3
Output
3
1 1 1Input
8 5
Output
-1Input
0 0
Output
0NoteIn the first sample, 3\oplus 1 = 2 and 3 + 1 = 4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty. | 2 4
| 2 3 1 | 1 second | 256 megabytes | ['bitmasks', 'constructive algorithms', 'greedy', 'number theory', '*1700'] |
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 0 and n-2 inclusive. All the written labels are distinct. The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v.InputThe first line contains the integer n (2 \le n \le 10^5) — the number of nodes in the tree.Each of the next n-1 lines contains two space-separated integers u and v (1 \le u,v \le n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.OutputOutput n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order).ExamplesInput
3
1 2
1 3
Output
0
1
Input
6
1 2
1 3
2 4
2 5
5 6
Output
0
3
2
4
1NoteThe tree from the second sample: | 3
1 2
1 3
| 0 1 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'greedy', 'trees', '*1500'] |
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array a of length n. He has just enough free time to make a new array consisting of n copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer t — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 10^5) — the number of elements in the array a.The second line contains n space-separated integers a_1, a_2, \ldots, a_{n} (1 \le a_i \le 10^9) — the elements of the array a.The sum of n across the test cases doesn't exceed 10^5.OutputFor each testcase, output the length of the longest increasing subsequence of a if you concatenate it to itself n times.ExampleInput
2
3
3 2 1
6
3 1 4 1 5 9
Output
3
5
NoteIn the first sample, the new array is [3,2,\textbf{1},3,\textbf{2},1,\textbf{3},2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9]. | 2
3
3 2 1
6
3 1 4 1 5 9
| 3 5 | 1 second | 256 megabytes | ['greedy', 'implementation', '*800'] |
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it.It's guaranteed that the solution always exists. If there are several such pairs (a, b), you can output any of them.InputThe first line contains a single integer t (1 \le t \le 100) — the number of testcases.Each testcase consists of one line containing a single integer, x (2 \le x \le 10^9).OutputFor each testcase, output a pair of positive integers a and b (1 \le a, b \le 10^9) such that GCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a, b), you can output any of them.ExampleInput
2
2
14
Output
1 1
6 4
NoteIn the first testcase of the sample, GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14. | 2
2
14
| 1 1 6 4 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'number theory', '*800'] |
F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black).You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b.InputThe first line of the input contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.The second line of the input contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 1), where a_i is the color of the i-th vertex.Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 \le u_i, v_i \le n, u_i \ne v_i).It is guaranteed that the given edges form a tree.OutputPrint n integers res_1, res_2, \dots, res_n, where res_i is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex i.ExamplesInput
9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
Output
2 2 2 2 2 1 1 0 2
Input
4
0 0 1 0
1 2
1 3
1 4
Output
0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 and 3. | 9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
| 2 2 2 2 2 1 1 0 2 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'trees', '*1800'] |
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are h hours in a day. Vova will sleep exactly n times. The i-th time he will sleep exactly after a_i hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 0). Each time Vova sleeps exactly one day (in other words, h hours).Vova thinks that the i-th sleeping time is good if he starts to sleep between hours l and r inclusive.Vova can control himself and before the i-th time can choose between two options: go to sleep after a_i hours or after a_i - 1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n, h, l and r (1 \le n \le 2000, 3 \le h \le 2000, 0 \le l \le r < h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i < h), where a_i is the number of hours after which Vova goes to sleep the i-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInput
7 24 21 23
16 17 14 20 20 11 22
Output
3
NoteThe maximum number of good times in the example is 3.The story starts from t=0. Then Vova goes to sleep after a_1 - 1 hours, now the time is 15. This time is not good. Then Vova goes to sleep after a_2 - 1 hours, now the time is 15 + 16 = 7. This time is also not good. Then Vova goes to sleep after a_3 hours, now the time is 7 + 14 = 21. This time is good. Then Vova goes to sleep after a_4 - 1 hours, now the time is 21 + 19 = 16. This time is not good. Then Vova goes to sleep after a_5 hours, now the time is 16 + 20 = 12. This time is not good. Then Vova goes to sleep after a_6 hours, now the time is 12 + 11 = 23. This time is good. Then Vova goes to sleep after a_7 hours, now the time is 23 + 22 = 21. This time is also good. | 7 24 21 23
16 17 14 20 20 11 22
| 3 | 2 seconds | 256 megabytes | ['dp', 'implementation', '*1700'] |
D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students.The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of topics.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the interestingness of the i-th topic for the teacher.The third line of the input contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^9), where b_i is the interestingness of the i-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInput
5
4 8 2 6 2
4 5 4 1 3
Output
7
Input
4
1 3 2 4
1 3 2 4
Output
0
| 5
4 8 2 6 2
4 5 4 1 3
| 7 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'sortings', 'two pointers', '*1400'] |
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s = s_1 s_2 \ldots s_n consisting of n characters (to be more precise, the frog initially stays at the cell 0). Each character of s is either 'L' or 'R'. It means that if the frog is staying at the i-th cell and the i-th character is 'L', the frog can jump only to the left. If the frog is staying at the i-th cell and the i-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 0.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1-th cell. The frog chooses some positive integer value d before the first jump (and cannot change it later) and jumps by no more than d cells at once. I.e. if the i-th character is 'L' then the frog can jump to any cell in a range [max(0, i - d); i - 1], and if the i-th character is 'R' then the frog can jump to any cell in a range [i + 1; min(n + 1; i + d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of d such that the frog can reach the cell n+1 from the cell 0 if it can jump by no more than d cells at once. It is guaranteed that it is always possible to reach n+1 from 0.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.The next t lines describe test cases. The i-th test case is described as a string s consisting of at least 1 and at most 2 \cdot 10^5 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2 \cdot 10^5 (\sum |s| \le 2 \cdot 10^5).OutputFor each test case, print the answer — the minimum possible value of d such that the frog can reach the cell n+1 from the cell 0 if it jumps by no more than d at once.ExampleInput
6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
Output
3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example, the frog can only jump directly from 0 to n+1.In the third test case of the example, the frog can choose d=3, jump to the cell 3 from the cell 0 and then to the cell 4 from the cell 3.In the fourth test case of the example, the frog can choose d=1 and jump 5 times to the right.In the fifth test case of the example, the frog can only jump directly from 0 to n+1.In the sixth test case of the example, the frog can choose d=1 and jump 2 times to the right. | 6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
| 3 2 3 1 7 1 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', 'greedy', 'implementation', '*1100'] |
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers.Your task is to determine if a has some subsequence of length at least 3 that is a palindrome.Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without changing the order of remaining elements. For example, [2], [1, 2, 1, 3] and [2, 3] are subsequences of [1, 2, 1, 3], but [1, 1, 2] and [4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array a of length n is the palindrome if a_i = a_{n - i - 1} for all i from 1 to n. For example, arrays [1234], [1, 2, 1], [1, 3, 2, 2, 3, 1] and [10, 100, 10] are palindromes, but arrays [1, 2] and [1, 2, 3, 1] are not.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases.Next 2t lines describe test cases. The first line of the test case contains one integer n (3 \le n \le 5000) — the length of a. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n), where a_i is the i-th element of a.It is guaranteed that the sum of n over all test cases does not exceed 5000 (\sum n \le 5000).OutputFor each test case, print the answer — "YES" (without quotes) if a has some subsequence of length at least 3 that is a palindrome and "NO" otherwise.ExampleInput
5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
Output
YES
YES
NO
YES
NO
NoteIn the first test case of the example, the array a has a subsequence [1, 2, 1] which is a palindrome.In the second test case of the example, the array a has two subsequences of length 3 which are palindromes: [2, 3, 2] and [2, 2, 2].In the third test case of the example, the array a has no subsequences of length at least 3 which are palindromes.In the fourth test case of the example, the array a has one subsequence of length 4 which is a palindrome: [1, 2, 2, 1] (and has two subsequences of length 3 which are palindromes: both are [1, 2, 1]).In the fifth test case of the example, the array a has no subsequences of length at least 3 which are palindromes. | 5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
| YES YES NO YES NO | 2 seconds | 256 megabytes | ['brute force', 'strings', '*1100'] |
A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 \times 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one a_i is greater than 0: You place one figure 2 \times 1 (choose some i from 1 to n and replace a_i with a_i + 2); then, while all a_i are greater than zero, replace each a_i with a_i - 1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases.The next 2t lines describe test cases. The first line of the test case contains one integer n (1 \le n \le 100) — the number of columns in the Tetris field. The second line of the test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100), where a_i is the initial height of the i-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInput
4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
Output
YES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process, the field becomes [2, 0, 2]. Then place the figure in the second column and after the second step of the process, the field becomes [0, 0, 0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0, 2]. Then place the figure in the first column and after the second step of the process, the field becomes [0, 0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102] after the first step of the process, and then the field becomes [0] after the second step of the process. | 4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
| YES NO YES YES | 2 seconds | 256 megabytes | ['implementation', 'number theory', '*900'] |
B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n and array b of length m both consisting of only integers 0 and 1. Consider a matrix c of size n \times m formed by following rule: c_{i, j} = a_i \cdot b_j (i.e. a_i multiplied by b_j). It's easy to see that c consists of only zeroes and ones too.How many subrectangles of size (area) k consisting only of ones are there in c?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x_1, x_2, y_1, y_2 (1 \le x_1 \le x_2 \le n, 1 \le y_1 \le y_2 \le m) a subrectangle c[x_1 \dots x_2][y_1 \dots y_2] is an intersection of the rows x_1, x_1+1, x_1+2, \dots, x_2 and the columns y_1, y_1+1, y_1+2, \dots, y_2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers n, m and k (1 \leq n, m \leq 40\,000, 1 \leq k \leq n \cdot m), length of array a, length of array b and required size of subrectangles.The second line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 1), elements of a.The third line contains m integers b_1, b_2, \ldots, b_m (0 \leq b_i \leq 1), elements of b.OutputOutput single integer — the number of subrectangles of c with size (area) k consisting only of ones.ExamplesInput
3 3 2
1 0 1
1 1 1
Output
4
Input
3 5 4
1 1 1
1 1 1 1 1
Output
14
NoteIn first example matrix c is: There are 4 subrectangles of size 2 consisting of only ones in it: In second example matrix c is: | 3 3 2
1 0 1
1 1 1
| 4 | 1 second | 512 megabytes | ['binary search', 'greedy', 'implementation', '*1500'] |
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer t (1 \leq t \leq 100), number of test cases to solve. Descriptions of t test cases follow.A description of each test case consists of two lines. The first line contains a single integer n (1 \leq n \leq 100), length of array a.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 100), elements of a. The given array a can contain equal values (duplicates).OutputFor each test case output -1 if there is no such subset of elements. Otherwise output positive integer k, number of elements in the required subset. Then output k distinct integers (1 \leq p_i \leq n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInput
3
3
1 4 3
1
15
2
3 5
Output
1
2
-1
2
1 2
NoteThere are three test cases in the example.In the first test case, you can choose the subset consisting of only the second element. Its sum is 4 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum. | 3
3
1 4 3
1
15
2
3 5
| 1 2 -1 2 1 2 | 1 second | 512 megabytes | ['brute force', 'dp', 'greedy', 'implementation', '*800'] |
F. Assigning Farestime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMayor of city M. decided to launch several new metro lines during 2020. Since the city has a very limited budget, it was decided not to dig new tunnels but to use the existing underground network.The tunnel system of the city M. consists of n metro stations. The stations are connected with n - 1 bidirectional tunnels. Between every two stations v and u there is exactly one simple path. Each metro line the mayor wants to create is a simple path between stations a_i and b_i. Metro lines can intersects freely, that is, they can share common stations or even common tunnels. However, it's not yet decided which of two directions each line will go. More precisely, between the stations a_i and b_i the trains will go either from a_i to b_i, or from b_i to a_i, but not simultaneously.The city M uses complicated faring rules. Each station is assigned with a positive integer c_i — the fare zone of the station. The cost of travel from v to u is defined as c_u - c_v roubles. Of course, such travel only allowed in case there is a metro line, the trains on which go from v to u. Mayor doesn't want to have any travels with a negative cost, so it was decided to assign directions of metro lines and station fare zones in such a way, that fare zones are strictly increasing during any travel on any metro line.Mayor wants firstly assign each station a fare zone and then choose a lines direction, such that all fare zones are increasing along any line. In connection with the approaching celebration of the day of the city, the mayor wants to assign fare zones so that the maximum c_i will be as low as possible. Please help mayor to design a new assignment or determine if it's impossible to do. Please note that you only need to assign the fare zones optimally, you don't need to print lines' directions. This way, you solution will be considered correct if there will be a way to assign directions of every metro line, so that the fare zones will be strictly increasing along any movement of the trains.InputThe first line contains an integers n, m (2 \le n, \le 500\,000,\ 1 \le m \le 500\,000) — the number of stations in the city and the number of metro lines.Each of the following n-1 lines describes another metro tunnel. Each tunnel is described with integers v_i, u_i (1 \le v_i,\ u_i \le n, v_i \ne u_i). It's guaranteed, that there is exactly one simple path between any two stations.Each of the following m lines describes another metro line. Each line is described with integers a_i, b_i (1 \le a_i,\ b_i \le n, a_i \neq b_i).OutputIn the first line print integer k — the maximum fare zone used.In the next line print integers c_1, c_2, \ldots, c_n (1 \le c_i \le k) — stations' fare zones. In case there are several possible answers, print any of them. In case it's impossible to assign fare zones, print "-1".ExamplesInput
3 1
1 2
2 3
1 3
Output
3
1 2 3
Input
4 3
1 2
1 3
1 4
2 3
2 4
3 4
Output
-1
Input
7 5
3 4
4 2
2 5
5 1
2 6
4 7
1 3
6 7
3 7
2 1
3 6
Output
-1
NoteIn the first example, line 1 \rightarrow 3 goes through the stations 1, 2, 3 in this order. In this order the fare zones of the stations are increasing. Since this line has 3 stations, at least three fare zones are needed. So the answer 1, 2, 3 is optimal.In the second example, it's impossible to assign fare zones to be consistent with a metro lines. | 3 1
1 2
2 3
1 3
| 3 1 2 3 | 6 seconds | 512 megabytes | ['dp', 'trees', '*3500'] |
E. Median Mountain Rangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland — is a huge country with diverse geography. One of the most famous natural attractions of Berland is the "Median mountain range". This mountain range is n mountain peaks, located on one straight line and numbered in order of 1 to n. The height of the i-th mountain top is a_i. "Median mountain range" is famous for the so called alignment of mountain peaks happening to it every day. At the moment of alignment simultaneously for each mountain from 2 to n - 1 its height becomes equal to the median height among it and two neighboring mountains. Formally, if before the alignment the heights were equal b_i, then after the alignment new heights a_i are as follows: a_1 = b_1, a_n = b_n and for all i from 2 to n - 1 a_i = \texttt{median}(b_{i-1}, b_i, b_{i+1}). The median of three integers is the second largest number among them. For example, \texttt{median}(5,1,2) = 2, and \texttt{median}(4,2,4) = 4.Recently, Berland scientists have proved that whatever are the current heights of the mountains, the alignment process will stabilize sooner or later, i.e. at some point the altitude of the mountains won't changing after the alignment any more. The government of Berland wants to understand how soon it will happen, i.e. to find the value of c — how many alignments will occur, which will change the height of at least one mountain. Also, the government of Berland needs to determine the heights of the mountains after c alignments, that is, find out what heights of the mountains stay forever. Help scientists solve this important problem!InputThe first line contains integers n (1 \le n \le 500\,000) — the number of mountains.The second line contains integers a_1, a_2, a_3, \ldots, a_n (1 \le a_i \le 10^9) — current heights of the mountains.OutputIn the first line print c — the number of alignments, which change the height of at least one mountain.In the second line print n integers — the final heights of the mountains after c alignments.ExamplesInput
5
1 2 1 2 1
Output
2
1 1 1 1 1
Input
6
1 3 2 5 4 6
Output
1
1 2 3 4 5 6
Input
6
1 1 2 2 1 1
Output
0
1 1 2 2 1 1
NoteIn the first example, the heights of the mountains at index 1 and 5 never change. Since the median of 1, 2, 1 is 1, the second and the fourth mountains will have height 1 after the first alignment, and since the median of 2, 1, 2 is 2, the third mountain will have height 2 after the first alignment. This way, after one alignment the heights are 1, 1, 2, 1, 1. After the second alignment the heights change into 1, 1, 1, 1, 1 and never change from now on, so there are only 2 alignments changing the mountain heights.In the third examples the alignment doesn't change any mountain height, so the number of alignments changing any height is 0. | 5
1 2 1 2 1
| 2 1 1 1 1 1 | 2 seconds | 512 megabytes | ['data structures', '*3300'] |
D. Reality Showtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA popular reality show is recruiting a new cast for the third season! n candidates numbered from 1 to n have been interviewed. The candidate i has aggressiveness level l_i, and recruiting this candidate will cost the show s_i roubles.The show host reviewes applications of all candidates from i=1 to i=n by increasing of their indices, and for each of them she decides whether to recruit this candidate or not. If aggressiveness level of the candidate i is strictly higher than that of any already accepted candidates, then the candidate i will definitely be rejected. Otherwise the host may accept or reject this candidate at her own discretion. The host wants to choose the cast so that to maximize the total profit.The show makes revenue as follows. For each aggressiveness level v a corresponding profitability value c_v is specified, which can be positive as well as negative. All recruited participants enter the stage one by one by increasing of their indices. When the participant i enters the stage, events proceed as follows: The show makes c_{l_i} roubles, where l_i is initial aggressiveness level of the participant i. If there are two participants with the same aggressiveness level on stage, they immediately start a fight. The outcome of this is: the defeated participant is hospitalized and leaves the show. aggressiveness level of the victorious participant is increased by one, and the show makes c_t roubles, where t is the new aggressiveness level. The fights continue until all participants on stage have distinct aggressiveness levels. It is allowed to select an empty set of participants (to choose neither of the candidates).The host wants to recruit the cast so that the total profit is maximized. The profit is calculated as the total revenue from the events on stage, less the total expenses to recruit all accepted participants (that is, their total s_i). Help the host to make the show as profitable as possible.InputThe first line contains two integers n and m (1 \le n, m \le 2000) — the number of candidates and an upper bound for initial aggressiveness levels.The second line contains n integers l_i (1 \le l_i \le m) — initial aggressiveness levels of all candidates.The third line contains n integers s_i (0 \le s_i \le 5000) — the costs (in roubles) to recruit each of the candidates.The fourth line contains n + m integers c_i (|c_i| \le 5000) — profitability for each aggrressiveness level.It is guaranteed that aggressiveness level of any participant can never exceed n + m under given conditions.OutputPrint a single integer — the largest profit of the show.ExamplesInput
5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
Output
6
Input
2 2
1 2
0 0
2 1 -100 -100
Output
2
Input
5 4
4 3 2 1 1
0 2 6 7 4
12 12 12 6 -3 -5 3 10 -4
Output
62
NoteIn the first sample case it is optimal to recruit candidates 1, 2, 3, 5. Then the show will pay 1 + 2 + 1 + 1 = 5 roubles for recruitment. The events on stage will proceed as follows: a participant with aggressiveness level 4 enters the stage, the show makes 4 roubles; a participant with aggressiveness level 3 enters the stage, the show makes 3 roubles; a participant with aggressiveness level 1 enters the stage, the show makes 1 rouble; a participant with aggressiveness level 1 enters the stage, the show makes 1 roubles, a fight starts. One of the participants leaves, the other one increases his aggressiveness level to 2. The show will make extra 2 roubles for this. Total revenue of the show will be 4 + 3 + 1 + 1 + 2=11 roubles, and the profit is 11 - 5 = 6 roubles.In the second sample case it is impossible to recruit both candidates since the second one has higher aggressiveness, thus it is better to recruit the candidate 1. | 5 4
4 3 1 2 1
1 2 1 2 1
1 2 3 4 5 6 7 8 9
| 6 | 2 seconds | 512 megabytes | ['bitmasks', 'dp', '*2800'] |
C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left half we define N(S) as the set of all vertices of the right half adjacent to at least one vertex in S, and f(S) as the sum of all numbers in vertices of N(S). Find the greatest common divisor of f(S) for all possible non-empty subsets S (assume that GCD of empty set is 0).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer t (1 \leq t \leq 500\,000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers n and m (1~\leq~n,~m~\leq~500\,000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains n integers c_i (1 \leq c_i \leq 10^{12}). The i-th number describes the integer in the vertex i of the right half of the graph.Each of the following m lines contains a pair of integers u_i and v_i (1 \leq u_i, v_i \leq n), describing an edge between the vertex u_i of the left half and the vertex v_i of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of n across all test cases does not exceed 500\,000, and the total value of m across all test cases does not exceed 500\,000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInput
3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
Output
2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer g such that all elements of the set are divisible by g.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S) for any non-empty subset is 2, thus the greatest common divisor of these values if also equal to 2.In the second sample case the subset \{1\} in the left half is connected to vertices \{1, 2\} of the right half, with the sum of numbers equal to 2, and the subset \{1, 2\} in the left half is connected to vertices \{1, 2, 3\} of the right half, with the sum of numbers equal to 3. Thus, f(\{1\}) = 2, f(\{1, 2\}) = 3, which means that the greatest common divisor of all values of f(S) is 1. | 3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
| 2 1 12 | 2 seconds | 512 megabytes | ['graphs', 'hashing', 'math', 'number theory', '*2300'] |
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute (a_1 + a_2) \oplus (a_1 + a_3) \oplus \ldots \oplus (a_1 + a_n) \\ \oplus (a_2 + a_3) \oplus \ldots \oplus (a_2 + a_n) \\ \ldots \\ \oplus (a_{n-1} + a_n) \\ Here x \oplus y is a bitwise XOR operation (i.e. x ^ y in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer n (2 \leq n \leq 400\,000) — the number of integers in the array.The second line contains integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^7).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInput
2
1 2
Output
3Input
3
1 2 3
Output
2NoteIn the first sample case there is only one sum 1 + 2 = 3.In the second sample case there are three sums: 1 + 2 = 3, 1 + 3 = 4, 2 + 3 = 5. In binary they are represented as 011_2 \oplus 100_2 \oplus 101_2 = 010_2, thus the answer is 2.\oplus is the bitwise xor operation. To define x \oplus y, consider binary representations of integers x and y. We put the i-th bit of the result to be 1 when exactly one of the i-th bits of x and y is 1. Otherwise, the i-th bit of the result is put to be 0. For example, 0101_2 \, \oplus \, 0011_2 = 0110_2. | 2
1 2
| 3 | 3 seconds | 512 megabytes | ['binary search', 'bitmasks', 'constructive algorithms', 'data structures', 'math', 'sortings', '*2100'] |
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes l nanoseconds, where l is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 2 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer n (1 \le n \le 10^6) — the length of Dima's sequence.The second line contains string of length n, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInput
8
))((())(
Output
6
Input
3
(()
Output
-1
NoteIn the first example we can firstly reorder the segment from first to the fourth character, replacing it with "()()", the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character, replacing it with "()". In the end the sequence will be "()()()()", while the total time spent is 4 + 2 = 6 nanoseconds. | 8
))((())(
| 6 | 1 second | 512 megabytes | ['greedy', '*1300'] |
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of lowercase Latin letters. Let the length of s be |s|. You may perform several operations on this string.In one operation, you can choose some index i and remove the i-th character of s (s_i) if at least one of its adjacent characters is the previous letter in the Latin alphabet for s_i. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index i should satisfy the condition 1 \le i \le |s| during each operation.For the character s_i adjacent characters are s_{i-1} and s_{i+1}. The first and the last characters of s both have only one adjacent character (unless |s| = 1).Consider the following example. Let s= bacabcab. During the first move, you can remove the first character s_1= b because s_2= a. Then the string becomes s= acabcab. During the second move, you can remove the fifth character s_5= c because s_4= b. Then the string becomes s= acabab. During the third move, you can remove the sixth character s_6='b' because s_5= a. Then the string becomes s= acaba. During the fourth move, the only character you can remove is s_4= b, because s_3= a (or s_5= a). The string becomes s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s| (1 \le |s| \le 100) — the length of s.The second line of the input contains one string s consisting of |s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInput
8
bacabcab
Output
4
Input
4
bcda
Output
3
Input
6
abbbbb
Output
5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only, but it can be shown that the maximum possible answer to this test is 4.In the second example, you can remove all but one character of s. The only possible answer follows. During the first move, remove the third character s_3= d, s becomes bca. During the second move, remove the second character s_2= c, s becomes ba. And during the third move, remove the first character s_1= b, s becomes a. | 8
bacabcab
| 4 | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', 'strings', '*1600'] |
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each problem, p_i is an integer not less than 1.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of p_i in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of p_i will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of p_i over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer n (1 \le n \le 100) — the number of problems.The second line contains n integers r_1, r_2, ..., r_n (0 \le r_i \le 1). r_i = 1 means that the "Robo-Coder Inc." robot will solve the i-th problem, r_i = 0 means that it won't solve the i-th problem.The third line contains n integers b_1, b_2, ..., b_n (0 \le b_i \le 1). b_i = 1 means that the "BionicSolver Industries" robot will solve the i-th problem, b_i = 0 means that it won't solve the i-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer -1.Otherwise, print the minimum possible value of \max \limits_{i = 1}^{n} p_i, if all values of p_i are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInput
5
1 1 1 0 0
0 1 1 1 1
Output
3
Input
3
0 0 0
0 0 0
Output
-1
Input
4
1 1 1 1
1 1 1 1
Output
-1
Input
9
1 0 0 0 0 0 0 0 1
0 1 1 0 1 1 1 1 0
Output
4
NoteIn the first example, one of the valid score assignments is p = [3, 1, 3, 1, 1]. Then the "Robo-Coder" gets 7 points, the "BionicSolver" — 6 points.In the second example, both robots get 0 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal. | 5
1 1 1 0 0
0 1 1 1 1
| 3 | 1 second | 256 megabytes | ['greedy', '*900'] |
F. Blocks and Sensorstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp plays a well-known computer game (we won't mention its name). Every object in this game consists of three-dimensional blocks — axis-aligned cubes of size 1 \times 1 \times 1. These blocks are unaffected by gravity, so they can float in the air without support. The blocks are placed in cells of size 1 \times 1 \times 1; each cell either contains exactly one block or is empty. Each cell is represented by its coordinates (x, y, z) (the cell with these coordinates is a cube with opposite corners in (x, y, z) and (x + 1, y + 1, z + 1)) and its contents a_{x, y, z}; if the cell is empty, then a_{x, y, z} = 0, otherwise a_{x, y, z} is equal to the type of the block placed in it (the types are integers from 1 to 2 \cdot 10^5).Polycarp has built a large structure consisting of blocks. This structure can be enclosed in an axis-aligned rectangular parallelepiped of size n \times m \times k, containing all cells (x, y, z) such that x \in [1, n], y \in [1, m], and z \in [1, k]. After that, Polycarp has installed 2nm + 2nk + 2mk sensors around this parallelepiped. A sensor is a special block that sends a ray in some direction and shows the type of the first block that was hit by this ray (except for other sensors). The sensors installed by Polycarp are adjacent to the borders of the parallelepiped, and the rays sent by them are parallel to one of the coordinate axes and directed inside the parallelepiped. More formally, the sensors can be divided into 6 types: there are mk sensors of the first type; each such sensor is installed in (0, y, z), where y \in [1, m] and z \in [1, k], and it sends a ray that is parallel to the Ox axis and has the same direction; there are mk sensors of the second type; each such sensor is installed in (n + 1, y, z), where y \in [1, m] and z \in [1, k], and it sends a ray that is parallel to the Ox axis and has the opposite direction; there are nk sensors of the third type; each such sensor is installed in (x, 0, z), where x \in [1, n] and z \in [1, k], and it sends a ray that is parallel to the Oy axis and has the same direction; there are nk sensors of the fourth type; each such sensor is installed in (x, m + 1, z), where x \in [1, n] and z \in [1, k], and it sends a ray that is parallel to the Oy axis and has the opposite direction; there are nm sensors of the fifth type; each such sensor is installed in (x, y, 0), where x \in [1, n] and y \in [1, m], and it sends a ray that is parallel to the Oz axis and has the same direction; finally, there are nm sensors of the sixth type; each such sensor is installed in (x, y, k + 1), where x \in [1, n] and y \in [1, m], and it sends a ray that is parallel to the Oz axis and has the opposite direction. Polycarp has invited his friend Monocarp to play with him. Of course, as soon as Monocarp saw a large parallelepiped bounded by sensor blocks, he began to wonder what was inside of it. Polycarp didn't want to tell Monocarp the exact shape of the figure, so he provided Monocarp with the data from all sensors and told him to try guessing the contents of the parallelepiped by himself.After some hours of thinking, Monocarp has no clue about what's inside the sensor-bounded space. But he does not want to give up, so he decided to ask for help. Can you write a program that will analyze the sensor data and construct any figure that is consistent with it?InputThe first line contains three integers n, m and k (1 \le n, m, k \le 2 \cdot 10^5, nmk \le 2 \cdot 10^5) — the dimensions of the parallelepiped.Then the sensor data follows. For each sensor, its data is either 0, if the ray emitted from it reaches the opposite sensor (there are no blocks in between), or an integer from 1 to 2 \cdot 10^5 denoting the type of the first block hit by the ray. The data is divided into 6 sections (one for each type of sensors), each consecutive pair of sections is separated by a blank line, and the first section is separated by a blank line from the first line of the input.The first section consists of m lines containing k integers each. The j-th integer in the i-th line is the data from the sensor installed in (0, i, j).The second section consists of m lines containing k integers each. The j-th integer in the i-th line is the data from the sensor installed in (n + 1, i, j).The third section consists of n lines containing k integers each. The j-th integer in the i-th line is the data from the sensor installed in (i, 0, j).The fourth section consists of n lines containing k integers each. The j-th integer in the i-th line is the data from the sensor installed in (i, m + 1, j).The fifth section consists of n lines containing m integers each. The j-th integer in the i-th line is the data from the sensor installed in (i, j, 0).Finally, the sixth section consists of n lines containing m integers each. The j-th integer in the i-th line is the data from the sensor installed in (i, j, k + 1).OutputIf the information from the input is inconsistent, print one integer -1.Otherwise, print the figure inside the parallelepiped as follows. The output should consist of nmk integers: a_{1, 1, 1}, a_{1, 1, 2}, ..., a_{1, 1, k}, a_{1, 2, 1}, ..., a_{1, 2, k}, ..., a_{1, m, k}, a_{2, 1, 1}, ..., a_{n, m, k}, where a_{i, j, k} is the type of the block in (i, j, k), or 0 if there is no block there. If there are multiple figures consistent with sensor data, describe any of them.For your convenience, the sample output is formatted as follows: there are n separate sections for blocks having x = 1, x = 2, ..., x = n; each section consists of m lines containing k integers each. Note that this type of output is acceptable, but you may print the integers with any other formatting instead (even all integers on the same line), only their order matters.ExamplesInput
4 3 2
1 4
3 2
6 5
1 4
3 2
6 7
1 4
1 4
0 0
0 7
6 5
6 5
0 0
0 7
1 3 6
1 3 6
0 0 0
0 0 7
4 3 5
4 2 5
0 0 0
0 0 7
Output
1 4
3 0
6 5
1 4
3 2
6 5
0 0
0 0
0 0
0 0
0 0
0 7
Input
1 1 1
0
0
0
0
0
0
Output
0
Input
1 1 1
0
0
1337
0
0
0
Output
-1
Input
1 1 1
1337
1337
1337
1337
1337
1337
Output
1337
| 4 3 2
1 4
3 2
6 5
1 4
3 2
6 7
1 4
1 4
0 0
0 7
6 5
6 5
0 0
0 7
1 3 6
1 3 6
0 0 0
0 0 7
4 3 5
4 2 5
0 0 0
0 0 7
| 1 4 3 0 6 5 1 4 3 2 6 5 0 0 0 0 0 0 0 0 0 0 0 7 | 3 seconds | 512 megabytes | ['brute force', '*3500'] |
E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n cities in Treeland connected with n - 1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are k_i virus species in the i-th scenario. Let us denote v_j the initial city for the virus j, and s_j the propagation speed of the virus j. The spread of the viruses happens in turns: first virus 1 spreads, followed by virus 2, and so on. After virus k_i spreads, the process starts again from virus 1.A spread turn of virus j proceeds as follows. For each city x not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus j if and only if there is such a city y that: city y was infected with virus j at the start of the turn; the path between cities x and y contains at most s_j edges; all cities on the path between cities x and y (excluding y) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process q independent scenarios. Each scenario is described by k_i virus species and m_i important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of cities in Treeland.The following n - 1 lines describe the roads. The i-th of these lines contains two integers x_i and y_i (1 \leq x_i, y_i \leq n) — indices of cities connecting by the i-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer q (1 \leq q \leq 2 \cdot 10^5) — the number of infection scenarios. q scenario descriptions follow.The description of the i-th scenario starts with a line containing two integers k_i and m_i (1 \leq k_i, m_i \leq n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that \sum_{i = 1}^ q k_i and \sum_{i = 1}^ q m_i do not exceed 2 \cdot 10^5.The following k_i lines describe the virus species. The j-th of these lines contains two integers v_j and s_j (1 \leq v_j \leq n, 1 \leq s_j \leq 10^6) – the initial city and the propagation speed of the virus species j. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains m_i distinct integers u_1, \ldots, u_{m_i} (1 \leq u_j \leq n) — indices of important cities.OutputPrint q lines. The i-th line should contain m_i integers — indices of virus species that cities u_1, \ldots, u_{m_i} are infected with at the end of the i-th scenario.ExampleInput
7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
Output
1 2
1 1
1 1 1
| 7
1 2
1 3
2 4
2 5
3 6
3 7
3
2 2
4 1
7 1
1 3
2 2
4 3
7 1
1 3
3 3
1 1
4 100
7 100
1 2 3
| 1 2 1 1 1 1 1 | 3 seconds | 512 megabytes | ['data structures', 'dfs and similar', 'dp', 'shortest paths', 'trees', '*3000'] |
D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string s starting from the l-th character and ending with the r-th character as s[l \dots r]. The characters of each string are numbered from 1.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string a is considered reachable from binary string b if there exists a sequence s_1, s_2, ..., s_k such that s_1 = a, s_k = b, and for every i \in [1, k - 1], s_i can be transformed into s_{i + 1} using exactly one operation. Note that k can be equal to 1, i. e., every string is reachable from itself.You are given a string t and q queries to it. Each query consists of three integers l_1, l_2 and len. To answer each query, you have to determine whether t[l_1 \dots l_1 + len - 1] is reachable from t[l_2 \dots l_2 + len - 1].InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the length of string t.The second line contains one string t (|t| = n). Each character of t is either 0 or 1.The third line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Then q lines follow, each line represents a query. The i-th line contains three integers l_1, l_2 and len (1 \le l_1, l_2 \le |t|, 1 \le len \le |t| - \max(l_1, l_2) + 1) for the i-th query.OutputFor each query, print either YES if t[l_1 \dots l_1 + len - 1] is reachable from t[l_2 \dots l_2 + len - 1], or NO otherwise. You may print each letter in any register.ExampleInput
5
11011
3
1 3 3
1 4 2
1 2 3
Output
Yes
Yes
No
| 5
11011
3
1 3 3
1 4 2
1 2 3
| Yes Yes No | 3 seconds | 256 megabytes | ['data structures', 'hashing', 'strings', '*2500'] |
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense modifier b_j and is worth cb_j coins.After choosing his equipment Roma can proceed to defeat some monsters. There are p monsters he can try to defeat. Monster k has defense x_k, attack y_k and possesses z_k coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster k can be defeated with a weapon i and an armor set j if a_i > x_k and b_j > y_k. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers n, m, and p (1 \leq n, m, p \leq 2 \cdot 10^5) — the number of available weapons, armor sets and monsters respectively.The following n lines describe available weapons. The i-th of these lines contains two integers a_i and ca_i (1 \leq a_i \leq 10^6, 1 \leq ca_i \leq 10^9) — the attack modifier and the cost of the weapon i.The following m lines describe available armor sets. The j-th of these lines contains two integers b_j and cb_j (1 \leq b_j \leq 10^6, 1 \leq cb_j \leq 10^9) — the defense modifier and the cost of the armor set j.The following p lines describe monsters. The k-th of these lines contains three integers x_k, y_k, z_k (1 \leq x_k, y_k \leq 10^6, 1 \leq z_k \leq 10^3) — defense, attack and the number of coins of the monster k.OutputPrint a single integer — the maximum profit of the grind.ExampleInput
2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
Output
1
| 2 3 3
2 3
4 7
2 4
3 2
5 11
1 2 4
2 1 6
3 4 6
| 1 | 2 seconds | 512 megabytes | ['brute force', 'data structures', 'sortings', '*2000'] |
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of n intersections, numbered from 1 to n and connected by m one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection v to another intersection u is the path that starts in v, ends in u and has the minimum length among all such paths.Polycarp lives near the intersection s and works in a building near the intersection t. Every day he gets from s to t by car. Today he has chosen the following path to his workplace: p_1, p_2, ..., p_k, where p_1 = s, p_k = t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from s to t.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection s, the system chooses some shortest path from s to t and shows it to Polycarp. Let's denote the next intersection in the chosen path as v. If Polycarp chooses to drive along the road from s to v, then the navigator shows him the same shortest path (obviously, starting from v as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection w instead, the navigator rebuilds the path: as soon as Polycarp arrives at w, the navigation system chooses some shortest path from w to t and shows it to Polycarp. The same process continues until Polycarp arrives at t: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1, 2, 3, 4] (s = 1, t = 4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 1, the system chooses some shortest path from 1 to 4. There is only one such path, it is [1, 5, 4]; Polycarp chooses to drive to 2, which is not along the path chosen by the system. When Polycarp arrives at 2, the navigator rebuilds the path by choosing some shortest path from 2 to 4, for example, [2, 6, 4] (note that it could choose [2, 3, 4]); Polycarp chooses to drive to 3, which is not along the path chosen by the system. When Polycarp arrives at 3, the navigator rebuilds the path by choosing the only shortest path from 3 to 4, which is [3, 4]; Polycarp arrives at 4 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 2 rebuilds in this scenario. Note that if the system chose [2, 3, 4] instead of [2, 6, 4] during the second step, there would be only 1 rebuild (since Polycarp goes along the path, so the system maintains the path [3, 4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers n and m (2 \le n \le m \le 2 \cdot 10^5) — the number of intersections and one-way roads in Bertown, respectively.Then m lines follow, each describing a road. Each line contains two integers u and v (1 \le u, v \le n, u \ne v) denoting a road from intersection u to intersection v. All roads in Bertown are pairwise distinct, which means that each ordered pair (u, v) appears at most once in these m lines (but if there is a road (u, v), the road (v, u) can also appear).The following line contains one integer k (2 \le k \le n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains k integers p_1, p_2, ..., p_k (1 \le p_i \le n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p_1 is the intersection where Polycarp lives (s = p_1), and p_k is the intersection where Polycarp's workplace is situated (t = p_k). It is guaranteed that for every i \in [1, k - 1] the road from p_i to p_{i + 1} exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInput
6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
Output
1 2
Input
7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
Output
0 0
Input
8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
Output
0 3
| 6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
| 1 2 | 2 seconds | 512 megabytes | ['dfs and similar', 'graphs', 'shortest paths', '*1700'] |
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n. Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to some other city c_2 > c_1, then to some other city c_3 > c_2, and so on, until she chooses to end her journey in some city c_k > c_{k - 1}. So, the sequence of visited cities [c_1, c_2, \dots, c_k] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city i has a beauty value b_i associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities c_i and c_{i + 1}, the condition c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i} must hold.For example, if n = 8 and b = [3, 4, 4, 6, 6, 7, 8, 9], there are several three possible ways to plan a journey: c = [1, 2, 4]; c = [3, 5, 6, 8]; c = [7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of cities in Berland.The second line contains n integers b_1, b_2, ..., b_n (1 \le b_i \le 4 \cdot 10^5), where b_i is the beauty value of the i-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInput
6
10 7 1 9 10 15
Output
26
Input
1
400000
Output
400000
Input
7
8 9 26 11 12 29 14
Output
55
NoteThe optimal journey plan in the first example is c = [2, 4, 5].The optimal journey plan in the second example is c = [1].The optimal journey plan in the third example is c = [3, 6]. | 6
10 7 1 9 10 15
| 26 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', 'math', 'sortings', '*1400'] |
F. Battalion Strengthtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n officers in the Army of Byteland. Each officer has some power associated with him. The power of the i-th officer is denoted by p_{i}. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these n officers and calls this subset a battalion.(All 2^n subsets of the n officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a_{1},a_{2},\ldots,a_{k}, where a_1 \le a_2 \le \dots \le a_k. The strength of this battalion is equal to a_1a_2 + a_2a_3 + \dots + a_{k-1}a_k. (If the size of Battalion is \leq 1, then the strength of this battalion is 0).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be q changes. Each one of the form i x indicating that p_{i} is changed to x.You need to find the strength of the army initially and after each of these q updates.Note that the changes are permanent.The strength should be found by modulo 10^{9}+7. Formally, let M=10^{9}+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q\not\equiv 0 \bmod M). Output the integer equal to p\cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \leq x < M and x ⋅ q \equiv p \bmod M).InputThe first line of the input contains a single integer n (1 \leq n \leq 3⋅10^{5}) — the number of officers in Byteland's Army.The second line contains n integers p_{1},p_{2},\ldots,p_{n} (1 \leq p_{i} \leq 10^{9}).The third line contains a single integer q (1 \leq q \leq 3⋅10^{5}) — the number of updates.Each of the next q lines contains two integers i and x (1 \leq i \leq n, 1 \leq x \leq 10^{9}), indicating that p_{i} is updated to x .OutputIn the first line output the initial strength of the army.In i-th of the next q lines, output the strength of the army after i-th update.ExamplesInput
2
1 2
2
1 2
2 1
Output
500000004
1
500000004
Input
4
1 2 3 4
4
1 5
2 5
3 5
4 5
Output
625000011
13
62500020
375000027
62500027
NoteIn first testcase, initially, there are four possible battalions {} Strength = 0 {1} Strength = 0 {2} Strength = 0 {1,2} Strength = 2 So strength of army is \frac{0+0+0+2}{4} = \frac{1}{2}After changing p_{1} to 2, strength of battallion {1,2} changes to 4, so strength of army becomes 1.After changing p_{2} to 1, strength of battalion {1,2} again becomes 2, so strength of army becomes \frac{1}{2}. | 2
1 2
2
1 2
2 1
| 500000004 1 500000004 | 5 seconds | 256 megabytes | ['data structures', 'divide and conquer', 'probabilities', '*2800'] |
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice, the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of p players playing in p different positions. She also recognizes the importance of audience support, so she wants to select k people as part of the audience.There are n people in Byteland. Alice needs to select exactly p players, one for each position, and exactly k members of the audience from this pool of n people. Her ultimate goal is to maximize the total strength of the club.The i-th of the n persons has an integer a_{i} associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person i and for each position j, Alice knows s_{i, j} — the strength added by the i-th person to the club if he is selected to play in the j-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 3 integers n,p,k (2 \leq n \leq 10^{5}, 1 \leq p \leq 7, 1 \le k, p+k \le n).The second line contains n integers a_{1},a_{2},\ldots,a_{n}. (1 \leq a_{i} \leq 10^{9}).The i-th of the next n lines contains p integers s_{i, 1}, s_{i, 2}, \dots, s_{i, p}. (1 \leq s_{i,j} \leq 10^{9})OutputPrint a single integer {res} — the maximum possible strength of the club.ExamplesInput
4 1 2
1 16 10 3
18
19
13
15
Output
44
Input
6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
Output
377
Input
3 2 1
500 498 564
100002 3
422332 2
232323 1
Output
422899
NoteIn the first sample, we can select person 1 to play in the 1-st position and persons 2 and 3 as audience members. Then the total strength of the club will be equal to a_{2}+a_{3}+s_{1,1}. | 4 1 2
1 16 10 3
18
19
13
15
| 44 | 3 seconds | 256 megabytes | ['bitmasks', 'dp', 'greedy', 'sortings', '*2300'] |
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n\times n board. Rows and columns of this board are numbered from 1 to n. The cell on the intersection of the r-th row and c-th column is denoted by (r, c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 5 characters — U, D, L, R or X — instructions for the player. Suppose that the current cell is (r, c). If the character is R, the player should move to the right cell (r, c+1), for L the player should move to the left cell (r, c-1), for U the player should move to the top cell (r-1, c), for D the player should move to the bottom cell (r+1, c). Finally, if the character in the cell is X, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n^2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r, c) she wrote: a pair (x,y), meaning if a player had started at (r, c), he would end up at cell (x,y). or a pair (-1,-1), meaning if a player had started at (r, c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer n (1 \leq n \leq 10^{3}) — the side of the board.The i-th of the next n lines of the input contains 2n integers x_1, y_1, x_2, y_2, \dots, x_n, y_n, where (x_j, y_j) (1 \leq x_j \leq n, 1 \leq y_j \leq n, or (x_j,y_j)=(-1,-1)) is the pair written by Alice for the cell (i, j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the i-th of the next n lines, print the string of n characters, corresponding to the characters in the i-th row of the suitable board you found. Each character of a string can either be U, D, L, R or X. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInput
2
1 1 1 1
2 2 2 2
Output
VALID
XL
RX
Input
3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
Output
VALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1), he doesn't move any further following X and stops there. If the player starts at (1,2), he moves to left following L and stops at (1,1). If the player starts at (2,1), he moves to right following R and stops at (2,2). If the player starts at (2,2), he doesn't move any further following X and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2), he wouldn't have moved further following instruction X .The simulation can be seen below : | 2
1 1 1 1
2 2 2 2
| VALID XL RX | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'implementation', '*2000'] |
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class, he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x) = a_0 + a_1x + \dots + a_{n-1}x^{n-1} and g(x) = b_0 + b_1x + \dots + b_{m-1}x^{m-1}, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 1 for both the given polynomials. In other words, gcd(a_0, a_1, \dots, a_{n-1}) = gcd(b_0, b_1, \dots, b_{m-1}) = 1. Let h(x) = f(x)\cdot g(x). Suppose that h(x) = c_0 + c_1x + \dots + c_{n+m-2}x^{n+m-2}. You are also given a prime number p. Professor R challenges you to find any t such that c_t isn't divisible by p. He guarantees you that under these conditions such t always exists. If there are several such t, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, n, m and p (1 \leq n, m \leq 10^6, 2 \leq p \leq 10^9), — n and m are the number of terms in f(x) and g(x) respectively (one more than the degrees of the respective polynomials) and p is the given prime number.It is guaranteed that p is prime.The second line contains n integers a_0, a_1, \dots, a_{n-1} (1 \leq a_{i} \leq 10^{9}) — a_i is the coefficient of x^{i} in f(x).The third line contains m integers b_0, b_1, \dots, b_{m-1} (1 \leq b_{i} \leq 10^{9}) — b_i is the coefficient of x^{i} in g(x).OutputPrint a single integer t (0\le t \le n+m-2) — the appropriate power of x in h(x) whose coefficient isn't divisible by the given prime p. If there are multiple powers of x that satisfy the condition, print any.ExamplesInput
3 2 2
1 1 2
2 1
Output
1
Input
2 2 999999937
2 1
3 1
Output
2NoteIn the first test case, f(x) is 2x^2 + x + 1 and g(x) is x + 2, their product h(x) being 2x^3 + 5x^2 + 3x + 2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x) is x + 2 and g(x) is x + 3, their product h(x) being x^2 + 5x + 6, so the answer can be any of the powers as no coefficient is divisible by the given prime. | 3 2 2
1 1 2
2 1
| 1 | 1.5 seconds | 256 megabytes | ['constructive algorithms', 'math', 'ternary search', '*1800'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.