problem_number stringclasses 123
values | problem_letter stringclasses 33
values | problem_title stringlengths 1 46 | tags stringlengths 2 129 | difficulty stringclasses 41
values | problem_link stringlengths 43 56 | start_time stringclasses 117
values | language stringclasses 2
values | problem_site stringclasses 3
values | description stringlengths 331 6.84k |
|---|---|---|---|---|---|---|---|---|---|
2053 | I2 | Affectionate Arrays (Hard Version) | ["data structures", "dp", "graphs", "greedy", "math", "shortest paths", "two pointers"] | https://codeforces.com/problemset/problem/2053/I2 | 1735396500 | en | codeforces | # Affectionate Arrays (Hard Version)
## Problem Description
You are the beginning of the letter, the development of a poem, and the end of a fairy tale.
โ ilem, [Pinky Promise](https://www.bilibili.com/video/BV1Jb411U7u2/)
This is the hard version of the problem. The difference between the versions is that in this version, you need to compute the number of different arrays. You can hack only if you solved all versions of this problem.
Iris treasures an integer array $ a_1, a_2, \ldots, a_n $ . She knows this array has an interesting property: the maximum absolute value of all elements is less than or equal to the sum of all elements, that is, $ \max(\lvert a_i\rvert) \leq \sum a_i $ .
Iris defines the boredom of an array as its maximum subarray $ ^{\text{โ}} $ sum.
Iris's birthday is coming, and Victor is going to send her another array $ b_1, b_2, \ldots, b_m $ as a gift. For some seemingly obvious reasons, he decides the array $ b_1, b_2, \ldots, b_m $ should have the following properties.
- $ a_1, a_2, \ldots, a_n $ should be a subsequence $ ^{\text{โ }} $ of $ b_1, b_2, \ldots, b_m $ .
- The two arrays have the same sum. That is, $ \sum\limits_{i=1}^n a_i = \sum\limits_{i=1}^m b_i $ .
- The boredom of $ b_1, b_2, \ldots, b_m $ is the smallest possible.
- Among the arrays with the smallest boredom, the length of the array $ b $ (i.e., $ m $ ) is the smallest possible. And in this case, Iris will understand his regard as soon as possible!
Even constrained as above, there are still too many possible gifts. So Victor asks you to count the number of possible arrays $ b_1, b_2, \ldots, b_m $ satisfying all the conditions above. Since the answer may be large, Victor only needs the number modulo $ 998\,244\,353 $ . He promises you: if you help him successfully, he will share a bit of Iris's birthday cake with you.
Note: since the input is large, you may need to optimize it for this problem.
For example, in C++, it is enough to use the following lines at the start of the main() function:
```
<pre class="lstlisting">```
int main() {<br></br> std::ios::sync_with_stdio(false);<br></br> std::cin.tie(nullptr); std::cout.tie(nullptr);<br></br>}<br></br>
```
```
$ ^{\text{โ}} $ An array $ c $ is a subarray of an array $ d $ if $ c $ can be obtained from $ d $ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
$ ^{\text{โ }} $ A sequence $ c $ is a subsequence of a sequence $ d $ if $ c $ can be obtained from $ d $ by the deletion of several (possibly, zero or all) element from arbitrary positions.
## Input Format
Each test contains multiple test cases. The first line of input contains an integer $ t $ ( $ 1 \leq t \leq 10^5 $ ) โ the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 1 \leq n \leq 3\cdot 10^6 $ ) โ the length of the array $ a_1, a_2, \ldots, a_n $ .
The second line of each test case contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ -10^9 \leq a_i \leq 10^9 $ ) โ the initial array. It is guaranteed that $ \max(\lvert a_i\rvert) \leq \sum a_i $ .
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 3\cdot 10^6 $ .
## Output Format
For each test case, output a single line containing an integer: the number of different valid arrays $ b_1, b_2, \ldots, b_m $ , modulo $ 998\,244\,353 $ .
## Sample #1
### Sample Input #1
```
4
4
1 2 3 4
4
2 -3 2 2
10
2 -7 6 3 -1 4 2 -5 8 -4
20
4 -2 4 3 -2 1 5 2 3 6 -5 -1 -4 -2 -3 5 -3 1 -4 1
```
### Sample Output #1
```
1
2
20
1472
```
## Hint
In the first test case, $ a=[1, 2, 3, 4] $ . The only possible array $ b $ is $ [1, 2, 3, 4] $ .
In the second test case, $ a=[2, -3, 2, 2] $ . The possible arrays $ b $ are $ [1, 2, -3, 2, -1, 2] $ and $ [2, 1, -3, 2, -1, 2] $ .
## Limit
Time Limit
3.00s
Memory Limit
500.00MB | |
2053 | I1 | Affectionate Arrays (Easy Version) | ["data structures", "dp", "greedy"] | https://codeforces.com/problemset/problem/2053/I1 | 1735396500 | en | codeforces | # Affectionate Arrays (Easy Version)
## Problem Description
You are the beginning of the letter, the development of a poem, and the end of a fairy tale.
โ ilem, [Pinky Promise](https://www.bilibili.com/video/BV1Jb411U7u2/)
This is the easy version of the problem. The difference between the versions is that in this version, you need to compute the minimum length of the arrays. You can hack only if you solved all versions of this problem.
Iris treasures an integer array $ a_1, a_2, \ldots, a_n $ . She knows this array has an interesting property: the maximum absolute value of all elements is less than or equal to the sum of all elements, that is, $ \max(\lvert a_i\rvert) \leq \sum a_i $ .
Iris defines the boredom of an array as its maximum subarray $ ^{\text{โ}} $ sum.
Iris's birthday is coming, and Victor is going to send her another array $ b_1, b_2, \ldots, b_m $ as a gift. For some seemingly obvious reasons, he decides the array $ b_1, b_2, \ldots, b_m $ should have the following properties.
- $ a_1, a_2, \ldots, a_n $ should be a subsequence $ ^{\text{โ }} $ of $ b_1, b_2, \ldots, b_m $ .
- The two arrays have the same sum. That is, $ \sum\limits_{i=1}^n a_i = \sum\limits_{i=1}^m b_i $ .
- The boredom of $ b_1, b_2, \ldots, b_m $ is the smallest possible.
- Among the arrays with the smallest boredom, the length of the array $ b $ (i.e., $ m $ ) is the smallest possible. And in this case, Iris will understand his regard as soon as possible!
Even constrained as above, there are still too many possible gifts. So Victor asks you to compute the value of $ \boldsymbol{m} $ of any array $ b_1, b_2, \ldots, b_m $ satisfying all the conditions above. He promises you: if you help him successfully, he will share a bit of Iris's birthday cake with you.
Note: since the input is large, you may need to optimize it for this problem.
For example, in C++, it is enough to use the following lines at the start of the main() function:
```
<pre class="lstlisting">```
int main() {<br></br> std::ios::sync_with_stdio(false);<br></br> std::cin.tie(nullptr); std::cout.tie(nullptr);<br></br>}<br></br>
```
```
$ ^{\text{โ}} $ An array $ c $ is a subarray of an array $ d $ if $ c $ can be obtained from $ d $ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
$ ^{\text{โ }} $ A sequence $ c $ is a subsequence of a sequence $ d $ if $ c $ can be obtained from $ d $ by the deletion of several (possibly, zero or all) element from arbitrary positions.
## Input Format
Each test contains multiple test cases. The first line of input contains an integer $ t $ ( $ 1 \leq t \leq 10^5 $ ) โ the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 1 \leq n \leq 3\cdot 10^6 $ ) โ the length of the array $ a_1, a_2, \ldots, a_n $ .
The second line of each test case contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ -10^9 \leq a_i \leq 10^9 $ ) โ the initial array. It is guaranteed that $ \max(\lvert a_i\rvert) \leq \sum a_i $ .
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 3\cdot 10^6 $ .
## Output Format
For each test case, output a single line containing an integer: the length $ m $ of a valid array $ b $ .
## Sample #1
### Sample Input #1
```
4
4
1 2 3 4
4
2 -3 2 2
10
2 -7 6 3 -1 4 2 -5 8 -4
20
4 -2 4 3 -2 1 5 2 3 6 -5 -1 -4 -2 -3 5 -3 1 -4 1
```
### Sample Output #1
```
4
6
14
25
```
## Hint
In the first test case, $ a=[1, 2, 3, 4] $ . The only array $ b $ which satisfies all the properties above is $ [1, 2, 3, 4] $ , so we should output $ 4 $ .
In the second test case, $ a=[2, -3, 2, 2] $ . The possible arrays $ b $ are $ [1, 2, -3, 2, -1, 2] $ and $ [2, 1, -3, 2, -1, 2] $ , so we should output $ 6 $ .
## Limit
Time Limit
3.00s
Memory Limit
500.00MB | |
2053 | H | Delicate Anti-monotonous Operations | ["constructive algorithms", "implementation"] | https://codeforces.com/problemset/problem/2053/H | 1735396500 | en | codeforces | # Delicate Anti-monotonous Operations
## Problem Description
I shall be looking for you who would be out of Existence.
โ HyuN, [Disorder](https://soundcloud.com/k-sounds-studio/g2r2018-hyun-disorder-feat-yuri)
There are always many repetitive tasks in life. Iris always dislikes them, so she refuses to repeat them. However, time cannot be turned back; we only have to move forward.
Formally, Iris has an integer sequence $ a_1, a_2, \ldots, a_n $ , where each number in the sequence is between $ 1 $ and $ w $ , inclusive. It is guaranteed that $ w \geq 2 $ .
Iris defines an operation as selecting two numbers $ a_i, a_{i+1} $ satisfying $ a_i = a_{i+1} $ , and then changing them to two arbitrary integers within the range $ [1, w] $ . Iris does not like equality, so she must guarantee that $ a_i \neq a_{i+1} $ after the operation. Two identical pairs $ a_i, a_{i+1} $ can be selected multiple times.
Iris wants to know the maximum possible sum of all elements of $ a $ after several (possible, zero) operations, as well as the minimum number of operations required to achieve this maximum value.
## Input Format
Each test contains multiple test cases. The first line contains an integer $ t $ ( $ 1 \leq t \leq 10^5 $ ) โ the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers $ n $ and $ w $ ( $ 1 \leq n \leq 2\cdot 10^5 $ , $ 2 \leq w \leq 10^8 $ ) โ the length of the array, and the maximum allowed value of the elements.
The second line of each test case contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 1 \leq a_i \leq w $ ) โ the elements in the array.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 10^6 $ .
## Output Format
For each test case, output two integers โ the maximum possible sum of all elements of $ a $ and the minimum number of operations required, respectively.
## Sample #1
### Sample Input #1
```
2
5 8
1 2 3 4 5
7 5
3 1 2 3 4 1 1
```
### Sample Output #1
```
15 0
34 6
```
## Hint
In the first test case, no operation can be performed so the answers are $ \sum a_i = 15 $ and $ 0 $ , respectively.
In the second test case, the operations can be performed as follows:
$ $$$[3, 1, 2, 3, 4, \underline{1, 1}] \rightarrow [3, 1, 2, 3, \underline{4, 4}, 5] \rightarrow [3, 1, 2, \underline{3, 3}, 5, 5] \rightarrow [3, 1, \underline{2, 2}, 5, 5, 5] \rightarrow [3, \underline{1, 1}, 5, 5, 5, 5] \rightarrow [\underline{3, 3}, 5, 5, 5, 5, 5] \rightarrow [4, 5, 5, 5, 5, 5, 5] $ $ </p><p>It can be shown this is optimal, so we should output $ \\sum a\_i = 34 $ and the number of <span class="tex-font-style-it">operations</span>, $ 6$$$, respectively.
## Limit
Time Limit
2.00s
Memory Limit
500.00MB | |
2053 | G | Naive String Splits | ["binary search", "brute force", "greedy", "hashing", "math", "number theory", "strings"] | https://codeforces.com/problemset/problem/2053/G | 1735396500 | en | codeforces | # Naive String Splits
## Problem Description
And I will: love the world that you've adored; wish the smile that you've longed for. Your hand in mine as we explore, please take me to tomorrow's shore.
โ Faye Wong, [As Wished](https://www.youtube.com/watch?v=ZoJCN0pV7Qs)
Cocoly has a string $ t $ of length $ m $ , consisting of lowercase English letters, and he would like to split it into parts. He calls a pair of strings $ (x, y) $ beautiful if and only if there exists a sequence of strings $ a_1, a_2, \ldots, a_k $ , such that:
- $ t = a_1 + a_2 + \ldots + a_k $ , where $ + $ denotes string concatenation.
- For each $ 1 \leq i \leq k $ , at least one of the following holds: $ a_i = x $ , or $ a_i = y $ .
Cocoly has another string $ s $ of length $ n $ , consisting of lowercase English letters. Now, for each $ 1 \leq i < n $ , Cocoly wants you to determine whether the pair of strings $ (s_1s_2 \ldots s_i, \, s_{i+1}s_{i+2} \ldots s_n) $ is beautiful.
Note: since the input and output are large, you may need to optimize them for this problem.
For example, in C++, it is enough to use the following lines at the start of the main() function:
```
<pre class="lstlisting">```
int main() {<br></br> std::ios::sync_with_stdio(false);<br></br> std::cin.tie(nullptr); std::cout.tie(nullptr);<br></br>}<br></br>
```
```
## Input Format
Each test contains multiple test cases. The first line contains an integer $ T $ ( $ 1 \leq T \leq 10^5 $ ) โ the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers $ n $ and $ m $ ( $ 2 \leq n \leq m \leq 5 \cdot 10^6 $ ) โ the lengths of $ s $ and the length of $ t $ .
The second line of each test case contains a single string $ s $ of length $ n $ , consisting only of lowercase English letters.
The third line of each test case contains a single string $ t $ of length $ m $ , consisting only of lowercase English letters.
It is guaranteed that the sum of $ m $ over all test cases does not exceed $ 10^7 $ .
## Output Format
For each test case, output a single binary string $ r $ of length $ n - 1 $ : for each $ 1 \leq i < n $ , if the $ i $ -th pair is beautiful, $ r_i=\texttt{1} $ ; otherwise, $ r_i=\texttt{0} $ . Do not output spaces.
## Sample #1
### Sample Input #1
```
7
3 5
aba
ababa
4 10
czzz
czzzzzczzz
5 14
dream
dredreamamamam
5 18
tcccc
tcctccccctccctcccc
7 11
abababc
abababababc
7 26
aaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaa
19 29
bbbbbbbbbbbbbbbbbbb
bbbbbbbbbbbbbbbbbbbbbbbbbbbbb
```
### Sample Output #1
```
11
011
0010
0000
010100
111111
110010001100010011
```
## Hint
In the first test case, $ s = \tt aba $ , $ t = \tt ababa $ .
- For $ i = 1 $ : Cocoly can split $ t = \texttt{a} + \texttt{ba} + \texttt{ba} $ , so the string pair $ (\texttt{a}, \texttt{ba}) $ is beautiful.
- For $ i = 2 $ : Cocoly can split $ t = \texttt{ab} + \texttt{ab} + \texttt{a} $ , so the string pair $ (\texttt{ab}, \texttt{a}) $ is beautiful.
In the second test case, $ s = \tt czzz $ , $ t = \tt czzzzzczzz $ .
- For $ i = 1 $ : It can be proven that there is no solution to give a partition of $ t $ using strings $ \texttt{c} $ and $ \texttt{zzz} $ .
- For $ i = 2 $ : Cocoly can split $ t $ into $ \texttt{cz} + \texttt{zz} + \texttt{zz} + \texttt{cz} + \texttt{zz} $ .
- For $ i = 3 $ : Cocoly can split $ t $ into $ \texttt{czz} + \texttt{z} + \texttt{z} + \texttt{z} + \texttt{czz} + \texttt{z} $ .
## Limit
Time Limit
10.00s
Memory Limit
1000.00MB | |
2053 | F | Earnest Matrix Complement | ["brute force", "data structures", "dp", "greedy", "implementation", "math"] | https://codeforces.com/problemset/problem/2053/F | 1735396500 | en | codeforces | # Earnest Matrix Complement
## Problem Description
3, 2, 1, ... We are the โ RiOI Team!
โ Felix & All, [Special Thanks 3](https://www.luogu.com.cn/problem/T351681)
- Peter: Good news: My problem T311013 is approved!
- $ \delta $ : I'm glad my computer had gone out of battery so that I wouldn't have participated in wyrqwq's round and gained a negative delta.
- Felix: \[thumbs\_up\] The problem statement concerning a removed song!
- Aquawave: Do I mourn my Chemistry?
- E.Space: ahh?
- Trine: Bread.
- Iris: So why am I always testing problems?
Time will pass, and we might meet again. Looking back at the past, everybody has lived the life they wanted.
Aquawave has a matrix $ A $ of size $ n\times m $ , whose elements can only be integers in the range $ [1, k] $ , inclusive. In the matrix, some cells are already filled with an integer, while the rest are currently not filled, denoted by $ -1 $ .
You are going to fill in all the unfilled places in $ A $ . After that, let $ c_{u,i} $ be the number of occurrences of element $ u $ in the $ i $ -th row. Aquawave defines the beauty of the matrix as
$ $$$\sum_{u=1}^k \sum_{i=1}^{n-1} c_{u,i} \cdot c_{u,i+1}. $ $ </p><p>You have to find the maximum possible beauty of $ A$$$ after filling in the blanks optimally.
## Input Format
The first line of input contains a single integer $ t $ ( $ 1 \leq t \leq 2\cdot 10^4 $ ) โ the number of test cases. The description of test cases follows.
The first line of each test case contains three integers $ n $ , $ m $ , and $ k $ ( $ 2 \leq n \leq 2\cdot 10^5 $ , $ 2 \leq m \leq 2\cdot 10^5 $ , $ n \cdot m \leq 6\cdot 10^5 $ , $ 1 \leq k \leq n\cdot m $ ) โ the number of rows and columns of the matrix $ A $ , and the range of the integers in the matrix, respectively.
Then $ n $ lines follow, the $ i $ -th line containing $ m $ integers $ A_{i,1},A_{i,2},\ldots,A_{i,m} $ ( $ 1 \leq A_{i,j} \leq k $ or $ A_{i,j} = -1 $ ) โ the elements in $ A $ .
It is guaranteed that the sum of $ n\cdot m $ over all test cases does not exceed $ 6\cdot 10^5 $ .
## Output Format
For each test case, output a single integer โ the maximum possible beauty.
## Sample #1
### Sample Input #1
```
9
3 3 3
1 2 2
3 1 3
3 2 1
2 3 3
-1 3 3
2 2 -1
3 3 6
-1 -1 1
1 2 -1
-1 -1 4
3 4 5
1 3 2 3
-1 -1 2 -1
3 1 5 1
5 3 8
5 -1 2
1 8 -1
-1 5 6
7 7 -1
4 4 4
6 6 5
-1 -1 5 -1 -1 -1
-1 -1 -1 -1 2 -1
-1 1 3 3 -1 -1
-1 1 -1 -1 -1 4
4 2 -1 -1 -1 4
-1 -1 1 2 -1 -1
6 6 4
-1 -1 -1 -1 1 -1
3 -1 2 2 4 -1
3 1 2 2 -1 -1
3 3 3 3 -1 2
-1 3 3 -1 1 3
3 -1 2 2 3 -1
5 5 3
1 1 3 -1 1
2 2 -1 -1 3
-1 -1 -1 2 -1
3 -1 -1 -1 2
-1 1 2 3 -1
6 2 7
-1 7
-1 6
7 -1
-1 -1
-1 -1
2 2
```
### Sample Output #1
```
4
4
10
10
8
102
93
58
13
```
## Hint
In the first test case, the matrix $ A $ is already determined. Its beauty is
$ $$$\sum_{u=1}^k \sum_{i=1}^{n-1} c_{u,i} \cdot c_{u,i+1} = c_{1,1}\cdot c_{1,2} + c_{1,2}\cdot c_{1,3} + c_{2,1}\cdot c_{2,2} + c_{2,2}\cdot c_{2,3} + c_{3,1}\cdot c_{3,2} + c_{3,2}\cdot c_{3,3} = 1\cdot 1 + 1\cdot 1 + 2\cdot 0 + 0\cdot 1 + 0\cdot 2 + 2\cdot 1 = 4. $ $ </p><p>In the second test case, one can fill the matrix as follows:</p><p> $ $ \begin{bmatrix} 2 &3 &3 \\ 2 &2 &3 \end{bmatrix}, $ $ </p><p>and get the value $ 4 $ . It can be proven this is the maximum possible answer one can get.</p><p>In the third test case, one of the possible optimal configurations is:</p><p> $ $ \begin{bmatrix} 1 &1 &1 \\ 1 &2 &1 \\ 1 &1 &4 \end{bmatrix}. $ $ </p><p>In the fourth test case, one of the possible optimal configurations is:</p><p> $ $ \begin{bmatrix} 1 &3 &2 &3 \\ 1 &3 &2 &1 \\ 3 &1 &5 &1 \end{bmatrix}. $ $ </p><p>In the fifth test case, one of the possible optimal configurations is:</p><p> $ $ \begin{bmatrix} 5 &5 &2 \\ 1 &8 &5 \\ 7 &5 &6 \\ 7 &7 &4 \\ 4 &4 &4 \end{bmatrix}. $ $$$
## Limit
Time Limit
5.00s
Memory Limit
500.00MB | |
2053 | E | Resourceful Caterpillar Sequence | ["dfs and similar", "dp", "games", "graphs", "greedy", "trees"] | https://codeforces.com/problemset/problem/2053/E | 1735396500 | en | codeforces | # Resourceful Caterpillar Sequence
## Problem Description
Endless Repeating 7 Days
โ r-906, [Panopticon](https://www.youtube.com/watch?v=_-Vd0ZGB-lo)
There is a tree consisting of $ n $ vertices. Let a caterpillar be denoted by an integer pair $ (p, q) $ ( $ 1 \leq p, q \leq n $ , $ p \neq q $ ): its head is at vertex $ p $ , its tail is at vertex $ q $ , and it dominates all the vertices on the simple path from $ p $ to $ q $ (including $ p $ and $ q $ ). The caterpillar sequence of $ (p, q) $ is defined as the sequence consisting only of the vertices on the simple path, sorted in the ascending order of the distance to $ p $ .
Nora and Aron are taking turns moving the caterpillar, with Nora going first. Both players will be using his or her own optimal strategy:
- They will play to make himself or herself win;
- However, if it is impossible, they will play to prevent the other person from winning (thus, the game will end in a tie).
In Nora's turn, she must choose a vertex $ u $ adjacent to vertex $ p $ , which is not dominated by the caterpillar, and move all the vertices in it by one edge towards vertex $ u $ $ ^{\text{โ}} $ . In Aron's turn, he must choose a vertex $ v $ adjacent to vertex $ q $ , which is not dominated by the caterpillar, and move all the vertices in it by one edge towards vertex $ v $ . Note that the moves allowed to the two players are different.
Whenever $ p $ is a leaf $ ^{\text{โ }} $ , Nora wins $ ^{\text{โก}} $ . Whenever $ q $ is a leaf, Aron wins. If either initially both $ p $ and $ q $ are leaves, or after $ 10^{100} $ turns the game has not ended, the result is a tie.
Please count the number of integer pairs $ (p, q) $ with $ 1 \leq p, q \leq n $ and $ p \neq q $ such that, if the caterpillar is initially $ (p, q) $ , Aron wins the game.
$ ^{\text{โ}} $ In other words: Let the current caterpillar sequence be $ c_1, c_2, \ldots, c_k $ , then after the move, the new caterpillar sequence becomes $ d(u, c_1), d(u, c_2), \ldots, d(u, c_k) $ . Here, $ d(x, y) $ is the next vertex on the simple path from $ y $ to $ x $ .
$ ^{\text{โ }} $ In a tree, a vertex is called a leaf if and only if its degree is $ 1 $ .
$ ^{\text{โก}} $ Therefore, Nora never fails to choose a vertex $ u $ when the game has not ended. The same goes for Aron.
## Input Format
Each test consists of multiple test cases. The first line contains a single integer $ t $ ( $ 1 \leq t \leq 2\cdot 10^4 $ ) โ the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 2 \leq n \leq 2\cdot 10^5 $ ) โ the number of vertices in the tree.
The following $ n - 1 $ lines each contain two integers $ u $ and $ v $ ( $ 1 \leq u, v \leq n $ ), denoting an edge between vertices $ u $ and $ v $ . It is guaranteed that the given edges form a tree.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 4\cdot 10^5 $ .
## Output Format
For each test case, output a single line containing an integer: the number of integer pairs $ (p, q) $ which make Aron win.
## Sample #1
### Sample Input #1
```
5
2
1 2
5
1 2
1 3
2 4
2 5
12
1 6
11 2
4 8
12 3
2 7
6 12
8 1
2 3
5 12
9 2
10 3
10
1 2
2 3
3 4
4 5
5 6
4 7
6 8
4 9
4 10
25
1 16
11 22
6 14
3 1
20 14
23 17
25 19
10 11
3 18
10 6
2 21
4 5
11 12
4 9
9 13
8 6
6 1
3 7
8 19
10 24
15 13
1 2
3 4
17 8
```
### Sample Output #1
```
0
6
40
27
171
```
## Hint
In the first test case, all possible caterpillars are $ (1, 2) $ and $ (2, 1) $ , resulting in a tie at the beginning, since both $ p $ and $ q $ are leaves.
In the second test case, the caterpillars that allow Aron to win are the following: $ (1, 3) $ , $ (1, 4) $ , $ (1, 5) $ , $ (2, 3) $ , $ (2, 4) $ , $ (2, 5) $ . Let's look at some specific caterpillars.
- For the caterpillar $ (1, 5) $ : vertex $ p = 1 $ is not a leaf, but vertex $ q = 5 $ is, so Aron wins at the beginning.
- For the caterpillar $ (2, 1) $ : vertex $ p = 2 $ is not a leaf, neither is vertex $ q = 1 $ . In Nora's first move, she can choose to move the caterpillar towards vertex $ 5 $ , therefore the caterpillar becomes $ (5, 2) $ , and vertex $ p = 5 $ is a leaf, so Nora will win.
## Limit
Time Limit
2.00s
Memory Limit
500.00MB | |
2053 | D | Refined Product Optimality | ["binary search", "data structures", "greedy", "math", "schedules", "sortings"] | https://codeforces.com/problemset/problem/2053/D | 1735396500 | en | codeforces | # Refined Product Optimality
## Problem Description
As a tester, when my solution has a different output from the example during testing, I suspect the author first.
โ Chris, [a comment](https://codeforces.com/blog/entry/133116?#comment-1190579)
Although Iris occasionally sets a problem where the solution is possibly wrong, she still insists on creating problems with her imagination; after all, everyone has always been on the road with their stubbornness... And like ever before, Iris has set a problem to which she gave a wrong solution, but Chris is always supposed to save it! You are going to play the role of Chris now:
- Chris is given two arrays $ a $ and $ b $ , both consisting of $ n $ integers.
- Iris is interested in the largest possible value of $ P = \prod\limits_{i=1}^n \min(a_i, b_i) $ after an arbitrary rearrangement of $ b $ . Note that she only wants to know the maximum value of $ P $ , and no actual rearrangement is performed on $ b $ .
- There will be $ q $ modifications. Each modification can be denoted by two integers $ o $ and $ x $ ( $ o $ is either $ 1 $ or $ 2 $ , $ 1 \leq x \leq n $ ). If $ o = 1 $ , then Iris will increase $ a_x $ by $ 1 $ ; otherwise, she will increase $ b_x $ by $ 1 $ .
- Iris asks Chris the maximum value of $ P $ for $ q + 1 $ times: once before any modification, then after every modification.
- Since $ P $ might be huge, Chris only needs to calculate it modulo $ 998\,244\,353 $ .
Chris soon worked out this problem, but he was so tired that he fell asleep. Besides saying thanks to Chris, now it is your turn to write a program to calculate the answers for given input data.
Note: since the input and output are large, you may need to optimize them for this problem.
For example, in C++, it is enough to use the following lines at the start of the main() function:
```
<pre class="lstlisting">```
int main() {<br></br> std::ios::sync_with_stdio(false);<br></br> std::cin.tie(nullptr); std::cout.tie(nullptr);<br></br>}<br></br>
```
```
## Input Format
Each test contains multiple test cases. The first line of input contains a single integer $ t $ ( $ 1 \leq t \leq 10^4 $ ) โ the number of test cases. The description of test cases follows.
The first line of each test case contains two integers $ n $ and $ q $ ( $ 1 \leq n \leq 2\cdot 10^5 $ , $ 1 \leq q \leq 2\cdot 10^5 $ ) โ the length of the array and the number of operations.
The second line of each test case contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 1 \leq a_i \leq 5\cdot 10^8 $ ) โ the array $ a $ .
The third line of each test case contains $ n $ integers $ b_1, b_2, \ldots, b_n $ ( $ 1 \leq b_i \leq 5\cdot 10^8 $ ) โ the array $ b $ .
Then $ q $ lines follow, each line contains two integers $ o $ and $ x $ ( $ o \in \{1, 2\} $ , $ 1 \leq x \leq n $ ), representing an operation.
It's guaranteed that the sum of $ n $ and the sum of $ q $ over all test cases does not exceed $ 4\cdot 10^5 $ , respectively.
## Output Format
For each test case, output $ q + 1 $ integers in a line, representing the answers that Chris will calculate, modulo $ 998\,244\,353 $ .
## Sample #1
### Sample Input #1
```
4
3 4
1 1 2
3 2 1
1 3
2 3
1 1
2 1
6 8
1 4 2 7 3 5
7 6 5 6 3 3
2 5
1 6
1 5
1 5
1 5
2 3
2 3
1 6
13 8
7 7 6 6 5 5 5 2 2 3 4 5 1
1 4 1 9 6 6 9 1 5 1 3 8 4
2 2
2 11
2 4
2 4
1 7
1 1
2 12
1 5
5 3
10000000 20000000 30000000 40000000 50000000
10000000 20000000 30000000 40000000 50000000
1 1
2 2
2 1
```
### Sample Output #1
```
2 3 3 6 6
840 840 1008 1344 1680 2016 2016 2016 2352
2116800 2646000 3528000 3528000 3528000 4233600 4838400 4838400 4838400
205272023 205272023 205272023 264129429
```
## Hint
In the first test case:
- Before the modifications, Chris can rearrange $ b $ to $ [1, 2, 3] $ so that $ P = \prod\limits_{i=1}^n \min(a_i, b_i) = 1 \cdot 1 \cdot 2 = 2 $ . We can prove that this is the maximum possible value. For example, if Chris rearranges $ b = [2, 3, 1] $ , $ P $ will be equal $ 1 \cdot 1 \cdot 1 = 1 < 2 $ , which is not optimal.
- After the first modification, Chris can rearrange $ b $ to $ [1, 2, 3] $ so that $ P = 1 \cdot 1 \cdot 3 = 3 $ , which is maximized.
- After the second modification, Chris can rearrange $ b $ to $ [2, 2, 3] $ so that $ P = 1 \cdot 1 \cdot 3 = 3 $ , which is maximized.
- After the third modification, Chris can rearrange $ b $ to $ [2, 2, 3] $ so that $ P = 6 $ , which is maximized.
- After the fourth modification, Chris can rearrange $ b $ to $ [2, 2, 4] $ so that $ P = 6 $ , which is maximized.
## Limit
Time Limit
3.00s
Memory Limit
500.00MB | |
2053 | C | Bewitching Stargazer | ["bitmasks", "divide and conquer", "dp", "math"] | https://codeforces.com/problemset/problem/2053/C | 1735396500 | en | codeforces | # Bewitching Stargazer
## Problem Description
I'm praying for owning a transparent heart; as well as eyes with tears more than enough...
โ Escape Plan, [Brightest Star in the Dark](https://www.youtube.com/watch?v=GPnymcrXgX0)
Iris looked at the stars and a beautiful problem emerged in her mind. She is inviting you to solve it so that a meteor shower is believed to form.
There are $ n $ stars in the sky, arranged in a row. Iris has a telescope, which she uses to look at the stars.
Initially, Iris observes stars in the segment $ [1, n] $ , and she has a lucky value of $ 0 $ . Iris wants to look for the star in the middle position for each segment $ [l, r] $ that she observes. So the following recursive procedure is used:
- First, she will calculate $ m = \left\lfloor \frac{l+r}{2} \right\rfloor $ .
- If the length of the segment (i.e. $ r - l + 1 $ ) is even, Iris will divide it into two equally long segments $ [l, m] $ and $ [m+1, r] $ for further observation.
- Otherwise, Iris will aim the telescope at star $ m $ , and her lucky value will increase by $ m $ ; subsequently, if $ l \neq r $ , Iris will continue to observe two segments $ [l, m-1] $ and $ [m+1, r] $ .
Iris is a bit lazy. She defines her laziness by an integer $ k $ : as the observation progresses, she will not continue to observe any segment $ [l, r] $ with a length strictly less than $ k $ . In this case, please predict her final lucky value.
## Input Format
Each test contains multiple test cases. The first line of input contains a single integer $ t $ ( $ 1 \leq t \leq 10^5 $ ) โ the number of test cases. The description of test cases follows.
The only line of each test case contains two integers $ n $ and $ k $ ( $ 1 \leq k \leq n \leq 2\cdot 10^9 $ ).
## Output Format
For each test case, output a single integer โ the final lucky value.
## Sample #1
### Sample Input #1
```
6
7 2
11 3
55 13
5801 6
8919 64
8765432 1
```
### Sample Output #1
```
12
18
196
1975581
958900
38416403456028
```
## Hint
In the first test case, at the beginning, Iris observes $ [1, 7] $ . Since $ [1, 7] $ has an odd length, she aims at star $ 4 $ and therefore increases her lucky value by $ 4 $ . Then it is split into $ 2 $ new segments: $ [1, 3] $ and $ [5, 7] $ . The segment $ [1, 3] $ again has an odd length, so Iris aims at star $ 2 $ and increases her lucky value by $ 2 $ . Then it is split into $ 2 $ new segments: $ [1, 1] $ and $ [3, 3] $ , both having a length less than $ 2 $ , so no further observation is conducted. For range $ [5, 7] $ , the progress is similar and the lucky value eventually increases by $ 6 $ . Therefore, the final lucky value is $ 4 + 2 + 6 = 12 $ .
In the last test case, Iris finally observes all the stars and the final lucky value is $ 1 + 2 + \cdots + 8\,765\,432 = 38\,416\,403\,456\,028 $ .
## Limit
Time Limit
2.00s
Memory Limit
250.00MB | |
2053 | B | Outstanding Impressionist | ["binary search", "brute force", "data structures", "greedy"] | https://codeforces.com/problemset/problem/2053/B | 1735396500 | en | codeforces | # Outstanding Impressionist
## Problem Description
If it was so, then let's make it a deal...
โ MayDay, [Gentleness](https://www.youtube.com/watch?v=mtAc_bMYBsM&list=PLj6NQzHFCvkHKIm0Vnk9LH3odqTIBRZ1Q&index=15)
Even after copying the paintings from famous artists for ten years, unfortunately, Eric is still unable to become a skillful impressionist painter. He wants to forget something, but the white bear phenomenon just keeps hanging over him.
Eric still remembers $ n $ pieces of impressions in the form of an integer array. He records them as $ w_1, w_2, \ldots, w_n $ . However, he has a poor memory of the impressions. For each $ 1 \leq i \leq n $ , he can only remember that $ l_i \leq w_i \leq r_i $ .
Eric believes that impression $ i $ is unique if and only if there exists a possible array $ w_1, w_2, \ldots, w_n $ such that $ w_i \neq w_j $ holds for all $ 1 \leq j \leq n $ with $ j \neq i $ .
Please help Eric determine whether impression $ i $ is unique for every $ 1 \leq i \leq n $ , independently for each $ i $ . Perhaps your judgment can help rewrite the final story.
## Input Format
Each test contains multiple test cases. The first line of the input contains a single integer $ t $ ( $ 1 \leq t \leq 10^4 $ ) โ the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 1 \leq n \leq 2\cdot 10^5 $ ) โ the number of impressions.
Then $ n $ lines follow, the $ i $ -th containing two integers $ l_i $ and $ r_i $ ( $ 1 \leq l_i \leq r_i \leq 2\cdot n $ ) โ the minimum possible value and the maximum possible value of $ w_i $ .
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2\cdot 10^5 $ .
## Output Format
For each test case, output a binary string $ s $ of length $ n $ : for each $ 1 \leq i \leq n $ , if impression $ i $ is unique, $ s_i=\texttt{1} $ ; otherwise, $ s_i=\texttt{0} $ . Do not output spaces.
## Sample #1
### Sample Input #1
```
5
2
1 1
1 1
4
1 3
1 3
1 3
1 3
6
3 6
2 2
1 2
1 1
3 4
2 2
7
3 4
4 4
4 4
1 3
2 5
1 4
2 2
3
4 5
4 4
5 5
```
### Sample Output #1
```
00
1111
100110
1001111
011
```
## Hint
In the first test case, the only possible array $ w $ is $ [1, 1] $ , making neither impression $ 1 $ nor $ 2 $ unique (since $ w_1 = w_2 $ ).
In the second test case, all impressions can be made unique:
- For $ i = 1 $ , we can set $ w $ to $ [1, 3, 2, 3] $ , in which $ w_1 \neq w_2 $ , $ w_1 \neq w_3 $ , and $ w_1 \neq w_4 $ ;
- For $ i = 2 $ , we can set $ w $ to $ [2, 3, 1, 2] $ , in which $ w_2 \neq w_1 $ , $ w_2 \neq w_3 $ , and $ w_2 \neq w_4 $ ;
- For $ i = 3 $ , we can set $ w $ to $ [1, 1, 3, 1] $ ;
- For $ i = 4 $ , we can set $ w $ to $ [2, 3, 3, 1] $ .
In the third test case, for $ i = 4 $ , we can set $ w $ to $ [3, 2, 2, 1, 3, 2] $ . Thus, impression $ 4 $ is unique.
## Limit
Time Limit
1.00s
Memory Limit
250.00MB | |
2053 | A | Tender Carpenter | ["dp", "geometry", "greedy", "math"] | https://codeforces.com/problemset/problem/2053/A | 1735396500 | en | codeforces | # Tender Carpenter
## Problem Description
I would use a firework to announce, a wave to bid farewell, and a bow to say thanks: bygones are bygones; not only on the following path will I be walking leisurely and joyfully, but also the footsteps won't halt as time never leaves out flowing; for in the next year, we will meet again.
โ Cocoly1990, [Goodbye 2022](https://www.luogu.com.cn/problem/P8941)
In his dream, Cocoly would go on a long holiday with no worries around him. So he would try out for many new things, such as... being a carpenter. To learn it well, Cocoly decides to become an apprentice of Master, but in front of him lies a hard task waiting for him to solve.
Cocoly is given an array $ a_1, a_2,\ldots, a_n $ . Master calls a set of integers $ S $ stable if and only if, for any possible $ u $ , $ v $ , and $ w $ from the set $ S $ (note that $ u $ , $ v $ , and $ w $ do not necessarily have to be pairwise distinct), sticks of length $ u $ , $ v $ , and $ w $ can form a non-degenerate triangle $ ^{\text{โ}} $ .
Cocoly is asked to partition the array $ a $ into several (possibly, $ 1 $ or $ n $ ) non-empty continuous subsegments $ ^{\text{โ }} $ , such that: for each of the subsegments, the set containing all the elements in it is stable.
Master wants Cocoly to partition $ a $ in at least two different $ ^{\text{โก}} $ ways. You have to help him determine whether it is possible.
$ ^{\text{โ}} $ A triangle with side lengths $ x $ , $ y $ , and $ z $ is called non-degenerate if and only if:
- $ x + y > z $ ,
- $ y + z > x $ , and
- $ z + x > y $ .
$ ^{\text{โ }} $ A sequence $ b $ is a subsegment of a sequence $ c $ if $ b $ can be obtained from $ c $ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
$ ^{\text{โก}} $ Two partitions are considered different if and only if at least one of the following holds:
- the numbers of continuous subsegments split in two partitions are different;
- there is an integer $ k $ such that the lengths of the $ k $ -th subsegment in two partitions are different.
## Input Format
Each test contains multiple test cases. The first line of the input contains a single integer $ t $ ( $ 1 \leq t \leq 200 $ ) โ the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 2 \leq n \leq 200 $ ) โ the length of the array $ a $ .
The second line contains $ n $ integers $ a_1,a_2,\ldots,a_n $ ( $ 1 \leq a_i \leq 10^5 $ ) โ the elements in the array $ a $ .
## Output Format
For each test case, print $ \texttt{YES} $ if there are at least two ways to partition $ a $ , and $ \texttt{NO} $ otherwise.
You can output the answer in any case (upper or lower). For example, the strings $ \texttt{yEs} $ , $ \texttt{yes} $ , $ \texttt{Yes} $ , and $ \texttt{YES} $ will be recognized as positive responses.
## Sample #1
### Sample Input #1
```
5
4
2 3 5 7
4
115 9 2 28
5
8 4 1 6 2
6
1 5 4 1 4 7
2
100000 100000
```
### Sample Output #1
```
YES
NO
NO
YES
YES
```
## Hint
In the first test case, here are two possible partitions:
- $ [2, 3], [5, 7] $ , since
- $ [2, 3] $ is stable because sticks of lengths $ (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3) $ respectively can all form non-degenerate triangles.
- $ [5, 7] $ is stable because sticks of lengths $ (5, 5, 5), (5, 5, 7), (5, 7, 7), (7, 7, 7) $ respectively can all form non-degenerate triangles.
- and $ [2], [3, 5], [7] $ , since
- $ [2] $ is stable because sticks of lengths $ (2, 2, 2) $ respectively can form a non-degenerate triangle.
- $ [3, 5] $ is stable because sticks of lengths $ (3, 3, 3), (3, 3, 5), (3, 5, 5), (5, 5, 5) $ respectively can all form non-degenerate triangles.
- $ [7] $ is stable because sticks of lengths $ (7, 7, 7) $ respectively can form a non-degenerate triangle.
Note that some other partitions also satisfy the constraints, such as $ [2], [3], [5], [7] $ and $ [2], [3], [5, 7] $ .
In the second test case, Cocoly can only partition each element as a single subsegment, resulting in $ [115], [9], [2], [28] $ . Since we only have one possible partition, the answer is $ \texttt{NO} $ .
In the third test case, please note that the partition $ [8, 4], [1], [6], [2] $ does not satisfy the constraints, because $ \{8, 4\} $ is not a stable set: sticks of lengths $ 4 $ , $ 4 $ , and $ 8 $ cannot form a non-degenerate triangle.
## Limit
Time Limit
1.00s
Memory Limit
250.00MB | |
2052 | J | Judicious Watching | ["binary search", "greedy", "sortings"] | 2000 | https://codeforces.com/problemset/problem/2052/J | 1734248100 | en | codeforces | # Judicious Watching
## Problem Description
Jill loves having good grades in university, so she never misses deadlines for her homework assignments. But even more, she loves watching the series and discussing it with her best friend Johnny. And unfortunately, today she needs to choose between these two activities!
Jill needs to complete $ n $ homework tasks. The $ i $ -th task would require $ a_i $ minutes to complete and needs to be submitted to the teacher at most $ d_i $ minutes from now. Also, there are $ m $ new episodes of the series that Johnny and Jill want to discuss. The $ j $ -th episode lasts $ l_j $ minutes. Jill can complete tasks in any order, but she needs to watch the episodes in the order they come. Neither completing a homework task nor watching an episode can be interrupted after starting.
Johnny and Jill need to agree on a time $ t_k $ when they would have a call to discuss the series. They are not sure yet which time to choose. For each possible time, compute the maximum number of episodes Jill could watch before that time while still being able to complete all $ n $ homework tasks in time.
Note that for the purpose of this problem we assume that discussing the series with Johnny at time $ t_k $ does not consume significant time from Jill and can happen even if she is in the middle of completing any of her homework tasks.
## Input Format
There are several test cases in the input. The input begins with the number of test cases $ T $ ( $ 1 \le T \le 1\,000 $ ).
Each test case starts with a line with three integers $ n $ ( $ 1 \le n \le 200\,000 $ ) โ the number of homework tasks, $ m $ ( $ 1 \le m \le 200\,000 $ ) โ the number of episodes, and $ q $ ( $ 1 \le q \le 200\,000 $ ) โ the number of possible times for the call with Jill.
The second line contains $ n $ integers $ a_i $ ( $ 1 \le a_i \le 10^9 $ ) โ the number of minutes it takes to complete the task. The next line contains $ n $ integers $ d_i $ ( $ 1 \le d_i \le 10^{15} $ ) โ the deadline before which this task must be completed. The next line contains $ m $ integers $ l_j $ ( $ 1 \le l_j \le 10^9 $ ) โ the length of episodes in the order they need to be watched. The next line contains $ q $ integers $ t_k $ ( $ 1 \le t_k \le 10^{15} $ ) โ the possible times of call with Jill.
It is possible to complete all tasks within their respective deadlines.
The sum of each of $ n $ , $ m $ , $ q $ over all test cases in input doesn't exceed $ 200\,000 $ .
## Output Format
For each test case output a single line with $ q $ integers โ for each possible time $ t_k $ the maximum number of episodes Jill can watch.
## Sample #1
### Sample Input #1
```
2
1 2 3
10
15
5 5
5 15 20
3 4 5
8 100 8
10 150 20
2 32 1 1
9 200 51 50 10
```
### Sample Output #1
```
1 1 2
1 4 2 2 1
```
## Limit
Time Limit
3.00s
Memory Limit
1000.00MB |
2052 | G | Geometric Balance | ["data structures", "geometry", "implementation"] | 2800 | https://codeforces.com/problemset/problem/2052/G | 1734248100 | en | codeforces | # Geometric Balance
## Problem Description
Peter's little brother Ivan likes to play with a turtle. The turtle is a special toy that lives on the plane and can execute three commands:
- Rotate $ a $ degrees counterclockwise.
- Draw $ d $ units in the direction it is facing while dispensing ink. No segment of the plane will be covered by ink more than once.
- Move $ d $ units in the direction it is facing without drawing.
Ivan just learned about the compass, so he will only rotate his turtle so it faces one of eight cardinal or ordinal directions (angles $ a $ in rotate commands are always divisible by 45). Also, he will perform at least one draw command.
Peter has noted all the commands Ivan has given to his turtle. He thinks that the image drawn by the turtle is adorable. Now Peter wonders about the smallest positive angle $ b $ such that he can perform the following operations: move the turtle to a point of his choosing, rotate it by $ b $ degrees, and execute all the commands in the same order. These operations should produce the same image as the original one. Can you help Peter?
Note, two images are considered the same if the sets of points covered by ink on the plane are the same in both of the images.
## Input Format
The first line of the input contains a single integer $ n\;(1 \le n \le 50000) $ โ the number of commands Ivan has given.
The next $ n $ lines contain commands. Each command is one of:
- "rotate $ a $ " ( $ 45 \le a \le 360 $ ) where $ a $ is divisible by $ 45 $ ;
- "draw $ d $ " ( $ 1 \le d \le 10^9 $ );
- "move $ d $ " ( $ 1 \le d \le 10^9 $ ).
At least one and at most 2000 of the commands are draw. It is guaranteed that no segment of the plane will be covered by ink more than once.
## Output Format
Output a single number, the answer to the question. The answer always exists.
## Sample #1
### Sample Input #1
```
1
draw 10
```
### Sample Output #1
```
180
```
## Sample #2
### Sample Input #2
```
7
draw 1
rotate 90
draw 1
rotate 90
draw 1
rotate 90
draw 1
```
### Sample Output #2
```
90
```
## Sample #3
### Sample Input #3
```
3
draw 1
move 1
draw 2
```
### Sample Output #3
```
360
```
## Limit
Time Limit
3.00s
Memory Limit
1000.00MB |
2052 | F | Fix Flooded Floor | ["constructive algorithms", "dp", "graphs"] | 1700 | https://codeforces.com/problemset/problem/2052/F | 1734248100 | en | codeforces | # Fix Flooded Floor
## Problem Description
Archimedes conducted his famous experiments on buoyancy. But not everyone knows that while he was taking a bath, he was too focused and didn't notice the moment when the water overflowed over the edge of the bath and flooded the floor near the wall. His expensive parquet was irreversibly damaged!
Archimedes noticed that not all was lost, and there were still several undamaged parquet pieces. The parquet near the wall had the shape of a long narrow stripe of $ 2\times n $ cells. Archimedes had an unlimited supply of $ 1\times 2 $ parquet pieces that could be placed parallel or perpendicular to the wall. Archimedes didn't want to cut the parquet pieces. As a great scientist, he figured out that there was exactly one way to restore the parquet by filling the damaged area of the parquet with the non-overlapping $ 1\times 2 $ cell shaped pieces.
Help historians to check Archimedes' calculations. For the given configuration of the $ 2\times n $ parquet floor, determine whether there is exactly one way to fill the damaged parquet cells with the $ 1\times 2 $ cell parquet pieces. If Archimedes was wrong, find out whether there are multiple ways to restore the parquet, or there are no ways at all.
## Input Format
The first line contains a single integer $ T $ ( $ 1 \le T \le 10^4 $ ) โ the number of test cases to solve.
Then the description of test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 1 \le n \le 2\cdot 10^5 $ ) โ the length of the parquet floor.
The following two lines contain exactly $ n $ characters each and describe the parquet, where '.' denotes a damaged cell and '\#' denotes an undamaged cell.
The total sum of $ n $ in all $ T $ test cases doesn't exceed $ 2\cdot 10^5 $ .
## Output Format
For each test case, print "Unique" if there is exactly one way to restore the parquet, "Multiple" if there are multiple ways to do so, or "None" if it is impossible to restore the parquet.
## Sample #1
### Sample Input #1
```
4
10
#.......##
##..#.##..
6
...#..
..#...
8
........
........
3
###
###
```
### Sample Output #1
```
Unique
None
Multiple
Unique
```
## Limit
Time Limit
3.00s
Memory Limit
1000.00MB |
2052 | E | Expression Correction | ["brute force", "expression parsing", "strings"] | 1900 | https://codeforces.com/problemset/problem/2052/E | 1734248100 | en | codeforces | # Expression Correction
## Problem Description
Eve is studying mathematics in school. They've already learned how to perform addition and subtraction of decimal numbers and are practicing it by solving fun puzzles. The specific type of the puzzle they are solving is described below. They are given an equality with addition and subtraction which may or may not be a correct one. They have to verify the equality, and if it is not a correct one, then they have to tell if it is possible to turn it into a correct one by moving one digit to a different place in the equality.
Let us formally define the equality in this puzzle:
- Number is a string of at least one and at most 10 decimal digits ('0' to '9') that has no extra leading zeroes (the only number that is allowed to start with the zero digit is "0").
- Expression is a string composed of one or more numbers, as defined above, that are separated with addition ('+') or subtraction ('-') operators.
- Equality is a string composed of an expression, as defined above, followed by an equals sign ('='), followed by another expression.
- Correct equality is an equality where both expressions on the left and right hand sides of the equals sign evaluate to the same decimal number according to the standard arithmetic. Note that while all the numbers in the expression are positive, the evaluated number can be negative. Also, the evaluated number can be longer than 10 digits.
- Moving a digit in an equality means removing a digit from any position in the string and inserting it into another position so that the resulting string is again an equality.
The puzzle is pretty straightforward once you know how to add and subtract decimal numbers, but it is tenuous. It is easy to get distracted and make a mistake while performing computation. Your task is to write a program that solves the expression correction puzzle to help Eve.
## Input Format
The input file consists of a single line โ an equality as defined in the problem statement. The total length of the input string does not exceed 100 characters.
## Output Format
Write a single line to the output. If the input contains a correct equality, output a single word "Correct". Otherwise, if the input equality can be turned into a correct one by moving one digit, output the resulting correct equality. If there are multiple possible correct equalities after moving one digit, you may output any one of them. Otherwise, output a single word "Impossible".
## Sample #1
### Sample Input #1
```
2+2=4
```
### Sample Output #1
```
Correct
```
## Sample #2
### Sample Input #2
```
123456789+9876543210=111111110+11-1
```
### Sample Output #2
```
123456789+987654321=1111111100+11-1
```
## Sample #3
### Sample Input #3
```
10+9=10
```
### Sample Output #3
```
Impossible
```
## Sample #4
### Sample Input #4
```
24=55-13
```
### Sample Output #4
```
42=55-13
```
## Sample #5
### Sample Input #5
```
1000000000-10=9999999999
```
### Sample Output #5
```
Impossible
```
## Limit
Time Limit
3.00s
Memory Limit
1000.00MB |
2052 | D | DAG Serialization | ["brute force", "graphs"] | 2100 | https://codeforces.com/problemset/problem/2052/D | 1734248100 | en | codeforces | # DAG Serialization
## Problem Description
Consider a simple single-bit boolean register that supports two operations:
- set โ sets the register to true if it was false, and returns true; otherwise, it returns false;
- unset โ sets the register to false if it was true, and returns true; otherwise, it returns false.
The initial state of the register is false. Suppose there were $ n $ operations $ op_i $ (for $ 1 \le i \le n $ ) where at most two operations returned true. Also, we are given the partial order of operations as a directed acyclic graph (DAG): an edge $ i \rightarrow j $ means that $ op_i $ happened before $ op_j $ . You are asked whether it is possible to put these operations in some linear sequential order that satisfies the given partial order and such that if operations are applied to the register in that order, their results are the same as given.
## Input Format
In the first line, you are given an integer $ n $ โ the number of operations ( $ 1 \le n \le 10^5 $ ). In the following $ n $ lines, you are given operations in the format "type result", where type is either "set" or "unset" and result is either "true" or "false". It is guaranteed that at most two operations have "true" results.
In the next line, you are given an integer $ m $ โ the number of arcs of the DAG ( $ 0 \le m \le 10^5 $ ). In the following $ m $ lines, you are given arcs โ pairs of integers $ a $ and $ b $ ( $ 1 \leq a, b \leq n $ ; $ a \neq b $ ). Each arc indicates that operation $ op_a $ happened before operation $ op_b $ .
## Output Format
Print any linear order of operations that satisfies the DAG constraints and ensures the results of the operations match the ones given in the input. If a correct operation order does not exist, print $ -1 $ .
## Sample #1
### Sample Input #1
```
5
set true
unset true
set false
unset false
unset false
2
1 4
5 2
```
### Sample Output #1
```
5 1 3 2 4
```
## Sample #2
### Sample Input #2
```
3
unset true
unset false
set true
0
```
### Sample Output #2
```
2 3 1
```
## Sample #3
### Sample Input #3
```
2
unset false
set true
1
2 1
```
### Sample Output #3
```
-1
```
## Sample #4
### Sample Input #4
```
2
unset false
set false
0
```
### Sample Output #4
```
-1
```
## Limit
Time Limit
3.00s
Memory Limit
1000.00MB |
2052 | A | Adrenaline Rush | ["constructive algorithms"] | 1600 | https://codeforces.com/problemset/problem/2052/A | 1734248100 | en | codeforces | # Adrenaline Rush
## Problem Description
Alice's friend is a big fan of the Adrenaline Rush racing competition and always strives to attend every race. However, this time, Alice is the one watching the race. To ensure her friend does not miss any important details, Alice decides to take notes on everything that happens on the track.
The first thing Alice notices before the race begins is the numbering of the cars. All the cars line up in front of the starting line in a specific order. The car closest to the line is numbered $ 1 $ , the second car is numbered $ 2 $ , and so on, up to the last car, which is numbered $ n $ . How convenient! โ Alice thought.
The race begins with the countdown: "Three! Two! One! Go!". Alice observes that the cars start in their original order. However, as the race progresses, their order changes. She records whenever one car overtakes another, essentially swapping places with it on the track.
During the race, Alice notices something curious: no car overtakes another more than once. In other words, for any two cars $ x $ and $ y $ , there are at most two overtakes between them during the race: " $ x $ overtakes $ y $ " and/or " $ y $ overtakes $ x $ ".
At the end of the race, Alice carefully writes down the final order of the cars $ c_1, c_2, \ldots, c_n $ , where $ c_1 $ represents the winner of the race.
Alice's friend, however, is only interested in the final ranking and discards all of Alice's notes except for the final ordering. As Alice is quite curious, she wonders: What is the longest possible sequence of overtakes she could have observed during the race? Your task is to help Alice answer this question.
## Input Format
The first line of the input contains a single integer $ n\;(1 \le n \le 1000) $ โ the number of cars in the race.
The second line contains a permutation $ c_1, c_2, \ldots, c_n\;(1 \le c_i \le n, c_i \ne c_j) $ โ the final order of the cars.
## Output Format
The first line of the output should contain a single integer $ m $ โ the maximum possible number of overtakes that can occur during the race.
Each of the next $ m $ lines should contain two integers $ x $ and $ y $ ( $ 1 \le x, y \le n $ , $ x \ne y $ ) representing an overtake event, where car $ x $ overtakes car $ y $ . This means that car $ x $ was directly behind car $ y $ and overtakes it. The overtakes must be listed in the order they occurred during the race.
After all $ m $ overtakes have occurred, the cars must arrive at the finish line in the order $ c_1, c_2, \ldots, c_n $ . Note that any car $ x $ should not overtake another car $ y $ more than once.
If there are multiple possible longest sequences of overtakes, output any of them.
## Sample #1
### Sample Input #1
```
3
2 3 1
```
### Sample Output #1
```
4
2 1
3 1
3 2
2 3
```
## Sample #2
### Sample Input #2
```
1
1
```
### Sample Output #2
```
0
```
## Sample #3
### Sample Input #3
```
2
1 2
```
### Sample Output #3
```
2
2 1
1 2
```
## Limit
Time Limit
3.00s
Memory Limit
1000.00MB |
2051 | G | Snakes | ["bitmasks", "dp", "dsu", "graphs"] | https://codeforces.com/problemset/problem/2051/G | 1734878100 | en | codeforces | # Snakes
## Problem Description
Suppose you play a game where the game field looks like a strip of $ 1 \times 10^9 $ square cells, numbered from $ 1 $ to $ 10^9 $ .
You have $ n $ snakes (numbered from $ 1 $ to $ n $ ) you need to place into some cells. Initially, each snake occupies exactly one cell, and you can't place more than one snake into one cell. After that, the game starts.
The game lasts for $ q $ seconds. There are two types of events that may happen each second:
- snake $ s_i $ enlarges: if snake $ s_i $ occupied cells $ [l, r] $ , it enlarges to a segment $ [l, r + 1] $ ;
- snake $ s_i $ shrinks: if snake $ s_i $ occupied cells $ [l, r] $ , it shrinks to a segment $ [l + 1, r] $ .
Each second, exactly one of the events happens.
If at any moment of time, any snake runs into some obstacle (either another snake or the end of the strip), you lose. Otherwise, you win with the score equal to the maximum cell occupied by any snake so far.
What is the minimum possible score you can achieve?
## Input Format
The first line contains two integers $ n $ and $ q $ ( $ 1 \le n \le 20 $ ; $ 1 \le q \le 2 \cdot 10^5 $ ) โ the number of snakes and the number of events. Next $ q $ lines contain the description of events โ one per line.
The $ i $ -th line contains
- either " $ s_i $ +" ( $ 1 \le s_i \le n $ ) meaning that the $ s_i $ -th snake enlarges
- or " $ s_i $ -" ( $ 1 \le s_i \le n $ ) meaning that the $ s_i $ -th snake shrinks.
Additional constraint on the input: the given sequence of events is valid, i. e. a snake of length $ 1 $ never shrinks.
## Output Format
Print one integer โ the minimum possible score.
## Sample #1
### Sample Input #1
```
3 6
1 +
1 -
3 +
3 -
2 +
2 -
```
### Sample Output #1
```
4
```
## Sample #2
### Sample Input #2
```
5 13
5 +
3 +
5 -
2 +
4 +
3 +
5 +
5 -
2 +
3 -
3 +
3 -
2 +
```
### Sample Output #2
```
11
```
## Hint
In the first test, the optimal strategy is to place the second snake at cell $ 1 $ , the third snake โ at $ 2 $ , and the first one โ at $ 3 $ . The maximum occupied cell is cell $ 4 $ , and it's the minimum possible score.
In the second test, one of the optimal strategies is to place:
- snake $ 2 $ at position $ 1 $ ;
- snake $ 3 $ at position $ 4 $ ;
- snake $ 5 $ at position $ 6 $ ;
- snake $ 1 $ at position $ 9 $ ;
- snake $ 4 $ at position $ 10 $ .
## Limit
Time Limit
3.00s
Memory Limit
500.00MB | |
2051 | F | Joker | ["brute force", "greedy", "implementation", "math"] | https://codeforces.com/problemset/problem/2051/F | 1734878100 | en | codeforces | # Joker
## Problem Description
Consider a deck of $ n $ cards. The positions in the deck are numbered from $ 1 $ to $ n $ from top to bottom. A joker is located at position $ m $ .
$ q $ operations are applied sequentially to the deck. During the $ i $ -th operation, you need to take the card at position $ a_i $ and move it either to the beginning or to the end of the deck. For example, if the deck is $ [2, 1, 3, 5, 4] $ , and $ a_i=2 $ , then after the operation the deck will be either $ [1, 2, 3, 5, 4] $ (the card from the second position moved to the beginning) or $ [2, 3, 5, 4, 1] $ (the card from the second position moved to the end).
Your task is to calculate the number of distinct positions where the joker can be after each operation.
## Input Format
The first line contains a single integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
The first line of each test case contains three integers $ n $ , $ m $ , and $ q $ ( $ 2 \le n \le 10^9 $ ; $ 1 \le m \le n $ ; $ 1 \le q \le 2 \cdot 10^5 $ ).
The second line contains $ q $ integers $ a_1, a_2, \dots, a_q $ ( $ 1 \le a_i \le n $ ).
Additional constraint on the input: the sum of $ q $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, print $ q $ integers โ the number of distinct positions where the joker can be after each operation.
## Sample #1
### Sample Input #1
```
5
6 5 3
1 2 3
2 1 4
2 1 1 2
5 3 1
3
3 2 4
2 1 1 1
18 15 4
13 15 1 16
```
### Sample Output #1
```
2 3 5
2 2 2 2
2
2 3 3 3
2 4 6 8
```
## Limit
Time Limit
2.00s
Memory Limit
250.00MB | |
2051 | E | Best Price | ["binary search", "brute force", "data structures", "greedy", "sortings"] | https://codeforces.com/problemset/problem/2051/E | 1734878100 | en | codeforces | # Best Price
## Problem Description
A batch of Christmas trees has arrived at the largest store in Berland. $ n $ customers have already come to the store, wanting to buy them.
Before the sales begin, the store needs to determine the price for one tree (the price is the same for all customers). To do this, the store has some information about each customer.
For the $ i $ -th customer, two integers $ a_i $ and $ b_i $ are known, which define their behavior:
- if the price of the product is at most $ a_i $ , the customer will buy a tree and leave a positive review;
- otherwise, if the price of the product is at most $ b_i $ , the customer will buy a tree but leave a negative review;
- otherwise, the customer will not buy a tree at all.
Your task is to calculate the maximum possible earnings for the store, given that it can receive no more than $ k $ negative reviews.
## Input Format
The first line contains a single integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
The first line of each test case contains two integers $ n $ and $ k $ ( $ 1 \le n \le 2 \cdot 10^5 $ ; $ 0 \le k \le n $ ).
The second line contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ 1 \le a_i \le 2 \cdot 10^9 $ ).
The third line contains $ n $ integers $ b_1, b_2, \dots, b_n $ ( $ 1 \le b_i \le 2 \cdot 10^9 $ ; $ a_i < b_i $ ).
Additional constraint on the input: the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, print a single integer โ the maximum possible earnings for the store, given that it can receive no more than $ k $ negative reviews.
## Sample #1
### Sample Input #1
```
5
2 0
2 1
3 4
1 1
2
5
3 3
1 5 2
3 6 4
4 3
2 3 2 8
3 7 3 9
3 1
2 9 5
12 14 9
```
### Sample Output #1
```
2
5
9
14
15
```
## Hint
Consider the example from the statement:
- In the first test case, the price should be set to $ 1 $ . Then both customers will buy one tree each and leave no negative reviews;
- In the second test case, the price should be set to $ 5 $ . Then the only customer will buy a tree and leave a negative review;
- In the third test case, the price should be set to $ 3 $ . Then all customers will buy one tree each, and the store will receive two negative reviews.
- In the fourth test case, the price should be set to $ 7 $ . Then two customers will buy one tree each, and the store will receive one negative review.
## Limit
Time Limit
2.00s
Memory Limit
250.00MB | |
2051 | D | Counting Pairs | ["binary search", "sortings", "two pointers"] | https://codeforces.com/problemset/problem/2051/D | 1734878100 | en | codeforces | # Counting Pairs
## Problem Description
You are given a sequence $ a $ , consisting of $ n $ integers, where the $ i $ -th element of the sequence is equal to $ a_i $ . You are also given two integers $ x $ and $ y $ ( $ x \le y $ ).
A pair of integers $ (i, j) $ is considered interesting if the following conditions are met:
- $ 1 \le i < j \le n $ ;
- if you simultaneously remove the elements at positions $ i $ and $ j $ from the sequence $ a $ , the sum of the remaining elements is at least $ x $ and at most $ y $ .
Your task is to determine the number of interesting pairs of integers for the given sequence $ a $ .
## Input Format
The first line contains one integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
Each test case consists of two lines:
- The first line contains three integers $ n, x, y $ ( $ 3 \le n \le 2 \cdot 10^5 $ , $ 1 \le x \le y \le 2 \cdot 10^{14} $ );
- The second line contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ 1 \le a_i \le 10^{9} $ ).
Additional constraint on the input: the sum of $ n $ across all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output one integer โ the number of interesting pairs of integers for the given sequence $ a $ .
## Sample #1
### Sample Input #1
```
7
4 8 10
4 6 3 6
6 22 27
4 9 6 3 4 5
3 8 10
3 2 1
3 1 1
2 3 4
3 3 6
3 2 1
4 4 12
3 3 2 1
6 8 8
1 1 2 2 2 3
```
### Sample Output #1
```
4
7
0
0
1
5
6
```
## Hint
In the first example, there are $ 4 $ interesting pairs of integers:
1. $ (1, 2) $ ;
2. $ (1, 4) $ ;
3. $ (2, 3) $ ;
4. $ (3, 4) $ .
## Limit
Time Limit
2.00s
Memory Limit
250.00MB | |
2051 | C | Preparing for the Exam | ["constructive algorithms", "implementation"] | https://codeforces.com/problemset/problem/2051/C | 1734878100 | en | codeforces | # Preparing for the Exam
## Problem Description
Monocarp is preparing for his first exam at the university. There are $ n $ different questions which can be asked during the exam, numbered from $ 1 $ to $ n $ . There are $ m $ different lists of questions; each list consists of exactly $ n-1 $ different questions. Each list $ i $ is characterized by one integer $ a_i $ , which is the index of the only question which is not present in the $ i $ -th list. For example, if $ n = 4 $ and $ a_i = 3 $ , the $ i $ -th list contains questions $ [1, 2, 4] $ .
During the exam, Monocarp will receive one of these $ m $ lists of questions. Then, the professor will make Monocarp answer all questions from the list. So, Monocarp will pass only if he knows all questions from the list.
Monocarp knows the answers for $ k $ questions $ q_1, q_2, \dots, q_k $ . For each list, determine if Monocarp will pass the exam if he receives that list.
## Input Format
The first line contains one integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
Each test case consists of three lines:
- the first line contains three integers $ n $ , $ m $ and $ k $ ( $ 2 \le n \le 3 \cdot 10^5 $ ; $ 1 \le m, k \le n $ );
- the second line contains $ m $ distinct integers $ a_1, a_2, \dots, a_m $ ( $ 1 \le a_i \le n $ ; $ a_i < a_{i+1} $ );
- the third line contains $ k $ distinct integers $ q_1, q_2, \dots, q_k $ ( $ 1 \le q_i \le n $ ; $ q_i < q_{i+1} $ ).
Additional constraints on the input:
- the sum of $ n $ over all test cases does not exceed $ 3 \cdot 10^5 $ .
## Output Format
For each test case, print a string of $ m $ characters. The $ i $ -th character should be 1 if Monocarp passes the exam if he receives the $ i $ -th question list, 0 if Monocarp won't pass.
## Sample #1
### Sample Input #1
```
4
4 4 3
1 2 3 4
1 3 4
5 4 3
1 2 3 4
1 3 4
4 4 4
1 2 3 4
1 2 3 4
2 2 1
1 2
2
```
### Sample Output #1
```
0100
0000
1111
10
```
## Hint
In the first test case, Monocarp knows the questions $ [1, 3, 4] $ . Let's consider all the question lists:
- the first list consists of questions $ [2, 3, 4] $ . Monocarp doesn't know the $ 2 $ -nd question, so he won't pass;
- the second list consists of questions $ [1, 3, 4] $ . Monocarp knows all these questions, so he will pass;
- the third list consists of questions $ [1, 2, 4] $ . Monocarp doesn't know the $ 2 $ -nd question, so he won't pass;
- the fourth list consists of questions $ [1, 2, 3] $ . Monocarp doesn't know the $ 2 $ -nd question, so he won't pass.
## Limit
Time Limit
1.50s
Memory Limit
250.00MB | |
2051 | B | Journey | ["binary search", "math"] | https://codeforces.com/problemset/problem/2051/B | 1734878100 | en | codeforces | # Journey
## Problem Description
Monocarp decided to embark on a long hiking journey.
He decided that on the first day he would walk $ a $ kilometers, on the second day he would walk $ b $ kilometers, on the third day he would walk $ c $ kilometers, on the fourth day, just like on the first, he would walk $ a $ kilometers, on the fifth day, just like on the second, he would walk $ b $ kilometers, on the sixth day, just like on the third, he would walk $ c $ kilometers, and so on.
Monocarp will complete his journey on the day when he has walked at least $ n $ kilometers in total. Your task is to determine the day on which Monocarp will complete his journey.
## Input Format
The first line contains one integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
Each test case consists of one line containing four integers $ n $ , $ a $ , $ b $ , $ c $ ( $ 1 \le n \le 10^9 $ ; $ 1 \le a, b, c \le 10^6 $ ).
## Output Format
For each test case, output one integer โ the day on which Monocarp will have walked at least $ n $ kilometers in total and will complete his journey.
## Sample #1
### Sample Input #1
```
4
12 1 5 3
6 6 7 4
16 3 4 1
1000000000 1 1 1
```
### Sample Output #1
```
5
1
6
1000000000
```
## Hint
In the first example, over the first four days, Monocarp will cover $ 1 + 5 + 3 + 1 = 10 $ kilometers. On the fifth day, he will cover another $ 5 $ kilometers, meaning that in total over five days he will have covered $ 10 + 5 = 15 $ kilometers. Since $ n = 12 $ , Monocarp will complete his journey on the fifth day.
In the second example, Monocarp will cover $ 6 $ kilometers on the first day. Since $ n = 6 $ , Monocarp will complete his journey on the very first day.
In the third example, Monocarp will cover $ 3 + 4 + 1 + 3 + 4 + 1 = 16 $ kilometers over the first six days. Since $ n = 16 $ , Monocarp will complete his journey on the sixth day.
## Limit
Time Limit
1.00s
Memory Limit
250.00MB | |
2051 | A | Preparing for the Olympiad | ["greedy"] | https://codeforces.com/problemset/problem/2051/A | 1734878100 | en | codeforces | # Preparing for the Olympiad
## Problem Description
Monocarp and Stereocarp are preparing for the Olympiad. There are $ n $ days left until the Olympiad. On the $ i $ -th day, if Monocarp plans to practice, he will solve $ a_i $ problems. Similarly, if Stereocarp plans to practice on the same day, he will solve $ b_i $ problems.
Monocarp can train on any day he wants. However, Stereocarp watches Monocarp and follows a different schedule: if Monocarp trained on day $ i $ and $ i < n $ , then Stereocarp will train on day $ (i+1) $ .
Monocarp wants to organize his training process in a way that the difference between the number of problems he solves and the number of problems Stereocarp solves is as large as possible. Formally, Monocarp wants to maximize the value of $ (m-s) $ , where $ m $ is the number of problems he solves, and $ s $ is the number of problems Stereocarp solves. Help Monocarp determine the maximum possible difference in the number of solved problems between them.
## Input Format
The first line contains a single integer $ t $ ( $ 1 \le t \le 10^3 $ ) โ the number of test cases.
The first line of each test case contains a single integer $ n $ ( $ 1 \le n \le 100 $ ).
The second line contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ 1 \le a_i \le 100 $ ).
The third line contains $ n $ integers $ b_1, b_2, \dots, b_n $ ( $ 1 \le b_i \le 100 $ ).
## Output Format
For each test case, print a single integer โ the maximum possible difference between the number of problems Monocarp solves and the number of problems Stereocarp solves.
## Sample #1
### Sample Input #1
```
4
2
3 2
2 1
1
5
8
3
1 1 1
2 2 2
6
8 2 5 6 2 6
8 2 7 4 3 4
```
### Sample Output #1
```
4
5
1
16
```
## Hint
Let's analyze the example from the statement:
- In the first test case, it is optimal for Monocarp to train both days; then Stereocarp will train on day $ 2 $ .
- In the second test case, it is optimal for Monocarp to train on the only day, and Stereocarp will not train at all.
- In the third test case, it is optimal for Monocarp to train on the last day (and only on that day).
- In the fourth test case, it is optimal for Monocarp to train on days $ 1, 3, 4, 6 $ ; then Stereocarp will train on days $ 2, 4, 5 $ .
## Limit
Time Limit
2.00s
Memory Limit
250.00MB | |
2050 | G | Tree Destruction | ["dfs and similar", "dp", "trees"] | 1900 | https://codeforces.com/problemset/problem/2050/G | 1733409300 | en | codeforces | # Tree Destruction
## Problem Description
Given a tree $ ^{\text{โ}} $ with $ n $ vertices. You can choose two vertices $ a $ and $ b $ once and remove all vertices on the path from $ a $ to $ b $ , including the vertices themselves. If you choose $ a=b $ , only one vertex will be removed.
Your task is to find the maximum number of connected components $ ^{\text{โ }} $ that can be formed after removing the path from the tree.
$ ^{\text{โ}} $ A tree is a connected graph without cycles.
$ ^{\text{โ }} $ A connected component is a set of vertices such that there is a path along the edges from any vertex to any other vertex in the set (and it is not possible to reach vertices not belonging to this set)
## Input Format
The first line of the input contains one integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
The first line of each test case contains one integer $ n $ ( $ 2 \le n \le 2 \cdot 10^5 $ ) โ the size of the tree.
The next $ n-1 $ lines contain two integers $ u $ and $ v $ ( $ 1 \le u, v \le n $ , $ u \ne v $ ) โ the vertices connected by an edge. It is guaranteed that the edges form a tree.
It is guaranteed that the sum of $ n $ across all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output one integer โ the maximum number of connected components that can be achieved using the described operation.
## Sample #1
### Sample Input #1
```
6
2
1 2
5
1 2
2 3
3 4
3 5
4
1 2
2 3
3 4
5
2 1
3 1
4 1
5 4
6
2 1
3 1
4 1
5 3
6 3
6
2 1
3 2
4 2
5 3
6 4
```
### Sample Output #1
```
1
3
2
3
4
3
```
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2050 | F | Maximum modulo equality | ["data structures", "divide and conquer", "math", "number theory"] | 1700 | https://codeforces.com/problemset/problem/2050/F | 1733409300 | en | codeforces | # Maximum modulo equality
## Problem Description
You are given an array $ a $ of length $ n $ and $ q $ queries $ l $ , $ r $ .
For each query, find the maximum possible $ m $ , such that all elements $ a_l $ , $ a_{l+1} $ , ..., $ a_r $ are equal modulo $ m $ . In other words, $ a_l \bmod m = a_{l+1} \bmod m = \dots = a_r \bmod m $ , where $ a \bmod b $ โ is the remainder of division $ a $ by $ b $ . In particular, when $ m $ can be infinite, print $ 0 $ .
## Input Format
The first line contains a single integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
The first line of each test case contains two integers $ n $ , $ q $ ( $ 1 \le n, q \le 2\cdot 10^5 $ ) โ the length of the array and the number of queries.
The second line of each test case contains $ n $ integers $ a_i $ ( $ 1 \le a_i \le 10^9 $ ) โ the elements of the array.
In the following $ q $ lines of each test case, two integers $ l $ , $ r $ are provided ( $ 1 \le l \le r \le n $ ) โ the range of the query.
It is guaranteed that the sum of $ n $ across all test cases does not exceed $ 2\cdot 10^5 $ , and the sum of $ q $ does not exceed $ 2\cdot 10^5 $ .
## Output Format
For each query, output the maximum value $ m $ described in the statement.
## Sample #1
### Sample Input #1
```
3
5 5
5 14 2 6 3
4 5
1 4
2 4
3 5
1 1
1 1
7
1 1
3 2
1 7 8
2 3
1 2
```
### Sample Output #1
```
3 1 4 1 0
0
1 6
```
## Hint
In the first query of the first sample, $ 6 \bmod 3 = 3 \bmod 3 = 0 $ . It can be shown that for greater $ m $ , the required condition will not be fulfilled.
In the third query of the first sample, $ 14 \bmod 4 = 2 \bmod 4 = 6 \bmod 4 = 2 $ . It can be shown that for greater $ m $ , the required condition will not be fulfilled.
## Limit
Time Limit
5.00s
Memory Limit
250.00MB |
2050 | E | Three Strings | ["dp", "implementation", "strings"] | 1500 | https://codeforces.com/problemset/problem/2050/E | 1733409300 | en | codeforces | # Three Strings
## Problem Description
You are given three strings: $ a $ , $ b $ , and $ c $ , consisting of lowercase Latin letters. The string $ c $ was obtained in the following way:
1. At each step, either string $ a $ or string $ b $ was randomly chosen, and the first character of the chosen string was removed from it and appended to the end of string $ c $ , until one of the strings ran out. After that, the remaining characters of the non-empty string were added to the end of $ c $ .
2. Then, a certain number of characters in string $ c $ were randomly changed.
For example, from the strings $ a=\color{red}{\text{abra}} $ and $ b=\color{blue}{\text{cada}} $ , without character replacements, the strings $ \color{blue}{\text{ca}}\color{red}{\text{ab}}\color{blue}{\text{d}}\color{red}{\text{ra}}\color{blue}{\text{a}} $ , $ \color{red}{\text{abra}}\color{blue}{\text{cada}} $ , $ \color{red}{\text{a}}\color{blue}{\text{cada}}\color{red}{\text{bra}} $ could be obtained.
Find the minimum number of characters that could have been changed in string $ c $ .
## Input Format
The first line of the input contains a single integer $ t $ ( $ 1 \le t \le 10^3 $ ) โ the number of test cases.
The first line of each test case contains one string of lowercase Latin letters $ a $ ( $ 1 \leq |a| \leq 10^3 $ ) โ the first string, where $ |a| $ denotes the length of string $ a $ .
The second line of each test case contains one string of lowercase Latin letters $ b $ ( $ 1 \leq |b| \leq 10^3 $ ) โ the second string, where $ |b| $ denotes the length of string $ b $ .
The third line of each test case contains one string of lowercase Latin letters $ c $ ( $ |c| = |a| + |b| $ ) โ the third string.
It is guaranteed that the sum of $ |a| $ across all test cases does not exceed $ 2 \cdot 10^3 $ . Also, the sum of $ |b| $ across all test cases does not exceed $ 2 \cdot 10^3 $ .
## Output Format
For each test case, output a single integer โ the minimum number of characters that could have been changed in string $ c $ .
## Sample #1
### Sample Input #1
```
7
a
b
cb
ab
cd
acbd
ab
ba
aabb
xxx
yyy
xyxyxy
a
bcd
decf
codes
horse
codeforces
egg
annie
egaegaeg
```
### Sample Output #1
```
1
0
2
0
3
2
3
```
## Limit
Time Limit
2.50s
Memory Limit
250.00MB |
2050 | D | Digital string maximization | ["brute force", "greedy", "math", "strings"] | 1300 | https://codeforces.com/problemset/problem/2050/D | 1733409300 | en | codeforces | # Digital string maximization
## Problem Description
You are given a string $ s $ , consisting of digits from $ 0 $ to $ 9 $ . In one operation, you can pick any digit in this string, except for $ 0 $ or the leftmost digit, decrease it by $ 1 $ , and then swap it with the digit left to the picked.
For example, in one operation from the string $ 1023 $ , you can get $ 1103 $ or $ 1022 $ .
Find the lexicographically maximum string you can obtain after any number of operations.
## Input Format
The first line of the input consists of an integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
Each test case consists of a single line consisting of a digital string $ s $ ( $ 1 \le |s| \le 2\cdot 10^5 $ ), where $ |s| $ denotes the length of $ s $ . The string does not contain leading zeroes.
It is guaranteed that the sum of $ |s| $ of all test cases doesn't exceed $ 2\cdot 10^5 $ .
## Output Format
For each test case, print the answer on a separate line.
## Sample #1
### Sample Input #1
```
6
19
1709
11555
51476
9876543210
5891917899
```
### Sample Output #1
```
81
6710
33311
55431
9876543210
7875567711
```
## Hint
In the first example, the following sequence of operations is suitable: $ 19 \rightarrow 81 $ .
In the second example, the following sequence of operations is suitable: $ 1709 \rightarrow 1780 \rightarrow 6180 \rightarrow 6710 $ .
In the fourth example, the following sequence of operations is suitable: $ 51476 \rightarrow 53176 \rightarrow 53616 \rightarrow 53651 \rightarrow 55351 \rightarrow 55431 $ .
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2050 | C | Uninteresting Number | ["brute force", "dp", "math"] | 1200 | https://codeforces.com/problemset/problem/2050/C | 1733409300 | en | codeforces | # Uninteresting Number
## Problem Description
You are given a number $ n $ with a length of no more than $ 10^5 $ .
You can perform the following operation any number of times: choose one of its digits, square it, and replace the original digit with the result. The result must be a digit (that is, if you choose the digit $ x $ , then the value of $ x^2 $ must be less than $ 10 $ ).
Is it possible to obtain a number that is divisible by $ 9 $ through these operations?
## Input Format
The first line contains an integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
The only line of each test case contains the number $ n $ , without leading zeros. The length of the number does not exceed $ 10^5 $ .
It is guaranteed that the sum of the lengths of the numbers across all test cases does not exceed $ 10^5 $ .
## Output Format
For each test case, output "YES" if it is possible to obtain a number divisible by $ 9 $ using the described operations, and "NO" otherwise.
You can output each letter in any case (lowercase or uppercase). For example, the strings "yEs", "yes", "Yes", and "YES" will be accepted as a positive answer.
## Sample #1
### Sample Input #1
```
9
123
322
333333333333
9997
5472778912773
1234567890
23
33
52254522632
```
### Sample Output #1
```
NO
YES
YES
NO
NO
YES
NO
YES
YES
```
## Hint
In the first example, from the integer $ 123 $ , it is possible to obtain only $ 123 $ , $ 143 $ , $ 129 $ , and $ 149 $ , none of which are divisible by $ 9 $ .
In the second example, you need to replace the second digit with its square; then $ n $ will equal $ 342 = 38 \cdot 9 $ .
In the third example, the integer is already divisible by $ 9 $ .
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2050 | B | Transfusion | ["brute force", "greedy", "math"] | 1100 | https://codeforces.com/problemset/problem/2050/B | 1733409300 | en | codeforces | # Transfusion
## Problem Description
You are given an array $ a $ of length $ n $ . In one operation, you can pick an index $ i $ from $ 2 $ to $ n-1 $ inclusive, and do one of the following actions:
- Decrease $ a_{i-1} $ by $ 1 $ , then increase $ a_{i+1} $ by $ 1 $ .
- Decrease $ a_{i+1} $ by $ 1 $ , then increase $ a_{i-1} $ by $ 1 $ .
After each operation, all the values must be non-negative. Can you make all the elements equal after any number of operations?
## Input Format
First line of input consists of one integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
First line of each test case consists of one integer $ n $ ( $ 3 \le n \le 2\cdot 10^5 $ ).
Second line of each test case consists of $ n $ integers $ a_i $ ( $ 1 \le a_i \le 10^9 $ ).
It is guaranteed that the sum of $ n $ of all test cases doesn't exceed $ 2\cdot 10^5 $ .
## Output Format
For each test case, print "YES" without quotation marks if it is possible to make all the elements equal after any number of operations; otherwise, print "NO" without quotation marks.
You can print answers in any register: "yes", "YeS", "nO" โ will also be considered correct.
## Sample #1
### Sample Input #1
```
8
3
3 2 1
3
1 1 3
4
1 2 5 4
4
1 6 6 1
5
6 2 1 4 2
4
1 4 2 1
5
3 1 2 1 3
3
2 4 2
```
### Sample Output #1
```
YES
NO
YES
NO
YES
NO
NO
NO
```
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2050 | A | Line Breaks | ["implementation"] | 800 | https://codeforces.com/problemset/problem/2050/A | 1733409300 | en | codeforces | # Line Breaks
## Problem Description
Kostya has a text $ s $ consisting of $ n $ words made up of Latin alphabet letters. He also has two strips on which he must write the text. The first strip can hold $ m $ characters, while the second can hold as many as needed.
Kostya must choose a number $ x $ and write the first $ x $ words from $ s $ on the first strip, while all the remaining words are written on the second strip. To save space, the words are written without gaps, but each word must be entirely on one strip.
Since space on the second strip is very valuable, Kostya asks you to choose the maximum possible number $ x $ such that all words $ s_1, s_2, \dots, s_x $ fit on the first strip of length $ m $ .
## Input Format
The first line contains an integer $ t $ ( $ 1 \le t \le 1000 $ ) โ the number of test cases.
The first line of each test case contains two integers $ n $ and $ m $ ( $ 1 \le n \le 50 $ ; $ 1 \le m \le 500 $ ) โ the number of words in the list and the maximum number of characters that can be on the first strip.
The next $ n $ lines contain one word $ s_i $ of lowercase Latin letters, where the length of $ s_i $ does not exceed $ 10 $ .
## Output Format
For each test case, output the maximum number of words $ x $ such that the first $ x $ words have a total length of no more than $ m $ .
## Sample #1
### Sample Input #1
```
5
3 1
a
b
c
2 9
alpha
beta
4 12
hello
world
and
codeforces
3 2
ab
c
d
3 2
abc
ab
a
```
### Sample Output #1
```
1
2
2
1
0
```
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2049 | F | MEX OR Mania | ["bitmasks", "brute force", "data structures", "dsu", "implementation"] | 2700 | https://codeforces.com/problemset/problem/2049/F | 1734705300 | en | codeforces | # MEX OR Mania
## Problem Description
An integer sequence $ b_1, b_2, \ldots, b_n $ is good if $ \operatorname{mex}(b_1, b_2, \ldots, b_n) - (b_1 | b_2 | \ldots | b_n) = 1 $ . Here, $ \operatorname{mex(c)} $ denotes the MEX $ ^{\text{โ}} $ of the collection $ c $ , and $ | $ is the [bitwise OR](https://en.wikipedia.org/wiki/Bitwise_operation#OR) operator.
Shohag has an integer sequence $ a_1, a_2, \ldots, a_n $ . He will perform the following $ q $ updates on $ a $ :
- $ i $ $ x $ โ increase $ a_i $ by $ x $ .
After each update, help him find the length of the longest good subarray $ ^{\text{โ }} $ of $ a $ .
$ ^{\text{โ}} $ The minimum excluded (MEX) of a collection of integers $ c_1, c_2, \ldots, c_k $ is defined as the smallest non-negative integer $ y $ which does not occur in the collection $ c $ .
$ ^{\text{โ }} $ An array $ d $ is a subarray of an array $ f $ if $ d $ can be obtained from $ f $ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^4 $ ). The description of the test cases follows.
The first line of each test case contains two space-separated integers $ n $ and $ q $ ( $ 1 \le n, q \le 10^5 $ ).
The second line of each test case contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 0 \le a_i \le n $ ).
The next $ q $ lines of each test case are of the following form:
- $ i $ $ x $ ( $ 1 \le i, x \le n $ ) โ it means you should increase $ a_i $ by $ x $ .
It is guaranteed that the sum of $ n $ over all test cases doesn't exceed $ 10^5 $ and the sum of $ q $ doesn't exceed $ 10^5 $ .
## Output Format
For each test case, output $ q $ lines โ on the $ i $ -th line output the length of the longest good subarray of $ a $ after the $ i $ -th update.
## Sample #1
### Sample Input #1
```
2
6 3
0 0 1 0 1 0
6 1
3 2
6 3
3 1
1 3 1
1 1
```
### Sample Output #1
```
6
3
2
0
```
## Hint
In the first test case, after the first update, the array becomes $ [0, 0, 1, 0, 1, 1] $ , and here the whole array is good because $ \operatorname{mex}([0, 0, 1, 0, 1, 1]) - (0 | 0 | 1 | 0 | 1 | 1) = 2 - 1 = 1 $ .
After the second update, the array becomes $ [0, 0, 3, 0, 1, 1] $ , and here the subarray $ [0, 1, 1] $ has the maximum length among all the good subarrays.
Finally, after the third update, the array becomes $ [0, 0, 3, 0, 1, 4] $ , and here the subarrays $ [0, 0] $ and $ [0, 1] $ both have the maximum length among all the good subarrays.
## Limit
Time Limit
4.00s
Memory Limit
1000.00MB |
2049 | E | Broken Queries | ["binary search", "bitmasks", "brute force", "constructive algorithms", "implementation", "interactive"] | 2400 | https://codeforces.com/problemset/problem/2049/E | 1734705300 | en | codeforces | # Broken Queries
## Problem Description
You, a wizard whose creation was destroyed by a dragon, are determined to hunt it down with a magical AOE tracker. But it seems to be toyed with...
This is an interactive problem.
There is a hidden binary array $ a $ of length $ n $ ( $ \mathbf{n} $ is a power of 2) and a hidden integer $ k\ (2 \le k \le n - 1) $ . The array $ a $ contains exactly one 1 (and all other elements are 0). For two integers $ l $ and $ r $ ( $ 1 \le l \le r \le n $ ), define the range sum $ s(l, r) = a_l + a_{l+1} + \cdots + a_r $ .
You have a magical device that takes ranges and returns range sums, but it returns the opposite result when the range has length at least $ k $ . Formally, in one query, you can give it a pair of integers $ [l, r] $ where $ 1 \le l \le r \le n $ , and it will return either $ 0 $ or $ 1 $ according to the following rules:
- If $ r - l + 1 < k $ , it will return $ s(l, r) $ .
- If $ r - l + 1 \ge k $ , it will return $ 1 - s(l, r) $ .
Find $ k $ using at most $ 33 $ queries.
The device is not adaptive. It means that the hidden $ a $ and $ k $ are fixed before the interaction and will not change during the interaction.
## Input Format
## Output Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 500 $ ). The description of the test cases follows.
The first line of each test case contains one positive integer $ n $ ( $ 4 \le n \le 2^{30} $ ) โ the length of the hidden array. It is guaranteed that $ \mathbf{n} $ is a power of 2; that is, $ n = 2^m $ for some non-negative integer $ m $ .
You can make queries in the following way โ print one line of the form " $ \mathtt{?}\,l\,r $ " where $ 1 \le l \le r \le n $ . After that, read a single integer: $ 0 $ or $ 1 $ , as described in the statement.
If you want to print the answer $ k $ , output " $ \mathtt{!}\,k $ ". Then, the interaction continues with the next test case.
Printing the answer does not count towards the number of queries made.
After printing each query do not forget to output the end of line and flush $ ^{\text{โ}} $ the output. Otherwise, you will get Idleness limit exceeded verdict.
If, at any interaction step, you read $ -1 $ instead of valid data, your solution must exit immediately. This means that your solution will receive Wrong answer because of an invalid query or any other mistake. Failing to exit can result in an arbitrary verdict because your solution will continue to read from a closed stream.
Hacks
The format of the hacks should be the following: the first line should contain one integer $ t $ ( $ 1 \le t \le 100 $ ) โ the number of test cases. The description of the test cases should follow.
The first and only line of each test case should contain three integers $ n $ , $ p $ , and $ k $ ( $ 4 \le n \le 2^{30} $ , $ 1 \le p \le n $ , $ 2 \le k \le n - 1 $ ) โ the length of the hidden array $ a $ , the position of the only 1 in $ a $ , and the hidden $ k $ . $ n $ must be a power of $ 2 $ .
$ ^{\text{โ}} $ To flush, use:
- fflush(stdout) or cout.flush() in C++;
- sys.stdout.flush() in Python;
- see the documentation for other languages.
## Sample #1
### Sample Input #1
```
2
8
0
0
1
0
4
1
0
```
### Sample Output #1
```
? 3 5
? 1 8
? 4 8
? 3 8
! 6
? 3 3
? 3 4
! 2
```
## Hint
In the first test case, $ k = 6 $ and the 1 in the hidden array is at index 6, so $ a = [0, 0, 0, 0, 0, 1, 0, 0] $ .
- For the query 3 5, since $ 5-3+1 = 3 < k $ , the device answers correctly. Since 6 is not contained in the range $ [3, 5] $ , the device answers $ 0 $ .
- For the query 1 8, since $ 8 - 1 + 1 = 8 \ge k $ , the device answers $ 0 $ incorrectly.
- For the query 4 8, since $ 8 - 4 + 1 = 5 < k $ , the device answers $ 1 $ correctly.
- For the query 3 8, since $ 8 - 3 + 1 = 6 \ge k $ , the device answers $ 0 $ incorrectly.
The example solution then outputs $ 6 $ as the answer, which is correct.In the second test case, $ k = 2 $ and the 1 in the hidden array is at index 3, so $ a = [0, 0, 1, 0] $ .
Note that the example solution may not have enough information to determine $ k $ above; this is only an example.
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2049 | D | Shift + Esc | ["brute force", "dp"] | 1900 | https://codeforces.com/problemset/problem/2049/D | 1734705300 | en | codeforces | # Shift + Esc
## Problem Description
After having fun with a certain contraption and getting caught, Evirir the dragon decides to put their magical skills to good use โ warping reality to escape fast!
You are given a grid with $ n $ rows and $ m $ columns of non-negative integers and an integer $ k $ . Let $ (i, j) $ denote the cell in the $ i $ -th row from the top and $ j $ -th column from the left ( $ 1 \le i \le n $ , $ 1 \le j \le m $ ). For every cell $ (i, j) $ , the integer $ a_{i, j} $ is written on the cell $ (i, j) $ .
You are initially at $ (1, 1) $ and want to go to $ (n, m) $ . You may only move down or right. That is, if you are at $ (i, j) $ , you can only move to $ (i+1, j) $ or $ (i, j+1) $ (if the corresponding cell exists).
Before you begin moving, you may do the following operation any number of times:
- Choose an integer $ i $ between $ 1 $ and $ n $ and cyclically shift row $ i $ to the left by $ 1 $ . Formally, simultaneously set $ a_{i,j} $ to $ a_{i,(j \bmod m) + 1} $ for all integers $ j $ ( $ 1 \le j \le m $ ).
Note that you may not do any operation after you start moving.After moving from $ (1, 1) $ to $ (n, m) $ , let $ x $ be the number of operations you have performed before moving, and let $ y $ be the sum of the integers written on visited cells (including $ (1, 1) $ and $ (n, m) $ ). Then the cost is defined as $ kx + y $ .
Find the minimum cost to move from $ (1, 1) $ to $ (n, m) $ .
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^4 $ ). The description of the test cases follows.
The first line contains three space-separated integers $ n $ , $ m $ , and $ k $ ( $ 1 \leq n, m \leq 200 $ , $ 0 \leq k \leq 10^9 $ ).
Then, $ n $ lines follow. The $ i $ -th line contains $ m $ space-separated integers, $ a_{i,1},\,a_{i,2},\,\ldots,\,a_{i,m} $ ( $ 0 \leq a_{i,j} \leq 10^9 $ ).
It is guaranteed that the sum of $ n \cdot m $ over all test cases does not exceed $ 5 \cdot 10^4 $ .
## Output Format
For each test case, output a single integer, the minimum cost to move from $ (1, 1) $ to $ (n, m) $ .
## Sample #1
### Sample Input #1
```
5
3 3 100
3 4 9
5 2 4
0 101 101
3 4 1
10 0 0 10
0 0 10 0
10 10 0 10
1 1 3
4
3 2 3
1 2
3 6
5 4
10 10 14
58 49 25 12 89 69 8 49 71 23
45 27 65 59 36 100 73 23 5 84
82 91 54 92 53 15 43 46 11 65
61 69 71 87 67 72 51 42 55 80
1 64 8 54 61 70 47 100 84 50
86 93 43 51 47 35 56 20 33 61
100 59 5 68 15 55 69 8 8 60
33 61 20 79 69 51 23 24 56 28
67 76 3 69 58 79 75 10 65 63
6 64 73 79 17 62 55 53 61 58
```
### Sample Output #1
```
113
6
4
13
618
```
## Hint
In the first test case, the minimum cost of $ 113 $ can be achieved as follows:
1. Cyclically shift row 3 once. The grid now becomes $ $$$\begin{bmatrix}3 & 4 & 9\\5 & 2 & 4\\101 & 101 & 0\end{bmatrix}. $ $ </li><li> Move as follows: $ (1, 1) \\to (1, 2) \\to (2, 2) \\to (2, 3) \\to (3, 3) $ . </li></ol><p> $ x = 1 $ operation is done before moving. The sum of integers on visited cells is $ y = 3 + 4 + 2 + 4 + 0 = 13 $ . Therefore, the cost is $ kx + y = 100 \\cdot 1 + 13 = 113 $ .</p><p>In the second test case, one can shift row 1 once, row 2 twice, and row 3 thrice. Then, the grid becomes $ $ \begin{bmatrix}0 & 0 & 10 & 10\\10 & 0 & 0 & 0\\10 & 10 & 10 & 0\end{bmatrix}. $ $ </p><p> $ x = 6 $ operations were done before moving, and there is a path of cost $ y = 0 $ . Therefore, the cost is $ 6 \\cdot 1 + 0 = 6$$$.
## Limit
Time Limit
2.50s
Memory Limit
500.00MB |
2049 | C | MEX Cycle | ["brute force", "constructive algorithms", "greedy", "implementation"] | 1500 | https://codeforces.com/problemset/problem/2049/C | 1734705300 | en | codeforces | # MEX Cycle
## Problem Description
Evirir the dragon has many friends. They have 3 friends! That is one more than the average dragon.
You are given integers $ n $ , $ x $ , and $ y $ . There are $ n $ dragons sitting in a circle. The dragons are numbered $ 1, 2, \ldots, n $ . For each $ i $ ( $ 1 \le i \le n $ ), dragon $ i $ is friends with dragon $ i - 1 $ and $ i + 1 $ , where dragon $ 0 $ is defined to be dragon $ n $ and dragon $ n + 1 $ is defined to be dragon $ 1 $ . Additionally, dragons $ x $ and $ y $ are friends with each other (if they are already friends, this changes nothing). Note that all friendships are mutual.
Output $ n $ non-negative integers $ a_1, a_2, \ldots, a_n $ such that for each dragon $ i $ ( $ 1 \le i \le n $ ), the following holds:
- Let $ f_1, f_2, \ldots, f_k $ be the friends of dragon $ i $ . Then $ a_i = \operatorname{mex}(a_{f_1}, a_{f_2}, \ldots, a_{f_k}) $ . $ ^{\text{โ}} $
$ ^{\text{โ}} $ The minimum excluded (MEX) of a collection of integers $ c_1, c_2, \ldots, c_m $ is defined as the smallest non-negative integer $ t $ which does not occur in the collection $ c $ .
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^4 $ ). The description of the test cases follows.
The first and only line of each test case contains three integers $ n $ , $ x $ , $ y $ ( $ 3 \le n \le 2 \cdot 10^5 $ , $ 1 \le x < y \le n $ ).
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output $ n $ space-separated non-negative integers $ a_1, a_2, \ldots, a_n $ ( $ 0 \le a_i \le 10^9 $ ) on a line that satisfy the condition in the statement. If there are multiple solutions, print any of them. It can be proven that under the problem constraints, a solution with $ 0 \le a_i \le 10^9 $ always exists.
## Sample #1
### Sample Input #1
```
7
5 1 3
4 2 4
6 3 5
7 3 6
3 2 3
5 1 5
6 2 5
```
### Sample Output #1
```
0 2 1 0 1
1 2 1 0
1 2 0 1 2 0
0 1 2 0 1 0 1
2 0 1
1 0 2 1 0
0 1 2 0 2 1
```
## Hint
For the first test case:
- $ i = 1 $ : Dragon $ 1 $ 's friends are dragons $ 2, 3, 5 $ . $ \operatorname{mex}(a_2, a_3, a_5) = \operatorname{mex}(2, 1, 1) = 0 = a_1 $ , so the condition for dragon $ 1 $ is satisfied.
- $ i = 2 $ : Dragon $ 2 $ 's friends are dragons $ 1, 3 $ . $ \operatorname{mex}(a_1, a_3) = \operatorname{mex}(0, 1) = 2 = a_2 $ .
- $ i = 3 $ : Dragon $ 3 $ 's friends are dragons $ 1, 2, 4 $ . $ \operatorname{mex}(a_1, a_2, a_4) = \operatorname{mex}(0, 2, 0) = 1 = a_3 $ .
- $ i = 4 $ : Dragon $ 4 $ 's friends are dragons $ 3, 5 $ . $ \operatorname{mex}(a_3, a_5) = \operatorname{mex}(1, 1) = 0 = a_4 $ .
- $ i = 5 $ : Dragon $ 5 $ 's friends are dragons $ 1, 4 $ . $ \operatorname{mex}(a_1, a_4) = \operatorname{mex}(0, 0) = 1 = a_5 $ .
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2049 | B | pspspsps | ["brute force", "constructive algorithms", "graph matchings", "implementation"] | 1300 | https://codeforces.com/problemset/problem/2049/B | 1734705300 | en | codeforces | # pspspsps
## Problem Description
Cats are attracted to pspspsps, but Evirir, being a dignified dragon, is only attracted to pspspsps with oddly specific requirements...
Given a string $ s = s_1s_2\ldots s_n $ of length $ n $ consisting of characters p, s, and . (dot), determine whether a permutation $ ^{\text{โ}} $ $ p $ of length $ n $ exists, such that for all integers $ i $ ( $ 1 \le i \le n $ ):
- If $ s_i $ is p, then $ [p_1, p_2, \ldots, p_i] $ forms a permutation (of length $ i $ );
- If $ s_i $ is s, then $ [p_i, p_{i+1}, \ldots, p_{n}] $ forms a permutation (of length $ n-i+1 $ );
- If $ s_i $ is ., then there is no additional restriction.
$ ^{\text{โ}} $ A permutation of length $ n $ is an array consisting of $ n $ distinct integers from $ 1 $ to $ n $ in arbitrary order. For example, $ [2,3,1,5,4] $ is a permutation, but $ [1,2,2] $ is not a permutation ( $ 2 $ appears twice in the array), and $ [1,3,4] $ is also not a permutation ( $ n=3 $ but there is $ 4 $ in the array).
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^4 $ ). The description of the test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 1 \le n \le 500 $ ), the length of $ s $ .
The second line of each test case contains a string $ s $ of length $ n $ that consists of the characters p, s, and ..
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 5000 $ .
## Output Format
For each test case, output YES or NO on a line. Output YES if there is such a permutation and NO otherwise.
You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.
## Sample #1
### Sample Input #1
```
9
4
s.sp
6
pss..s
5
ppppp
2
sp
4
.sp.
8
psss....
1
.
8
pspspsps
20
....................
```
### Sample Output #1
```
YES
NO
YES
YES
NO
NO
YES
NO
YES
```
## Hint
For the first test case, one permutation that works is $ p = [3, 4, 1, 2] $ . The restrictions are as follows:
- $ s_1 = $ s: $ [p_1, p_2, p_3, p_4] = [3, 4, 1, 2] $ forms a permutation.
- $ s_2 = $ .: No additional restriction.
- $ s_3 = $ s: $ [p_3, p_4] = [1, 2] $ forms a permutation.
- $ s_4 = $ p: $ [p_1, p_2, p_3, p_4] = [3, 4, 1, 2] $ forms a permutation.
For the second test case, it can be proven that there is no permutation that satisfies all restrictions.
For the third test case, one permutation that satisfies the constraints is $ p = [1, 2, 3, 4, 5] $ .
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2049 | A | MEX Destruction | ["greedy", "implementation"] | 800 | https://codeforces.com/problemset/problem/2049/A | 1734705300 | en | codeforces | # MEX Destruction
## Problem Description
Evirir the dragon snuck into a wizard's castle and found a mysterious contraption, and their playful instincts caused them to play with (destroy) it...
Evirir the dragon found an array $ a_1, a_2, \ldots, a_n $ of $ n $ non-negative integers.
In one operation, they can choose a non-empty subarray $ ^{\text{โ}} $ $ b $ of $ a $ and replace it with the integer $ \operatorname{mex}(b) $ $ ^{\text{โ }} $ . They want to use this operation any number of times to make $ a $ only contain zeros. It can be proven that this is always possible under the problem constraints.
What is the minimum number of operations needed?
$ ^{\text{โ}} $ An array $ c $ is a subarray of an array $ d $ if $ c $ can be obtained from $ d $ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.
$ ^{\text{โ }} $ The minimum excluded (MEX) of a collection of integers $ f_1, f_2, \ldots, f_k $ is defined as the smallest non-negative integer $ x $ which does not occur in the collection $ f $ .
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 200 $ ). The description of the test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 1 \le n \le 50 $ ), the length of $ a $ .
The second line of each test case contains $ n $ space-separated integers, $ a_1, a_2, \ldots, a_n $ ( $ 0 \le a_i \le 100 $ ).
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 500 $ .
## Output Format
For each test case, output a single integer on a line, the minimum number of operations needed to make $ a $ contain only zeros.
## Sample #1
### Sample Input #1
```
10
4
0 1 2 3
6
0 0 0 0 0 0
5
1 0 1 0 1
5
3 1 4 1 5
4
3 2 1 0
7
9 100 0 89 12 2 3
4
0 3 9 0
7
0 7 0 2 0 7 0
1
0
2
0 1
```
### Sample Output #1
```
1
0
2
1
1
2
1
2
0
1
```
## Hint
In the first test case, Evirir can choose the subarray $ b = [1, 2, 3] $ and replace it with $ \operatorname{mex}(1, 2, 3) = 0 $ , changing $ a $ from $ [0, \underline{1, 2, 3}] $ to $ [0, 0] $ (where the chosen subarray is underlined). Therefore, the answer is $ 1 $ .
In the second test case, $ a $ already contains only $ 0 $ s, so no operation is needed.
In the third test case, Evirir can change $ a $ as follows: $ [1, \underline{0, 1, 0, 1}] \to [\underline{1, 2}] \to [0] $ . Here, $ \operatorname{mex}(0, 1, 0, 1) = 2 $ and $ \operatorname{mex}(1, 2) = 0 $ .
In the fourth test case, Evirir can choose $ b $ to be the entire array $ a $ , changing $ a $ from $ [\underline{3, 1, 4, 1, 5}] $ to $ [0] $ .
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2048 | I2 | Kevin and Puzzle (Hard Version) | ["bitmasks", "fft", "math"] | 3500 | https://codeforces.com/problemset/problem/2048/I2 | 1734618900 | en | codeforces | # Kevin and Puzzle (Hard Version)
## Problem Description
This is the hard version of the problem. The difference between the versions is that in this version, you need to count the number of good arrays. You can hack only if you solved all versions of this problem.
Kevin is visiting the Red Church, and he found a puzzle on the wall.
For an array $ a $ , let $ c(l,r) $ indicate how many distinct numbers are among $ a_l, a_{l+1}, \ldots, a_r $ . In particular, if $ l > r $ , define $ c(l,r) = 0 $ .
You are given a string $ s $ of length $ n $ consisting of letters $ \texttt{L} $ and $ \texttt{R} $ only. Let a non-negative array $ a $ be called good, if the following conditions hold for $ 1 \leq i \leq n $ :
- if $ s_i=\verb!L! $ , then $ c(1,i-1)=a_i $ ;
- if $ s_i=\verb!R! $ , then $ c(i+1,n)=a_i $ .
You need to count the number of good arrays $ a $ . Since the answer may be large, you only need to output the answer modulo $ 998\,244\,353 $ .
## Input Format
Each test contains multiple test cases. The first line contains a single integer $ t $ ( $ 1\le t \le 10^4 $ ) โ the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 2\leq n\leq 2\cdot 10^5 $ ) โ the length of string $ s $ .
The second line of each test case contains a string $ s $ with a length $ n $ , containing only English uppercase letters $ \verb!L! $ and $ \verb!R! $ .
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2\cdot 10^5 $ .
## Output Format
For each test case, output the number of good arrays modulo $ 998\,244\,353 $ .
## Sample #1
### Sample Input #1
```
4
3
LLR
3
RRL
4
RRLR
5
LLRLR
```
### Sample Output #1
```
1
2
0
1
```
## Hint
All arrays satisfying the conditions can be found in the easy version of this problem.
## Limit
Time Limit
6.00s
Memory Limit
500.00MB |
2048 | I1 | Kevin and Puzzle (Easy Version) | ["constructive algorithms"] | 3500 | https://codeforces.com/problemset/problem/2048/I1 | 1734618900 | en | codeforces | # Kevin and Puzzle (Easy Version)
## Problem Description
This is the easy version of the problem. The difference between the versions is that in this version, you need to find any one good array. You can hack only if you solved all versions of this problem.
Kevin is visiting the Red Church, and he found a puzzle on the wall.
For an array $ a $ , let $ c(l,r) $ indicate how many distinct numbers are among $ a_l, a_{l+1}, \ldots, a_r $ . In particular, if $ l > r $ , define $ c(l,r) = 0 $ .
You are given a string $ s $ of length $ n $ consisting of letters $ \texttt{L} $ and $ \texttt{R} $ only. Let a non-negative array $ a $ be called good, if the following conditions hold for $ 1 \leq i \leq n $ :
- if $ s_i=\verb!L! $ , then $ c(1,i-1)=a_i $ ;
- if $ s_i=\verb!R! $ , then $ c(i+1,n)=a_i $ .
If there is a good array $ a $ , print any of the good arrays. Otherwise, report that no such arrays exists.
## Input Format
Each test contains multiple test cases. The first line contains a single integer $ t $ ( $ 1\le t \le 10^4 $ ) โ the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 2\leq n\leq 2\cdot 10^5 $ ) โ the length of string $ s $ .
The second line of each test case contains a string $ s $ with a length $ n $ , containing only English uppercase letters $ \verb!L! $ and $ \verb!R! $ .
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2\cdot 10^5 $ .
## Output Format
For each test case, if a good array exists, print $ n $ non-negative integers: a good array $ a $ . Otherwise, print a single integer $ -1 $ .
If there are multiple arrays $ a $ satisfying the conditions, you can output any of them.
## Sample #1
### Sample Input #1
```
4
3
LLR
3
RRL
4
RRLR
5
LLRLR
```
### Sample Output #1
```
0 1 0
2 1 2
-1
0 1 2 3 0
```
## Hint
In the first test case, the array $ [0,1,0] $ satisfies the conditions because:
- When $ i=1 $ , $ s_i=\verb!L! $ , and $ c(1,0)=0 $ ;
- When $ i=2 $ , $ s_i=\verb!L! $ , and $ c(1,1)=1 $ , since there is only one distinct number in $ a_1 $ ;
- When $ i=3 $ , $ s_i=\verb!R! $ , and $ c(4,3)=0 $ .
In the second test case, another suitable answer is $ [1,1,1] $ .
In the third test case, it can be proven that there's no array satisfying the conditions.
## Limit
Time Limit
2.00s
Memory Limit
500.00MB |
2048 | H | Kevin and Strange Operation | ["data structures", "dp"] | 3100 | https://codeforces.com/problemset/problem/2048/H | 1734618900 | en | codeforces | # Kevin and Strange Operation
## Problem Description
Kevin is exploring problems related to binary strings in Chinatown. When he was at a loss, a stranger approached him and introduced a peculiar operation:
- Suppose the current binary string is $ t $ , with a length of $ \vert t \vert $ . Choose an integer $ 1 \leq p \leq \vert t \vert $ . For all $ 1 \leq i < p $ , simultaneously perform the operation $ t_i = \max(t_i, t_{i+1}) $ , and then delete $ t_p $ .
For example, suppose the current binary string is 01001, and you choose $ p = 4 $ . Perform $ t_i = \max(t_i, t_{i+1}) $ for $ t_1 $ , $ t_2 $ , and $ t_3 $ , transforming the string into 11001, then delete $ t_4 $ , resulting in 1101.
Kevin finds this strange operation quite interesting. Thus, he wants to ask you: Given a binary string $ s $ , how many distinct non-empty binary strings can you obtain through any number of operations (possibly zero)?
Since the answer may be very large, you only need to output the result modulo $ 998\,244\,353 $ .
## Input Format
Each test contains multiple test cases. The first line contains a single integer $ t $ ( $ 1\le t \le 10^4 $ ) โ the number of test cases.
For each test case, the only line contains a binary string $ s $ ( $ 1 \le \lvert s \rvert \le 10^6 $ ).
It is guaranteed that the sum of $ \lvert s \rvert $ over all test cases does not exceed $ 10^6 $ .
## Output Format
For each test case, print a single integer in the only line of the output โ the number of distinct non-empty binary strings you can obtain, modulo $ 998\,244\,353 $ .
## Sample #1
### Sample Input #1
```
2
11001
000110111001100
```
### Sample Output #1
```
9
73
```
## Hint
In the first test case, all the binary strings you can obtain are: 11001, 1001, 1101, 001, 101, 111, 01, 11, and 1. There are $ 9 $ in total.
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2048 | G | Kevin and Matrices | ["brute force", "combinatorics", "dp", "math"] | 2800 | https://codeforces.com/problemset/problem/2048/G | 1734618900 | en | codeforces | # Kevin and Matrices
## Problem Description
Kevin has been transported to Sacred Heart Hospital, which contains all the $ n \times m $ matrices with integer values in the range $ [1,v] $ .
Now, Kevin wants to befriend some matrices, but he is willing to befriend a matrix $ a $ if and only if the following condition is satisfied:
$ $$$ \min_{1\le i\le n}\left(\max_{1\le j\le m}a_{i,j}\right)\le\max_{1\le j\le m}\left(\min_{1\le i\le n}a_{i,j}\right). $ $ </p><p>Please count how many matrices in Sacred Heart Hospital can be friends with Kevin.</p><p>Since Kevin is very friendly, there could be many matrices that meet this condition. Therefore, you only need to output the result modulo $ 998\\,244\\,353$$$.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 8\cdot 10^3 $ ).
The only line of each test case contains three integers $ n $ , $ m $ , $ v $ ( $ 1 \le n, v, n \cdot v \leq 10^6 $ , $ 1 \le m \le 10^9 $ ).
It is guaranteed that the sum of $ n \cdot v $ over all test cases doesn't exceed $ 10^6 $ .
## Output Format
For each test case, output one integer โ the number of matrices that can be friends with Kevin modulo $ 998\,244\,353 $ .
## Sample #1
### Sample Input #1
```
3
2 2 2
2 3 4
11 45 14
```
### Sample Output #1
```
14
2824
883799966
```
## Hint
In the first test case, besides the matrices $ a=\begin{bmatrix}1&2\\2&1\end{bmatrix} $ and $ a=\begin{bmatrix}2&1\\1&2\end{bmatrix} $ , which do not satisfy the condition, the remaining $ 2^{2 \cdot 2} - 2 = 14 $ matrices can all be friends with Kevin.
## Limit
Time Limit
6.00s
Memory Limit
250.00MB |
2048 | F | Kevin and Math Class | ["brute force", "data structures", "divide and conquer", "dp", "implementation", "math", "trees"] | 2500 | https://codeforces.com/problemset/problem/2048/F | 1734618900 | en | codeforces | # Kevin and Math Class
## Problem Description
Kevin is a student from Eversleeping Town, currently attending a math class where the teacher is giving him division exercises.
On the board, there are two rows of positive integers written, each containing $ n $ numbers. The first row is $ a_1, a_2, \ldots, a_n $ , and the second row is $ b_1, b_2, \ldots, b_n $ .
For each division exercise, Kevin can choose any segment $ [l, r] $ and find the smallest value $ x $ among $ b_l, b_{l+1}, \ldots, b_r $ . He will then modify each $ a_i $ for $ l \leq i \leq r $ to be the ceiling of $ a_i $ divided by $ x $ .
Formally, he selects two integers $ 1 \leq l \leq r \leq n $ , sets $ x = \min_{l \leq i \leq r} b_i $ , and changes all $ a_i $ for $ l \leq i \leq r $ to $ \lceil \frac{a_i}{x} \rceil $ .
Kevin can leave class and go home when all $ a_i $ become $ 1 $ . He is eager to leave and wants to know the minimum number of division exercises required to achieve this.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^4 $ ).
The first line of each test case contains an integer $ n $ ( $ 1 \le n \leq 2 \cdot 10^5 $ ) โ the length of the sequence $ a $ and $ b $ .
The second line of each test case contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 1 \le a_i \le 10^{18} $ ) โ the first row of integers on the board.
The third line of each test case contains $ n $ integers $ b_1, b_2, \ldots, b_n $ ( $ 2 \le b_i \le 10^{18} $ ) โ the second row of integers on the board.
It is guaranteed that the sum of $ n $ over all test cases doesn't exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output one integer โ the minimum number of division exercises required to leave class.
## Sample #1
### Sample Input #1
```
3
3
5 4 2
6 3 2
5
3 6 1 3 2
3 5 3 2 2
6
8 3 3 7 5 8
3 2 3 4 2 3
```
### Sample Output #1
```
2
3
3
```
## Hint
For the first test case: $ [{\color{red}{5,4}},2]\xrightarrow[\min(b_1,b_2)=3]{\text{operate segment }[1,2]}[{\color{red}{2,2,2}}]\xrightarrow[\min(b_1,b_2,b_3)=2]{\text{operate segment }[1,3]}[1,1,1] $ .
For the second test case: $ [{\color{red}{3,6,1}},3,2]\xrightarrow[\min(b_1,b_2,b_3)=3]{\text{operate segment }[1,3]}[1,{\color{red}{2,1,3}},2]\xrightarrow[\min(b_2,b_3,b_4)=2]{\text{operate segment }[2,4]}[1,1,1,{\color{red}{2,2}}]\xrightarrow[\min(b_4,b_5)=2]{\text{operate segment }[4,5]}[1,1,1,1,1] $ .
## Limit
Time Limit
2.00s
Memory Limit
1000.00MB |
2048 | E | Kevin and Bipartite Graph | ["constructive algorithms", "graphs", "greedy"] | 2000 | https://codeforces.com/problemset/problem/2048/E | 1734618900 | en | codeforces | # Kevin and Bipartite Graph
## Problem Description
The Arms Factory needs a poster design pattern and finds Kevin for help.
A poster design pattern is a bipartite graph with $ 2n $ vertices in the left part and $ m $ vertices in the right part, where there is an edge between each vertex in the left part and each vertex in the right part, resulting in a total of $ 2nm $ edges.
Kevin must color each edge with a positive integer in the range $ [1, n] $ . A poster design pattern is good if there are no monochromatic cycles $ ^{\text{โ}} $ in the bipartite graph.
Kevin needs your assistance in constructing a good bipartite graph or informing him if it is impossible.
$ ^{\text{โ}} $ A monochromatic cycle refers to a simple cycle in which all the edges are colored with the same color.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 100 $ ).
The only line of each test case contains two integers $ n $ and $ m $ ( $ 1 \le n, m \leq 10^3 $ ) โ the bipartite graph has $ 2n $ vertices in the left part and $ m $ vertices in the right part.
It is guaranteed that both the sum of $ n $ and the sum of $ m $ over all test cases do not exceed $ 10^3 $ .
## Output Format
For each test case, if there is no solution, then output No.
Otherwise, output Yes, and then output $ 2n $ lines, with each line containing $ m $ positive integers. The $ i $ -th line's $ j $ -th integer represents the color of the edge between the $ i $ -th vertex in the left part and the $ j $ -th vertex in the right part.
If there are multiple answers, you can print any of them.
You can output each letter in any case (for example, the strings yEs, yes, Yes, and YES will be recognized as a positive answer).
## Sample #1
### Sample Input #1
```
3
2 2
3 7
5 4
```
### Sample Output #1
```
YES
1 2
2 1
2 2
2 1
NO
YES
1 1 1 1
1 2 2 2
1 2 3 3
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
```
## Hint
For the first test case, the graph is shown as follows:
For the second test case, it can be proven that there is no valid solution.
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2048 | D | Kevin and Competition Memories | ["binary search", "brute force", "data structures", "greedy", "sortings", "two pointers"] | 1600 | https://codeforces.com/problemset/problem/2048/D | 1734618900 | en | codeforces | # Kevin and Competition Memories
## Problem Description
Kevin used to get into Rio's Memories, and in Rio's Memories, a series of contests was once held. Kevin remembers all the participants and all the contest problems from that time, but he has forgotten the specific rounds, the distribution of problems, and the exact rankings.
There are $ m $ problems in total, with the $ i $ -th problem having a difficulty of $ b_i $ . Let each contest consist of $ k $ problems, resulting in a total of $ \lfloor \frac{m}{k} \rfloor $ contests. This means that you select exactly $ \lfloor \frac{m}{k} \rfloor \cdot k $ problems for the contests in any combination you want, with each problem being selected at most once, and the remaining $ m\bmod k $ problems are left unused. For example, if $ m = 17 $ and $ k = 3 $ , you should create exactly $ 5 $ contests consisting of $ 3 $ problems each, and exactly $ 2 $ problems will be left unused.
There are $ n $ participants in the contests, with Kevin being the $ 1 $ -st participant. The $ i $ -th participant has a rating of $ a_i $ . During the contests, each participant solves all problems with a difficulty not exceeding their rating, meaning the $ i $ -th participant solves the $ j $ -th problem if and only if $ a_i \geq b_j $ . In each contest, Kevin's rank is one plus the number of participants who solve more problems than he does.
For each $ k = 1, 2, \ldots, m $ , Kevin wants to know the minimum sum of his ranks across all $ \lfloor \frac{m}{k} \rfloor $ contests. In other words, for some value of $ k $ , after selecting the problems for each contest, you calculate the rank of Kevin in each contest and sum up these ranks over all $ \lfloor \frac{m}{k} \rfloor $ contests. Your goal is to minimize this value.
Note that contests for different values of $ k $ are independent. It means that for different values of $ k $ , you can select the distribution of problems into the contests independently.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 5\cdot 10^4 $ ).
The first line of each test case contains two integers $ n $ and $ m $ ( $ 1 \le n, m \leq 3\cdot 10^5 $ ) โ the number of participants and the number of problems.
The second line of each test case contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 0 \le a_i \le 10^9 $ ) โ the rating of each participant.
The third line of each test case contains $ m $ integers $ b_1, b_2, \ldots, b_m $ ( $ 0 \le b_i \le 10^9 $ ) โ the difficulty of each problem.
It is guaranteed that both the sum of $ n $ and the sum of $ m $ over all test cases do not exceed $ 3 \cdot 10^5 $ .
## Output Format
For each test case, output $ m $ integers โ the minimum sum of Kevin's ranks for each $ k = 1, 2, \ldots, m $ .
## Sample #1
### Sample Input #1
```
4
4 4
4 3 7 5
2 5 4 6
5 5
5 0 4 8 6
1 3 9 2 7
6 7
1 1 4 5 1 4
1 9 1 9 8 1 0
7 6
1 9 1 9 8 1 0
1 1 4 5 1 4
```
### Sample Output #1
```
7 4 2 3
6 2 1 1 2
7 3 2 1 1 1 1
15 9 5 4 4 4
```
## Hint
For the first test case:
When $ k=1 $ , since each contest only contains one problem, the distribution is in fact unique. For example, in the contest which only includes the third problem (which has a difficulty of $ 4 $ ), all participants except the $ 2 $ -nd can solve it. Since no one solves strictly more problems than Kevin, his ranking in this contest is $ 1 $ . Similarly, in all $ 4 $ contests, Kevin's rankings are $ 1,3,1,2 $ , and the sum is $ 7 $ .
When $ k=2 $ , one optimal way is to choose the $ 1 $ -st and the $ 3 $ -rd problem to form a contest, while the $ 2 $ -nd and $ 4 $ -th for another. In the former contest, $ 4 $ participants respectively solve $ 2,1,2,2 $ problems, so Kevin's ranking is $ 1 $ ; in the latter one, they respectively solve $ 0,0,2,1 $ , since there are $ 2 $ participants ( $ 3 $ -rd and $ 4 $ -th) solve more problems than Kevin, his ranking is $ 1+2=3 $ . Thus the answer is $ 1+3=4 $ . It can be proven that there's no way to achieve a lower sum.
When $ k=3 $ , we can simply choose the $ 1 $ -st, the $ 3 $ -rd, and the $ 4 $ -th problem to make a contest, and Kevin has a ranking of $ 2 $ , which is optimal.
When $ k=4 $ , since there's only one contest, the distribution is also unique, and Kevin's ranking is $ 3 $ .
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2048 | C | Kevin and Binary Strings | ["bitmasks", "brute force", "greedy", "implementation", "strings"] | 1200 | https://codeforces.com/problemset/problem/2048/C | 1734618900 | en | codeforces | # Kevin and Binary Strings
## Problem Description
Kevin discovered a binary string $ s $ that starts with 1 in the river at Moonlit River Park and handed it over to you. Your task is to select two non-empty substrings $ ^{\text{โ}} $ of $ s $ (which can be overlapped) to maximize the XOR value of these two substrings.
The XOR of two binary strings $ a $ and $ b $ is defined as the result of the $ \oplus $ operation applied to the two numbers obtained by interpreting $ a $ and $ b $ as binary numbers, with the leftmost bit representing the highest value. Here, $ \oplus $ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
The strings you choose may have leading zeros.
$ ^{\text{โ}} $ A string $ a $ is a substring of a string $ b $ if $ a $ can be obtained from $ b $ by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^3 $ ).
The only line of each test case contains a binary string $ s $ that starts with 1 ( $ 1\le\lvert s\rvert\le 5000 $ ).
It is guaranteed that the sum of $ \lvert s\rvert $ over all test cases doesn't exceed $ 5000 $ .
## Output Format
For each test case, output four integers $ l_1, r_1, l_2, r_2 $ ( $ 1 \le l_1 \le r_1 \le |s| $ , $ 1 \le l_2 \le r_2 \le |s| $ ) โ in the case the two substrings you selected are $ s_{l_1} s_{l_1 + 1} \ldots s_{r_1} $ and $ s_{l_2} s_{l_2 + 1} \ldots s_{r_2} $ .
If there are multiple solutions, print any of them.
## Sample #1
### Sample Input #1
```
5
111
1000
10111
11101
1100010001101
```
### Sample Output #1
```
2 2 1 3
1 3 1 4
1 5 1 4
3 4 1 5
1 13 1 11
```
## Hint
In the first test case, we can choose $ s_2=\texttt{1} $ and $ s_1 s_2 s_3=\texttt{111} $ , and $ \texttt{1}\oplus\texttt{111}=\texttt{110} $ . It can be proven that it is impossible to obtain a larger result. Additionally, $ l_1=3 $ , $ r_1=3 $ , $ l_2=1 $ , $ r_2=3 $ is also a valid solution.
In the second test case, $ s_1 s_2 s_3=\texttt{100} $ , $ s_1 s_2 s_3 s_4=\texttt{1000} $ , the result is $ \texttt{100}\oplus\texttt{1000}=\texttt{1100} $ , which is the maximum.
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2048 | B | Kevin and Permutation | ["constructive algorithms", "greedy"] | 900 | https://codeforces.com/problemset/problem/2048/B | 1734618900 | en | codeforces | # Kevin and Permutation
## Problem Description
Kevin is a master of permutation-related problems. You are taking a walk with Kevin in Darkwoods, and during your leisure time, he wants to ask you the following question.
Given two positive integers $ n $ and $ k $ , construct a permutation $ ^{\text{โ}} $ $ p $ of length $ n $ to minimize the sum of the minimum values of all subarrays $ ^{\text{โ }} $ of length $ k $ . Formally, you need to minimize
$ $$$ \sum_{i=1}^{n-k+1}\left( \min_{j=i}^{i+k-1} p_j\right). $ $ </p><div class="statement-footnote"><p> $ ^{\\text{โ}} $ A permutation of length $ n $ is an array consisting of $ n $ distinct integers from $ 1 $ to $ n $ in arbitrary order. For example, $ \[2,3,1,5,4\] $ is a permutation, but $ \[1,2,2\] $ is not a permutation ( $ 2 $ appears twice in the array), and $ \[1,3,4\] $ is also not a permutation ( $ n=3 $ but there is $ 4 $ in the array). </p><p> $ ^{\\text{โ }} $ An array $ a $ is a subarray of an array $ b $ if $ a $ can be obtained from $ b$$$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Two subarrays are considered different if the sets of positions of the deleted elements are different.
## Input Format
Each test consists of multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^3 $ ).
The only line of each test case contains two integers $ n $ and $ k $ ( $ 1\le k\le n\le 10^5 $ ).
It is guaranteed that the sum of $ n $ over all test cases doesn't exceed $ 10^5 $ .
## Output Format
For each test case, output $ n $ integers on a single line โ the permutation $ p $ you constructed.
If there are multiple answers, you can print any of them.
## Sample #1
### Sample Input #1
```
3
4 2
6 1
8 3
```
### Sample Output #1
```
3 1 2 4
5 2 1 6 4 3
4 6 2 8 3 1 5 7
```
## Hint
In the first test case, with $ k=2 $ , consider all subarrays of length $ 2 $ : the minimum value of $ p_1,p_2 $ is $ 1 $ , the minimum value of $ p_2,p_3 $ is $ 1 $ , and the minimum value of $ p_3,p_4 $ is $ 2 $ . The sum $ 1+1+2=4 $ is the smallest among all possible permutations.
In the second test case, all subarrays of length $ 1 $ have minimum values of $ 5, 2, 1, 6, 4, 3 $ , and the sum $ 5+2+1+6+4+3=21 $ is proven to be the smallest.
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2048 | A | Kevin and Combination Lock | ["brute force", "greedy", "implementation", "math", "number theory"] | 800 | https://codeforces.com/problemset/problem/2048/A | 1734618900 | en | codeforces | # Kevin and Combination Lock
## Problem Description
Kevin is trapped in Lakeside Village by Grace. At the exit of the village, there is a combination lock that can only be unlocked if Kevin solves it.
The combination lock starts with an integer $ x $ . Kevin can perform one of the following two operations zero or more times:
1. If $ x \neq 33 $ , he can select two consecutive digits $ 3 $ from $ x $ and remove them simultaneously. For example, if $ x = 13\,323 $ , he can remove the second and third $ 3 $ , changing $ x $ to $ 123 $ .
2. If $ x \geq 33 $ , he can change $ x $ to $ x - 33 $ . For example, if $ x = 99 $ , he can choose this operation to change $ x $ to $ 99 - 33 = 66 $ .
When the value of $ x $ on the combination lock becomes $ 0 $ , Kevin can unlock the lock and escape from Lakeside Village. Please determine whether it is possible for Kevin to unlock the combination lock and escape.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^4 $ ).
The only line of each test case contains a positive integer $ x $ ( $ 1\leq x\leq 10^9 $ ).
## Output Format
For each test case, output "YES" or "NO" (without quotes) in one line, representing whether Kevin can unlock the combination lock and escape. You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.
## Sample #1
### Sample Input #1
```
5
165
6369
666
114514
133333332
```
### Sample Output #1
```
YES
YES
NO
NO
YES
```
## Hint
For the first test case, $ 165\xrightarrow{-33}132\xrightarrow{-33}99\xrightarrow{-33}66\xrightarrow{-33}33\xrightarrow{-33}0 $ .
For the second test case, $ 6369\xrightarrow{-33}6{\color{red}{33}}6\xrightarrow{\text{remove "33"}}66\xrightarrow{-33}33\xrightarrow{-33}0 $ .
For the third test case, it can be proven that, regardless of the operations performed, $ 666 $ cannot be transformed into $ 0 $ .
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2047 | B | Replace Character | ["brute force", "combinatorics", "greedy", "strings"] | 900 | https://codeforces.com/problemset/problem/2047/B | 1733207100 | en | codeforces | # Replace Character
## Problem Description
You're given a string $ s $ of length $ n $ , consisting of only lowercase English letters.
You must do the following operation exactly once:
- Choose any two indices $ i $ and $ j $ ( $ 1 \le i, j \le n $ ). You can choose $ i = j $ .
- Set $ s_i := s_j $ .
You need to minimize the number of distinct permutations $ ^\dagger $ of $ s $ . Output any string with the smallest number of distinct permutations after performing exactly one operation.
$ ^\dagger $ A permutation of the string is an arrangement of its characters into any order. For example, "bac" is a permutation of "abc" but "bcc" is not.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 500 $ ). The description of the test cases follows.
The first line of each test case contains $ n $ ( $ 1 \le n \le 10 $ ) โ the length of string $ s $ .
The second line of each test case contains $ s $ of length $ n $ . The string contains only lowercase English letters.
## Output Format
For each test case, output the required $ s $ after applying exactly one operation. If there are multiple solutions, print any of them.
## Sample #1
### Sample Input #1
```
6
3
abc
4
xyyx
8
alphabet
1
k
10
aabbccddee
6
ttbddq
```
### Sample Output #1
```
cbc
yyyx
alphaaet
k
eabbccddee
tttddq
```
## Hint
In the first test case, we can obtain the following strings in one operation: "abc", "bbc", "cbc", "aac", "acc", "aba", and "abb".
The string "abc" has $ 6 $ distinct permutations: "abc", "acb", "bac", "bca", "cab", and "cba".
The string "cbc" has $ 3 $ distinct permutations: "bcc", "cbc", and "ccb", which is the lowest of all the obtainable strings. In fact, all obtainable strings except "abc" have $ 3 $ permutations, so any of them would be accepted.
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2047 | A | Alyona and a Square Jigsaw Puzzle | ["implementation", "math"] | 800 | https://codeforces.com/problemset/problem/2047/A | 1733207100 | en | codeforces | # Alyona and a Square Jigsaw Puzzle
## Problem Description
Alyona assembles an unusual square Jigsaw Puzzle. She does so in $ n $ days in the following manner:
- On the first day, she starts by placing the central piece in the center of the table.
- On each day after the first one, she places a certain number of pieces around the central piece in clockwise order, always finishing each square layer completely before starting a new one.
For example, she places the first $ 14 $ pieces in the following order:
 The colors denote the layers. The third layer is still unfinished.Alyona is happy if at the end of the day the assembled part of the puzzle does not have any started but unfinished layers. Given the number of pieces she assembles on each day, find the number of days Alyona is happy on.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 500 $ ). The description of the test cases follows.
The first line contains a single integer $ n $ ( $ 1 \le n \le 100 $ ), the number of days.
The second line contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 1 \le a_i \le 100 $ , $ a_1 = 1 $ ), where $ a_i $ is the number of pieces Alyona assembles on the $ i $ -th day.
It is guaranteed in each test case that at the end of the $ n $ days, there are no unfinished layers.
## Output Format
For each test case, print a single integer: the number of days when Alyona is happy.
## Sample #1
### Sample Input #1
```
5
1
1
2
1 8
5
1 3 2 1 2
7
1 2 1 10 2 7 2
14
1 10 10 100 1 1 10 1 10 2 10 2 10 1
```
### Sample Output #1
```
1
2
2
2
3
```
## Hint
In the first test case, in the only day Alyona finishes the only layer.
In the second test case, on the first day, Alyona finishes the first layer, and on the second day, she finishes the second layer.
In the third test case, she finishes the second layer in a few days.
In the fourth test case, she finishes the second layer and immediately starts the next one on the same day, therefore, she is not happy on that day. She is only happy on the first and last days.
In the fifth test case, Alyona is happy on the first, fourth, and last days.
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2046 | F2 | Yandex Cuneiform (Hard Version) | ["constructive algorithms", "data structures", "greedy", "implementation"] | 3500 | https://codeforces.com/problemset/problem/2046/F2 | 1733207100 | en | codeforces | # Yandex Cuneiform (Hard Version)
## Problem Description
This is the hard version of the problem. The difference between the versions is that in this version, there is no restriction on the number of question marks. You can hack only if you solved all versions of this problem.
For a long time, no one could decipher Sumerian cuneiform. However, it has finally succumbed to pressure! Today, you have the chance to decipher Yandex cuneiform.
Yandex cuneiform is defined by the following rules:
1. An empty string is a Yandex cuneiform.
2. If you insert exactly one copy of each of the three letters 'Y', 'D', and 'X' into a Yandex cuneiform in such a way that no two adjacent letters become equal after the operation, you obtain a Yandex cuneiform.
3. If a string can't be obtained using the above rules, it is not a Yandex cuneiform.
You are given a template. A template is a string consisting of the characters 'Y', 'D', 'X', and '?'.
You need to check whether there exists a way to replace each question mark with 'Y', 'D', or 'X' to obtain a Yandex cuneiform, and if it exists, output any of the matching options, as well as a sequence of insertion operations to obtain the resulting cuneiform.
In this version of the problem, the number of question marks in the template can be arbitrary.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 5 \cdot 10^4 $ ). The description of the test cases follows.
Each test case consists of a single line containing a template of length $ n $ ( $ 3 \leq n < 2 \cdot 10^5 $ , $ n \bmod 3 = 0 $ ), consisting only of characters 'Y', 'D', 'X', and '?'.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output a single line containing 'NO' if it is not possible to obtain a cuneiform from the given template.
Otherwise, output 'YES' on the first line, and on the second line, any obtainable cuneiform. After that, you need to output the sequence of operations that leads to the cuneiform you printed.
A sequence of operations is described by $ \frac{n}{3} $ triples of pairs. A pair has the form c p, where $ c $ is one of the letters 'Y', 'D', or 'X', and $ p $ is the position at which the letter $ c $ should be inserted. The insertion position is the number of letters to skip from the beginning of the string for the insertion. For example, after inserting the character 'D' into the string "YDX" with $ p=3 $ , the result is "YDXD", and with $ p=0 $ , it is "DYDX". Note that the index cannot exceed the current length of the string.
The operations are applied from top to bottom, left to right. After inserting each triple to the string, there should be no two adjacent identical characters.
## Sample #1
### Sample Input #1
```
4
???
Y??D?X
???
D??DXYXYX
```
### Sample Output #1
```
YES
YDX
X 0 D 0 Y 0
YES
YDXDYX
X 0 Y 0 D 1
X 2 D 3 Y 4
YES
YDX
Y 0 D 1 X 2
NO
```
## Hint
In the second example, the string is transformed like this: $ "" \to \mathtt{YDX} \to \mathtt{YDXDYX} $ .
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2046 | F1 | Yandex Cuneiform (Easy Version) | ["constructive algorithms", "data structures", "greedy"] | 3300 | https://codeforces.com/problemset/problem/2046/F1 | 1733207100 | en | codeforces | # Yandex Cuneiform (Easy Version)
## Problem Description
This is the easy version of the problem. The difference between the versions is that in this version, there are no question marks. You can hack only if you solved all versions of this problem.
For a long time, no one could decipher Sumerian cuneiform. However, it has finally succumbed to pressure! Today, you have the chance to decipher Yandex cuneiform.
Yandex cuneiform is defined by the following rules:
1. An empty string is a Yandex cuneiform.
2. If you insert exactly one copy of each of the three letters 'Y', 'D', and 'X' into a Yandex cuneiform in such a way that no two adjacent letters become equal after the operation, you obtain a Yandex cuneiform.
3. If a string can't be obtained using the above rules, it is not a Yandex cuneiform.
You are given a template. A template is a string consisting of the characters 'Y', 'D', 'X', and '?'.
You need to check whether there exists a way to replace each question mark with 'Y', 'D', or 'X' to obtain a Yandex cuneiform, and if it exists, output any of the matching options, as well as a sequence of insertion operations to obtain the resulting cuneiform.
In this version of the problem, there are no question marks in the template.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 5 \cdot 10^4 $ ). The description of the test cases follows.
Each test case consists of a single line containing a template of length $ n $ ( $ 3 \leq n < 2 \cdot 10^5 $ , $ n \bmod 3 = 0 $ ), consisting only of characters 'Y', 'D', 'X'.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output a single line containing 'NO' if it is not possible to obtain a cuneiform from the given template.
Otherwise, output 'YES' on the first line, and on the second line, any obtainable cuneiform. After that, you need to output the sequence of operations that leads to the cuneiform you printed.
A sequence of operations is described by $ \frac{n}{3} $ triples of pairs. A pair has the form c p, where $ c $ is one of the letters 'Y', 'D', or 'X', and $ p $ is the position at which the letter $ c $ should be inserted. The insertion position is the number of letters to skip from the beginning of the string for the insertion. For example, after inserting the character 'D' into the string "YDX" with $ p=3 $ , the result is "YDXD", and with $ p=0 $ , it is "DYDX". Note that the index cannot exceed the current length of the string.
The operations are applied from top to bottom, left to right. After inserting each triple to the string, there should be no two adjacent identical characters.
## Sample #1
### Sample Input #1
```
4
YDX
YDXDYX
YDX
DYYDXYXYX
```
### Sample Output #1
```
YES
YDX
X 0 D 0 Y 0
YES
YDXDYX
X 0 Y 0 D 1
X 2 D 3 Y 4
YES
YDX
Y 0 D 1 X 2
NO
```
## Hint
In the second example, the string is transformed like this: $ "" \to \mathtt{YDX} \to \mathtt{YDXDYX} $ .
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2046 | E2 | Cheops and a Contest (Hard Version) | ["greedy", "implementation"] | 3500 | https://codeforces.com/problemset/problem/2046/E2 | 1733207100 | en | codeforces | # Cheops and a Contest (Hard Version)
## Problem Description
This is the hard version of the problem. The difference between the versions is that in this version, $ m $ is arbitrary. You can hack only if you solved all versions of this problem.
There is a problem-solving competition in Ancient Egypt with $ n $ participants, numbered from $ 1 $ to $ n $ . Each participant comes from a certain city; the cities are numbered from $ 1 $ to $ m $ . There is at least one participant from each city.
The $ i $ -th participant has strength $ a_i $ , specialization $ s_i $ , and wisdom $ b_i $ , so that $ b_i \ge a_i $ . Each problem in the competition will have a difficulty $ d $ and a unique topic $ t $ . The $ i $ -th participant will solve the problem if
- $ a_i \ge d $ , i.e., their strength is not less than the problem's difficulty, or
- $ s_i = t $ , and $ b_i \ge d $ , i.e., their specialization matches the problem's topic, and their wisdom is not less than the problem's difficulty.
Cheops wants to choose the problems in such a way that each participant from city $ i $ will solve strictly more problems than each participant from city $ j $ , for all $ i < j $ .
Please find a set of at most $ 5n $ problems, where the topics of all problems are distinct, so that Cheops' will is satisfied, or state that it is impossible.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ T $ ( $ 1 \le T \le 10^4 $ ). The description of the test cases follows.
The first line of each test case contains two integers $ n $ , $ m $ ( $ 2 \le m \le n \le 3 \cdot {10}^5 $ ) โ the number of participants and the number of cities.
The following $ n $ lines describe the participants. The $ i $ -th line contains three integers โ $ a_i $ , $ b_i $ , $ s_i $ ( $ 0 \le a_i, b_i, s_i \le {10}^9 $ , $ a_i \le b_i $ ) โ strength, wisdom, and specialization of the $ i $ -th participant, respectively.
The next $ m $ lines describe the cities. In the $ i $ -th line, the first number is an integer $ k_i $ ( $ 1 \le k_i \le n $ ) โ the number of participants from the $ i $ -th city. It is followed by $ k_i $ integers $ q_{i, 1}, q_{i, 2}, \ldots, q_{i, k_i} $ โ ( $ 1 \le q_{i, j} \le n $ , $ 1 \le j \le k_i $ ) โ the indices of the participants from this city. It is guaranteed that each participant is mentioned exactly once.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 3 \cdot 10^5 $ .
## Output Format
For each test case, if there exists a set of problems that satisfies Cheops' conditions, then in the first line output a single integer $ p $ ( $ 1 \le p \le 5n $ ) โ the number of problems in your solution.
Then output $ p $ lines, each containing two integers $ d $ and $ t $ ( $ 0 \le d, t \le {10}^9 $ ) โ the difficulty and topic of the respective problem. The topics must be distinct.
If there is no set of problems that meets Cheops' wishes, print $ -1 $ instead.
## Sample #1
### Sample Input #1
```
2
5 2
5 7 1
6 7 2
3 9 2
5 10 3
4 4 1
2 1 2
3 3 4 5
2 2
1 2 1
1 2 1
1 2
1 1
```
### Sample Output #1
```
7
6 4
6 5
5 6
5 7
4 8
4 9
7 1
-1
```
## Limit
Time Limit
4.00s
Memory Limit
500.00MB |
2046 | E1 | Cheops and a Contest (Easy Version) | ["constructive algorithms", "greedy"] | 2900 | https://codeforces.com/problemset/problem/2046/E1 | 1733207100 | en | codeforces | # Cheops and a Contest (Easy Version)
## Problem Description
This is the easy version of the problem. The difference between the versions is that in this version, $ m $ equals $ 2 $ . You can hack only if you solved all versions of this problem.
There is a problem-solving competition in Ancient Egypt with $ n $ participants, numbered from $ 1 $ to $ n $ . Each participant comes from a certain city; the cities are numbered from $ 1 $ to $ m $ . There is at least one participant from each city.
The $ i $ -th participant has strength $ a_i $ , specialization $ s_i $ , and wisdom $ b_i $ , so that $ b_i \ge a_i $ . Each problem in the competition will have a difficulty $ d $ and a unique topic $ t $ . The $ i $ -th participant will solve the problem if
- $ a_i \ge d $ , i.e., their strength is not less than the problem's difficulty, or
- $ s_i = t $ , and $ b_i \ge d $ , i.e., their specialization matches the problem's topic, and their wisdom is not less than the problem's difficulty.
Cheops wants to choose the problems in such a way that each participant from city $ i $ will solve strictly more problems than each participant from city $ j $ , for all $ i < j $ .
Please find a set of at most $ 5n $ problems, where the topics of all problems are distinct, so that Cheops' will is satisfied, or state that it is impossible.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ T $ ( $ 1 \le T \le 10^4 $ ). The description of the test cases follows.
The first line of each test case contains two integers $ n $ , $ m $ ( $ 2 \mathbf{=} m \le n \le 3 \cdot {10}^5 $ ) โ the number of participants and the number of cities.
The following $ n $ lines describe the participants. The $ i $ -th line contains three integers โ $ a_i $ , $ b_i $ , $ s_i $ ( $ 0 \le a_i, b_i, s_i \le {10}^9 $ , $ a_i \le b_i $ ) โ strength, wisdom, and specialization of the $ i $ -th participant, respectively.
The next $ m $ lines describe the cities. In the $ i $ -th line, the first number is an integer $ k_i $ ( $ 1 \le k_i \le n $ ) โ the number of participants from the $ i $ -th city. It is followed by $ k_i $ integers $ q_{i, 1}, q_{i, 2}, \ldots, q_{i, k_i} $ โ ( $ 1 \le q_{i, j} \le n $ , $ 1 \le j \le k_i $ ) โ the indices of the participants from this city. It is guaranteed that each participant is mentioned exactly once.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 3 \cdot 10^5 $ .
## Output Format
For each test case, if there exists a set of problems that satisfies Cheops' conditions, then in the first line output a single integer $ p $ ( $ 1 \le p \le 5n $ ) โ the number of problems in your solution.
Then output $ p $ lines, each containing two integers $ d $ and $ t $ ( $ 0 \le d, t \le {10}^9 $ ) โ the difficulty and topic of the respective problem. The topics must be distinct.
If there is no set of problems that meets Cheops' wishes, print $ -1 $ instead.
## Sample #1
### Sample Input #1
```
2
5 2
5 7 1
6 7 2
3 9 2
5 10 3
4 4 1
2 1 2
3 3 4 5
2 2
1 2 1
1 2 1
1 2
1 1
```
### Sample Output #1
```
7
6 4
6 5
5 6
5 7
4 8
4 9
7 1
-1
```
## Limit
Time Limit
4.00s
Memory Limit
500.00MB |
2046 | D | For the Emperor! | ["flows", "graphs"] | 3100 | https://codeforces.com/problemset/problem/2046/D | 1733207100 | en | codeforces | # For the Emperor!
## Problem Description
In Ancient Rome, a plan to defeat the barbarians was developed, but for its implementation, each city must be informed about it.
The northern part of the Roman Empire consists of $ n $ cities connected by $ m $ one-way roads. Initially, the $ i $ -th city has $ a_i $ messengers, and each messenger can freely move between cities following the existing roads. A messenger can carry a copy of the plan with him and inform the cities he visits, and can make unlimited copies for other messengers in the city he is currently in.
At the start, you will produce some number of plans and deliver them to messengers of your choice. Your goal is to make sure that every city is visited by a messenger with a plan. Find the smallest number of the plans you need to produce originally, so that the messengers will deliver them to every city, or determine that it is impossible to do so at all.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 100 $ ). The description of the test cases follows.
The first line contains two integers $ n $ and $ m $ ( $ 2 \le n \le 200 $ , $ 1 \le m \le 800 $ ) โ the number of cities and roads.
The second line contains $ n $ non-negative integers $ a_1, a_2, \ldots, a_n $ ( $ 0 \le a_{i} \le n $ ) โ the initial number of messengers in each city.
Each of the following $ m $ lines contains two integers $ u $ and $ v $ ( $ 1 \le u,v \le n, u \ne v $ ), indicating that there is a one-way road from city $ u $ to city $ v $ . The roads may repeat.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 200 $ . It is guaranteed that the sum of $ m $ over all test cases does not exceed $ 800 $ .
## Output Format
Output a single line containing a single integer โ the smallest number of messengers you need to give a copy of the plan in the beginning, or $ -1 $ if it is not possible to inform all cities.
## Sample #1
### Sample Input #1
```
2
7 6
2 1 0 1 2 3 4
1 2
1 3
2 4
2 5
3 6
3 7
4 4
1 1 1 1
1 2
1 3
2 4
3 4
```
### Sample Output #1
```
2
2
```
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2046 | C | Adventurers | ["binary search", "data structures", "greedy", "sortings", "ternary search", "two pointers"] | 2100 | https://codeforces.com/problemset/problem/2046/C | 1733207100 | en | codeforces | # Adventurers
## Problem Description
Once, four Roman merchants met in a Roman mansion to discuss their trading plans. They faced the following problem: they traded the same type of goods, and if they traded in the same city, they would inevitably incur losses. They decided to divide up the cities between them where they would trade.
The map of Rome can be represented in this problem as a plane with certain points marked โ the cities of the Roman Empire.
The merchants decided to choose a certain dividing point $ (x_0, y_0) $ . Then, in a city with coordinates $ (x_i, y_i) $ ,
- the first merchant sells goods if $ x_0 \le x_i $ and $ y_0 \le y_i $ ;
- the second merchant sells goods if $ x_0 > x_i $ and $ y_0 \le y_i $ ;
- the third merchant sells goods if $ x_0 \le x_i $ and $ y_0 > y_i $ ;
- the fourth merchant sells goods if $ x_0 > x_i $ and $ y_0 > y_i $ .
The merchants want to choose $ (x_0, y_0) $ in such a way as to maximize the smallest number of cities that any of them gets (i. e., as fair as possible). Please find such a point for them.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^4 $ ). The description of the test cases follows.
The first line of each test case contains a single integer $ n $ ( $ 4 \le n \le 10^5 $ ) โ the number of cities on the map.
Each of the next $ n $ lines contains two integers $ x_i, y_i $ ( $ -10^9 \le x_i, y_i \le 10^9 $ ) โ the coordinates of the cities.
Note that some points may coincide. This is because some cities may be so close that they cannot be distinguished on the map at the given scale.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 10^5 $ .
## Output Format
For each test case, in the first line, print a single integer $ k $ ( $ 0 \le k \le \frac{n}{4} $ ) โ the maximum possible number of cities that each merchant can get at a minimum.
In the second line, print two integers $ x_0 $ and $ y_0 $ ( $ |x_0|, |y_0| \le 10^9 $ ) โ the coordinates of the dividing point. If there are multiple suitable points, print any of them.
## Sample #1
### Sample Input #1
```
4
4
1 1
1 2
2 1
2 2
4
0 0
0 0
0 0
0 0
8
1 2
2 1
2 -1
1 -2
-1 -2
-2 -1
-2 1
-1 2
7
1 1
1 2
1 3
1 4
2 1
3 1
4 1
```
### Sample Output #1
```
1
2 2
0
0 0
2
1 0
0
0 0
```
## Limit
Time Limit
3.00s
Memory Limit
250.00MB |
2046 | B | Move Back at a Cost | ["binary search", "data structures", "greedy", "sortings"] | 1600 | https://codeforces.com/problemset/problem/2046/B | 1733207100 | en | codeforces | # Move Back at a Cost
## Problem Description
You are given an array of integers $ a $ of length $ n $ . You can perform the following operation zero or more times:
- In one operation choose an index $ i $ ( $ 1 \le i \le n $ ), assign $ a_i := a_i + 1 $ , and then move $ a_i $ to the back of the array (to the rightmost position). For example, if $ a = [3, 5, 1, 9] $ , and you choose $ i = 2 $ , the array becomes $ [3, 1, 9, 6] $ .
Find the lexicographically smallest $ ^{\text{โ}} $ array you can get by performing these operations.
$ ^{\text{โ}} $ An array $ c $ is lexicographically smaller than an array $ d $ if and only if one of the following holds:
- $ c $ is a prefix of $ d $ , but $ c \ne d $ ; or
- in the first position where $ c $ and $ d $ differ, the array $ c $ has a smaller element than the corresponding element in $ d $ .
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 10^4 $ ). The description of the test cases follows.
The first line contains a single integer $ n $ ( $ 1 \le n \le 10^5 $ ), the length of the array.
The second line contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 1 \le a_i \le 10^9 $ ), the elements of the array.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 10^5 $ .
## Output Format
For each test case, print the lexicographically smallest array you can get.
## Sample #1
### Sample Input #1
```
3
3
2 1 3
5
1 2 2 1 4
6
1 2 3 6 5 4
```
### Sample Output #1
```
1 3 3
1 1 3 3 5
1 2 3 4 6 7
```
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2046 | A | Swap Columns and Find a Path | ["greedy", "sortings"] | 1200 | https://codeforces.com/problemset/problem/2046/A | 1733207100 | en | codeforces | # Swap Columns and Find a Path
## Problem Description
There is a matrix consisting of $ 2 $ rows and $ n $ columns. The rows are numbered from $ 1 $ to $ 2 $ from top to bottom; the columns are numbered from $ 1 $ to $ n $ from left to right. Let's denote the cell on the intersection of the $ i $ -th row and the $ j $ -th column as $ (i,j) $ . Each cell contains an integer; initially, the integer in the cell $ (i,j) $ is $ a_{i,j} $ .
You can perform the following operation any number of times (possibly zero):
- choose two columns and swap them (i. e. choose two integers $ x $ and $ y $ such that $ 1 \le x < y \le n $ , then swap $ a_{1,x} $ with $ a_{1,y} $ , and then swap $ a_{2,x} $ with $ a_{2,y} $ ).
After performing the operations, you have to choose a path from the cell $ (1,1) $ to the cell $ (2,n) $ . For every cell $ (i,j) $ in the path except for the last, the next cell should be either $ (i+1,j) $ or $ (i,j+1) $ . Obviously, the path cannot go outside the matrix.
The cost of the path is the sum of all integers in all $ (n+1) $ cells belonging to the path. You have to perform the operations and choose a path so that its cost is maximum possible.
## Input Format
Each test contains multiple test cases. The first line contains the number of test cases $ t $ ( $ 1 \le t \le 5000 $ ). The description of the test cases follows.
Each test case consists of three lines:
- the first line contains one integer $ n $ ( $ 1 \le n \le 5000 $ ) โ the number of columns in the matrix;
- the second line contains $ n $ integers $ a_{1,1}, a_{1,2}, \ldots, a_{1,n} $ ( $ -10^5 \le a_{i,j} \le 10^5 $ ) โ the first row of the matrix;
- the third line contains $ n $ integers $ a_{2,1}, a_{2,2}, \ldots, a_{2,n} $ ( $ -10^5 \le a_{i,j} \le 10^5 $ ) โ the second row of the matrix.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 5000 $ .
## Output Format
For each test case, print one integer โ the maximum cost of a path you can obtain.
## Sample #1
### Sample Input #1
```
3
1
-10
5
3
1 2 3
10 -5 -3
4
2 8 5 3
1 10 3 4
```
### Sample Output #1
```
-5
16
29
```
## Hint
Here are the explanations of the first three test cases of the example. The left matrix is the matrix given in the input, the right one is the state of the matrix after several column swaps (possibly zero). The optimal path is highlighted in green.

## Limit
Time Limit
2.00s
Memory Limit
500.00MB |
2045 | M | Mirror Maze | ["brute force", "dfs and similar", "graphs", "implementation"] | 1800 | https://codeforces.com/problemset/problem/2045/M | 1733029500 | en | codeforces | # Mirror Maze
## Problem Description
You are given a grid of $ R $ rows (numbered from $ 1 $ to $ R $ from north to south) and $ C $ columns (numbered from $ 1 $ to $ C $ from west to east). Every cell in this grid is a square of the same size. The cell located at row $ r $ and column $ c $ is denoted as $ (r, c) $ . Each cell can either be empty or have a mirror in one of the cell's diagonals. Each mirror is represented by a line segment. The mirror is type $ 1 $ if it is positioned diagonally from the southwest corner to the northeast corner of the cell, or type $ 2 $ for the other diagonal.
These mirrors follow the law of reflection, that is, the angle of reflection equals the angle of incidence. Formally, for type $ 1 $ mirror, if a beam of light comes from the north, south, west, or east of the cell, then it will be reflected to the west, east, north, and south of the cell, respectively. Similarly, for type $ 2 $ mirror, if a beam of light comes from the north, south, west, or east of the cell, then it will be reflected to the east, west, south, and north of the cell, respectively.
You want to put a laser from outside the grid such that all mirrors are hit by the laser beam. There are $ 2 \cdot (R+C) $ possible locations to put the laser:
- from the north side of the grid at column $ c $ , for $ 1 \leq c \leq C $ , shooting a laser beam to the south;
- from the south side of the grid at column $ c $ , for $ 1 \leq c \leq C $ , shooting a laser beam to the north;
- from the east side of the grid at row $ r $ , for $ 1 \leq r \leq R $ , shooting a laser beam to the west; and
- from the west side of the grid at row $ r $ , for $ 1 \leq r \leq R $ , shooting a laser beam to the east.
Determine all possible locations for the laser such that all mirrors are hit by the laser beam.
## Input Format
The first line consists of two integers $ R $ $ C $ ( $ 1 \leq R, C \leq 200 $ ).
Each of the next $ R $ lines consists of a string $ S_r $ of length $ C $ . The $ c $ -th character of string $ S_r $ represents cell $ (r, c) $ . Each character can either be . if the cell is empty, / if the cell has type $ 1 $ mirror, or \\ if the cell has type $ 2 $ mirror. There is at least one mirror in the grid.
## Output Format
Output a single integer representing the number of possible locations for the laser such that all mirrors are hit by the laser beam. Denote this number as $ k $ .
If $ k > 0 $ , then output $ k $ space-separated strings representing the location of the laser. Each string consists of a character followed without any space by an integer. The character represents the side of the grid, which could be N, S, E, or W if you put the laser on the north, south, east, or west side of the grid, respectively. The integer represents the row/column number. You can output the strings in any order.
## Sample #1
### Sample Input #1
```
4 4
.//.
.\\.
.\/.
....
```
### Sample Output #1
```
2
N3 W2
```
## Sample #2
### Sample Input #2
```
4 6
./..\.
.\...\
./../\
......
```
### Sample Output #2
```
2
E3 S2
```
## Sample #3
### Sample Input #3
```
4 4
....
./\.
.\/.
....
```
### Sample Output #3
```
0
```
## Hint
Explanation for the sample input/output #1
The following illustration shows one of the solutions of this sample.
Explanation for the sample input/output #2
The following illustration shows one of the solutions of this sample.

## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | L | Buggy DFS | ["constructive algorithms"] | 3000 | https://codeforces.com/problemset/problem/2045/L | 1733029500 | en | codeforces | # Buggy DFS
## Problem Description
You are currently studying a graph traversal algorithm called the Depth First Search (DFS). However, due to a bug, your algorithm is slightly different from the standard DFS. The following is an algorithm for your Buggy DFS (BDFS), assuming the graph has $ N $ nodes (numbered from $ 1 $ to $ N $ ).
```
<pre class="verbatim"><br></br> BDFS():<br></br> let S be an empty stack<br></br> let FLAG be a boolean array of size N which are all false initially<br></br> let counter be an integer initialized with 0<br></br><br></br> push 1 to S<br></br><br></br> while S is not empty:<br></br> pop the top element of S into u<br></br> FLAG[u] = true<br></br><br></br> for each v neighbour of u in ascending order:<br></br> counter = counter + 1<br></br> if FLAG[v] is false:<br></br> push v to S<br></br><br></br> return counter<br></br>
```
You realized that the bug made the algorithm slower than standard DFS, which can be investigated by the return value of the function BDFS(). To investigate the behavior of this algorithm, you want to make some test cases by constructing an undirected simple graph such that the function BDFS() returns $ K $ , or determine if it is impossible to do so.
## Input Format
A single line consisting of an integer $ K $ ( $ 1 \leq K \leq 10^9 $ ).
## Output Format
If it is impossible to construct an undirected simple graph such that the function BDFS() returns $ K $ , then output -1 -1 in a single line.
Otherwise, output the graph in the following format. The first line consists of two integers $ N $ and $ M $ , representing the number of nodes and undirected edges in the graph, respectively. Each of the next $ M $ lines consists of two integers $ u $ and $ v $ , representing an undirected edge that connects node $ u $ and node $ v $ . You are allowed to output the edges in any order. This graph has to satisfy the following constraints:
- $ 1 \leq N \leq 32\,768 $
- $ 1 \leq M \leq 65\,536 $
- $ 1 \leq u, v \leq N $ , for all edges.
- The graph is a simple graph, i.e. there are no multi-edges nor self-loops.
Note that you are not required to minimize the number of nodes or edges. It can be proven that if constructing a graph in which the return value of BDFS() is $ K $ is possible, then there exists one that satisfies all the constraints above. If there are several solutions, you can output any of them.
## Sample #1
### Sample Input #1
```
8
```
### Sample Output #1
```
3 3
1 2
1 3
2 3
```
## Sample #2
### Sample Input #2
```
1
```
### Sample Output #2
```
-1 -1
```
## Sample #3
### Sample Input #3
```
23
```
### Sample Output #3
```
5 7
4 5
2 3
3 1
2 4
4 3
2 1
1 5
```
## Hint
Explanation for the sample input/output #1
The graph on the left describes the output of this sample. The graph on the right describes another valid solution for this sample.
Explanation for the sample input/output #3
The following graph describes the output of this sample.

## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | K | GCDDCG | [] | 2900 | https://codeforces.com/problemset/problem/2045/K | 1733029500 | en | codeforces | # GCDDCG
## Problem Description
You are playing the Greatest Common Divisor Deck-Building Card Game (GCDDCG). There are $ N $ cards (numbered from $ 1 $ to $ N $ ). Card $ i $ has the value of $ A_i $ , which is an integer between $ 1 $ and $ N $ (inclusive).
The game consists of $ N $ rounds (numbered from $ 1 $ to $ N $ ). Within each round, you need to build two non-empty decks, deck $ 1 $ and deck $ 2 $ . A card cannot be inside both decks, and it is allowed to not use all $ N $ cards. In round $ i $ , the greatest common divisor (GCD) of the card values in each deck must equal $ i $ .
Your creativity point during round $ i $ is the product of $ i $ and the number of ways to build two valid decks. Two ways are considered different if one of the decks contains different cards.
Find the sum of creativity points across all $ N $ rounds. Since the sum can be very large, calculate the sum modulo $ 998\,244\,353 $ .
## Input Format
The first line consists of an integer $ N $ ( $ 2 \leq N \leq 200\,000) $ .
The second line consists of $ N $ integers $ A_i $ ( $ 1 \leq A_i \leq N $ ).
## Output Format
Output a single integer representing the sum of creativity points across all $ N $ rounds modulo $ 998\,244\,353 $ .
## Sample #1
### Sample Input #1
```
3
3 3 3
```
### Sample Output #1
```
36
```
## Sample #2
### Sample Input #2
```
4
2 2 4 4
```
### Sample Output #2
```
44
```
## Sample #3
### Sample Input #3
```
9
4 2 6 9 7 7 7 3 3
```
### Sample Output #3
```
10858
```
## Hint
Explanation for the sample input/output #1
The creativity point during each of rounds $ 1 $ and $ 2 $ is $ 0 $ .
During round $ 3 $ , there are $ 12 $ ways to build both decks. Denote $ B $ and $ C $ as the set of card numbers within deck $ 1 $ and deck $ 2 $ , respectively. The $ 12 $ ways to build both decks are:
- $ B = \{ 1 \}, C = \{ 2 \} $ ;
- $ B = \{ 1 \}, C = \{ 3 \} $ ;
- $ B = \{ 1 \}, C = \{ 2, 3 \} $ ;
- $ B = \{ 2 \}, C = \{ 1 \} $ ;
- $ B = \{ 2 \}, C = \{ 3 \} $ ;
- $ B = \{ 2 \}, C = \{ 1, 3 \} $ ;
- $ B = \{ 3 \}, C = \{ 1 \} $ ;
- $ B = \{ 3 \}, C = \{ 2 \} $ ;
- $ B = \{ 3 \}, C = \{ 1, 2 \} $ ;
- $ B = \{ 1, 2 \}, C = \{ 3 \} $ ;
- $ B = \{ 2, 3 \}, C = \{ 1 \} $ ; and
- $ B = \{ 1, 3 \}, C = \{ 2 \} $ .
Explanation for the sample input/output #2
For rounds $ 1 $ , $ 2 $ , $ 3 $ and $ 4 $ , there are $ 0 $ , $ 18 $ , $ 0 $ , and $ 2 $ ways to build both decks, respectively.
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | J | Xorderable Array | ["bitmasks", "data structures"] | 2600 | https://codeforces.com/problemset/problem/2045/J | 1733029500 | en | codeforces | # Xorderable Array
## Problem Description
You are given an array $ A $ of $ N $ integers: $ [A_1, A_2, \dots, A_N] $ .
The array $ A $ is $ (p, q) $ -xorderable if it is possible to rearrange $ A $ such that for each pair $ (i, j) $ that satisfies $ 1 \leq i < j \leq N $ , the following conditions must be satisfied after the rearrangement: $ A_i \oplus p \leq A_j \oplus q $ and $ A_i \oplus q \leq A_j \oplus p $ . The operator $ \oplus $ represents the bitwise xor.
You are given another array $ X $ of length $ M $ : $ [X_1, X_2, \dots, X_M] $ . Calculate the number of pairs $ (u, v) $ where array $ A $ is $ (X_u, X_v) $ -xorderable for $ 1 \leq u < v \leq M $ .
## Input Format
The first line consists of two integers $ N $ $ M $ ( $ 2 \leq N, M \leq 200\,000) $ .
The second line consists of $ N $ integers $ A_i $ ( $ 0 \leq A_i < 2^{30}) $ .
The third line consists of $ M $ integers $ X_u $ ( $ 0 \leq X_u < 2^{30}) $ .
## Output Format
Output a single integer representing the number of pairs $ (u, v) $ where array $ A $ is $ (X_u, X_v) $ -xorderable for $ 1 \leq u < v \leq M $ .
## Sample #1
### Sample Input #1
```
3 4
0 3 0
1 2 1 1
```
### Sample Output #1
```
3
```
## Sample #2
### Sample Input #2
```
5 2
0 7 13 22 24
12 10
```
### Sample Output #2
```
1
```
## Sample #3
### Sample Input #3
```
3 3
0 0 0
1 2 3
```
### Sample Output #3
```
0
```
## Hint
Explanation for the sample input/output #1
The array $ A $ is $ (1, 1) $ -xorderable by rearranging the array $ A $ to $ [0, 0, 3] $ .
Explanation for the sample input/output #2
The array $ A $ is $ (12, 10) $ -xorderable by rearranging the array $ A $ to $ [13, 0, 7, 24, 22] $ .
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | I | Microwavable Subsequence | ["data structures"] | 2100 | https://codeforces.com/problemset/problem/2045/I | 1733029500 | en | codeforces | # Microwavable Subsequence
## Problem Description
You are given an array of $ N $ integers: $ [A_1, A_2, \dots, A_N] $ .
A subsequence can be derived from an array by removing zero or more elements without changing the order of the remaining elements. For example, $ [2, 1, 2] $ , $ [3, 3] $ , $ [1] $ , and $ [3, 2, 1, 3, 2] $ are subsequences of array $ [3, 2, 1, 3, 2] $ , while $ [1, 2, 3] $ is not a subsequence of array $ [3, 2, 1, 3, 2] $ .
A subsequence is microwavable if the subsequence consists of at most two distinct values and each element differs from its adjacent elements. For example, $ [2, 1, 2] $ , $ [3, 2, 3, 2] $ , and $ [1] $ are microwavable, while $ [3, 3] $ and $ [3, 2, 1, 3, 2] $ are not microwavable.
Denote a function $ f(x, y) $ as the length of the longest microwavable subsequence of array $ A $ such that each element within the subsequence is either $ x $ or $ y $ . Find the sum of $ f(x, y) $ for all $ 1 \leq x < y \leq M $ .
## Input Format
The first line consists of two integers $ N $ $ M $ ( $ 1 \leq N, M \leq 300\,000 $ ).
The second line consists of $ N $ integers $ A_i $ ( $ 1 \leq A_i \leq M $ ).
## Output Format
Output a single integer representing the sum of $ f(x, y) $ for all $ 1 \leq x < y \leq M $ .
## Sample #1
### Sample Input #1
```
5 4
3 2 1 3 2
```
### Sample Output #1
```
13
```
## Sample #2
### Sample Input #2
```
3 3
1 1 1
```
### Sample Output #2
```
2
```
## Hint
Explanation for the sample input/output #1
The value of $ f(1, 2) $ is $ 3 $ , taken from the subsequence $ [2, 1, 2] $ that can be obtained by removing $ A_1 $ and $ A_4 $ . The value of $ f(1, 3) $ is $ 3 $ , taken from the subsequence $ [3, 1, 3] $ that can be obtained by removing $ A_2 $ and $ A_5 $ . The value of $ f(2, 3) $ is $ 4 $ , taken from the subsequence $ [3, 2, 3, 2] $ that can be obtained by removing $ A_3 $ . The value of $ f(1, 4) $ , $ f(2, 4) $ , and $ f(3, 4) $ are all $ 1 $ .
Explanation for the sample input/output #2
The value of $ f(1, 2) $ and $ f(1, 3) $ are both $ 1 $ , while the value of $ f(2, 3) $ is $ 0 $ .
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | H | Missing Separators | ["dp", "sortings", "string suffix structures", "strings"] | 2200 | https://codeforces.com/problemset/problem/2045/H | 1733029500 | en | codeforces | # Missing Separators
## Problem Description
You have a dictionary, which is a list of distinct words sorted in alphabetical order. Each word consists of uppercase English letters.
You want to print this dictionary. However, there is a bug with the printing system, and all words in the list are printed next to each other without any separators between words. Now, you ended up with a string $ S $ that is a concatenation of all the words in the dictionary in the listed order.
Your task is to reconstruct the dictionary by splitting $ S $ into one or more words. Note that the reconstructed dictionary must consist of distinct words sorted in alphabetical order. Furthermore, you want to maximize the number of words in the dictionary. If there are several possible dictionaries with the maximum number of words, you can choose any of them.
## Input Format
A single line consisting of a string $ S $ ( $ 1 \leq |S| \leq 5000) $ . String $ S $ consists of only uppercase English letters.
## Output Format
First, output an integer in a single line representing the maximum number of the words in the reconstructed dictionary. Denote this number as $ n $ .
Then, output $ n $ lines, each containing a single string representing the word. The words must be distinct, and the list must be sorted alphabetically. The concatenation of the words in the listed order must equal $ S $ .
If there are several possible dictionaries with the maximum number of words, output any of them.
## Sample #1
### Sample Input #1
```
ABACUS
```
### Sample Output #1
```
4
A
BA
C
US
```
## Sample #2
### Sample Input #2
```
AAAAAA
```
### Sample Output #2
```
3
A
AA
AAA
```
## Sample #3
### Sample Input #3
```
EDCBA
```
### Sample Output #3
```
1
EDCBA
```
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | G | X Aura | ["graphs", "math", "shortest paths"] | 2200 | https://codeforces.com/problemset/problem/2045/G | 1733029500 | en | codeforces | # X Aura
## Problem Description
Mount ICPC can be represented as a grid of $ R $ rows (numbered from $ 1 $ to $ R $ ) and $ C $ columns (numbered from $ 1 $ to $ C $ ). The cell located at row $ r $ and column $ c $ is denoted as $ (r, c) $ and has a height of $ H_{r, c} $ . Two cells are adjacent to each other if they share a side. Formally, $ (r, c) $ is adjacent to $ (r-1, c) $ , $ (r+1, c) $ , $ (r, c-1) $ , and $ (r, c+1) $ , if any exists.
You can move only between adjacent cells, and each move comes with a penalty. With an aura of an odd positive integer $ X $ , moving from a cell with height $ h_1 $ to a cell with height $ h_2 $ gives you a penalty of $ (h_1 - h_2)^X $ . Note that the penalty can be negative.
You want to answer $ Q $ independent scenarios. In each scenario, you start at the starting cell $ (R_s, C_s) $ and you want to go to the destination cell $ (R_f, C_f) $ with minimum total penalty. In some scenarios, the total penalty might become arbitrarily small; such a scenario is called invalid. Find the minimum total penalty to move from the starting cell to the destination cell, or determine if the scenario is invalid.
## Input Format
The first line consists of three integers $ R $ $ C $ $ X $ ( $ 1 \leq R, C \leq 1000; 1 \leq X \leq 9; X $ is an odd integer).
Each of the next $ R $ lines consists of a string $ H_r $ of length $ C $ . Each character in $ H_r $ is a number from 0 to 9. The $ c $ -th character of $ H_r $ represents the height of cell $ (r, c) $ , or $ H_{r, c} $ .
The next line consists of an integer $ Q $ ( $ 1 \leq Q \leq 100\,000) $ .
Each of the next $ Q $ lines consists of four integers $ R_s $ $ C_s $ $ R_f $ $ C_f $ ( $ 1 \leq R_s, R_f \leq R; 1 \leq C_s, C_f \leq C $ ).
## Output Format
For each scenario, output the following in a single line. If the scenario is invalid, output INVALID. Otherwise, output a single integer representing the minimum total penalty to move from the starting cell to the destination cell.
## Sample #1
### Sample Input #1
```
3 4 1
3359
4294
3681
5
1 1 3 4
3 3 2 1
2 2 1 4
1 3 3 2
1 1 1 1
```
### Sample Output #1
```
2
4
-7
-1
0
```
## Sample #2
### Sample Input #2
```
2 4 5
1908
2023
2
1 1 2 4
1 1 1 1
```
### Sample Output #2
```
INVALID
INVALID
```
## Sample #3
### Sample Input #3
```
3 3 9
135
357
579
2
3 3 1 1
2 2 2 2
```
### Sample Output #3
```
2048
0
```
## Hint
Explanation for the sample input/output #1
For the first scenario, one of the solutions is to move as follows: $ (1, 1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (3, 2) \rightarrow (3, 3) \rightarrow (3, 4) $ . The total penalty of this solution is $ (3 - 4)^1 + (4 - 3)^1 + (3 - 6)^1 + (6 - 8)^1 + (8 - 1)^1 = 2 $ .
Explanation for the sample input/output #2
For the first scenario, the cycle $ (1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (1, 2) \rightarrow (1, 1) $ has a penalty of $ (1 - 2)^5 + (2 - 0)^5 + (0 - 9)^5 + (9 - 1)^5 = -26250 $ . You can keep repeating this cycle to make your total penalty arbitrarily small. Similarly, for the second scenario, you can move to $ (1, 1) $ first, then repeat the same cycle.
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | F | Grid Game 3-angle | ["games", "math"] | 3000 | https://codeforces.com/problemset/problem/2045/F | 1733029500 | en | codeforces | # Grid Game 3-angle
## Problem Description
Your friends, Anda and Kamu decide to play a game called Grid Game and ask you to become the gamemaster. As the gamemaster, you set up a triangular grid of size $ N $ . The grid has $ N $ rows (numbered from $ 1 $ to $ N $ ). Row $ r $ has $ r $ cells; the $ c $ -th cell of row $ r $ is denoted as $ (r, c) $ .
Before the game starts, $ M $ different cells (numbered from $ 1 $ to $ M $ ) are chosen: at cell $ (R_i, C_i) $ , you add $ A_i $ stones on it. You then give Anda and Kamu an integer $ K $ and commence the game.
Anda and Kamu will take turns alternately with Anda taking the first turn. A player on their turn will do the following.
- Choose a cell $ (r, c) $ with at least one stone on it.
- Remove at least one but at most $ K $ stones from the chosen cell.
- For each cell $ (x, y) $ such that $ r + 1 \leq x \leq \min(N, r + K) $ and $ c \leq y \leq c + x - r $ , add zero or more stones but at most $ K $ stones to cell $ (x, y) $ .
The following illustrations show all the possible cells in which you can add stones for $ K = 3 $ . You choose the cell $ (2, 1) $ for the left illustration and the cell $ (4, 3) $ for the right illustration.
A player who is unable to complete their turn (because there are no more stones on the grid) will lose the game, and the opposing player wins. Determine who will win the game if both players play optimally.
## Input Format
This problem is a multi-case problem. The first line consists of an integer $ T $ ( $ 1 \leq T \leq 100 $ ) that represents the number of test cases.
Each test case starts with a single line consisting of three integers $ N $ $ M $ $ K $ ( $ 1 \leq N \leq 10^9; 1 \leq M, K \leq 200\,000 $ ). Then, each of the next $ M $ lines consists of three integers $ R_i $ $ C_i $ $ A_i $ ( $ 1 \leq C_i \leq R_i \leq N; 1 \leq A_1 \leq 10^9 $ ). The pairs $ (R_i, C_i) $ are distinct.
The sum of $ M $ across all test cases does not exceed $ 200\,000 $ .
## Output Format
For each case, output a string in a single line representing the player who will win the game if both players play optimally. Output Anda if Anda, the first player, wins. Otherwise, output Kamu.
## Sample #1
### Sample Input #1
```
3
2 2 4
1 1 3
2 1 2
100 2 1
4 1 10
4 4 10
10 5 2
1 1 4
3 1 2
4 2 5
2 2 1
5 3 4
```
### Sample Output #1
```
Anda
Kamu
Anda
```
## Hint
Explanation for the sample input/output #1
For the first case, during the first turn, Anda will remove all the stones from cell $ (1, 1) $ and then add three stones at $ (2, 1) $ . The only cell with stones left is now cell $ (2, 1) $ with five stones, so Kamu must remove stones from that cell. No matter how many stones are removed by Kamu, Anda can remove all the remaining stones at $ (2, 1) $ and win the game.
For the second case, Kamu can always mirror whatever move made by Anda until Anda can no longer complete their turn.
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | E | Narrower Passageway | ["combinatorics", "data structures"] | 2700 | https://codeforces.com/problemset/problem/2045/E | 1733029500 | en | codeforces | # Narrower Passageway
## Problem Description
You are a strategist of The ICPC Kingdom. You received an intel that there will be monster attacks on a narrow passageway near the kingdom. The narrow passageway can be represented as a grid with $ 2 $ rows (numbered from $ 1 $ to $ 2 $ ) and $ N $ columns (numbered from $ 1 $ to $ N $ ). Denote $ (r, c) $ as the cell in row $ r $ and column $ c $ . A soldier with a power of $ P_{r, c} $ is assigned to protect $ (r, c) $ every single day.
It is known that the passageway is very foggy. Within a day, each column in the passageway has a $ 50\% $ chance of being covered in fog. If a column is covered in fog, the two soldiers assigned to that column are not deployed that day. Otherwise, the assigned soldiers will be deployed.
Define a connected area $ [u, v] $ ( $ u \leq v $ ) as a maximal set of consecutive columns from $ u $ to $ v $ (inclusive) such that each column in the set is not covered in fog. The following illustration is an example of connected areas. The grayed cells are cells covered in fog. There are $ 4 $ connected areas: $ [1, 2] $ , $ [4, 6] $ , $ [9, 9] $ , and $ [11, 11] $ .
The strength of a connected area $ [u, v] $ can be calculated as follows. Let $ m_1 $ and $ m_2 $ be the maximum power of the soldiers in the first and second rows of the connected area, respectively. Formally, $ m_r = \max (P_{r, u}, P_{r, u + 1}, \dots, P_{r, v}) $ for $ r \in \{ 1, 2\} $ . If $ m_1 = m_2 $ , then the strength is $ 0 $ . Otherwise, the strength is $ \min (m_1, m_2) $ .
The total strength of the deployment is the sum of the strengths for all connected areas. Determine the expected total strength of the deployment on any single day.
## Input Format
The first line consists of an integer $ N $ ( $ 1 \leq N \leq 100\,000 $ ).
Each of the next two lines consists of $ N $ integers $ P_{r, c} $ ( $ 1 \leq P_{r, c} \leq 200\,000 $ ).
## Output Format
Let $ M = 998\,244\,353 $ . It can be shown that the expected total strength can be expressed as an irreducible fraction $ \frac{x}{y} $ such that $ x $ and $ y $ are integers and $ y \not\equiv 0 \pmod{M} $ . Output an integer $ k $ in a single line such that $ 0 \leq k < M $ and $ k \cdot y \equiv x \pmod{M} $ .
## Sample #1
### Sample Input #1
```
3
8 4 5
5 4 8
```
### Sample Output #1
```
249561092
```
## Sample #2
### Sample Input #2
```
5
10 20 5 8 5
5 20 7 5 8
```
### Sample Output #2
```
811073541
```
## Hint
Explanation for the sample input/output #1
There are $ 8 $ possible scenarios for the passageway.
Each scenario is equally likely to happen. Therefore, the expected total strength is $ (0 + 5 + 10 + 5 + 5 + 0 + 5 + 0) / 8 = \frac{15}{4} $ . Since $ 249\,561\,092 \cdot 4 \equiv 15 \pmod{998\,244\,353} $ , the output of this sample is $ 249\,561\,092 $ .
Explanation for the sample input/output #2
The expected total strength is $ \frac{67}{16} $ .
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | D | Aquatic Dragon | [] | 3500 | https://codeforces.com/problemset/problem/2045/D | 1733029500 | en | codeforces | # Aquatic Dragon
## Problem Description
You live in an archipelago consisting of $ N $ islands (numbered from $ 1 $ to $ N $ ) laid out in a single line. Island $ i $ is adjacent to island $ i+1 $ , for $ 1 \leq i < N $ . Between adjacent islands $ i $ and $ i+1 $ , there is a pair of one-directional underwater tunnels: one that allows you to walk from island $ i $ to island $ i+1 $ and one for the opposite direction. Each tunnel can only be traversed at most once.
You also have a dragon with you. It has a stamina represented by a non-negative integer. The stamina is required for the dragon to perform its abilities: swim and fly. Initially, its stamina is $ 0 $ .
Your dragon's stamina can be increased as follows. There is a magical shrine on each island $ i $ that will immediately increase your dragon's stamina by $ P_i $ (regardless the position of the dragon) when you visit island $ i $ for the first time. This event takes no time.
When you are on an island, there are $ 3 $ moves that you can perform.
- Swim with your dragon to an adjacent island if your dragon and you are on the same island. You can perform if your dragon's stamina is at least $ D $ . This move reduces your dragon's stamina by $ D $ , and it takes $ T_s $ seconds to perform.
- Fly with your dragon to an adjacent island if your dragon and you are on the same island. You can perform this move if your dragon's stamina is not $ 0 $ . This move sets your dragon's stamina to $ 0 $ , and it takes $ T_f $ seconds to perform.
- Walk alone without your dragon to an adjacent island through the underwater tunnel. This move takes $ T_w $ seconds to perform. Once you walk through this tunnel, it cannot be used again.
Note that both swimming and flying do not use tunnels.
Your dragon and you are currently on island $ 1 $ . Your mission is to go to island $ N $ with your dragon. Determine the minimum possible time to complete your mission.
## Input Format
The first line consists of five integers $ N $ $ D $ $ T_s $ $ T_f $ $ T_w $ ( $ 2 \leq N \leq 200\,000; 1 \leq D, T_s, T_f, T_w \leq 200\,000 $ ).
The second line consists of $ N $ integers $ P_i $ ( $ 1 \leq P_i \leq 200\,000) $ .
## Output Format
Output an integer in a single line representing the minimum possible time to go to island $ N $ with your dragon.
## Sample #1
### Sample Input #1
```
5 4 2 9 1
1 2 4 2 1
```
### Sample Output #1
```
28
```
## Sample #2
### Sample Input #2
```
5 4 2 1 1
1 2 4 2 1
```
### Sample Output #2
```
4
```
## Sample #3
### Sample Input #3
```
3 4 2 10 1
3 1 2
```
### Sample Output #3
```
16
```
## Hint
Explanation for the sample input/output #1
The following sequence of events will complete your mission in the minimum time.
1. The shrine on island $ 1 $ increases your dragon's stamina to $ 1 $ .
2. Fly with your dragon to island $ 2 $ . The shrine on island $ 2 $ increases your dragon's stamina to $ 2 $ .
3. Walk alone to island $ 3 $ . The shrine on island $ 3 $ increases your dragon's stamina to $ 6 $ .
4. Walk alone to island $ 4 $ . The shrine on island $ 4 $ increases your dragon's stamina to $ 8 $ .
5. Walk alone to island $ 3 $ .
6. Walk alone to island $ 2 $ .
7. Swim with your dragon to island $ 3 $ . Your dragon's stamina is now $ 4 $ .
8. Swim with your dragon to island $ 4 $ . Your dragon's stamina is now $ 0 $ .
9. Walk alone to island $ 5 $ . The shrine on island $ 5 $ increases your dragon's stamina to $ 1 $ .
10. Walk alone to island $ 4 $ .
11. Fly with your dragon to island $ 5 $ .
Explanation for the sample input/output #2
Repeat the following process for $ 1 \leq i < 5 $ : The shrine on island $ i $ increases your dragon's stamina, then use the stamina to fly with your dragon to island $ i+1 $ .
## Limit
Time Limit
3.00s
Memory Limit
1000.00MB |
2045 | C | Saraga | ["greedy", "strings"] | 1400 | https://codeforces.com/problemset/problem/2045/C | 1733029500 | en | codeforces | # Saraga
## Problem Description
The word saraga is an abbreviation of sarana olahraga, an Indonesian term for a sports facility. It is created by taking the prefix sara of the word sarana and the suffix ga of the word olahraga. Interestingly, it can also be created by the prefix sa of the word sarana and the suffix raga of the word olahraga.
An abbreviation of two strings $ S $ and $ T $ is interesting if there are at least two different ways to split the abbreviation into two non-empty substrings such that the first substring is a prefix of $ S $ and the second substring is a suffix of $ T $ .
You are given two strings $ S $ and $ T $ . You want to create an interesting abbreviation of strings $ S $ and $ T $ with minimum length, or determine if it is impossible to create an interesting abbreviation.
## Input Format
The first line consists of a string $ S $ ( $ 1 \leq |S| \leq 200\,000 $ ).
The second line consists of a string $ T $ ( $ 1 \leq |T| \leq 200\,000 $ ).
Both strings $ S $ and $ T $ only consist of lowercase English letters.
## Output Format
If it is impossible to create an interesting abbreviation, output -1.
Otherwise, output a string in a single line representing an interesting abbreviation of strings $ S $ and $ T $ with minimum length. If there are multiple solutions, output any of them.
## Sample #1
### Sample Input #1
```
sarana
olahraga
```
### Sample Output #1
```
saga
```
## Sample #2
### Sample Input #2
```
berhiber
wortelhijau
```
### Sample Output #2
```
berhijau
```
## Sample #3
### Sample Input #3
```
icpc
icpc
```
### Sample Output #3
```
icpc
```
## Sample #4
### Sample Input #4
```
icpc
jakarta
```
### Sample Output #4
```
-1
```
## Hint
Explanation for the sample input/output #1
You can split saga into s and aga, or sa and ga. The abbreviation saraga is interesting, but saga has a smaller length.
Explanation for the sample input/output #2
The abbreviation belhijau is also interesting with minimum length, so it is another valid solution.
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | B | ICPC Square | ["math", "number theory"] | 2000 | https://codeforces.com/problemset/problem/2045/B | 1733029500 | en | codeforces | # ICPC Square
## Problem Description
ICPC Square is a hotel provided by the ICPC Committee for the accommodation of the participants. It consists of $ N $ floors (numbered from $ 1 $ to $ N $ ). This hotel has a very unique elevator. If a person is currently at floor $ x $ , by riding the elevator once, they can go to floor $ y $ if and only if $ y $ is a multiple of $ x $ and $ y - x \leq D $ .
You are currently at floor $ S $ . You want to go to the highest possible floor by riding the elevator zero or more times. Determine the highest floor you can reach.
## Input Format
A single line consisting of three integers $ N $ $ D $ $ S $ ( $ 2 \leq N \leq 10^{12}; 1 \leq D \leq N - 1; 1 \leq S \leq N $ ).
## Output Format
Output a single integer representing the highest floor you can reach by riding the elevator zero or more times.
## Sample #1
### Sample Input #1
```
64 35 3
```
### Sample Output #1
```
60
```
## Sample #2
### Sample Input #2
```
2024 2023 1273
```
### Sample Output #2
```
1273
```
## Hint
Explanation for the sample input/output #1
First, ride the elevator from floor $ 3 $ to floor $ 15 $ . This is possible because $ 15 $ is a multiple of $ 3 $ and $ 15 - 3 \leq 35 $ . Then, ride the elevator from floor $ 15 $ to floor $ 30 $ . This is possible because $ 30 $ is a multiple of $ 15 $ and $ 30 - 15 \leq 35 $ . Finally, ride the elevator from floor $ 30 $ to floor $ 60 $ . This is possible because $ 60 $ is a multiple of $ 30 $ and $ 60 - 30 \leq 35 $ .
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2045 | A | Scrambled Scrabble | ["brute force", "greedy"] | 1700 | https://codeforces.com/problemset/problem/2045/A | 1733029500 | en | codeforces | # Scrambled Scrabble
## Problem Description
You are playing a word game using a standard set of $ 26 $ uppercase English letters: A โ Z. In this game, you can form vowels and consonants as follows.
- The letters A, E, I, O, and U can only form a vowel.
- The letter Y can form either a vowel or a consonant.
- Each of the remaining letters other than A, E, I, O, U, and Y can only form a consonant.
- The string NG can form a single consonant when concatenated together.
Denote a syllable as a concatenation of a consonant, a vowel, and a consonant in that order. A word is a concatenation of one or more syllables.
You are given a string $ S $ and you want to create a word from it. You are allowed to delete zero or more letters from $ S $ and rearrange the remaining letters to form the word. Find the length of the longest word that can be created, or determine if no words can be created.
## Input Format
A single line consisting of a string $ S $ ( $ 1 \leq |S| \leq 5000 $ ). The string $ S $ consists of only uppercase English letters.
## Output Format
If a word cannot be created, output 0. Otherwise, output a single integer representing the length of longest word that can be created.
## Sample #1
### Sample Input #1
```
ICPCJAKARTA
```
### Sample Output #1
```
9
```
## Sample #2
### Sample Input #2
```
NGENG
```
### Sample Output #2
```
5
```
## Sample #3
### Sample Input #3
```
YYY
```
### Sample Output #3
```
3
```
## Sample #4
### Sample Input #4
```
DANGAN
```
### Sample Output #4
```
6
```
## Sample #5
### Sample Input #5
```
AEIOUY
```
### Sample Output #5
```
0
```
## Hint
Explanation for the sample input/output #1
A possible longest word is JAKCARTAP, consisting of the syllables JAK, CAR, and TAP.
Explanation for the sample input/output #2
The whole string $ S $ is a word consisting of one syllable which is the concatenation of the consonant NG, the vowel E, and the consonant NG.
Explanation for the sample input/output #3
The whole string $ S $ is a word consisting of one syllable which is the concatenation of the consonant Y, the vowel Y, and the consonant Y.
Explanation for the sample input/output #4
The whole string $ S $ is a word consisting of two syllables: DAN and GAN.
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2044 | H | Hard Demon Problem | ["constructive algorithms", "data structures", "dp", "implementation", "math"] | 2100 | https://codeforces.com/problemset/problem/2044/H | 1734273300 | en | codeforces | # Hard Demon Problem
## Problem Description
Swing is opening a pancake factory! A good pancake factory must be good at flattening things, so Swing is going to test his new equipment on 2D matrices.
Swing is given an $ n \times n $ matrix $ M $ containing positive integers. He has $ q $ queries to ask you.
For each query, he gives you four integers $ x_1 $ , $ y_1 $ , $ x_2 $ , $ y_2 $ and asks you to flatten the submatrix bounded by $ (x_1, y_1) $ and $ (x_2, y_2) $ into an array $ A $ . Formally, $ A = [M_{(x1,y1)}, M_{(x1,y1+1)}, \ldots, M_{(x1,y2)}, M_{(x1+1,y1)}, M_{(x1+1,y1+1)}, \ldots, M_{(x2,y2)}] $ .
The following image depicts the flattening of a submatrix bounded by the red dotted lines. The orange arrows denote the direction that the elements of the submatrix are appended to the back of $ A $ , and $ A $ is shown at the bottom of the image.
Afterwards, he asks you for the value of $ \sum_{i=1}^{|A|} A_i \cdot i $ (sum of $ A_i \cdot i $ over all $ i $ ).
## Input Format
The first line contains an integer $ t $ ( $ 1 \leq t \leq 10^3 $ ) โ the number of test cases.
The first line of each test contains two integers $ n $ and $ q $ ( $ 1 \leq n \leq 2000, 1 \leq q \leq 10^6 $ ) โ the length of $ M $ and the number of queries.
The following $ n $ lines contain $ n $ integers each, the $ i $ 'th of which contains $ M_{(i,1)}, M_{(i,2)}, \ldots, M_{(i,n)} $ ( $ 1 \leq M_{(i, j)} \leq 10^6 $ ).
The following $ q $ lines contain four integers $ x_1 $ , $ y_1 $ , $ x_2 $ , and $ y_2 $ ( $ 1 \leq x_1 \leq x_2 \leq n, 1 \leq y_1 \leq y_2 \leq n $ ) โ the bounds of the query.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2000 $ and the sum of $ q $ over all test cases does not exceed $ 10^6 $ .
## Output Format
For each test case, output the results of the $ q $ queries on a new line.
## Sample #1
### Sample Input #1
```
2
4 3
1 5 2 4
4 9 5 3
4 5 2 3
1 5 5 2
1 1 4 4
2 2 3 3
1 2 4 3
3 3
1 2 3
4 5 6
7 8 9
1 1 1 3
1 3 3 3
2 2 2 2
```
### Sample Output #1
```
500 42 168
14 42 5
```
## Hint
In the second query of the first test case, $ A = [9, 5, 5, 2] $ . Therefore, the sum is $ 1 \cdot 9 + 2 \cdot 5 + 3 \cdot 5 + 4 \cdot 2 = 42 $ .
## Limit
Time Limit
3.50s
Memory Limit
500.00MB |
2044 | G2 | Medium Demon Problem (hard version) | ["dfs and similar", "dp", "dsu", "graphs", "implementation", "trees"] | 1900 | https://codeforces.com/problemset/problem/2044/G2 | 1734273300 | en | codeforces | # Medium Demon Problem (hard version)
## Problem Description
This is the hard version of the problem. The key difference between the two versions is highlighted in bold.
A group of $ n $ spiders has come together to exchange plushies. Initially, each spider has $ 1 $ plushie. Every year, if spider $ i $ has at least one plushie, he will give exactly one plushie to spider $ r_i $ . Otherwise, he will do nothing. Note that all plushie transfers happen at the same time. In this version, each spider is allowed to have more than 1 plushie at any point in time.
The process is stable in the current year if each spider has the same number of plushies (before the current year's exchange) as he did the previous year (before the previous year's exchange). Note that year $ 1 $ can never be stable.
Find the first year in which the process becomes stable.
## Input Format
The first line contains an integer $ t $ ( $ 1 \leq t \leq 10^4 $ ) โ the number of test cases.
The first line of each test case contains an integer $ n $ ( $ 2 \leq n \leq 2 \cdot 10^5 $ ) โ the number of spiders.
The following line contains $ n $ integers $ r_1, r_2, \ldots, r_n $ ( $ 1 \leq r_i \leq n, r_i \neq i $ ) โ the recipient of the plushie of each spider.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output an integer on a new line, the first year in which the process becomes stable.
## Sample #1
### Sample Input #1
```
5
2
2 1
5
2 3 4 5 1
5
2 1 4 2 3
5
4 1 1 5 4
10
4 3 9 1 6 7 9 10 10 3
```
### Sample Output #1
```
2
2
5
5
5
```
## Hint
For the second test case:
- At year $ 1 $ , the following array shows the number of plushies each spider has: $ [1, 1, 1, 1, 1] $ . Then, year $ 1 $ 's exchange happens.
- At year $ 2 $ , the following array shows the number of plushies each spider has: $ [1, 1, 1, 1, 1] $ . Since this array is the same as the previous year, this year is stable.
For the third test case:
- At year $ 1 $ , the following array shows the number of plushies each spider has: $ [1, 1, 1, 1, 1] $ . Then, year $ 1 $ 's exchange happens.
- At year $ 2 $ , the following array shows the number of plushies each spider has: $ [1, 2, 1, 1, 0] $ . Then, year $ 2 $ 's exchange happens.
- At year $ 3 $ , the following array shows the number of plushies each spider has: $ [1, 3, 0, 1, 0] $ . Then, year $ 3 $ 's exchange happens.
- At year $ 4 $ , the following array shows the number of plushies each spider has: $ [1, 4, 0, 0, 0] $ . Then, year $ 4 $ 's exchange happens.
- At year $ 5 $ , the following array shows the number of plushies each spider has: $ [1, 4, 0, 0, 0] $ . Since this array is the same as the previous year, this year is stable.
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2044 | G1 | Medium Demon Problem (easy version) | ["dfs and similar", "graph matchings", "graphs", "implementation", "trees"] | 1700 | https://codeforces.com/problemset/problem/2044/G1 | 1734273300 | en | codeforces | # Medium Demon Problem (easy version)
## Problem Description
This is the easy version of the problem. The key difference between the two versions is highlighted in bold.
A group of $ n $ spiders has come together to exchange plushies. Initially, each spider has $ 1 $ plushie. Every year, if spider $ i $ has at least one plushie, he will give exactly one plushie to spider $ r_i $ . Otherwise, he will do nothing. Note that all plushie transfers happen at the same time. In this version, if any spider has more than $ 1 $ plushie at any point in time, they will throw all but $ 1 $ away.
The process is stable in the current year if each spider has the same number of plushies (before the current year's exchange) as he did the previous year (before the previous year's exchange). Note that year $ 1 $ can never be stable.
Find the first year in which the process becomes stable.
## Input Format
The first line contains an integer $ t $ ( $ 1 \leq t \leq 10^4 $ ) โ the number of test cases.
The first line of each test case contains an integer $ n $ ( $ 2 \leq n \leq 2 \cdot 10^5 $ ) โ the number of spiders.
The following line contains $ n $ integers $ r_1, r_2, \ldots, r_n $ ( $ 1 \leq r_i \leq n, r_i \neq i $ ) โ the recipient of the plushie of each spider.
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output an integer on a new line, the first year in which the process becomes stable.
## Sample #1
### Sample Input #1
```
5
2
2 1
5
2 3 4 5 1
5
2 1 4 2 3
5
4 1 1 5 4
10
4 3 9 1 6 7 9 10 10 3
```
### Sample Output #1
```
2
2
5
4
5
```
## Hint
For the second test case:
- At year $ 1 $ , the following array shows the number of plushies each spider has: $ [1, 1, 1, 1, 1] $ . Then, year $ 1 $ 's exchange happens.
- At year $ 2 $ , the following array shows the number of plushies each spider has: $ [1, 1, 1, 1, 1] $ . Since this array is the same as the previous year, this year is stable.
For the third test case:
- At year $ 1 $ , the following array shows the number of plushies each spider has: $ [1, 1, 1, 1, 1] $ . Then, year $ 1 $ 's exchange happens.
- At year $ 2 $ , the following array shows the number of plushies each spider has: $ [1, 1, 1, 1, 0] $ . Then, year $ 2 $ 's exchange happens. Note that even though two spiders gave spider $ 2 $ plushies, spider $ 2 $ may only keep one plushie.
- At year $ 3 $ , the following array shows the number of plushies each spider has: $ [1, 1, 0, 1, 0] $ . Then, year $ 3 $ 's exchange happens.
- At year $ 4 $ , the following array shows the number of plushies each spider has: $ [1, 1, 0, 0, 0] $ . Then, year $ 4 $ 's exchange happens.
- At year $ 5 $ , the following array shows the number of plushies each spider has: $ [1, 1, 0, 0, 0] $ . Since this array is the same as the previous year, this year is stable.
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2044 | F | Easy Demon Problem | ["binary search", "brute force", "data structures", "math", "number theory"] | 1900 | https://codeforces.com/problemset/problem/2044/F | 1734273300 | en | codeforces | # Easy Demon Problem
## Problem Description
For an arbitrary grid, Robot defines its beauty to be the sum of elements in the grid.
Robot gives you an array $ a $ of length $ n $ and an array $ b $ of length $ m $ . You construct a $ n $ by $ m $ grid $ M $ such that $ M_{i,j}=a_i\cdot b_j $ for all $ 1 \leq i \leq n $ and $ 1 \leq j \leq m $ .
Then, Robot gives you $ q $ queries, each consisting of a single integer $ x $ . For each query, determine whether or not it is possible to perform the following operation exactly once so that $ M $ has a beauty of $ x $ :
1. Choose integers $ r $ and $ c $ such that $ 1 \leq r \leq n $ and $ 1 \leq c \leq m $
2. Set $ M_{i,j} $ to be $ 0 $ for all ordered pairs $ (i,j) $ such that $ i=r $ , $ j=c $ , or both.
Note that queries are not persistent, meaning that you do not actually set any elements to $ 0 $ in the process โ you are only required to output if it is possible to find $ r $ and $ c $ such that if the above operation is performed, the beauty of the grid will be $ x $ . Also, note that you must perform the operation for each query, even if the beauty of the original grid is already $ x $ .
## Input Format
The first line contains three integers $ n $ , $ m $ , and $ q $ ( $ 1 \leq n,m \leq 2\cdot 10^5, 1 \leq q \leq 5\cdot 10^4 $ ) โ the length of $ a $ , the length of $ b $ , and the number of queries respectively.
The second line contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 0 \leq |a_i| \leq n $ ).
The third line contains $ m $ integers $ b_1, b_2, \ldots, b_m $ ( $ 0 \leq |b_i| \leq m $ ).
The following $ q $ lines each contain a single integer $ x $ ( $ 1 \leq |x| \leq 2\cdot 10^5 $ ), the beauty of the grid you wish to achieve by setting all elements in a row and a column to $ 0 $ .
## Output Format
For each testcase, output "YES" (without quotes) if there is a way to perform the aforementioned operation such that the beauty is $ x $ , and "NO" (without quotes) otherwise.
You can output "YES" and "NO" in any case (for example, strings "yES", "yes" and "Yes" will be recognized as a positive response).
## Sample #1
### Sample Input #1
```
3 3 6
-2 3 -3
-2 2 -1
-1
1
-2
2
-3
3
```
### Sample Output #1
```
NO
YES
NO
NO
YES
NO
```
## Sample #2
### Sample Input #2
```
5 5 6
1 -2 3 0 0
0 -2 5 0 -3
4
-3
5
2
-1
2
```
### Sample Output #2
```
YES
YES
YES
YES
NO
YES
```
## Hint
In the second example, the grid is
0 -2 5 0 -3
0 4 -10 0 6
0 -6 15 0 -9
0 0 0 0 0
0 0 0 0 0
By performing the operation with $ r=4 $ and $ c=2 $ , we create the following grid:
0 0 5 0 -3
0 0 -10 0 6
0 0 15 0 -9
0 0 0 0 0
0 0 0 0 0
which has beauty $ 4 $ . Thus, we output YES.
In the second query, selecting $ r=3 $ and $ c=5 $ creates a grid with beauty $ -3 $ .
In the third query, selecting $ r=3 $ and $ c=3 $ creates a grid with beauty $ 5 $ .
## Limit
Time Limit
4.00s
Memory Limit
250.00MB |
2044 | E | Insane Problem | ["binary search", "greedy", "implementation", "math", "number theory"] | 1300 | https://codeforces.com/problemset/problem/2044/E | 1734273300 | en | codeforces | # Insane Problem
## Problem Description
Wave is given five integers $ k $ , $ l_1 $ , $ r_1 $ , $ l_2 $ , and $ r_2 $ . Wave wants you to help her count the number of ordered pairs $ (x, y) $ such that all of the following are satisfied:
- $ l_1 \leq x \leq r_1 $ .
- $ l_2 \leq y \leq r_2 $ .
- There exists a non-negative integer $ n $ such that $ \frac{y}{x} = k^n $ .
## Input Format
The first line contains an integer $ t $ ( $ 1 \leq t \leq 10^4 $ ) โ the number of test cases.
The only line of each test case contains five integers $ k $ , $ l_1 $ , $ r_1 $ , $ l_2 $ , and $ r_2 $ ( $ 2 \leq k \leq 10^9, 1 \leq l_1 \leq r_1 \leq 10^9, 1 \leq l_2 \leq r_2 \leq 10^9 $ ).
## Output Format
For each test case, output the number of matching ordered pairs $ (x, y) $ on a new line.
## Sample #1
### Sample Input #1
```
5
2 2 6 2 12
2 1 1000000000 1 1000000000
3 5 7 15 63
1000000000 1 5 6 1000000000
15 17 78 2596 20914861
```
### Sample Output #1
```
12
1999999987
6
1
197
```
## Hint
In the third test case, the matching ordered pairs are the following:
- $ (5,15) $
- $ (5,45) $
- $ (6,18) $
- $ (6,54) $
- $ (7,21) $
- $ (7,63) $
In the fourth test case, the only valid ordered pair is $ (1,1\,000\,000\,000) $
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2044 | D | Harder Problem | ["constructive algorithms", "greedy", "math"] | 1100 | https://codeforces.com/problemset/problem/2044/D | 1734273300 | en | codeforces | # Harder Problem
## Problem Description
Given a sequence of positive integers, a positive integer is called a mode of the sequence if it occurs the maximum number of times that any positive integer occurs. For example, the mode of $ [2,2,3] $ is $ 2 $ . Any of $ 9 $ , $ 8 $ , or $ 7 $ can be considered to be a mode of the sequence $ [9,9,8,8,7,7] $ .
You gave UFO an array $ a $ of length $ n $ . To thank you, UFO decides to construct another array $ b $ of length $ n $ such that $ a_i $ is a mode of the sequence $ [b_1, b_2, \ldots, b_i] $ for all $ 1 \leq i \leq n $ .
However, UFO doesn't know how to construct array $ b $ , so you must help her. Note that $ 1 \leq b_i \leq n $ must hold for your array for all $ 1 \leq i \leq n $ .
## Input Format
The first line contains $ t $ ( $ 1 \leq t \leq 10^4 $ ) โ the number of test cases.
The first line of each test case contains an integer $ n $ ( $ 1 \leq n \leq 2 \cdot 10^5 $ ) โ the length of $ a $ .
The following line of each test case contains $ n $ integers $ a_1, a_2, \ldots, a_n $ ( $ 1 \leq a_i \leq n $ ).
It is guaranteed that the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output $ n $ numbers $ b_1, b_2, \ldots, b_n $ ( $ 1 \leq b_i \leq n $ ) on a new line. It can be shown that $ b $ can always be constructed. If there are multiple possible arrays, you may print any.
## Sample #1
### Sample Input #1
```
4
2
1 2
4
1 1 1 2
8
4 5 5 5 1 1 2 1
10
1 1 2 2 1 1 3 3 1 1
```
### Sample Output #1
```
1 2
1 1 2 2
4 5 5 1 1 2 2 3
1 8 2 2 1 3 3 9 1 1
```
## Hint
Let's verify the correctness for our sample output in test case $ 2 $ .
- At $ i = 1 $ , $ 1 $ is the only possible mode of $ [1] $ .
- At $ i = 2 $ , $ 1 $ is the only possible mode of $ [1, 1] $ .
- At $ i = 3 $ , $ 1 $ is the only possible mode of $ [1, 1, 2] $ .
- At $ i = 4 $ , $ 1 $ or $ 2 $ are both modes of $ [1, 1, 2, 2] $ . Since $ a_i = 2 $ , this array is valid.
## Limit
Time Limit
2.00s
Memory Limit
250.00MB |
2044 | C | Hard Problem | ["greedy", "math"] | 800 | https://codeforces.com/problemset/problem/2044/C | 1734273300 | en | codeforces | # Hard Problem
## Problem Description
Ball is the teacher in Paperfold University. The seats of his classroom are arranged in $ 2 $ rows with $ m $ seats each.
Ball is teaching $ a + b + c $ monkeys, and he wants to assign as many monkeys to a seat as possible. Ball knows that $ a $ of them only want to sit in row $ 1 $ , $ b $ of them only want to sit in row $ 2 $ , and $ c $ of them have no preference. Only one monkey may sit in each seat, and each monkey's preference must be followed if it is seated.
What is the maximum number of monkeys that Ball can seat?
## Input Format
The first line contains an integer $ t $ ( $ 1 \leq t \leq 10^4 $ ) โ the number of test cases.
Each test case contains four integers $ m $ , $ a $ , $ b $ , and $ c $ ( $ 1 \leq m, a, b, c \leq 10^8 $ ).
## Output Format
For each test case, output the maximum number of monkeys you can seat.
## Sample #1
### Sample Input #1
```
5
10 5 5 10
3 6 1 1
15 14 12 4
1 1 1 1
420 6 9 69
```
### Sample Output #1
```
20
5
30
2
84
```
## Hint
In the second test case, $ 6 $ monkeys want to sit in the front row, but only $ 3 $ seats are available. The monkeys that have no preference and the monkeys who prefer sitting in the second row can sit in the second row together. Thus, the answer is $ 3+2=5 $ .
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2044 | B | Normal Problem | ["implementation", "strings"] | 800 | https://codeforces.com/problemset/problem/2044/B | 1734273300 | en | codeforces | # Normal Problem
## Problem Description
A string consisting of only characters 'p', 'q', and 'w' is painted on a glass window of a store. Ship walks past the store, standing directly in front of the glass window, and observes string $ a $ . Ship then heads inside the store, looks directly at the same glass window, and observes string $ b $ .
Ship gives you string $ a $ . Your job is to find and output $ b $ .
## Input Format
The first line contains an integer $ t $ ( $ 1 \leq t \leq 100 $ ) โ the number of test cases.
The only line of each test case contains a string $ a $ ( $ 1 \leq |a| \leq 100 $ ) โ the string Ship observes from outside the store. It is guaranteed that $ a $ only contains characters 'p', 'q', and 'w'.
## Output Format
For each test case, output string $ b $ , the string Ship observes from inside the store, on a new line.
## Sample #1
### Sample Input #1
```
5
qwq
ppppp
pppwwwqqq
wqpqwpqwwqp
pqpqpqpq
```
### Sample Output #1
```
pwp
qqqqq
pppwwwqqq
qpwwpqwpqpw
pqpqpqpq
```
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2044 | A | Easy Problem | ["brute force", "math"] | 800 | https://codeforces.com/problemset/problem/2044/A | 1734273300 | en | codeforces | # Easy Problem
## Problem Description
Cube is given an integer $ n $ . She wants to know how many ordered pairs of positive integers $ (a,b) $ there are such that $ a=n-b $ . Since Cube is not very good at math, please help her!
## Input Format
The first line contains an integer $ t $ ( $ 1 \leq t \leq 99 $ ) โ the number of test cases.
The only line of each test case contains an integer $ n $ ( $ 2 \leq n \leq 100 $ ).
## Output Format
For each test case, output the number of ordered pairs $ (a, b) $ on a new line.
## Sample #1
### Sample Input #1
```
3
2
4
6
```
### Sample Output #1
```
1
3
5
```
## Hint
In the first test case, the only ordered pair that works is $ (a,b)=(1,1) $ .
In the second test case, the three ordered pairs of $ (a,b) $ that work are $ (3,1), (2,2), (1,3) $ .
## Limit
Time Limit
1.00s
Memory Limit
250.00MB |
2043 | G | Problem with Queries | ["brute force", "data structures", "implementation"] | https://codeforces.com/problemset/problem/2043/G | 1735050900 | en | codeforces | # Problem with Queries
## Problem Description
You are given an array $ a $ , consisting of $ n $ integers. Your task is to process $ q $ queries of two types:
- $ 1~p~x $ โ set the value of the element at index $ p $ equal to $ x $ ;
- $ 2~l~r $ โ count the number of pairs of indices $ (i, j) $ such that $ l \le i < j \le r $ and $ a_i \ne a_j $ .
Note that the queries in this task are encoded; each subsequent query can only be decoded after calculating the answer to the preceding query of the second type.
## Input Format
The first line contains a single integer $ n $ ( $ 1 \le n \le 10^5 $ ).
The second line contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ 1 \le a_i \le n $ ).
The third line contains a single integer $ q $ ( $ 1 \le q \le 3 \cdot 10^5 $ ) โ the number of queries.
The next $ q $ lines describe the queries in one of the following formats:
- $ 1~p'~x' $ ( $ 0 \le p', x' \le n-1 $ );
- $ 2~l'~r' $ ( $ 0 \le l', r' \le n-1 $ ).
The queries are encoded as follows: let $ \mathit{last} $ be the answer to the latest processed query of the second type (initially, $ \mathit{last} = 0 $ ).
- if the type of the query is $ 1 $ , then $ p = ((p' + \mathit{last}) \bmod n) + 1 $ , $ x = ((x' + \mathit{last}) \bmod n) + 1 $ .
- if the type of the query is $ 2 $ , $ l = ((l' + \mathit{last}) \bmod n) + 1 $ , $ r = ((r' + \mathit{last}) \bmod n) + 1 $ . If $ l > r $ , swap their values.
Don't forget to update the value of $ \mathit{last} $ after answering each query of the second type.
Additional constraint on the input: there is at least one query of the second type.
## Output Format
For each query of the second type, print the answer โ the number of pairs of indices $ (i, j) $ such that $ l \le i < j \le r $ and $ a_i \ne a_j $ .
## Sample #1
### Sample Input #1
```
3
1 2 3
5
2 0 2
1 0 2
2 0 2
1 2 0
2 1 0
```
### Sample Output #1
```
3 2 0
```
## Sample #2
### Sample Input #2
```
7
1 3 4 4 7 1 3
3
2 1 6
2 1 0
2 5 6
```
### Sample Output #2
```
13 18 0
```
## Hint
In the first example, the actual queries (after decoding) are:
- 2 1 3
- 1 1 3
- 2 1 3
- 1 2 3
- 2 1 3
## Limit
Time Limit
8.00s
Memory Limit
1000.00MB | |
2043 | F | Nim | ["bitmasks", "brute force", "combinatorics", "dp", "games", "greedy", "implementation", "shortest paths"] | https://codeforces.com/problemset/problem/2043/F | 1735050900 | en | codeforces | # Nim
## Problem Description
Recall the rules of the game "Nim". There are $ n $ piles of stones, where the $ i $ -th pile initially contains some number of stones. Two players take turns choosing a non-empty pile and removing any positive (strictly greater than $ 0 $ ) number of stones from it. The player unable to make a move loses the game.
You are given an array $ a $ , consisting of $ n $ integers. Artem and Ruslan decided to play Nim on segments of this array. Each of the $ q $ rounds is defined by a segment $ (l_i, r_i) $ , where the elements $ a_{l_i}, a_{l_i+1}, \dots, a_{r_i} $ represent the sizes of the piles of stones.
Before the game starts, Ruslan can remove any number of piles from the chosen segment. However, at least one pile must remain, so in a single round he can remove at most $ (r_i - l_i) $ piles. He is allowed to remove $ 0 $ piles. After the removal, the game is played on the remaining piles within the segment.
All rounds are independent: the changes made in one round do not affect the original array or any other rounds.
Ruslan wants to remove as many piles as possible so that Artem, who always makes the first move, loses.
For each round, determine:
1. the maximum number of piles Ruslan can remove;
2. the number of ways to choose the maximum number of piles for removal.
Two ways are considered different if there exists an index $ i $ such that the pile at index $ i $ is removed in one way but not in the other. Since the number of ways can be large, output it modulo $ 998\,244\,353 $ .
If Ruslan cannot ensure Artem's loss in a particular round, output -1 for that round.
## Input Format
The first line of input contains two integers $ n $ and $ q $ ( $ 1 \le n, q \le 10^5 $ ) โ the size of the array and the number of segments for which the answers need to be calculated.
The second line of input contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ 0 \le a_i \le 50 $ ) โ the elements of the initial array.
The $ i $ -th of the next $ q $ lines contains two integers $ l_i, r_i $ ( $ 1 \le l_i \le r_i \le n $ ) โ the bounds of the segment on which the boys want to play the game during the $ i $ -th round.
## Output Format
For each round:
- if Ruslan can win, print two integers โ the maximum number of piles that can be removed, and the number of ways to remove the maximum number of piles, taken modulo $ 998\,244\,353 $ ;
- otherwise print -1.
## Sample #1
### Sample Input #1
```
9 5
0 1 2 1 3 4 5 6 0
1 5
2 5
3 5
4 5
1 9
```
### Sample Output #1
```
4 1
2 1
0 1
-1
8 2
```
## Limit
Time Limit
6.00s
Memory Limit
500.00MB | |
2043 | E | Matrix Transformation | ["bitmasks", "brute force", "data structures", "dfs and similar", "graphs", "greedy", "implementation"] | https://codeforces.com/problemset/problem/2043/E | 1735050900 | en | codeforces | # Matrix Transformation
## Problem Description
You are given two matrices $ A $ and $ B $ of size $ n \times m $ , filled with integers between $ 0 $ and $ 10^9 $ . You can perform the following operations on matrix $ A $ in any order and any number of times:
- &=: choose two integers $ i $ and $ x $ ( $ 1 \le i \le n $ , $ x \ge 0 $ ) and replace each element in row $ i $ with the result of the bitwise AND operation between $ x $ and that element. Formally, for every $ j \in [1, m] $ , the element $ A_{i,j} $ is replaced with $ A_{i,j} \text{ & } x $ ;
- |=: choose two integers $ j $ and $ x $ ( $ 1 \le j \le m $ , $ x \ge 0 $ ) and replace each element in column $ j $ with the result of the bitwise OR operation between $ x $ and that element. Formally, for every $ i \in [1, n] $ , the element $ A_{i,j} $ is replaced with $ A_{i,j} \text{ | } x $ .
The value of $ x $ may be chosen differently for different operations.
Determine whether it is possible to transform matrix $ A $ into matrix $ B $ using the given operations any number of times (including zero).
## Input Format
The first line contains a single integer $ t $ ( $ 1 \le t \le 100 $ ) โ the number of test cases. Then, $ t $ test cases follow.
Each test case is given as follows:
- the first line contains two integers $ n $ and $ m $ ( $ 1 \le n, m \le 10^3 $ ; $ n \cdot m \le 10^3 $ ) โ the dimensions of the matrices $ A $ and $ B $ ;
- the following $ n $ lines describe the matrix $ A $ , where the $ i $ -th line contains $ m $ integers $ A_{i,1}, A_{i,2}, \dots, A_{i,m} $ ( $ 0 \le A_{i,j} \le 10^9 $ );
- the following $ n $ lines describe the matrix $ B $ , where the $ i $ -th line contains $ m $ integers $ B_{i,1}, B_{i,2}, \dots, B_{i,m} $ ( $ 0 \le B_{i,j} \le 10^9 $ ).
## Output Format
For each test case, output Yes if it is possible to transform the matrix $ A $ into the matrix $ B $ ; otherwise, output No. Each letter can be output in any case, upper or lower.
## Sample #1
### Sample Input #1
```
4
1 1
12
13
2 2
10 10
42 42
21 21
21 21
2 2
74 10
42 106
21 85
85 21
2 4
1 2 3 4
5 6 7 8
3 2 3 4
1 0 1 0
```
### Sample Output #1
```
Yes
Yes
No
Yes
```
## Hint
Let's consider the second set of input data and show a sequence of operations that transforms matrix $ A $ into matrix $ B $ :
Initially, the matrix looks like this:
$ \begin{bmatrix} 10&10\\ 42&42\\ \end{bmatrix} $
Apply an operation of the first type with parameters $ i = 1 $ and $ x = 0 $ . As a result, we get the matrix:
$ \begin{bmatrix} 0&0\\ 42&42\\ \end{bmatrix} $
Apply an operation of the first type with parameters $ i = 2 $ and $ x = 0 $ . As a result, we get the matrix:
$ \begin{bmatrix} 0&0\\ 0&0\\ \end{bmatrix} $
Apply an operation of the second type with parameters $ j = 1 $ and $ x = 21 $ . As a result, we get the matrix:
$ \begin{bmatrix} 21&0\\ 21&0\\ \end{bmatrix} $
Apply an operation of the second type with parameters $ j = 2 $ and $ x = 21 $ . As a result, we get the matrix:
$ \begin{bmatrix} 21&21\\ 21&21\\ \end{bmatrix} $
Thus, we have transformed matrix $ A $ into matrix $ B $ .
## Limit
Time Limit
1.00s
Memory Limit
250.00MB | |
2043 | D | Problem about GCD | ["brute force", "flows", "math", "number theory"] | https://codeforces.com/problemset/problem/2043/D | 1735050900 | en | codeforces | # Problem about GCD
## Problem Description
Given three integers $ l $ , $ r $ , and $ G $ , find two integers $ A $ and $ B $ ( $ l \le A \le B \le r $ ) such that their greatest common divisor (GCD) equals $ G $ and the distance $ |A - B| $ is maximized.
If there are multiple such pairs, choose the one where $ A $ is minimized. If no such pairs exist, output "-1 -1".
## Input Format
The first line contains a single integer $ t $ ( $ 1 \le t \le 10^3 $ ) โ the number of test cases. Then, $ t $ test cases follow.
Each test case consists of a single line containing three integers $ l, r, G $ ( $ 1 \le l \le r \le 10^{18} $ ; $ 1 \le G \le 10^{18} $ ) โ the range boundaries and the required GCD.
## Output Format
For each test case, output two integers $ A $ and $ B $ โ the solution to the problem, or "-1 -1" if no such pair exists.
## Sample #1
### Sample Input #1
```
4
4 8 2
4 8 3
4 8 4
5 7 6
```
### Sample Output #1
```
4 6
-1 -1
4 8
6 6
```
## Limit
Time Limit
1.00s
Memory Limit
250.00MB | |
2043 | C | Sums on Segments | ["binary search", "brute force", "data structures", "dp", "greedy", "math"] | https://codeforces.com/problemset/problem/2043/C | 1735050900 | en | codeforces | # Sums on Segments
## Problem Description
You are given an array $ a $ of $ n $ integers, where all elements except for at most one are equal to $ -1 $ or $ 1 $ . The remaining element $ x $ satisfies $ -10^9 \le x \le 10^9 $ .
Find all possible sums of subarrays of $ a $ , including the empty subarray, whose sum is defined as $ 0 $ . In other words, find all integers $ x $ such that the array $ a $ has at least one subarray (possibly empty) with sum equal to $ x $ . A subarray is a contiguous subsegment of an array.
Output these sums in ascending order. Each sum should be printed only once, even if it is achieved by multiple subarrays.
## Input Format
The first line contains a single integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases. Then, $ t $ test cases follow.
Each test case consists of two lines:
- The first line contains a single integer $ n $ ( $ 1 \le n \le 2 \cdot 10^5 $ ) โ the size of the array.
- The second line contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ -10^9 \le a_i \le 10^9 $ ) โ the elements of the array $ a $ . In the array $ a $ , there is at most one element that is neither $ 1 $ nor $ -1 $ .
Additional constraint on the input: the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, output two lines:
- In the first line, print a single integer โ the number of distinct subarray sums.
- In the second line, print these sums in ascending order.
Each sum should be printed only once, even if it is produced by multiple subarrays.
## Sample #1
### Sample Input #1
```
5
5
1 -1 10 1 1
5
-1 -1 -1 -1 -1
2
-1 2
2
7 1
3
1 4 -1
```
### Sample Output #1
```
8
-1 0 1 2 9 10 11 12
6
-5 -4 -3 -2 -1 0
4
-1 0 1 2
4
0 1 7 8
6
-1 0 1 3 4 5
```
## Hint
Let's define $ a[i,j] $ as the subarray of $ a $ from position $ i $ to position $ j $ .
Consider the first test case of the example:
- $ -1 $ is produced by $ a[2,2] $ ;
- $ 0 $ is produced by the empty subarray;
- $ 1 $ is produced by $ a[4,4] $ ;
- $ 2 $ is produced by $ a[4,5] $ ;
- $ 9 $ is produced by $ a[2,3] $ ;
- $ 10 $ is produced by $ a[1,3] $ ;
- $ 11 $ is produced by $ a[3,4] $ ;
- $ 12 $ is produced by $ a[3,5] $ .
## Limit
Time Limit
1.00s
Memory Limit
250.00MB | |
2043 | B | Digits | ["math", "number theory"] | https://codeforces.com/problemset/problem/2043/B | 1735050900 | en | codeforces | # Digits
## Problem Description
Artem wrote the digit $ d $ on the board exactly $ n! $ times in a row. So, he got the number $ dddddd \dots ddd $ (exactly $ n! $ digits).
Now he is curious about which odd digits from $ 1 $ to $ 9 $ divide the number written on the board.
## Input Format
The first line contains a single integer $ t $ ( $ 1 \le t \le 100 $ ) โ the number of test cases. The next $ t $ test cases follow.
Each test case consists of a single line containing two integers $ n $ and $ d $ ( $ 2 \le n \le 10^9 $ , $ 1 \le d \le 9 $ ).
## Output Format
For each test case, output the odd digits in ascending order that divide the number written on the board.
## Sample #1
### Sample Input #1
```
3
2 6
7 1
8 5
```
### Sample Output #1
```
1 3
1 3 7 9
1 3 5 7 9
```
## Hint
The factorial of a positive integer $ n $ ( $ n! $ ) is the product of all integers from $ 1 $ to $ n $ . For example, the factorial of $ 5 $ is $ 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120 $ .
## Limit
Time Limit
1.00s
Memory Limit
250.00MB | |
2043 | A | Coin Transformation | ["brute force", "math"] | https://codeforces.com/problemset/problem/2043/A | 1735050900 | en | codeforces | # Coin Transformation
## Problem Description
Initially, you have a coin with value $ n $ . You can perform the following operation any number of times (possibly zero):
- transform one coin with value $ x $ , where $ x $ is greater than $ 3 $ ( $ x>3 $ ), into two coins with value $ \lfloor \frac{x}{4} \rfloor $ .
What is the maximum number of coins you can have after performing this operation any number of times?
## Input Format
The first line contains one integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
Each test case consists of one line containing one integer $ n $ ( $ 1 \le n \le 10^{18} $ ).
## Output Format
For each test case, print one integer โ the maximum number of coins you can have after performing the operation any number of times.
## Sample #1
### Sample Input #1
```
4
1
5
16
1000000000000000000
```
### Sample Output #1
```
1
2
4
536870912
```
## Hint
In the first example, you have a coin of value $ 1 $ , and you can't do anything with it. So, the answer is $ 1 $ .
In the second example, you can transform a coin of value $ 5 $ into two coins with value $ 1 $ .
In the third example, you can transform a coin of value $ 16 $ into two coins with value $ 4 $ . Each of the resulting coins can be transformed into two coins with value $ 1 $ .
## Limit
Time Limit
2.00s
Memory Limit
500.00MB | |
2042 | F | Two Subarrays | ["data structures", "dp", "implementation", "matrices"] | 2600 | https://codeforces.com/problemset/problem/2042/F | 1733150100 | en | codeforces | # Two Subarrays
## Problem Description
You are given two integer arrays $ a $ and $ b $ , both of size $ n $ .
Let's define the cost of the subarray $ [l, r] $ as $ a_l + a_{l + 1} + \cdots + a_{r - 1} + a_r + b_l + b_r $ . If $ l=r $ , then the cost of the subarray is $ a_l + 2 \cdot b_l $ .
You have to perform queries of three types:
- " $ 1 $ $ p $ $ x $ " โ assign $ a_{p} := x $ ;
- " $ 2 $ $ p $ $ x $ " โ assign $ b_{p} := x $ ;
- " $ 3 $ $ l $ $ r $ " โ find two non-empty non-overlapping subarrays within the segment $ [l, r] $ with the maximum total cost and print their total cost.
## Input Format
The first line contains a single integer $ n $ ( $ 2 \le n \le 2 \cdot 10^5 $ ).
The second line contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ -10^9 \le a_i \le 10^9 $ ).
The third line contains $ n $ integers $ b_1, b_2, \dots, b_n $ ( $ -10^9 \le b_i \le 10^9 $ ).
The fourth line contains a single integer $ q $ ( $ 1 \le q \le 2 \cdot 10^5 $ ).
The next $ q $ lines contain the queries: one per line. Each query is of one of three types:
- " $ 1 $ $ p $ $ x $ " ( $ 1 \le p \le n $ ; $ -10^9 \le x \le 10^9 $ );
- " $ 2 $ $ p $ $ x $ " ( $ 1 \le p \le n $ ; $ -10^9 \le x \le 10^9 $ );
- " $ 3 $ $ l $ $ r $ " ( $ 1 \le l < r \le n $ ).
It is guaranteed that there is at least one query of the third type.
## Output Format
For each query of the third type, print the maximum possible total cost of two non-empty non-overlapping subarrays within the segment $ [l, r] $ .
## Sample #1
### Sample Input #1
```
7
3 -1 4 -3 2 4 0
0 6 1 0 -3 -2 -1
6
3 1 7
1 2 0
3 3 6
2 5 -3
1 3 2
3 1 5
```
### Sample Output #1
```
18
7
16
```
## Sample #2
### Sample Input #2
```
10
2 -1 -3 -2 0 4 5 6 2 5
2 -4 -5 -1 6 2 5 -6 4 2
10
3 6 7
1 10 -2
3 5 7
3 2 8
2 1 -5
2 7 4
3 1 3
3 3 8
3 2 3
1 4 4
```
### Sample Output #2
```
23
28
28
-17
27
-22
```
## Limit
Time Limit
3.00s
Memory Limit
500.00MB |
2042 | E | Vertex Pairs | ["binary search", "brute force", "data structures", "dfs and similar", "divide and conquer", "greedy", "implementation", "trees"] | 2900 | https://codeforces.com/problemset/problem/2042/E | 1733150100 | en | codeforces | # Vertex Pairs
## Problem Description
You are given a tree consisting of $ 2n $ vertices. Recall that a tree is a connected undirected graph with no cycles. Each vertex has an integer from $ 1 $ to $ n $ written on it. Each value from $ 1 $ to $ n $ is written on exactly two different vertices. Each vertex also has a cost โvertex $ i $ costs $ 2^i $ .
You need to choose a subset of vertices of the tree such that:
- the subset is connected; that is, from each vertex in the subset, you can reach every other vertex in the subset by passing only through the vertices in the subset;
- each value from $ 1 $ to $ n $ is written on at least one vertex in the subset.
Among all such subsets, you need to find the one with the smallest total cost of the vertices in it. Note that you are not required to minimize the number of vertices in the subset.
## Input Format
The first line contains a single integer $ n $ ( $ 1 \le n \le 2 \cdot 10^5 $ ).
The second line contains $ 2n $ integers $ a_1, a_2, \dots, a_{2n} $ ( $ 1 \le a_i \le n $ ). Each value from $ 1 $ to $ n $ appears exactly twice.
Each of the next $ 2n-1 $ lines contains two integers $ v $ and $ u $ ( $ 1 \le v, u \le 2n $ ) โ the edges of the tree. These edges form a valid tree.
## Output Format
In the first line, print a single integer $ k $ โ the number of vertices in the subset.
In the second line, print $ k $ distinct integers from $ 1 $ to $ 2n $ โ the indices of the vertices in the chosen subset. The vertices can be printed in an arbitrary order.
## Sample #1
### Sample Input #1
```
3
1 1 3 2 3 2
4 2
1 6
6 2
6 3
2 5
```
### Sample Output #1
```
3
2 4 5
```
## Sample #2
### Sample Input #2
```
3
2 3 1 3 2 1
6 4
2 4
5 2
3 6
3 1
```
### Sample Output #2
```
4
1 3 4 6
```
## Sample #3
### Sample Input #3
```
6
5 2 3 4 6 4 2 5 6 1 1 3
10 8
2 10
12 7
4 10
5 9
6 2
1 9
3 4
12 6
11 5
4 5
```
### Sample Output #3
```
6
2 3 4 5 8 10
```
## Hint
The images show the answers to the first two examples. The numbers in parentheses are the values written on the vertices.
In the first example, there are valid subsets such as: $ [2, 4, 5] $ (with a cost of $ 2^2 + 2^4 + 2^5 = 52 $ ), $ [2, 4, 5, 6] $ (with a cost of $ 116 $ ), $ [1, 6, 3] $ (with a cost of $ 74 $ ), $ [2, 6, 3] $ (with a cost of $ 76 $ ), and many others.
In the second example, the cost of the subset $ [4, 6, 3, 1] $ is $ 90 $ .
## Limit
Time Limit
3.00s
Memory Limit
500.00MB |
2042 | D | Recommendations | ["data structures", "implementation", "sortings", "two pointers"] | 1900 | https://codeforces.com/problemset/problem/2042/D | 1733150100 | en | codeforces | # Recommendations
## Problem Description
Suppose you are working in some audio streaming service. The service has $ n $ active users and $ 10^9 $ tracks users can listen to. Users can like tracks and, based on likes, the service should recommend them new tracks.
Tracks are numbered from $ 1 $ to $ 10^9 $ . It turned out that tracks the $ i $ -th user likes form a segment $ [l_i, r_i] $ .
Let's say that the user $ j $ is a predictor for user $ i $ ( $ j \neq i $ ) if user $ j $ likes all tracks the $ i $ -th user likes (and, possibly, some other tracks too).
Also, let's say that a track is strongly recommended for user $ i $ if the track is not liked by the $ i $ -th user yet, but it is liked by every predictor for the $ i $ -th user.
Calculate the number of strongly recommended tracks for each user $ i $ . If a user doesn't have any predictors, then print $ 0 $ for that user.
## Input Format
The first line contains one integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases. Next, $ t $ cases follow.
The first line of each test case contains one integer $ n $ ( $ 1 \le n \le 2 \cdot 10^5 $ ) โ the number of users.
The next $ n $ lines contain two integers $ l_i $ and $ r_i $ per line ( $ 1 \le l_i \le r_i \le 10^9 $ ) โ the segment of tracks the $ i $ -th user likes.
Additional constraint on the input: the sum of $ n $ over all test cases doesn't exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, print $ n $ integers, where the $ i $ -th integer is the number of strongly recommended tracks for the $ i $ -th user (or $ 0 $ , if that user doesn't have any predictors).
## Sample #1
### Sample Input #1
```
4
3
3 8
2 5
4 5
2
42 42
1 1000000000
3
42 42
1 1000000000
42 42
6
1 10
3 10
3 7
5 7
4 4
1 2
```
### Sample Output #1
```
0
0
1
999999999
0
0
0
0
0
2
3
2
4
8
```
## Hint
In the first test case:
- the first user has no predictors;
- the second user has no predictors;
- the third user has two predictors: users $ 1 $ and $ 2 $ ; only track $ 3 $ is liked by both of them and not liked by the third user.
In the second test case, the second user is a predictor for the first user. Therefore, all tracks, except $ 42 $ , are strongly recommended for the first user.
In the third test case, the first user has two predictors: users $ 2 $ and $ 3 $ , but there is no track that is liked by them and not liked by the first user himself.
## Limit
Time Limit
2.00s
Memory Limit
500.00MB |
2042 | C | Competitive Fishing | ["greedy"] | 1800 | https://codeforces.com/problemset/problem/2042/C | 1733150100 | en | codeforces | # Competitive Fishing
## Problem Description
Alice and Bob participate in a fishing contest! In total, they caught $ n $ fishes, numbered from $ 1 $ to $ n $ (the bigger the fish, the greater its index). Some of these fishes were caught by Alice, others โ by Bob.
Their performance will be evaluated as follows. First, an integer $ m $ will be chosen, and all fish will be split into $ m $ non-empty groups. The first group should contain several (at least one) smallest fishes, the second group โ several (at least one) next smallest fishes, and so on. Each fish should belong to exactly one group, and each group should be a contiguous subsegment of fishes. Note that the groups are numbered in exactly that order; for example, the fishes from the second group cannot be smaller than the fishes from the first group, since the first group contains the smallest fishes.
Then, each fish will be assigned a value according to its group index: each fish in the first group gets value equal to $ 0 $ , each fish in the second group gets value equal to $ 1 $ , and so on. So, each fish in the $ i $ -th group gets value equal to $ (i-1) $ .
The score of each contestant is simply the total value of all fishes that contestant caught.
You want Bob's score to exceed Alice's score by at least $ k $ points. What is the minimum number of groups ( $ m $ ) you have to split the fishes into? If it is impossible, you should report that.
## Input Format
The first line contains a single integer $ t $ ( $ 1 \le t \le 10^4 $ ) โ the number of test cases.
The first line of each test case contains two integers $ n $ and $ k $ ( $ 2 \le n \le 2 \cdot 10^5 $ ; $ 1 \le k \le 10^9 $ ).
The second line contains a string, consisting of exactly $ n $ characters. The $ i $ -th character is either 0 (denoting that the $ i $ -th fish was caught by Alice) or 1 (denoting that the $ i $ -th fish was caught by Bob).
Additional constraint on the input: the sum of $ n $ over all test cases does not exceed $ 2 \cdot 10^5 $ .
## Output Format
For each test case, print a single integer โ the minimum number of groups you have to split the fishes into; or -1 if it's impossible.
## Sample #1
### Sample Input #1
```
7
4 1
1001
4 1
1010
4 1
0110
4 2
0110
6 3
001110
10 20
1111111111
5 11
11111
```
### Sample Output #1
```
2
-1
2
-1
3
4
-1
```
## Hint
In the first test case of the example, you can split the fishes into groups as follows: the first three fishes form the $ 1 $ -st group, the last fish forms the $ 2 $ -nd group. Then, Bob's score will be $ 1 $ , and Alice's score will be $ 0 $ .
In the third test case of the example, you can split the fishes into groups as follows: the first fish forms the $ 1 $ -st group, the last three fishes form the $ 2 $ -nd group. Then, Bob's score will be $ 2 $ , and Alice's score will be $ 1 $ .
## Limit
Time Limit
2.00s
Memory Limit
500.00MB |
2042 | B | Game with Colored Marbles | ["games", "greedy"] | 900 | https://codeforces.com/problemset/problem/2042/B | 1733150100 | en | codeforces | # Game with Colored Marbles
## Problem Description
Alice and Bob play a game. There are $ n $ marbles, the $ i $ -th of them has color $ c_i $ . The players take turns; Alice goes first, then Bob, then Alice again, then Bob again, and so on.
During their turn, a player must take one of the remaining marbles and remove it from the game. If there are no marbles left (all $ n $ marbles have been taken), the game ends.
Alice's score at the end of the game is calculated as follows:
- she receives $ 1 $ point for every color $ x $ such that she has taken at least one marble of that color;
- additionally, she receives $ 1 $ point for every color $ x $ such that she has taken all marbles of that color (of course, only colors present in the game are considered).
For example, suppose there are $ 5 $ marbles, their colors are $ [1, 3, 1, 3, 4] $ , and the game goes as follows: Alice takes the $ 1 $ -st marble, then Bob takes the $ 3 $ -rd marble, then Alice takes the $ 5 $ -th marble, then Bob takes the $ 2 $ -nd marble, and finally, Alice takes the $ 4 $ -th marble. Then, Alice receives $ 4 $ points: $ 3 $ points for having at least one marble for colors $ 1 $ , $ 3 $ and $ 4 $ , and $ 1 $ point for having all marbles of color $ 4 $ . Note that this strategy is not necessarily optimal for both players.
Alice wants to maximize her score at the end of the game. Bob wants to minimize it. Both players play optimally (i. e. Alice chooses a strategy which allows her to get as many points as possible, and Bob chooses a strategy which minimizes the amount of points Alice can get).
Calculate Alice's score at the end of the game.
## Input Format
The first line contains one integer $ t $ ( $ 1 \le t \le 1000 $ ) โ the number of test cases.
Each test case consists of two lines:
- the first line contains one integer $ n $ ( $ 1 \le n \le 1000 $ ) โ the number of marbles;
- the second line contains $ n $ integers $ c_1, c_2, \dots, c_n $ ( $ 1 \le c_i \le n $ ) โ the colors of the marbles.
Additional constraint on the input: the sum of $ n $ over all test cases does not exceed $ 1000 $ .
## Output Format
For each test case, print one integer โ Alice's score at the end of the game, assuming that both players play optimally.
## Sample #1
### Sample Input #1
```
3
5
1 3 1 3 4
3
1 2 3
4
4 4 4 4
```
### Sample Output #1
```
4
4
1
```
## Hint
In the second test case of the example, the colors of all marbles are distinct, so, no matter how the players act, Alice receives $ 4 $ points for having all marbles of two colors, and no marbles of the third color.
In the third test case of the example, the colors of all marbles are the same, so, no matter how the players act, Alice receives $ 1 $ point for having at least one (but not all) marble of color $ 4 $ .
## Limit
Time Limit
2.00s
Memory Limit
500.00MB |
2042 | A | Greedy Monocarp | ["greedy", "sortings"] | 800 | https://codeforces.com/problemset/problem/2042/A | 1733150100 | en | codeforces | # Greedy Monocarp
## Problem Description
There are $ n $ chests; the $ i $ -th chest initially contains $ a_i $ coins. For each chest, you can choose any non-negative ( $ 0 $ or greater) number of coins to add to that chest, with one constraint: the total number of coins in all chests must become at least $ k $ .
After you've finished adding coins to the chests, greedy Monocarp comes, who wants the coins. He will take the chests one by one, and since he is greedy, he will always choose the chest with the maximum number of coins. Monocarp will stop as soon as the total number of coins in chests he takes is at least $ k $ .
You want Monocarp to take as few coins as possible, so you have to add coins to the chests in such a way that, when Monocarp stops taking chests, he will have exactly $ k $ coins. Calculate the minimum number of coins you have to add.
## Input Format
The first line contains one integer $ t $ ( $ 1 \le t \le 1000 $ ) โ the number of test cases.
Each test case consists of two lines:
- the first line contains two integers $ n $ and $ k $ ( $ 1 \le n \le 50 $ ; $ 1 \le k \le 10^7 $ );
- the second line contains $ n $ integers $ a_1, a_2, \dots, a_n $ ( $ 1 \le a_i \le k $ ).
## Output Format
For each test case, print one integer โ the minimum number of coins you have to add so that, when Monocarp stops taking the chests, he has exactly $ k $ coins. It can be shown that under the constraints of the problem, it is always possible.
## Sample #1
### Sample Input #1
```
4
5 4
4 1 2 3 2
5 10
4 1 2 3 2
2 10
1 1
3 8
3 3 3
```
### Sample Output #1
```
0
1
8
2
```
## Hint
In the first test case of the example, you don't have to add any coins. When Monocarp arrives, he will take the chest with $ 4 $ coins, so he will have exactly $ 4 $ coins.
In the second test case of the example, you can add $ 1 $ coin to the $ 4 $ -th chest, so, when Monocarp arrives, he will take a chest with $ 4 $ coins, then another chest with $ 4 $ coins, and a chest with $ 2 $ coins.
In the third test case of the example, you can add $ 3 $ coins to the $ 1 $ -st chest and $ 5 $ coins to the $ 2 $ -nd chest.
In the fourth test case of the example, you can add $ 1 $ coin to the $ 1 $ -st chest and $ 1 $ coin to the $ 3 $ -rd chest.
## Limit
Time Limit
2.00s
Memory Limit
500.00MB |
2041 | N | Railway Construction | [] | 3300 | https://codeforces.com/problemset/problem/2041/N | 1732431900 | en | codeforces | # Railway Construction
## Problem Description
The country of Truckski is located in a rugged, mountainous region, and the geological condition has engendered a wide range of issues. The challenging terrain separates the different states in the country, resulting in an extremely inconvenient inter-state commute and more crucially a lack of central governmental control. Adding on top of that is a rampant crime rate that increases annually, and this severely disrupts the everyday lives of innocent citizens.
A recent protest finally shed light on the situation, as the newly elected president has announced an ambitious project to resolve these issues. Her plan consists of two major components. The first is the construction of high-speed railways between the states to facilitate better connections and unity across the country. Since the states are mostly running independently from each other, to construct a railway between states $ u $ and $ v $ , the government has to pay a fee of $ a_u + a_v $ dollars, with $ a_u $ dollars given to state $ u $ and $ a_v $ dollars given to state $ v $ . The railway operates bidirectionally, meaning that once it is built, people from state $ u $ can now travel to state $ v $ and vice versa. A railway can be built between almost any pair of states, except for $ m $ particular pairs for which the terrain dividing them is so treacherous that the construction of a direct railroad between the two states becomes impossible.
The second component of the project is to build a centralized prison that manages all criminals across the country. Given the large number of estimated prisoners, the president decided to pick one of the states to build the central prison and sever the connection from the state to the rest of the country.
 An illustration for the sample input 1. (a) The costs of building direct railways between the states. (b) Consider building the central prison in State #3. All direct railroads that do not involve State #3 have to be built, with a total cost of $ 3+3+2=8 $ dollars.Given the above, the president would like to search for the minimum cost plan to construct railroads between the states so that:
- the state with the central prison should not have any railway connecting it to any other states, and
- all the other states should be connected, i.e., people should be able to travel from one such state to another, possibly by taking more than one train.
You are working for the team in charge of the overall planning of the construction. The meeting with the president is happening in just a few hours, at which time you will have to brief her on the cost of different construction plans. Please calculate, for each state $ u $ , the minimum cost plan to construct railroads between states meeting the above conditions when $ u $ is where the central prison is built.
## Input Format
The first line of the input contains two integers $ n $ and $ m $ , the number of states in Truckski and the number of pairs for which railroad construction is not feasible. The next line contains $ n $ integers $ a_1, \ldots, a_n $ , the construction fee the government needs to pay to the $ i $ -th state. Then, $ m $ lines follow. The $ i $ -th line contains two integers $ u_i $ and $ v_i $ meaning that it is impossible to build a (direct) railway between states $ u_i $ and $ v_i $ .
- $ 2\leq n\leq 10^5 $
- $ 0\leq m\leq 10^5 $
- $ 1\leq a_i\leq 10^9 $
- $ 1\leq u_i<v_i\leq n $
- For all $ i\neq j, (u_i, v_i)\neq (u_j, v_j) $ .
## Output Format
Output $ n $ integers in one line. The $ i $ -th integer is the minimum construction cost when the $ i $ -th state is where the prison is built. If it is impossible to find a feasible railroad construction, output -1 instead.
## Sample #1
### Sample Input #1
```
5 3
1 2 1 1 1
1 4
1 5
2 5
```
### Sample Output #1
```
7 6 8 7 7
```
## Sample #2
### Sample Input #2
```
3 2
1 2 3
1 2
2 3
```
### Sample Output #2
```
-1 4 -1
```
## Limit
Time Limit
4.00s
Memory Limit
1000.00MB |
2041 | M | Selection Sort | ["binary search", "data structures", "greedy", "two pointers"] | 2000 | https://codeforces.com/problemset/problem/2041/M | 1732431900 | en | codeforces | # Selection Sort
## Problem Description
Every student enrolled in the algorithms course is required to submit an assignment this week. The task is to implement an $ O(n^2) $ -time algorithm to sort $ n $ given integers in non-decreasing order. Alice has already completed her assignment, and her implementation is shown below.
```
<pre class="lstlisting">```
int alice_sort(int *s, int n){<br></br> for(int i = 0; i < n; ++i){<br></br> for(int j = i + 1; j < n; ++j){<br></br> if(s[i] > s[j]){<br></br> int swap = s[i];<br></br> s[i] = s[j];<br></br> s[j] = swap;<br></br> }<br></br> }<br></br> }<br></br> return 0;<br></br>}<br></br>
```
```
While you have access to Alice's code, you prefer not to simply copy it. Instead, you want to use Alice's sorting function as a building block for your own solution. There are two ways as listed below you can utilize her function, but each of them can be applied at most once. The order in which these two operations are invoked can be arbitrary.
- Prefix sort: choose a length $ i \in \{1, 2, \ldots, n\} $ and call $ \texttt{alicesort(}s, i\texttt{)} $ . This sorts the first $ i $ elements in the array $ s $ .
- Suffix sort: choose a length $ i \in \{1, 2, \ldots, n\} $ and call $ \texttt{alicesort(}s+n-i, i\texttt{)} $ . This sorts the last $ i $ elements in the array $ s $ .
Due to the time complexity of the sorting algorithm, the cost of performing either a prefix or suffix sort is $ i^2 $ , where $ i $ is the length of the chosen subarray. Your goal is to determine the minimum cost to sort the input array $ s $ of $ n $ integers in non-decreasing order using Alice's function, following the rules mentioned above.
For example, Let $ s=[3,2,5,5,4,1] $ . We can first perform a suffix sort of length $ 4 $ , and the array becomes $ [3,2,1,4,5,5] $ . Then, we perform a prefix sort of length $ 3 $ , and the array becomes $ [1,2,3,4,5,5] $ , which is a sorted array. The cost is $ 4^2+3^2=25 $ . Here is another example, let $ s=[4,3,2,1] $ . We can complete the sorting by performing only a prefix sort of length $ 4 $ , and the cost is $ 4^2=16 $ .
## Input Format
The first line contains exactly one integer $ n $ which indicates the number of integers in the array $ s $ . The second line contains the $ n $ integers in $ s=[s_0, s_1, \ldots, s_{n-1}] $ .
- $ 1 \le n \le 10^6 $
- For all $ i $ ( $ 0\le i < n $ ), $ 0\le s_i < 2^{31}-1 $ .
## Output Format
Output an integer on a line, indicating the minimum cost to sort the input array $ s $ of $ n $ integers in non-decreasing order using Alice's function, following the rules mentioned above.
## Sample #1
### Sample Input #1
```
6
3 2 5 5 4 1
```
### Sample Output #1
```
25
```
## Sample #2
### Sample Input #2
```
4
4 3 2 1
```
### Sample Output #2
```
16
```
## Limit
Time Limit
2.00s
Memory Limit
1000.00MB |
2041 | L | Building Castle | [] | 2900 | https://codeforces.com/problemset/problem/2041/L | 1732431900 | en | codeforces | # Building Castle
## Problem Description
A-Ju has a gorgeous castle in which she often enjoys living. However, she gets tired of living in the castle for a long time. Thus, she decides to rebuild her castle into some specific shape to make her it more beautiful.
Let's say we represent A-Ju's castle as a 2D convex polygon $ ^{\text{โ}} $ on the 2D plane. A-Ju aims to rebuild her castle into a point symmetric convex polygon. Here, a polygon is point symmetric if there exists a center $ c $ such that for every point $ p $ in the polygon, the reflection $ p^\prime $ of $ p $ across $ c $ is also in the polygon.
While designing an arbitrary point symmetric convex polygon shape is easy, the cost of rebuilding is very high. After some estimation, A-Ju found that the cost of rebuilding is proportional to the area of the symmetric difference $ ^{\text{โ }} $ between the original castle and the new castle. See the following figure for an example:
In the example above, A-Ju's castle is a shape of the convex polygon formed by points $ (3, 7) - (2, 1) - (6, 3) $ . After rebuilding her castle into the shape of the polygon formed by $ (3, 7) - (\frac{7}{3}, 3) - (\frac{13}{3}, \frac{1}{3}) - (5, \frac{13}{3}) $ , the area of the symmetric difference between these two polygons will be $ \frac{11}{3} $ . The difference can be calculated as the sum of the additional area (represented by the green grid region) and the shaved area (represented by the red line region).
Please write a program that helps A-Ju design a blueprint of the new castle, such that the area of the symmetric difference between the original one and the new one is minimized. You only need to output the minimum value since A-Ju wants to estimate her cost first.
$ ^{\text{โ}} $ A polygon $ P $ is convex if for every two points $ p, q \in P $ , the line segment connecting them is also contained in $ P $ , i.e., $ tp + (1-t)q \in P $ for all $ t \in [0, 1] $ . Equivalently, it is a polygon whose interior angles are all less than $ 180^{\circ} $ .
$ ^{\text{โ }} $ The symmetric difference of two polygons is the part of the 2D plane that belongs to exactly one polygon.
## Input Format
The first line contains an integer $ n $ , representing the number of vertices of the polygon that forms A-Ju's castle.
Then, $ n $ lines follow, the $ i $ -th of which contains two integers $ x_i, y_i $ , representing the coordinates of the $ i $ -th vertex. The vertices are given in a counterclockwise order.
- $ 3\leq n\leq 500 $
- $ |x_i|, |y_i|\leq 10^4 $
- The vertices are given in a counterclockwise order and are guaranteed to form a convex polygon without three collinear points.
## Output Format
Print a single real number in one line, representing the minimum area of the symmetric difference between the original castle and the new castle.
Your answer will be accepted if the absolute or relative error does not exceed $ 10^{-4} $ . Formally, let your answer be $ a $ , and the jury's answer be $ b $ . Your answer is considered correct if $ \frac{|a-b|}{\max(1,|b|)}\le 10^{-4} $ .
## Sample #1
### Sample Input #1
```
3
2 1
6 3
3 7
```
### Sample Output #1
```
3.666666666667
```
## Sample #2
### Sample Input #2
```
4
0 0
5 0
5 5
0 5
```
### Sample Output #2
```
0.000000000000
```
## Limit
Time Limit
10.00s
Memory Limit
1000.00MB |
2041 | K | Trophic Balance Species | ["binary search", "brute force", "dfs and similar", "graphs"] | 3100 | https://codeforces.com/problemset/problem/2041/K | 1732431900 | en | codeforces | # Trophic Balance Species
## Problem Description
 Image generated by ChatGPT 4o.In an interdisciplinary collaboration, an ecosystem scientist and a computer scientist join forces to analyze the structure of a complex ecosystem using computational methods. The ecosystem scientist models the ecosystem as a directed graph $ D = (V, A) $ , where each species is represented by a node $ v \in V $ , and each feeding relationship is represented as a directed edge $ (x, y) \in A $ from prey $ x $ to predator $ y $ . This graph structure allows them to simulate the flow of energy throughout the ecosystem from one species to another.
Two essential features of the ecosystem are defined:
- Independent Trophic Group: A set $ S $ of animal species is classified as an independent trophic group if no species $ x \in S $ can reach another species $ y \in S $ (for some $ y \ne x $ ) through a series of directed feeding relationships, meaning there is no directed path in $ D $ from $ x $ to $ y $ .
- Trophic Balance Species: A species is termed a trophic balance species if it has a nearly equal number of species that affect it as directly or indirectly predators (species it can reach via a directed path in $ D $ , excluding itself) and species that affect it as directly or indirectly prey (species that can reach it via a directed path in $ D $ , excluding itself). Specifically, trophic balance species are those for which the absolute difference between the above two numbers is minimum among all species in the ecosystem.
Consider an ecosystem with $ n = 4 $ species and $ m = 3 $ feeding relationships:
- Species 1: Grass (Node 1)
- Species 2: Rabbits (Node 2)
- Species 3: Foxes (Node 3)
- Species 4: Hawks (Node 4)
The directed edges representing the feeding relationships are as follows:
- $ (1, 2) $ : Grass is eaten by Rabbits.
- $ (2, 3) $ : Rabbits are eaten by Foxes.
- $ (2, 4) $ : Rabbits are also eaten by Hawks.
Now, consider the set $ S=\{3,4\} $ (Foxes and Hawks). There are no directed paths between Foxes (Node 3) and Hawks (Node 4); Foxes cannot reach Hawks, and Hawks cannot reach Foxes through any directed paths. Therefore, this set qualifies as an independent trophic group.
Examination of Species
- Species 1 (Grass):
- Can reach: 3 (Rabbits, Foxes, and Hawks)
- Can be reached by: 0 (None)
- Absolute difference: $ |3 - 0| = 3 $
- Species 2 (Rabbits):
- Can reach: 2 (Foxes and Hawks)
- Can be reached by: 1 (Grass)
- Absolute difference: $ |2 - 1| = 1 $
- Species 3 (Foxes):
- Can reach: 0 (None)
- Can be reached by: 2 (Grass and Rabbits)
- Absolute difference: $ |0-2| = 2 $
- Species 4 (Hawks):
- Can reach: 0 (None)
- Can be reached by: 2 (Grass and Rabbits)
- Absolute difference: $ |0-2| = 2 $
Among these species, Rabbits have the smallest absolute difference of $ 1 $ , indicating that they are a trophic balance species within the ecosystem.
It is known that any independent trophic group in the ecosystem has a size of at most $ k $ . The task is to find the set of all trophic balance species in the ecosystem.
## Input Format
The first line contains exactly two integers $ n $ and $ m $ , where $ n $ (resp. $ m $ ) denotes the number of nodes (resp. edges) in the directed graph $ D $ induced by the investigated ecosystem. The nodes are numbered as $ 1, 2, \ldots, n $ . Then, $ m $ lines follow. The $ i $ -th line contains two integers $ x_i $ and $ y_i $ indicating a directed edge from node $ x_i $ to node $ y_i $ .
- $ 1 \le n \le 2 \times 10^5 $
- $ 0 \le m \le \min\{ n(n-1), 4 \times 10^5\} $
- $ k $ is not an input value, and it is guaranteed that $ 1 \le k \le 16 $ for each investigated ecosystem.
- For all $ i $ ( $ 1\le i\le m $ ), $ 1\le x_i, y_i\le n $ and $ x_i\neq y_i $ .
- Each ordered pair $ (x_i, y_i) $ appears at most once in the input.
## Output Format
Output on a single line the node identidiers of all trophic balance species in ascending order. For any two consecutive node identifiers, separate them by a space.
## Sample #1
### Sample Input #1
```
4 3
1 2
2 3
2 4
```
### Sample Output #1
```
2
```
## Sample #2
### Sample Input #2
```
4 5
1 2
1 3
1 4
2 3
3 2
```
### Sample Output #2
```
2 3 4
```
## Limit
Time Limit
3.00s
Memory Limit
125.00MB |
2041 | J | Bottle Arrangement | ["data structures", "divide and conquer", "dp", "dsu", "greedy"] | 2700 | https://codeforces.com/problemset/problem/2041/J | 1732431900 | en | codeforces | # Bottle Arrangement
## Problem Description
 Image generated by ChatGPT 4o.Mayaw works in a renowned Epah (aboriginal Taiwanese millet wine; Epah is the Pangcah term for aboriginal Taiwanese millet wine, named in the language of the Pangcah people, the largest Indigenous group in Taiwan) bar in the Fata'an Village. To showcase the depth of its collections, the bar has a two-row wine rack where each row can fit exactly $ n $ bottles. There are already $ n $ bottles placed on the back row of the rack, where the $ i $ -th bottle from left has height $ a_i $ . The owner of the bar has another $ n $ bottles with distinct heights $ b_1, \ldots, b_n $ that he would like Mayaw to put on the first row. To ensure that all bottles on the rack are visible, the owner requires that each bottle on the back row should not be blocked by the one put in front of it. That is, if a bottle of height $ h $ is put on the $ i $ -th spot (from left) in the first row, then $ h $ must be less than $ a_i $ . However, not all such arrangements are good for the owner. To pay tributes to the Maxi Mountain nearby, he additionally demands that the bottles in the front row should display a mountain-like shape. In particular, the heights of the bottles, when listing from left to right, should form a sequence that is first (non-strictly) increasing and then (non-strictly) decreasing.
Unfortunately, sometimes it is impossible to achieve owner's requirements. That is why Mayaw is also allowed to slightly reduce a bottle's height by removing its cap that has a height of $ 1 $ . In other words, after the removal of the cap, the height of the bottle decreases by exactly $ 1 $ . Of course, exposing the Epah inside the bottle to the open air is detrimental to its quality, and therefore it is desirable to remove as few bottle caps as possible.
Can you help Mayaw determine the minimum number of caps needed to be removed so that he can arrange the bottles in a way that satisfies the owner's requirements? Note that the positions of the bottles in the back row are fixed and Mayaw is not allowed to modify them.
## Input Format
The first line contains an integer $ n $ which represents the number of bottles in each row. The second line contains $ n $ integers $ a_1, \ldots, a_n $ , the height of the bottles in the back row. The third line contains $ n $ distinct integers $ b_1, \ldots, b_n $ , the height of the bottles in the front row.
- $ 1 \leq n \leq 5 \times 10^5 $
- $ 1 \leq a_i, b_i \leq 10^9 $
- All $ b_i $ 's are distinct.
## Output Format
Output the minimum number of bottle caps needed to be removed so that Mayaw can arrange the bottles in the desired way. If it is impossible to achieve that (regardless of the number of caps removed), output -1 instead.
## Sample #1
### Sample Input #1
```
5
2 4 6 5 4
1 2 3 4 5
```
### Sample Output #1
```
0
```
## Sample #2
### Sample Input #2
```
5
2 3 6 5 4
1 2 3 4 5
```
### Sample Output #2
```
0
```
## Sample #3
### Sample Input #3
```
5
6 2 6 6 6
1 2 3 4 5
```
### Sample Output #3
```
1
```
## Sample #4
### Sample Input #4
```
5
7 2 7 7 7
1 3 4 5 6
```
### Sample Output #4
```
-1
```
## Sample #5
### Sample Input #5
```
10
18 20 16 18 16 10 13 6 4 10
19 10 9 15 4 16 6 12 3 17
```
### Sample Output #5
```
4
```
## Limit
Time Limit
5.00s
Memory Limit
1000.00MB |
2041 | I | Auto Complete | ["binary search", "data structures", "hashing", "implementation", "sortings", "strings", "trees"] | 2300 | https://codeforces.com/problemset/problem/2041/I | 1732431900 | en | codeforces | # Auto Complete
## Problem Description
You are designing a snazzy new text editor, and you want to add a nifty auto-complete feature to help users save time. Here is how it will work: if a user types "App", your editor will magically suggest the word "Application"! Even better, users can personalize the words that auto-complete in your editor.
Your editor will support 4 kinds of operations (Let's say the current text in your editor is $ t $ ):
1. Add an auto complete pattern $ p_i $ .
2. Delete an auto complete pattern $ p_i $ .
3. Append a string $ s $ to the end of $ t $ .
4. Delete $ c $ characters from the end of $ t $ . Note that if $ c $ is larger then the length of $ t $ , delete all the characters from $ t $ .
After each action, your editor should suggest an auto-complete candidate $ i $ that matches the following criteria:
1. The string $ p_i $ has a prefix equal to $ t $ .
2. If there are multiple $ p_i $ , pick the longest one.
3. If there are still multiple $ p_i $ , pick the one with the smallest lexicographic order.
4. If there are still multiple $ p_i $ , pick the one with the smallest ID.
To simplify the question, for each action, print the suggested auto complete pattern ID. If there's no match, print -1.For example, let us say we have three candidates: "alice", "bob", and "charlie", with ID 1, 2, and 3. At first, there is nothing on the screen, so "charlie" (3) should be suggested because it is the longest. Then, let us say the user types "b". You should suggest "bob" (2) because it is the only one that starts with "b". Finally, let us say the user type "body". You should print -1 because there is no matched pattern.
## Input Format
The first line contains an integer $ n $ , followed by $ n $ lines, with each line containing an action.
There are four types of actions:
1. $ i $ $ p_i $
2. $ i $
3. $ s $
4. $ c $
The add actions are followed by an integer $ i $ and a pattern $ p_i $ , which means the user wants to add a pattern with ID $ i $ . The delete actions are followed by an integer $ i $ , which means the user wants to delete $ p_i $ from the pattern set. The append actions are followed by a string $ s $ , which means the user appends $ s $ to the end of $ t $ . The backspace actions are followed by an integer $ c $ , which means the user deletes $ c $ characters from the end of $ t $ . All the parameters are splitted by a single space character.- $ 1 \leq n \leq 10^6 $
- The total number of characters in all $ p_i $ and $ s $ does not exceed $ 2\times 10^6 $ .
- $ 1 \leq c \leq 2\times 10^6 $
- The strings $ p_i $ and $ s $ may contain any printable characters, excluding all space characters (ASCII number in the range from $ 33 $ to $ 126 $ ).
- The ID $ i $ for each add operation is unique.
- The ID $ i $ for each delete is guaranteed to be valid.
- Each ID $ i $ satisfies $ 0\le i \le n $ .
## Output Format
The program should output $ n $ lines. For each action, output an integer $ i $ , which means that after the action, $ p_i $ is the suggested auto complete candidate. If there is no $ p_i $ that matches the requirement, output -1.
## Sample #1
### Sample Input #1
```
6
add 1 pattern1_alice
add 2 pattern2_bob
add 3 pattern3_charlie
append pattern
append 2_bobabc
backspace 3
```
### Sample Output #1
```
1
1
3
3
-1
2
```
## Sample #2
### Sample Input #2
```
6
append pattern
add 1 pattern1_alice____
add 2 pattern2_bob______
add 3 pattern3_charlie__
delete 1
delete 2
```
### Sample Output #2
```
-1
1
1
1
2
3
```
## Limit
Time Limit
4.00s
Memory Limit
1000.00MB |
2041 | H | Sheet Music | ["combinatorics", "dp", "math"] | 2300 | https://codeforces.com/problemset/problem/2041/H | 1732431900 | en | codeforces | # Sheet Music
## Problem Description
 Image generated by ChatGPT 4o.Alice likes singing. As a singing enthusiast, Alice has listened to countless songs and has tried singing them many times. However, occasionally, some songs make Alice feel bored. After some research, Alice believes that this is because even though the songs she chose are all different, due to her instinctive preference, they all turn out to be musically similar to one another.
To thoroughly analyze this, Alice decided to study the sheet music of the songs. For convenience, Alice represented a song of length $ n $ as an integer sequence $ a_1, a_2, \ldots, a_n $ , where $ a_i $ is the pitch of the $ i $ -th note. Then she defined the musical equivalence between songs. Two songs $ a_1, a_2, \ldots, a_n $ and $ b_1, b_2, \ldots, b_n $ of length $ n $ are musically equivalent if for all $ 1\leq i<n $ , both $ a_i, a_{i+1} $ and $ b_{i}, b_{i+1} $ have the same pitch relationship. More specifically, $ a_i, a_{i+1} $ and $ b_i, b_{i+1} $ have the same pitch relationship if either
- $ a_i < a_{i + 1} $ and $ b_i < b_{i + 1} $ ,
- $ a_i = a_{i + 1} $ and $ b_i = b_{i + 1} $ , or
- $ a_i > a_{i + 1} $ and $ b_i > b_{i + 1} $ .
For example, $ 1, 2, 3, 3, 2 $ and $ 5, 9, 13, 13, 1 $ are musically equivalent, while $ 1, 2, 3, 2, 1 $ and $ 1, 2, 2, 2, 1 $ are not. Having practiced consistently for a long time, Alice is able to sing any note in the range of $ [1, k] $ . She wants to know how many different songs of length $ n $ within her range there are, if we treat musically equivalent songs as the same one. Can you help her calculate the number?
Since the answer might be large, print the answer modulo $ 998244353 $ .
## Input Format
The only line contains two integers $ n, k $ .
- $ 1\leq n\leq 10^6 $
- $ 1\leq k \leq 10^9 $
## Output Format
Output the number of different songs modulo $ 998244353 $ .
## Sample #1
### Sample Input #1
```
3 2
```
### Sample Output #1
```
7
```
## Sample #2
### Sample Input #2
```
5 3
```
### Sample Output #2
```
67
```
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
2041 | G | Grid Game | [] | 3100 | https://codeforces.com/problemset/problem/2041/G | 1732431900 | en | codeforces | # Grid Game
## Problem Description
Claire loves drawing lines. She receives a sheet of paper with an $ n \times n $ grid and begins drawing "lines" on it. Wellโthe concept of a "line" here is not what we usually think of. Claire refers each line to be a set of consecutive vertical grid cells. When she draws a line, these cells are all covered with black ink. Initially, all the cells are white, and drawing lines turns some of them black. After drawing a few lines, Claire wonders: how many ways she can color an additional white cell black so that the remaining white cells do not form a single connected component.
Two cells are directly connected if they share an edge. Two cells $ x $ and $ y $ are indirectly connected if there exists a sequence of cells $ c_0, c_1, \ldots, c_k $ with $ k > 1 $ such that $ c_0 = x $ , $ c_k = y $ , and for every $ i \in \{1, 2, \ldots, k\} $ the cells $ c_i $ and $ c_{i-1} $ are directly connected. A set of cells forms a single connected component if each pair of cells in the set is either directly or indirectly connected.
The grid has $ n $ rows and $ n $ columns, both indexed from $ 1 $ to $ n $ . Claire will draw $ q $ lines. The $ i $ -th line is drawn in the $ y_i $ -th column, from the $ s_i $ -th row to the $ f_i $ -th row, where $ s_i \leq f_i $ for each $ i \in \{1, 2, \ldots, q\} $ . Note that the cells that are passed by at least one of the $ q $ lines are colored black. The following figure shows an example of a $ 20\times 20 $ grid with $ q=67 $ lines. The grid cells marked with red star symbols refer to the cells such that, if Claire colors that cell black, all white cells no longer form a single connected component.
You may assume that, after drawing the $ q $ lines, the remaining white cells form a single connected component with at least three white cells.
## Input Format
The first line contains exactly one integer $ t $ , indicating the number of test cases. For each test case, it begins with a line containing exactly two integers $ n $ and $ q $ . This indicates that the grid is $ n $ by $ n $ and that Claire draws $ q $ lines on it. Then $ q $ lines follow. For each $ i \in \{1, 2, \ldots, q\} $ , the $ i $ -th line among the $ q $ lines contains exactly three integers $ y_i $ , $ s_i $ , and $ f_i $ .
- $ 1\le t \le 125 $
- $ 2\leq n \leq 10^9 $
- $ q\ge 1 $ ; the sum of all $ q $ values is at most $ 10^5 $ .
- $ 1\leq y_i \leq n $
- $ 1\leq s_i \leq f_i \leq n $
- There are at least three white cells and all white cells form a connected component.
## Output Format
Print an integer on a line, indicating how many ways Claire can color an additional white cell black so that the remaining white cells do not form a single connected component.
## Sample #1
### Sample Input #1
```
2
3 1
2 1 2
5 2
2 1 4
4 2 5
```
### Sample Output #1
```
5
15
```
## Limit
Time Limit
4.00s
Memory Limit
1000.00MB |
2041 | F | Segmentation Folds | ["brute force", "dfs and similar", "number theory"] | 2400 | https://codeforces.com/problemset/problem/2041/F | 1732431900 | en | codeforces | # Segmentation Folds
## Problem Description
Peter loves folding segments. There is a segment on a number line occupying the interval $ [\ell, r] $ . Since it is the prime time for folding the segments, Peter decides to fold the segment carefully. In each step, he chooses one of the two following operations whenever possible:
1. Operation $ \tt{LTR} $ : he folds the segment from left to right, where $ \ell $ coincides with a point $ x $ ( $ \ell < x \le r $ ) such that $ \ell+x $ is a prime number $ ^{\text{โ}} $ . When Peter chooses this operation, he always chooses the largest possible value $ x $ . Note that the segment occupies the interval $ [\frac{1}{2}(\ell+x), r] $ afterwards.
2. Operation $ \tt{RTL} $ : he folds the segment from right to left, where $ r $ coincides with a point $ x $ ( $ \ell \le x < r $ ) such that $ r+x $ is a prime number. When Peter chooses this operation, he always chooses the smallest possible value $ x $ . Note that the segment occupies the interval $ [\ell, \frac{1}{2}(r+x)] $ afterwards.
A folding sequence refers to a sequence of operations specified above. Peter wants to fold the segment several times, resulting in the shortest possible interval whose length that cannot be further reduced. The length of an interval $ [\ell, r] $ is defined naturally to be $ r-\ell $ . Let's consider the following example. Suppose that we are folding a segment initially occupying the interval $ [1, 30] $ . There are three folding sequences that lead to the shortest possible resulting interval, as shown in the following figure.
Please help Peter determine the number of folding sequences such that the resulting interval has a shortest possible length. Output the number modulo $ 998244353 $ .
$ ^{\text{โ}} $ Recall that an integer $ p>1 $ is a prime number if there do not exist integers $ a, b>1 $ such that $ p=ab $ .
## Input Format
The first line contains an integer $ t $ , denoting the number of test cases. In each of the following $ t $ lines, there are two integers $ \ell $ and $ r $ .
- $ 1 \le t \le 10 $
- $ 1 \le \ell < r \le 10^{12} $
- $ r - \ell \le 10^5 $
## Output Format
For each test case, please output a line denoting the number of ways to fold the given segment such that the resulting segment has the shortest possible length, modulo $ 998244353 $ .
## Sample #1
### Sample Input #1
```
3
1 30
16 18
142857 240135
```
### Sample Output #1
```
3
1
63
```
## Limit
Time Limit
1.00s
Memory Limit
1000.00MB |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.