contest_id
stringlengths
1
4
index
stringclasses
43 values
title
stringlengths
2
63
statement
stringlengths
51
4.24k
tutorial
stringlengths
19
20.4k
tags
listlengths
0
11
rating
int64
800
3.5k
code
stringlengths
46
29.6k
2070
B
Robot Program
There is a robot on the coordinate line. Initially, the robot is located at the point $x$ ($x \ne 0$). The robot has a sequence of commands of length $n$ consisting of characters, where L represents a move to the left by one unit (from point $p$ to point $(p-1)$) and R represents a move to the right by one unit (from point $p$ to point $(p+1)$). The robot starts executing this sequence of commands (one command per second, in the order they are presented). However, whenever the robot reaches the point $0$, the counter of executed commands is reset (i. e. it starts executing the entire sequence of commands from the very beginning). If the robot has completed all commands and is not at $0$, it stops. Your task is to calculate how many times the robot will enter the point $0$ during the next $k$ seconds.
Let's simulate the process until either the command sequence terminates or the robot reaches the point $0$. If the sequence ends and the robot is not at $0$, then the answer to the problem is $0$. Otherwise, we need to check whether the robot can return to the point $0$ if we begin executing commands again. We can simply iterate through the sequence and record the first time the robot returns to the point $0$. If no such time exists, then the answer to the problem is $1$. Otherwise, this loop (from $0$ to $0$) will continue until time $k$ expires. In this case, the answer is $\left\lfloor\frac{k'}{c}\right\rfloor + 1$, where $k'$ is the remaining time after the first hit of the point $0$, and $c$ is the time required for the robot to return to the same position from the point $0$.
[ "brute force", "implementation", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; using li = long long; int main() { int t; cin >> t; while (t--) { li n, x, k; cin >> n >> x >> k; string s; cin >> s; for (int i = 0; i < n; ++i) { x += (s[i] == 'L' ? -1 : +1); --k; if (!x) break; } li ans = 0; if (!x) { ans = 1; for (int i = 0; i < n; ++i) { x += (s[i] == 'L' ? -1 : +1); if (!x) { ans += k / (i + 1); break; } } } cout << ans << '\n'; } }
2070
C
Limited Repainting
You are given a strip, consisting of $n$ cells, all cells are initially colored red. In one operation, you can choose a segment of consecutive cells and paint them \textbf{blue}. Before painting, the chosen cells can be either red or blue. Note that it is not possible to paint them red. You are allowed to perform at most $k$ operations (possibly zero). For each cell, the desired color after all operations is specified: red or blue. It is clear that it is not always possible to satisfy all requirements within $k$ operations. Therefore, for each cell, a penalty is also specified, which is applied if the cell ends up the wrong color after all operations. For the $i$-th cell, the penalty is equal to $a_i$. The penalty of the final painting is calculated as the \textbf{maximum penalty} among all cells that are painted the wrong color. If there are no such cells, the painting penalty is equal to $0$. What is the minimum penalty of the final painting that can be achieved?
The problem asks to minimize the maximum. An experienced participant should immediately consider binary search as a possible solution. The condition for binary search can be formulated as follows: is there a coloring such that its penalty does not exceed $x$? If the penalty does not exceed $x$, then it does not exceed $x+1$, which means the function is monotonic. This can be interpreted as follows. Cells with a penalty less than or equal to $x$ can be left red, or they can be painted blue. Cells with a penalty greater than $x$ must be painted the correct color. In fact, since we don't care about the cells of the first type, we can simply remove them from the strip. We need to ensure that the cells of the second type can be correctly colored in no more than $k$ operations. That is, we need to check that the blue cells can be divided into no more than $k$ contiguous segments. This check can be done in linear time. We can count the number of positions $i$ such that cell $i$ is blue, and cell $i-1$ is either absent or red. Each such position indicates the start of a segment. Therefore, their count is equal to the number of segments. Overall complexity: $O(n \log A)$ for each testcase.
[ "binary search", "greedy" ]
1,500
for _ in range(int(input())): n, k = map(int, input().split()) s = input() a = list(map(int, input().split())) l, r = 0, 10**9 res = -1 def check(d): last = 'R' cnt = 0 for i in range(n): if a[i] > d: if s[i] == 'B' and last != 'B': cnt += 1 last = s[i] return cnt <= k while l <= r: m = (l + r) // 2 if check(m): res = m r = m - 1 else: l = m + 1 print(res)
2070
D
Tree Jumps
You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. Let $d_x$ be the distance (the number of edges on the shortest path) from the root to the vertex $x$. There is a chip that is initially placed at the root. You can perform the following operation as many times as you want (possibly zero): - move the chip from the current vertex $v$ to a vertex $u$ such that $d_u = d_v + 1$. If $v$ is the root, you can choose any vertex $u$ meeting this constraint; however, if $v$ is not the root, $u$ should not be a neighbor of $v$ (there should be no edge connecting $v$ and $u$). For example, in the tree above, the following chip moves are possible: $1 \rightarrow 2$, $1 \rightarrow 5$, $2 \rightarrow 7$, $5 \rightarrow 3$, $5 \rightarrow 4$, $3 \rightarrow 6$, $7 \rightarrow 6$. A sequence of vertices is \textbf{valid} if you can move the chip in such a way that it visits all vertices from the sequence (and only them), in the order they are given in the sequence. Your task is to calculate the number of valid vertex sequences. Since the answer might be large, print it modulo $998244353$.
We can solve this problem by using dynamic programming. Let $dp_v$ represent the number of valid sequences ending at vertex $v$. To calculate $dp_v$, we can iterate over all previous vertices $u$ in the sequence, such that $d_v = d_u + 1$ and $u \ne p_v$ (or $u$ is the root). Then, $dp_v$ is the sum of $dp_u$ for all such $u$. Note that the vertices should be processed in order of increasing distance from the root, because otherwise, $dp_u$ might not be calculated when we need to use it in $dp_v$. However, this approach can be very slow, as there may be $O(n)$ vertices $u$ for each vertex $v$. In order to speed up this solution, we can observe that if vertices have the same distance from the root, the calculation of their $dp$ values follows a similar pattern. Specifically, we only need to consider the $dp$ values of vertices in the previous "layer" of the tree, excluding their parent node. Thus, we can store the sum of all $dp$ values for each "layer". Let $tot_i$ be the sum of $dp_v$ for all vertices $v$ with distance $i$ from the root. Then we can easily calculate $dp_v$ as $tot_{d_v - 1} - dp_{p_v}$ (or minus $0$ if $p_v$ is the root). The answer to the problem is the sum of all values $dp_v$. To order the vertices according to the distance from the root, you can use DFS (and then sort the vertices according to the distance) or BFS. Or you can use the following method: since for every vertex, the index of its parent is less, we can process the vertices from $1$ to $n$ and set $d_v = d_{p_v} + 1$. Then, for every depth, you can build a vector of all vertices on that depth (by adding each vertex to the corresponding vector). This approach works in $O(n)$.
[ "dfs and similar", "dp", "trees" ]
1,600
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; if (x >= MOD) x -= MOD; if (x < 0) x += MOD; return x; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> p(n), d(n); vector<vector<int>> vs(n); for (int v = 1; v < n; ++v) { cin >> p[v]; --p[v]; d[v] = d[p[v]] + 1; vs[d[v]].push_back(v); } vector<int> dp(n), tot(n); dp[0] = tot[0] = 1; for (int i = 1; i < n; ++i) { for (int v : vs[i]) { dp[v] = add(tot[d[v] - 1], d[v] == 1 ? 0 : -dp[p[v]]); tot[d[v]] = add(tot[d[v]], dp[v]); } } int ans = 0; for (int v = 0; v < n; ++v) { ans = add(ans, dp[v]); } cout << ans << '\n'; } }
2070
E
Game with Binary String
Consider the following game. Two players have a binary string (a string consisting of characters 0 and/or 1). The players take turns, the first player makes the first turn. During a player's turn, he or she has to choose exactly two adjacent elements of the string and remove them (\textbf{the first element and the last element are also considered adjacent}). Furthermore, there are additional constraints depending on who makes the move: - if it's the first player's move, \textbf{both} chosen characters should be 0; - if it's the second player's move, \textbf{at least one} of the chosen characters should be 1. The player who can't make a valid move loses the game. This also means that if the string currently has less than $2$ characters, the current player loses the game. You are given a binary string $s$ of length $n$. You have to calculate the number of its substrings such that, if the game is played on that substring and both players make optimal decisions, the first player wins. In other words, calculate the number of pairs $(l, r)$ such that $1 \le l \le r \le n$ and the first player has a winning strategy on the string $s_l s_{l+1} \dots s_r$.
First, we need to modify the game a bit. Suppose that, instead of removing two adjacent characters, a player can remove any pair of characters of the required type. So, the first player can remove any two characters equal to 0; the second player can remove any two characters, at least one of which is 1. Now the order of characters does not matter, only their quantities. Let $c_0$ be the number of 0's in the string, $c_1$ be the number of 1's. It's pretty obvious that in this version of the game, the second player should always remove one 0 and one 1, if it is possible (and only if there are no 0's, remove two 1's). So, after each pair of moves, one 1 and three 0's are removed. Suppose that the length of the string is divisible by $4$. Then, if $c_0 = c_1 \cdot 3$, the game lasts until the whole string is removed, and the first player loses. If $c_0 < c_1 \cdot 3$, the first player runs out of moves before the second, and if $c_0 > c_1 \cdot 3$, the second player runs out of moves first. So, if the length of the string is divisible by $4$, the first player wins iff $c_0 > c_1 \cdot 3$. If the length of the string is not divisible by $4$, then we can derive a similar condition, but it will depend on the remainder of the length modulo $4$. For example, let's derive a condition for the case when the length is equal to $3$ modulo $4$. We need to derive a threshold like "if $c_0 \ge f(c_1)$, the first player wins, otherwise the second player wins". Suppose we made $\lfloor \frac{|s|}{4} \rfloor$ moves for both players. Then we have removed some $x$ characters equal to 1 and $3x$ characters equal to 0. If the resulting string has at least $2$ characters equal to 0, then the first player wins, otherwise the second player wins. So, if $c_0 - 3 = c_1 \cdot 3$ or $c_0 - 2 = (c_1 - 1) \cdot 3$, then the first player wins. We can rewrite this condition to $c_0 \ge c_1 \cdot 3 - 1$: if it is met, then the first player wins (either the string gets reduced to size $3$ and the first player can make a move, or the second player runs out of 1's before that). We can derive similar conditions for $|s| \bmod 4 = 1$ and $|s| \bmod 4 = 2$. All of them have the form $c_0 > c_1 \cdot 3 + k$, where $k$ is some constant depending on $|s| \bmod 4$. You can either derive them analytically, or write a dynamic programming to check all strings with length $\le 20$ and derive this constant $k$ for every remainder from this dynamic programming. The only issue is that we have allowed the players to take non-adjacent characters. For the second player, it does not matter: that player always wants to take one 0 and one 1, and if there are at least one pair of different characters in the string, there is at least one substring 10 or 01. However, for the first player, this might be an issue: we have allowed to remove two characters equal to 0 even if there is no substring 00. We can prove that the result of the game does not depend on it. If the first player cannot make a move according to the rules of the original game (there is no substring 00, and either the first or the last character is 1), then $c_0 \le c_1$. And since every pair of moves removes three 0's and one 1, the first player will run out of moves before the second player even if the first player is allowed to remove non-adjacent character. Okay, now the problem reduces to the following: for every remainder of length $i$ modulo $4$, there is some constant $k_i$, and we have to calculate the number of substrings $s[l:r]$ such that: $(r - l + 1) \bmod 4 = i$; in $s[l:r]$, $c_0 > c_1 \cdot 3 + k_i$. Let's replace every character 1 with the integer $-3$, and every character 0 with the integer $1$. Then, the condition $c_0 > c_1 \cdot 3 + k_i$ means that $sum[l:r] > k_i$, where $sum[l:r]$ is the sum on segment $[l, r]$ of the resulting array. To calculate the number of such subarrays efficiently, we can build the prefix sums over the array (let the sum of first $i$ elements be $p_i$), and rewrite this condition as $p_{r+1} - p_l > k_i$. Let's go through prefix sums from left to right and maintain four data structures $D_0, D_1, D_2, D_3$, where $D_i$ stores the sums on prefixes $p_j$ we met earlier such that $j \bmod 4 = i$. When we process the prefix $p_x$, for each of these data structures $D_i$, we need to calculate the number of values $v$ in it such that $p_x - v > k_{(x-i) \bmod 4}$, or $v < p_x - k_{(x-i) \bmod 4}$. Then, we need to add $p_x$ into the data structure $D_{x \bmod 4}$. Which data structure we need? It should support operations like "insert an element" and "get the number of elements less than some value $x$". You can use something like an order statistics tree, a Fenwick tree or a Segment tree. Note that you have to insert negative elements up to $-3 \cdot n$, so if you use a Fenwick tree or a Segment tree, you should add $3n$ to all values you insert there. This solution works in $O(n \log n)$. You can actually speed this up by merging these data structures into one and/or getting rid of the $O(\log n)$ altogether using the fact that every next query you make is pretty close to the previous query, but this was not needed.
[ "constructive algorithms", "data structures", "divide and conquer", "games", "greedy", "math" ]
2,200
#include<bits/stdc++.h> using namespace std; const int N = 300003; const int M = 3 * N; const int S = 4 * N; struct segtree { vector<int> T; void add(int v, int l, int r, int pos, int val) { T[v] += val; if(l != r - 1) { int m = (l + r) / 2; if(pos < m) add(v * 2 + 1, l, m, pos, val); else add(v * 2 + 2, m, r, pos, val); } } int get(int v, int l, int r, int L, int R) { if(L >= R) return 0; if(l == L && r == R) return T[v]; int m = (l + r) / 2; return get(v * 2 + 1, l, m, L, min(m, R)) + get(v * 2 + 2, m, r, max(m, L), R); } int getSumLess(int l) { return get(0, 0, S, 0, l + M); } void add(int pos, int val) { add(0, 0, S, pos + M, val); } segtree() { T.resize(4 * S); } }; int threshold[] = {0, 1, 1, -2}; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; string s; cin >> s; vector<int> p(n + 1); for(int i = 0; i < n; i++) p[i + 1] = p[i] + (s[i] == '1' ? -3 : 1); vector<segtree> trees(4); long long ans = 0; for(int i = 0; i <= n; i++) { for(int j = 0; j < 4; j++) { int len = (i - j + 4) % 4; int bound = p[i] - threshold[len]; ans += trees[j].getSumLess(bound); } trees[i % 4].add(p[i], 1); } cout << ans << endl; }
2070
F
Friends and Pizza
Monocarp has $n$ pizzas, the $i$-th pizza consists of $a_i$ slices. Pizzas are denoted by uppercase Latin letters from A to the $n$-th letter of the Latin alphabet. Monocarp also has $m$ friends, and he wants to invite \textbf{exactly two} of them to eat pizza. For each friend, Monocarp knows which pizzas that friend likes. After the friends arrive at Monocarp's house, for each pizza, the following happens: - if the pizza is not liked by any of the two invited friends, Monocarp eats it; - if the pizza is liked by exactly one of the two invited friends, that friend eats it; - and if the pizza is liked by both friends, they try to split it. If it consists of an even number of slices, they both eat exactly half of the slices. But if the pizza consists of an odd number of slices, they start quarrelling, trying to decide who will eat an extra slice — and Monocarp doesn't like that. For each $k$ from $0$ to $\sum a_i$, calculate the number of ways to choose \textbf{exactly two friends} to invite so that the friends don't quarrel, and Monocarp eats exactly $k$ slices.
Before solving this problem, I highly recommend that you learn Sum over Subsets Dynamic Programming (aka SOS DP), if you don't know it yet. For example, you can use this CF blog, it has a great explanation of SOS DP: https://codeforces.com/blog/entry/45223 First, we will somewhat change the problem. The original problem wants us to consider all pairs of friends $(i, j)$ where $1 \le i < j \le n$; but instead, we will consider all pairs of friends where $1 \le i, j \le n$ (so, $i$ can be greater than $j$ and can even be equal to $j$). After solving this modified version, we can "subtract" all pairs where $i=j$ (since there are only $O(m)$ of them) and divide all the answers by $2$ to get rid of the pairs where $i>j$ (they are symmetrical to $i<j$, so they yield the same answer). From now on, we consider only the version where we need to count all pairs of friends. For every friend, we can transform the string $s_i$ into a bit mask which shows what pizzas that friend likes. Then, checking if the friends quarrel and which pizzas they will eat can be done by bit operations on their masks: if the bitwise AND of their masks and the mask of odd-size pizzas is non-zero, there is at least one odd-size pizza they both like, so they will quarrel; and the mask of pizzas they will eat is just the bitwise OR of their masks. So, if for each mask, we want to calculate the number of pairs of friends which don't quarrel and result in exactly that mask being eaten, we can run the following code: Or, if for each mask, we calculate $c_i$ as the number of friends having that mask, we can rewrite it as follows: Let's first consider two special instances of this problem, and then we'll combine their solutions to solve the general case. Instance 1. What if all pizzas have even sizes? Then our mask of add pizzas is $0$, so friends will never quarrel. In this case, we can rewrite the "naive" code as follows: This is an OR convolution of the sequence $c$ with itself, and it can be calculated much faster than $O(4^n)$. When dealing with regular convolutions, a fast way to calculate them is the following one: Transform the sequences using FFT or NTT. Multiply the corresponding elements of the transformed sequences. Perform the inverse transformation. OR convolution can be done in the same way, but instead of FFT or NTT, we will use SOS DP. So, an OR convolution of two sequences $a$ and $b$ looks like that: Why does SOS DP do the trick? $C_i = A_i \cdot B_i$ means that $C_i$ is the sum of $a_j \cdot b_k$ over all $j$ and $k$ that are submasks of $i$. For some pairs $(j, k)$, their bitwise OR is exactly $i$; but for others, their bitwise OR is a submask of $i$. So, actually, $C_i$ is the sum over submasks of the sequence we need to obtain, so by applying inverse SOS DP (the transformation which returns the sequence by its sums over submasks), we get exactly what we need. Quick note about inverse SOS DP - it is done the same as the regular SOS DP, but with subtractions instead of additions. You can prove it by trying to "rollback" the changes the regular SOS DP does to a sequence. Okay, the instance when all pizzas have even size is done. Next, we have Instance 2. What if all pizzas have odd sizes? The "naive" code would look like that: Unfortunately, this is much trickier. This is called Fast Subset Convolution, and to do it faster, we have to add another dimension to our sequence. Now suppose we want to get the FSC of sequences $a$ and $b$, and the resulting sequence is named $c$. If the bitwise OR of $i$ and $j$ is $k$, and the bitwise AND of $i$ and $j$ is $0$, then $popcount(k)$ (the number of bits set to $1$ in $k)$ is equal to $popcount(i) + popcount(j)$. So, the value of $c_k$ can be represented as the sum of $a_i \cdot b_j$ over all such $i, j$ that the bitwise OR of $i$ and $j$ is $k$, and $popcount(k) = popcount(i) + popcount(j)$. Let's transform our given sequences of length $2^n$ into two-dimensional matrices of size $(n + 1) \times (2^n)$. Let $a'_{x,i}$ be $0$ if $popcount(i) \ne x$, or $a_i$ if $popcount(i) = x$. Similarly, we denote $b'_{y,j}$ based on $b$. Okay, now let's try to make it so that, in the resulting convolution, the product $a'_{x,i} \cdot b'_{y,j}$ ends up in the cell $c'_{x+y, i \lor j}$, where $\lor$ denotes bitwise OR. To do this, let's evaluate the $k$-th row of $c'$ as the following sum: $\sum_{i=0}^k \text{ORConvolution}(a'_i, b'_{k-i})$. The OR Convolution will make sure that, for every pair of $i, j$, $a_i \cdot b_j$ ends up in some cell of the form $c'_{k, i \lor j}$, and to verify that their bitwise AND is $0$, we can check that $k = popcount(i \lor j)$. So, the resulting value of $c_i$ we want to get is equal to $c'_{popcount(i),i}$. This Fast Subset Convolution can be done in $O(n^2 2^n)$ if you apply SOS DP to every row of $a'$ and $b'$ to get matrices with sums over submasks in each row (let's call them $A$ and $B$), calculate $C_{k,i} = \sum \limits_{j=0}^k A_{j,i} \cdot B_{k-j,i}$, and then apply Inverse SOS DP to each row of $C$ to get the matrix $c'$. Okay, now back to the original problem. Instance 3. What if some pizzas have odd size, and others have even size? We need to make a convolution for which some bits (represending even-sized pizzas) work as in OR Convolution, but other bits (representing odd-sized pizzas) work as in Fast Subset Convolution. The key idea is that we can modify Fast Subset Convolution so that it tracks only the number of bits representing odd-sized pizzas. So, let's define $F(x)$ as the number of bits representing odd-sized pizzas in $x$. So, when we transform the given sequences $a$ and $b$ to the matrices $a'$ and $b'$, we set $a'_{x,i}$ to $0$ if $F(i) \ne x$, or $a_i$ if $F(i) = x$. And our matrices will have size $(p+1) \times (2^n)$, where $p$ is the number of odd-sized pizzas. Note that, in our problem, the sequences $a$ and $b$ are the same, so the matrix $b'$ is actually the same as $a'$. Similarly, to get the sequence $c$ from the matrix $c'$, we set $c_i = c'_{F(i), i}$. This modification of Fast Subset Convolution works in $O(p \cdot n \cdot 2^n)$. Since $p \le n$, we get a solution working in $O(n^2 2^n + mn)$ (the $O(mn)$ summand comes from processing the friends and converting them into masks).
[ "bitmasks", "divide and conquer", "dp", "fft" ]
3,000
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n, m; cin >> n >> m; vector<long long> cnt(1 << n); for(int i = 0; i < m; i++) { string s; cin >> s; int mask = 0; for(auto c : s) mask += (1 << (c - 'A')); cnt[mask]++; } vector<int> a(n); for(int i = 0; i < n; i++) cin >> a[i]; vector<bool> odd(n); int odd_pizzas = 0; int odd_mask = 0; for(int i = 0; i < n; i++) if(a[i] % 2 == 1) { odd[i] = true; odd_pizzas++; odd_mask += (1 << i); } // calculating the number of bits representing odd-sized pizzas in each mask vector<int> cnt_odd(1 << n); for(int i = 0; i < (1 << n); i++) for(int j = 0; j < n; j++) if(odd[j] && ((i >> j) & 1) == 1) cnt_odd[i]++; // transforming the sequence a to a' (and b to b', since a and b are the same) vector<vector<long long>> A(odd_pizzas + 1, vector<long long>(1 << n, 0ll)); for(int i = 0; i < (1 << n); i++) A[cnt_odd[i]][i] = cnt[i]; // applying SOS DP to every row of the matrix for(int k = 0; k <= odd_pizzas; k++) for(int i = 0; i < n; i++) for(int j = 0; j < (1 << n); j++) if((j >> i) & 1) A[k][j] += A[k][j ^ (1 << i)]; // getting the SOS DP of the matrix c' from the editorial vector<vector<long long>> B(odd_pizzas + 1, vector<long long>(1 << n, 0ll)); for(int x = 0; x <= odd_pizzas; x++) for(int y = 0; y <= odd_pizzas - x; y++) for(int i = 0; i < (1 << n); i++) B[x + y][i] += A[x][i] * A[y][i]; // applying inverse SOS DP to every row for(int k = 0; k <= odd_pizzas; k++) for(int i = 0; i < n; i++) for(int j = 0; j < (1 << n); j++) if((j >> i) & 1) B[k][j] -= B[k][j ^ (1 << i)]; int size_ans = 0; for(auto x : a) size_ans += x; vector<long long> ans(size_ans + 1); for(int i = 0; i < (1 << n); i++) { long long cur_cnt = B[cnt_odd[i]][i]; int sum = 0; for(int j = 0; j < n; j++) if((i >> j) & 1) sum += a[j]; ans[sum] += cur_cnt; } for(int i = 0; i < (1 << n); i++) { if(i & odd_mask) continue; int sum = 0; for(int j = 0; j < n; j++) if((i >> j) & 1) sum += a[j]; ans[sum] -= cnt[i]; } reverse(ans.begin(), ans.end()); for(auto x : ans) cout << x / 2 << " "; cout << endl; }
2071
A
The Play Never Ends
Let's introduce a two-player game, table tennis, where a winner is always decided and draws are impossible. Three players, Sosai, Fofo, and Hohai, want to spend the rest of their lives playing table tennis. They decided to play forever in the following way: - In each match, two players compete while the third spectates. - To ensure fairness, no player can play three times in a row. The player who plays twice in a row must sit out as a spectator in the next match, which will be played by the other two players. Otherwise, the winner and the spectator will play in the next match, while the loser will spectate. Now, the players, fully immersed in this infinite loop of matches, have tasked you with solving the following problem: Given an integer $k$, determine whether the spectator of the first match can be the spectator in the $k$-th match.
When Fofo is the spectator of the first match, what is the earliest subsequent game in which he will spectate again? Suppose Sosai wins the first game. What becomes clear? Once the winner of the first match is decided, the rest of the game is completely predictable. For example, if Hohai wins the first match which Fofo spectated, we can see that: ${}$ $\text{Sosai} \overset{\text{Spectator of 1st: Fofo}}{\longleftrightarrow} \text{Hohai}$ $\text{Fofo} \overset{\text{Spectator of 2nd: Sosai}}{\longleftrightarrow} \text{Hohai}$ $\text{Fofo} \overset{\text{Spectator of 3rd: Hohai}}{\longleftrightarrow} \text{Sosai}$ $\text{Hohai} \overset{\text{Spectator of 4th: Fofo}}{\longleftrightarrow} \text{Sosai}$ $\text{Hohai} \overset{\text{Spectator of 5th: Sosai}}{\longleftrightarrow} \text{Fofo}$ $\text{Sosai} \overset{\text{Spectator of 6th: Hohai}}{\longleftrightarrow} \text{Fofo}$ $\text{Sosai} \overset{\text{Spectator of 7th: Fofo}}{\longleftrightarrow} \text{Hohai}$ No matter who wins in the second match, Hohai won't be able to continue playing in the third match (even if he wins the second match) since he has already played two times in a row. Similarly, Fofo won't be able to play in the fourth match because he has already played twice in a row, regardless of the match result. As a result, Fofo won't be able to spectate in the $k$-th match for any $k$ of the form $3x + 1$. The overall time complexity is: $O(1)$.
[ "math", "number theory" ]
800
#include<bits/stdc++.h> using namespace std; void solve() { int k; cin >> k; if (k % 3 == 1) { cout << "Yes\n"; } else { cout << "No\n"; } } int main() { ios::sync_with_stdio(0), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solve(); } }
2071
B
Perfecto
A permutation $p$ of length $n$$^{\text{∗}}$ is perfect if, for each index $i$ ($1 \le i \le n$), it satisfies the following: - The sum of the first $i$ elements $p_1 + p_2 + \ldots + p_i$ is \textbf{not} a perfect square$^{\text{†}}$. You would like things to be perfect. Given a positive integer $n$, find a perfect permutation of length $n$, or print $-1$ if none exists. \begin{footnotesize} $^{\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). $^{\text{†}}$A perfect square is an integer that is the square of an integer, e.g., $9=3^2$ is a perfect square, but $8$ and $14$ are not. \end{footnotesize}
Consider the identity permutation, defined by $p_i = i$. When and why does this permutation not work? The smallest index $i$ where the issue occurs must satisfy the condition that $1 + \ldots + i$ is a perfect square. What is the simplest and most efficient way to resolve this issue? The first observation is that if the sum $1 + 2 + \dots + n = \frac{n(n+1)}{2}$ is a perfect square, no valid perfect permutation exists. To prove that a solution always exists otherwise, start with the identity permutation $p_i = i$ and iterate through indices from $1$ to $n$. We keep on iterating as long as the prefix sum till that moment isn't a perfect square. If the prefix sum up to index $k$ becomes a perfect square, $\frac{k(k+1)}{2} = x^2$, swap $p_k$ and $p_{k + 1}$. This changes the prefix sum to $x^2 + 1$, which is not a perfect square. To ensure this method works, we must show that $\frac{(k+1)(k+2)}{2}$ cannot also be a perfect square. Assume for contradiction that $\frac{(k+1)(k+2)}{2} = y^2$. Then: $y^2 = x^2 + k + 1$ Since $x > \frac{k}{2}$ (because $x^2 = \frac{k(k+1)}{2} > \frac{k^2}{4}$), we have: ${}$ $y^2 = x^2 + k + 1 < x^2 + 2x + 1 = (x+1)^2 \le y^2$ which is a contradiction. Thus, $\frac{(k+1)(k+2)}{2}$ cannot be a perfect square, and the process can be repeated until all indices are processed, ensuring a valid permutation. The overall time complexity is: $O(n)$.
[ "brute force", "constructive algorithms", "greedy", "math" ]
1,100
#include<bits/stdc++.h> using namespace std; void solve() { auto check = [&](int k) { int j = sqrtl((int64_t)k * (k + 1) / 2); return ((int64_t)j * j != (int64_t)k * (k + 1) / 2); }; int n; cin >> n; if (!check(n)) { cout << "-1\n"; return; } vector<int> ans(n + 1); for (int i = 1; i <= n; i++) { ans[i] = i; } int j = 0; for (int i = 1; i <= n; i++) { while ((int64_t)j * j < (int64_t)i * (i + 1) / 2) j++; if ((int64_t)j * j == (int64_t)i * (i + 1) / 2) { swap(ans[i], ans[i + 1]); } cout << ans[i] << " "; } cout << "\n"; } int main() { ios::sync_with_stdio(0), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solve(); } }
2071
C
Trapmigiano Reggiano
In an Italian village, a hungry mouse starts at vertex $\textrm{st}$ on a given tree$^{\text{∗}}$ with $n$ vertices. Given a permutation $p$ of length $n$$^{\text{†}}$, there are $n$ steps. For the $i$-th step: - A tempting piece of Parmesan cheese appears at vertex $p_i$. If the mouse is currently at vertex $p_i$, it will stay there and enjoy the moment. Otherwise, it will move along the simple path to vertex $p_i$ \textbf{by one edge}. Your task is to find such a permutation so that, after all $n$ steps, the mouse inevitably arrives at vertex $\textrm{en}$, where a trap awaits. Note that the mouse must arrive at $\textrm{en}$ after all $n$ steps, though it may pass through $\textrm{en}$ earlier during the process. \begin{footnotesize} $^{\text{∗}}$A tree is a connected graph without cycles. $^{\text{†}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). \end{footnotesize}
Root the tree at vertex $\textrm{en}$. What observations can you make? Can the cheese be placed at the vertices in a specific sequence that prevents the mouse from moving farther away from vertex $\textrm{en}$? First, root the tree at vertex $\textrm{en}$ and approach it step by step. Observe that after processing all vertices at the largest depth $n-1$, the mouse's current depth cannot exceed $n-1$. By repeating this process for the next largest depth $n-2$, the mouse's depth will inevitably become $n-2$ or less. Continuing this way, we process vertices in descending order of depth until we reach the root, achieving the desired result. The overall time complexity is: $O(n)$.
[ "constructive algorithms", "data structures", "dfs and similar", "dp", "greedy", "sortings", "trees" ]
1,700
#include<bits/stdc++.h> using namespace std; void solve() { int n, s, e; cin >> n >> s >> e; vector adj(n + 1, vector<int> ()); for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; adj[u].push_back(v), adj[v].push_back(u); } vector dis(n + 1, vector<int> ()); vector<int> d(n + 1); auto dfs = [&](auto &&self, int v, int par) -> void { d[v] = d[par] + 1; dis[d[v]].push_back(v); for (int u: adj[v]) { if (u == par) continue; self(self, u, v); } }; dfs(dfs, e, 0); for (int i = n; i >= 1; i--) { for (int j: dis[i]) { cout << j << " "; } } cout << "\n"; } int main() { ios::sync_with_stdio(0), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solve(); } }
2071
D1
Infinite Sequence (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $l=r$. You can hack only if you solved all versions of this problem.} You are given a positive integer $n$ and the first $n$ terms of an infinite binary sequence $a$, which is defined as follows: - For $m>n$, $a_m = a_1 \oplus a_2 \oplus \ldots \oplus a_{\lfloor \frac{m}{2} \rfloor}$$^{\text{∗}}$. Your task is to compute the sum of elements in a given range $[l, r]$: $a_l + a_{l + 1} + \ldots + a_r$. \begin{footnotesize} $^{\text{∗}}$$\oplus$ denotes the bitwise XOR operation. \end{footnotesize}
Try to determine the connection between $a_{2m}$ and $a_{2m+1}$ for indices where $2m > n$. Try to express $a_{2m}$ as the XOR of a short prefix of terms plus at most one extra term. For convenience, assume $n$ is odd (if not, increment $n$ and handle the edge case separately). Start by precomputing the first $2n$ terms $a_1, a_2, \ldots, a_{2n}$. For queries with indices less than or equal to $2n$, directly return the precomputed value. For $2m>n$, observe the following relationship $a_{2m} = a_1 \oplus a_2 \oplus \ldots \oplus a_m = a_{2m + 1}.$ Define $p = a_1 \oplus a_2 \oplus \ldots \oplus a_n$. Notice that when $m > n$, we can decompose the XOR sum as: ${}$ $a_{2m} = a_1 \oplus a_2 \oplus \ldots \oplus a_m = a_1 \oplus a_2 \oplus \ldots \oplus a_n \oplus (a_{n + 1} \oplus a_{n + 2}) \oplus (a_{n + 3} \oplus a_{n + 4}) \oplus \ldots \oplus a_m$ $a_{2m} = p \oplus (a_{n + 1} \oplus a_{n + 2}) \oplus (a_{n + 3} \oplus a_{n + 4}) \oplus \ldots \oplus a_m$ Since $n$ is odd, the pairs $(a_{n + 1} \oplus a_{n + 2}), (a_{n + 3} \oplus a_{n + 4}), \ldots$ cancel out. This simplifies the formula to: ${}$ $a_{2m} = a_{2m + 1} = \begin{cases} p & \text{if } m \text{ is odd}, \\ p \oplus a_m & \text{if } m \text{ is even}. \end{cases}$ As a result, we can compute $a_m$ recursively by halving $m$ until $m \le 2n$, applying the parity rule at each step. The overall time complexity is: $O(n+\log(m))$.
[ "bitmasks", "brute force", "dp", "implementation", "math" ]
1,800
#include<bits/stdc++.h> using namespace std; void solve() { int n; int64_t l, r; cin >> n >> l >> r; vector<int> a(n + 1); for (int i = 1; i <= n; i++) { cin >> a[i]; } vector<int> pref(n + 1); for (int i = 1; i <= n; i++) { pref[i] = pref[i - 1] + a[i]; } if (n % 2 == 0) { n++; int cur = pref[n / 2] & 1; a.push_back(cur); pref.push_back(pref.back() + cur); } for (int i = n + 1; i <= n * 2; i++) { a.push_back(pref[i / 2] & 1); pref.push_back(pref[i - 1] + a[i]); } int p = pref[n] & 1; auto get = [&](int64_t x) { int ret = 0; while (true) { if (x <= n * 2) { ret ^= a[x]; break; } ret ^= p; if ((x / 2 - n) % 2 == 0) { break; } x /= 2; } return ret; }; cout << get(l) << "\n"; } int main() { ios::sync_with_stdio(0), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solve(); } }
2071
D2
Infinite Sequence (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $l\le r$. You can hack only if you solved all versions of this problem.} You are given a positive integer $n$ and the first $n$ terms of an infinite binary sequence $a$, which is defined as follows: - For $m>n$, $a_m = a_1 \oplus a_2 \oplus \ldots \oplus a_{\lfloor \frac{m}{2} \rfloor}$$^{\text{∗}}$. Your task is to compute the sum of elements in a given range $[l, r]$: $a_l + a_{l + 1} + \ldots + a_r$. \begin{footnotesize} $^{\text{∗}}$$\oplus$ denotes the bitwise XOR operation. \end{footnotesize}
Generalize the recursive method for evaluating an index to handle the computation of the prefix sum. First, check the editorial of D1. To upgrade the solution, we define a recursive function: $\text{sum}(m) = \left( \displaystyle\sum_{\substack{i \leq m \\ i \text{ even}}} a_i,\; \displaystyle\sum_{\substack{i \leq m \\ i \text{ odd}}} a_i \right).$ We precompute the even and odd prefix sums for $m \le 2n$. For $m > 2n$, the term $a_m$ follows: ${}$ $a_m = \begin{cases} p & \text{if } \lfloor \frac{m}{2} \rfloor \text{ is odd}, \\ p \oplus a_{\lfloor \frac{m}{2} \rfloor} & \text{if } \lfloor \frac{m}{2} \rfloor \text{ is even}. \end{cases}$ For simplicity, assume $m \equiv 1 \pmod{4}$ (if not, keep incrementing $m$ and adjusting its contribution separately). Define $e = \displaystyle\sum_{\substack{n < i \leq \lfloor \frac{m}{2} \rfloor \\ i \text{ even}}} a_i = a_{n+1} + a_{n+3} + \dots + a_{\lfloor \frac{m}{2} \rfloor}$ This sum can be expressed as: $e = \text{sum}(\lfloor \frac{m}{2} \rfloor)_{\text{even}} - prefix_{\text{even}}(n).$ The pairs we're interested in computing are (keep in mind that $n$ is odd): ${}$ $a_{2n} = a_{2n + 1} = p$ $a_{2n + 2} = a_{2n + 3} = p \oplus a_{n + 1}$ $a_{2n + 4} = a_{2n + 5} = p$ $a_{2n + 6} = a_{2n + 7} = p \oplus a_{n + 3}$ $\vdots$ $a_{m - 3} = a_{m - 2} = p$ $a_{m - 1} = a_{m} = p \oplus a_{\lfloor \frac{m}{2} \rfloor}$ Notice that the sums of the above even and odd indices are equal, and depend on $p$: ${}$ $both = \begin{cases} e & \text{if } p = 0, \\ (\lfloor \frac{m}{2} \rfloor - n + 1) - e & \text{if } p = 1. \end{cases}$ Thus, the final sums are: $\text{sum}(m)_{\text{even}} = prefix_{\text{even}}(2n - 1) + both$ $\text{sum}(m)_{\text{odd}} = prefix_{\text{odd}}(2n - 1) + both$ As a result, we can compute $\text{sum}(m)$ recursively by halving $m$ until $m \le 2n$, benefitting the precomputed even and odd prefix sums at each step. The overall time complexity is: $O(n+\log(m))$.
[ "bitmasks", "brute force", "constructive algorithms", "data structures", "dp", "implementation", "math" ]
2,500
#include<bits/stdc++.h> using namespace std; void solve() { int n; int64_t l, r; cin >> n >> l >> r; vector<int> a(n + 1); for (int i = 1; i <= n; i++) { cin >> a[i]; } vector<int> pref(n + 1); for (int i = 1; i <= n; i++) { pref[i] = pref[i - 1] + a[i]; } if (n % 2 == 0) { n++; int cur = pref[n / 2] & 1; a.push_back(cur); pref.push_back(pref.back() + cur); } for (int i = n + 1; i <= n * 2; i++) { a.push_back(pref[i / 2] & 1); pref.push_back(pref[i - 1] + a[i]); } vector<int> even(n * 2 + 1); for (int i = 1; i <= n * 2; i++) { even[i] = even[i - 1] + (i & 1 ? 0 : a[i]); } int p = pref[n] & 1; auto get = [&](int64_t x) { int ret = 0; while (true) { if (x <= n * 2) { ret ^= a[x]; break; } ret ^= p; if ((x / 2 - n) % 2 == 0) { break; } x /= 2; } return ret; }; auto sum = [&](auto&& self, int64_t m) -> pair<int64_t, int64_t> {// {sum even, sum odd} if (m <= n * 2) { return {even[m], pref[m] - even[m]}; } int64_t eve = even[n * 2 - 1], odd = pref[n * 2 - 1] - eve; if (m % 2 == 0) { m += 1, odd -= get(m); } if (m / 2 % 2) { m += 1, eve -= get(m); m += 1, odd -= get(m); } auto [e, _] = self(self, m / 2); e -= even[n]; int64_t c = m / 2 - n + 1, both = (p ? c - e : e); eve += both, odd += both; return {eve, odd}; }; int64_t ans = 0; auto [re, ro] = sum(sum, r); ans += re + ro; auto [le, lo] = sum(sum, l - 1); ans -= le + lo; cout << ans << "\n"; } int main() { ios::sync_with_stdio(0), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solve(); } }
2071
E
LeaFall
You are given a tree$^{\text{∗}}$ with $n$ vertices. Over time, each vertex $i$ ($1 \le i \le n$) has a probability of $\frac{p_i}{q_i}$ of falling. Determine the expected value of the number of unordered pairs$^{\text{†}}$ of \textbf{distinct} vertices that become leaves$^{\text{‡}}$ in the resulting forest$^{\text{§}}$, modulo $998\,244\,353$. Note that when vertex $v$ falls, it is removed along with all edges connected to it. However, adjacent vertices remain unaffected by the fall of $v$. \begin{footnotesize} $^{\text{∗}}$A tree is a connected graph without cycles. $^{\text{†}}$An unordered pair is a collection of two elements where the order in which the elements appear does not matter. For example, the unordered pair $(1, 2)$ is considered the same as $(2, 1)$. $^{\text{‡}}$A leaf is a vertex that is connected to exactly one edge. $^{\text{§}}$A forest is a graph without cycles \end{footnotesize}
Think about an unordered pair $(u, v)$ where both u and v are leaves in the final forest. Consider dividing all such pairs into separate categories based on their relationship in the original tree. Let the first category be the pairs that are directly connected (neighbors), and analyze under what conditions both vertices become leaves. For the pairs that are not direct neighbors, focus on those that share a common neighbor. Investigate how the state (fallen or not) of their neighbors influences the possibility of both vertices becoming leaves. Let $fall_{i}$ denote the probability that the $i$-th node falls. We partition the unordered pairs $(u,v)$ into three categories: $u$ and $v$ are direct neighbors. $u$ and $v$ share a common neighbor. Pairs that do not satisfy the first two conditions. Now, let us analyze the contribution of the first category to the final answer. For a pair $(u,v)$ of direct neighbors, both vertices become leaves if neither $u$ nor $v$ falls and if all of their other neighbors fall. Thus, the contribution of a specific pair $(u,v)$ is given by: ${}$ $contribution_1(u,v) = (1 - fall_{u}) \cdot (1 - fall_{v}) \cdot \prod_{\substack{k \text{ is a neighbor of } u \text{ or } v,\, k \neq u,\, k \neq v}} fall_{k}.$ The whole contribution of the first category is: ${}$ $\sum_{(u,v) \text{ are neighbors}} contribution_1(u,v).$ For the second category, $u$ and $v$ share a neighbor, so this shared neighbor either must be the only one not falling among the neighbors of $u$ and $v$, or it must fall and exactly one of the other neighbors of both $u$ and $v$ must not fall. Additionally, both $u$ and $v$ must not fall anyway. Therefore, the contribution for a pair $(u,v)$ in the second category is given by: ${}$ $e_i = (\prod_{c \text{ is a neighbor of } i, \, c \neq s} fall_{c}) \cdot (\sum_{c \text{ is a neighbor of } i, \, c \neq s} \frac{1 - fall_{c}}{fall_{c}})$ ${}$ $contribution_2(u,v) = (1 - fall_{u}) \cdot (1 - fall_{v}) \cdot (1 - fall_{s}) \cdot \prod_{\substack{k \text{ is a neighbor of } u \text{ or } v,\, k \neq u,\, k \neq v,\, k \neq s }} fall_{k}$ ${}$ $+ (1 - fall_{u}) \cdot (1 - fall_{v}) \cdot (fall_{s}) \cdot e_u \cdot e_v$ where $s$ is the shared neighbor of $u$ and $v$. The whole contribution of the second category is: ${}$ $\sum_{(u,v) \text{ share a neighbor}} contribution_2(u,v).$ Moving to the third category: Here, $u$ and $v$ are neither direct neighbors nor do they share any common neighbor. In this case, the events that $u$ and $v$ become leaves are completely independent. Define $leaf_{i} = (1 - fall_{i}) \cdot (\prod_{c \text{ is a neighbor of } i} fall_{c}) \cdot (\sum_{c \text{ is a neighbor of } i} \frac{1 - fall_{c}}{fall_{c}})$ as the probability that vertex $i$ becomes a leaf. Hence, for a pair $(u,v)$ in this category, the contribution is given by: ${}$ $contribution_3(u,v) = leaf_{u} \cdot leaf_{v}.$ The whole contribution of the third category is: ${}$ $\sum_{(u,v) \in \text{third category}} contribution_3(u,v).$ The final answer is obtained by summing the contributions from all three categories. We can compute the contribution of the third category by summing $leaf_{i} \cdot leaf_{j}$ for all pairs $(i, j)$ with $i < j$, and then subtracting the contributions corresponding to pairs that satisfy one of the first two categories. The contribution of the second category can be computed by iterating over each node and accumulating the contributions from its neighbors (since these pairs share that node as their only common neighbor). The contribution of the first category can be computed in linear time too. The overall time complexity is $O(n \cdot \log M)$, where the $\log$ factor arises from the modular inverse computations.
[ "combinatorics", "dp", "probabilities", "trees" ]
2,600
#include<bits/stdc++.h> using namespace std; const int mod = 998244353; int add(int x, int y) { return x + y - (x + y >= mod) * mod; } void add2(int &x, int y) { x += y; if (x >= mod) x -= mod; } int mul(int x, int y) { return int((int64_t)x * y % mod); } int sub(int x, int y) { return x - y + (x < y) * mod; } void sub2(int &x, int y) { x -= y; if (x < 0) x += mod; } int pwr(int x, int y) { int ret = 1; while (y) { if (y & 1) ret = mul(ret, x); x = mul(x, x); y /= 2; } return ret; } int inv(int x) { return pwr(x, mod - 2); } int norm(int64_t x) { x %= mod; if (x < 0) x += mod; return int(x); } void solve() { int n; cin >> n; vector adj(n + 1, vector<int> ()); vector<int> p(n + 1); for (int i = 1; i <= n; i++) { int q; cin >> p[i] >> q; p[i] = mul(p[i], inv(q)); //here, p[i] is the probability that node i will fall } for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; adj[u].push_back(v), adj[v].push_back(u); } vector<int> p1(n + 1), p2(n + 1); for (int i = 1; i <= n; i++) { p1[i] = sub(1, p[i]); for (int u: adj[i]) { p1[i] = mul(p1[i], p[u]); } //p1[i] is the probability that node i won't fall, but all nodes around it will fall for (int u: adj[i]) { add2(p2[i], mul(p1[i], mul(inv(p[u]), sub(1, p[u])))); } //p2[i] is the probability that node i will be a leaf (it won't fall, all it's neighbors except one will fall) } int ans = 0, sum = 0; for (int i = 1; i <= n; i++) { add2(ans, mul(p2[i], sum)); add2(sum, p2[i]); } //take all contributions of unordered pairs for (int i = 1; i <= n; i++) { //recalculate the contribution of neighboring pairs for (auto u: adj[i]) { if (u < i) continue; //avoid calculating the same pair probabilty twice int pi = mul(p1[i], inv(p[u])); //pi is the probability that every neighbour of i would fall except for u (not including the probability of u not falling down) int pu = mul(p1[u], inv(p[i])); //pu is the probability that every neighbour of u would fall except for i (not including the probability of i not falling down) //this case is just a tree of 2 nodes, both of them are leaves add2(ans, mul(pi, pu)); //subtract the old contribution sub2(ans, mul(p2[i], p2[u])); } //recalculate the contribution of pairs with a shared neighbour which is node i (ie calculate the contribution for pairs u, v such that dis(u, v) = 2 and dis(u, i) = dis(v, i) = 1 sum = 0; for (int u: adj[i]) { sub2(ans, mul(sum, p2[u])); add2(sum, p2[u]); //subtract the old contribution } //p[i] doesn't fall sum = 0; for (int u: adj[i]) { int pu = mul(p1[u], inv(p[i])); //pu is the probability that node u is a leaf connected to node i add2(ans, mul(sum, pu)); add2(sum, mul(pu, sub(1, p[i]))); } //p[i] falls sum = 0; for (int u: adj[i]) { int pu = sub(p2[u], mul(p1[u], mul(inv(p[i]), sub(1, p[i])))); //pu is the probability that node u is a leaf not connected to node i add2(ans, mul(sum, pu)); add2(sum, mul(pu, inv(p[i]))); } } cout << ans << "\n"; } int main() { ios::sync_with_stdio(0), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solve(); } }
2071
F
Towering Arrays
An array $b = [b_1, b_2, \ldots, b_m]$ of length $m$ is called $p$-towering if there exists an index $i$ ($1\le i\le m$) such that for every index $j$ ($1 \le j \le m$), the following condition holds: $$b_j \ge p - |i - j|.$$ Given an array $a = [a_1, a_2, \ldots, a_n]$ of length $n$, you can remove at most $k$ elements from it. Determine the maximum value of $p$ for which the remaining array can be made $p$-towering.
Binary search on $p$. After fixing $p$, find the maximum $p$-towering subsequence. if we denote the set of indexes that correspond to the maximum "increasing" $p$-towering subsequence on prefix $i$ as $S_i$, then for any $i < n$: $S_i \subseteq S_{i + 1}$. Let's do binary search on $p$. After fixing some $p$ our goal is to find the maximum $p$-towering subsequence and check if the length of that subsequence $s$ satisfies $n - s \le k$. To find the maximum $p$-towering subsequence, for each index $i$ we will find the maximum $p$-towering subsequence such that the "left" part of that subsequence is in prefix $i$ and its right part is in suffix $i$. Let's focus only on prefixes, as the suffixes can be done similarly. So, for each prefix $i$ we want to find the maximum "increasing" $p$-towering subsequence. To do it, we will traverse the array from left to right and maintain the currently found maximum subsequence. The key idea here is that as you move from left to right you only need to add new elements to the "increasing" subsequence and never delete any (or, formally speaking, if we denote the set of indexes that correspond to maximum "increasing" $p$-towering subsequence on prefix $i$ as $S_i$, then for any $i < n$: $S_i \subseteq S_{i + 1}$ (the proof is left to the reader). Before moving to the details of implementation, let's elaborate a bit on the previous paragraph. Consider the fifth test case from the sample; suppose the current $p = 7$; and we have just arrived at the tenth element (denoted with star $^*$). Before this position, the maximum "increasing" $p$-towering subsequence consists of the first, third, and fifth elements (denoted with underlines): $[\underline{6}, 3, \underline{8}, 5, \underline{8}, 3, 2, 1, 2, 7^*, 1]$. Now we need to check if we can increase the size of the subsequence. Since $p = 7$, then we certainly can add the tenth element with value $7$ to the subsequence. However, since we add a new number to the subsequence, two numbers become available: the second one with value $3$ and the forth one with value $5$. Thus, after processing the tenth element, the maximum "increasing" $p$-towering subsequence will look like this: $[\underline{6}, \color{red}{\underline{3}}, \underline{8}, \color{red}{\underline{5}}, \underline{8}, 3, 2, 1, 2, \color{red}{\underline{7}}^*, 1]$. So we need some way to find such "new" numbers that appear when we add some elements to the subsequence (like when the element with value $5$ becomes available from the example). To resolve this we first assign $a_i := p - a_i$ for each $i$. To find the positions that are becoming available, we can search for the rightmost non-positive element on the current prefix. Once found (suppose its index is $j$), decrease all elements on the prefix $j$ by one and assign $a_j := \infty$ (to avoid this position in the future). All these operations can be performed with the help of a segment tree. This concludes the asymptotic complexity: $O(n \log{C} \log{n})$.
[ "binary search", "data structures" ]
2,700
#include <bits/stdc++.h> #define len(a) (int)a.size() #define all(a) a.begin(), a.end() using namespace std; const int MAXI = 1e9 + 1e7; const int MAXN = 2e5 + 100; struct Node { int min_on_subtree = 0, push_addition = 0; }; Node t[MAXN * 4]; int a[MAXN], pref[MAXN], suf[MAXN]; class Segtree { private: int n; void add_on_subtree(int u, int val) { t[u].push_addition += val; t[u].min_on_subtree += val; } void push(int u) { if (t[u].push_addition) { add_on_subtree(u * 2 + 1, t[u].push_addition); add_on_subtree(u * 2 + 2, t[u].push_addition); t[u].push_addition = 0; } } void recalc(int u) { t[u].min_on_subtree = min(t[u * 2 + 1].min_on_subtree, t[u * 2 + 2].min_on_subtree); } void update(int u, int l, int r, int pos, int val) { if (l == r) { t[u].min_on_subtree = val; } else { push(u); int mid = (l + r) / 2; if (pos <= mid) update(u * 2 + 1, l, mid, pos, val); else update(u * 2 + 2, mid + 1, r, pos, val); recalc(u); } } void add_on_segment(int u, int l, int r, int ql, int qr, int val) { if (ql <= l && r <= qr) add_on_subtree(u, val); else { push(u); int mid = (l + r) / 2; if (ql <= mid) add_on_segment(u * 2 + 1, l, mid, ql, qr, val); if (qr > mid) add_on_segment(u * 2 + 2, mid + 1, r, ql, qr, val); recalc(u); } } int find_prev_non_pos_put_inf(int u, int l, int r, int pos) { if (t[u].min_on_subtree > 0) return -1; if (l == r) { t[u].min_on_subtree = MAXI; return l; } push(u); int mid = (l + r) / 2, res = -1; if (pos > mid) res = find_prev_non_pos_put_inf(u * 2 + 2, mid + 1, r, pos); if (res == -1) res = find_prev_non_pos_put_inf(u * 2 + 1, l, mid, pos); recalc(u); return res; } public: explicit Segtree(int n): n(n) { fill(t, t + 4 * n, Node{MAXI, 0}); }; void update(int pos, int val) { update(0, 0, n - 1, pos, val); } void add_on_segment(int ql, int qr, int val) { add_on_segment(0, 0, n - 1, ql, qr, val); } int find_prev_non_pos_put_inf(int pos) { return find_prev_non_pos_put_inf(0, 0, n - 1, pos); } }; void f(int n, int p, int *res) { Segtree tree(n); int cur_sz = 0; for (int i = 0; i < n; i++) { tree.update(i, p - a[i]); int pos = i; while ((pos = tree.find_prev_non_pos_put_inf(pos)) != -1) { cur_sz++; tree.add_on_segment(0, pos, -1); } res[i] = cur_sz; } } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int testcases; cin >> testcases; while (testcases--) { int n, k; cin >> n >> k; int max_a = -1; for (int i = 0; i < n; i++) { cin >> a[i]; max_a = max(max_a, a[i]); } int l = 0, r = max_a + 1; while (l + 1 < r) { int mid = (l + r) / 2; f(n, mid, pref); reverse(a, a + n); f(n, mid, suf); reverse(a, a + n); reverse(suf, suf + n); int mx = -1; for (int i = 0; i < n; i++) { if (a[i] >= mid) mx = max(mx, pref[i] + suf[i] - 1); } if (n - mx <= k) l = mid; else r = mid; } cout << l << '\n'; } }
2072
A
New World, New Me, New Array
Natsume Akito has just woken up in a new world and immediately received his first quest! The system provided him with an array $a$ of $n$ zeros, an integer $k$, and an integer $p$. In one operation, Akito chooses two integers $i$ and $x$ such that $1 \le i \le n$ and $-p \le x \le p$, and performs the assignment $a_i = x$. Akito is still not fully accustomed to controlling his new body, so help him calculate the minimum number of operations required to make the sum of all elements in the array equal to $k$, or tell him that it is impossible.
In an array $a$ of length $n$ containing numbers from $-p$ to $p$ inclusive, any sum $k$ in the range $[-p \cdot n; p \cdot n]$ is achievable. We will present an algorithm that constructs an array with a given sum $k$ within this range. We will construct the array for $k \ge 0$, as the problem for $k$ and $-k$ is equivalent. Let the current sum in the array be $s = 0$. At the current step, if $s + p < k$, we will find any index $i$ such that $a_i = 0$ and assign $p$ to $a_i$, updating $s$ to $s + p$. Otherwise, if $k - s \le p$, we can assign $k - s$ to any $a_i = 0$ in one operation and finish the algorithm. In fact, this algorithm is optimal for this problem. Let's determine how many operations will be performed. $\left\lfloor \frac{k}{p} \right\rfloor$ operations will be spent assigning the number $p$. If $k - \left\lfloor \frac{k}{p} \right\rfloor \cdot p > 0$, then one more operation will be performed, which is only possible if $k$ is not divisible by $p$. This means that the number of operations will be equal to $\left\lceil \frac{k}{p} \right\rceil = \left\lfloor \frac{k + p - 1}{p} \right\rfloor$ operations, which is the answer to the problem. Asymptotic complexity: $\mathcal{O}(1)$.
[ "greedy", "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n, k, p; cin >> n >> k >> p; if (-n * p <= k && k <= n * p) { cout << (abs(k) + p - 1) / p << '\n'; } else { cout << "-1\n"; } } int main() { int tt; cin >> tt; while (tt --> 0) { solve(); } return 0; }
2072
B
Having Been a Treasurer in the Past, I Help Goblins Deceive
After completing the first quest, Akito left the starting cave. After a while, he stumbled upon a goblin village. Since Akito had nowhere to live, he wanted to find out the price of housing. It is well known that goblins write numbers as a string of characters '-' and '_', and the value represented by the string $s$ is the number of distinct subsequences$^{\text{∗}}$ of the string $s$ that are equal to the string "-_-" (this is very similar to goblin faces). For example, the string $s=$"-_--_-" represents the number $6$, as it has $6$ subsequences "-_-": - $s_1+s_2+s_3$ - $s_1+s_2+s_4$ - $s_1+s_2+s_6$ - $s_1+s_5+s_6$ - $s_3+s_5+s_6$ - $s_4+s_5+s_6$ Initially, the goblins wrote a random string-number $s$ in response to Akito's question, but then they realized that they wanted to take as much gold as possible from the traveler. To do this, they ask you to rearrange the characters in the string $s$ so that the value of the number represented by the string $s$ is maximized. \begin{footnotesize} $^{\text{∗}}$A subsequence of a string $a$ is a string $b$ that can be obtained by deleting several (possibly $0$) characters from $a$. Subsequences are considered different if they are obtained by deleting different sets of indices. \end{footnotesize}
For $n \le 2$ or when the number of $i$ such that $s_i =$ '-' is less than two or there are no indices $i$ where $s_i =$ '_', the answer will be $0$. Otherwise, let's solve the problem if there is only one symbol '_' in the string. It is easy to see that the string will look like a prefix of length $\ell_p$ made of '-', a single symbol '_', and a suffix of length $\ell_s$ made of the remaining '-'. Then the number of subsequences is equal to $\ell_p \cdot \ell_s$. The sum $\ell_p + \ell_s$ is fixed and equals the number of '-' symbols in the string, let's call this number $c$. It is straightforward to show that the optimal $\ell_p = \left\lfloor \frac{c}{2} \right\rfloor$, and the optimal $\ell_s = \left\lceil \frac{c}{2} \right\rceil$. Now let's return to the original problem. In fact, the solution above is also optimal for it! The string will still consist of a prefix of length $\ell_p$ made of '-', a suffix of length $\ell_s$ made of '-', and $(n - c)$ symbols '_' in the middle. $(n - c)$ is constant, which means we need to maximize the product $\ell_p \cdot \ell_s$, and we already know how to do that. Thus, the answer is simply $\left\lfloor \frac{c}{2} \right\rfloor \cdot \left\lceil \frac{c}{2} \right\rceil \cdot (n - c)$. Asymptotic complexity: $\mathcal{O}(n)$.
[ "combinatorics", "constructive algorithms", "strings" ]
900
#include <bits/stdc++.h> using namespace std; void solve() { int n; string s; cin >> n >> s; int64_t dash = count(s.begin(), s.end(), '-'); int64_t under = n - dash; int64_t ans = (dash / 2) * (dash - dash / 2) * under; cout << ans << '\n'; } int main() { int tt; cin >> tt; while (tt --> 0) { solve(); } return 0; }
2072
C
Creating Keys for StORages Has Become My Main Skill
Akito still has nowhere to live, and the price for a small room is everywhere. For this reason, Akito decided to get a job at a bank as a key creator for storages. In this magical world, everything is different. For example, the key for a storage with the code $(n, x)$ is an array $a$ of length $n$ such that: - $a_1 \ | \ a_2 \ | \ a_3 \ | \ \ldots \ | \ a_n = x$, where $a \ | \ b$ is the bitwise "OR" of numbers $a$ and $b$. - $\text{MEX}(\{ a_1, a_2, a_3, \ldots, a_n \})$$^{\text{∗}}$ is maximized among all such arrays. Akito diligently performed his job for several hours, but suddenly he got a headache. Substitute for him for an hour; for the given $n$ and $x$, create any key for the storage with the code $(n, x)$. \begin{footnotesize} $^{\text{∗}}$$\text{MEX}(S)$ is the minimum non-negative integer $z$ such that $z$ is not contained in the set $S$ and all $0 \le y < z$ are contained in $S$. \end{footnotesize}
In problems involving $\text{MEX}$, a common idea is its greedy maximization. This problem is no exception. Note that $a\ |\ b \ge \max(a, b)$. We will iterate through the number $m$ from $0$ to $\min(n - 1, x)$. We will also keep a number $v$ initially set to $0$. When processing the current $m$, we check that $v\ |\ m$ has only those bits set that are set in the number $x$. If this is the case, we assign $m$ to $a_{m + 1}$, update $v$ to $v\ |\ m$, and proceed to check the next $m$. If this is not the case, we exit the loop. Finally, we need to check if the current bitwise OR of the array equals the number $x$. If so, we immediately output this array. Otherwise, we assign the number $x$ to $a_n$. Asymptotic complexity: $\mathcal{O}(n)$.
[ "bitmasks", "constructive algorithms", "greedy" ]
1,200
#include <iostream> #include <vector> using namespace std; void Solve() { int len, val; cin >> len >> val; vector<int> ans(len, val); int or_val = 0; bool flag = true; for (int i = 0; i < len - 1; ++i) { if (((or_val | i) & val) == (or_val | i)) { or_val |= i; ans[i] = i; } else { flag = false; break; } } if (flag && (or_val | (len - 1)) == val) { ans[len - 1] = len - 1; } for (auto it : ans) cout << it << ' '; cout << '\n'; } signed main() { cin.tie(0)->sync_with_stdio(0); int test_count = 1; cin >> test_count; while (test_count --> 0) Solve(); }
2072
D
For Wizards, the Exam Is Easy, but I Couldn't Handle It
Akito got tired of being a simple locksmith at a bank, so he decided to enroll in the Magical Academy and become the best wizard in the world! However, to enroll, he needed to solve a single problem on the exam, which the ambitious hero could not manage. In the problem, he was given an array $a$ of length $n$. He needed to minimize the number of inversions$^{\text{∗}}$ in the array after applying the spell \textbf{exactly once}. The spell was simple; to apply it, Akito had to choose two numbers $l$ and $r$ such that $1 \le l \le r \le n$ and perform a cyclic shift of the subarray from $l$ to $r$ one position to the left. More formally, Akito selects the subarray $[l, r]$ and modifies the array as follows: - From the original array $[a_1, a_2, \ldots, a_{l - 1}, \mathbf{ a_l }, \mathbf{ a_{l + 1} } , \mathbf{ \ldots }, \mathbf{ a_{r - 1} }, \mathbf{ a_r }, a_{r + 1}, \ldots, a_{n - 1}, a_n]$, he obtains the array $[a_1, a_2, \ldots, a_{l - 1}, \mathbf{ a_{l + 1} }, \mathbf{ a_{l + 2} }, \mathbf{ \ldots }, \mathbf{ a_{r - 1} }, \mathbf{ a_{r} }, \mathbf{ a_{l} }, a_{r + 1}, \ldots, a_{n - 1}, a_{n}]$. Akito is eager to start his studies, but he still hasn't passed the exam. Help him enroll and solve the problem! \begin{footnotesize} $^{\text{∗}}$An inversion in an array $b$ of length $m$ is defined as a pair of indices $(i, j)$ such that $1 \le i < j \le m$ and $b_i > b_j$. For example, in the array $b = [3, 1, 4, 1, 5]$, the inversions are the pairs of indices $(1, 2)$, $(1, 4)$, $(3, 4)$. \end{footnotesize}
In fact, a cyclic shift of the subarray $[l, r]$ to the left by $1$ is the same as removing the element $a_l$ from the array and then inserting it after the $r$-th element. This means that we can move the number $a_i$ to any position $j \ge i$. Let's see how the number of inversions in the array changes with the operation on the segment $[l, r]$. Inversions with indices from $[1, l - 1]$ and $[r + 1, n]$ will remain in the array, and any pair that forms an inversion will stay in the same relative order as in the original array. Thus, we are interested in the inversions with indices from the segment $[l, r]$. Since only the position of the number $a_l$ changes, we can remove inversions of the form $(l, i)$, where $l < i \le r$ (let's call these first-type inversions), and add inversions of the form $(i, l)$, where $l < i \le r$ (let's call these second-type inversions). The number of first-type inversions is equal to the number of $i$ such that $l < i \le r$ and $a_l > a_i$, let's denote this count as $c_1$. Similarly, the number of second-type inversions is equal to the number of $i$ such that $l < i \le r$ and $a_l < a_i$, let's denote this count as $c_2$. Then the new number of inversions in the array will change by $c_2 - c_1$. It remains to find a subarray of $a$ with the minimal difference $c_2 - c_1$, which can be done using prefix sums for the count of each $a_i$ from $1$ to $2000$ or by simply iterating over the left boundary and traversing the suffix (see the author's solution). Asymptotic complexity: $\mathcal{O}(n^2)$.
[ "brute force", "greedy", "implementation" ]
1,300
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } int best_diff = 0, L = 0, R = 0; for (int i = 0; i < n; ++i) { int cnt_greater = 0, cnt_less = 0; for (int j = i + 1; j < n; ++j) { cnt_greater += a[j] > a[i]; cnt_less += a[j] < a[i]; if (best_diff > cnt_greater - cnt_less) { best_diff = cnt_greater - cnt_less; L = i, R = j; } } } cout << L + 1 << ' ' << R + 1 << '\n'; } int main() { int tt = 1; cin >> tt; while (tt --> 0) { solve(); } return 0; }
2072
E
Do You Love Your Hero and His Two-Hit Multi-Target Attacks?
Akito decided to study a new powerful spell. Since it possesses immeasurable strength, it certainly requires a lot of space and careful preparation. For this, Akito went out into the field. Let's represent the field as a Cartesian coordinate system. For the spell, Akito needs to place $0 \le n \le 500$ staffs at \textbf{distinct integer coordinates} in the field such that there will be \textbf{exactly $k$ pairs} $(i, j)$ such that $1 \le i < j \le n$ and $\rho(i, j) = d(i, j)$. Here, for two points with integer coordinates $a = (x_a, y_a)$ and $b = (x_b, y_b)$, $\rho(a, b) = \sqrt{(x_a - x_b)^2 + (y_a - y_b)^2}$ and $d(a, b) = |x_a - x_b| + |y_a - y_b|$.
After playing a bit with the formulas $\rho(a, b)$ and $d(a, b)$, we can derive that $\rho(a, b) = d(a, b)$ if $x_a = x_b$ or $y_a = y_b$. Let us define a recursive function $f(k, x_0, y_0)$ that returns a set of sticks $P$ such that there are exactly $k$ unordered pairs that satisfy the condition, given that for all sticks $p \in P$, $x_p \ge x_0$ and $y_p \ge y_0$. If $k = 0$, the function will return an empty set. For $k > 0$, we find the maximum $m$ such that $\frac{m(m - 1)}{2} \le k$. Next, we add the sticks $(x_0, y_0), (x_0 + 1, y_0), \ldots, (x_0 + m - 1, y_0)$ to the set $P$. Note that any pair from this set satisfies the condition, and thus there are exactly $\frac{m(m - 1)}{2}$ such pairs. We then combine the current set $P$ with the set $f(k - \frac{m(m - 1)}{2}, x_0 + m, y_0 + 1)$. This will yield the set of sticks that meets the problem's requirements. We will prove that there will be no more than $500$ points. Let $g(x) = \frac{x(x - 1)}{2}$. In fact, the value $k - g(m) \le 446$, since $g(x + 1) - g(x) = \frac{x(x + 1)}{2} - \frac{x(x - 1)}{2} = \frac{x}{2}(x + 1 - x + 1) = x$, and the maximum value of $g(x) \le 10^5$ is $g(447)$, which means the maximum value of $g(x + 1) - g(x) = 446$. For $k \le 446$, the algorithm places no more than 43 sticks; for $k = g(x)$, the algorithm will place $x$ sticks, thus the maximum number of sticks will be $447 + 43 = 490 \le 500$. Asymptotic complexity: $\mathcal{O}(\sqrt{k})$.
[ "binary search", "brute force", "constructive algorithms", "dp", "geometry", "greedy", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; vector<pair<int64_t, int64_t>> rec(int64_t k, int64_t x0 = 0, int64_t y0 = 0) { if (!k) { return {}; } int64_t delta = 0; while (delta * (delta - 1) / 2 <= k) { delta++; } delta--; auto remaining = rec(k - delta * (delta - 1) / 2, x0 + delta + 1, y0 + 1); vector<pair<int64_t, int64_t>> ans; for (int x = x0; x < x0 + delta; ++x) { ans.push_back({x, y0}); } ans.insert(ans.end(), remaining.begin(), remaining.end()); return ans; } void solve() { int64_t k; cin >> k; if (!k) { cout << "1\n69 52\n"; return; } auto ans = rec(k, 0, 0); cout << ans.size() << '\n'; for (auto [x, y] : ans) { cout << x << ' ' << y << '\n'; } } int main() { int tt = 1; cin >> tt; while (tt --> 0) { solve(); } return 0; }
2072
F
Goodbye, Banker Life
Monsters are approaching the city, and to protect it, Akito must create a protective field around the city. As everyone knows, protective fields come in various levels. Akito has chosen the field of level $n$. To construct the field, a special phrase is required, which is the $n$-th row of the Great Magical Triangle, represented as a two-dimensional array. We will call this array $T$. The triangle is defined as follows: - In the $i$-th row, there are $i$ integers. - The single integer in the first row is $k$. - Let the $j$-th element of the $i$-th row be denoted as $T_{i,j}$. Then $$T_{i,j} = \begin{cases} T_{i-1,j-1} \oplus T_{i-1,j}, &\textrm{if } 1 < j < i \\ T_{i-1,j}, &\textrm{if } j = 1 \\ T_{i-1,j-1}, &\textrm{if } j = i \end{cases}$$ where $a \oplus b$ is the bitwise exclusive "OR"(XOR) of the integers $a$ and $b$.Help Akito find the integers in the $n$-th row of the infinite triangle before the monsters reach the city.
Since the value of the $i$-th bit in $a \oplus b$ depends only on the $i$-th bits of the numbers $a$ and $b$, we can solve the problem separately for each bit. Let $a_i$ be the $i$-th bit of the number $a$. If $k_i = 0$, then the triangle for the $i$-th bit will consist only of $0$s. If $k_i = 1$, then since $\oplus$ is the bitwise addition modulo $2$, we simply obtain Pascal's Triangle, where all values are taken modulo $2$. Now the problem has reduced to finding $\binom{n}{r} \mod 2$. $\binom{n}{r} = \frac{n!}{r! \cdot (n - r)!}$, which means the parity of $\binom{n}{r}$ depends on the power of $2$ in $n!$, $r!$, and $(n - r)!$. Let $c_n$ be the power of $2$ in $n!$. $\binom{n}{r}$ will be odd if and only if $c_n = c_r + c_{n - r}$. It remains to learn how to find the power of $2$ in $n!$. We have $c_0 = c_1 = 0$, and $c_n = c_{n - 1} + f(n)$, where $f(n)$ is the maximum $m$ such that $2^m | n$. Asymptotic complexity: $\mathcal{O}(N \log N)$ for preprocessing and $\mathcal{O}(n)$. Here, $N$ denotes the maximum possible $n$.
[ "2-sat", "bitmasks", "combinatorics", "constructive algorithms", "fft", "math", "number theory" ]
1,700
#include <bits/stdc++.h> using namespace std; constexpr int64_t kMaxN = 1e6 + 69; vector<int64_t> c(kMaxN); void precalc() { c[0] = c[1] = 0; for (int i = 2; i < kMaxN; ++i) { c[i] = c[i - 1]; int x = i; while (x % 2 == 0) { x /= 2, c[i]++; } } } void solve() { int n, k; cin >> n >> k; --n; for (int i = 0; i <= n; ++i) { cout << k * (c[n] == c[i] + c[n - i]) << " \n"[i == n]; } } int main() { ios::sync_with_stdio(0); cin.tie(0); precalc(); int tt = 1; cin >> tt; while (tt --> 0) { solve(); } return 0; }
2072
G
I've Been Flipping Numbers for 300 Years and Calculated the Sum
After three hundred years of slime farming, Akito finally obtained the magical number $n$. Upon reaching the merchant, he wanted to exchange the number for gold, but the merchant gave the hero a quest. The merchant said that for the quest, the skill $\text{rev}(n, p)$ would be required, which Akito, by happy coincidence, had recently learned. $\text{rev}(n, p)$ represents the following procedure: - Write the number $n$ in base $p$, let this representation be $n = \overline{n_{\ell - 1} \ldots n_1 n_0}$, where $\ell$ is the length of the base $p$ representation of the number $n$. - Reverse the base $p$ representation, let this be $m = \overline{n_0 n_1 \ldots n_{\ell - 1}}$. - Convert the number $m$ back to decimal and return it as the result. The merchant's quest was to calculate the sum $x = \sum\limits_{p = 2}^{k} \text{rev}(n, p)$. Since this number can be quite large, only the remainder of $x$ when divided by $10^9 + 7$ is required. The merchant also mentioned that the previous traveler had been calculating this sum for three hundred years and had not finished it. But you will help Akito finish it faster, right?
Let's consider three cases: $2 \le p \le \sqrt{n}$. We calculate for each of the $\mathcal{O}(\sqrt{n})$ values of $p$ in $\mathcal{O}(\log n)$. One could think that it takes $\mathcal{O}(\sqrt{n} \log{n})$ time, but it actually takes $\mathcal{O}(\sqrt{n})$ time! Read this comment for explanation. $n < p \le k$. For each such $p$, $\text{rev}(n, p) = n$, and their count is $k - n$. Thus, the sum for them is $(k - n) \cdot n$. This takes $O(1)$ for the calculation. $\sqrt{n} < p \le n$. We note that $\log_p{n} \le \log_{\sqrt{n}}{n} = \frac{\log{n}}{\log{\sqrt{n}}} = \frac{\log{n}}{\log{n^{ \frac{1}{2} }}} = 2 \cdot \frac{\log{n}}{\log{n}} = 2$. Thus, the length of the base $p$ representation of the number $n$ is 2.Let's consider some $p$ from this range. Let $n = \overline{n_1 n_0} = n_1 \cdot p + n_0$. It is easy to show that $n_0 = (n \text{ mod } p)$, and $n_1 = \left\lfloor \frac{n}{p} \right\rfloor$. We find the value $\text{rev}(n, p) = n_0 \cdot p + n_1 = p \cdot (n \text{ mod } p) + \left\lfloor \frac{n}{p} \right\rfloor$, so the entire sum looks like this: $\sum\limits_{p = \sqrt{n} + 1}^{n} (p \cdot (n \text{ mod } p) + \left\lfloor \frac{n}{p} \right\rfloor) = \sum\limits_{p = \sqrt{n} + 1}^{n} p \cdot (n \text{ mod } p) + \sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor$ which in turn equals $\sum\limits_{p = \sqrt{n} + 1}^{n} p \cdot (n - \left\lfloor \frac{n}{p} \right\rfloor \cdot p) + \sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor = \sum\limits_{p = \sqrt{n} + 1}^{n} pn - \sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor \cdot p^2 + \sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor$ We will calculate all three sums separately. $\sum\limits_{p = \sqrt{n} + 1}^{n} pn = n \sum\limits_{p = \sqrt{n} + 1}^{n} p$. The sum is simply the sum of an arithmetic progression multiplied by $n$. This takes $\mathcal{O}(1)$ for the calculation. For the remaining sums, we need to note the following fact. The number of distinct values of $\left\lfloor \frac{n}{i} \right\rfloor$ is $\le 2\sqrt{n}$. The proof is quite simple: Consider two cases: $i \le \sqrt{n}$ - the number of numbers we divide by is equal to the square root, so we cannot get more than $\sqrt{n}$ distinct values. $i > \sqrt{n}$ - if $i > \sqrt{n}$, then $\left\lfloor \frac{n}{i} \right\rfloor \le \sqrt{n}$, so there are also no more than $\sqrt{n}$ such values. In total, we find that the number of distinct values is $\sqrt{n} + \sqrt{n} = 2\sqrt{n}$ q. e. d.To calculate $\sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor$, we will explicitly iterate over the value $x = \left\lfloor \frac{n}{p} \right\rfloor$ and find such $l, r$ that all numbers from $l$ to $r$ give the value $x$ and we will sum $x \cdot (r - l + 1)$. This takes $\mathcal{O}(\sqrt{n})$ for the calculation. To calculate $\sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor \cdot p^2$, we will do exactly the same as in the previous sum, but now $x$ will have to be multiplied by the sum of squares of numbers from $l$ to $r$. This also takes $\mathcal{O}(\sqrt{n})$ for the calculation. Thus, in total, the third case takes $\mathcal{O}(1) + \mathcal{O}(\sqrt{n}) + \mathcal{O}(\sqrt{n}) = \mathcal{O}(\sqrt{n})$. Let's consider some $p$ from this range. Let $n = \overline{n_1 n_0} = n_1 \cdot p + n_0$. It is easy to show that $n_0 = (n \text{ mod } p)$, and $n_1 = \left\lfloor \frac{n}{p} \right\rfloor$. We find the value $\text{rev}(n, p) = n_0 \cdot p + n_1 = p \cdot (n \text{ mod } p) + \left\lfloor \frac{n}{p} \right\rfloor$, so the entire sum looks like this: $\sum\limits_{p = \sqrt{n} + 1}^{n} (p \cdot (n \text{ mod } p) + \left\lfloor \frac{n}{p} \right\rfloor) = \sum\limits_{p = \sqrt{n} + 1}^{n} p \cdot (n \text{ mod } p) + \sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor$ which in turn equals $\sum\limits_{p = \sqrt{n} + 1}^{n} p \cdot (n - \left\lfloor \frac{n}{p} \right\rfloor \cdot p) + \sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor = \sum\limits_{p = \sqrt{n} + 1}^{n} pn - \sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor \cdot p^2 + \sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor$ We will calculate all three sums separately. $\sum\limits_{p = \sqrt{n} + 1}^{n} pn = n \sum\limits_{p = \sqrt{n} + 1}^{n} p$. The sum is simply the sum of an arithmetic progression multiplied by $n$. This takes $\mathcal{O}(1)$ for the calculation. For the remaining sums, we need to note the following fact. The number of distinct values of $\left\lfloor \frac{n}{i} \right\rfloor$ is $\le 2\sqrt{n}$. The proof is quite simple: Consider two cases: $i \le \sqrt{n}$ - the number of numbers we divide by is equal to the square root, so we cannot get more than $\sqrt{n}$ distinct values. $i > \sqrt{n}$ - if $i > \sqrt{n}$, then $\left\lfloor \frac{n}{i} \right\rfloor \le \sqrt{n}$, so there are also no more than $\sqrt{n}$ such values. To calculate $\sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor$, we will explicitly iterate over the value $x = \left\lfloor \frac{n}{p} \right\rfloor$ and find such $l, r$ that all numbers from $l$ to $r$ give the value $x$ and we will sum $x \cdot (r - l + 1)$. This takes $\mathcal{O}(\sqrt{n})$ for the calculation. To calculate $\sum\limits_{p = \sqrt{n} + 1}^{n} \left\lfloor \frac{n}{p} \right\rfloor \cdot p^2$, we will do exactly the same as in the previous sum, but now $x$ will have to be multiplied by the sum of squares of numbers from $l$ to $r$. This also takes $\mathcal{O}(\sqrt{n})$ for the calculation. Thus, in total, the third case takes $\mathcal{O}(1) + \mathcal{O}(\sqrt{n}) + \mathcal{O}(\sqrt{n}) = \mathcal{O}(\sqrt{n})$. Final asymptotic complexity: $\mathcal{O}(\sqrt{n}) + \mathcal{O}(1) + \mathcal{O}(\sqrt{n}) = \mathcal{O}(\sqrt{n} + \sqrt{n}) = \mathcal{O}(\sqrt{n})$
[ "binary search", "brute force", "combinatorics", "divide and conquer", "math", "number theory" ]
2,200
#include <bits/stdc++.h> using namespace std; constexpr int64_t mod = 1e9 + 7; constexpr int64_t twoInv = 500'000'004; constexpr int64_t sixInv = 166'666'668; int64_t add(int64_t a, int64_t b) { return (a % mod + b % mod) % mod; } int64_t mns(int64_t a, int64_t b) { return (a % mod - b % mod + mod) % mod; } int64_t mul(int64_t a, int64_t b) { return (a % mod) * (b % mod) % mod; } int64_t rev(int64_t n, int64_t p) { int64_t res = 0; while (n) { res = add(mul(res, p), n % p); n /= p; } return res; } int64_t stupid(int64_t n, int64_t k) { int64_t res = 0; for (int64_t p = 2; p <= k; ++p) { res = add(res, rev(n, p)); } return res; } int64_t sum1(int64_t r) { return mul(mul(r, r + 1), twoInv); } int64_t sum1(int64_t l, int64_t r) { return mns(sum1(r), sum1(l - 1)); } int64_t sum2(int64_t r) { return mul(mul(mul(r, r + 1), 2 * r + 1), sixInv); } int64_t sum2(int64_t l, int64_t r) { return mns(sum2(r), sum2(l - 1)); } int64_t get(int64_t n, int64_t l, int64_t r) { if (l > r) { return 0; } int64_t res = mul(sum1(l, r), n); int64_t minus = 0, plus = 0; int64_t L = l; while (L <= r) { int64_t value = n / L; int64_t R = min(r, n / value); minus = add(minus, mul(sum2(L, R), value)); plus = add(plus, mul(R - L + 1, value)); L = R + 1; } return add(mns(res, minus), plus); } void solve() { int64_t n, k; cin >> n >> k; int64_t sq = (int64_t)sqrtl((long double)n); int64_t ans = mul(max<int64_t>(0, k - n), n); ans = add(ans, stupid(n, min(sq, k))); ans = add(ans, get(n, sq + 1, min(n, k))); cout << ans << '\n'; } int main() { int tt = 1; cin >> tt; while (tt --> 0) { solve(); } return 0; }
2074
A
Draw a Square
The pink soldiers have given you $4$ \textbf{distinct points} on the plane. The $4$ points' coordinates are $(-l,0)$, $(r,0)$, $(0,-d)$, $(0,u)$ correspondingly, where $l$, $r$, $d$, $u$ are positive integers. \begin{center} {\small In the diagram, a square is drawn by connecting the four points $L$, $R$, $D$, $U$.} \end{center} Please determine if it is possible to draw a square$^{\text{∗}}$ with the given points as its vertices. \begin{footnotesize} $^{\text{∗}}$A square is defined as a polygon consisting of $4$ vertices, of which all sides have equal length and all inner angles are equal. No two edges of the polygon may intersect each other. \end{footnotesize}
For the given four points to make a square, we can see that the following must hold: $l$, $r$, $d$, $u$ must all be equal. The proof is left as a practice for the reader, but generally, it can be proved easily by seeing that the square is both a rhombus and a rectangle. The problem is solved in $\mathcal{O}(1)$ per test case.
[ "geometry", "implementation" ]
800
for i in range(int(input())): l,r,d,u=map(int,input().split()) if l==r==d==u: print("Yes") else: print("No")
2074
B
The Third Side
The pink soldiers have given you a sequence $a$ consisting of $n$ positive integers. You must repeatedly perform the following operation \textbf{until there is only $1$ element left}. - Choose two \textbf{distinct} indices $i$ and $j$. - Then, choose a positive integer value $x$ such that there exists a \textbf{non-degenerate triangle}$^{\text{∗}}$ with side lengths $a_i$, $a_j$, and $x$. - Finally, remove two elements $a_i$ and $a_j$, and append $x$ to the end of $a$. Please find the maximum possible value of the only last element in the sequence $a$. \begin{footnotesize} $^{\text{∗}}$A triangle with side lengths $a$, $b$, $c$ is non-degenerate when $a+b > c$, $a+c > b$, $b+c > a$. \end{footnotesize}
We can solve this problem by observing a property on the sum of elements. After each operation, it must hold that $a_i+a_j>x$, and the new element is at most $a_i+a_j-1$. Therefore, the sum decreases by at least $1$. However, we notice that a triangle of side lengths $p$, $q$, $p+q-1$ is always non-degenerate due to the following: $p+q>p+q-1$; $p+(p+q-1)>q$ due to $2p-1>0$; $q+(p+q-1)>p$ due to $2q-1>0$. Therefore, you can decrease the sum by exactly $1$ on each operation. The maximum final sum (which is the last element) is thus $\text{sum}-n+1$.
[ "geometry", "greedy", "math" ]
800
t = int(input()) for _ in range(t): n = int(input()) sm = sum(map(int, input().split())) print(sm - n + 1)
2074
C
XOR and Triangle
This time, the pink soldiers have given you an integer $x$ ($x \ge 2$). Please determine if there exists a \textbf{positive} integer $y$ that satisfies the following conditions. - $y$ is \textbf{strictly} less than $x$. - There exists a \textbf{non-degenerate triangle}$^{\text{∗}}$ with side lengths $x$, $y$, $x \oplus y$. Here, $\oplus$ denotes the bitwise XOR operation. Additionally, if there exists such an integer $y$, output any. \begin{footnotesize} $^{\text{∗}}$A triangle with side lengths $a$, $b$, $c$ is non-degenerate when $a+b > c$, $a+c > b$, $b+c > a$. \end{footnotesize}
Let us interpret the triangle inequality in terms of bitmasking. Then, we get the following. (One is omitted as it is implied in the constraints.) $x+y>x \oplus y$, $(x \oplus y)+2(x \,\&\, y)> x \oplus y$, $x\,\&\,y>0$; $y+(x \oplus y)>x$, $y+(x + y) - 2(x\,\&\,y)> x$, $y > x\,\&\,y$. In other words, $y$ satisfies the following conditions. $y$ contains at least one bit turned on in $x$; $y$ contains at least one bit not turned on in $x$. The smallest values of $y$ that satisfy this have exactly two bits turned on; one in $x$ and one not in it. Therefore, if one such value exists, then a smallest one can be found in $\mathcal{O}(\log ^2 x)$ time by simply bruteforcing all integers with two bits turned on. If any one of them is less than $x$, then it satisfies all conditions. The problem has been solved in $\mathcal{O}(\log ^2 x)$ per test case. While there exist ways to solve it in $\mathcal{O}(\log x)$ per test case, they were not required.
[ "bitmasks", "brute force", "geometry", "greedy", "probabilities" ]
1,100
t = int(input()) for _ in range(t): x = int(input()) ans = -1 for i in range(30): for j in range(30): y = (1 << i) | (1 << j) if y < x and x + y > (x ^ y) and y + (x ^ y) > x: ans = y print(ans)
2074
D
Counting Points
The pink soldiers drew $n$ circles with their center \textbf{on the $x$-axis} of the plane. Also, they have told that \textbf{the sum of radii is exactly $m$}$^{\text{∗}}$. Please find the number of integer points \textbf{inside or on the border of} at least one circle. Formally, the problem is defined as follows. You are given an integer sequence $x_1,x_2,\ldots,x_n$ and a positive integer sequence $r_1,r_2,\ldots,r_n$, where it is known that $\sum_{i=1}^n r_i = m$. You must count the number of integer pairs $(x,y)$ that satisfy the following condition. - There exists an index $i$ such that $(x-x_i)^2 + y^2 \le r_i^2$ ($1 \le i \le n$). \begin{footnotesize} $^{\text{∗}}$Is this information really useful? Don't ask me; I don't really know. \end{footnotesize}
For some value of $x$ and a circle centered on $(x_i,0)$ with radius $r_i$, we can find the range of $y$ where the points lie on using simple algebra. $y^2 \le r_i^2-(x-x_i)^2 \Longrightarrow -\sqrt{r_i^2-(x-x_i)^2} \le y \le \sqrt{r_i^2-(x-x_i)^2}$ Here, we can see that when $a=\left \lfloor {\sqrt{r_i^2-(x-x_i)^2}} \right \rfloor$, there are $2a+1$ different integer values of $y$ in this range. Now, think of how to deal with when multiple circles cover the same value of $x$. This is not too hard; you can compute the value of $a$ for all of them and take the largest one. The rest can be ignored as the largest value of $a$ covers all of them. The implementation is not hard; it simply boils down to using a std::map or some data structure to record the maximum value of $a$ for each value of $x$ that holds at least one point. The problem is solved in time complexity $\mathcal{O}(m \log m)$. It is technically possible to solve the problem by fixing the value of $y$ instead of the value of $x$, but it is significantly more tedious to implement.
[ "brute force", "data structures", "geometry", "implementation", "two pointers" ]
1,400
#include<bits/stdc++.h> using namespace std; using ll=long long; int main() { int t;cin>>t; for(int i=0;i<t;i++) { int n,m;cin>>n>>m; map<ll,ll>cnt; auto isqrt=[&](ll x) { ll val=sqrtl(x)+5; while(val*val>x)val--; return val; }; vector<ll>a(n),r(n); for(ll&i:a)cin>>i; for(ll&i:r)cin>>i; for(int i=0;i<n;i++) { ll aa=a[i],rr=r[i]; for(ll x=aa-rr;x<=aa+rr;x++) { cnt[x]=max(cnt[x],2*isqrt(rr*rr-(x-aa)*(x-aa))+1); } } ll ans=0; for(auto[x,c]:cnt)ans+=c; cout<<ans<<"\n"; } }
2074
E
Empty Triangle
This is an interactive problem. The pink soldiers hid from you $n$ ($3 \le n \le 1500$) \textbf{fixed} points $(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$, \textbf{whose coordinates are not given to you}. Also, it is known that no two points have the same coordinates, and no three points are collinear. You can ask the Frontman about three \textbf{distinct} indices $i$, $j$, $k$. Then, he will draw a triangle with points $(x_i,y_i)$, $(x_j,y_j)$, $(x_k,y_k)$, and respond with the following: - If at least one of the hidden points lies inside the triangle, then the Frontman gives you the index of one such point. Do note that if there are multiple such points, \textbf{the Frontman can arbitrarily select one of them}. - Otherwise, the Frontman responds with $0$. \begin{center} {\small Your objective in this problem is to find a triangle not containing any other hidden point, such as the blue one in the diagram.} \end{center} Using at most $\mathbf{75}$ queries, you must find any triangle formed by three of the points, \textbf{not containing} any other hidden point inside. Do note that the Frontman may be \textbf{adaptive} while choosing the point to give you. In other words, the choice of the point can be determined by various factors including but not limited to the orientation of points and the previous queries. However, note that \textbf{the sequence of points will never be altered}. Hacks are disabled for this problem. Your solution will be judged on exactly $\mathbf{35}$ input files, including the example input.
After querying the triple $(i,j,k)$ and receiving the index $p$, we seem to gain almost no info other than the following. The three triples $(p,j,k)$, $(i,p,k)$, $(i,j,p)$ all yield strictly fewer points inside the triangle than $(i,j,k)$. One may think that repeatedly substituting one index arbitrarily with $p$ gets a worst case of $1498$ queries needed. However, there is also the following information that we gain. If we found $c_i$, $c_j$, $c_k$ points after substituting one index with $p$, and found $c$ points after querying $(i,j,k)$, then $c_i+c_j+c_k+1=c$. So, after finding $c_i+c_j+c_k=c-1$, we can infer the following facts. Due to the pigeonhole principle, at least one of $c_i$, $c_j$, $c_k$ must be no greater than $\frac{c-1}{3}$. Then, if we substitute one index at random with equal probability, we choose this triangle with $\frac{1}{3}$ probability. We can expect to choose the 'good' triangle $\frac{75}{3}=25$ times on average, and the number of points inside decreases to $0$ after choosing the 'good' triangle at least $\left \lfloor {\log_3(n)} \right \rfloor +1 \le 7$ times. As $7 \ll 25$, we can expect that we will almost certainly find some empty triangle within $75$ queries. Asking Wolfram Alpha for the probability after modeling the number of correct guesses as a binomial distribution, we can estimate the failure probability for one test case to be no greater than $2.4 \cdot 10^{-7}$. As $\left ( {1 - 2.4 \cdot 10^{-7}} \right )^{700} > 0.9998$, we find that this solution has strictly less than $0.02\%$ probability to fail on at least one of the test cases. The asymptotic complexity on the number of queries required is $\mathcal{O}(\log n)$ with high probability. Challenge: In fact, this solution's failure probability for one test case is actually much less than given above, around $1.8 \cdot 10^{-20}$. Why?
[ "geometry", "interactive", "probabilities" ]
1,600
#include<bits/stdc++.h> using namespace std; int main() { mt19937 mt(727); uniform_int_distribution uni(1,3); int tc;cin>>tc; while(tc--) { int n;cin>>n; if(n<0)return 0; vector<int>vec(n); for(int i=0;i<n;i++)vec[i]=i+1; shuffle(begin(vec),end(vec),mt); int ii=vec[0],jj=vec[1],kk=vec[2]; cerr<<n<<endl; while(1) { cout<<"? "<<ii<<" "<<jj<<" "<<kk<<endl; int id;cin>>id; if(id<0)return 0; if(id==0)break; int sw=uni(mt); if(sw==1)ii=id; else if(sw==2)jj=id; else kk=id; } cout<<"! "<<ii<<" "<<jj<<" "<<kk<<endl; } }
2074
F
Counting Necessary Nodes
A \textbf{quadtree} is a tree data structure in which each node has at most four children and accounts for a square-shaped region. Formally, \textbf{for all tuples} of nonnegative integers $k,a,b \ge 0$, there exists \textbf{exactly one node} accounting for the following region$^{\text{∗}}$. $$[a \cdot 2^k,(a+1) \cdot 2^k] \times [b \cdot 2^k,(b+1) \cdot 2^k]$$ All nodes whose region is larger than $1 \times 1$ contain four children corresponding to the regions divided equally into four, and the nodes whose region is $1 \times 1$ correspond to the leaf nodes of the tree. \begin{center} {\small A small subset of the regions accounted for by the nodes is shown. The relatively darker regions are closer to leaf nodes.} \end{center} The Frontman hates the widespread misconception, such that the quadtree can perform range queries in $\mathcal{O}(\log n)$ time when there are $n$ leaf nodes inside the region. In fact, sometimes it is necessary to query much more than $\mathcal{O}(\log n)$ regions for this, and the time complexity is $\mathcal{O}(n)$ in some extreme cases. Thus, the Frontman came up with this task to educate you about this worst case of the data structure. The pink soldiers have given you a finite region $[l_1,r_1] \times [l_2,r_2]$, where $l_i$ and $r_i$ ($l_i < r_i$) are nonnegative integers. Please find the minimum number of nodes that you must choose in order to make the union of regions accounted for by the chosen nodes \textbf{exactly} the same as the given region. Here, two sets of points are considered different if there exists a point included in one but not in the other. \begin{footnotesize} $^{\text{∗}}$Regions are sets of points \textbf{with real coordinates}, where the point $(x,y)$ is included in the region $[p,q] \times [r,s]$ if and only if $p \le x \le q$ and $r \le y \le s$. Here, $\times$ formally refers to Cartesian product of sets. \end{footnotesize}
Notice how the interval on each axis corresponds to those found in nodes of segment trees. Let us find the segment tree intervals on each axis and call those sets of intervals $I_x$ and $I_y$. Then, for each rectangle formed by some $a \times b$ such that $a \in I_x$, $b \in I_y$, the following holds. No node with side length strictly greater than $\min(|a|,|b|)$ can cover this rectangle without moving outside the given region. All nodes with side length no greater than $\min(|a|,|b|)$ are either completely inside the rectangle or completely outside. Thus, we find the following strategy to cover the region optimally. For all $a \times b$ such that $a \in I_x$, $b \in I_y$, cover the sub-region with the following method. As both $|a|$ and $|b|$ are powers of two, the larger one is divisible by the smaller one. Therefore, we can cover the sub-region with nodes with side length $\min(|a|,|b|)$. This requires us to use $\frac{\max(|a|,|b|)}{\min(|a|,|b|)}$ nodes. As both $|a|$ and $|b|$ are powers of two, the larger one is divisible by the smaller one. Therefore, we can cover the sub-region with nodes with side length $\min(|a|,|b|)$. This requires us to use $\frac{\max(|a|,|b|)}{\min(|a|,|b|)}$ nodes. Implementing this leads to a solution with time complexity $\mathcal{O}(\log^2 X)$. While there are solutions with time complexity $\mathcal{O}(\log X)$, they were not needed.
[ "bitmasks", "divide and conquer", "greedy", "implementation", "math" ]
2,000
#include<bits/stdc++.h> using namespace std; using ll=long long; int main() { int t;cin>>t; for(int i=0;i<t;i++) { int l1,r1,l2,r2;cin>>l1>>r1>>l2>>r2; vector<pair<ll,ll>>it1,it2; auto rec=[&](auto rec,int L,int R,int l,int r,vector<pair<ll,ll>>&v)->void { if(r<=L||l>=R)return; if(l<=L&&R<=r) { v.emplace_back(L,R); return; } rec(rec,L,(L+R)/2,l,r,v); rec(rec,(L+R)/2,R,l,r,v); }; rec(rec,0,1<<25,l1,r1,it1); rec(rec,0,1<<25,l2,r2,it2); ll ans=0; for(auto[al,ar]:it1) { for(auto[bl,br]:it2) { ll a=ar-al,b=br-bl; if(a<b)swap(a,b); ans+=a/b; } } cout<<ans<<"\n"; } }
2074
G
Game With Triangles: Season 2
\begin{center} \begin{tabular}{c} The Frontman greets you to this final round of the survival game. \ \end{tabular} \end{center} There is a regular polygon with $n$ sides ($n \ge 3$). The vertices are indexed as $1,2,\ldots,n$ in clockwise order. On each vertex $i$, the pink soldiers have written a positive integer $a_i$. With this regular polygon, you will play a game defined as follows. Initially, your score is $0$. Then, you perform the following operation any number of times to increase your score. - Select $3$ different vertices $i$, $j$, $k$ that you \textbf{have not chosen} before, and draw the triangle formed by the three vertices. - Then, your score increases by $a_i \cdot a_j \cdot a_k$. - However, you \textbf{can not perform this operation} if the triangle shares a positive common area with any of the triangles drawn previously. \begin{center} {\small An example of a state after two operations is on the left. The state on the right \textbf{is impossible} as the two triangles share a positive common area.} \end{center} Your objective is to maximize the score. Please find the maximum score you can get from this game.
If we cut a single edge and consider the regular polygon as a polyline of $n$ points, then we can think of using some form of Range DP to solve this problem. This is correct when you simply take the maximum value over all possible edges you can cut. It is not hard to see that doing this should not change the overall time complexity (unless you did recalculate the same state multiple times). However, it is hard to immediately think of a transition that is both correct and efficient. Let's find a trivially correct but slow solution and reduce the complexity. A correct $\mathcal{O}(n^5)$ DP which is (arguably) easy to find is as follows. $\text{dp}_{[L,R]}=\max_{L \le i < j < k \le R}{\left ({\text{dp}_{[L,i-1]}+\text{dp}_{[i+1,j-1]}+\text{dp}_{[j+1,k-1]}+\text{dp}_{[k+1,R]}+\text{score}(i,j,k)}\right )}$ It is not too hard to prove the correctness of this transition, as it follows from the conditions such that two triangles will not coincide anywhere. It is only tricky for us to improve the complexity. First, we can find that $\text{score}(i,j,k)$ will also be found with $L=i$ and $k=R$ later in some smaller subproblem. Then, our transition changes. $\text{dp}_{[L,R]}=\max\left ({ {\max_{L < i < R}{\left ({\text{dp}_{[L+1,i-1]}+\text{dp}_{[i+1,R-1]}+\text{score}(L,i,R)}\right )}},{\max_{L \le i < j < R}{\left ({\text{dp}_{[L,i]}+\text{dp}_{[i+1,j]}+\text{dp}_{[j+1,R]}}\right )}} }\right)$ This is a correct $\mathcal{O}(n^4)$ DP which cuts a lot of useless transitions from the $\mathcal{O}(n^5)$. But it is, in fact, still redundant. It can be reduced further. We only wanted to split our range into three disjoint ones. But even by just splitting the range into two, it later splits into two other disjoint ones in our subproblem. Now we don't need to split into three, only two is necessary. So it is as follows. $\text{dp}_{[L,R]}=\max\left ({ {\max_{L < i < R}{\left ({\text{dp}_{[L+1,i-1]}+\text{dp}_{[i+1,R-1]}+\text{score}(L,i,R)}\right )}},{\max_{L \le i < R}{\left ({\text{dp}_{[L,i]}+\text{dp}_{[i+1,R]}}\right )}} }\right)$ Now this computes the correct answer in $\mathcal{O}(n^3)$, which is the complexity we needed. It is important to note that even though it might be easy to see the similarity to Triangulation DP problems (such as the Matrix Chain Product problem), it is not an immediate transformation from such problems. That is, it is not easy to lead to a correct transition by modifying the transition starting from Triangulation DP, and likely there will be quite an excessive amount of states that you need to compute even if you did.
[ "dp", "geometry" ]
2,100
#include<bits/stdc++.h> using namespace std; using ll=long long; ll dp[505][505]; int main() { cin.tie(0)->sync_with_stdio(0); int t;cin>>t; for(int tc=0;tc<t;tc++) { ll n;cin>>n; vector<ll>vec(n); for(ll&i:vec)cin>>i; for(int i=0;i<n;i++) { for(int j=0;j<n;j++)dp[i][j]=-1e18; } auto value=[&](ll i,ll j,ll k) { return i*j*k; }; for(int len=1;len<=n;len++) { for(int L=0;L<n;L++) { ll ans=0; ll R=(L+len-1)%n; if(len<=2) { dp[L][R]=0; continue; } if(len==3) { dp[L][R]=max(0LL,value(vec[L],vec[(L+1)%n],vec[R])); continue; } for(int i=(L+1)%n;i!=R;i=(i+1)%n) { ll val=value(vec[L],vec[i],vec[R]); if(i!=(L+1)%n)val+=dp[(L+1)%n][(i+n-1)%n]; if(i!=(R+n-1)%n)val+=dp[(i+1)%n][(R+n-1)%n]; ans=max(ans,val); } for(int i=L;i!=R;i=(i+1)%n) { ans=max(ans,dp[L][i]+dp[(i+1)%n][R]); } dp[L][R]=ans; } } ll ans=0; for(int i=0;i<n;i++) { ans=max(ans,dp[i][(i+n-1)%n]); } cout<<ans<<"\n"; } }
2075
A
To Zero
You are given two integers $n$ and $k$; $k$ is an odd number not less than $3$. Your task is to turn $n$ into $0$. To do this, you can perform the following operation any number of times: choose a number $x$ from $1$ to $k$ and subtract it from $n$. However, if the \textbf{current} value of $n$ is even (divisible by $2$), then $x$ must also be even, and if the \textbf{current} value of $n$ is odd (not divisible by $2$), then $x$ must be odd. In different operations, you can choose the same values of $x$, but you don't have to. So, there are no limitations on using the same value of $x$. Calculate the minimum number of operations required to turn $n$ into $0$.
If you subtract an odd number from an odd number, you will get an even number. And if you subtract an even number from an even number, you will also get an even number. Therefore, after each operation, we obtain an even number. Additionally, we can always subtract the maximum number that we can. If the result of the subtraction is less than $0$, we can simply use a smaller value of $x$ in the last operation. Based on this, we can write the following solution: initially, if $n$ is odd, subtract $k$ from it to make it even (or do nothing if it is already even). Then subtract $(k-1)$ from the resulting $n$ until we reach $0$ or a negative number. However, we may have to subtract $(k-1)$ from $n$ for a long time. Therefore, let's speed this up. We need to find the minimum number of operations $m$ such that $m(k-1) \ge n$. That is, $m$ is $\lceil \frac{n}{k-1} \rceil$ (the result of dividing $n$ by $(k-1)$, rounded up). You can simply calculate $\lceil \frac{n}{k-1} \rceil$ using double precision floating-point numbers (type double) and round it using some standard function like ceil; in this problem, you won't have issues with calculation accuracy. However, with large values of $n$ and $k$, you may get an incorrect answer due to precision errors, so it's better to divide $n$ by $(k-1)$ with rounding up using integers. To divide the number $x$ by the number $y$ without using floating-point numbers, you can use one of two methods: either perform integer division of $x$ by $y$ rounding down (this is standard integer division), and then add $1$ to the answer if $x \bmod y \ne 0$; or divide $(x+y-1)$ by $y$ rounding down; this will automatically increase the answer by $1$ compared to dividing $x$ by $y$ if $x$ is not divisible by $y$.
[ "greedy", "math" ]
800
t = int(input()) for i in range(t): n, k = map(int, input().split()) ans = 0 if n % 2 == 1: n -= k ans = 1 k -= 1 ans += (n + k - 1) // k print(ans)
2075
B
Array Recoloring
You are given an integer array $a$ of size $n$. Initially, all elements of the array are colored red. You have to choose exactly $k$ elements of the array and paint them blue. Then, while there is at least one red element, you have to select any red element with a blue neighbor and make it blue. The cost of painting the array is defined as the sum of the first $k$ chosen elements and the last painted element. Your task is to calculate the maximum possible cost of painting for the given array.
Since the cost depends on the first $k$ painted elements and the last one, it cannot exceed the sum of $(k+1)$ maximum elements of the array. In fact, in most cases, you can get exactly that cost. Let $k \ge 2$ and the positions of the $(k+1)$ maxima are $p_1, p_2, \dots, p_k, p_{k+1}$. In this case, you can initially color the elements $p_1, p_3, \dots, p_k, p_{k + 1}$, then all except $p_2$, and then color the element $p_2$ last. So the cost is exactly the sum of $(k+1)$ maxima. This works because the element we want to color last is between two elements we choose initially. However, if $k=1$, then whatever element we choose and how we color the remaining elements, the first or the last element of the array will be the last to be colored. Therefore, in this case, you can consider two options (and pick the one with the maximum cost): the element among the first $(n-1)$ positions is painted first, and the $n$-th element is painted last; or the element among the last $(n-1)$ positions is painted first, and the $1$-st element is painted last.
[ "constructive algorithms", "greedy" ]
1,300
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<int> a(n); for (auto &x : a) cin >> x; long long ans = 0; if (k > 1) { sort(a.begin(), a.end(), greater<int>()); ans = accumulate(a.begin(), a.begin() + k + 1, 0LL); } else { int l = *max_element(a.begin(), a.end() - 1); int r = *max_element(a.begin() + 1, a.end()); ans = max(l + a.back(), r + a[0]); } cout << ans << '\n'; } }
2075
C
Two Colors
Monocarp has installed a new fence at his summer house. The fence consists of $n$ planks of the same size arranged in a row. Monocarp decided that he would paint his fence according to the following rules: - each plank of the fence will be painted in exactly one color; - the number of different colors that the planks will be painted in is \textbf{exactly} two; - the planks of the fence that are painted in the same color must form a continuous sequence, meaning that for all pairs of planks painted in the same color, there will be no planks painted in a different color between them. Monocarp has $m$ different paints, and the paint of the $i$-th color is sufficient to paint no more than $a_i$ planks of the fence. Monocarp will not buy any additional paints. Your task is to determine the number of different ways to paint the fence that satisfy all of Monocarp's described wishes. Two ways to paint are considered different if there exists a plank that is painted in different colors in these two ways.
Consider a general form of a fence: the planks from $1$ to $k$ are painted in one color, and the planks from $k + 1$ to $n$ are painted in another color. Let's iterate over the value of $k$. It is then easy to determine which colors are suitable for the first half and which are suitable for the second half. Any color with $a_i \ge k$ will work for the first half, while for the second half, the colors must satisfy $a_i \ge n - k$. If we sort the values of $a_i$ in non-decreasing order, we can find the number of available colors using binary search. In C++, we can use lower_bound, and in Python, we can use bisect.bisect_left. Let there be $x$ candidates for the first half and $y$ candidates for the second half. We would like the number of ways to choose two colors to be equal to $x \cdot y$. However, we have accidentally counted cases where we chose the same color for both halves of the fence. The number of such cases is $\min(x, y)$, as that color must be sufficient for both halves. Therefore, the contribution of $k$ to the answer is $x \cdot y - \min(x, y)$. Sum up the answers for all $k$ to obtain the final answer to the problem. Overall complexity: $O((n + m) \log m)$ for each test case.
[ "binary search", "combinatorics", "math" ]
1,500
from bisect import bisect_left for _ in range(int(input())): n, m = map(int, input().split()) a = sorted(list(map(int, input().split()))) ans = 0 for k in range(1, n): x = m - bisect_left(a, k) y = m - bisect_left(a, n - k) ans += x * y - min(x, y) print(ans)
2075
D
Equalization
You are given two non-negative integers $x$ and $y$. You can perform the following operation any number of times (possibly zero): choose a positive integer $k$ and divide either $x$ or $y$ by $2^k$ rounding down. The cost of this operation is $2^k$. However, there is an additional constraint: you cannot select the same value of $k$ more than once. Your task is to calculate the minimum possible cost in order to make $x$ equal to $y$.
Note that for any positive integer $x$, the following equality holds: $\left\lfloor\frac{\left\lfloor\frac{x}{2^a}\right\rfloor}{2^b}\right\rfloor = \left\lfloor\frac{x}{2^{a+b}}\right\rfloor$. This means that for each number, only the total power of two by which it will be divided is significant. Due to the restriction that the same power of two cannot be used twice, we can divide all powers (in this problem, we can consider powers from $1$ to $60$) into three groups: the powers by which $x$ will be divided; the powers by which $y$ will be divided; and the powers that will not be used. However, there may be many suitable partitions, but we need to minimize the cost. To do so, we can use dynamic programming to calculate $dp_{k, i, j}$ - the minimum cost if we considered the first $k$ powers, with the sum of the first group equal to $i$ and the sum of the second group equal to $j$. The transitions in this dynamic programming are straightforward: either we add the next power to the first group, or to the second, or we exclude it. Note that this dynamic programming can be computed once and then used to calculate the answer for any given test case. Using this dynamic programming, the answer can be computed as follows: iterate over $i$ and $j$ such that $\left\lfloor\frac{x}{2^i}\right\rfloor = \left\lfloor\frac{y}{2^j}\right\rfloor$, and select the minimum among the values $dp_{60, i, j}$.
[ "bitmasks", "brute force", "dp", "graphs", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; using li = long long; const int B = 60; const li INF = 1e18; int main() { ios::sync_with_stdio(false); cin.tie(0); array<array<li, B>, B> dp; for (int i = 0; i < B; ++i) { for (int j = 0; j < B; ++j) { dp[i][j] = INF; } } dp[0][0] = 0; for (int x = 0; x < B; ++x) { for (int i = B - 1; i >= 0; --i) { for (int j = B - 1; j >= 0; --j) { if (dp[i][j] == INF) continue; if (i + x < B) dp[i + x][j] = min(dp[i + x][j], dp[i][j] + (1LL << x)); if (j + x < B) dp[i][j + x] = min(dp[i][j + x], dp[i][j] + (1LL << x)); } } } int t; cin >> t; while (t--) { li x, y; cin >> x >> y; li ans = INF; for (int i = 0; i < B; ++i) { for (int j = 0; j < B; ++j) { if ((x >> i) == (y >> j)) ans = min(ans, dp[i][j]); } } cout << ans << '\n'; } }
2075
E
XOR Matrix
For two arrays $a = [a_1, a_2, \dots, a_n]$ and $b = [b_1, b_2, \dots, b_m]$, we define the XOR matrix $X$ of size $n \times m$, where for each pair $(i,j)$ ($1 \le i \le n$; $1 \le j \le m$) it holds that $X_{i,j} = a_i \oplus b_j$. The symbol $\oplus$ denotes the bitwise XOR operation. You are given four integers $n, m, A, B$. Count the number of such pairs of arrays $(a, b)$ such that: - $a$ consists of $n$ integers, each of which is from $0$ to $A$; - $b$ consists of $m$ integers, each of which is from $0$ to $B$; - in the XOR matrix formed from these arrays, there are no more than two distinct values.
If there are at least three pairwise distinct elements in one of the two arrays ($a$ and $b$), then there will also be at least three distinct elements in the matrix. Therefore, we can assume that the number of distinct elements in each of the arrays does not exceed $2$. This allows us to construct the answer from the following parts: the number of pairs of arrays where all elements in $a$ are the same and all elements in $b$ are the same; the number of pairs of arrays where all elements in $a$ are the same, and the number of distinct elements in $b$ is $2$; the number of pairs of arrays where the number of distinct elements in $a$ is $2$, and all elements in $b$ are the same; the number of pairs of arrays where both $a$ and $b$ have two distinct elements each. The first part of the answer is simply $(A+1) \cdot (B+1)$, as we can choose which number all elements in $A$ will equal, and which number all elements in $B$ will equal. The second and third parts are very similar to each other. Therefore, we will explain how the second part is calculated, and the third can be computed similarly. We can choose which number will be in $a$, and the number of ways to do this is $(A+1)$. We can also choose which two numbers will be in $b$, which can be done in $\frac{B(B+1)}{2}$ ways. Additionally, we need to choose the positions in $b$ where the first number will be; the number of ways to do this is $2^m - 2$ (not $2^m$, since we need to exclude the cases where the same number appears in all positions). Therefore, the second part of the answer is $(A+1) \cdot \frac{B(B+1)}{2} \cdot (2^m-2)$. The fourth part is the most complex. The main problem is that it is important which specific values we choose for the arrays $a$ and $b$. Let all elements of $a$ be either $a_1$ or $a_2$ ($a_1 > a_2$), and all elements of $b$ be either $b_1$ or $b_2$ ($b_1 > b_2$). Then for this quadruple $(a_1, a_2, b_1, b_2)$, there are $(2^n-2) \cdot (2^m-2)$ ways to choose which positions in which arrays correspond to which numbers. This must be multiplied by the number of suitable quadruples, so let's learn how to count them. We are interested in quadruples of numbers $(a_1, a_2, b_1, b_2)$ that satisfy the conditions: $0 \le a_2 < a_1 \le A$; $0 \le b_2 < b_1 \le B$; $a_1 \oplus b_2 = a_2 \oplus b_1$ (otherwise, we will have more than two distinct values in the matrix, since $a_1 \oplus b_1 \ne a_1 \oplus b_2$). This condition is also equivalent to $a_1 \oplus b_1 = a_2 \oplus b_2$, so if it holds, there are exactly two distinct values in the matrix. The third condition can be rewritten as $a_1 \oplus a_2 = b_1 \oplus b_2$. Let's then count not the quadruples $(a_1, a_2, b_1, b_2)$, but the triples $(a_1, b_1, x)$ such that $0 \le a_1 \oplus x < a_1 \le A$ and $0 \le b_1 \oplus x < b_1 \le B$. This can be done using digit dynamic programming on the bits of these three numbers from the most significant to the least significant. Let $dp[i][f_a][f_b][f_x]$ be the number of ways to set the $i$ most significant bits in these three numbers such that: $f_a = 0$, if the number $a_1$ is still equal to the upper limit $A$, or $f_a = 1$, if it is definitely less; $f_b = 0$, if the number $b_1$ is still equal to the upper limit $B$, or $f_b = 1$, if it is definitely less; $f_x = 0$, if the number $x$ is still equal to $0$, or $f_x = 1$, if it is definitely not $0$. Transitions in this dynamic programming are done as follows: we iterate over which values will be in the next bit of these three numbers, check that this does not violate any conditions, and observe how the values of $f_a, f_b, f_x$ change. What conditions do we need to check? We need to ensure that $a_1 \le A$, so if $f_a$ is $0$ and the next bit in $A$ is $0$, we cannot set $1$ in the next bit of $a_1$; We need to ensure that $b_1 \le B$ (similarly); We need to ensure that $a_1 \oplus x < a_1$, so if $f_x$ is $0$ and we set the next bit in $a_1$ to $0$, this bit must also be $0$ in the number $x$; We need to ensure that $b_1 \oplus x < b_1$ (similarly). The flags $f_a, f_b, f_x$ are recalculated quite trivially, and we will not discuss this in detail in the explanation. The answer should be collected from all states of the form $dp[K][f_a][f_b][1]$, where $K$ is the number of bits in the numbers. This way, we will obtain the number of pairs $(a_1, a_2, b_1, b_2)$ that can be used. This dynamic programming is the most computationally intensive part of the solution, so the entire solution works in $O(\log \max(A,B))$, but with a very large constant in the asymptotic notation.
[ "bitmasks", "combinatorics", "dp", "implementation", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; const int K = 31; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int sub(int x, int y) { return add(x, -y); } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y) { if(y & 1) z = mul(z, x); x = mul(x, x); y >>= 1; } return z; } int dp[K][2][2][2]; int choose2(int n) { return mul(n, mul(sub(n, 1), binpow(2, MOD - 2))); } void solve() { int n, m, A, B; cin >> n >> m >> A >> B; memset(dp, 0, sizeof dp); dp[0][0][0][0] = 1; for(int i = 0; i + 1 < K; i++) for(int f1 = 0; f1 <= 1; f1++) for(int f2 = 0; f2 <= 1; f2++) for(int fx = 0; fx <= 1; fx++) { int d = dp[i][f1][f2][fx]; if(!d) continue; int j = K - 2 - i; int curA = (A >> j) & 1; int curB = (B >> j) & 1; for(int bit_a = 0; bit_a <= 1; bit_a++) for(int bit_b = 0; bit_b <= 1; bit_b++) for(int bit_x = 0; bit_x <= 1; bit_x++) { if(f1 == 0 && bit_a == 1 && curA == 0) continue; if(f2 == 0 && bit_b == 1 && curB == 0) continue; if(fx == 0 && bit_x == 1 && (bit_a == 0 || bit_b == 0)) continue; int nf1 = max(f1, bit_a ^ curA); int nf2 = max(f2, bit_b ^ curB); int nfx = max(fx, bit_x); int& d2 = dp[i + 1][nf1][nf2][nfx]; d2 = add(d2, d); } } int pairs_of_pairs = 0; for(int i = 0; i <= 1; i++) for(int j = 0; j <= 1; j++) pairs_of_pairs = add(pairs_of_pairs, dp[K - 1][i][j][1]); int comb_a = sub(binpow(2, n), 2); int comb_b = sub(binpow(2, m), 2); int ans = mul(pairs_of_pairs, mul(comb_a, comb_b)); ans = add(ans, mul(add(A, 1), add(B, 1))); ans = add(ans, mul(add(A, 1), mul(comb_b, choose2(add(B, 1))))); ans = add(ans, mul(add(B, 1), mul(comb_a, choose2(add(A, 1))))); cout << ans << endl; } int main() { int t; cin >> t; for(int i = 0; i < t; i++) solve(); }
2075
F
Beautiful Sequence Returns
Let's call an integer sequence \textbf{beautiful} if the following conditions hold: - for every element except the first one, there is an element to the left less than it; - for every element except the last one, there is an element to the right larger than it; For example, $[1, 2]$, $[42]$, $[1, 4, 2, 4, 7]$, and $[1, 2, 4, 8]$ are beautiful, but $[2, 2, 4]$ and $[1, 3, 5, 3]$ are not. Recall that a subsequence is a sequence that can be obtained from another sequence by removing some elements (possibly zero) without changing the order of the remaining elements. You are given an integer array $a$ of size $n$. Find the longest beautiful subsequence of the array $a$ and print its length.
For the start, let's note that the definition of the beauty of a sequence is equivalent to the following: a sequence is beautiful if and only if the first element is a unique minimum and the last element is a unique maximum. Next, consider each element of the array as a point in $2D$: let's transform $a_i$ into the point $(i, a_i)$. Observe that the length of the longest beautiful subsequence can be found as follows: iterate over the position $i$ of the start of the subsequence and the position $j$ of the end of the subsequence; look at the rectangle where the bottom left point is $(i, a_i)$ and the top right point is $(j, a_j)$; take the corners and all points that lie strictly inside this rectangle. Notice that if the chosen point $(i, a_i)$ has another point $i'$, such that $i' < i$ and $a_{i'} \le a_i$, then the answer for $i'$ will definitely be no worse than for $i$, which means we do not need to check the answer for $i$. Therefore, let's write down in a separate array $\mathrm{left}$ only those elements that make sense to choose as the bottom left corners of the rectangle. These will be indices $i$ such that for all $i' < i$, $a_{i'} > a_i$ (we will call them prefix minimums). Note that the resulting array $\mathrm{left}$ has interesting monotonicity properties: $\mathrm{left}_k < \mathrm{left}_{k+1}$ and at the same time $a[\mathrm{left}_k] > a[\mathrm{left}_{k + 1}]$. Therefore, if we look at an arbitrary point $(x, a_x)$, the left corners of the rectangles it falls into form an interval $\mathrm{seg}_x = [l, r)$ in the array $\mathrm{left}$, the boundaries of which can be found using binary search: $l$ is the minimum $l$ such that $a[\mathrm{left}_l] < a[x]$; $r$ is the minimum $r$ such that $\mathrm{left}_r \ge x$. Now, let's note that a similar situation occurs with the top right point: we are only interested in points that form "suffix maximums". They will have similar monotonicity: as we move from right to left, the values $a_k$ will only increase. Therefore, let's iterate over the right corner of the rectangle from right to left, maintaining the necessary information for all left corners. Specifically, we will "include" and "exclude" points, and for each left corner, we will keep track of how many included points are located to its top right. Assume that for the current right corner $k$, we have included only points that lie strictly to its bottom left. Then we can already find the answer for it as follows: let's take the maximum over the left corners from the interval $\mathrm{seg}_k$ - only these corners can be bottom left for the current corner, and the necessary values are already there. When we need to move from the right corner $k$ to the corner $k' < k$, we know that $a[k'] > a[k]$. Therefore, we need to: include all points $x$ for which $a[k] \le a[x] < a[k']$; exclude all points $x$ for which $k' \le x < k$. Including/excluding a point is simply adding $\pm 1$ over the interval $\mathrm{seg}_x$. Note that each point is included and excluded no more than once, which means there will be no more than $2n$ operations of addition over the segment. To handle the addition over a segment and the maximum over a segment, it is sufficient to use a Segment Tree. Thus, the resulting asymptotic complexity is $O(n \log{n})$.
[ "binary search", "brute force", "data structures", "implementation" ]
3,000
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); vector<int> Tadd, Tmax; int getmax(int v) { return Tmax[v] + Tadd[v]; } void push(int v) { Tadd[2 * v + 1] += Tadd[v]; Tadd[2 * v + 2] += Tadd[v]; Tadd[v] = 0; } void upd(int v) { Tmax[v] = max(getmax(2 * v + 1), getmax(2 * v + 2)); } void addVal(int v, int l, int r, int lf, int rg, int val) { if (l == lf && r == rg) { Tadd[v] += val; return; } push(v); int mid = (l + r) >> 1; if (lf < mid) addVal(2 * v + 1, l, mid, lf, min(mid, rg), val); if (rg > mid) addVal(2 * v + 2, mid, r, max(lf, mid), rg, val); upd(v); } int n; vector<int> a; inline bool read() { if(!(cin >> n)) return false; a.resize(n); fore (i, 0, n) cin >> a[i]; return true; } inline void solve() { vector<int> ask(n, 0); int mx = -1; for (int i = n - 1; i >= 0; i--) { if (a[i] > mx) { ask[i] = 1; mx = a[i]; } } vector<int> left; fore (i, 0, n) { if (left.empty() || a[left.back()] > a[i]) left.push_back(i); } vector<pt> seg(n); fore (i, 0, n) { int lf = upper_bound(left.begin(), left.end(), i, [&left](int v, int i) { return a[v] > a[i]; }) - left.begin(); int rg = lower_bound(left.begin(), left.end(), i) - left.begin(); seg[i] = {lf, rg}; } Tadd.assign(4 * n, 0); Tmax.assign(4 * n, 0); vector<int> ordToAdd(n); iota(ordToAdd.begin(), ordToAdd.end(), 0); sort(ordToAdd.begin(), ordToAdd.end(), [](int i, int j) { return a[i] < a[j]; }); auto addToSeg = [&left, &seg](int id, int val) { auto [lf, rg] = seg[id]; if (lf < rg) addVal(0, 0, sz(left), lf, rg, val); }; int ans = 0; int pos = 0; vector<int> added(n, 0); for (int i = n - 1; i >= 0; i--) { while (pos < n && a[ordToAdd[pos]] < a[i]) { if (ordToAdd[pos] <= i) { addToSeg(ordToAdd[pos], 1); added[ordToAdd[pos]] = 1; } pos++; } if (ask[i]) { auto [lf, rg] = seg[i]; ans = max(ans, 1 + (lf < rg ? 1 + getmax(0) : 0)); } if (added[i]) { addToSeg(i, -1); added[i] = 0; } } cout << ans << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); int t; cin >> t; while(t--) { (read()); solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
2077
A
Breach of Faith
\begin{quote} Breach of Faith - Supire feat.eili \end{quote} You and your team have worked tirelessly until you have a sequence $a_1, a_2, \ldots, a_{2n+1}$ of positive integers satisfying these properties. - $1 \le a_i \le 10^{18}$ for all $1 \le i \le 2n + 1$. - $a_1, a_2, \ldots, a_{2n+1}$ are pairwise \textbf{distinct}. - $a_1 = a_2 - a_3 + a_4 - a_5 + \ldots + a_{2n} - a_{2n+1}$. However, the people you worked with sabotaged you because they wanted to publish this sequence first. They deleted one number from this sequence and shuffled the rest, leaving you with a sequence $b_1, b_2, \ldots, b_{2n}$. You have forgotten the sequence $a$ and want to find a way to recover it. If there are many possible sequences, you can output any of them. It can be proven under the constraints of the problem that at least one sequence $a$ exists.
Rearrange the equation around. Try to maximize the missing number. The equation can be rearranged to $a_{2n} = a_1 + (a_3 - a_2) + (a_5 - a_4) + \ldots + (a_{2n-1} - a_{2n-2}) + a_{2n+1}$ Choose $a_1$ as the largest number, $a_3, a_5, \ldots, a_{2n+1}$ as the next $n$ largest numbers, and the rest as $a_2, a_4, \ldots, a_{2n-2}$. The value of the missing number $a_{2n}$ will be larger than $a_1$, and so larger than every number in $b$. Time complexity: $\mathcal{O}(n \log n)$ per test case. Logarithmic factor is from sorting.
[ "constructive algorithms", "greedy", "math", "sortings" ]
1,500
for test_case in range(int(input())): n = int(input()) b = sorted([int(_) for _ in input().split()]) a = [0 for _ in range(2*n+1)] # Implementation note: 0-based index used here # assign a[0], a[2], ... large numbers for i in range(0, n+1): a[2*i] = b[n+i-1] # assign a[1], a[3], .. small numbers for i in range(0, n-1): a[2*i+1] = b[i] a[2*n-1] = sum(b[n-1:]) - sum(b[:n-1]) print(*a) # model solution
2077
B
Finding OR Sum
\begin{quote} ALTER EGO - Yuta Imai vs Qlarabelle \end{quote} This is an interactive problem. There are two hidden non-negative integers $x$ and $y$ ($0 \leq x, y < 2^{30}$). You can ask no more than $2$ queries of the following form. - Pick a non-negative integer $n$ ($0 \leq n < 2^{30}$). The judge will respond with the value of $(n \mathbin{|} x) + (n \mathbin{|} y)$, where $|$ denotes the bitwise OR operation. After this, the judge will give you another non-negative integer $m$ ($0 \leq m < 2^{30}$). You must answer the correct value of $(m \mathbin{|} x) + (m \mathbin{|} y)$.
Try to get information on half of the bits. Alternate the bits. The queries are $\ldots 0101_2$ and $\ldots 1010_2$. It's easier to look at the case with only two binary digits first. Let the result of query $01_2$ be $q_1$ and $10_2$ be $q_2$. Observe that if $q_2 = 100_2$ then the first (from the right) digit of both $x$ and $y$ is $0$. $q_2 = 100_2$ then the first (from the right) digit of both $x$ and $y$ is $0$. $q_2 = 101_2$ then the first (from the right) digit of one of $x$ or $y$ is $0$, and the other one is $1$. $q_2 = 101_2$ then the first (from the right) digit of one of $x$ or $y$ is $0$, and the other one is $1$. $q_2 = 110_2$ then the first (from the right) digit of both $x$ and $y$ is $1$. $q_2 = 110_2$ then the first (from the right) digit of both $x$ and $y$ is $1$. Similarly, if $q_1 = 10_2$ then the second (from the right) digit of both $x$ and $y$ is $0$. $q_1 = 10_2$ then the second (from the right) digit of both $x$ and $y$ is $0$. $q_1 = 100_2$ then the second (from the right) digit of one of $x$ or $y$ is $0$, and the other one is $1$. $q_1 = 100_2$ then the second (from the right) digit of one of $x$ or $y$ is $0$, and the other one is $1$. $q_1 = 110_2$ then the second (from the right) digit of both $x$ and $y$ is $1$. $q_1 = 110_2$ then the second (from the right) digit of both $x$ and $y$ is $1$. To generalize to every other digit, apply the same logic to every consecutive pair of digits in $x$ and $y$. Note that you must account for the carries from the digits before too. After this, you will know for every digit position whether both $x$ and $y$ are $0$, are $1$, or have one $0$ and one $1$. You can use this information to find $(m|x) + (m|y)$ for any $m$. Time complexity: $\mathcal{O}(\log \max (x))$ per test case.
[ "bitmasks", "constructive algorithms", "implementation", "interactive", "math" ]
1,900
def query(n): print(n) return int(input()) def end_query(): print("!") return int(input()) def test_case(): n0, n1 = 0, 0 for i in range(1, 30, 2): n0 |= (1 << i) for i in range(0, 30, 2): n1 |= (1 << i) q0 = query(n0) q1 = query(n1) m = end_query() val_and, val_or = 0, 0 # solve for even indices for i in range(0, 30, 2): curf = (q0 >> (i + 1)) & 1 curb = (q0 >> i) & 1 pos = (1 << i) if curf: # 10 val_and |= pos val_or |= pos elif curb: # 01 val_or |= pos q0 -= 4 * pos # solve for odd indices q1 -= 2 for i in range(1, 30, 2): curf = (q1 >> (i + 1)) & 1 curb = (q1 >> i) & 1 pos = (1 << i) if curf and not curb: # 10 val_and |= pos val_or |= pos elif not curf and curb: # 01 val_or |= pos q1 -= 4 * pos ans = 0 for i in range(0, 30): cur = (m >> i) & 1 curand = (val_and >> i) & 1 curor = (val_or >> i) & 1 pos = (1 << i) if cur or curand: ans += 2 * pos elif curor: ans += pos print(ans) if __name__ == "__main__": t = int(input()) for _ in range(t): test_case() # model solution
2077
C
Binary Subsequence Value Sum
\begin{quote} Last | Moment - onoken \end{quote} For a binary string$^{\text{∗}}$ $v$, the score of $v$ is defined as the maximum value of $$F\big(v, 1, i\big) \cdot F\big(v, i+1, |v|\big)$$ over all $i$ ($0 \leq i \leq |v|$). Here, $F\big(v, l, r\big) = r - l + 1 - 2 \cdot \operatorname{zero}(v, l, r)$, where $\operatorname{zero}(v, l, r)$ denotes the number of $\mathtt{0}$s in $v_lv_{l+1} \ldots v_r$. If $l > r$, then $F\big(v, l, r\big) = 0$. You are given a binary string $s$ of length $n$ and a positive integer $q$. You will be asked $q$ queries. In each query, you are given an integer $i$ ($1 \leq i \leq n$). You must flip $s_i$ from $\mathtt{0}$ to $\mathtt{1}$ (or from $\mathtt{1}$ to $\mathtt{0}$). Find the sum of the scores over all non-empty subsequences$^{\text{†}}$ of $s$ after each modification query. Since the result may be large, output the answer modulo $998\,244\,353$. Note that the modifications are persistent. \begin{footnotesize} $^{\text{∗}}$A binary string is a string that consists only of the characters $\mathtt{0}$ and $\mathtt{1}$. $^{\text{†}}$A binary string $x$ is a subsequence of a binary string $y$ if $x$ can be obtained from $y$ by deleting several (possibly zero or all) characters. \end{footnotesize}
Find a closed-form expression for the score of a binary string. The closed-form expression for the score of a binary string is $\lfloor \frac{cnt_0-cnt_1}{2} \rfloor \lceil \frac{cnt_0-cnt_1}{2} \rceil$ Where $cnt_0$ and $cnt_1$ are the number of $\tt{0}$ and $\tt{1}$ in the binary string, respectively. $\lfloor \frac{cnt_0-cnt_1}{2} \rfloor \lceil \frac{cnt_0-cnt_1}{2} \rceil = \frac{(cnt_0-cnt_1)^2}{4} - \frac{(cnt_0-cnt_1 \mod 2)}{4}$ The expression for counting subsequences might be simpler than you think. Think of $\tt{0}$ as $-1$ and $\tt{1}$ as $1$. Let us count the number of subsequences of a binary string which will have the sum of $i$. Let $cnt_0$ and $cnt_1$ as the number of $\tt{0}$ and $\tt{1}$ in the binary string. The number of subsequences is ${n} \choose {i + cnt_0}$ We change the perspective on $\tt{0}$ slightly from contributing $-1$ to the sum if chosen and $0$ to the sum if not chosen, to contributing $0$ to the sum if chosen and $1$ to the sum if not chosen. This changes the problem to having $cnt_0 + cnt_1 = n$ distinct objects and needing to pick $i+cnt_0$ of them. So the desired sum of the score over all subsequences (see expression of score of a single string in Hint 2) is $\sum_{i = -cnt_0}^{n - cnt_0} {{n} \choose {i + cnt_0}} (\frac{i^2}{4} - \frac{(i \mod 2)}{4})$ At this point, you can throw convolution at the problem by precomputing the answer for $cnt_0 = 0, 1, \ldots, n$ and solve it in $\mathcal{O}(n \log n + q)$. Alternatively, you can do more algebra to arrive at a closed-form expression. $2^{n-4}(n(n+1) - 4cnt_0n + 4cnt_0^2 - 2)$ Consider $\sum_{i = -cnt_0}^{n - cnt_0} {{n} \choose {i + cnt_0}} i^2$ $= \sum_{i = 0}^{n} {{n} \choose {i}} (i-cnt_0)^2$ $= \sum_{i = 0}^{n} {{n} \choose {i}} i^2 - 2cnt_0 \sum_{i = 0}^{n} {{n} \choose {i}} i + cnt_0^2 \sum_{i = 0}^{n} {{n} \choose {i}} 1$ $= n(n+1) \cdot 2^{n-2} - 2cnt_0 n \cdot 2^{n-1} + cnt_0^2 \cdot 2^n$ And $\sum_{i = -cnt_0}^{n - cnt_0} {{n} \choose {i + cnt_0}} (i \mod 2) = 2^{n-1}$ So $\frac{1}{4} \sum_{i = -cnt_0}^{n - cnt_0} {{n} \choose {i + cnt_0}} i^2 + (i \mod 2)$ $= \frac{1}{4} (n(n+1) \cdot 2^{n-2} - 2cnt_0 n \cdot 2^{n-1} + cnt_0^2 \cdot 2^n - 2^{n-1})$ $= 2^{n-4}(n(n+1) - 4cnt_0n + 4cnt_0^2 - 2)$ Time complexity: $\mathcal{O}(n+q)$ per test case.
[ "combinatorics", "data structures", "dp", "fft", "math", "matrices" ]
2,300
mod = 998244353 import sys input = sys.stdin.readline for test_case in range(int(input())): n, q = map(int, input().split()) s = list(map(int, list(input()[:-1]))) cnt0 = n - sum(s) pw2 = pow(2, n-4+mod-1, mod) for _ in range(q): a = int(input()) - 1 cnt0 += 2 * s[a] - 1 s[a] = 1 - s[a] ans = pw2 * (n*(n+1) - 4*cnt0*n + 4*cnt0*cnt0 - 2) % mod ans = (ans + mod) % mod print(ans) # model solution, math
2077
D
Maximum Polygon
Given an array $a$ of length $n$, determine the lexicographically largest$^{\text{∗}}$ subsequence$^{\text{†}}$ $s$ of $a$ such that $s$ can be the side lengths of a polygon. Recall that $s$ can be the side lengths of a polygon if and only if $|s| \geq 3$ and $$ 2 \cdot \max(s_1, s_2, \ldots, s_{|s|}) < s_1 + s_2 + \ldots + s_{|s|}. $$ If no such subsequence $s$ exists, print $-1$. \begin{footnotesize} $^{\text{∗}}$A sequence $x$ is lexicographically smaller than a sequence $y$ if and only if one of the following holds: - $x$ is a prefix of $y$, but $x \ne y$; - in the first position where $x$ and $y$ differ, the sequence $x$ has a smaller element than the corresponding element in $y$. $^{\text{†}}$A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deleting several (possibly zero or all) elements. \end{footnotesize}
Find a way to get the answer if you fixed the largest value or the first value of the subsequence. Sufficiently long (which is not that long) arrays will definitely be polygon side lengths. Suppose we consider some integer $x$, and we try to find the lexicographically largest subsequence (say $s$) such that the maximum element of $s$ is $x$. We can do it greedily. For the subsequence $s$ to be valid, we need to ensure that the sum of the elements of $s$ is greater than $2x$. So, our greedy strategy is like we have an empty vector $s$, and we iterate over the array $a$ from left to right, and for each element $a_i$, we do the following: If $s$ is not empty and $a_i$ is greater than the last element of $s$, we will check whether we can make the total sum of $s$ greater than $2x$, if we remove the last element of $s$. Now what can be the maximum possible sum of $s$? We can just append all the elements of $a$ which are less than or equal to $x$, and are present to the right of $a_i$ to $s$. Append $a_i$ to $s$. Thus, we see that the subsequence $s$ is the lexicographically largest subsequence such that the maximum element of $s$ is $x$. Now, we have $O(n)$ candidates for the maximum element of $s$. We cannot find the best subsequence for each candidate, as it will be too slow. Here comes the key observation. Now, what can be the maximum possible size of a sorted vector $v$ such that there does not exist any subsequence of $v$ which can form the sides of a valid polygon? We should have $v_i > \sum_{j=1}^{i-1} v_j$. Now, to get the maximum possible size of $v$, we should have $v_1 = 1$ and $v_i = 2^{i - 2}$ for $i \geq 2$. Thus, the maximum possible size of $v$ can be $p = \log_2(10^9) + 2$. Our claim is that in the lexicographically largest subsequence $s$, the maximum element should be one of the largest $p + 1$ elements of $a$. Suppose we do not have the maximum element of $s$ in the largest $p + 1$ elements of $a$. Let's consider the multiset of the largest $p + 1$ elements of $a$. As we saw above, there should be a subsequence (say $t$) of this multiset which forms the sides of a valid polygon. Now if we insert the elements of $t$ in $s$, we will get a subsequence $s'$ such that $s'$ is valid and $s'$ is lexicographically larger than $s$. Thus, we cannot have a subsequence $s$ such that $s$ is the largest possible subsequence and the maximum element of $s$ is not in the largest $p + 1$ elements of $a$. Time complexity: $\mathcal{O}(n \log \max(a))$ per test case.
[ "brute force", "data structures", "greedy", "implementation", "math" ]
3,100
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define ll long long #define ld long double #define nline "\n" #define f first #define s second const ll INF_MUL=1e13; const ll INF_ADD=1e18; #define sz(x) (ll)x.size() #define vl vector<ll> #define all(x) x.begin(),x.end() #define rall(x) x.rbegin(),x.rend() mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; typedef tree<pair<ll,ll>, null_type, less<pair<ll,ll>>, rb_tree_tag, tree_order_statistics_node_update> ordered_pset; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- const ll MOD=998244353; const ll MAX=500500; void solve(){ ll n; cin>>n; vector<ll> ans,p(n+5); vector<ll> track; for(ll i=1;i<=n;i++){ cin>>p[i]; track.push_back(p[i]); } ll till=min(60ll,n); sort(rall(track)); vector<ll> consider; for(ll i=0;i<=till-1;i++){ consider.push_back(track[i]); } for(ll x:consider){ vector<ll> cur; vector<ll> sum(n+5,0); for(ll i=n;i>=1;i--){ sum[i]=sum[i+1]; if(p[i]<=x){ sum[i]+=p[i]; } } ll need=2*x+1; if(sum[1]<=need-1){ continue; } ll have=0; for(ll i=1;i<=n;i++){ if(p[i]>x){ continue; } while(!cur.empty()){ auto last=cur.back(); if(last<p[i] and have-last+sum[i]>=need){ cur.pop_back(); have-=last; } else{ break; } } cur.push_back(p[i]); have+=p[i]; } ans=max(ans,cur); } if(ans.empty()){ cout<<"-1\n"; return; } cout<<sz(ans)<<nline; for(auto it:ans){ cout<<it<<" "; } cout<<nline; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll test_cases=1; cin>>test_cases; while(test_cases--){ solve(); } cout<<fixed<<setprecision(15); cerr<<"Time:"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<"ms\n"; } // model solution
2077
E
Another Folding Strip
For an array $b$ of length $m$, define $f(b)$ as follows. Consider a $1 \times m$ strip, where all cells initially have darkness $0$. You want to transform it into a strip where the color at the $i$-th position has darkness $b_i$. You can perform the following operation, which consists of two steps: - Fold the paper at any line between two cells. You may fold as many times as you like, or choose not to fold at all. - Choose \textbf{one} position to drop the black dye. The dye permeates from the top and flows down to the bottom, increasing the darkness of all cells in its path by $1$. After dropping the dye, you unfold the strip. Let $f(b)$ be the minimum number of operations required to achieve the desired configuration. It can be proven that the goal can always be achieved in a finite number of operations. You are given an array $a$ of length $n$. Evaluate $$\sum_{l=1}^n\sum_{r=l}^n f(a_l a_{l+1} \ldots a_r)$$ modulo $998\,244\,353$.
Folding is basically alternating the parity of the indices. Maximum subarray sum. As mentioned in Hint 1, we can see that if the darkness of the cells $i_1, i_2, \ldots, i_k$ increases in some operation, the parity of $i_j$ should be different from that of $i_{j+1}$ for $1 \le j \le k - 1$ Let us try to find $f(a[1, n])$. Consider an array $b$ such that $b_i = (-1)^i a_i$ for all $1 \le i \le n$. Let us perform exactly one operation, and say our subsequence of indices is $i_1, i_2, \ldots, i_k$. Let $a'$ be the updated array after performing the operation, and $b'_i = (-1)^{i'} a'_i$ for all $1 \le i \le n$. Now we can see that $\left| \sum_{i = l}^{r} b'_i - \sum_{i = l}^{r} b_i \right| \le 1,$ for all $1 \le l \le r \le n$. This is so because for any subarray $b[l, r]$, if $x$ elements at odd indices and $y$ elements at even indices were selected, we should have $|x - y| \le 1$. So, we can see that after any operation, the absolute sum of any subarray of $b$ decreases by at most $1$. Thus, this gives us a lower bound for the value of $f(a[1, n])$, which is $\max_{1 \le l \le r \le n} \left| \sum_{i = l}^{r} b_i \right|.$ Now let us consider the following greedy algorithm for selecting a subsequence $s$ of indices: Start from $i = 1$ and move to the right. If $b_i$ is zero, we continue. If $s$ is empty, we append $i$ to $s$, and continue. If $i$ does not have the same parity as the last element of $s$, we append $i$ to $s$, and continue. Otherwise, we continue. Now suppose $T$ is the set of pairs of indices $(l, r)$ such that $b_l$ and $b_r$ are nonzero and $\left| \sum_{i = l}^{r} b_i \right|$ is maximized. We can prove that the absolute sum of all subarrays in $T$ would be reduced by $1$ after performing the operation. We can notice that if $(l, r) \in T$, then $l$ and $r$ should have the same parity. Otherwise, $\max \left( \left| b[l + 1, r] \right|, \left| b[l, r - 1] \right| \right) > \left| b[l, r] \right|.$ Next, we claim that $l$ should be in $s$. Suppose $l$ is not in $s$. This means that there should be an index $k$ in $s$ such that $k$ has the same parity as $l$ and there are no nonzero elements between $k$ and $l$ that have a parity different from $l$. Now if that is the case, then $b[k, r]$ would have a greater absolute sum than $b[l, r]$. Thus, we conclude that $l$ will always be in $s$. Now let $d$ be the largest index in $s$ smaller than or equal to $r$. First of all, we should have $d \ge l$. Now $d$ should have the same parity as $r$. This is so because if that is not the case, we should have $d < r$ and we would have selected $r$ or any other element having the same parity as $r$ after $d$ in $s$. Thus, we can see that for all the pairs $(l, r) \in T$, we should have $l$ in $s$ and the largest element smaller than or equal to $r$ in $s$ should have the same parity as that of $r$. This implies that the absolute sum of all subarrays in $T$ would be reduced by $1$ after performing the operation. This is because if $l$ is odd, we would have added $1, -1, 1, -1, \ldots, 1$ to the subarray $b[l, r]$, increasing the subarray sum of $b[l, r]$ by $1$. And if $l$ is even, we would have added $-1, 1, -1, 1, \ldots, -1$ to the subarray $b[l, r]$, decreasing the subarray sum of $b[l, r]$ by $1$. Now we can see that the greedy algorithm would achieve the lower bound. So, the answer for the array $a$ is the maximum absolute sum over all subarrays of $b$. Let us consider an array $c$ such that $c_i = c_{i - 1} + b_i, \quad \text{with } c_0 = 0.$ We can further notice that the maximum absolute sum over all subarrays of $b$ is equal to $\max_{1 \le i \le n} c_i - \min_{1 \le i \le n} c_i.$ Now we can see that $f(a[l, r]) = \max_{l \le i \le r} c_i - \min_{l \le i \le r} c_i.$ Thus, $\sum_{l = 1}^{n} \sum_{r = l}^{n} f(a[l, r]) = \sum_{l = 1}^{n} \sum_{r = l}^{n} \max_{l \le i \le r} c_i - \min_{l \le i \le r} c_i.$ So, $\sum_{l = 1}^{n} \sum_{r = l}^{n} f(a[l, r]) = \sum_{l = 1}^{n} \sum_{r = l}^{n} \max_{l \le i \le r} c_i - \sum_{l = 1}^{n} \sum_{r = l}^{n} \min_{l \le i \le r} c_i.$ Finding the value of $\sum_{l = 1}^{n} \sum_{r = l}^{n} \max_{l \le i \le r} c_i$ is a fairly standard exercise, which can be done using a stack in $O(n)$ time.
[ "combinatorics", "constructive algorithms", "data structures", "divide and conquer", "dp", "greedy", "math" ]
2,700
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define ll long long #define ld long double #define nline "\n" #define f first #define s second const ll INF_MUL=1e13; const ll INF_ADD=1e18; #define sz(x) (ll)x.size() #define vl vector<ll> #define all(x) x.begin(),x.end() #define rall(x) x.rbegin(),x.rend() mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; typedef tree<pair<ll,ll>, null_type, less<pair<ll,ll>>, rb_tree_tag, tree_order_statistics_node_update> ordered_pset; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- const ll MOD=998244353; const ll MAX=500500; void solve(){ ll n; cin>>n; vector<ll> a(n+5),c(n+5,0); for(ll i=1;i<=n;i++){ cin>>a[i]; ll val=a[i]; if(i&1){ val=-val; } c[i]=c[i-1]+val; } auto getv=[&](vector<ll> d,ll status){ set<ll> track; track.insert(-1); track.insert(n+1); vector<pair<ll,ll>> consider; ll sum=0; for(ll i=0;i<=n;i++){ if(status==0){ c[i]=-c[i]; } consider.push_back({c[i],i}); } sort(rall(consider)); for(auto it:consider){ ll val=it.f,pos=it.s; ll now=val%=MOD; track.insert(pos); ll l=*(--track.lower_bound(pos)),r=*(track.upper_bound(pos)); ll subarrays=((pos-l)*(r-pos))%MOD; sum=(sum+now*subarrays)%MOD; } sum=(sum+MOD)%MOD; return sum; }; ll ans=(getv(c,1)+getv(c,0))%MOD; cout<<ans<<nline; return; } int main() { ll test_cases=1; cin>>test_cases; while(test_cases--){ solve(); } cout<<fixed<<setprecision(12); cerr<<"Time:"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<"ms\n"; }
2077
F
AND x OR
Suppose you have two arrays $c$ and $d$, each of length $k$. The pair $(c, d)$ is called \textbf{good} if $c$ can be changed to $d$ by performing the following operation any number of times. - Select two distinct indices $i$ and $j$ ($1 \leq i, j \leq k$, $i \neq j$) and a nonnegative integer $x$ ($0 \leq x < 2^{30}$). Then, apply the following transformations: - $c_i := c_i \mathbin{\&} x$, where $\&$ denotes the bitwise AND operation. - $c_j := c_j \mathbin{|} x$, where $|$ denotes the bitwise OR operation. You are given two arrays $a$ and $b$, both of length $n$, containing nonnegative integers not exceeding $m$. You can perform two types of moves on these arrays any number of times: - Select an index $i$ ($1 \leq i \leq n$) and set $a_i := a_i + 1$. - Select an index $i$ ($1 \leq i \leq n$) and set $b_i := b_i + 1$. Note that the elements of $a$ and $b$ may exceed $m$ at some point while performing the moves. Find the minimum number of moves required to make the pair $(a, b)$ good.
Characterize the property of a good pair of arrays. Think about the last operation that turns a good pair of arrays into the same array. $(a, b)$ is a good pair only if at least one of these two conditions hold $a = b$ $a = b$ There exist two distinct indices $i$, $j$ such that $b_i$ is a submask of $b_j$. There exist two distinct indices $i$, $j$ such that $b_i$ is a submask of $b_j$. If $a \neq b$, then you need to do at least one operation to $a$. In the last operation, if you choose $i$, $j$, $x$, then $a_i$ is a submask of $x$ and $x$ is a submask of $a_j$. So in the final array, there must be at least one pair of submask and supermask. Next, we will show that this is sufficient. For every index $k$ other than $i$ and $j$, you can do this. Perform operation with $k$, $i$, $0$ Perform operation with $k$, $i$, $0$ Perform operation with $i$, $k$, $b_k$ Perform operation with $i$, $k$, $b_k$ Then Perform operation with $i$, $j$, $0$ Perform operation with $i$, $j$, $0$ Perform operation with $j$, $i$, $0$ Perform operation with $j$, $i$, $0$ Perform operation with $j$, $i$, $b_i$ Perform operation with $j$, $i$, $b_i$ Perform operation with $i$, $j$, $b_j$ Perform operation with $i$, $j$, $b_j$ We need to check the two cases. In the first case, the minimum cost will be $\sum_{i=1}^n |a_i - b_i|$. In the second case, we want the minimum cost to create a submask-supermask pair in $b$. Solution 1 For explanation simplicity, consider the graph $G$ with $2m$ vertices, representing the numbers from $1$ to $2m$. In this graph, there's an unweighted edge from vertex $i$ to vertex $i+1$, and from vertex $i$ to all submask vertices. Color all vertices in which its value appears in $b$. The answer is the shortest path between all pairs of distinct colored vertices. The implementation itself (see below), uses dynamic programming consisting of three phases. The dynamic programming tracks the first and second closest vertex to each vertex, because the first closest vertex would be itself. Propagate each colored vertices up (from $i$ to $i+1$). Propagate each colored vertices up (from $i$ to $i+1$). Propagate to the submasks (from $i$ to its submasks). Propagate to the submasks (from $i$ to its submasks). Propagate down (from $i$ to $i-1$). Propagate down (from $i$ to $i-1$). Time complexity: $\mathcal{O}(n \log n + m \log m)$ per test case. The $\log n$ factor is from the implementation which checks for duplicates in $b$ by sorting.
[ "bitmasks", "constructive algorithms", "dp" ]
3,300
#pragma GCC optimize("Ofast") #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define ll long long #define ld long double #define nline "\n" #define f first #define s second const ll INF_MUL=1e13; const ll INF_ADD=1e18; #define sz(x) (ll)x.size() #define vl vector<ll> #define all(x) x.begin(),x.end() #define rall(x) x.rbegin(),x.rend() mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; typedef tree<pair<ll,ll>, null_type, less<pair<ll,ll>>, rb_tree_tag, tree_order_statistics_node_update> ordered_pset; //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- const ll MOD=998244353; const ll MAX=500500; void solve(){ ll n,m; cin>>n>>m; m*=2; vector<ll> a(n+5),b(n+5),closest(m+5,-INF_ADD); for(ll i=1;i<=n;i++){ cin>>a[i]; } vector<ll> found(m+5,0); for(ll i=1;i<=n;i++){ cin>>b[i]; closest[b[i]]=b[i]; found[b[i]]=1; } ll ans=0; for(ll i=1;i<=n;i++){ ans+=abs(a[i]-b[i]); } vector<ll> c=b; sort(c.begin()+1,c.begin()+n+1); for(ll i=1;i<=n-1;i++){ ans=min(ans,c[i+1]-c[i]); } for(ll i=1;i<=m;i++){ closest[i]=max(closest[i],closest[i-1]); } vector<ll> dp(m+5,INF_ADD),trav[m+5]; for(ll i=m;i>=0;i--){ ans=min(ans,dp[i]+i-closest[i]); if(closest[i]>=0){ trav[closest[i]].push_back(i); } for(auto it:trav[i]){ dp[it]=min(dp[it],it-closest[it]); for(ll j=0;j<=21;j++){ ll v=(1<<j); if(it&v){ dp[it^v]=min(dp[it^v],dp[it]); } } } for(ll j=0;j<=21;j++){ ll v=(1<<j); if(i&v){ dp[i^v]=min(dp[i^v],dp[i]); } } } cout<<ans<<nline; return; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll test_cases=1; cin>>test_cases; while(test_cases--){ solve(); } cout<<fixed<<setprecision(15); cerr<<"Time:"<<1000*((double)clock())/(double)CLOCKS_PER_SEC<<"ms\n"; }
2077
G
RGB Walking
\begin{quote} Red and Blue and Green - fn and Silentroom \hfill ⠀ \end{quote} You are given a connected graph with $n$ vertices and $m$ bidirectional edges with weight not exceeding $x$. The $i$-th edge connects vertices $u_i$ and $v_i$, has weight $w_i$, and is assigned a color $c_i$ ($1 \leq i \leq m$, $1 \leq u_i, v_i \leq n$). The color $c_i$ is either red, green, or blue. It is guaranteed that there is \textbf{at least} one edge of each color. For a walk where vertices and edges may be repeated, let $s_r, s_g, s_b$ denote the sum of the weights of the red, green, and blue edges that the walk passes through, respectively. If an edge is traversed multiple times, each traversal is counted separately. Find the minimum value of $\max(s_r, s_g, s_b) - \min(s_r, s_g, s_b)$ over all possible walks from vertex $1$ to vertex $n$.
It might help to solve this task with two colors first. As in, minimize the difference between red and blue. Walking back and forth can do wonders. Let the difference between the red edges and the blue edges passed be $d$. Let the edge weights of the red edges be $r_1, r_2, \ldots$ and the blue edges be $b_1, b_2, \ldots$. Let $c = gcd(r_1, r_2, \ldots, b_1, b_2, \ldots)$ and $C = lcm(r_1, r_2, \ldots, b_1, b_2, \ldots)$. We can find a walk with $d=0$ which passes every edge and returns to vertex $1$. For each edge, walk to one of its endpoint, walk that edge, and then walk back to vertex $1$ using the same walk. This way, we passed through every edge an even number of times. We will now walk back and forth using the edges we passed. This way, we can add to $d$ by some linear combination of $2r_1, 2r_2, \ldots, 2b_1, 2b_2, \ldots$. Because $d$ is divisible by $2c$, we can add to it such that $d=0$ by Bézout's identity. Note: About the "can add by some linear combination", there's the slight caveat that we can only add the red and subtract the blue. We can subtract the red (or similarly, add the blue) by first subtracting from blue by $2C$, then add back red just so that it is deficit by the edge weight. After passing every edge and returning to vertex $1$ with $d=0$, we can walk from vertex $1$ to vertex $n$. If the walk have $d$ divisible by $2c$, then the answer is $0$ and $c$ otherwise. The proof of this is similar to the proof above. To check if a walk with $d$ divisible by $2c$ exist or not, create a state graph where each vertex is either "reach the vertex with $d$ divisible by $2c$" and "$d$ not divisible by $2c$". In the two-color version (in Hint 1), we created a state graph on the parity. Can a similar idea be used? Think about each color separately first. Let the edge weights of the red edges be $r_1, r_2, \ldots$, the green edges be $g_1, g_2, \ldots$ and the blue edges be $b_1, b_2, \ldots$. the edge weights of the red edges be $r_1, r_2, \ldots$, the green edges be $g_1, g_2, \ldots$ and the blue edges be $b_1, b_2, \ldots$. $\gcd(r_1, r_2, \ldots)$, $\gcd(g_1, g_2, \ldots)$ and $\gcd(b_1, b_2, \ldots)$ be $c_r, c_g, c_b$. $\gcd(r_1, r_2, \ldots)$, $\gcd(g_1, g_2, \ldots)$ and $\gcd(b_1, b_2, \ldots)$ be $c_r, c_g, c_b$. the sum of weights of red, green and blue edges traversed be $d_r, d_g, d_b$. the sum of weights of red, green and blue edges traversed be $d_r, d_g, d_b$. Define $<d_{r_1}, d_{g_1}, d_{b_1}> = <d_{r_2}, d_{g_2}, d_{b_2}>$ only if $d_{r_1}-d_{g_1} = d_{r_2}-d_{g_2}$, $d_{r_1}-d_{b_1} = d_{r_2}-d_{b_2}$ and $d_{g_1}-d_{b_1} = d_{g_2}-d_{b_2}$. In a similar manner to hint 1, there's a walk that passes through every edge and have $<d_r, d_g, d_b> = <0, 0, 0>$. Furthermore, if we have $<d_r, d_g, d_b>$, then we can have $<d_r + 2g_r, d_g, d_b>$ and $<d_r - 2g_r, d_g, d_b>$. The analogous statement holds for the other two colors. Consequently, from any reachable $<d_r, d_g, d_b>$, we can have $<s_r, s_g, s_b>$, where $s_r$ is either $0$ or $c_r$ depending on whether $d_r \equiv 0$ ($\mod 2c_r$) or $d_r \equiv c_r$ ($\mod 2c_r$). The idea holds similarly for the other two colors. This invites us to look at each vertex as $8$ possible states, corresponding to $3$ binary options of each color. We simply need to solve the answer for each reachable state then take the minimum. Each state corresponds to the following system of linear congruences. $d_r \equiv s_r (\mod 2c_r)$ $d_g \equiv s_g (\mod 2c_g)$ $d_b \equiv s_b (\mod 2c_b)$ We aim to minimize $\max(d_r, d_g, d_b) - \min(d_r, d_g, d_b)$ over all triplets which satisfy the conditions. To do so, we will fix one of them, which we'll suppose is $d_r$, as the minimum. Denote $f_g(p)$ and $f_b(p)$ as the minimum possible $d_g - (d_r + 2pc_r)$ and $r_b - (d_r + 2pc_r)$ where $r_g, r_p \geq d_r + 2pc_r$. We want to find $\min_{k \in \mathbb{Z}} \max(f_g(k), f_b(k))$ Observe that $f_g(k + c_g) = f_g(p)$ and $fb(k + c_b) = f_b(p)$. By the Chinese remainder theorem, the expression above reduces to $\min_{0 \leq k < \gcd(c_g, c_b)} \max(\min_{(k_g \mod \gcd(c_g, c_b) = k)} f_g(k_g), \min_{(k_b \mod \gcd(c_g, c_b) = k)} f_b(k_b))$ Which can be evaluated in $\mathcal{O}(x)$. Time complexity: $\mathcal{O}(n \log x + x)$ per test case. The logarithmic factor is from gcd computations.
[ "bitmasks", "chinese remainder theorem", "dfs and similar", "graphs", "number theory" ]
3,500
#include <bits/stdc++.h> #define int long long using namespace std; typedef pair<int, int> pii; void test_case() { // read input int n, m, x; cin >> n >> m >> x; vector<tuple<int, int, int>> edge_list[3]; map<char, int> color_map = {{'r', 0}, {'g', 1}, {'b', 2}}; for (int i = 1; i <= m; i++) { int u, v, w; char c; cin >> u >> v >> w >> c; edge_list[color_map[c]].emplace_back(u, v, w); } // graph constuction int color_gcd[3]; vector<pii> edge[n+1]; for (int i = 0; i < 3; i++) { color_gcd[i] = get<2>(edge_list[i][0]); for (auto [u, v, w] : edge_list[i]) color_gcd[i] = __gcd(color_gcd[i], w); for (auto [u, v, w] : edge_list[i]) { int val = (1<<i)*(w/color_gcd[i]%2); edge[u].emplace_back(v, val); edge[v].emplace_back(u, val); } } // bfs bool visited[n+1][8]; memset(visited, 0, sizeof(visited)); queue<pii> bfs_q; bfs_q.emplace(1, 0); while (!bfs_q.empty()) { auto [u, mask] = bfs_q.front(); bfs_q.pop(); if (visited[u][mask]) continue; visited[u][mask] = true; for (auto [v, val] : edge[u]) bfs_q.emplace(v, mask^val); } // solve answer for each mask int ans = INT_MAX; for (int mask = 0; mask < 8; mask++) { if (!visited[n][mask]) continue; for (int i = 0; i < 3; i++) { int ssz[2]; for (int j = 0, cj = 0; j < 3; j++) { if (i == j) continue; ssz[cj++] = color_gcd[j]; } int sgcd = 2*__gcd(ssz[0], ssz[1]); int seq[2][sgcd]; for (int j = 0; j < sgcd; j++) seq[0][j] = seq[1][j] = (int)1e9; for (int j = 0, cj = 0; j < 3; j++) { if (i == j) continue; for (int k = 0; k < 2*ssz[cj]; k++) { int vi = ((mask>>i)&1)*color_gcd[i]; int mi = 2*color_gcd[i]; int vj = ((mask>>j)&1)*color_gcd[j]; int mj = 2*color_gcd[j]; seq[cj][k%sgcd] = min(seq[cj][k%sgcd], ((vj - vi - k*mi)%mj + mj)%mj); } cj++; } for (int k = 0; k < sgcd; k++) ans = min(ans, max(seq[0][k], seq[1][k])); } } cout << ans << "\n"; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) test_case(); return 0; } // model solution
2078
A
Final Verdict
\begin{quote} Testify - void (Mournfinale) feat. 星熊南巫 \end{quote} You are given an array $a$ of length $n$, and must perform the following operation until the length of $a$ becomes $1$. Choose a positive integer $k < |a|$ such that $\frac{|a|}{k}$ is an integer. Split $a$ into $k$ subsequences$^{\text{∗}}$ $s_1, s_2, \ldots, s_k$ such that: - Each element of $a$ belongs to exactly one subsequence. - The length of every subsequence is equal. After this, replace $a = \left[ \operatorname{avg}(s_1), \operatorname{avg}(s_2), \ldots, \operatorname{avg}(s_k) \right] $, where $\operatorname{avg}(s) = \frac{\sum_{i = 1}^{|s|} s_i}{|s|}$ is the average of all the values in the subsequence. For example, $\operatorname{avg}([1, 2, 1, 1]) = \frac{5}{4} = 1.25$. Your task is to determine whether there exists a sequence of operations such that after all operations, $a = [x]$. \begin{footnotesize} $^{\text{∗}}$A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by the deletion of several (possibly, zero or all) elements. \end{footnotesize}
Something doesn't change after each operation. The average of the entire array doesn't change after each operation. Simply check whether the average value of $a$ is $x$ or not. Time complexity: $\mathcal{O}(n)$ per test case.
[ "math" ]
800
for test_case in range(int(input())): n, x = [int(_) for _ in input().split()] a = [int(_) for _ in input().split()] if sum(a) == n*x: print("YES") else: print("NO") # model solution
2078
B
Vicious Labyrinth
\begin{quote} Axium Crisis - ak+q \end{quote} There are $n$ cells in a labyrinth, and cell $i$ ($1 \leq i \leq n$) is $n - i$ kilometers away from the exit. In particular, cell $n$ is the exit. Note also that each cell is connected to the exit but is not accessible from any other cell in any way. In each cell, there is initially exactly one person stuck in it. You want to help everyone get as close to the exit as possible by installing a teleporter in each cell $i$ ($1 \leq i \leq n$), which translocates the person in that cell to another cell $a_i$. The labyrinth owner caught you in the act. Amused, she let you continue, but under some conditions: - Everyone must use the teleporter exactly $k$ times. - No teleporter in any cell can lead to the same cell it is in. Formally, $i \neq a_i$ for all $1 \leq i \leq n$. You must find a teleporter configuration that minimizes the sum of distances of all individuals from the exit after using the teleporter exactly $k$ times while still satisfying the restrictions of the labyrinth owner. If there are many possible configurations, you can output any of them.
Try to put as many people in cell $n$ as possible. The minimum sum of distances will always be $1$. The following configuration gives $1$ as the sum of distances. For odd $k$: $n, n, \ldots, n, n, n-1$ For even $k$: $n-1, n-1, \ldots, n-1, n, n-1$ And the sum of distances cannot be $0$. Look at this as a directed (or more specifically, a functional) graph. There will be a cycle, and people in the same cycle will never be in the same cell, so not everyone can simultaneously be in cell $n$. Time complexity: $\mathcal{O}(n)$ per test case.
[ "constructive algorithms", "graphs", "greedy", "implementation", "math" ]
1,100
for test_case in range(int(input())): n, k = [int(_) for _ in input().split()] if k % 2 == 0: for i in range(n-2): print(n-1, end = ' ') print(n, end = ' ') print(n-1) else: for i in range(n-2): print(n, end = ' ') print(n, end = ' ') print(n-1) # model solution
2078
D
Scammy Game Ad
Consider the following game. In this game, a level consists of $n$ pairs of gates. Each pair contains one left gate and one right gate. Each gate performs one of two operations: - \textbf{Addition Operation} (+ a): Increases the number of people in a lane by a constant amount $a$. - \textbf{Multiplication Operation} (x a): Multiplies the current number of people in a lane by an integer $a$. This means the number of people increases by $(a - 1)$ times the current count in that lane. The additional people gained from each operation can be assigned to either lane. However, people already in a lane \textbf{cannot} be moved to the other lane. Initially, there is one person in each lane. Your task is to determine the maximum total number of people that can be achieved by the end of the level.
It is optimal to place everyone on the same lane. Think about the multiplier. It is best to think of each $\tt{+}$ as "how much can we multiply this by". This is the greedy solution. When we get more people, place all to where the $\tt{x}$ will occur first. If both lanes have the next multiply at the same gate pair, then choose the one with higher multiply. If the multiply is the same, look to the next multiply. It's easier to think of $\tt{+}$ as $\tt{x} 1$. The idea is as follows. Consider the range of gate pairs between two pairs with different multiply, and the pairs in the range all have the same multiply. You have $l$ people on the left side and $r$ on the right side before you enter the range. In this range, you will gain a constant number of people, say $x$, regardless of your actions here. You choose to allocate $y$ to the left side. At the end of the range, there's a pair of gates $\tt{x} a$ $\tt{x} b$ where $a > b$ (same argument for case $a < b$). After passing the gate, you will gain $(a-1)(l+y) + (b-1)(r+x-y)$ more people. With the current number people of $l+y$ on the left side and $r+x-y$ on the right side, we can see that maximizing $y$ is the optimal choice, because there always exist an allocation such that both number of people on the left and right side will exceed those with lower selection of $y$. Time complexity: $\mathcal{O}(n)$ per test case. $\mathcal{O}(n^2)$ implementations are also acceptable. This is the dynamic programming solution. Let $dp_l[i]$ and $dp_r[i]$ be the maximum possible multiplication possible that can be applied if a person enters the $i$-th left and right gate, respectively. Then we have the following equation (only for left is written, it's the same for the right). If the gate is $\tt{+}$ $dp_l[i] = dp_l[i+1]$ If the gate is $\tt{x}$ by $a$ $dp_l[i] = dp_l[i+1] + (a-1)\max(dp_l[i+1], dp_r[i+1])$ For each $\tt{+}$, we choose to place people at the side with more multiplication. Time complexity: $\mathcal{O}(n)$ per test case.
[ "dp", "greedy", "implementation" ]
1,800
def test_case(): n = int(input()) op = [[] for _ in range(n+1)] val = [[] for _ in range(n+1)] for i in range(1, n + 1): tmp = input().split() op[i] = [tmp[0], tmp[2]] val[i] = [int(tmp[1]), int(tmp[3])] op[0] = ['+', '+'] val[0] = [1, 1] dp = [[0, 0] for _ in range(n + 2)] dp[n + 1][0] = dp[n + 1][1] = 1 for i in range(n, 0, -1): dp[i][0] = (dp[i + 1][0] + (val[i][0] - 1) * max(dp[i + 1][0], dp[i + 1][1])) if op[i][0] == 'x' else dp[i + 1][0] dp[i][1] = (dp[i + 1][1] + (val[i][1] - 1) * max(dp[i + 1][0], dp[i + 1][1])) if op[i][1] == 'x' else dp[i + 1][1] ans = 0 for i in range(1, n + 1): sm = 0 if op[i][0] == '+': sm += val[i][0] if op[i][1] == '+': sm += val[i][1] ans += sm * max(dp[i + 1][0], dp[i + 1][1]) ans += dp[1][0] ans += dp[1][1] print(ans) t = int(input()) for _ in range(t): test_case() # model solution, dp
2081
A
Math Division
Ecrade has an integer $x$. He will show you this number in the form of a binary number of length $n$. There are two kinds of operations. - Replace $x$ with $\left\lfloor \dfrac{x}{2}\right\rfloor$, where $\left\lfloor \dfrac{x}{2}\right\rfloor$ is the greatest integer $\le \dfrac{x}{2}$. - Replace $x$ with $\left\lceil \dfrac{x}{2}\right\rceil$, where $\left\lceil \dfrac{x}{2}\right\rceil$ is the smallest integer $\ge \dfrac{x}{2}$. Ecrade will perform several operations until $x$ becomes $1$. Each time, he will independently choose to perform either the first operation or the second operation with probability $\frac{1}{2}$. Ecrade wants to know the expected number of operations he will perform to make $x$ equal to $1$, modulo $10^9 + 7$. However, it seems a little difficult, so please help him!
Consider $x$ in binary form. What are all possible numbers of operations to make $x$ equal to $1$? Consider using dynamic programming to calculate the answer. Similar to the previous problem, the possible number of operations can only be $n-1$ or $n$, depending on whether a carry-over occurs in $x$ during the $(n-1)$ -th operation. We can use dynamic programming to compute the probability of a carry-over occurring during the $(n-1)$ -th operation. Let $f_i$ denote the probability of a carry-over occurring at the $i$ -th least significant bit. The recurrence relation is: $f_i = \begin{cases} \dfrac{1}{2} \times f_{i-1} & x_i = 0 \\ \dfrac{1}{2} \times (1 - f_{i-1}) + f_{i-1} & x_i = 1 \end{cases}$ The final answer is given by $n-1+f_{n-1}$. The time complexity is $O(\sum n)$.
[ "bitmasks", "dp", "math", "probabilities" ]
1,800
#include<bits/stdc++.h> using namespace std; typedef long long ll; const ll inv2 = 5e8 + 4,mod = 1e9 + 7; ll t,n; char s[1000009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } int main(){ t = read(); while (t --){ n = read(),scanf("%s",s + 1); ll ans = 0; for (ll i = n;i > 1;i -= 1) ans = (ans + (s[i] == '1')) * inv2 % mod; printf("%lld\n",(n - 1 + ans) % mod); } return 0; }
2081
B
Balancing
Ecrade has an integer array $a_1, a_2, \ldots, a_n$. It's guaranteed that for each $1 \le i < n$, $a_i \neq a_{i+1}$. Ecrade can perform several operations on the array to make it strictly increasing. In each operation, he can choose two integers $l$ and $r$ ($1 \le l \le r \le n$) and replace $a_l, a_{l+1}, \ldots, a_r$ with any $r-l+1$ integers $a'_l, a'_{l+1}, \ldots, a'_r$ satisfying the following constraint: - For each $l \le i < r$, the comparison between $a'_i$ and $a'_{i+1}$ is the same as that between $a_i$ and $a_{i+1}$, i.e., if $a_i < a_{i + 1}$, then $a'_i < a'_{i + 1}$; otherwise, if $a_i > a_{i + 1}$, then $a'_i > a'_{i + 1}$; otherwise, if $a_i = a_{i + 1}$, then $a'_i = a'_{i + 1}$. Ecrade wants to know the minimum number of operations to make the array strictly increasing. However, it seems a little difficult, so please help him!
Let's only consider the comparison between adjacent pairs first. Call a pair $(a_i,a_{i+1})$ an inversion pair if $a_i>a_{i+1}$. In each operation, how can the number of inversion pairs change? Under what circumstances can we decrease the maximum number of inversion pairs in every operation? Let's only consider the comparison between adjacent pairs first. Call a pair $(a_i,a_{i+1})$ an inversion pair if $a_i>a_{i+1}$. Our goal is to decrease the number of inversion pairs to zero. If we choose to replace $a_l,a_{l+1},\ldots,a_r$, only the comparison between $(a_{l-1},a_l)$ and $(a_{r},a_{r+1})$ can change, which means we can eliminate at most two inversion pairs in one operation. Let $s$ be the number of inversion pairs in $a_1,a_2,\ldots,a_n$, then a lower bound of the answer is $l=\left\lceil\dfrac{s}{2}\right\rceil$. In order to obtain the lower bound $l$, each operation must eliminate exactly two inversion pairs. This necessitates that we cannot alter any numbers before the first element $a_{p_1}$ of the first inversion pair or after the second element $a_{p_2}$ of the last inversion pair. (Why?) An intuitive idea is that the difference between $a_{p_1}$ and $a_{p_2}$ should be as large as possible (more precisely, $a_{p_2} - a_{p_1} \geq p_2 - p_1$), so that a strictly increasing sequence can be "accommodated" between them. It is not difficult to constructively prove by recursion that this condition is both necessary and sufficient. In other words, when $a_{p_2} - a_{p_1} \geq p_2 - p_1$, the answer is $l$; otherwise, an additional operation is required, making the answer $l+1$. It's not difficult to prove that the answer in this case is $l$. (Why?) The time complexity is $O(\sum n)$.
[ "greedy" ]
2,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,a[200009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } int main(){ t = read(); while (t --){ n = read(); for (ll i = 1;i <= n;i += 1) a[i] = read(); ll ans = 0,pos1 = 0,pos2 = 0; for (ll i = 1;i < n;i += 1) if (a[i] > a[i + 1]){ ans += 1,pos2 = i + 1; if (!pos1) pos1 = i; } if ((ans & 1) || (pos1 && a[pos2] - a[pos1] < pos2 - pos1)) printf("%lld\n",(ans >> 1) + 1); else printf("%lld\n",ans >> 1); } return 0; }
2081
C
Quaternary Matrix
A matrix is called quaternary if all its elements are $0$, $1$, $2$, or $3$. Ecrade calls a quaternary matrix $A$ good if the following two properties hold. - The bitwise XOR of all numbers in each row of matrix $A$ is equal to $0$. - The bitwise XOR of all numbers in each column of matrix $A$ is equal to $0$. Ecrade has a quaternary matrix of size $n \times m$. He is interested in the minimum number of elements that need to be changed for the matrix to become good, and he also wants to find one of the possible resulting matrices. However, it seems a little difficult, so please help him!
Do we really have to consider the problem on the whole matrix? Use greedy algorithm and guess some possible conclusions. Can you prove them (or construct some counterexamples) ? The problem can be rephrased as follows: Let the XOR sum of each row be $r_1, r_2, \ldots, r_n$, and the XOR sum of each column be $c_1, c_2, \ldots, c_m$. In each operation, we can choose any $1 \le i \le n$, $1 \le j \le m$, and $0 \le x \le 3$, then let $r_i \leftarrow r_i \oplus x$ and $c_j \leftarrow c_j \oplus x$. The goal is to determine the minimum number of operations required to make all $r_1, r_2, \ldots, r_n$ and $c_1, c_2, \ldots, c_m$ zero. Let $R_x\ ( 0 \le x \le 3 )$ denote the count of $x$ in $r_1, r_2, \ldots, r_n$, and $C_x$ denote the count of $x$ in $c_1, c_2, \ldots, c_m$. A trivial upper bound for the answer is $s = R_1 + R_2 + R_3 + C_1 + C_2 + C_3$, which corresponds to the scenario where each operation only zeros out one of $r_i$ and $c_j$. To reduce the number of operations, we can consider grouping the non-zero elements in $r_1, \ldots, r_n, c_1, \ldots, c_m$ into disjoint groups where: The XOR sum of each group is zero. Each group contains at least one element from $r$ and one from $c$. For such a group, we can reduce the number of operations by one, as there always exists an operation which can zero out both $r_i$ and $c_j$. Thus, the goal is to maximize the number of such groups, and the minimum number of operations will be $s - \text{(number of groups formed)}$. Define the following group types: $P_2$: Groups of the form $(R_1,C_1)$, $(R_2,C_2)$ or $(R_3,C_3)$. $P_3$: Groups of the form $(R_1,R_2,C_3)$, $(R_1,C_2,C_3)$, $(R_1,C_2,R_3)$, $(C_1,C_2,R_3)$, $(C_1,R_2,R_3)$ or $(C_1,R_2,C_3)$. $P_4$: Groups of the form $(R_1,R_1,C_2,C_2)$, $(R_1,R_1,C_3,C_3)$, $(R_2,R_2,C_1,C_1)$, $(R_2,R_2,C_3,C_3)$, $(R_3,R_3,C_1,C_1)$ or $(R_3,R_3,C_2,C_2)$. Conclusion 1: There exists an optimal solution where all groups are of the form $P_2$, $P_3$, or $P_4$. Each group must have size at least 2. Groups of size 2 or 3 can only be $P_2$ or $P_3$. Groups of size 4 not conforming to $P_4$ (e.g., $(R_1, R_1, R_1, C_1)$) can be decomposed into at least one $P_2$. Larger groups can be decomposed into combinations of $P_2$, $P_3$, and $P_4$. Conclusion 2: There exists an optimal solution where all $P_3$ groups share the same structure, and so do all $P_4$ groups. Two different $P_3$ groups can be decomposed into at least two $P_2$ or at least one $P_2$ and one $P_4$. Two different $P_4$ groups can be decomposed into at least two $P_2$ or at least two $P_3$. Conclusion 3: There exists an optimal solution where the elements in $P_4$ groups are a subset of those in $P_3$ groups (e.g., if $P_3$ is $(R_1, R_2, C_3)$, then $P_4$ can only be $(R_1, R_1, C_3, C_3)$ or $(R_2, R_2, C_3, C_3)$). The proof is analogous to Conclusion 2 and is left as an exercise. Based on these conclusions, the optimal strategy is: first form as many $P_2$ groups as possible; then form as many $P_3$ groups as possible from the remaining elements; then form as many $P_4$ groups as possible from the remaining elements. After grouping, each group can be zeroed out with one less operation. Note that the remaining ungrouped elements require individual operations. The time complexity is $O(\sum nm)$.
[ "bitmasks", "constructive algorithms", "greedy", "implementation", "matrices" ]
2,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,m,a[1009][1009]; char s[1009]; vector <ll> row[4],col[4]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } int main(){ t = read(); while (t --){ n = read(),m = read(); for (ll i = 1;i <= 3;i += 1) row[i].clear(),col[i].clear(); for (ll i = 1;i <= n;i += 1){ scanf("%s",s + 1); for (ll j = 1;j <= m;j += 1) a[i][j] = s[j] - '0'; } for (ll i = 1;i <= n;i += 1){ ll sum = 0; for (ll j = 1;j <= m;j += 1) sum ^= a[i][j]; if (sum) row[sum].emplace_back(i); } for (ll j = 1;j <= m;j += 1){ ll sum = 0; for (ll i = 1;i <= n;i += 1) sum ^= a[i][j]; if (sum) col[sum].emplace_back(j); } ll ans = 0; for (ll i = 1;i <= 3;i += 1){ while (row[i].size() && col[i].size()){ ans += 1; a[row[i].back()][col[i].back()] ^= i; row[i].pop_back(),col[i].pop_back(); } } for (ll i = 1;i <= 3;i += 1){ ll j = i % 3 + 1,k = j % 3 + 1; while (row[i].size() && col[j].size() && col[k].size()){ ans += 2; a[row[i].back()][col[j].back()] ^= j; a[row[i].back()][col[k].back()] ^= k; row[i].pop_back(),col[j].pop_back(),col[k].pop_back(); } while (col[i].size() && row[j].size() && row[k].size()){ ans += 2; a[row[j].back()][col[i].back()] ^= j; a[row[k].back()][col[i].back()] ^= k; col[i].pop_back(),row[j].pop_back(),row[k].pop_back(); } } for (ll i = 1;i <= 3;i += 1) for (ll j = 1;j <= 3;j += 1) if (i != j){ while (row[i].size() >= 2 && col[j].size() >= 2){ ll r1 = row[i].back(); row[i].pop_back(); ll r2 = row[i].back(); row[i].pop_back(); ll c1 = col[j].back(); col[j].pop_back(); ll c2 = col[j].back(); col[j].pop_back(); ans += 3; a[r1][c1] ^= i; a[r2][c1] ^= (i ^ j); a[r2][c2] ^= j; } } for (ll i = 1;i <= 3;i += 1){ while (row[i].size()) ans += 1,a[row[i].back()][1] ^= i,row[i].pop_back(); while (col[i].size()) ans += 1,a[1][col[i].back()] ^= i,col[i].pop_back(); } printf("%lld\n",ans); for (ll i = 1;i <= n;i += 1,puts("")) for (ll j = 1;j <= m;j += 1) printf("%lld",a[i][j]); } return 0; }
2081
D
MST in Modulo Graph
You are given a complete graph with $n$ vertices, where the $i$-th vertex has a weight $p_i$. The weight of the edge connecting vertex $x$ and vertex $y$ is equal to $\operatorname{max}(p_x, p_y) \bmod \operatorname{min}(p_x, p_y)$. Find the smallest total weight of a set of $n - 1$ edges that connect all $n$ vertices in this graph.
There are only $O(n\log n)$ edges that are truly useful in the whole graph. First, for vertices with the same weight, they can naturally be treated as a single vertex. We observe that in the interval of weights $(kx,(k+1)x)\ (k\ge 1)$, only the smallest $y$ is useful. It is because, if $x<y<z<2x$, connecting edges $(x,y)$ and $(y,z)$ will always be better than connecting $(x,y)$ and $(x,z)$. Therefore, for a vertex with weight $x$, we enumerate $k = x , 2 x , \ldots , \lfloor \frac{n}{x}\rfloor\cdot x$. For each $k$, we connect $x$ to the smallest $y$ that is greater than or equal to $k$. It can be proven that this approach guarantees a connected graph (since connecting only the first edge larger than $x$ already forms a connected structure). This method generates $O(n\log n)$ edges (due to the harmonic series property). Directly applying Kruskal's algorithm would result in a time complexity of $O(n\log^2 n)$. With radix sort, this can be optimized to $O(n\log n)$.
[ "constructive algorithms", "dsu", "graphs", "greedy", "math", "number theory", "sortings", "trees" ]
2,600
#include<iostream> #include<cstdio> #include<algorithm> #include<string.h> #include<vector> #include<queue> #include<map> #include<ctime> #include<bitset> #include<set> #include<math.h> //#include<unordered_map> #define fi first #define se second #define mp make_pair #define pii pair<int,int> #define pb push_back #define pil pair<int,long long> #define pll pair<long long,long long> #define vi vector<int> #define vl vector<long long> #define ci ios::sync_with_stdio(false) //#define int long long using namespace std; typedef long long ll; typedef unsigned long long ull; int read(){ char c=getchar(); ll x=1,s=0; while(c<'0'||c>'9'){ if(c=='-')x=-1;c=getchar(); } while(c>='0'&&c<='9'){ s=s*10+c-'0';c=getchar(); } return s*x; } const int N=5e5+55; int MAXN=0; int n,tot,ans,maxx,f[N],siz[N],p[N],bj[N],pre[N],suf[N],pos[N]; struct node{ int from,to,dis; }a[N*20]; int cmp(node x,node y){ return x.dis<y.dis; } int find(int x){ if(f[x]!=x)return f[x]=find(f[x]); else return x; } void merge(int x,int y){ x=find(x);y=find(y); if(siz[x]<siz[y])swap(x,y); siz[x]+=siz[y]; f[y]=x; } int T; int main(){ T=read(); while(T--) { tot=ans=maxx=0; for(int i=1;i<=MAXN;++i) { f[i]=siz[i]=p[i]=bj[i]=pre[i]=suf[i]=pos[i]=0; } for(int i=0;i<=MAXN*19;++i) a[i].from=a[i].to=a[i].dis=0; n=read(); MAXN=n; for(int i=1;i<=n;i++)p[i]=read(),bj[p[i]]=1,maxx=max(maxx,p[i]),MAXN=max(MAXN,p[i]); sort(p+1,p+n+1); for(int i=1;i<=maxx;i++){ if(bj[i])pre[i]=i; else pre[i]=pre[i-1]; } for(int i=maxx;i>=1;i--){ if(bj[i])suf[i]=i; else suf[i]=suf[i+1]; } for(int i=1;i<=n;i++)pos[p[i]]=i; for(int i=1;i<=n;i++){ if(p[i]==p[i-1]){ a[++tot]={i,i-1,0}; continue; } for(int k=1;k*p[i]<=maxx;k++){ int tmy=0; if(bj[k*p[i]] and k!=1){ a[++tot]={pos[k*p[i]],i,0}; continue; } if(suf[k*p[i]+1]<=(k+1)*p[i])tmy=suf[k*p[i]+1]; if(!tmy)continue; int cost=abs(k*p[i]-tmy); a[++tot]={pos[tmy],i,cost}; } } sort(a+1,a+tot+1,cmp); for(int i=1;i<=n;i++)f[i]=i,siz[i]=1; for(int i=1;i<=tot;i++){ if(find(a[i].from)!=find(a[i].to)){ merge(a[i].from,a[i].to); ans+=a[i].dis; } } cout<<ans<<endl; } return 0; }
2081
E
Quantifier
Given a rooted tree with $n+1$ nodes labeled from $0$ to $n$, where the root is node $0$, and \textbf{its only child is node $1$}. There are $m$ \textbf{distinct} chips labeled from $1$ to $m$, each colored either black or white. Initially, they are arranged on edge $(0,1)$ from top to bottom in ascending order of labels. \begin{center} {\small The initial position of the chips. Tree nodes are shown in blue.} \end{center} You can perform the following operations any number of times (possibly zero) in any order: - Select two edges ($u,v$) and ($v,w$) such that $u$ is the parent of $v$ and $v$ is the parent of $w$, where edge ($u,v$) contains at least one chip. Move the \textbf{bottommost} chip on edge ($u,v$) to the \textbf{topmost} place on edge ($v,w$), i. e., above all existing chips on ($v,w$). - Select two edges ($u,v$) and ($v,w$) such that $u$ is the parent of $v$ and $v$ is the parent of $w$, where edge ($v,w$) contains at least one chip. Move the \textbf{topmost} chip on edge ($v,w$) to the \textbf{bottommost} place on edge ($u,v$), i. e., below all existing chips on ($u,v$). - Select two \textbf{adjacent} chips of the same color on the same edge, and swap their positions. \begin{center} {\small Permitted operations.} \end{center} Each chip $i$ has a movement range, defined as all edges on the simple path from the root to node $d_i$. During operations, you must ensure that no chip is moved to an edge outside its movement range. Finally, you must move all chips back to edge $(0,1)$. It can be found that the order of the chips may change. Compute the number of possible permutations of chips for the final arrangement on the edge $(0,1)$ modulo $998\,244\,353$. A permutation of chips is defined as a sequence of length $m$ consisting of the \textbf{labels} of the chips from top to bottom.
Move each chip as deep as possible in descending order of labels. Can we simplify the operations after that? Now we only need to move the chips upward and swap adjacent chips with the same color. What can we do after that? We can perform dynamic programming (DP) to calculate the numbers. What information do we need to record? We need to record the color and the length of the top monochromatic segment. How can we perform the DP in $\mathcal{O}(m^2)$ time complexity? First, in descending order of labels, move each chip to the deepest possible position successively. It can be shown that this allows each chip to reach the theoretically deepest position it can attain. Consequently, every final state can be obtained from this configuration by performing only upward moves of chips and swaps of adjacent chips with the same color. Next comes the process of moving chips upward while performing dynamic programming (DP). Let $e_u$ denote the edge from node $u$ to its parent. Assume we have decided the order of all the chips in subtree $u$ (except the ones on $e_u$), and we need to merge them with the original chips on $e_u$. If the bottom chip on $e_u$ shares color with the subtree's top chip, we need to know the length of the subtree's topmost maximal monochromatic contiguous segment to calculate the number of ways to merge the two parts, i.e., if the length of the bottommost segment on $e_u$ is $x$ and the length of the topmost segment of the subtree is $y$, we have $\dbinom{x+y}{x}$ ways to combine them. So we need to record the color and the length of the top segment. Let $f_{u,0/1,i}$ denote the number of permutation schemes on $e_u$ after moving all the chips in subtree $u$ to $e_u$, where: The topmost chip on $e_u$ is black/white (0/1). The length of the topmost maximal monochromatic contiguous segment on $e_u$ is $i$. When calculating $f_{u,0/1,i}$ for all $i$, we first merge the DP states of all the subtrees of node $u$, and then merge the original chips on $e_u$ into the resulting DP states. Subtree merging: Assume we merge two subtrees $v$ and $w$. Let $S$ and $T$ denote the number of chips on $e_v$ and $e_w$ respectively, and let $g_{0/1,i}$ be a temporary DP array initialized to all zeros. Let's consider two cases. Suppose the top chip comes from $e_v$ after merging. Then the maximal monochromatic segment length from $e_w$ becomes irrelevant, and therefore let $h_c=\sum_{i=1}^T f_{w,c,i}$. If the top chip of $e_w$ would split the top segment of $e_v$, enumerate split positions. The split position should be strictly inside the top segment of $e_v$. $g_{c,i}\leftarrow g_{c,i} + \dbinom{S-i+T-1}{T-1} h_{1-c} \sum_{k=i+1}^S f_{v,c,k}\ (1\le i\le S)$ Otherwise, the position of the top chip of $e_w$ becomes irrelevant. $g_{c,i}\leftarrow g_{c,i} + \dbinom{S-i+T}{T} h_{1-c} f_{v,c,i}$ With suffix sum optimization, this achieves $\mathcal{O}(m^2)$ time complexity. If there are only chips of this color on both edges: $g_{c,S+T}\leftarrow g_{c,S+T} + \dbinom{S+T}{T} f_{v,c,S} f_{w,c,T}$ Otherwise, assume the topmost different-colored chip is from subtree $w$ after merging. Enumerate insertion positions where this chip splits the top segment of the other (not necessarily strictly inside the segment). $g_{c,i+j}\leftarrow g_{c,i+j} + \dbinom{i+j}{j} \dbinom{S-i+T-j-1}{T-j-1} f_{w,c,j} \sum_{k=i}^S f_{v,c,k}\ (0\le i\le S,\ 1\le j < T)$ (Similar transition equation for $v$.) With suffix sum optimization, this forms a tree knapsack DP with $\mathcal{O}(m^2)$ time complexity. After computing $g_{0/1,i}$, we can treat $g$ as the DP states of a subtree, and continue to perform the process above. Merging original chips on $e_u$ into the results: We first account for internal permutations of original monochromatic segments. After that, if the bottom chip on $e_u$ shares color with merged subtrees' top chip (with segment lengths $x$ and $y$), multiply the DP state by $\dbinom{x+y}{x}$. Assuming $n$ and $m$ are of the same order, the overall time complexity is $\mathcal{O}(m^2)$.
[ "combinatorics", "dp", "implementation" ]
3,300
#include <bits/stdc++.h> #define eb emplace_back using namespace std; typedef long long ll; const int p=998244353; int T,n,m,fa[5005],col[5005],d[5005],stk[5005],top,ct[5005][2]; int C[5005][5005],fac[5005],siz[5005],f[5005][2][5005],g[2][5005],ans; vector<int> to[5005],vec[5005]; inline void diff(int u,int v){ int S=siz[u],T=siz[v]; for(int x=0,A,B;x<2;++x){ A=B=0; for(int j=1;j<=T;++j)B=(B+f[v][x^1][j])%p; for(int i=S;i>=1;--i){ g[x][i]=(g[x][i]+((ll)A*C[S+T-i-1][T-1]+(ll)f[u][x][i]*C[S+T-i][T])%p*B)%p; A=(A+f[u][x][i])%p; } } } inline void same1(int u,int v){ int S=siz[u],T=siz[v]; for(int x=0,A,B;x<2;++x){ for(int i=1;i<S;++i){ if(!(A=f[u][x][i]))continue; B=0; for(int j=T;j>=0;--j){ B=(B+f[v][x][j])%p; g[x][i+j]=(g[x][i+j]+(ll)A*B%p*C[i+j][j]%p*C[S-i-1+T-j][T-j])%p; } } } } inline void same(int u,int v){ same1(u,v),same1(v,u); int S=siz[u],T=siz[v]; for(int x=0;x<2;++x) g[x][S+T]=(g[x][S+T]+(ll)f[u][x][S]*f[v][x][T]%p*C[S+T][T])%p; } inline void merge(int u,int v){ for(int i=1;i<=siz[u]+siz[v];++i)g[0][i]=g[1][i]=0; diff(u,v),diff(v,u),same(u,v); siz[u]+=siz[v]; for(int i=1;i<=siz[u];++i) f[u][0][i]=g[0][i],f[u][1][i]=g[1][i]; } void dfs(int u){ siz[u]=0; for(auto v:to[u]){ dfs(v); if(!siz[v])continue; if(siz[u])merge(u,v); else{ for(int i=1;i<=siz[v];++i) f[u][0][i]=f[v][0][i],f[u][1][i]=f[v][1][i]; siz[u]=siz[v]; } } if(vec[u].empty())return; int prd=1,L=vec[u].size(),c=vec[u][0],fir=0,lst=0,res=0; for(int i=0,j=0;i<L;i=j){ while(j<L && vec[u][i]==vec[u][j])++j; if(i==0)fir=j-i; if(j==L)lst=j-i; prd=(ll)prd*fac[j-i]%p; } for(int i=siz[u]+1;i<=siz[u]+L;++i)f[u][0][i]=f[u][1][i]=0; if(!siz[u])f[u][vec[u][L-1]][lst]=prd; else if(fir==L){ for(int i=siz[u];i>=1;--i){ f[u][c][i+L]=(ll)f[u][c][i]*C[i+L][i]%p*fac[L]%p; res=(res+f[u][c^1][i])%p; f[u][c^1][i]=0; } for(int i=1;i<L;++i)f[u][c][i]=0; f[u][c][L]=(ll)res*fac[L]%p; } else{ for(int i=1;i<=siz[u];++i){ res=(res+(ll)f[u][c][i]*C[i+fir][i]+f[u][c^1][i])%p; f[u][0][i]=f[u][1][i]=0; } f[u][vec[u][L-1]][lst]=(ll)res*prd%p; } siz[u]+=L; } int main(){ scanf("%d",&T); while(T--){ scanf("%d%d",&n,&m); for(int i=0;i<=n;++i){ to[i].clear(),vec[i].clear(); ct[i][0]=ct[i][1]=0; } for(int i=1;i<=n;++i) scanf("%d",fa+i),to[fa[i]].eb(i); for(int i=1;i<=m;++i)scanf("%d",col+i); for(int i=1;i<=m;++i)scanf("%d",d+i); for(int i=m,u;i>=1;--i){ top=0,u=d[i]; while(u)stk[++top]=u,u=fa[u]; for(int j=top;j>=1;--j){ if(j>1 && !ct[stk[j]][col[i]^1])continue; vec[stk[j]].eb(col[i]),++ct[stk[j]][col[i]]; break; } } C[0][0]=fac[0]=1; for(int i=1;i<=m;++i){ for(int j=1;j<=i;++j) C[i][j]=(C[i-1][j-1]+C[i-1][j])%p; C[i][0]=1; fac[i]=(ll)fac[i-1]*i%p; } dfs(1),ans=0; for(int i=1;i<=m;++i) ans=((ll)ans+f[1][0][i]+f[1][1][i])%p; printf("%d\n",ans); } return 0; }
2081
F
Hot Matrix
Piggy Zhou loves matrices, especially those that make him get excited, called hot matrix. A hot matrix of size $n \times n$ can be defined as follows. Let $a_{i, j}$ denote the element in the $i$-th row, $j$-th column ($1 \le i, j \le n$). - Each column and row of the matrix is a permutation of all numbers from $0$ to $n-1$. - For each pair of indices $i$, $j$, such that $1 \le i, j \le n$, $a_{i, j} + a_{i, n - j + 1} = n - 1$. - For each pair of indices $i$, $j$, such that $1 \le i, j \le n$, $a_{i, j} + a_{n - i + 1, j} = n - 1$. - All ordered pairs $\left(a_{i, j}, a_{i, j + 1}\right)$, where $1 \le i \le n$, $1 \le j < n$, are distinct. - All ordered pairs $\left(a_{i, j}, a_{i + 1, j}\right)$, where $1 \le i < n$, $1 \le j \le n$, are distinct. Now, Piggy Zhou gives you a number $n$, and you need to provide him with a hot matrix if the hot matrix exists for the given $n$, or inform him that he will never get excited if the hot matrix does not exist for the given $n$.
First, it is not difficult to observe that when $n$ is odd, a solution exists if and only if $n = 1$. When $n$ is even, a solution always exists. Consider the following construction: Let $n = 2m$. Use $(x, y)$ to denote the cell in the $x$-th row and $y$-th column of the matrix, and assume the top-left corner of the matrix is $(1, 1)$, while the bottom-right corner is $(n, n)$. For $(a, b)$ and $(c, d)$, let $k_1 = c - a$ and $k_2 = d - b$. When $|k_1| = |k_2|$, denote $(a, b) \sim (c, d)$ as: $(a, b), (a+1, b+1), \dots, (a+k_1, b+k_2)$ if $k_1, k_2 \geq 0$. $(a, b), (a+1, b-1), \dots, (a+k_1, b+k_2)$ if $k_1 \geq 0, k_2 \leq 0$. $(a, b), (a-1, b+1), \dots, (a+k_1, b+k_2)$ if $k_1 \leq 0, k_2 \geq 0$. $(a, b), (a-1, b-1), \dots, (a+k_1, b+k_2)$ if $k_1, k_2 \leq 0$. For any $1 \leq i \leq m$, we alternately fill the numbers $2i-1$ and $2i-2$ in the cells along the paths $(1, 2i) \sim (n-2i+1, n)$, $(n-2i+2, n) \sim (n, n-2i+2)$, $(n, n-2i+1) \sim (2i, 1)$, and $(2i-1, 1) \sim (1, 2i-1)$. An illustration for $n = 10$: Next, we prove that this construction satisfies all the requirements of the problem: Each row and column of $A$ is a permutation of $0 \sim n-1$. For each $1 \leq i \leq m$, color the cells containing the numbers $2i-1$ and $2i-2$ black and white alternately along the paths described above. It can be shown that each row and column contains exactly one black and one white cell, ensuring that $2i-1$ and $2i-2$ appear exactly once in each row and column. Thus, each row and column is a permutation of $0 \sim n-1$. $a_{i,j} + a_{i,n-j+1} = n-1$ and $a_{i,j} + a_{n-i+1,j} = n-1$. From the filling process, the cells containing $2i-1$ and $2i-2$ and the cells containing $n-2i+1$ and $n-2i$ are symmetric with respect to the midline between the $m$-th and $(m+1)$-th rows, as well as the midline between the $m$-th and $(m+1)$-th columns. This symmetry further ensures that $2i-1$ and $n-2i$ are symmetric, as are $2i-2$ and $n-2i+1$. Therefore, both $a_{i,j} + a_{i,n-j+1} = n-1$ and $a_{i,j} + a_{n-i+1,j} = n-1$ are satisfied. All ordered pairs $\langle a_{i,j}, a_{i,j+1} \rangle$ (for $1 \leq i \leq n, 1 \leq j < n$) are distinct, and all ordered pairs $\langle a_{i,j}, a_{i+1,j} \rangle$ (for $1 \leq i < n, 1 \leq j \leq n$) are distinct. For each $1 \leq i \leq m$, divide the cells containing $2i-1$ and $2i-2$ into four categories: First category: $(1, 2i) \sim (n-2i+1, n)$ Second category: $(n-2i+2, n) \sim (n, n-2i+2)$ Third category: $(n, n-2i+1) \sim (2i, 1)$ Fourth category: $(2i-1, 1) \sim (1, 2i-1)$ For any $1 \leq i < j \leq m$: The first and third category cells of $2i-1, 2i-2$ do not neighbor the first and third category cells of $2j-1, 2j-2$ (since the sum of their coordinates is odd). The second and fourth category cells of $2i-1, 2i-2$ do not neighbor the second and fourth category cells of $2j-1, 2j-2$ (since the sum of their coordinates is even). The second and fourth category cells of $2i-1, 2i-2$ do not have row-wise neighbors with the first and third category cells of $2j-1, 2j-2$, and the first and third category cells of $2i-1, 2i-2$ have exactly $2$ pairs of row-wise neighbors with the second and fourth category cells of $2j-1, 2j-2$ (this can be visualized and proven through diagrams). Specifically: The first category cells of $2i-1, 2i-2$ and the second category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{n-i-j+1,n+i-j} = 2i-2 + ((i+j+1) \bmod 2), a_{n-i-j+1,n+i-j+1} = 2j-2 + ((i+j+1) \bmod 2)$ $a_{n-i-j+2,n+i-j+1} = 2i-2 + ((i+j) \bmod 2), a_{n-i-j+2,n+i-j} = 2j-2 + ((i+j) \bmod 2)$ The first category cells of $2i-1, 2i-2$ and the second category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{n-i-j+1,n+i-j} = 2i-2 + ((i+j+1) \bmod 2), a_{n-i-j+1,n+i-j+1} = 2j-2 + ((i+j+1) \bmod 2)$ $a_{n-i-j+2,n+i-j+1} = 2i-2 + ((i+j) \bmod 2), a_{n-i-j+2,n+i-j} = 2j-2 + ((i+j) \bmod 2)$ The first category cells of $2i-1, 2i-2$ and the fourth category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{j-i,i+j-1} = 2i-2 + ((i+j) \bmod 2), a_{j-i,i+j} = 2j-2 + ((i+j+1) \bmod 2)$ $a_{j-i+1,i+j} = 2i-2 + ((i+j+1) \bmod 2), a_{j-i+1,i+j-1} = 2j-2 + ((i+j) \bmod 2)$ The first category cells of $2i-1, 2i-2$ and the fourth category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{j-i,i+j-1} = 2i-2 + ((i+j) \bmod 2), a_{j-i,i+j} = 2j-2 + ((i+j+1) \bmod 2)$ $a_{j-i+1,i+j} = 2i-2 + ((i+j+1) \bmod 2), a_{j-i+1,i+j-1} = 2j-2 + ((i+j) \bmod 2)$ The third category cells of $2i-1, 2i-2$ and the second category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{n+i-j+1,n-i-j+2} = 2i-2 + ((i+j) \bmod 2), a_{n+i-j+1,n-i-j+1} = 2j-2 + ((i+j+1) \bmod 2)$ $a_{n+i-j,n-i-j+1} = 2i-2 + ((i+j+1) \bmod 2), a_{n+i-j,n-i-j+2} = 2j-2 + ((i+j) \bmod 2)$ The third category cells of $2i-1, 2i-2$ and the second category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{n+i-j+1,n-i-j+2} = 2i-2 + ((i+j) \bmod 2), a_{n+i-j+1,n-i-j+1} = 2j-2 + ((i+j+1) \bmod 2)$ $a_{n+i-j,n-i-j+1} = 2i-2 + ((i+j+1) \bmod 2), a_{n+i-j,n-i-j+2} = 2j-2 + ((i+j) \bmod 2)$ The third category cells of $2i-1, 2i-2$ and the fourth category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{i+j,j-i+1} = 2i-2 + ((i+j+1) \bmod 2), a_{i+j,j-i} = 2j-2 + ((i+j+1) \bmod 2)$ $a_{i+j-1,j-i} = 2i-2 + ((i+j) \bmod 2), a_{i+j-1,j-i+1} = 2j-2 + ((i+j) \bmod 2)$ The third category cells of $2i-1, 2i-2$ and the fourth category cells of $2j-1, 2j-2$ have exactly 2 pairs of row-wise neighbors: $a_{i+j,j-i+1} = 2i-2 + ((i+j+1) \bmod 2), a_{i+j,j-i} = 2j-2 + ((i+j+1) \bmod 2)$ $a_{i+j-1,j-i} = 2i-2 + ((i+j) \bmod 2), a_{i+j-1,j-i+1} = 2j-2 + ((i+j) \bmod 2)$ From the above analysis and by enumerating the parity of $i+j$, it is clear that all ordered pairs $\langle a_{i,j}, a_{i,j+1} \rangle$ (for $1 \leq i \leq n, 1 \leq j < n$) are distinct, and all ordered pairs $\langle a_{i,j}, a_{i+1,j} \rangle$ (for $1 \leq i < n, 1 \leq j \leq n$) are distinct. In conclusion, we have provided a construction for even $n$ and proven that it satisfies all the problem's requirements. The time complexity is $O(\sum n^2)$.
[ "constructive algorithms", "math" ]
3,300
#include<bits/stdc++.h> using namespace std; int Test_num,n; int a[3002][3002]; void solve() { scanf("%d",&n); if(n>=3 && (n&1))return (void)(puts("NO")); puts("YES"); if(n==1)return (void)(puts("0")); for(int i=0;i<n;i+=2) { for(int j=1;j<=i+1;++j)a[j][i+2-j]=i+((j&1)^1); for(int j=i+2;j<=n;++j)a[j][j-i-1]=i+((j&1)^1); for(int j=1;j<=n-i-1;++j)a[j][i+1+j]=i+(j&1); for(int j=n-i;j<=n;++j)a[j][2*n-i-j]=i+(j&1); } for(int i=1;i<=n;++i)for(int j=1;j<=n;++j)printf("%d%c",a[i][j],j==n? '\n':' '); } int main() { for(scanf("%d",&Test_num);Test_num--;)solve(); return 0; }
2081
G1
Hard Formula
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, the limits on $n$ and the time limit are smaller. You can hack only if you solved all versions of this problem.} You are given an integer $n$, and you need to compute $(\sum_{k=1}^n k\bmod\varphi(k))\bmod 2^{32}$, where $\varphi(k)$ equals the number of positive integers no greater than $k$ that are coprime with $k$.
If $g'(np)\neq g'(n)$ , then $p\le n$ unless $n=2,p=3$ or $n=1,p=2$ . Think about the method of $\min 25$ sieve. We define $\displaystyle g(n)=\frac n{\varphi(n)}=\prod_{p|n}\frac p{p-1},g'(n)=\lfloor g(n)\rfloor$. It's easy to see that $res=\frac{N(N+1)}2-\sum_{i=1}^Ng'(i)\varphi(i)$. Let's consider how to calculate $\sum_{i=1}^Ng'(i)\varphi(i)$. $\texttt{Key observation 1}$:if $g'(np)\neq g'(n)$, then $p\le n$ unless $n=2,p=3$ or $n=1,p=2$. $\begin{aligned} &\because g(n)\cdot\frac p{p-1}\ge g'(np)\ge g'(n)+1\\ &\therefore p\le\frac{g'(n)+1}{g'(n)+1-g(n)}\\ &\therefore p\le\dfrac{\left\lfloor\dfrac n{\varphi(n)}\right\rfloor\varphi(n)+\varphi(n)}{\left\lfloor\dfrac n{\varphi(n)}\right\rfloor\varphi(n)+\varphi(n)-n}\\ &\texttt{let}\ x=\left\lfloor\dfrac n{\varphi(n)}\right\rfloor\varphi(n)+\varphi(n)-n\ge 1\\ &\therefore p\le\dfrac{x+n}x\le n+1\\ \end{aligned}$ if $p=n+1$, then $\dfrac{x+n}x=n+1\implies x=1\implies \left(1+\left\lfloor \dfrac n{\phi(n)}\right\rfloor\right)\varphi(n) = n+1 \implies \varphi(n)\mid n+1$. if $n\gt 2$ then $\varphi(n)\ge 2$, but $\varphi(n)\mid n+1=p$, which is contradict the fact that $p$ is a prime number. The case of $n\le 2$ is easy to check. Therefore, all the prime factors $p$ that $\gt \sqrt N$ wouldn't change the number of $g'(n)$. Use a linear sieve to find all the prime numbers $\le \sqrt N$, following the approach for handling composite numbers in the min25 sieve: Let's define: $s(n,k)=\varphi(n)\sum_{k\leq p\leq\lfloor\frac{N}{n}\rfloor}g'(np)\times\varphi(p)$ $S(n,k)=s(n,k)+\sum_{k\leq p\leq\sqrt N\And p^e\leq\lfloor\frac{N}{n}\rfloor}S(np^e,p)+[e\neq 1]g'(np^e)\times\varphi(np^e)$ When $p\leq\frac{n+(\varphi(n)-n\mod\varphi(n))}{\varphi(n)-n\mod\varphi(n)}$, there is $g'(np)=g'(n)+1$, otherwise $g'(np)=g'(n)$. Pre-calculate the prefix of $\varphi(p)$ among prime numbers, we can calculate $s(n,k)$ like this: $s(n,k)=\varphi(n)\times\left(g'(n)\sum_{k\leq p\leq\lfloor\frac{N}{n}\rfloor}\varphi(p)+\sum_{k\leq p\leq\min\left(\frac{n+(\varphi(n)-n\mod\varphi(n))}{\varphi(n)-n\mod\varphi(n)},\lfloor\frac{N}{n}\rfloor\right)}\varphi(p)\right)$ The answer is $\frac{N(N+1)}{2}-1-S(1,1)$. With time complexity $\mathcal O\left(\frac{n^{0.75}}{\log n}\right)$, it could pass the test cases of $N\le 10^{11}$.
[ "math", "number theory" ]
3,100
#include<cstdio> #include<cmath> typedef unsigned long long ull; typedef unsigned uint; const uint M=1e6+5; ull N;const uint ANS[11]={0,0,0,1,1,2,2,3,3,6,8}; uint B,n4,top,pri[M],F0[M],F1[M],G0[M],G1[M],SF[M],SG[M]; inline ull Div(const ull&n,const ull&m){ return double(n)/m; } inline ull min(const ull&a,const ull&b){ return a>b?b:a; } inline uint DFS(const ull&n,uint k,const ull&phi){ const ull&T=Div(N,n); const uint&g=int(n*1./phi),&R=min(Div((g+1)*phi,(g+1)*phi-n),min(ull(B),T)); uint ans=0; if(k>top)ans=T<=B?0:g*phi*(SF[n]-SG[B]); else if(pri[k]>T)ans=0; else if(pri[k]<=R)ans=g*phi*((n<=B?SF[n]:SG[T])-SG[R])+(g+1)*phi*(SG[R]-SG[pri[k-1]]); else ans=g*phi*((n<=B?SF[n]:SG[T])-SG[pri[k-1]]); for(;k<=top;++k){ const uint&p=pri[k],&w=p<=R?g+1:g;if(1ull*p*p>T)break; for(ull x=n,tp=phi*(p-1);x*p<=N;tp*=p)ans+=DFS(x*=p,k+1,tp)+w*tp; ans-=w*phi*(p-1); } return ans; } signed main(){ scanf("%llu",&N); if(N<=10)return!printf("%d",ANS[N]);B=sqrt(N);n4=sqrt(B); for(uint i=1;i<=B;++i){ const ull&w=Div(N,i); F0[i]=w-1;F1[i]=w*(w+1)/2-1; G0[i]=i-1;G1[i]=i*(i+1ull)/2-1; } for(uint p=2;p<=n4;++p)if(G0[p]!=G0[p-1]){ const uint&lim=Div(B,p),&S0=G0[p-1],&S1=G1[p-1];pri[++top]=p; for(uint k=1;k<=lim;++k){ F0[k]-=F0[k*p]-S0;F1[k]-=p*(F1[k*p]-S1); } for(uint k=lim+1;k<=B;++k){ const uint&x=Div(N,k*p);F0[k]-=G0[x]-S0;F1[k]-=p*(G1[x]-S1); } for(uint k=B,e=lim;e>=p;--e)for(uint x=e*p,V0=G0[e]-S0,V1=p*(G1[e]-S1);k>=x;--k){ G0[k]-=V0;G1[k]-=V1; } } for(uint p=n4+1;p<=B;++p)if(G0[p]!=G0[p-1]){ const uint&lim=Div(B,p),&T=Div(N,1ll*p*p),&S0=G0[p-1],&S1=G1[p-1];pri[++top]=p; for(uint k=1;k<=lim;++k){ F0[k]-=F0[k*p]-S0;F1[k]-=p*(F1[k*p]-S1); } for(uint k=lim+1;k<=T;++k){ const uint&x=Div(N,k*p);F0[k]-=G0[x]-S0;F1[k]-=p*(G1[x]-S1); } } for(uint i=1;i<=B;++i)SF[i]=F1[i]-F0[i],SG[i]=G1[i]-G0[i]; printf("%u",N*(N+1)/2-1-DFS(1,1,1)); }
2081
G2
Hard Formula (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, the limit on $n$ and the time limit are higher. You can hack only if you solved all versions of this problem.} You are given an integer $n$, and you need to compute $(\sum_{k=1}^n k\bmod\varphi(k))\bmod 2^{32}$, where $\varphi(k)$ equals the number of positive integers no greater than $k$ that are coprime with $k$.
Consider the DFS structure of $\min 25$ sieve. What kind of nodes are important? How many of nodes are important? Consider using Du Sieve to get some important functions. For further optimization, let's consider the DFS tree of $\min25$ sieve: $N$ vertices, rooted on $1$, the father of a node $d$ is $\frac{d}{\text{maxp}(d)}$ where $\text{maxp}(d)$ denotes the maximum prime factor of $d$. Consider all the positions $d$ that $g'(d)\neq g'(fa_d)$. Let's divide them into two cases: $d$ is a leaf, which means $d\le N\lt d\times \operatorname{maxp}(d)$. $d$ is not a leaf, which means $d\times \operatorname{maxp}(d)\le N$. The answer could be calculated like this: $\sum_{g'(d)\neq g'(fa_d)\text{ or }d=1}G(\frac{d}{\mathrm{maxp}(d)},\mathrm{maxp}(d))$ where $G(d,p)$ denotes the sum of $\varphi$ in the subtree of node $d$, and $G(d,p)$ could be calculated like this: $G(d,p)=\varphi(d)\sum_{i=1}^{\lfloor\frac{N}{d}\rfloor}[\mathrm{minp}(i)=p]\varphi(i)$ We could use DFS to search all the nodes $d$ which satisfy case 2, and we can calculate its contribution to the answer during our DFS. For a non-leaf node $u$, let's consider its child nodes $up$ which satisfy case 1. It's easy to see that $p$ is in an interval, which allows $O(1)$ calculation of the contributions of these nodes. As a result, we get the number of nodes $d$. Let's consider how to calculate $G(d,p)$. Define: $f_k(x)=\sum_{i=1}^n [\text{minp}(i)\ge k]\varphi(i)$ where $\text{minp}(i)$ denote the minimum prime number of $i$. Then we can see that: $G(d,p)=f_p(\lfloor\frac{N}{d}\rfloor)-f_{p+1}(\lfloor\frac{N}{d}\rfloor)$ It's easy to see that $F_0(x)=\frac{\zeta(x-1)}{\zeta(x)}$, we can use Du Sieve to get all the $f_0(\lfloor \frac Nd\rfloor)$ in $O(N^{\frac 23})$. According to $\texttt{Key observation 1}$, $\forall d\notin{2,6},\mathrm{maxp}(d)\leq\sqrt d$. Let $k=\max_{g'(d)\neq g'(fa_d)\And d\leq B}(\mathrm{maxp}(d))$, categorize these nodes $d$ again: (i) $\mathrm{maxp}(d)\leq k$, Then $\mathrm{maxp}(d)\leq \sqrt B$. (ii) $\mathrm{maxp}(d)>k$, then $B\leq\mathrm{maxp^2(d)}\leq d$, $\lfloor\frac{N}{d}\rfloor<\frac NB$. For those $d$ satisfy condition (i), let's begin with $f_0$, delete the prime numbers from small to large, until $f_k$ and calculate the contributions of these $d$. We could use Dirichlet convolution to calculate $f_{p+1}$ from $f_p$. Step 1: $h_p(N)=f_p(N)-p\times f_p(\lfloor\frac{N}{p}\rfloor)$ Step 2: $f_{p+1}(N)=\sum_{i=0}h_p(\lfloor\frac{N}{p^i}\rfloor)=h_p(N)+f_{p+1}(\lfloor\frac{N}{p}\rfloor)$ These could solve in $O\left(\frac{\sqrt N \times \sqrt B}{\log n}\right)$. For those $d$ satisfy condition (ii), we calculate $G(d,p)$ in this method: $G(d,p)=\sum_{k=1}\varphi(dp^k)f_{p+1}(\lfloor\frac{N}{dp^k}\rfloor)$ Because $p\geq \sqrt B$ and $d\geq B$, we only need to consider $k\le \frac{\log N}{\log B}$, which is similar to $O(1)$. In this part, we only need $f(x)$ for $x\le B$, so to calculate these $f$ is actually a two-dimensional partial order problem which can be solved using a BIT, time complexity $O(\frac NB\log N)$. Since for each $d$, we get $G(d,p)$ in $O(1)$ in case (i), and $O(\log N)$ in case (ii). The total time complexity is $O\left(N^{\frac 23} + \frac{\sqrt N\times \sqrt B}{\log N}+ \frac NB\log N+D\log N\right)$. Let $B=N^{\frac 13}\log^{\frac 43}N$, the total time complexity is $O\left(N^{\frac 23}+ \frac{N^{\frac 23}}{\log^{\frac 13}N}+D\log N\right)$. This part is included in the offline contest. $\texttt{Key observation 2}$ : The number of $i$ in range $[1,n]$ that satisfy $\mathrm{minp}\geq n^{\frac{1}{4}}$ is of the order of $\frac{n}{\ln n}$. $O\left(\sum_{x=\pi(n^{\frac{1}{4}})}^{\pi(n)}\sum_{y=\pi(n^{\frac{1}{4}})}^{\pi(\frac{n}{p_x})}\max\left(\pi(\frac{n}{p_xp_y})-\pi(n^{\frac{1}{4}}),0\right)\right)=O\left(\sum_{x=\pi(n^{\frac{1}{4}})}^{\pi(n)}\pi(\frac{n}{p_x})\sum_{y=\pi(n^{\frac{1}{4}})}^{\pi(\frac{n}{p_x})}\frac{1}{p_y}\right)$ $O\left(\sum_{n^{\frac{1}{3}}\leq p\leq n}\frac{1}{p}\right)=O(\log\log n-\log\log n^{\frac{1}{3}})=O(\log 3)$ $O\left(\sum_{x=\pi(n^{\frac{1}{4}})}^{\pi(n)}\pi(\frac{n}{p_x})\sum_{y=\pi(n^{\frac{1}{4}})}^{\pi(\frac{n}{p_x})}\frac{1}{p_y}\right)=O\left(\sum_{x=\pi(n^{\frac{1}{4}})}^{\pi(n)}\pi(\frac{n}{p_x})\right)=O(\pi(n))=O(\frac{n}{\log n})$ Since we only need to calculate $G(\frac{d}{\mathrm{maxp}(d)},\mathrm{maxp}(d))$ where $\text{maxp}(d)\gt \sqrt B$ in case (ii). We actually only need to consider those $\text{minp}(i)\gt \sqrt B$, and $i\le \frac{d}{\text{maxp}(d)}\le\frac N{\sqrt B}$. Then if $B\gt N^{\frac 13}$, the actual size to append into the BIT is only $O(\frac{N}{B\log N})$, so the time complexity of case ii is $O(\frac NB)$. Then we could adjust $B$ to $N^{\frac 13}\log^{\frac 23}N$, the time complexity could reduce to $O\left(\frac {N^{\frac 23}}{\log^{\frac 23}N}+D\log N+N^{\frac 23}\right)$. To further optimize, let's introduce a method that could significantly reduce the time consumption of Du Sieve. The formula of Du Sieve is $\sum_{xy\leq N}f(x)g(y)=S_{f*g}(N)$. We can see that $\min(x,y)\leq\sqrt{N}$, Let $B=\lfloor\sqrt{N}\rfloor$, the formula could be rewritten like this: $\sum_{i=1}^Bf(i)S_g(\lfloor\frac{N}{i}\rfloor)+g(i)S_f(\lfloor\frac{N}{i}\rfloor)-S_f(B)S_g(B)=S_{f*g}(N)$ $S_f(N)=S_{f*g}(N)+S_f(B)S_g(B)-\sum_{i=2}^Bf(i)S_g(\lfloor\frac{N}{i}\rfloor)+g(i)S_f(\lfloor\frac{N}{i}\rfloor)-S_g(N)$ Traditionally, we need $[6B,8B]$ times of division, but using this method need a maximum of $2B$ times of division. As for what we need to calculate in this problem, we can get the formula: $S_{\varphi}(N)=\frac{N(N-1)}{2}+S_{\varphi(B)}\times B-\sum_{i=2}^B\varphi(i)\lfloor\frac{N}{i}\rfloor+iS_{\varphi}(\lfloor\frac{N}{i}\rfloor)$ Without using things like $\text{std::map}$, and use dynamic programming instead of DFS, we can further reduce the time consumption. Then consider how to optimize Du Sieve to $O\left(\frac{N^{\frac{2}{3}}}{\log N}\right)$. Definition: if $f$ is a multiplicative function, then we define a multiplicative function $f_x(p^k)=[p\geq x]f(p^k)$. We can calculate $\varphi_{N^{\frac{1}{6}}}(\lfloor\frac {N}{i} \rfloor)$ for each $i$ and then recurrence $\varphi$ from $\varphi_{N^{\frac 16}}$. Let $n6=N^{\frac{1}{6}}$, we can change the formula into: $S_{\varphi_{n6}}(N)=S_{id_{n6}}(N)-S_{1_{n6}}(N)+S_{\varphi_{n6}}(B)S_{1_{n6}}(B)-\sum_{i=2}^B[\mathrm{minp}(i)\geq n6]\varphi(i)S_{1_{n6}}(\lfloor\frac{N}{i}\rfloor)+S_{\varphi_{n6}}(\lfloor\frac{N}{i})$ Where $\text{id}(x)=x$ and $1(x)=1$, which can be calculated through $\text{min25}$ Seive, but we only need to solve $p\leq n6$ instead of $p\leq\sqrt N$. According to $\texttt{Key observation 2}$, we know that the number of $i\le \sqrt N$ that satisfy $\mathrm{minp}(i)\geq n6$ is about $\frac{\sqrt N}{\log N}$, find them and iterate these numbers in the Du Sieve. The time complexity of this part is $O\left(\frac{N^{\frac{2}{3}}}{\log N}\right)$. At last we get a solution of $O\left(\frac{N^{\frac{2}{3}}}{\log N}+\frac{\sqrt{NK}}{\log N}+\frac{N}{K}\right)$.
[ "math" ]
3,400
#include<bitset> #include<cstdio> #include<vector> #include<cmath> #include<ctime> using std::min; using std::max; typedef unsigned uint; typedef unsigned long long ull; namespace Sol{ const uint M=4162277+5,Pi=1001258+5,M2=500000000+5; uint sum;ull N; uint F[M],G[M]; uint top,Sp[Pi],pri[Pi],pi[M],phi[M2];double g[Pi]; uint n4,K,B,m,lim,BIT[M]; double st,ed; struct nb{ ull n;uint phi; nb(const ull&n=1,const uint&phi=1):n(n),phi(phi){} };std::vector<nb>d[Pi]; inline ull div(const ull&n,const ull&m){ return n*1./m; } inline void Add(uint n,const uint&V){ while(n<=B)BIT[n]+=V,n+=n&-n; } inline uint Qry(uint n){ uint ans(0);while(n)ans+=BIT[n],n-=n&-n;return ans; } inline bool check(double P,ull n,uint k){ ull x(1);while(P>1&&k<=m&&x*pri[k]<=n)P*=g[k],x*=pri[k++];return P>1; } inline bool DFS1(const ull&n,uint k,const ull&phi){ const ull&T=div(N,n);const uint&w=int(n/phi)+1; if(check(w*phi*1./n,T,k))return true; //g(n)*p/(p-1)>=int(g(n))+1 const uint&R=pi[min(div(w*phi,w*phi-n),min(ull(B),T))]; for(;k<=m;++k){ const uint&p=pri[k];if(p*p>T)break; if(k<=R)d[k].push_back(nb(n,phi)),n*p<=B&&(lim=max(lim,k)); for(ull x=n,tp=phi*(p-1);x*p<=N;tp*=p)if(DFS1(x*=p,k+1,tp))break; } if(k<=R)sum+=phi*(Sp[R]-Sp[k-1]); return false; } inline void DFS2(const uint&n,uint k,const uint&phi){ const uint&T=div(B,n);Add(n,phi); for(;k<=m;++k){ const uint&p=pri[k],&T2=div(B,p);if(p>T)return; for(uint x=n,tp=phi*(p-1);x<=T2;tp*=p)DFS2(x*=p,k+1,tp); } } void sieve(const uint&n){ phi[1]=1; for(uint i=2;i<=n;++i){ if(!phi[i]){ phi[i]=i-1;if(i<=B)pri[++top]=i,g[top]=1.*(i-1)/i,Sp[top]=Sp[top-1]+phi[i],pi[i]=1; } for(uint x,j=1;j<=top&&(x=i*pri[j])<=n;++j){ phi[x]=phi[i]*(pri[j]-1);if(div(i,pri[j])*pri[j]==i){phi[x]+=phi[i];break;} } if(i<=B)pi[i]+=pi[i-1]; } } void Getphi(const ull&n){ const uint&B2=div(N,K); for(uint i=1;i<=B;++i)G[i]=G[i-1]+phi[i];for(uint i=div(N,B);i>=1;--i)F[B]+=phi[i]; for(uint i=B-1;i>B2;--i){ const uint&L=div(N,i+1)+1,&R=div(N,i);F[i]=F[i+1];for(uint k=L;k<=R;++k)F[i]+=phi[k]; } for(uint i=B2;i>=1;--i){ const ull&T=div(N,i);const uint&lim=sqrt(T);F[i]=lim*G[lim]+T*(T-1)/2; for(uint k=2;k<=lim;++k){ const uint&x=div(T,k);F[i]-=(i*k<=B?F[i*k]:G[x])+phi[k]*x; } } } uint Solve(const ull&n){ st=clock(); N=n;B=sqrt(N);n4=sqrt(B); sieve(K=uint(pow(N,2./3)));m=pi[B]; fprintf(stderr,"sieve(%d) done %lf\n",K,((ed=clock())-st)/1000);st=ed; DFS1(1,1,1); fprintf(stderr,"DFS done %lf\n",((ed=clock())-st)/1000);st=ed; Getphi(N);sum+=F[1]; fprintf(stderr,"Getphi done %lf\n",((ed=clock())-st)/1000);st=ed; for(uint i=1;i<=lim;++i){ const uint&p=pri[i],&T=B/p;const ull&k=div(N,p); for(nb&x:d[i])sum+=x.phi*(x.n<=B?F[x.n]:G[div(N,x.n)]); for(uint i=1;i<=T;++i)F[i]-=p*F[i*p]; for(uint i=T+1;i<=B;++i)F[i]-=p*G[div(k,i)]; for(uint i=B,j=div(i,p);j;--j)for(uint e=j*p,V=p*G[j];i>=e;--i)G[i]-=V; for(uint i=p,j=1;i<=B;++j)for(uint e=min(i+p,B+1),V=G[j];i<e;++i)G[i]+=V; for(uint i=B;i>T;--i)F[i]+=G[div(k,i)]; for(uint i=T;i>=1;--i)F[i]+=F[i*p]; for(nb&x:d[i])sum-=x.phi*(x.n<=B?F[x.n]:G[div(N,x.n)]); } fprintf(stderr,"case1 done %lf\n",((ed=clock())-st)/1000);st=ed; Add(1,1); for(uint i=m;i>lim;--i){ const uint&p=pri[i]; for(nb&x:d[i]){ ull n=N/x.n/p,phi=x.phi*(p-1); while(n)sum+=phi*Qry(n),n/=p,phi*=p; } for(ull x=p,phi=p-1;x<=B;x*=p,phi*=p)DFS2(x,i+1,phi); } fprintf(stderr,"case2 done %lf\n",((ed=clock())-st)/1000);st=ed; return n*(n+1)/2-sum; } } namespace sol{ uint top,pri[10005],pos[10005],phi[10005]; inline uint solve(const uint&N){ uint sum(0);phi[1]=1; for(uint i=2;i<=N;++i){ if(!pos[i])pri[pos[i]=++top]=i,phi[i]=i-1; for(uint x,j=1;j<=pos[i]&&(x=i*pri[j])<=N;++j)phi[x]=(pos[x]=j)==pos[i]?phi[i]*pri[j]:phi[i]*(pri[j]-1); sum+=i%phi[i]; } return sum; } } signed main(){ ull n;scanf("%llu",&n);if(n<=10000)return printf("%u\n",sol::solve(n)),0;printf("%u\n",Sol::Solve(n)); }
2082
A
Binary Matrix
A matrix is called binary if all its elements are either $0$ or $1$. Ecrade calls a binary matrix $A$ good if the following two properties hold: - The bitwise XOR of all numbers in each row of matrix $A$ is equal to $0$. - The bitwise XOR of all numbers in each column of matrix $A$ is equal to $0$. Ecrade has a binary matrix of size $n \cdot m$. He is interested in the minimum number of elements that need to be changed for the matrix to become good. However, it seems a little difficult, so please help him!
Do we really have to consider the problem on the whole matrix? Let $r$ be the number of rows where the bitwise XOR of all the numbers in it is $1$, and $c$ be the number of columns where the bitwise XOR of all the numbers in it is $1$. Our goal is to make both $r$ and $c$ zero. When we change an element in the matrix, both $r$ and $c$ change by exactly one. Thus, it's not hard to see that the answer is $\max (r,c)$. The time complexity is $O(\sum nm)$.
[ "constructive algorithms", "greedy" ]
800
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,m,r,c; char s[1009]; bool a[1009][1009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } int main(){ t = read(); while (t --){ n = read(),m = read(),r = c = 0; for (ll i = 1;i <= n;i += 1){ scanf("%s",s + 1); for (ll j = 1;j <= m;j += 1) a[i][j] = s[j] - '0'; } for (ll i = 1;i <= n;i += 1){ bool sum = 0; for (ll j = 1;j <= m;j += 1) sum ^= a[i][j]; if (sum) r += 1; } for (ll j = 1;j <= m;j += 1){ bool sum = 0; for (ll i = 1;i <= n;i += 1) sum ^= a[i][j]; if (sum) c += 1; } printf("%lld\n",max(r,c)); } return 0; }
2082
B
Floor or Ceil
Ecrade has an integer $x$. There are two kinds of operations. - Replace $x$ with $\left\lfloor \dfrac{x}{2}\right\rfloor$, where $\left\lfloor \dfrac{x}{2}\right\rfloor$ is the greatest integer $\le \dfrac{x}{2}$. - Replace $x$ with $\left\lceil \dfrac{x}{2}\right\rceil$, where $\left\lceil \dfrac{x}{2}\right\rceil$ is the smallest integer $\ge \dfrac{x}{2}$. Ecrade will perform exactly $n$ first operations and $m$ second operations in any order. He wants to know the minimum and the maximum possible value of $x$ after $n+m$ operations. However, it seems a little difficult, so please help him!
Consider $x$ in binary form. What are all possible values of $x$ after $n+m$ operations? Let's consider how to find the maximum value first. Consider $x$ in binary form. Let the number formed by the last $n+m$ bits of $x$ be denoted as $r$, and the remaining higher bits form the number $l$ (for instance, if $x=12=(1100)_2$, $n=1$, $m=2$, then $l=1=(1)_2$, $r=4=(100)_2$), then the final value of $x$ after $n+m$ operations will be either $l$ or $l+1$, depending on whether a carry-over occurs in $r$ during the last operation. If there are no $1$s in the higher $m$ bits of $r$, then the carry-over in $r$ during the last operation can never occur (operating on some small tests may give you a better understanding). Otherwise, we can choose to perform $n$ floor operations first followed by $m$ ceil operations, which can guarantee a carry-over in $r$ during the last operation. This demonstrates that performing $n$ floor operations first followed by $m$ ceil operations will always yield the maximum value. Similarly, performing $m$ ceil operations first followed by $n$ floor operations will always produce the minimum value. We can simply simulate these operations because after $O(\log x)$ same operations, $x$ will remain unchanged. The time complexity is $O(T\log x)$.
[ "brute force", "greedy" ]
1,600
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,x,n,m; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } ll F(ll x,ll n){ while (n --){ if (!x) return x; x = (x >> 1); } return x; } ll C(ll x,ll n){ while (n --){ if (x <= 1) return x; x = ((x + 1) >> 1); } return x; } int main(){ t = read(); while (t --){ x = read(),n = read(),m = read(); printf("%lld %lld\n",F(C(x,m),n),C(F(x,n),m)); } return 0; }
2084
A
Max and Mod
You are given an integer $n$. Find any permutation $p$ of length $n$$^{\text{∗}}$ such that: - For all $2 \le i \le n$, $\max(p_{i - 1}, p_i) \bmod i$ $^{\text{†}}$ $= i - 1$ is satisfied. If it is impossible to find such a permutation $p$, output $-1$. \begin{footnotesize} $^{\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). $^{\text{†}}$$x \bmod y$ denotes the remainder from dividing $x$ by $y$. \end{footnotesize}
When $n$ is odd, we can construct $p = [n, 1, 2, \ldots, n - 1]$. In this case: For $i = 2$, $\max(p_1, p_2) = n$ and $n \bmod 2 = 1$. For $i \geq 3$, $\max(p_{i - 1}, p_i) = i - 1$ and $(i - 1) \bmod i = i - 1$. It can be proven that there is no solution when $n$ is even. Clearly, $n$ cannot be placed at $p_1, p_2$, or $p_n$. If $n$ is placed in position $3 \sim n - 1$, let $x$ be the position of $n$, then we have $\max(p_{x - 1}, p_x) = \max(p_x, p_{x + 1}) = n$. Thus, there must exist an even number $2 \leq i \leq n$ such that $\max(p_{i - 1}, p_i) = n$ and it must satisfy $\max(p_{i - 1}, p_i) \bmod i = i - 1$. However, an even number modulo another even number can never yield an odd result, leading to a contradiction. Time complexity: $O(n)$ per test case.
[ "constructive algorithms", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int T, n; cin >> T; while (T--) { cin >> n; if (n & 1) { cout << n << ' '; for (int i = 1; i < n; ++i) { cout << i << " \n"[i == n - 1]; } } else { cout << "-1\n"; } } return 0; }
2084
B
MIN = GCD
You are given a positive integer sequence $a$ of length $n$. Determine if it is possible to rearrange $a$ such that there exists an integer $i$ ($1 \le i<n$) satisfying $$ \min([a_1,a_2,\ldots,a_i])=\gcd([a_{i+1},a_{i+2},\ldots,a_n]). $$ Here $\gcd(c)$ denotes the greatest common divisor of $c$, which is the maximum positive integer that divides all integers in $c$.
For any positive integer sequence $a$, we always have $\gcd(a) \leq \min(a)$. Let $x = \min(a)$, then $x$ must be placed on the $\min([a_1, a_2, \ldots, a_i])$ side. Thus, we can conclude that: $\min([a_1, a_2, \ldots, a_i]) = \gcd([a_{i + 1}, a_{i + 2}, \ldots, a_n]) = x$ Now, we need to select some numbers, excluding one occurrence of $x$, to be placed on the $\gcd([a_{i + 1}, a_{i + 2}, \ldots, a_n])$ side, ensuring that $\gcd([a_{i + 1}, a_{i + 2}, \ldots, a_n]) = x$. A greedy strategy is to place all multiples of $x$ on the $\gcd$ side after removing one occurrence of $x$. This minimizes $\gcd$ while ensuring it remains a multiple of $x$. Thus, we only need to check whether the $\gcd$ of the remaining multiples of $x$ (after removing one occurrence of $x$) is still equal to $x$. Time complexity: $O(n + \log a)$ or $O(n \log a)$ (depending on which $\gcd$ implementation you use) per test case.
[ "greedy", "math", "number theory" ]
1,100
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(0); cin.tie(0); int T, n; cin >> T; while (T--) { cin >> n; vector<ll> a(n); for (ll &x : a) { cin >> x; } int p = min_element(a.begin(), a.end()) - a.begin(); ll g = 0; for (int i = 0; i < n; ++i) { if (i != p && a[i] % a[p] == 0) { g = __gcd(g, a[i]); } } cout << (g == a[p] ? "Yes\n" : "No\n"); } return 0; }
2084
C
You Soared Afar With Grace
You are given a permutation $a$ and $b$ of length $n$$^{\text{∗}}$. You can perform the following operation at most $n$ times: - Choose two indices $i$ and $j$ ($1 \le i, j \le n$, $i \ne j$), swap $a_i$ with $a_j$, swap $b_i$ with $b_j$. Determine whether $a$ and $b$ can be reverses of each other after operations. In other words, for each $i = 1, 2, \ldots, n$, $a_i = b_{n + 1 - i}$. If it is possible, output any valid sequence of operations. Otherwise, output $-1$. \begin{footnotesize} $^{\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). \end{footnotesize}
By analyzing the structure of the operation, we can see that each pair $(a_i, b_i)$ is swapped together, meaning that the corresponding $b_i$ of a given $a_i$ remains unchanged. Since our goal is to make $b$ the reverse of $a$, in the final sequence, $(a_{n - i + 1}, b_{n - i + 1})$ must be equal to $(b_i, a_i)$. This implies that in the initial sequence, if $(a_i, b_i)$ exists, then $(b_i, a_i)$ must also exist; otherwise, no solution is possible. In particular, if $n$ is odd, there must be exactly one pair $(a_i, b_i)$ satisfying $a_i = b_i$, and this pair must be swapped to position $\frac{n + 1}{2}$. As for the construction method, first, if $n$ is odd, move the pair where $a_i = b_i$ to position $\frac{n + 1}{2}$. Then, let $p_i$ denote the position of $i$ in $a$. Iterate over $i = 1, 2, \ldots, \left\lfloor\frac{n}{2}\right\rfloor$, swapping positions $p_{b_i}$ and $n - i + 1$. This ensures that by the time we reach $i$, for every $1 \leq j \leq i$, the conditions $a_j = b_{n - j + 1}$ and $a_{n - j + 1} = b_j$ hold. This process requires at most $\left\lceil\frac{n}{2}\right\rceil$ operations. Time complexity: $O(n)$ per test case.
[ "constructive algorithms", "data structures", "greedy", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; const int maxn = 200100; int n, a[maxn], b[maxn], m, p[maxn], ans[maxn][2]; inline void work(int x, int y) { if (x == y) { return; } ans[++m][0] = x; ans[m][1] = y; swap(a[x], a[y]); swap(p[a[x]], p[a[y]]); swap(b[x], b[y]); } void solve() { cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; p[a[i]] = i; } for (int i = 1; i <= n; ++i) { cin >> b[i]; } m = 0; int x = 0; for (int i = 1; i <= n; ++i) { if (a[i] == b[i]) { if (n % 2 == 0 || x) { cout << "-1\n"; return; } x = i; } else if (b[p[b[i]]] != a[i]) { cout << "-1\n"; return; } } if (n & 1) { work(x, (n + 1) / 2); } for (int i = 1; i <= n / 2; ++i) { work(p[b[i]], n - i + 1); } cout << m << '\n'; for (int i = 1; i <= m; ++i) { cout << ans[i][0] << ' ' << ans[i][1] << '\n'; } } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { solve(); } return 0; }
2084
D
Arcology On Permafrost
You are given three integers $n$, $m$, and $k$, where $m \cdot k < n$. For a sequence $b$ consisting of non-negative integers, define $f(b)$ as follows: - You may perform the following operation on $b$: - Let $l$ denote the current length of $b$. Choose a positive integer $1 \leq i \leq l - k + 1$, remove the subarray from index $i$ to $i + k - 1$ and concatenate the remaining parts. In other words, replace $b$ with $$[b_1, b_2, \ldots, b_{i - 1}, b_{i + k}, b_{i + k + 1}, \ldots, b_l].$$ - $f(b)$ is defined as the \textbf{minimum} possible value of $\operatorname{mex}(b)$$^{\text{∗}}$ after performing the above operation \textbf{at most $m$ times} (possibly zero). You need to construct a sequence $a$ of length $n$ consisting of non-negative integers, such that: - For all $1 \le i \le n$, $0 \le a_i \le 10^9$. - Over all such sequences $a$, $f(a)$ is \textbf{maximized}. \begin{footnotesize} $^{\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 $x$ which does not occur in the collection $c$. \end{footnotesize}
Since performing the operation will never increase $\operatorname{mex}$ of the sequence, we can treat "at most $m$ operations" as "exactly $m$ operations". Next, we consider computing the maximum value of $f(a)$. First, we have $f(a) \leq n - m \cdot k$ because after the operations, the length of $a$ becomes $n - m \cdot k$, and the $\operatorname{mex}$ of a sequence must be no more than its length. Second, we have $f(a) \leq \frac{n}{m + 1}$, because to ensure that all numbers in $0 \sim f(a) - 1$ are not completely removed, each of them must appear at least $m + 1$ times. We claim that the maximum value of $f(a)$ is $\min(n - m \cdot k, \left\lfloor\frac{n}{m + 1}\right\rfloor)$ Next, we prove that this maximum value can be achieved through construction. If $n - m \cdot k < \frac{n}{m + 1}$, then $n < (m + 1) \cdot k$, which implies $n - m \cdot k < k$, meaning that the final length of $a$ is less than $k$. In this case, we construct $a_i = i \bmod k$. This ensures that no matter which subarray is removed, the remaining sequence still satisfies $a_i = i \bmod k$. After performing $m$ deletions, we are left with $a_i = i$. If $n - m \cdot k \geq \frac{n}{m + 1}$, then $n \geq (m + 1) \cdot k$, which implies $\frac{n}{m + 1} \geq k$. Here, we construct $a_i = i \bmod \left\lfloor\frac{n}{m + 1}\right\rfloor$. This guarantees that every pair of identical numbers has a distance of at least $k$, and that all numbers in $0 \sim \left\lfloor\frac{n}{m + 1}\right\rfloor - 1$ appear at least $m + 1$ times. Thus, each deletion can remove at most one of these numbers, ensuring that no number is completely removed after $m$ deletions. Time complexity: $O(n)$ per test case.
[ "binary search", "brute force", "constructive algorithms", "greedy", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { int T; cin >> T; while (T--) { int n, m, k; cin >> n >> m >> k; for (int i = 0; i < n; ++i) { cout << i % (n < (m + 1) * k ? k : n / (m + 1)) << " \n"[i == n - 1]; } } return 0; }
2084
E
Blossom
You are given a permutation $a$ of length $n$$^{\text{∗}}$ where some elements are missing and represented by $-1$. Define the value of a permutation as the sum of the MEX$^{\text{†}}$ of all its non-empty subsegments$^{\text{‡}}$. Find the sum of the value of all possible valid permutations that can be formed by filling in the missing elements of $a$ modulo $10^9 + 7$. \begin{footnotesize} $^{\text{∗}}$ A permutation of length $n$ is an array consisting of $n$ distinct integers \textbf{from $\bf{0}$ to $\bf{n - 1}$} in arbitrary order. For example, $[1,2,0,4,3]$ is a permutation, but $[0,1,1]$ is not a permutation ($1$ appears twice in the array), and $[0,2,3]$ is also not a permutation ($n=3$ but there is $3$ in the array). $^{\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 $x$ which does not occur in the collection $c$. $^{\text{‡}}$A sequence $a$ is a subsegment of a sequence $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. \end{footnotesize}
We transform $\operatorname{mex}([a_i, a_{i + 1}, \ldots, a_j])$ into $\sum\limits_{k = 0}^{n - 1} [\text{numbers from 0 to}\ k\ \text{all appear in}\ [i, j]]$. Let there be $t$ occurrences of $-1$ in $a$. Since $a$ needs to be a permutation, for each number from $0$ to $k$, if it has appeared in $a$, it must appear in $[i, j]$. For such a group $(i, j, k)$, let $[i, j]$ contain $c_1$ $-1$s, and the number of elements in $0 \sim k$ that have not appeared in $a$ be $c_2$. The contribution is: $\binom{c_1}{c_2} \cdot c_2! \cdot (t - c_2)!$ As for the optimization, consider enumerating $k$ and $c_1$. We need to quickly find how many intervals $[i, j]$ satisfy: There are exactly $c_1$ $-1$s in $[i, j]$; For every number from $0$ to $k$, if it appears in $a$, its position must lie within $[i, j]$. Let $d_{i, j}$ be the number of intervals satisfying these conditions for $c_1 = i$ and $k = j$. We enumerate each interval $[i, j]$, and let $x$ be the number of $-1$s in $[i, j]$, and $y$ be the minimum number of numbers that appeared in $a$ but whose positions do not lie in $[i, j]$ (if no such number exists, then $y = n$). The contribution of this interval to $d$ is that $d_{x, 0}, d_{x, 1}, \ldots, d_{x, y - 1}$ are all added by $1$. Time complexity: $O(n^2)$ per test case.
[ "binary search", "combinatorics", "dp", "implementation", "math", "two pointers" ]
2,400
#include <bits/stdc++.h> using namespace std; const int maxn = 5050; const int mod = 1000000007; int n, a[maxn], fac[maxn], C[maxn][maxn], b[maxn], d[maxn][maxn]; bool vis[maxn]; void solve() { cin >> n; for (int i = 0; i <= n; ++i) { vis[i] = 0; for (int j = 0; j <= n; ++j) { d[i][j] = 0; } } fac[0] = 1; for (int i = 1; i <= n; ++i) { cin >> a[i]; fac[i] = 1LL * fac[i - 1] * i % mod; b[i] = b[i - 1] + (a[i] == -1); if (a[i] != -1) { vis[a[i]] = 1; } } for (int i = 0; i <= n; ++i) { C[i][0] = C[i][i] = 1; for (int j = 1; j < i; ++j) { C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % mod; } } int mn1 = n; for (int i = 1; i <= n; ++i) { int mn2 = n; for (int j = n; j >= i; --j) { int x = b[j] - b[i - 1], y = min(mn1, mn2); ++d[x][0]; --d[x][y]; if (a[j] != -1) { mn2 = min(mn2, a[j]); } } if (a[i] != -1) { mn1 = min(mn1, a[i]); } } for (int i = 0; i <= b[n]; ++i) { for (int j = 1; j <= n; ++j) { d[i][j] += d[i][j - 1]; } } int ans = 0, cnt = 0; for (int i = 0; i < n; ++i) { cnt += (!vis[i]); for (int j = cnt; j <= b[n]; ++j) { ans = (ans + 1LL * C[j][cnt] * fac[cnt] % mod * fac[b[n] - cnt] % mod * d[j][i]) % mod; } } cout << ans << '\n'; } int main() { int T; cin >> T; while (T--) { solve(); } return 0; }
2084
F
Skyscape
You are given a permutation $a$ of length $n$$^{\text{∗}}$. We say that a permutation $b$ of length $n$ is good if the two permutations $a$ and $b$ can become the same after performing the following operation \textbf{at most $n$ times} (possibly zero): - Choose two integers $l, r$ such that $1 \le l < r \le n$ and $a_r = \min(a_l, a_{l + 1}, \ldots, a_r)$. - Cyclically shift the subsegment $[a_l, a_{l + 1}, \ldots, a_r]$ one position to the right. In other words, replace $a$ with $[a_1, \ldots, a_{l - 1}, \; a_r, a_l, a_{l + 1}, \ldots, a_{r - 1}, \; a_{r + 1}, \ldots, a_n]$. You are also given a permutation $c$ of length $n$ where some elements are missing and represented by $0$. You need to find a \textbf{good} permutation $b_1, b_2, \ldots, b_n$ such that $b$ can be formed by filling in the missing elements of $c$ (i.e., for all $1 \le i \le n$, if $c_i \ne 0$, then $b_i = c_i$). If it is impossible, output $-1$. \begin{footnotesize} $^{\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). \end{footnotesize}
A permutation $b$ is considered good if and only if the ordered pairs in $a$ remain ordered pairs in $b$. In other words, for any pair $i < j$, if the position of $i$ in $a$ is smaller than that of $j$, then the position of $i$ in $b$ must also be smaller than that of $j$. Proof of necessity: The operation will not turn any originally ordered pair in $a$ into an inversion. Proof of sufficiency: For $a$ and $b$ that satisfy the above condition, it is always possible to make $a$ identical to $b$ through the following operation: Iterate over $i = 1, 2, \ldots, n$. If $a_i = b_i$, skip; otherwise, let $j$ be the position of $b_i$ in $a$, and perform an operation with $l = i, r = j$. Iterate over $i = 1, 2, \ldots, n$. If $a_i = b_i$, skip; otherwise, let $j$ be the position of $b_i$ in $a$, and perform an operation with $l = i, r = j$. For numbers in $c$ that are not $0$, if they violate the above condition, then it is clearly impossible to find a solution. Otherwise, for a number $x$ that does not appear in $c$, if we only consider the restrictions imposed by the numbers in $c$, the legal range for its position in $c$ is an interval $[l_x, r_x]$. $l_x$ and $r_x$ can be calculated using a Fenwick Tree or Segment Tree. It seems that this is a classic greedy problem of "filling numbers into positions, where the $i$-th number's position must be within the interval $[l_i, r_i]$." The approach is to determine each position from left to right. For the $i$-th position, fill the smallest number $j$ such that $l_j \leq i$ and $r_j$ is the minimum over all numbers $j$ that have not been filled yet. This can be implemented with a heap. However, we must also consider the mutual constraints between the numbers to be placed in $c$. In fact, we can observe that for any $x < y$, if $x$'s position in $a$ is smaller than $y$'s position, then $l_x \leq l_y$ and $r_x \leq r_y$. Therefore, if we directly apply the above greedy approach (when multiple $r_j$'s are the smallest, fill the smallest $j$), the legality condition will naturally be satisfied. Time complexity: $O(n \log n)$ per test case.
[ "constructive algorithms", "data structures", "greedy" ]
2,900
#include <bits/stdc++.h> using namespace std; const int maxn = 500100; int n, a[maxn], b[maxn], c[maxn], p[maxn], q[maxn]; struct node { int r, x; node(int a = 0, int b = 0) : r(a), x(b) {} }; inline bool operator < (const node &a, const node &b) { return a.r > b.r || (a.r == b.r && a.x > b.x); } vector<node> vc[maxn]; struct DS1 { int c[maxn]; inline void init() { for (int i = 0; i <= n; ++i) { c[i] = 0; } } inline void update(int x, int d) { for (int i = x; i <= n; i += (i & (-i))) { c[i] = max(c[i], d); } } inline int query(int x) { int res = 0; for (int i = x; i; i -= (i & (-i))) { res = max(res, c[i]); } return res; } } T1; struct DS2 { int c[maxn]; inline void init() { for (int i = 0; i <= n; ++i) { c[i] = n + 1; } } inline void update(int x, int d) { for (int i = x; i; i -= (i & (-i))) { c[i] = min(c[i], d); } } inline int query(int x) { int res = n + 1; for (int i = x; i <= n; i += (i & (-i))) { res = min(res, c[i]); } return res; } } T2; void solve() { cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; p[a[i]] = i; q[i] = 0; vector<node>().swap(vc[i]); } for (int i = 1; i <= n; ++i) { cin >> b[i]; if (b[i]) { q[b[i]] = i; } } T1.init(); for (int i = 1; i <= n; ++i) { if (q[i]) { if (T1.query(p[i]) > q[i]) { cout << "-1\n"; return; } T1.update(p[i], q[i]); } } T1.init(); T2.init(); for (int i = 1; i <= n; ++i) { if (q[a[i]]) { T1.update(a[i], q[a[i]]); } else { c[i] = T1.query(a[i]) + 1; } } for (int i = n; i; --i) { if (q[a[i]]) { T2.update(a[i], q[a[i]]); } else { int r = T2.query(a[i]) - 1; if (c[i] > r) { cout << "-1\n"; return; } vc[c[i]].emplace_back(r, a[i]); } } priority_queue<node> pq; for (int i = 1; i <= n; ++i) { for (node u : vc[i]) { pq.push(u); } if (!b[i]) { if (pq.empty() || pq.top().r < i) { cout << "-1\n"; return; } b[i] = pq.top().x; pq.pop(); } } for (int i = 1; i <= n; ++i) { cout << b[i] << " \n"[i == n]; } } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { solve(); } return 0; }
2084
G1
Wish Upon a Satellite (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $t \le 1000$, $n \le 5000$ and the sum of $n$ does not exceed $5000$. You can hack only if you solved all versions of this problem.} For a non-empty sequence $c$ of length $k$, define $f(c)$ as follows: - Turtle and Piggy are playing a game on a sequence. They are given the sequence $c_1, c_2, \ldots, c_k$, and Turtle goes first. Turtle and Piggy alternate in turns (so, Turtle does the first turn, Piggy does the second, Turtle does the third, etc.). - The game goes as follows: - Let the current length of the sequence be $m$. If $m = 1$, the game ends. - If the game does not end and it's Turtle's turn, then Turtle must choose an integer $i$ such that $1 \le i \le m - 1$, set $c_i$ to $\min(c_i, c_{i + 1})$, and remove $c_{i + 1}$. - If the game does not end and it's Piggy's turn, then Piggy must choose an integer $i$ such that $1 \le i \le m - 1$, set $c_i$ to $\max(c_i, c_{i + 1})$, and remove $c_{i + 1}$. - Turtle wants to \textbf{maximize} the value of $c_1$ in the end, while Piggy wants to \textbf{minimize} the value of $c_1$ in the end. - $f(c)$ is the value of $c_1$ in the end if both players play optimally. For a permutation $p$ of length $n$$^{\text{∗}}$, Turtle defines the beauty of the permutation as $\sum\limits_{i = 1}^n \sum\limits_{j = i}^n f([p_i, p_{i + 1}, \ldots, p_j])$ (i.e., the sum of $f(c)$ where $c$ is a non-empty subsegment$^{\text{†}}$ of $p$). Piggy gives Turtle a permutation $a$ of length $n$ where some elements are missing and represented by $0$. Turtle asks you to determine a permutation $b$ of length $n$ such that: - $b$ can be formed by filling in the missing elements of $a$ (i.e., for all $1 \le i \le n$, if $a_i \ne 0$, then $b_i = a_i$). - The beauty of the permutation $b$ is \textbf{maximized}. For convenience, you only need to find the maximum beauty of such permutation $b$. \begin{footnotesize} $^{\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). $^{\text{†}}$A sequence $a$ is a subsegment of a sequence $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. \end{footnotesize}
First, we have $f(c) = \begin{cases} \min(c_1, c_k) & k \bmod 2 = 0 \\ \max(c_1, c_k) & k \bmod 2 = 1 \end{cases}$ Symmetrically, let $g(c)$ be the result when the order of the first and second players is swapped. Then, $g(c) = \begin{cases} \max(c_1, c_k) & k \bmod 2 = 0 \\ \min(c_1, c_k) & k \bmod 2 = 1 \end{cases}$ Proof: Consider an inductive approach. The base case $k \leq 2$ is evident. For $k \geq 3$, consider computing $f(c)$. Assume $k$ is odd. If the first player chooses $2 \leq i \leq k - 2$, the game reduces to $g(c')$, and the answer is $\max(c_1, c_k)$. If the first player chooses $i = 1$ or $i = k - 1$, the answer is at most $\max(c_1, c_k)$. Other cases follow similarly. Thus, for a permutation $p_1, p_2, \dots, p_n$, we have $\begin{aligned} & \sum\limits_{i = 1}^n \sum\limits_{j = i}^n f([p_i, p_{i + 1}, \dots, p_j]) \\ = & \sum\limits_{i = 1}^n \sum\limits_{j = i}^n \Big( [i \bmod 2 = j \bmod 2] \max(p_i, p_j) + [i \bmod 2 \neq j \bmod 2] \min(p_i, p_j) \Big) \\ = & \sum\limits_{i = 1}^n \sum\limits_{j = i}^n \max(p_i, p_j) - \sum\limits_{i = 1}^n \sum\limits_{j = i + 1}^n [i \bmod 2 \neq j \bmod 2] (\max(p_i, p_j) - \min(p_i, p_j)) \\ = & \sum\limits_{i = 1}^n i^2 - \sum\limits_{i = 1}^n \sum\limits_{j = i + 1}^n [i \bmod 2 \neq j \bmod 2] |p_i - p_j| \end{aligned}$ Thus, the problem reduces to minimizing the following expression: $\sum\limits_{i = 1}^n \sum\limits_{j = i + 1}^n [i \bmod 2 \neq j \bmod 2] |b_i - b_j|$ This can be further transformed into a problem involving a number line from $1$ to $n$, where point $i$ can be black, white, or undetermined. If $i$ is at an odd index in sequence $a$, it is black; if even, it is white. If $i$ does not appear in $a$, it is undetermined. Our goal is to color the undetermined points as either black or white such that: There are exactly $\left\lceil\frac{n}{2}\right\rceil$ black points. The sum of distances between all pairs of differently colored points is minimized. This sum can be rewritten as: for each $1 \leq k < n$, the number of black points in $1 \sim k$ times the number of white points in $k + 1 \sim n$, plus the number of white points in $1 \sim k$ times the number of black points in $k + 1 \sim n$. This reformulated problem can be solved using DP. Define $f_{i, j}$ as the minimum possible sum of the above distances when $1 \le k < i$ after determining the colors of the first $i$ points, with exactly $j$ black points. For transitions, first update $f_{i, j}$ by adding the contribution from $k = i$. That is to add $j \times (\left\lfloor\frac{n}{2}\right\rfloor - (i - j)) + (i - j) \times (\left\lceil\frac{n}{2}\right\rceil - j)$ to all $f_{i, j}$. Then, consider whether the $(i+1)$-th point is black or white: If it can be white, then perform $f_{i + 1, j} = \min(f_{i + 1, j}, f_{i, j})$. If it can be black, then perform $f_{i + 1, j + 1} = \min(f_{i + 1, j + 1}, f_{i, j})$. The final answer is $\sum\limits_{i = 1}^n i^2 - f_{n, \left\lceil\frac{n}{2}\right\rceil}$. Time complexity: $O(n^2)$ per test case.
[ "dp", "games" ]
2,600
#include <bits/stdc++.h> using namespace std; typedef long long ll; void solve() { int n; cin >> n; vector<int> a(n + 1, -1); vector< vector<ll> > f(n + 1, vector<ll>(n + 1, 1e18)); for (int i = 1, x; i <= n; ++i) { cin >> x; if (x) { a[x] = i & 1; } } if (a[1] != 1) { f[1][0] = 0; } if (a[1] != 0) { f[1][1] = 0; } for (int i = 1; i < n; ++i) { for (int j = 0; j <= i; ++j) { f[i][j] += j * (n / 2 - (i - j)) + (i - j) * ((n + 1) / 2 - j); if (a[i + 1] != 1) { f[i + 1][j] = min(f[i + 1][j], f[i][j]); } if (a[i + 1] != 0) { f[i + 1][j + 1] = min(f[i + 1][j + 1], f[i][j]); } } } ll ans = -f[n][(n + 1) / 2]; for (int i = 1; i <= n; ++i) { ans += i * i; } cout << ans << '\n'; } int main() { int T; cin >> T; while (T--) { solve(); } return 0; }
2084
G2
Wish Upon a Satellite (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $t \le 10^4$, $n \le 5 \cdot 10^5$ and the sum of $n$ does not exceed $5 \cdot 10^5$. You can hack only if you solved all versions of this problem.} For a non-empty sequence $c$ of length $k$, define $f(c)$ as follows: - Turtle and Piggy are playing a game on a sequence. They are given the sequence $c_1, c_2, \ldots, c_k$, and Turtle goes first. Turtle and Piggy alternate in turns (so, Turtle does the first turn, Piggy does the second, Turtle does the third, etc.). - The game goes as follows: - Let the current length of the sequence be $m$. If $m = 1$, the game ends. - If the game does not end and it's Turtle's turn, then Turtle must choose an integer $i$ such that $1 \le i \le m - 1$, set $c_i$ to $\min(c_i, c_{i + 1})$, and remove $c_{i + 1}$. - If the game does not end and it's Piggy's turn, then Piggy must choose an integer $i$ such that $1 \le i \le m - 1$, set $c_i$ to $\max(c_i, c_{i + 1})$, and remove $c_{i + 1}$. - Turtle wants to \textbf{maximize} the value of $c_1$ in the end, while Piggy wants to \textbf{minimize} the value of $c_1$ in the end. - $f(c)$ is the value of $c_1$ in the end if both players play optimally. For a permutation $p$ of length $n$$^{\text{∗}}$, Turtle defines the beauty of the permutation as $\sum\limits_{i = 1}^n \sum\limits_{j = i}^n f([p_i, p_{i + 1}, \ldots, p_j])$ (i.e., the sum of $f(c)$ where $c$ is a non-empty subsegment$^{\text{†}}$ of $p$). Piggy gives Turtle a permutation $a$ of length $n$ where some elements are missing and represented by $0$. Turtle asks you to determine a permutation $b$ of length $n$ such that: - $b$ can be formed by filling in the missing elements of $a$ (i.e., for all $1 \le i \le n$, if $a_i \ne 0$, then $b_i = a_i$). - The beauty of the permutation $b$ is \textbf{maximized}. For convenience, you only need to find the maximum beauty of such permutation $b$. \begin{footnotesize} $^{\text{∗}}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation ($2$ appears twice in the array), and $[1,3,4]$ is also not a permutation ($n=3$ but there is $4$ in the array). $^{\text{†}}$A sequence $a$ is a subsegment of a sequence $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. \end{footnotesize}
Please read the solution for G1 first. Now, consider the operations we need to perform on the DP array at each step: For all $j$, update $f_{i, j}$ by adding $j \times \left(\left\lfloor\frac{n}{2}\right\rfloor - (i - j)\right) + (i - j) \times \left(\left\lceil\frac{n}{2}\right\rceil - j\right) = 2j^2 + (-2i - (n \bmod 2)) j + i \cdot \left\lceil\frac{n}{2}\right\rceil$, which is a quadratic function of $j$; Perform the transition $f_{i + 1, j} = \min(f_{i + 1, j}, f_{i, j})$; Perform the transition $f_{i + 1, j + 1} = \min(f_{i + 1, j + 1}, f_{i, j})$. We can inductively prove that $f_{i, j}$ is convex downward, meaning the difference array of $f_i$ is non-decreasing. Instead of maintaining $f_{i, j}$ directly, consider maintaining its difference array $g_{i, j} = f_{i, j + 1} - f_{i, j}$. Then, the operations transform into: For all $j$, add a linear function of $j$ to $g_{i, j}$; Shift $g_{i, j}$ one position to the right; Insert a zero into $g_i$ while keeping it sorted. To efficiently maintain $g_{i, j}$, we use a Treap. Each node in the Treap stores the value of $g_{i, j}$ along with its index $j$, so all operations can be rewritten as linear transformations of $(g_{i, j}, j)$, which can be efficiently handled using vectors and matrices. Time complexity: $O(n \log n)$ per test case.
[ "data structures", "dp" ]
3,500
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 500100; int n, a[maxn]; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); int p[maxn], nt, ls[maxn], rs[maxn], sz[maxn]; bool vis[maxn]; struct vec { ll a0, a1, a2; vec(ll a = 0, ll b = 0, ll c = 0) : a0(a), a1(b), a2(c) {} } val[maxn]; struct mat { ll a00, a01, a02, a10, a11, a12, a20, a21, a22; mat(ll a = 0, ll b = 0, ll c = 0, ll d = 0, ll e = 0, ll f = 0, ll g = 0, ll h = 0, ll i = 0) : a00(a), a01(b), a02(c), a10(d), a11(e), a12(f), a20(g), a21(h), a22(i) {} } I, tag[maxn]; inline vec operator * (const vec &a, const mat &b) { vec res; res.a0 = a.a0 * b.a00 + a.a1 * b.a10 + a.a2 * b.a20; res.a1 = a.a0 * b.a01 + a.a1 * b.a11 + a.a2 * b.a21; res.a2 = a.a0 * b.a02 + a.a1 * b.a12 + a.a2 * b.a22; return res; } inline mat operator * (const mat &a, const mat &b) { mat res; res.a00 = a.a00 * b.a00 + a.a01 * b.a10 + a.a02 * b.a20; res.a01 = a.a00 * b.a01 + a.a01 * b.a11 + a.a02 * b.a21; res.a02 = a.a00 * b.a02 + a.a01 * b.a12 + a.a02 * b.a22; res.a10 = a.a10 * b.a00 + a.a11 * b.a10 + a.a12 * b.a20; res.a11 = a.a10 * b.a01 + a.a11 * b.a11 + a.a12 * b.a21; res.a12 = a.a10 * b.a02 + a.a11 * b.a12 + a.a12 * b.a22; res.a20 = a.a20 * b.a00 + a.a21 * b.a10 + a.a22 * b.a20; res.a21 = a.a20 * b.a01 + a.a21 * b.a11 + a.a22 * b.a21; res.a22 = a.a20 * b.a02 + a.a21 * b.a12 + a.a22 * b.a22; return res; } inline void init() { for (int i = 0; i <= nt; ++i) { p[i] = ls[i] = rs[i] = sz[i] = 0; val[i] = vec(); tag[i] = I; vis[i] = 0; } nt = 0; } inline int newnode(ll x, ll y) { int u = ++nt; p[u] = rnd(); ls[u] = rs[u] = 0; sz[u] = 1; val[u] = vec(x, y, 1); tag[u] = I; vis[u] = 0; return u; } inline void pushup(int x) { sz[x] = sz[ls[x]] + sz[rs[x]] + 1; } inline void pushtag(int x, const mat &y) { if (!x) { return; } val[x] = val[x] * y; tag[x] = tag[x] * y; vis[x] = 1; } inline void pushdown(int x) { if (!vis[x]) { return; } pushtag(ls[x], tag[x]); pushtag(rs[x], tag[x]); vis[x] = 0; tag[x] = I; } void split(int u, int &x, int &y) { if (!u) { x = y = 0; return; } pushdown(u); if (val[u].a0 < 0) { x = u; split(rs[u], rs[u], y); } else { y = u; split(ls[u], x, ls[u]); } pushup(u); } int merge(int x, int y) { if (!x || !y) { return x | y; } pushdown(x); pushdown(y); if (p[x] < p[y]) { rs[x] = merge(rs[x], y); pushup(x); return x; } else { ls[y] = merge(x, ls[y]); pushup(y); return y; } } ll f[maxn], tot; void dfs(int u) { if (!u) { return; } pushdown(u); dfs(ls[u]); f[++tot] = val[u].a0; dfs(rs[u]); } void solve() { cin >> n; for (int i = 1; i <= n; ++i) { a[i] = -1; } for (int i = 1, x; i <= n; ++i) { cin >> x; if (x) { a[x] = (i & 1); } } init(); int rt = 0; ll l = 0, r = 0, x = 0; if (a[1] == 1) { l = r = 1; } else if (a[1] == -1) { rt = newnode(0, 1); r = 1; } for (ll i = 1; i < n; ++i) { x += l * l * 2 + (-i - i - (n & 1)) * l + i * ((n + 1) / 2); pushtag(rt, mat(1, 0, 0, 4, 1, 0, -i - i - (n & 1) - 2, 0, 1)); if (a[i + 1] == 1) { pushtag(rt, mat(1, 0, 0, 0, 1, 0, 0, 1, 1)); ++l; ++r; } else if (a[i + 1] == -1) { int u, v; split(rt, u, v); pushtag(v, mat(1, 0, 0, 0, 1, 0, 0, 1, 1)); rt = merge(merge(u, newnode(0, l + 1 + sz[u])), v); ++r; } } tot = 0; dfs(rt); ll ans = -x; for (int i = 1; i <= (n + 1) / 2 - l; ++i) { ans -= f[i]; } for (ll i = 1; i <= n; ++i) { ans += i * i; } cout << ans << '\n'; } int main() { ios::sync_with_stdio(0); cin.tie(0); I.a00 = I.a11 = I.a22 = 1; int T; cin >> T; while (T--) { solve(); } return 0; }
2084
H
Turtle and Nediam 2
\begin{quote} LGR-205-Div.1 C Turtle and Nediam \end{quote} You are given a binary sequence $s$ of length $n$ which only consists of $0$ and $1$. You can do the following operation \textbf{at most $n - 2$ times} (possibly zero): - Let $m$ denote the current length of $s$. Choose an integer $i$ such that $1 \le i \le m - 2$. - Let the median$^{\text{∗}}$ of the subarray $[s_i, s_{i + 1}, s_{i + 2}]$ be $x$, and let $j$ be the smallest integer such that $j \ge i$ and $s_j = x$. - Remove $s_j$ from the sequence and concatenate the remaining parts. In other words, replace $s$ with $[s_1, s_2, \ldots, s_{j - 1}, s_{j + 1}, s_{j + 2}, \ldots, s_m]$. Note that after every operation, the length of $s$ decreases by $1$. Find how many different binary sequences can be obtained after performing the operation, modulo $10^9 + 7$. \begin{footnotesize} $^{\text{∗}}$The median of an array of odd length $k$ is the $\frac{k + 1}{2}$-th element when sorted. \end{footnotesize}
First, extract the longest contiguous segments in $s$ where the values remain the same. Suppose there are $m$ such segments with lengths $a_1, a_2, \dots, a_m$. Then, the operations can be described as follows: Choose an index $1 \leq i \leq |a|$ such that $a_i \geq 2$ and decrease $a_i$ by 1. Choose an index $2 \leq i < |a|$ such that $a_{i-1} = a_i = 1$. Remove $a_{i-1}$. If $i \geq 3$, then merge $a_{i-2}$ with $a_i$ and remove $a_i$. First handle the corner case when $m \leq 2$. It can be observed that the length of the last segment never increases, and it is independent of the preceding segments. Thus, we only need to consider the strings that can be generated from $a_1, a_2, \ldots, a_{m-1}$, and the final answer is multiplied by $a_m$. Now, consider counting the strings that begin with the same character as $s_1$. For a generated sequence of contiguous segments $b_1, b_2, \dots, b_k$, we greedily find the shortest prefix in $a$ that can generate $b_1, b_2, \dots, b_k$. Define $f_i$ as the number of strings that can match $a_i$. For the transition when adding a new segment $b_{k+1}$, iterate over indices $j > i$ such that $j \bmod 2 \neq i \bmod 2$. Let $x$ be the maximum value of $b_{k+1}$ that can be generated by the previous $j$. Then, the maximum value that $j$ can generate for $b_{k+1}$ is $\max(x+1, a_j)$. Thus, if $b_{k+1}$ is matched at position $j$, we have $x < b_{k+1} \leq \max(x+1, a_j)$, which gives $\max(x+1, a_j) - x$ possible values for $b_{k+1}$. Thus, the transition is as follows: The initial values are given by $f_1 = a_1, \forall i \geq 3 \land i \bmod 2 = 1, f_i = 1$. The final answer is $a_m \cdot \sum\limits_{i = 1}^{m - 1} [(m - i) \bmod 2 = 1] f_i$. Next, consider counting the strings whose first character is different from $s_1$. It turns out that if the resulting string starts with a different character, then in order to delete the first contiguous segment, the second segment can be at most of length $1$. Therefore, after removing $a_1$ and setting $a_2$ to $1$, we can repeat the above process. Next, we optimize the above $O(m^2)$ DP. Define $\text{nxt}_i$ as the smallest $j$ such that $j \bmod 2 = i \bmod 2 \land a_j - \frac{j}{2} > a_i - \frac{i}{2}$. For a given $i$, the transition works as follows: Maintain a variable $j$ initialized as $j = i + 1$. Perform a special transition at $j$. For $j + 2 \leq k < \text{nxt}_j$ such that $k \bmod 2 = j \bmod 2$, update $f_k$ by adding $f_i$ (which can be implemented using a difference array). Set $j = \text{nxt}_j$ and repeat the process. By directly simulating the transition process, it can be shown that the complexity is $O\left(\sum a_i\right) = O(n)$, since each $a_i$ is only jumped to at most $a_i$ times. We can further optimize the DP process to $O(m)$. Define $g_i$ as the sum of $f$-values of all positions that can jump to $i$. Then, the transition is $g_{\text{nxt}_i} \gets g_{\text{nxt}_i} + g_i$. Additionally, for $i + 2 \leq k < \text{nxt}_i$ such that $k \bmod 2 = i \bmod 2$, update $f_k$ by adding $g_i$, and then perform a special transition for $f_{\text{nxt}_i}$. Time complexity: $O(n)$ per test case.
[ "dp", "greedy" ]
3,500
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 2000100; const ll mod = 1000000007; int n, a[maxn], m, nxt[maxn], stk[maxn], top; ll f[maxn], g[maxn], d[maxn]; char s[maxn]; inline ll calc() { top = 0; for (int i = m; i >= 1; i -= 2) { while (top && a[stk[top]] - stk[top] / 2 < a[i] - i / 2) { --top; } nxt[i] = stk[top]; stk[++top] = i; } top = 0; for (int i = m - 1; i >= 1; i -= 2) { while (top && a[stk[top]] - stk[top] / 2 < a[i] - i / 2) { --top; } nxt[i] = stk[top]; stk[++top] = i; } for (int i = 1; i < m; ++i) { f[i] = g[i] = d[i] = 0; } f[1] = a[1]; for (int i = 3; i < m; i += 2) { f[i] = 1; } ll ans = 0; for (int i = 1; i < m; ++i) { if (i >= 3) { d[i] = (d[i] + d[i - 2]) % mod; } f[i] = (f[i] + d[i]) % mod; g[i + 1] = (g[i + 1] + f[i]) % mod; f[i + 1] = (f[i + 1] + f[i] * a[i + 1]) % mod; d[i + 2] = (d[i + 2] + g[i]) % mod; if (nxt[i]) { g[nxt[i]] = (g[nxt[i]] + g[i]) % mod; f[nxt[i]] = (f[nxt[i]] + g[i] * (a[nxt[i]] - a[i] - (nxt[i] - i) / 2 + 1)) % mod; d[nxt[i]] = (d[nxt[i]] - g[i] + mod) % mod; } if ((m - i) & 1) { ans = (ans + f[i]) % mod; } } return ans * a[m] % mod; } void solve() { cin >> n >> s; m = 0; for (int i = 0, j = 0; i < n; i = (++j)) { while (j + 1 < n && s[j + 1] == s[i]) { ++j; } a[++m] = j - i + 1; } if (m == 1) { cout << n - 1 << '\n'; return; } if (m == 2) { cout << 1LL * a[1] * a[2] % mod << '\n'; return; } ll ans = calc(); --m; for (int i = 1; i <= m; ++i) { a[i] = a[i + 1]; } a[1] = 1; ans = (ans + calc()) % mod; cout << ans << '\n'; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { solve(); } return 0; }
2085
A
Serval and String Theory
A string $r$ consisting only of lowercase Latin letters is called universal if and only if $r$ is lexicographically smaller$^{\text{∗}}$ than the reversal$^{\text{†}}$ of $r$. You are given a string $s$ consisting of $n$ lowercase Latin letters. You are required to make $s$ universal. To achieve this, you can perform the following operation on $s$ \textbf{at most} $k$ times: - Choose two indices $i$ and $j$ ($1\le i,j\le n$), then swap $s_i$ and $s_j$. Note that if $i=j$, you do nothing. Determine whether you can make $s$ universal by performing the above operation at most $k$ times. \begin{footnotesize} $^{\text{∗}}$A string $a$ is lexicographically smaller than a string $b$ of the same length, if and only if the following holds: - in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$. $^{\text{†}}$The reversal of a string $r$ is the string obtained by writing $r$ from right to left. For example, the reversal of the string $abcad$ is $dacba$. \end{footnotesize}
When $s$ is lexicographically equal to or greater than the reversal of $s$, is it possible to make $s$ universal by performing the operations? If possible, what is the minimum number of the operations required to make $s$ universal? Case 1. If $s$ contains only one kind of letter, the answer will be NO. Case 2. If $s$ is universal already, no operation is needed, and the answer will be YES. Otherwise, $s$ falls into the following Case 3. Case 3.1. When $s$ is not a palindrome, one can make $s$ universal in one operation by swapping the first pair of different letters of $s$ and its reversal. $\left.\begin{aligned} s ={}& \texttt{s}{\color{red}{\underline{\texttt{t}}}}\texttt{rings} \\ \text{reversal of } s ={}& \texttt{s}{\color{red}{\underline{\texttt{g}}}}\texttt{nirts} \end{aligned}\;\right\} \xrightarrow{\text{swap}} \boxed{\texttt{sgrints}}$ Case 3.2. When $s$ is a palindrome, swapping any two distinct letters will make $s$ no longer a palindrome. Note that the reversal of $s$ after the swap can be obtained by swapping the letters in the symmetric positions of the original $s$. Since either $s$ or its reversal is universal, the original $s$ can be made universal in one operation. $s = \texttt{l}{\color{red}{\underline{\texttt{e}}}}{\color{blue}{\underline{\texttt{v}}}}\texttt{el} \xrightarrow{\text{swap}} \left\{\;\begin{aligned} s' ={}& \texttt{l}{\color{blue}{\underline{\texttt{v}}}}{\color{red}{\underline{\texttt{e}}}}\texttt{el} \\ \text{reversal of } s' ={}& \texttt{le}{\color{red}{\underline{\texttt{e}}}}{\color{blue}{\underline{\texttt{v}}}}\texttt{l} \end{aligned}\;\right\} \;\boxed{\texttt{leevl}}$ Thus, for Case 3, the answer will be NO if no operation can be performed; otherwise, the answer will be YES.
[ "constructive algorithms", "implementation" ]
900
getint = lambda: int(input()) getints = lambda: map(int, input().split()) def solve(): n, k = getints() s = input().strip() if s < s[::-1] or (k >= 1 and min(s) != max(s)): print('YES') else: print('NO') t = getint() for _ in range(t): solve()
2085
B
Serval and Final MEX
You are given an array $a$ consisting of $n\ge 4$ non-negative integers. You need to perform the following operation on $a$ until its length becomes $1$: - Select two indices $l$ and $r$ ($1\le {\textcolor{red}{ l < r }} \le |a|$), and replace the subarray $[a_l,a_{l+1},\ldots,a_r]$ with a single integer $\operatorname{mex}([a_l,a_{l+1},\ldots,a_r])$, where $\operatorname{mex}(b)$ denotes the minimum excluded (MEX)$^{\text{∗}}$ of the integers in $b$. In other words, let $x=\operatorname{mex}([a_l,a_{l+1},\ldots,a_r])$, the array $a$ will become $[a_1,a_2,\ldots,a_{l-1},x,a_{r+1},a_{r+2},\ldots,a_{|a|}]$. Note that the length of $a$ decreases by $(r-l)$ after this operation. Serval wants the final element in $a$ to be $0$. Help him! More formally, you have to find a sequence of operations, such that after performing these operations in order, the length of $a$ becomes $1$, and the final element in $a$ is $0$. It can be shown that at least one valid operation sequence exists under the constraints of the problem, and the length of any valid operation sequence does not exceed $n$. Note that you do \textbf{not} need to minimize the number of operations. \begin{footnotesize} $^{\text{∗}}$The minimum excluded (MEX) of a collection of integers $b_1, b_2, \ldots, b_k$ is defined as the smallest non-negative integer $x$ which does not occur in the collection $b$. \end{footnotesize}
Before the last operation, what should the array be to obtain $0$? How to make all the elements in the array non-zero? Note that before the last operation, all the integers in the array should be positive. Thus, we aim to turn the zeroes in $a$ into non-zeroes. To achieve this, we split the given array $a$ into two halves and perform the operations on the halves that contain zeroes. After that, there will be no zeroes in either of the two halves. The final $0$ can be obtained by performing the last operation on the entire array. $[{\color{red}{\underline{1, 0, 1, 1}}}, {\color{blue}{2, 0, 8, 5}}] \to [{\color{red}{2}}, {\color{blue}{\underline{2, 0, 8, 5}}}] \to [\underline{{\color{red}{2}}, {\color{blue}{1}}}] \to [0]$ In fact, the final element can be $0$ after the operations for any array of length $4$. Can you solve the problem under the constraint of $n=4$? When $n>4$, you can perform the operation on any subarray of length $(n-3)$. After the operation, the array $a$ will contain only $4$ integers, which can be solved by brute force.
[ "constructive algorithms", "implementation" ]
1,200
getint = lambda: int(input()) getints = lambda: map(int, input().split()) def solve(): n = getint() a = list(getints()) op = [] mid, r = n // 2, n if 0 in a[mid:]: op.append([mid + 1, n]) r -= n - mid - 1 if 0 in a[:mid]: op.append([1, mid]) r -= mid - 1 op.append([1, r]) print(len(op)) for o in op: print(*o) t = getint() for _ in range(t): solve()
2085
C
Serval and The Formula
You are given two positive integers $x$ and $y$ ($1\le x, y\le 10^9$). Find a \textbf{non-negative} integer $k\le 10^{18}$, such that $(x+k) + (y+k) = (x+k)\oplus (y+k)$ holds$^{\text{∗}}$, or determine that such an integer does not exist. \begin{footnotesize} $^{\text{∗}}$$\oplus$ denotes the bitwise XOR operation. \end{footnotesize}
The formula $(x+k) + (y+k) = (x+k) \oplus (y+k)$ is equivalent to $(x+k) \mathbin{\&} (y+k) = 0$, where $\&$ denotes the bitwise AND operation. Note that a power of $2$ shares no common bits with any positive integer less than it. It can be shown that such an non-negative integer $k$ does not exist when $x=y$. When $x\neq y$, one can show that $k = 2^n - \max(x, y)$ is a possible answer, where $2^n$ is a power of $2$ that is sufficiently large.
[ "bitmasks", "constructive algorithms", "dp", "greedy" ]
1,600
getint = lambda: int(input()) getints = lambda: map(int, input().split()) def solve(): x, y = getints() if x == y: print(-1) else: print(2 ** 48 - max(x, y)) t = getint() for _ in range(t): solve()
2085
D
Serval and Kaitenzushi Buffet
Serval has just found a Kaitenzushi buffet restaurant. Kaitenzushi means that there is a conveyor belt in the restaurant, delivering plates of sushi in front of the customer, Serval. In this restaurant, each plate contains exactly $k$ pieces of sushi and the $i$-th plate has a deliciousness $d_i$. Serval will have a meal in this restaurant for $n$ minutes, and within the $n$ minutes, he must eat up \textbf{all} the pieces of sushi he took from the belt. Denote the counter for uneaten taken pieces of sushi as $r$. Initially, $r=0$. In the $i$-th minute ($1\leq i\leq n$), only the $i$-th plate of sushi will be delivered in front of Serval, and he can do \textbf{one} of the following: - Take the $i$-th plate of sushi (whose deliciousness is $d_i$) from the belt, and $r$ will be increased by $k$; - Eat one uneaten piece of sushi that he took from the belt before, and $r$ will be decreased by $1$. Note that you can do this only if $r>0$; - Or, do nothing, and $r$ will remain unchanged. Note that after the $n$ minutes, the value of $r$ \textbf{must} be $0$. Serval wants to maximize the sum of the deliciousnesses of all the plates he took. Help him find it out!
Do not go for DP. How many plates of sushi can be taken? What are the constraints on the time of taking plates of sushi? Note that the last $i$-th time taking a plate of sushi should be no later than the $(n - i\cdot(k+1) + 1)$-th minute. This constraint limits the time that a taking action can be performed. Therefore, we enumerate the $n$ minutes in chronological order, and greedily take the untaken plates delivered before with the greatest deliciousness when we reach a constraint, i.e., the current minute is the $(n - i\cdot(k+1) + 1)$-th minute for a certain $i$. The deliciousnesses of the untaken plates can be maintained by a heap. The total complexity is $O(n \log n)$.
[ "data structures", "graph matchings", "greedy" ]
2,000
#include <cstdio> #include <queue> using namespace std; const int N = 2e5 + 5; int n, k; int d[N]; long long ans; void solve() { scanf("%d%d", &n, &k); ans = 0; priority_queue <int> q; for (int i = 1; i <= n; i++) { scanf("%d", &d[i]); q.push(d[i]); if ((n - i + 1) % (k + 1) == 0) { ans += q.top(); q.pop(); } } printf("%lld\n", ans); } int main() { int t; scanf("%d", &t); while (t--) solve(); return 0; }
2085
E
Serval and Modulo
There is an array $a$ consisting of $n$ non-negative integers and a magic number $k$ ($k\ge 1$, $k$ is an integer). Serval has constructed another array $b$ of length $n$, where $b_i = a_i \bmod k$ holds$^{\text{∗}}$ for all $1\leq i\leq n$. Then, he \textbf{shuffled} $b$. You are given the two arrays $a$ and $b$. Find a possible magic number $k$. However, there is a small possibility that Serval fooled you, and such an integer does not exist. In this case, output $-1$. It can be shown that, under the constraints of the problem, if such an integer $k$ exists, then there exists a valid answer no more than $10^9$. And you need to guarantee that $k\le 10^9$ in your output. \begin{footnotesize} $^{\text{∗}}$$a_i \bmod k$ denotes the remainder from dividing $a_i$ by $k$. \end{footnotesize}
What happens when an integer $a_i$ mods $k$? Note that the difference between $a_i$ and $b_i$ is a multiple of $k$. The same holds for the difference between the sum of $a_i$ and the sum of $b_i$. Notice that $d(n) \leq 2304$ holds for all $n \leq 10^{10}$, where $d(n)$ denotes the number of divisors of $n$. Note that if such a magic number $k$ exists, it will be a divisor of $\Delta = \sum a_i - \sum b_i$ when $\Delta \neq 0$, or it can be any integer greater than all the $a_i$. Thus, we can check all the divisors of $\Delta$, resulting in a solution of $O\left(\sum (n \cdot d(\sum a_i) + \sqrt{\sum a_i})\right)$ time, where $d(n)$ denotes the number of divisors of $n$.
[ "constructive algorithms", "math", "number theory" ]
2,200
#include <cstdio> using namespace std; const int N = 1e4 + 5; const int C = 1e6 + 5; int n; int a[N], b[N]; int cnt[C]; long long s; bool check(int k) { for (int i = 1; i <= n; i++) cnt[a[i] % k]++; for (int i = 1; i <= n; i++) if (--cnt[b[i]] < 0) { cnt[b[i]] = 0; for (int i = 1; i <= n; i++) cnt[a[i] % k] = 0; return 0; } return 1; } void solve() { scanf("%d", &n); s = 0; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); s += a[i]; } for (int i = 1; i <= n; i++) { scanf("%d", &b[i]); s -= b[i]; } if (s == 0) { printf("%d\n", check(0xc0ffee) ? 0xc0ffee : -1); return; } for (int i = 1; 1ll * i * i <= s; i++) if (s % i == 0) { if (check(i)) { printf("%d\n", i); return; } if (i < C && check(s / i)) { printf("%d\n", (int)(s / i)); return; } } printf("-1\n"); } int main() { int t; scanf("%d", &t); while (t--) solve(); return 0; }
2085
F1
Serval and Colorful Array (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $n\le 3000$. You can hack only if you solved all versions of this problem.} Serval has a magic number $k$ ($k\ge 2$). We call an array $r$ colorful if and only if: - The length of $r$ is $k$, and - Each integer between $1$ and $k$ appears \textbf{exactly once} in $r$. You are given an array $a$ consisting of $n$ integers between $1$ and $k$. It is guaranteed that each integer between $1$ and $k$ appears in $a$ at least once. You can perform the following operation on $a$: - Choose an index $i$ ($1\le i < n$), then swap $a_i$ and $a_{i+1}$. Find the minimum number of operations needed to make at least one subarray$^{\text{∗}}$ of $a$ colorful. It can be shown that this is always possible under the constraints of the problem. \begin{footnotesize} $^{\text{∗}}$An array $b$ is a subarray of an array $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. \end{footnotesize}
Consider the integers in the colorful subarray after swapping. How to gather these integers together, forming a colorful subarray, with the minimum number of swaps? Consider the middle one among all the the elements in the colorful subarray. Consider the elements in the colorful subarray after swapping. The first observation is as follows. Observation. Mark the elements in the colorful subarray. Before swapping, to make these marked elements continuous, gathering them toward the middle one among them minimizes the number of swaps. Proof. It is not optimal to swap two marked elements. Thus, the leftmost $x$ elements will move to their right, and the rightmost $(k-x)$ elements will move to their left. They will meet at some point between the $x$-th element and the $(x+1)$-th element. If $x < {k\over 2}$, adjusting the meeting point to its right reduces $(k-x)-x > 0$ swaps. If $x > {k\over 2}$, we can adjust it to its left and reduce the number of swaps similarly. Therefore, one can show that setting the meeting point to the middle of them is optimal through adjustments. $\square$ From the observation we can also conclude that, the minimum number of swaps required to make the marked elements continuous is the difference between the sum of the distances from each marked element to the middle position before swapping and that sum after swapping, if the marked elements are swapped toward the middle position. Notice that the latter sum is a fixed constant only related to $k$. Focusing on the middle position of the colorful subarray, we enumerate all the positions in the array as possible middle positions. For each possible middle position $p$, to form the colorful subarray whose middle position is $p$, we should choose ${k\over 2}$ distinct integers from its left and the other $k\over 2$ from its right. The rounding of $k\over 2$ will not affect the correctness as long as the sum of the rounded numbers is $k$. For each $1\leq i\leq k$, we should determine whether $i$ should be chosen from the left side of $p$ or the right side of $p$. Let the distance from $p$ to the rightmost integer $i$ on its left be $l_i$, and the distance for the right side be $r_i$. We should choose either $l_i$ or $r_i$ for each $i$ under the constraint that both the number of chosen $l_i$ and that of $r_i$ are $k\over 2$, minimizing the sum of the distances we choose. This can be done by first forcing to choose all the $l_i$, and then choosing the smallest $k\over 2$ elements of $(r_i-l_i)$ greedily. In implementation, when enumerating the middle position $p$, both $l_i$ and $r_i$ can be simply calculated in $O(n)$ time, and then sort $(r_i - l_i)$ in $O(n\log n)$ time. The total complexity is $O(n^2\log n)$.
[ "data structures", "greedy" ]
2,600
#include <cstdio> #include <algorithm> using namespace std; const int N = 3005; const long long oo = 1e18; int n, k; int a[N], l[N], r[N], d[N]; long long ans; void solve() { scanf("%d%d", &n, &k); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); ans = oo; for (int i = 1; i <= n; i++) { for (int j = 1; j <= k; j++) l[j] = r[j] = n + 1; for (int j = i; j; j--) l[a[j]] = min(l[a[j]], i - j); for (int j = i; j <= n; j++) r[a[j]] = min(r[a[j]], j - i); long long s = 0; for (int j = 1; j <= k; j++) { s += l[j]; d[j] = r[j] - l[j]; } sort(d + 1, d + k + 1); for (int j = 1; j <= (k + 1) / 2; j++) s += d[j]; ans = min(ans, s); } for (int i = 1; i <= k; i++) ans -= abs(i - (k + 1) / 2); printf("%lld\n", ans); } int main() { int T; scanf("%d", &T); while (T--) solve(); return 0; }
2085
F2
Serval and Colorful Array (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $n\le 4\cdot 10^5$. You can hack only if you solved all versions of this problem.} Serval has a magic number $k$ ($k\ge 2$). We call an array $r$ colorful if and only if: - The length of $r$ is $k$, and - Each integer between $1$ and $k$ appears \textbf{exactly once} in $r$. You are given an array $a$ consisting of $n$ integers between $1$ and $k$. It is guaranteed that each integer between $1$ and $k$ appears in $a$ at least once. You can perform the following operation on $a$: - Choose an index $i$ ($1\le i < n$), then swap $a_i$ and $a_{i+1}$. Find the minimum number of operations needed to make at least one subarray$^{\text{∗}}$ of $a$ colorful. It can be shown that this is always possible under the constraints of the problem. \begin{footnotesize} $^{\text{∗}}$An array $b$ is a subarray of an array $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. \end{footnotesize}
Is it possible to simplify the constraints? Is it possible to remove the constraint that exactly $k\over 2$ elements should be chosen from both sides of the enumerated position? Optimizing the solution of F1 using (possibly, heavy) data structures results in a $O(n\log n)$ solution. Here we introduce a linear approach for F2 came up by Error_Yuan. In fact, the following proposition holds. Proposition. The answer obtained is still correct without the constraint that exactly $k\over 2$ elements should be chosen from both sides of the enumerated position. Without the constraint, when enumerating the position $p$, we can directly choose the smaller one between $l_i$ and $r_i$ for each $1\leq i\leq k$. Proof. On the one hand, notice that the distance sum will not be smaller when $p$ is not the middle position among the chosen elements. On the other hand, consider the colorful subarray that produces the optimal answer, and mark the elements in it first. When $p$ enumerates to the middle position of the marked elements before swapping, the minimal distance sum without the constraint is no greater than that under the constraint. Therefore, all the considered candidates are no less than the real answer, and the real answer can be reached, completing the proof. $\square$ In implementation, we consider the contribution to each position $p$ for each integer $1\leq i\leq k$. For a certain $i$, it can be shown that the delta of the contribution will be one of $-1$, $0$, or $+1$ when $p$ moves to an adjacent position. The delta of the contribution remains unchanged for most positions, and only changes either at the position where $i$ placed, or at the midpoint between two adjacent $i$. By pre-calculating the changes of contribution deltas over all the $i$ and performing the prefix sum on the array twice, we can obtain the distance sums, resulting in an $O(n)$ solution.
[ "data structures", "greedy" ]
2,900
#include <cstdio> #include <algorithm> using namespace std; const int N = 4e5 + 5; const long long oo = 1e18; int n, k; int a[N]; int last[N], dd[N]; long long s, d, ans; void solve() { scanf("%d%d", &n, &k); for (int i = 1; i <= n; i++) last[i] = dd[i] = 0; s = 0; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); if (!last[a[i]]) s += i - 1; else { int pre = last[a[i]]; int mid = (pre + i) / 2; if ((pre + i) & 1) { dd[mid]--; dd[mid + 1]--; } else dd[mid] -= 2; } dd[i] += 2; last[a[i]] = i; } ans = oo; d = -k; for (int i = 1; i <= n; i++) { ans = min(ans, s); d += dd[i]; s += d; } for (int i = 1; i <= k; i++) ans -= abs(i - (k + 1) / 2); printf("%lld\n", ans); } int main() { int T; scanf("%d", &T); while (T--) solve(); return 0; }
2086
A
Cloudberry Jam
The most valuable berry of the Karelian forests is cloudberry. To make jam from cloudberries, you take equal amounts of berries and sugar and cook them. Thus, if you have $2$ kg of berries, you need $2$ kg of sugar. However, from $2$ kg of berries and $2$ kg of sugar, you will not get $4$ kg of jam, as one might expect, but only $3$ kg, since some of the jam evaporates during cooking. Specifically, during standard cooking, exactly a quarter (or $25\%$) of the jam evaporates. How many kilograms of cloudberries are needed to prepare $n$ $3$-kilogram jars of jam?
As stated in the problem, to prepare one $3$kg jar of jam, $2$ kg of berries are required; therefore, to prepare $n$ jars, you need to take $2 \cdot n$ kg of cloudberries.
[ "math" ]
800
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while (t--) { int n; cin >> n; cout << n * 2 << "\n"; } return 0; }
2086
B
Large Array and Segments
There is an array $a$ consisting of $n$ \textbf{positive} integers, and a positive integer $k$. An array $b$ is created from array $a$ according to the following rules: - $b$ contains $n \cdot k$ numbers; - the first $n$ numbers of array $b$ are the same as the numbers of array $a$, that is, $b_{i} = a_{i}$ for $i \le n$; - for any $i > n$, it holds that $b_{i} = b_{i - n}$. For example, if $a = [2, 3, 1, 4]$ and $k = 3$, then $b = [2, 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4]$. Given a number $x$, it is required to count the number of such positions $l$ ($1 \le l \le n \cdot k$), for which there exists a position $r \ge l$, such that the sum of the elements of array $b$ on the segment $[l, r]$ is \textbf{at least} $x$ (in other words, $b_{l} + b_{l+1} + \dots + b_{r} \ge x$).
In this problem, the array $b$ is obtained by copying the array $a$ exactly $k$ times. Notice that all elements of the array $a$ are positive; therefore, the elements of the array $b$ are also positive. From this, we can conclude that the optimal $r$ for any $l$ that maximizes the sum over the segment [$l, r$] is always equal to $n \cdot k$. It also follows that the maximum sum for $l$ is less than the maximum sum for $l - 1$. The condition of monotonicity holds, so we can perform a binary search to find the first such $l$ for which the maximum sum is $< x$. How do we write a check for such a binary search? Given a position $m$, we need to calculate the maximum sum for it. To do this, we find how many "full arrays $a$" fit into the suffix $[m, n \cdot k]$: there are $\lfloor \frac{n \cdot k - m + 1}{n} \rfloor$ of them. In addition to this, there are $suff = (n \cdot k - m + 1) \bmod n$ elements from the suffix of the array $a$ on this segment, so the total sum of the elements of the array $b$ over the segment [$m, n \cdot k$] can be found using the formula: $\lfloor \frac{n \cdot k - m + 1}{n} \rfloor \cdot \sum_{i=1}^{n} a_{i} + \sum_{i = n - suff + 1}^{n} a_{i}$ At this point, we can write a solution that works in $O(n \cdot (\log n + \log k))$. If we pre-calculate all suffix sums for the array $a$, then the formula above can be calculated in $O(1)$, so the solution can be optimized to $O(n + \log k)$. There are also other solutions with $O(n + k)$ complexity that also get Accepted.
[ "binary search", "brute force", "greedy" ]
1,100
#include<bits/stdc++.h> using namespace std; #define int long long void solve(){ int n, k, x; cin >> n >> k >> x; vector<int> a(n); for (int i = 0; i < n; i++){ cin >> a[i]; } if (accumulate(a.begin(), a.end(), 0ll) * k < x){ cout << 0 << '\n'; return; } int l = 1, r = n * k; while(l <= r){ int m = l + (r - l) / 2; int cnt_a = (n * k - m + 1) / n; int suff = (n * k - m + 1) % n; int sum = cnt_a * accumulate(a.begin(), a.end(), 0ll); for (int i = n - suff; i < n; i++){ sum += a[i]; } if (sum < x){ r = m - 1; } else{ l = m + 1; } } cout << r << '\n'; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--){ solve(); } }
2086
C
Disappearing Permutation
A permutation of integers from $1$ to $n$ is an array of size $n$ where each integer from $1$ to $n$ appears exactly once. You are given a permutation $p$ of integers from $1$ to $n$. You have to process $n$ queries. During the $i$-th query, you replace $p_{d_i}$ with $0$. Each element is replaced with $0$ exactly once. The changes made in the queries are saved, that is, after the $i$-th query, all integers $p_{d_1}, p_{d_2}, \dots, p_{d_i}$ are zeroes. After each query, you have to find the minimum number of operations required to fix the array; in other words, to transform the current array into any permutation of integers from $1$ to $n$ (possibly into the original permutation $p$, possibly into some other permutation). The operation you can perform to fix the array is the following one: - choose the integer $i$ from $1$ to $n$, replace the $i$-th element of the array \textbf{with $i$}. Note that the answer for each query is calculated independently, meaning you do not actually apply any operations, just calculate the minimum number of operations.
Let's take a closer look at how the fixing the array operation works: Suppose we have a missing number $p_{d_{i}}$, we know that the final permutation must contain this number, and the only place we can put the number $p_{d_{i}}$ is position $p_{d_{i}}$. However, if we place the number there, we might lose $p_{p_{d_{i}}}$, which also needs to be placed in the final permutation, and the only place we can put it is position $p_{p_{d_{i}}}$, but we might again lose some number, and so on. This process will end when we place a number in the position of an already missing number. This process can be implemented either recursively or iteratively, and we are only interested in the set of positions we need to fix. Let's denote the set of all positions to be fixed as $X$. Then we can observe the following: if the current query $d_{i}$ is contained in $X$, then the union of the sets of fixable positions for $d_{i}$ and $X$ is equal to $X$. If the query $d_{i}$ is not contained in $X$, then it adds some positions to the set $X$. Based on this observation, we can write a solution. I will outline the main points of the solution: we maintain the set $X$; when the query comes with $d_{i}$ that is contained in $X$, we do nothing and simply output the size of the set $X$; when the query comes with $d_{i}$ that is not contained in $X$, then we add all the positions that are necessary to fix the array if $d_{i}$ is missing, and output the size of the set $X$. The final implementation may have a complexity of $O(n)$ or $O(n \log n)$.
[ "dfs and similar", "dp", "dsu", "graphs", "greedy", "implementation" ]
1,300
#include<bits/stdc++.h> using namespace std; #define int long long void solve(){ int n; cin >> n; vector<int> p(n); for (int i = 0; i < n; i++){ cin >> p[i]; p[i]--; } set<int> X; for (int i = 0; i < n; i++){ int d; cin >> d; d--; while(!X.contains(d)){ X.insert(d); d = p[d]; } cout << X.size() << ' '; } cout << endl; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--){ solve(); } }
2086
D
Even String
You would like to construct a string $s$, consisting of lowercase Latin letters, such that the following condition holds: - For every pair of indices $i$ and $j$ such that $s_{i} = s_{j}$, the difference of these indices is even, that is, $|i - j| \bmod 2 = 0$. Constructing any string is too easy, so you will be given an array $c$ of $26$ numbers — the required number of occurrences of each individual letter in the string $s$. So, for every $i \in [1, 26]$, the $i$-th letter of the Latin alphabet should occur exactly $c_i$ times. Your task is to count the number of distinct strings $s$ that satisfy all these conditions. Since the answer can be huge, output it modulo $998\,244\,353$.
From the statement, it follows that all identical letters in $s$ must be positioned either at even indices or at odd indices simultaneously. Let's examine how the ways to construct the string $s$ are formed: A subset of letters that we take for the odd positions (the remaining letters will be at the even positions); The number of ways to create a string with a fixed subset of letters at the odd positions. Let $S$ denote the sum of the array $c$. We also denote $odd = \lceil\frac{S}{2}\rceil$ as the number of odd positions, and $even = \lfloor\frac{S}{2}\rfloor$ as the number of even positions. For now, let's ignore the second point and calculate how many ways there are to distribute the letters such that we can create at least one suitable string $s$. That is, we need to count the number of ways to choose a set of letters that will occupy the odd positions. This resembles a modification of the classical knapsack problem, which can be solved using dynamic programming. Let $\text{dp}[i]$ denote the number of ways to take a subset of letters such that the number of letters taken equals $i$. The base case of the dynamic programming is $\text{dp}[i] = 0$, and the entire dynamic can be computed using two nested loops: The number we're interested in will be in $\text{dp}[odd]$. Now we need to understand what to do with point $2$. Notice that if we have fixed a subset of letters $X$ at the odd positions, then the number of ways to create the string is equal to the product of the multinomial coefficients: $\frac{odd!}{\prod_{i \in X} c_{i}!} \cdot \frac{even!}{\prod_{i \notin X} c_{i}!}$ Notice that this product is a constant, meaning it does not depend on the specific subset $X$: $\frac{odd! \cdot even!}{\prod_{i = 0}^{26} c_{i}!}$ Thus, the answer to the entire problem is simply the product: $\frac{odd! \cdot even!}{\prod_{i = 0}^{26} c_{i}!} \cdot \text{dp}[odd]$ The total complexity complexity is $O(S \cdot 26)$.
[ "brute force", "combinatorics", "dp", "math", "strings" ]
1,700
#include<bits/stdc++.h> using namespace std; #define int long long const int MOD = 998'244'353; int bpow(int x, int p){ int res = 1; while(p){ if (p % 2){ res = (res * x) % MOD; } p >>= 1; x = (x * x) % MOD; } return res; } int fact(int x){ int res = 1; for (int i = 1; i <= x; i++){ res = (res * i) % MOD; } return res; } void solve(){ vector<int> c(26); for (int i = 0; i < 26; i++){ cin >> c[i]; } int s = accumulate(c.begin(), c.end(), 0ll); vector<int> dp(s + 1); dp[0] = 1; for (int i = 0; i < 26; i++){ if (c[i] == 0){ continue; } for (int j = s; j >= 0; j--){ if (j + c[i] <= s){ dp[j + c[i]] = (dp[j + c[i]] + dp[j]) % MOD; } } } int ans = dp[s / 2] * fact(s / 2) % MOD * fact((s + 1) / 2) % MOD; for (int i = 0; i < 26; i++){ ans = (ans * bpow(fact(c[i]), MOD - 2)) % MOD; } cout << ans << '\n'; } signed main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t; cin >> t; while(t--){ solve(); } }
2086
E
Zebra-like Numbers
We call a positive integer zebra-like if its binary representation has alternating bits up to the most significant bit, and the least significant bit is equal to $1$. For example, the numbers $1$, $5$, and $21$ are zebra-like, as their binary representations $1$, $101$, and $10101$ meet the requirements, while the number $10$ is not zebra-like, as the least significant bit of its binary representation $1010$ is $0$. We define the zebra value of a positive integer $e$ as the minimum integer $p$ such that $e$ can be expressed as the sum of $p$ zebra-like numbers (possibly the same, possibly different) Given three integers $l$, $r$, and $k$, calculate the number of integers $x$ such that $l \le x \le r$ and the zebra value of $x$ equals $k$.
First, let's see how many zebra-Like numbers less than or equal to $10^{18}$ exist. It turns out there are only $30$ of them, and based on some zebra-like number $z_{i}$, the next one can be calculated using the formula $z_{i + 1} = 4 \cdot z_{i} + 1$. Then, we have to be able to quickly calculate the zebra value for an arbitrary number $x$. Since each subsequent zebra-like number is approximately $4$ times larger than the previous one, intuitively, it seems like a greedy algorithm should be optimal: for any number $x$, we can determine its zebra value by subtracting the largest zebra-like number that does not exceed $x$, until $x$ becomes $0$. Let's prove the correctness of the greedy algorithm: Assume that $y$ is the smallest number for which the greedy algorithm does not work, meaning that in the optimal decomposition of $y$ into zebra-like numbers, the largest zebra-like number $z_{i}$ that does not exceed $y$ does not appear at all. If the greedy algorithm works for all numbers less than $y$, then in the decomposition of the number $y$, there must be at least one number $z_{i - 1}$. And since $y - z_{i - 1}$ can be decomposed greedily and will contain at least $3$ numbers $z_{i - 1}$, we will end up with at least $4$ numbers $z_{i - 1}$ in the decomposition. Moreover, there will be at least $5$ numbers in the decomposition because $4 \cdot z_{i - 1} < z_{i}$, which means it is also less than $y$. Therefore, if the fifth number is $1$, we simply combine $4 \cdot z_{i - 1}$ with $1$ to obtain $z_{i}$; otherwise, we decompose the fifth number into $4$ smaller numbers plus $1$, and we also combine this $1$ with $4 \cdot z_{i - 1}$ to get $z_{i}$. Thus, the new decomposition of the number $y$ into zebra-like numbers will have no more numbers than the old one, but it will include the number $z_i$ - the maximum zebra-like number that does not exceed $y$. This means that $y$ can be decomposed greedily. We have reached a contradiction; therefore, the greedy algorithm works for any positive number. Now, let's express the greedy decomposition of the number $x$ in a more convenient form. We will represent the decomposition as a string $s$ of length $30$ consisting of digits, where the $i$-th character will denote how many zebra numbers $z_{i}$ are present in this decomposition. Let's take a closer look at what such a string might look like: $s_{i} \in \{0, 1, 2, 3, 4\}$; if $s_{i} = 4$, then for any $j < i$, the character $s_{j} = 0$ (this follows from the proof of the greedy algorithm). Moreover, any number generates a unique string of this form. This is very similar to representing a number in a new numeric system, which we will call zebroid. In summary, the problem has been reduced to counting the number of numbers in the interval $[l, r]$ such that the sum of the digits in the zebroid numeral system equals $x$. This is a standard problem that can be solved using dynamic programming on digits. Instead of counting the suitable numbers in the interval $[l, r]$, we will count the suitable numbers in the intervals $[1, l]$ and $[1, r]$ and subtract the first from the second to get the answer. Let $\text{dp}[\text{ind}][\text{sum}][\text{num_less_m}][\text{was_4}]$ be the number of numbers in the interval $[1, m]$ such that: they have $\text{ind} + 1$ digits; the sum of the digits equals $\text{sum}$; $\text{num_less_m} = 0$ if the prefix of $\text{ind} + 1$ digits of the number $m$ is lexicographically greater than these numbers, otherwise $\text{num_less_m} = 1$; $\text{was_4} = 0$ if there has not been a $4$ in the $\text{ind} + 1$ digits of these numbers yet, otherwise $\text{was_4} = 1$. Transitions in this dynamic programming are not very difficult - they are basically appending a new digit at the end. The complexity of the solution is $O(\log^2 A)$, if we estimate the number of zebra-like numbers up to $A = 10^{18}$ as $\log A$. Alternative solution (BledDest) First, let's prove that we can decompose numbers into zebra-like numbers greedily, constantly subtracting the maximum zebra-like number we can (the proof is the same as in the first solution). After that, we will learn to calculate the following dynamic programming: $dp_{i,j}$ - the number of numbers from $0$ to $i-1$ with a zebra value of exactly $j$. The base states of the dynamic programming will be as follows: $dp_{0,x} = 0$ (since there are no numbers in the interval); $dp_{1,0} = 1$ (since the number $0$ has a zebra value of $0$); $dp_{1,i} = 0$ for $i \ne 0$ (similarly); $dp_{i,j} = 0$ for $i < 0$ (numbers cannot have negative zebra value). Additionally, the same can be done for $j$ greater than the number of zebra-like numbers multiplied by $4$ (since there cannot be more than $4$ identical zebra-like numbers in the decomposition of a number). Okay, now let's consider the transitions in this dynamic programming. Suppose we want to calculate $dp_{i,j}$. We find the largest zebra-like number $k$ that is less than $i$. Then for all numbers from $k$ to $i-1$, the maximum zebra number in the decomposition is $k$, and if we subtract it from them, we get the interval of numbers from $0$ to $i-k-1$. Therefore, $dp_{i,j} = dp_{k,j} + dp_{i-k,j-1}$. Intuitively, it seems that there are not many states in this dynamic programming, so it can be calculated "lazily", and we can store all already computed values in a map. But let's prove this. $j$ will be on the order of $\log A$, so let's estimate the number of different values of $i$ that we will need. We will divide them into two categories - zebra-like numbers $i$ and all others. If $i$ is a zebra-like number, then the previous zebra number is $k = \frac{i - 1}{4}$. Therefore, $dp_{i,j} = dp_{k,j} + dp_{i-k,j-1} = \dots = dp_{k,j} + dp_{k,j-1} + dp_{k,j-2} + dp_{k,j-3} + dp_{1,j-4}$. Thus, the states where $i$ is a zebra-like number generate $O(1)$ new states, and in total, the states where $i$ is zebra-like and the states generated by them will require only $O(\log A)$ different values of $i$. If $i$ is not a zebra-like number, one of the transitions leads to a state with a zebra-like number, and the other does not. That is, from each state, there is a "chain" of states with values of $i$ that are not zebra-like numbers, and the length of such a chain is $O(\log A)$ (since every $O(1)$ steps in the chain effectively take $i$ modulo some zebra-like number), so there will be a total of $O(\log A)$ values of $i$ that are not zebra numbers. Thus, the total number of states in the dynamic programming will be $O(\log^2 A)$, so the entire solution will work in $O(\log^2 A \log \log A)$ for each test case.
[ "bitmasks", "brute force", "constructive algorithms", "dfs and similar", "dp", "greedy", "math" ]
2,400
#include <bits/stdc++.h> using namespace std; vector<long long> z; void precalc() { z = {1ll}; while(z.back() < 1e18) z.push_back(4 * z.back() + 1); } map<pair<long long, long long>, long long> dp; long long get(long long r, long long x) { if(dp.count(make_pair(r, x))) return dp[make_pair(r, x)]; long long& d = dp[make_pair(r, x)]; if(x > 4 * z.size()) return d = 0; if(x < 0) return d = 0; if(r == 0) return d = 0; if(r == 1) { if(x == 0) return d = 1; return d = 0; } auto it = lower_bound(z.begin(), z.end(), r); --it; long long y = *it; return d = get(y, x) + get(r - y, x - 1); } int main() { precalc(); int t; cin >> t; for(int i = 0; i < t; i++) { long long l, r, x; cin >> l >> r >> x; cout << get(r + 1, x) - get(l, x) << endl; } }
2086
F
Online Palindrome
This is an interactive problem. The jury has a string $s$ consisting of lowercase Latin letters. The following constraints apply to this string: - the string has an odd length that does not exceed $99$; - the string consists only of the characters "a" and "b". There is also a string $t$, which is initially empty. Then, $|s|$ steps happen. During the $i$-th step, the following events occur: - first, the jury tells you the character $s_i$ and appends it to the end of the string $t$; - then, you may swap any two characters in $t$, or do nothing. Your task is to ensure that after the $|s|$-th step, the string $t$ is a palindrome.
From the problem statement, it can be understood that at each step, when we have an odd number of characters, the string $t$ must be a palindrome, since the length of the string $s$ is not provided. Therefore, we need to come up with a strategy for swaps to ensure this condition is met. The first thought is to try a brute-force approach of the following kind: When the current step is odd (i.e., $|t| \bmod 2 = 1$), let's obtain the next character $s_{i}$, add it to the end of $t$, and perform some swap. After this, two conditions must be satisfied: if we then add the character "a", the string $t$ can be turned into a palindrome with no more than one swap; if we then add the character "b", the string $t$ can be turned into a palindrome with no more than one swap. If the step is even, let's obtain the next character $s_{i}$, add it to the end of $t$, and perform a swap so that $t$ becomes a palindrome. If we try to submit this solution, we will get WA, as there can be situations where both conditions for the odd step are not satisfied simultaneously. This is due to the fact that we allow the construction of any palindromes. Based on this, we conclude that any palindrome is not suitable for us, and we need to maintain some template palindrome. The most challenging part of this problem is to find such a template. Next, I will describe how the template should look: if there is more than one letter "a", then we place the letter "a" as the first and last character; if there is more than one letter "b", then we place the letter "b" as the second and second-to-last character; if there is more than one letter "a", then we place the letter "a" as the third and third-to-last character; we alternate this way while possible; then we fill all paired positions with the letter that has more than one left; the center is filled unambiguously. All palindromes that start with the letter "b" and have the same form are also suitable for us. For example, the following strings fit the template: "a"; "bab"; "abbabba"; "abababaaaaabababa"; For this template, there are transitions (i.e., swaps such that from a template of length $x$ we can transition to a template of length $x + 2$ by adding any possible pair of characters), however, deriving them manually is quite complicated, as there are many situations. However, this can be added to our brute-force approach for the odd step. Once again, here's how it will look: obtain the next character from the input; iterate through a pair of characters in the string that we want to swap; for each iterated pair, consider two variants of the second incoming character. Check if we can obtain the expected template from the current string with no more than one swap; this can be checked unambiguously with a linear pass through the string and the expected template, looking at the differing positions; if for the checked permutation we can transition to the template with any next letter, then we perform that permutation. For the even step, we can simply find the necessary swap in a linear manner. Thus, the asymptotic complexity of this solution is $O(|s|^{4})$. As an appendix, I will list examples of transitions by pairs of characters in the template: "aaa" + "aa" $\to$ "aaaaa"; "aaa" + "ab" $\to$ "aabaa"; "aaa" + "bb" $\to$ "ababa"; "bab" + "aa" $\to$ "ababa"; "bab" + "ab" $\to$ "abbba"; "bab" + "bb" $\to$ "bbabb"; "ababa" + "aa" $\to$ "abaaaba"; "ababa" + "ab" $\to$ "abababa"; "ababa" + "bb" $\to$ "abbabba"; "abbba" + "aa" $\to$ "abababa"; "abbba" + "ab" $\to$ "abbabba"; "abbba" + "bb" $\to$ "abbbbba"; "bbabb" + "aa" $\to$ "abbabba"; "bbabb" + "ab" $\to$ "abbbbba"; "bbabb" + "bb" $\to$ "bbbabbb"; "ababbbbbbbaba" + "aa" $\to$ "abababbbbbababa"; "ababbbbbbbaba" + "ab" $\to$ "ababbbbabbbbaba"; "ababbbbbbbaba" + "bb" $\to$ "ababbbbbbbbbaba"; "ababbbabbbaba" + "aa" $\to$ "abababbabbababa"; "ababbbabbbaba" + "ab" $\to$ "abababbbbbababa"; "ababbbabbbaba" + "bb" $\to$ "ababbbbabbbbaba"; "ababaaaaababa" + "aa" $\to$ "ababaaaaaaababa"; "ababaaaaababa" + "ab" $\to$ "ababaaabaaababa"; "ababaaaaababa" + "bb" $\to$ "abababaaabababa"; "ababaabaababa" + "aa" $\to$ "ababaaabaaababa"; "ababaabaababa" + "ab" $\to$ "abababaaabababa"; "ababaabaababa" + "bb" $\to$ "abababababababa";
[ "brute force", "constructive algorithms", "interactive" ]
3,000
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) const int N = 100; bool dp[N][N]; pair<int, int> nxt[N][N][2]; bitset<N> cur; bitset<N> form[N][N]; int main(){ forn(i, N) forn(j, N) dp[i][j] = (i + j) % 2; for (int len = 1; len < N; len += 2){ forn(x, len + 1){ int y = len - x; int nx = x, ny = y; int i = 0; while (nx > 1 || ny > 1){ if (nx > 1){ nx -= 2; ++i; } if (ny > 1){ form[x][y][i] = form[x][y][len - i - 1] = 1; ny -= 2; ++i; } } if (ny > 0){ form[x][y][i] = 1; } } } for (int len = N - 3; len >= 1; len -= 2){ forn(x, len + 1){ int y = len - x; cur = form[x][y]; forn(c, 2){ cur[len] = c; bool found = false; forn(l, len + 1){ forn(r, l + 1){ if (cur[l] != cur[r]) cur[l].flip(), cur[r].flip(); bool ok = true; forn(d, 2){ cur[len + 1] = d; int nx = x + (c == 0) + (d == 0); int ny = y + (c == 1) + (d == 1); if ((cur ^ form[nx][ny]).count() > 2){ ok = false; break; } } if (ok){ found = true; nxt[x][y][c] = {l, r}; } if (cur[l] != cur[r]) cur[l].flip(), cur[r].flip(); if (found) break; } if (found) break; } if (!found){ dp[x][y] = false; break; } } } } string s; cur.reset(); for (int i = 0;; ++i){ cin >> s; if (s == "0") break; int c = s[0] - 'a'; int py = cur.count(), px = i - py; cur[i] = c; int nx = px + (c == 0), ny = py + (c == 1); int l = -1, r = -1; if (i % 2 == 1){ auto res = nxt[px][py][c]; if (res.first != res.second){ l = res.first; r = res.second; } } else{ assert(dp[nx][ny]); bitset<N> dif = cur ^ form[nx][ny]; assert(dif.count() <= 2); if (dif.count() == 2){ l = dif._Find_first(); r = dif._Find_next(l); } } if (l == -1){ cout << 0 << " " << 0 << endl; } else{ cout << l + 1 << " " << r + 1 << endl; if (cur[l] != cur[r]) cur[l].flip(), cur[r].flip(); } } }
2089
A
Simple Permutation
Given an integer $n$. Construct a permutation $p_1, p_2, \ldots, p_n$ of length $n$ that satisfies the following property: For $1 \le i \le n$, define $c_i = \lceil \frac{p_1+p_2+\ldots +p_i}{i} \rceil$, then among $c_1,c_2,\ldots,c_n$ there must be at least $\lfloor \frac{n}{3} \rfloor - 1$ prime numbers.
Lemma (Bertrand's postulate): For each positive integer $x$, there is a prime $p$ inside the interval $[x,2x]$. Find a prime number $p$ between $\lfloor \frac{n}{3} \rfloor$ and $\lceil \frac{2n}{3} \rceil$, and construct the permutation in an alternating way: $p, p-1, p+1, p-2, p+2, \dots$. Place the remaining numbers arbitrarily. In this construction, we have $c_1 = c_3 = c_5 = \dots = c_{2 \lfloor \frac{n}{3} \rfloor - 1} = p$, which meets the requirement with at least $\lfloor \frac{n}{3} \rfloor$ numbers being prime. 2089B1 - Canteen (Easy Version) Idea: Ecrade_
[ "constructive algorithms", "number theory" ]
1,700
#include<bits/stdc++.h> using namespace std; bool isPrime(int x){ if(x <= 1) return 0; for(int i = 2 ; i * i <= x ; ++i) if(x % i == 0) return 0; return 1; } vector<int> generateSol(int n, int p){ vector<int> ans; ans.push_back(p); for(int i = 1 ; i <= n ; ++i){ if(p - i > 0) ans.push_back(p - i); if(p + i <= n) ans.push_back(p + i); } return ans; } int main(){ int t; cin >> t; for(int i = 1 ; i <= t ; ++i){ int n; cin >> n; vector < int > ans; for(int x = 0 ; ; ++x){ if(isPrime(n / 2 - x)){ ans = generateSol(n , n / 2 - x); break; } if(isPrime(n / 2 + x)){ ans = generateSol(n , n / 2 + x); break; } } for(int i = 0 ; i < n ; ++i) cout << ans[i] << " \n"[i == n - 1]; } return 0; }
2089
B1
Canteen (Easy Version)
\textbf{This is the easy version of the problem. The difference between the versions is that in this version, $k=0$. You can hack only if you solved all versions of this problem.} Ecrade has two sequences $a_0, a_1, \ldots, a_{n - 1}$ and $b_0, b_1, \ldots, b_{n - 1}$ consisting of integers. It is guaranteed that the sum of all elements in $a$ does not exceed the sum of all elements in $b$. Initially, Ecrade can make exactly $k$ changes to the sequence $a$. It is guaranteed that $k$ does not exceed the sum of $a$. In each change: - Choose an integer $i$ ($0 \le i < n$) such that $a_i > 0$, and perform $a_i := a_i - 1$. Then Ecrade will perform the following three operations sequentially on $a$ and $b$, which constitutes one round of operations: - For each $0 \le i < n$: $t := \min(a_i, b_i), a_i := a_i - t, b_i := b_i - t$; - For each $0 \le i < n$: $c_i := a_{(i - 1) \bmod n}$; - For each $0 \le i < n$: $a_i := c_i$; Ecrade wants to know the minimum number of rounds required for all elements in $a$ to become equal to $0$ after exactly $k$ changes to $a$. However, this seems a bit complicated, so please help him!
For each $a_i$, calculate the minimum number of cyclic right shifts required to reduce it to zero, denoted as $d_i$. The answer is the maximum $d_i$ across all $i$. For cyclic problems, we can consider breaking the cycle into a chain (i.e., let $a_{i+n} = a_i$, $b_{i+n} = b_i$). Consider constructing a parenthesis sequence $s$ by concatenating $a_0$ left parentheses, $b_0$ right parentheses, $a_1$ left parentheses, $b_1$ right parentheses, ... ,$a_{2n-1}$ left parentheses and $b_{2n-1}$ right parentheses. The operation in the original problem corresponds to the process of matching parentheses in $s$: "Set the smaller of $(a_i, b_i)$ to zero and the larger to their difference" $\Rightarrow$ "Match the parentheses corresponding to $(a_i, b_i)$". "Cyclically right-shift $a$" $\Rightarrow$ "Unmatched left parentheses continue to find matching right parentheses". The first time $a_i$ is reduced to zero depends on which $b_j$ 's right parenthesis matches the leftmost parenthesis corresponding to $a_i$. We can use prefix sums to find matchings of the parenthesis: Let $c_i = \sum\limits_{j=0}^i (a_j - b_j)$. Define $p_i$ as the smallest index satisfying $p_i > i$ and $c_{p_i} \leq c_i$, then $d_i = p_i - i$. We can compute all $p_i$ with a monotonic stack. It should be pointed out that matching parentheses is just an intuitive way of understanding the solution. You can, of course, also draw the above conclusion by direct observation. The time complexity is $O(\sum n)$. 2089B2 - Canteen (Hard Version) Idea: Ecrade_
[ "binary search", "data structures", "flows", "greedy", "two pointers" ]
1,900
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,k,a[400009],stk[400009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } int main(){ t = read(); while (t --){ n = read(),k = read(); for (ll i = 1;i <= n;i += 1) a[i] = read(); for (ll i = 1;i <= n;i += 1) a[i] = a[i + n] = a[i] - read(); for (ll i = 1;i <= 2 * n;i += 1) a[i] += a[i - 1]; ll tp = 0,ans = 0; for (ll i = 2 * n;i >= 1;i -= 1){ while (tp && a[stk[tp]] > a[i]) tp -= 1; if (i <= n) ans = max(ans,stk[tp] - i); stk[++ tp] = i; } printf("%lld\n",ans); } return 0; }
2089
B2
Canteen (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, there are no additional limits on $k$. You can hack only if you solved all versions of this problem.} Ecrade has two sequences $a_0, a_1, \ldots, a_{n - 1}$ and $b_0, b_1, \ldots, b_{n - 1}$ consisting of integers. It is guaranteed that the sum of all elements in $a$ does not exceed the sum of all elements in $b$. Initially, Ecrade can make exactly $k$ changes to the sequence $a$. It is guaranteed that $k$ does not exceed the sum of $a$. In each change: - Choose an integer $i$ ($0 \le i < n$) such that $a_i > 0$, and perform $a_i := a_i - 1$. Then Ecrade will perform the following three operations sequentially on $a$ and $b$, which constitutes one round of operations: - For each $0 \le i < n$: $t := \min(a_i, b_i), a_i := a_i - t, b_i := b_i - t$; - For each $0 \le i < n$: $c_i := a_{(i - 1) \bmod n}$; - For each $0 \le i < n$: $a_i := c_i$; Ecrade wants to know the minimum number of rounds required for all elements in $a$ to become equal to $0$ after exactly $k$ changes to $a$. However, this seems a bit complicated, so please help him!
We can use binary search on the answer $x$, and calculate the minimum number of changes needed to make $a$ zero within $x$ rounds. However, direct computation on the cyclic chain of $2n$ elements is troublesome (due to overlapping contributions). Instead, we can cyclically shift $a$ and $b$ such that $c_{n-1} = \min\limits_{i=0}^{n-1} c_i$, which ensures that no $a_{n-1}>0$ will be cyclically shifted to $a_0$, enabling us to only consider the first $n$ elements of the chain. For the adjusted $a$ and $b$, we can greedily process $i$ from $n - x - 1$ to $-1$: If $\min\limits_{j=i+1}^{i+x}c_j > c_i$, then we should apply $\min\limits_{j=i+1}^{i+x}c_j - c_i$ changes to $a_{i+1}$ (assume that $c_{-1}=0$). We can also use a monotonic stack to maintain the whole process. Note that if $\sum\limits_{i=0}^{n-1} a_i=k$, we should output $0$. The time complexity is $O(\sum n\log k)$. Bonus: Find an $O(\sum n)$ solution. 2089C2 - Key of Like (Hard Version) Idea: SpiritualKhorosho
[ "binary search", "data structures", "dp", "flows", "greedy", "two pointers" ]
2,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,k,pos,a[400009],stk[400009]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } bool judge(ll x){ ll l = 1,r = 0,res = 0; for (ll i = pos;i >= pos - n;i -= 1){ if (l <= r && stk[l] - i > x) l += 1; if (pos - i >= x) res += max(0ll,a[stk[l]] - a[i]); if (res > k) return 0; while (l <= r && a[stk[r]] > a[i]) r -= 1; stk[++ r] = i; } return 1; } int main(){ t = read(); while (t --){ n = read(),k = read(); ll suma = 0; for (ll i = 1;i <= n;i += 1) a[i] = read(),suma += a[i]; for (ll i = 1;i <= n;i += 1) a[i] -= read(),a[i + n] = a[i]; if (suma == k){puts("0"); continue;} for (ll i = 1;i <= 2 * n;i += 1) a[i] += a[i - 1]; pos = n; for (ll i = n + 1;i <= 2 * n;i += 1) if (a[i] < a[pos]) pos = i; ll l = 1,r = n,ans = n; while (l <= r){ ll mid = (l + r) >> 1; if (judge(mid)) ans = mid,r = mid - 1; else l = mid + 1; } printf("%lld\n",ans); } return 0; }
2089
C2
Key of Like (Hard Version)
\textbf{This is the hard version of the problem. The difference between the versions is that in this version, $k$ can be non-zero. You can hack only if you solved all versions of this problem.} A toy box is a refrigerator filled with childhood delight. Like weakness, struggle, hope ... When such a sleeper is reawakened, what kind of surprises will be waiting? M received her toy box as a birthday present from her mother. A jewellery designer would definitely spare no effort in decorating yet another priceless masterpiece as a starry firmament with exquisitely shaped gemstones. In addition, $l$ distinct locks secure the tiny universe of her lovely daughter: a hair clip featuring a flower design, a weathered feather pen, a balloon shaped like the letter M ... each piece obscures a precious moment. A few days ago, M rediscovered her toy box when she was reorganizing her bedroom, along with a ring of keys uniquely designed for the toy box. Attached to the key ring are $(l + k)$ keys, of which $l$ keys are able to open one of the $l$ locks correspondingly, while the other $k$ keys are nothing but counterfeits to discourage brute-force attack. To remind the correspondence, M's mother adorned each key with a gemstone of a different type. However, passing days have faded M's memory away. "... So I have to turn to you all," M said while laying that ring of keys on the table. K picked up the keys and examined them carefully. "The appearance of these keys unveils nothing fruitful. Thus, I am afraid that we shall inspect them sequentially." Although everyone is willing to help M, nobody has a plan. Observing others' reactions, T suggested, "Let's play a game. Everyone tries a key in turn, and who opens the most locks is amazing." $n$ members, including M herself, take turns to unlock the toy box recursively in the same order until all the $l$ locks are unlocked. At each turn, the current member only selects a single key and tests it on exactly one of the locks. To open the toy box as soon as possible, every member chooses the key and the lock that maximize the probability of being a successful match. If there are multiple such pairs, a member will randomly choose one of such pairs with equal probability. Apparently, if a lock has been matched with a key, then neither the lock nor the key will be chosen again in following attempts. Assume that at the very beginning, the probability that a lock can be opened by any key is equal. If everyone always tries the optimal pairs of keys and locks based on all the historical trials, what will the expected number of successful matches be for each member?
This problem is inspired by a minigame from a recently released party video game, but the story was modified to comply with the title. We tried to isolate the artistic part and the theoretical part, and I apologize if you still feel like working on reading comprehension exercises. Noticing that each member's strategy is not maximizing the total outcome (which is the expected number of successful matches between keys and locks), but only maximizing the outcome in her current turn, and equally likely to adopt each of optimal (pure) strategies, it will be ideal if there is some simple form of the strategy that only depends on $L$ and $K$. At the very beginning, when there is no information about the relationship between keys and locks, the first member in her first turn must randomly choose a key and a lock. What about the second member, if the first one is not lucky enough? Since she will not choose the same pair of keys and locks, there are three different types of (pure) strategies: Choose a different key to open the same lock; Choose a different key to open the same lock; Choose the same key to open a different lock; Choose the same key to open a different lock; Choose a different key and a different lock. Choose a different key and a different lock. For the first type of strategy, since there are $(L+K-1)$ keys remaining (after the very first attempt), and among them is only one correct key, the probability of opening the same lock is $1/(L+K-1)$. For the second type, it can be proven that the probability is also $1/(L+K-1)$. Another way to think of this is, add $K$ imaginary locks and match each of them with a counterfeit key. Then, it is apparent that a new lock matches the selected key with the given probability. The key selected by the first member can either be a real key or a counterfeit one. Denote the event of the key being authentic as $A$, and that of it failing to open the lock at the first turn as $B$. Then, according to the Bayes' theorem along with the law of total probability, $\begin{equation} \begin{split} P(A|B) &= \frac{P(B|A)P(A)}{P(B)} = \frac{P(B|A)P(A)}{P(B|A)P(A) + P\left(B\left|\bar{A}\right.\right)P\left(\bar{A}\right)} \\ &= \frac{((L-1)/L)\cdot (L/(L+K))}{((L-1)/L)\cdot (L/(L+K)) + 1\cdot(K/(L+K))}\\ &= \frac{L-1}{L+K-1},\\ P\left(\left.\bar{A}\right|B\right) &= 1 - P(A|B) = \frac{K}{L+K-1}. \end{split} \end{equation}$ Thus, the probability that the same key selected by the first member can open another lock randomly chosen by the second member (denoted as $C$) is $\begin{equation} \begin{split} P(C|B) &= P(A|B)\cdot P(C|AB) + P\left(\left.\bar{A}\right|B\right)\cdot P\left(C\left|\bar{A}B\right.\right)\\ &=\frac{L-1}{L+K-1}\cdot\frac{1}{L-1} + \frac{K}{L+K-1}\cdot 0\\ &= \frac{1}{L+K-1}. \end{split} \end{equation}$ For the third type of strategy, its probability can be computed from either the first type or the second type, as $(L+K-1)$ different outcomes are equally likely to happen: $\begin{equation} \frac{1-1/(L+K-1)}{L+K-1}=\frac{L+K-2}{(L+K-1)^2}<\frac{1}{L+K-1}. \end{equation}$ In conclusion, the second member will either choose the same key or the same lock. Because there are $(L - 1)$ pairs of the same key and other locks, and $(L + K - 1)$ pairs of other keys and the same lock, the second member will use the same key with probability $(L - 1)/(2L + K - 2)$, or check the same lock with probability $(L + K - 1)/(2L + K - 2)$. As for all the following attempts, a similar Proof shows that, everyone will imitate the strategy adopted by the second member. That is to say, if the second member decides to continue with the same key, everyone will keep using this same key, until a lock is opened or all the locks are checked; if the second member picks a different key for the same lock, everyone will challenge this same lock, until it is eventually settled (and obviously it will). Furthermore, whenever a key is identified as counterfeit, or a lock is opened, the information 'collapses', which turns the original problem into a subproblem with either one less counterfeit key (corresponding to $K' = K - 1$), or both one less valid key and one less lock ($L' = L - 1$), respectively. To sum up, the process of the game is: Whenever a lock is opened, the original problem is reduced to a subproblem with $L' = L - 1$; Whenever a key is proven counterfeit, the original problem is reduced to a subproblem where $K' = K - 1$; -The first member randomly chooses a key and a lock to check if they match; If the first member fails, the second member adopts the same key with probability $(L - 1)/(2L + K - 2)$, or investigates the same lock with probability $(L + K - 1)/(2L + K - 2)$; If the second member fails as well, all the following attempts will replicate the choice of whether to employ the same key or the same lock. Knowing the concrete strategies, the task now becomes how to compute the expected values efficiently. As you might have imagined, it can be achieved using dynamic programming due to the existence of overlapping subproblems. But let's examine another approach which might be easier to understand: compute $p_i (l, k)$, the total probability that the $i$-th member begins a subproblem with $l$ locks and $k$ counterfeit keys, and accumulate $e_i$'s during the computation. Transitions for $p$ itself include (and those from $p$ to $e$ will be similar to): The first member manages to open the lock without any prior information; The second member makes a successful guess; Any of the succeeding attempts succeeds; Everyone uses the same key but it fails on all the locks. For each $p_i(l, k)$, all the transition can be easily processed in $\Theta(1)$ time, except the third one. A verbatim implementation requires $O(L + K)$ time per state, which is apparently not efficient enough. Since $N \ll L$, a possible work-around is to compute the transition coefficient for each member, instead of each attempt. Intuitively, all attempts should share the same probability of success, regardless of the order. A simplified model is to draw all balls sequentially without replacement from a box of $1$ red ball and $(x-1)$ white balls, in which the red ball appears at the $i$-th attempt with an equal probability of $1/x$. Of course, the observation for our problem can also be proven mathematically, but let's omit it for simplicity. This important observation reduces the time complexity of the third type of transition to $O(N)$, as we can first compute the maximum number of attempts for each member, and then multiply it with the common probability of a single attempt. However, this is still not enough for passing the problem (and we adjusted the constraints to prevent so). The final trick to pass all testcases requires revisiting the transition coefficients we just computed. Notice that, if all the members have $a$ attempts in total (but for the third type of transition only, which excludes the first two), then: If $a$ is a multiple of $N$, then every member can have at most $a/N$ attempts; If $a$ is a multiple of $N$, then every member can have at most $a/N$ attempts; Otherwise, the first $a \bmod N$ members (right after the second member, who decides to advance with the same key or the same lock) can have at most $\lceil a/N\rceil$ attempts, while all the others can have at most $\lfloor a/N\rfloor$ attempts. Otherwise, the first $a \bmod N$ members (right after the second member, who decides to advance with the same key or the same lock) can have at most $\lceil a/N\rceil$ attempts, while all the others can have at most $\lfloor a/N\rfloor$ attempts. This implies that the transition coefficients consists of at most $3$ maximal contiguous subsequences of the same coefficients (in fact, if the coefficients are treated as a circular sequence, then there will be exactly $1$ or $2$ for the two cases respectively). Using techniques such as prefix sums helps further decrease the complexity of the computation to $\Theta(1)$ per state. The total time complexity is $O(NLK)$. 2089D - Conditional Operators Idea: E.Space
[ "dp", "math", "probabilities" ]
3,100
#include <cstdio> #include <cstring> using namespace std; #define MOD 1000000007 #define MAXN 108 #define MAXL 5004 #define MAXK 27 int e[MAXN], p[2][MAXK][MAXN], inv[2 * MAXL + MAXK]; inline void _update(int * const a, const int lbd, const int rbd, const int base, const int diff) { (a[0] += base) %= MOD; (a[lbd] += diff) %= MOD; (a[rbd] += MOD - diff) %= MOD; return ; } #define Hill(_a, _lbd, _rbd, _base, _diff) _update(_a, _lbd, _rbd, _base, _diff) #define Valley(_a, _lbd, _rbd, _base, _diff) _update(_a, _rbd, _lbd, ((_base) + (_diff)) % MOD, MOD - (_diff)) #define Update(_a, _lbd, _rbd, _base, _diff) { if (_lbd < _rbd) Hill(_a, _lbd, _rbd, _base, _diff); else Valley(_a, _lbd, _rbd, _base, _diff); } int like() { int n, l, k, i, j, a, b, dh, now, nxt, totk, ntry, prob, pd, pb, lbd, rbd; scanf("%d %d %d", &n, &l, &k); if (n == 1) { printf("%d\n", l); return 0; } inv[1] = 1; j = 2 * l + k; for (i = 2; i <= j; ++i) inv[i] = 1ll * (MOD - MOD / i) * inv[MOD % i] % MOD; memset(p, 0, sizeof(p)); memset(e, 0, sizeof(e)); p[0][0][0] = 1; p[0][0][1] = -1; now = 0; nxt = 1; for (i = 0; i < l; ++i) { for (j = 0; j <= k; ++j) { totk = l + k - i - j; for (a = 1; a < n; ++a) (p[now][j][a] += p[now][j][a - 1]) %= MOD; for (a = 0; a < n; ++a) { // Match at the first try prob = 1ll * p[now][j][a] * inv[totk] % MOD; (e[a] += prob) %= MOD; if (a != n - 1) (e[a + 1] += MOD - prob) %= MOD; (p[nxt][j][(a + 1) % n] += prob) %= MOD; if (a != n - 2) (p[nxt][j][(a + 2) % n] += MOD - prob) %= MOD; prob = 1ll * prob * inv[totk + l - i - 2] % MOD; // Same lock pd = 1ll * prob * (ntry = totk - 1) % MOD; pb = 1ll * (ntry / n) * pd % MOD; if (dh = ntry % n) { lbd = (a + 1) % n; rbd = (a + dh) % n + 1; Update(e, lbd, rbd, pb, pd); (++lbd) %= n; ++(rbd %= n); Update(p[nxt][j], lbd, rbd, pb, pd); } else { (e[0] += pb) %= MOD; (p[nxt][j][0] += pb) %= MOD; } // Same key pd = 1ll * prob * (ntry = l - i - 1) % MOD; if (j < k) { pb = 1ll * pd * (k - j) % MOD; b = (a + l - i) % n; (p[now][j + 1][b] += pb) %= MOD; if (b != n - 1) (p[now][j + 1][b + 1] += MOD - pb) %= MOD; } pb = 1ll * (ntry / n) * pd % MOD; if (dh = ntry % n) { lbd = (a + 1) % n; rbd = (a + dh) % n + 1; Update(e, lbd, rbd, pb, pd); (++lbd) %= n; ++(rbd %= n); Update(p[nxt][j], lbd, rbd, pb, pd); } else { (e[0] += pb) %= MOD; (p[nxt][j][0] += pb) %= MOD; } } } now ^= 1; nxt ^= 1; memset(p[nxt], 0, sizeof(int) * MAXK * MAXN); } for (i = 1; i < n; ++i) (e[i] += e[i - 1]) %= MOD; for (i = 0; i < n; ++i) printf("%d%c", e[i], " \n"[i == n - 1]); return 0; } int main() { int t; scanf("%d", &t); while (t--) { like(); } return 0; }
2089
D
Conditional Operators
In C++, the conditional operator ?: is used as the value of x?y:z is $y$ if $x$ is true; otherwise, the value is $z$. $x$, $y$, and $z$ may also be expressions. It is right-associated; that is, a?b:c?d:e is equivalent to a?b:(c?d:e). $0$ means false and $1$ means true. Given a binary string with length $2n+1$, you need to show whether the value of the expression can be $1$ after inserting $n$ conditional operators into the string. You can use parentheses. For example, the string 10101 can be transformed into (1?0:1)?0:1, whose value is $1$.
Each operation transform three adjacent characters into one. If the string starts with 11, the answer should be yes since we can first transform the remaining part into a single 0 or 1 and then the value of 11? is always $1$. If the string ends with 1, only 101 has no solution, otherwise it starts with 11 or 0, or we can transform 10? in the front of the string into a 0. Then transform the rest part of the string into a single character to make the last operation 0?(anything):1 makes 1. If an operation transformed a string ending with 0 into one ending with 1, it must be 1?1:0 makes 1. Consider the case where the strings contains 11 as a substring. After transforming the remaining part, ?11?? or ??11? will be derived. The cases are 01100, 00110, 01110, 10110. All other cases start with 11 or end with 1. All cases of ??11? have a solution: (0?0:1)?1:0 makes 1. (0?1:1)?1:0 makes 1. 1?(0?1:1):0 makes 1. However, 01100 has no solution. Since 0?0:1 equals 1, before the last 1, any two adjacent 0's with no 1 in between can be eliminated. Thus, if there are two 1's with an even number of 0's in between, and there are an even number of characters in front the former 1, i.e., (..)*1(00)*1(..)*0 in regular expression, the answer should be yes, since after eliminating the 0's in between, the 1's become adjacent. The parity of the characters before the former 1 guarantees that it will not become 01100. Another case is that the string ends with 0 and every pair of adjacent 1's has an odd number of 0's in between. Since 0(1?0:1)0 makes 000, 1(0?1:0)1 makes 101, 10(1?0:0)01 makes 10001, there is no way to change the parity of the consecutive 0's to make 11 to change the ending 0 into 1. In the remaining case, there are even 0's between some pair of adjacent 1's, but the number of characters before the first 1 is odd, there must be only one pair. Suppose the string is 1-indexed. It is because the indices of such pair of 1's must be [odd, even]; while the indices in the previous case must be [even, odd]. Thus, if there are two such pairs of this case [odd, even], in the parity sequence [odd, even, ..., odd, even] there must be an [even, odd] as a substring. Therefore, any other pair of adjacent 1's must have odd 0's in between, i.e., $0(00)^*\color{blue}{(10(00)^*)^*}\color{red}1\color{black}(00)^*\color{red}1\color{blue}{((00)^*01)^*}\color{black}(00)^+$ in regular expression. Any operation remains the string in this case, except that the string is $0(00)^*\color{blue}{(10(00)^*)^*}\color{red}1\color{red}1\color{black}(00)^+$ and the operation is $\color{red}1\color{black}?\color{red}1\color{black}:0$ makes 1. Since it must ends with 00, it becomes a string ending with 0 and every pair of adjacent 1's has odd 0's in between, which is a case mentioned before that has no solution. In conclusion, it has a solution if and only of at least one of the two following conditions is met: It ends with 1 but it is not 101. It has two adjacent 1's such that there are even 0's in between and the number of characters before the former 1 is even. 2089E - Black Cat Collapse Idea: abruce
[ "constructive algorithms" ]
3,200
#include<bits/stdc++.h> char s[333333]; char val(char x,char y,char z){ return x=='1'?y:z; } std::pair<std::string, char> fold(int l,int r){ std::string str; char v=s[r]; for(int i=l;i<r;i+=2){ str+=s[i]; str+='?'; str+=s[i+1]; str+=':'; } str+=s[r]; for(int i=r-2;i>=l;i-=2){ v=val(s[i],s[i+1],v); } return std::make_pair(str,v); } void solve(){ int n; scanf("%d",&n); n=2*n+1; scanf("%s",s+1); int last=0; for(int i=1;i<=n;++i){ if(s[i]=='1'&&last>0){ if(i%2==0&&last&1){ puts("Yes"); std::string s4=fold(last+1,i).first; auto tmp=fold(i+1,n); std::string s5=tmp.first; char v5=tmp.second; if(last==1){ printf("1?(%s):(%s)\n",s4.c_str(),s5.c_str()); return; } tmp=fold(1,last-2); std::string s1=tmp.first; char v1=tmp.second; if(v1=='1'){ printf("(%s)?(%c?1:(%s)):(%s)\n",s1.c_str(),s[last-1],s4.c_str(),s5.c_str()); } else{ printf("((%s)?%c:1)?(%s):(%s)\n",s1.c_str(),s[last-1],s4.c_str(),s5.c_str()); } return; } } if(s[i]=='1'){ last=i; } } if(s[n]=='1'&&std::string(s+1)!="101"){ puts("Yes"); auto left=s[1]=='0'?fold(1,1):fold(1,3); auto mid=s[1]=='0'?fold(2,n-1):fold(4,n-1); printf("(%s)?(%s):1\n",left.first.c_str(),mid.first.c_str()); return; } puts("No"); return; } int main(){ int T; scanf("%d",&T); while(T--){ solve(); } return 0; }
2089
E
Black Cat Collapse
The world of the black cat is collapsing. In this world, which can be represented as a rooted tree with root at node $1$, Liki and Sasami need to uncover the truth about the world. Each day, they can explore a node $u$ that has not yet collapsed. After this exploration, the black cat causes $u$ and all nodes in its subtree to collapse. Additionally, at the end of the $i$ th day, if it exists, the number $n-i+1$ node will also collapse. For each $i$ from $1$ to $n$, determine the number of exploration schemes where Liki and Sasami explore exactly $i$ days (i.e., they perform exactly $i$ operations), with the last exploration being at node $1$. The result should be computed modulo $998\,244\,353$. \textbf{Note:} It is guaranteed that nodes $1$ to $n$ can form a "DFS" order of the tree, meaning there exists a depth-first search traversal where the $i$ th visited node is $i$.
Firstly, consider a classical dp to calculate $dp_{u,k}$ as the number of delete $k$ vertices in subtree $u$ without considering deleting vertex $n-i+1$ everyday. This is trivial. Then, due to the existence of an "automatic deletion" process, we cannot view the selected points within the subtree of $u$ as operations with only relative order, because they may be illegal. However, we consider the final operation sequence, putting the vertex chosen on the $i$ th day in the position $n-i+1$. That is, if we firstly choose $4$, then $3$, then $1$, it will be $0431$. Then, one vertex $u$ must be put in position $u$ or later. Then, we find that for the subtree of vertex $u$ with DFS order interval $[l,r]$, all vertices can't be put in position before $l$, and it is always legal to put in position after $r$ if parent-child relations are satisfied. So we consider a dp $f_{u,i,j,k}$ which represents that the subtree of $u$ leaves position $i$ for ancestors (which means nothing can be placed at position $i$ or before, and if $i=0$, then nothing is left for ancestors), there are $j$ empty spaces (not including the one left for ancestors), and $k$ vertices need to be put into positions after the subtree of $u$. In the $i=0$ case, we merge subtrees, and the subtree with smaller DFS order can put some backward operations into the space of the subtree with bigger DFS order. Specifically, consider the sons of $u$ enumerated in reverse order of DFS, and the son is $v$. Then enumerate $w$ as how many backward operations of $v$ will fill in space of $u$. The transition is $f_{u,0,j+j1-w,k+k1-w}\leftarrow f_{u,0,j+j1-w,k+k1-w}+f_{u,0,j,k}\times f_{v,0,j1,k1}\times \binom{j}{w}\times\binom{k+k1-w}{k}$. That is, after putting $w$ operations from backward operations of $v$ into spaces of $u$, we merge the spaces of $u$ and $v$, then the backward operations of $u$ and $v$. For $f_{v,i,j,k}(i\neq 0)$, it won't interfere with the transition with its following siblings. And for $f_{u,i,j,k}$,any operations from $v$ can't put into the subtree of $u$ and $v$, so we only need to merge backward operations of $u$ and $v$. After finishing the transition of subtrees, we consider where to put $u$. If we don't put $u$, there will be one more space, and we can consider whether to leave it for ancestors if $i=0$.That is $f_{u,i,j,k}\rightarrow f_{u,i,j+1,k},f_{u,0,j,k}\rightarrow f_{u,u,j,k}$. We put $u$ into the position left for ancestors, that is $f_{u,i,j,k}\rightarrow f_{u,0,j+1,k}$. And we can leave another position for ancestors of $u$, that is $f_{u,i,j,k}\rightarrow f_{u,i1,j+1,k}(i1<i)$. We put $u$ into position $u$, in that case, we can't leave position for ancestors of $u$, that is $f_{u,0,j,k}\rightarrow f_{u,0,j,k}$. We put $u$ backward, then we can't put anything in the subtree of $u$, but we can leave position for ancestors of $u$, that is $f_{u,i,siz_u-2,k}\rightarrow f_{u,i,siz_u-1,k+1},f_{u,0,siz_u-1,k}\rightarrow f_{u,0,siz_u,k+1}$. The answer for $i$ operations is just we leave position $n-i+1$ for $1$, and there are $n-i$ spaces (therefore the spaces are before $n-i+1$) and no backward operations. The time complexity is $O(\sum n^5)$.
[]
3,500
#include<bits/stdc++.h> using namespace std; typedef long long ll; int read() { int x=0,f=1; char c=getchar(); while(c<'0'||c>'9') { if(c=='-')f=-1; c=getchar(); } while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar(); return x*f; } namespace tokido_saya { const int maxn=81,mod=998244353; typedef vector<int>::iterator iter; int n,lp[maxn],rp[maxn],siz[maxn],t; vector<int> v[maxn]; ll f[maxn][maxn][maxn][maxn],dp[maxn][maxn],fac[maxn],inv[maxn]; int zc[maxn][maxn][maxn][maxn]; ll qpow(ll x,int y) { ll w=1; while(y) { if(y&1)w=w*x%mod; x=x*x%mod,y>>=1; } return w; } ll C(int x,int y) { if(y<0||y>x)return 0; return fac[x]*inv[x-y]%mod*inv[y]%mod; } void dfs1(int u) { lp[u]=rp[u]=u; for(iter it=v[u].begin();it!=v[u].end();it++)dfs1(*it),rp[u]=max(rp[u],rp[*it]); } void dfs2(int u) { f[u][0][0][0]=1,dp[u][0]=1; for(iter it=v[u].begin();it!=v[u].end();it++) { int v=*it; dfs2(v); for(int i=siz[u];i>=0;i--) for(int j=siz[v];j;j--)dp[u][i+j]=(dp[u][i+j]+dp[u][i]*dp[v][j]%mod*C(i+j,j))%mod; for(int j1=0;j1<=siz[v];j1++) for(int k1=0;k1<=min(j1+1,siz[v]);k1++) { memset(zc[j1][k1],0,sizeof(zc[j1][k1])); for(int j=0;j<=siz[u];j++) for(int k=0;k<=j+1;k++) for(int w=0;w<=min(k1,j);w++)zc[j1][k1][j+j1-w][k+k1-w]=(zc[j1][k1][j+j1-w][k+k1-w]+f[u][0][j][k]*C(j,w)%mod*C(k+k1-w,k))%mod; } memset(f[u][0],0,sizeof(f[u][0])); for(int j=0;j<=siz[v];j++) for(int k=0;k<=j+1;k++) for(int j1=0;j1<=siz[u]+siz[v];j1++) for(int k1=0;k1<=min(siz[u]+siz[v],j1+1);k1++) if(zc[j][k][j1][k1]) { const int w=zc[j][k][j1][k1]; f[u][0][j1][k1]=(f[u][0][j1][k1]+f[v][0][j][k]*w)%mod; for(int i=lp[v];i<=rp[v];i++)f[u][i][j1][k1]=(f[u][i][j1][k1]+f[v][i][j][k]*w)%mod; } for(int i=rp[v]+1;i<=rp[u];i++) for(int j=siz[u]-1;j>=i-rp[v]-1;j--) for(int k=j+1;k>=0;k--) { const int val=f[u][i][j][k]; f[u][i][j][k]=0; for(int p=0;p<=siz[v];p++) for(int w=0;w<=min(p,j-(i-rp[v]-1));w++)f[u][i][j+siz[v]-w][k+p-w]=(f[u][i][j+siz[v]-w][k+p-w]+dp[v][p]*val%mod*C(j-(i-rp[v]-1),w)%mod*C(k+p-w,k))%mod; } siz[u]+=siz[v]; } for(int i=siz[u];i>=0;i--)dp[u][i+1]=(dp[u][i+1]+dp[u][i])%mod; if(u!=1)for(int j=siz[u];j>=0;j--) for(int k=min(j+1,siz[u]);k>=0;k--) { ll sum=0; for(int i=rp[u];i>=lp[u];i--) { const int w=f[u][i][j][k]; f[u][i][j+1][k]=(f[u][i][j+1][k]+w)%mod; if(j==siz[u]-1)f[u][i][j+1][k+1]=(f[u][i][j+1][k+1]+w)%mod; f[u][i][j][k]=sum,sum=(sum+w)%mod; } const int w=f[u][0][j][k]; f[u][lp[u]][j][k]=(f[u][lp[u]][j][k]+w)%mod,f[u][0][j+1][k]=(f[u][0][j+1][k]+w+sum)%mod; if(j==siz[u])f[u][0][j+1][k+1]=(f[u][0][j+1][k+1]+w)%mod,f[u][lp[u]][j][k+1]=(f[u][lp[u]][j][k+1]+w)%mod; } siz[u]++; } int main() { int x,y; t=read(),fac[0]=1; for(int i=1;i<=80;i++)fac[i]=fac[i-1]*i%mod; inv[80]=qpow(fac[80],mod-2); for(int i=80;i;i--)inv[i-1]=inv[i]*i%mod; while(t--) { n=read(),memset(f,0,sizeof(f)),memset(dp,0,sizeof(dp)),memset(siz,0,sizeof(siz)); for(int i=1;i<=n;i++)v[i].clear(); for(int i=1;i<n;i++) { x=read(),y=read(); if(x>y)swap(x,y); v[x].push_back(y); } for(int i=1;i<n;i++)sort(v[i].begin(),v[i].end()),reverse(v[i].begin(),v[i].end()); dfs1(1),dfs2(1); for(int i=n;i>1;i--)printf("%lld ",f[1][i][i-2][0]); puts("1"); } return 0; } } int main() { return tokido_saya::main(); }
2090
A
Treasure Hunt
Little B and his friend Little K found a treasure map, and now they just need to dig up the treasure, which is buried at a depth of $a.5$ meters. They take turns digging. On the first day, Little B digs; on the second day, Little K. After each day, they switch. Little B digs exactly $x$ meters of soil each day, while Little K digs $y$ meters. They became curious about who will dig up the treasure first, meaning during whose day the total dug depth will exceed $a.5$. But they are too busy digging, so help them and tell who will dig up the treasure!
Let's calculate how many operations we need. The number of pairs of operations is $\left\lfloor\frac{a}{x + y}\right\rfloor$. Additionally, we add $+1$ if $(a \bmod (x + y)) \ge x$, because in this case, the first player will be able to make one more move. Note that the first part is always even, which means the answer depends only on whether $(a \bmod (x + y)) \ge x$, and in this case, the answer is YES.
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int x, y, a; cin >> x >> y >> a; if (a % (x + y) < x) { cout << "NO\n"; } else { cout << "YES\n"; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) solve(); }
2090
B
Pushing Balls
Ecrade has an $n \times m$ grid, originally empty, and he has pushed several (possibly, zero) balls in it. Each time, he can push one ball into the grid either from the leftmost edge of a particular row or the topmost edge of a particular column of the grid. When a ball moves towards a position: - If there is no ball originally at that position, the incoming ball will stop and occupy the position. - If there is already a ball at that position, the incoming ball will stop and occupy the position, while the original ball will continue moving to the next position in the same direction. Note that if a row or column is full (i.e., all positions in that row or column have balls), he cannot push a ball into that row or column. Given the final state of whether there is a ball at each position of the grid, you need to determine whether it is possible for Ecrade to push the balls to reach the final state.
We can transform the problem into: select a row / column and replace the leftmost / topmost $0$ with $1$. Then the solution is clear: if, for each $1$ in the grid, there does not exist any $0$ on its top, or does not exist any $0$ on its left, then the answer is YES; otherwise NO. But how to prove that if the condition is satisfied, we can always construct a valid series of ball-pushing operations? We can consider the problem in reverse order: given the final state, if, for an $1$ in the grid, there does not exist any $0$ on its top, or does not exist any $0$ on its left, then we can turn it into $0$, and our goal is to turn all $1$ s into $0$ s. We can always reach the goal if we choose $1$ s in descending order of $i+j$, where $(i,j)$ is their coordinates in the grid.
[ "brute force", "dp", "implementation" ]
1,000
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll t,n,m,a[59][59],vis[59][59]; char s[59]; inline ll read(){ ll s = 0,w = 1; char ch = getchar(); while (ch > '9' || ch < '0'){ if (ch == '-') w = -1; ch = getchar();} while (ch <= '9' && ch >= '0') s = (s << 1) + (s << 3) + (ch ^ 48),ch = getchar(); return s * w; } int main(){ t = read(); while (t --){ n = read(),m = read(); for (ll i = 1;i <= n;i += 1){ scanf("%s",s + 1); for (ll j = 1;j <= m;j += 1){ a[i][j] = s[j] - '0'; vis[i][j] = 0; } } for (ll i = 1;i <= n;i += 1){ for (ll j = 1;j <= m;j += 1){ if (!a[i][j]) break; vis[i][j] = 1; } } for (ll j = 1;j <= m;j += 1){ for (ll i = 1;i <= n;i += 1){ if (!a[i][j]) break; vis[i][j] = 1; } } bool fl = 1; for (ll i = 1;i <= n && fl;i += 1){ for (ll j = 1;j <= m;j += 1){ if (a[i][j] && !vis[i][j]){ fl = 0; break; } } } puts(fl ? "YES" : "NO"); } return 0; }
2090
C
Dining Hall
Inside the large kingdom, there is an infinite dining hall. It can be represented as a set of cells ($x, y$), where $x$ and $y$ are non-negative integers. There are an infinite number of tables in the hall. Each table occupies four cells ($3x + 1, 3y + 1$), ($3x + 1, 3y + 2$), ($3x + 2, 3y + 1$), ($3x + 2, 3y + 2$), where $x$ and $y$ are arbitrary non-negative integers. All cells that do not belong to any of the tables are corridors. There are $n$ guests that come to the dining hall one by one. Each guest appears in the cell $(0, 0)$ and wants to reach a table cell. In one step, they can move to any neighboring by side \textbf{corridor} cell, and in their \textbf{last} step, they must move to a neighboring by side a free \textbf{table} cell. They occupy the chosen table cell, and no other guest can move there. Each guest has a characteristic $t_i$, which can either be $0$ or $1$. They enter the hall in order, starting to walk from the cell ($0, 0$). If $t_i=1$, the $i$-th guest walks to the nearest vacant table cell. If $t_i=0$, they walk to the nearest table cell that belongs to a completely unoccupied table. Note that other guests may choose the same table later. The distance is defined as the smallest number of steps needed to reach the table cell. If there are multiple table cells at the same distance, the guests choose the cell with the smallest $x$, and if there are still ties, they choose among those the cell with the smallest $y$. For each guest, find the table cell which they choose.
Original idea from myee has $4$ cases, which is a medium difficulty problem using deletable heap. You may find the original statement in zh-cn on GitHub later. The Codeforces version by FairyWinx has only $2$ cases, in order to meet the difficulty as Div2C. The En/Ru statement changes for times after checking. Sorry for the inconvenience. Firstly we can get the distance of each cell by BFS or Math Way: $d(x,y)=x+y+2[x\bmod3=y\bmod3=2]$. The proof is trivial. Then we can sort out the first $4n$ table cell with the lowest distance in $O(n)$ time: by BFS or enumerating possible $d(x,y)=k$. Suppose we record whether a table cell is occupied or not by a bool array. Then we can check whether a cell can be allowed to go by someone $o=0/1$ in $O(1)$ time. Suppose the shortest table cell we can choose is $x_0$ -th and $x_1$ -th ones, then $x_1\le x_0\le4n$. We can keep trying the smallest $x_o$ until it's okay. The time complexity is $O(n)$. 2089A - Simple Permutation Idea: QuietBeautifulThoughts
[ "data structures", "greedy", "implementation", "sortings" ]
1,700
#include <bits/stdc++.h> using uint = unsigned; using bol = bool; const uint T=2000; const uint R=200000; uint Ord[R+5]; uint Nxt(uint p,uint o) { uint x=p/T,y=p%T; if(o&1)y=y/3*3+3-y%3; if(o&2)x=x/3*3+3-x%3; return x*T+y; } bol G[2][T*T];uint Ans[2]; int main() { #ifdef MYEE freopen("QAQ.in","r",stdin); freopen("QAQ.out","w",stdout); #endif for(uint i=2,tp=0;i<T&&tp<R;i++)if(i%3==2) { for(uint x=1;x<i&&tp<R;x+=3)Ord[tp++]=x*T+i-x; } else if(!(i%3)) { for(uint x=1;x<=i-2&&tp<R;x++) if(x%3==1)Ord[tp++]=x*T+i-x; else if(x%3==2)Ord[tp++]=x*T+i-x-2,Ord[tp++]=x*T+i-x; Ord[tp++]=(i-1)*T+1; } uint t;scanf("%u",&t); while(t--) { uint q;scanf("%u",&q); for(uint i=0;i<q*4;i++)G[0][Ord[i]]=G[1][Ord[i]]=0; Ans[0]=Ans[1]=0; while(q--) { uint t;scanf("%u",&t);while(G[t][Ord[Ans[t]]])Ans[t]++; t=Ord[Ans[t]];printf("%u %u\n",t/T,t%T); G[1][t]=1;for(uint o=0;o<4;o++)G[0][Nxt(t,o)]=1; } } return 0; }
2091
A
Olympiad Date
The final of the first Olympiad by IT Campus "NEIMARK" is scheduled for March 1, 2025. A nameless intern was tasked with forming the date of the Olympiad using digits — 01.03.2025. To accomplish this, the intern took a large bag of digits and began drawing them one by one. In total, he drew $n$ digits — the digit $a_i$ was drawn in the $i$-th turn. You suspect that the intern did extra work. Determine at which step the intern could have first assembled the digits to form the date of the Olympiad (the separating dots can be ignored), or report that it is impossible to form this date from the drawn digits. Note that leading zeros \textbf{must be displayed}.
Let's start a digit counter $cnt[i]$ ($0 \leq i \leq 9$). At the moment when $3 \leq cnt[0]$, $1 \leq cnt[1]$, $2 \leq cnt[2]$, $1 \leq cnt[3]$, $1 \leq cnt[5]$ - the answer is found. If after counting all the digits one of the conditions is not fulfilled, then there is no solution and the answer is $0$. $O(n)$.
[ "greedy", "strings" ]
800
#include <iostream> using namespace std; void solve() { int n; cin >> n; int cnt[10] = {}; bool f = 0; for (int i = 0; i < n; i++) { int dig; cin >> dig; cnt[dig]++; if (cnt[0] >= 3 && cnt[1] >= 1 && cnt[2] >= 2 && cnt[3] >= 1 && cnt[5] >= 1 && !f) { cout << i + 1 << endl; f = 1; } } if (!f) cout << 0 << endl; } int main() { int t; cin >> t; while (t--) { solve(); } }
2091
B
Team Training
At the IT Campus "NEIMARK", there are training sessions in competitive programming — both individual and team-based! For the next team training session, $n$ students will attend, and the skill of the $i$-th student is given by a positive integer $a_i$. The coach considers a team strong if its strength is at least $x$. The strength of a team is calculated as the number of team members multiplied by the minimum skill among the team members. For example, if a team consists of $4$ members with skills $[5, 3, 6, 8]$, then the team's strength is $4 \cdot min([5, 3, 6, 8]) = 12$. Output the maximum possible number of strong teams, given that each team must have at least one participant and every participant must belong to exactly one team.
Let's assume that there are $k$ people in a team and $a[i_1]$ - the student with the lowest skill. Then all other participants will have skill greater than or equal to $a[i_1] \leq a[i_2], \ldots a[i_k]$. The greater the value of $a[i_1]$, the fewer people are needed to form a team. In essence, at each stage after sorting in non-increasing order, we choose whether the current student $a_i$ will be the weakest in the team or not. If not, it means that we will put this student aside for now to add someone to the team. If yes, it means that from the put aside students we will add some number so that $x \leq a_i \cdot k$, where $k$ - the number of students in the team. With each transition to the next student, the size of the team, if he is the weakest - will monotonically non-decrease. And to maximize the number of strong teams - their size should be the minimum possible, which will be suitable for a strong team. Accordingly, at the moment when we find a student who can be called the weakest in the team, but at the same time the number of team members will allow the team to be strong, then we immediately form such a strong team. $O(n \space log \space n)$.
[ "dp", "greedy", "sortings" ]
800
#include <iostream> #include <algorithm> using namespace std; void solve() { int n, x; cin >> n >> x; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n); reverse(a, a + n); int ans = 0; for (int i = 0, cnt = 1; i < n; i++, cnt++) { if (a[i] * cnt >= x) { ans++; cnt = 0; } } cout << ans << endl; } int main() { int t; cin >> t; while (t--) { solve(); } }
2091
C
Combination Lock
At the IT Campus "NEIMARK", there are several top-secret rooms where problems for major programming competitions are developed. To enter one of these rooms, you must unlock a circular lock by selecting the correct code. This code is updated every day. Today's code is a permutation$^{\text{∗}}$ of the numbers from $1$ to $n$, with the property that in every cyclic shift$^{\text{†}}$ of it, there is exactly one fixed point. That is, in every cyclic shift, there exists exactly one element whose value is equal to its position in the permutation. Output any valid permutation that satisfies this condition. Keep in mind that a valid permutation might not exist, then output $-1$. \begin{footnotesize} $^{\text{∗}}$A permutation is defined as a sequence of length $n$ consisting of integers from $1$ to $n$, where each number appears exactly once. For example, (2 1 3), (1), (4 3 1 2) are permutations; (1 2 2), (3), (1 3 2 5) are not. $^{\text{†}}$A cyclic shift of an array is obtained by moving the last element to the beginning of the array. A permutation of length $n$ has exactly $n$ cyclic shifts. \end{footnotesize}
Let after $k$ cyclic shifts the element $p_i$ be at position $(i + k) \mod n$. For this point to be fixed, it is necessary that $(i + k) \mod n = p_i$. Let assume that permutation $p$ is starting from $0$, $[0, 1, 2, \ldots, n - 1]$. From this we get that $k = p_i - i \ (mod \ n)$. For any cyclic shift to be a fixed point - it must be possible to obtain any $k$ from $0$ to $n - 1$. Let us sum both sides for all possible values of $k = p_i - i \ (mod \ n)$. We get $\sum_{k=0}^{n - 1} k = \frac{n \cdot (n - 1)}{2}$ and $\sum_{i=0}^{n - 1} (p_i - i) =\sum_{0=1}^{n - 1} p_i - \sum_{i=0}^{n - 1} i = 0$. In order to construct a permutation, these sums must be equal modulo $n$, i.e. $\frac{n \cdot (n - 1)}{2} = 0 \ (mod \ n)$. For even $n$ - this is impossible and the answer is $-1$. And for odd $n$ one of the options - $p = [n, n - 1, \ldots, 2, 1]$. $O(n)$.
[ "constructive algorithms", "greedy" ]
1,000
#include <iostream> using namespace std; void solve() { int n; cin >> n; if (n % 2 == 0) { cout << -1 << endl; return; } for (int i = n; i > 0; i--) { cout << i << ' '; } cout << endl; } int main() { int t = 1; cin >> t; while (t--) solve(); }
2091
D
Place of the Olympiad
For the final of the first Olympiad by IT Campus "NEIMARK", a rectangular venue was prepared. You may assume that the venue is divided into $n$ rows, each containing $m$ spots for participants' desks. A total of $k$ participants have registered for the final, and each participant will sit at an individual desk. Now, the organizing committee must choose the locations for the desks in the venue. Each desk occupies one of the $m$ spots in a row. Moreover, if several desks occupy consecutive spots in the same row, we call such a group of desks a bench, and the number of desks in the group is the bench's length. For example, seating $7$ participants on a $3 \times 4$ venue (with $n = 3, m = 4$) can be arranged as follows: In the figure above, the first row has one bench of length $3$, the second row has one bench of length $2$, and the third row has two benches of length $1$. The organizing committee wants to choose the locations so that the length of the longest bench is as small as possible. In particular, the same $7$ desks can be arranged in a more optimal way, so that the lengths of all benches do not exceed $2$: Given the integers $n$, $m$, and $k$, determine the minimum possible length of the longest bench.
Let the length of the maximal bench be $x$, then to maximize the number of desks in one row - we need to put as many benches of exactly $x$ length as possible. There should be an indent after each bench, let's say, that the length of the block is $x + 1$. The total number of such blocks in a row will be $\lfloor \frac{m}{x + 1} \rfloor$, and the last bench will have a length of $m \mod (x + 1)$. Then the number of desks in one row can reach $f(x) = x \cdot \lfloor \frac{m}{x + 1} \rfloor +(m \mod (x + 1))$. Since the rows are independent, there should be $k \leq n \cdot f(x)$ desks in total. We need to find the minimum $x$, and since $f(x)$ is monotonically non-decreasing, then the answer can be found using binary search. (You can also come up with a formula, we'll leave it as an exercise). $O(log \ k)$ or $O(1)$.
[ "binary search", "greedy", "math" ]
1,200
#include <iostream> using namespace std; void solve() { long long n, m, k, l, r, mid; cin >> n >> m >> k; l = 0, r = m; while (l + 1 < r) { mid = (l + r) / 2; if ((m / (mid + 1) * mid + m % (mid + 1)) * n >= k) { r = mid; } else { l = mid; } } cout << r << endl; } int main() { int t = 1; cin >> t; while (t--) { solve(); } }
2091
E
Interesting Ratio
Recently, Misha at the IT Campus "NEIMARK" camp learned a new topic — the Euclidean algorithm. He was somewhat surprised when he realized that $a \cdot b = lcm(a, b) \cdot gcd(a, b)$, where $gcd(a, b)$ — is the greatest common divisor (GCD) of the numbers $a$ and $b$ and $lcm(a, b)$ — is the least common multiple (LCM). Misha thought that since the product of LCM and GCD exists, it might be interesting to consider their quotient: $F(a,b)=\frac{lcm(a, b)}{gcd(a, b)}$. For example, he took $a = 2$ and $b = 4$, computed $F(2, 4) = \frac{4}{2} = 2$ and obtained a prime number (a number is prime if it has exactly two divisors)! Now he considers $F(a, b)$ to be an interesting ratio if $a < b$ and $F(a, b)$ is a prime number. Since Misha has just started studying number theory, he needs your help to calculate — how many different pairs of numbers $a$ and $b$ are there such that $F(a, b)$ is an interesting ratio and $1 \leq a < b \leq n$?
Let $a = gcd(a, b) \cdot x$, $b = gcd(a, b) \cdot y$ for some $x$ and $y$. Now $F(a,b)=\frac{lcm(a, b)}{gcd(a, b)} = \frac{a \cdot b}{ gcd(a,b)^2} = x \cdot y$. Since $F(a,b)$ - is a prime number, then $x \cdot y$ - is a prime number. For $x \cdot y$ to be a prime number, then one of the numbers must be prime and the other must be equal to $1$. We have the condition that $a < b$, which means that $x = 1$, and $y$ - is a prime number. We get that $a = gcd(a, b)$, $b = gcd(a, b) \cdot y$, where $y$ - is a prime number. The problem becomes the following - count pairs $(a,b)$ such that $1 \leq gcd(a,b) < gcd(a,b) \cdot y \leq n$. Let's fix $y$, then $gcd(a,b)$ can take any value from $1$ to $\lfloor \frac{n}{y} \rfloor$. Thus, for each prime $y$, the number of suitable pairs $(a, b)$ is $\lfloor \frac{n}{y} \rfloor$. It remains to enumerate all prime numbers up to $n$. With the constraint $n \leq 10^7$, this can be done using the sieve of Eratosthenes. $O(n \ log \ log \ n)$.
[ "brute force", "math", "number theory", "two pointers" ]
1,300
#include <iostream> using namespace std; const int MAXN = 10000001; bool prime[MAXN]; void solve() { int n, ans = 0; cin >> n; for (int i = 2; i <= n; i++) { if (prime[i]) { ans += n / i; } } cout << ans << endl; } int main() { for (int i = 0; i < MAXN; i++) prime[i] = 1; prime[0] = prime[1] = 0; for (int i = 2; i * i < MAXN; i++) { if (!prime[i]) continue; for (int j = i * i; j < MAXN; j += i) prime[j] = 0; } int t; cin >> t; while (t--) { solve(); } }
2091
F
Igor and Mountain
The visitors of the IT Campus "NEIMARK" are not only strong programmers but also physically robust individuals! Some practice swimming, some rowing, and some rock climbing! Master Igor is a prominent figure in the local rock climbing community. One day, he went on a mountain hike to ascend one of the peaks. As an experienced climber, Igor decided not to follow the established trails but to use his skills to climb strictly vertically. Igor found a rectangular vertical section of the mountain and mentally divided it into $n$ horizontal levels. He then split each level into $m$ segments using vertical partitions. Upon inspecting these segments, Igor discovered convenient protrusions that can be grasped (hereafter referred to as holds). Thus, the selected part of the mountain can be represented as an $n \times m$ rectangle, with some cells containing holds. Being an experienced programmer, Igor decided to count the number of valid routes. A route is defined as a sequence of \textbf{distinct} holds. A route is considered valid if the following conditions are satisfied: - The first hold in the route is located on the very bottom level (row $n$); - The last hold in the route is located on the very top level (row $1$); - Each subsequent hold is not lower than the previous one; - At least one hold is used on each level (i.e., in every row of the rectangle); - At most two holds are used on each level (since Igor has only two hands); - Igor can reach from the current hold to the next one if the distance between the centers of the corresponding sections does not exceed Igor's arm span. Igor's arm span is $d$, which means he can move from one hold to another if the \textbf{Euclidean distance} between the centers of the corresponding segments does not exceed $d$. The distance between sections ($i_1, j_1$) and ($i_2, j_2$) is given by $\sqrt{(i_1 - i_2) ^ 2 + (j_1 - j_2) ^ 2}$. Calculate the number of different valid routes. Two routes are considered different if they differ in the list of holds used or in the order in which these holds are visited.
Let's use the dynamic programming method $dp[i][j][f]$: $i$ - row number. $j$ - column number. $f = 0$ means that exactly one hold has already been selected in the current row, and a second one can still be added (since there are a maximum of two holds per level). $f = 1$ means that two holds have already been used in this level. $dp[i][j][f]$ - the number of ways to construct a correct route starting with a hold in cell $(i,j)$, given that $f + 1$ holds are already used in row $i$. For a cell $(i,j)$ with a hold (i.e. $s[i][j] =$ 'X'): At the lower level, i.e. $i = n - 1$, this hold can serve as the start of the route, so all such $dp[n - 1][j][f] = 1$. If one hold $f = 0$ is already selected at the current level, then you can take the second hold at the same level at a distance of no more than $d$, i.e. $dp[i][j][f]= dp[i][j][f] + \sum_{y = j - d}^{j + d}{dp[i][y][1]} - dp[i][j][1]$ (let's not forget to exclude the point $(i, j)$ from the sum, so as not to count it twice). The transition to the next level (if possible) $i$ in $i+1$ takes a vertical distance equal to $1$. So the range of $j$ for the transition will be $[j - dx, j + dx]$, where $dx = \lfloor \sqrt{d^2 - 1^2} \rfloor = d - 1$$dp[i][j][f]= dp[i][j][f] + \sum_{y = j - dx}^{j + dx}{dp[i + 1][y][0]}$ $dp[i][j][f]= dp[i][j][f] + \sum_{y = j - dx}^{j + dx}{dp[i + 1][y][0]}$ This solution recalculates each state in $O(d)$, to make it more efficient - you need to use prefix sums. $O(n \cdot m)$.
[ "binary search", "brute force", "dp" ]
1,800
#include <iostream> using namespace std; const int MAXN = 2010; const int MOD = 998244353; string s[MAXN]; int dp[MAXN][MAXN][2]; long long sdp[MAXN][MAXN][2]; int n, m, d; long long getsum(int x, int y1, int y2, int f) { long long res = sdp[x][y2][f]; if (y1) res -= sdp[x][y1 - 1][f]; return res; } int get(int i, int j, int f) { if (s[i][j] != 'X') return 0; long long res = 0; if (i == n - 1) res++; if (!f) { res += getsum(i, max(0, j - d), min(m - 1, j + d), 1); res -= dp[i][j][1]; } if (i < n - 1) { res += getsum(i + 1, max(0, j - d + 1), min(m - 1, j + d - 1), 0); } return res % MOD; } void solve() { cin >> n >> m >> d; for (int i = 0; i < n; i++) { cin >> s[i]; } for (int i = n - 1; i >= 0; i--) { for (int f = 1; f >= 0; f--) { for (int j = 0; j < m; j++) { sdp[i][j][f] = dp[i][j][f] = get(i, j, f); } for (int j = 1; j < m; j++) { sdp[i][j][f] += sdp[i][j - 1][f]; } } } long long ans = 0; for (int j = 0; j < m; j++) { ans += dp[0][j][0]; } cout << ans % MOD << endl; } int main() { int t; cin >> t; while (t--) { solve(); } }
2091
G
Gleb and Boating
Programmer Gleb frequently visits the IT Campus "NEIMARK" to participate in programming training sessions. Not only is Gleb a programmer, but he is also a renowned rower, so he covers part of his journey from home to the campus by kayaking along a river. Assume that Gleb starts at point $0$ and must reach point $s$ (i.e., travel $s$ meters along a straight line). To make the challenge tougher, Gleb has decided not to go outside the segment $[0, s]$. The dimensions of the kayak can be neglected. Gleb is a strong programmer! Initially, his power is $k$. Gleb's power directly affects the movement of his kayak. If his current power is $x$, then with one paddle stroke the kayak moves $x$ meters in the current direction. Gleb can turn around and continue moving in the opposite direction, but such a maneuver is quite challenging, and after each turn, his power decreases by $1$. The power can never become $0$ — if his current power is $1$, then even after turning it remains $1$. Moreover, Gleb cannot make two turns in a row — after each turn, he must move at least once before making another turn. Similarly, Gleb cannot make a turn immediately after the start — he must first perform a paddle stroke. Gleb wants to reach point $s$ from point $0$ without leaving the segment $[0, s]$ and while preserving as much power as possible. Help him — given the value $s$ and his initial power $k$, determine the maximum possible power he can have upon reaching point $s$.
Let's consider a simple solution - we will iterate through Gleb's current strength $t$, from $k$ to $1$, and check which positions can be reached using that strength value. For each fixed $t$, the set of positions can be obtained by any search method, for example, breadth-first search. Next, let's assume that Gleb has turned around and we will start a search from all reached positions with strength $t-1$ and in the opposite direction. For one strength value, such a search works in the worst case in $O(s)$, so the overall complexity of the algorithm will be $O(s \cdot k)$ (which, of course, will take too long) and will require $O(s)$ memory. Now we need to speed up this solution. First, we need to solve the problem for very large values of $s$. It is not difficult to prove that if $k \geq 3$, then for $s > k^2$, the answer to the problem will be $k$ or $k-2$. Indeed, let's assume that Gleb with strength $k$ has reached the maximum possible position on the segment. Next, he turns around, takes one step back (with strength $k-1$). Let's find the position where Gleb will end up if he turns around and moves to the right with strength $k-2$ until he crosses the boundary $s$ (including the assumption that he can swim beyond $s$). Let this position be $s + r$, where $0 \leq r < k - 2$. Then, Gleb would need to take another $r$ steps to the left with strength $k-1$ before the second turn; in this case, he will end up exactly at point $s$ with strength $k-2$. For this maneuver, he will need a distance of at most $k + (r+1) \cdot (k-1) < k + (k-1)^2 < k^2$. Thus, for $s \geq k^2$, we can obtain either the answer $k$ (which can be checked by simple division) or the answer $k-2$ (we print it if the answer $k$ is not possible). It is also easy to see that this statement remains true when starting from any point from $0$ to $s$. Next, we will assume that $s \leq k^2$. Let the answer to the problem be $ans$. Then, if in the algorithm described above we stop the iteration upon reaching point $s$ for some $t$, the total running time will be $O(s \cdot (k - ans))$. Considering the above, we can assert that $ans \geq \sqrt{s} - 3$ (due to the even number of turns, the answer $\sqrt{s} - 2$ may not be suitable). Then the running time of the algorithm does not exceed $T = (k - \sqrt{s}) \cdot s$ We can rewrite this value as follows: $(k - \sqrt{s}) \cdot s = (k - \sqrt{s}) \cdot (\sqrt{s})^2 = \frac{(2 \cdot k - 2 \cdot \sqrt{s}) \cdot \sqrt{s} \cdot \sqrt{s}}{2}$ Next, we note that the sum of the factors in the numerator equals $2 \cdot k$, meaning that the maximum value is achieved when they are equal (see, for example, Karamata's inequality). We obtain that: $T \leq \frac{1}{2} \cdot \left(\frac{2 \cdot k}{3}\right)^3 = \frac{4 \cdot k^3}{27}$ which is already fast enough to pass all tests. In practice, even in the worst case, the specified algorithm requires even fewer operations and comfortably fits within the time limits.
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "greedy", "math", "number theory", "shortest paths" ]
2,300
#include <iostream> #include <vector> using namespace std; int s, k, p; vector<bool> was1, was2; void bfs() { vector<int> v; for (int i = 0; i < s; i++) { if (was1[i]) v.push_back(i); } int q = 0; while (q < v.size()) { int x = v[q++]; int y = x + p * k; if (y >= 0 && y <= s && !was1[y]) { was1[y] = 1; v.push_back(y); } } } void solve() { cin >> s >> k; if (s % k == 0) { cout << k << endl; return; } if (s > k * k) { cout << max(1, k - 2) << endl; return; } was1.resize(s + 1); was2.resize(s + 1); for (int i = 0; i <= s; i++) { was1[i] = was2[i] = 0; } p = 1; was1[k] = 1; while (1) { bfs(); if (was1[s]) { cout << k << endl; return; } k = max(k - 1, 1); p *= -1; for (int i = 0; i <= s; i++) { was2[i] = 0; } for (int i = 0; i < s; i++) { if (was1[i]) { if (i + p * k >= 0 && i + p * k <= s) { was2[i + p * k] = 1; } } } swap(was1, was2); } } int main() { int t; cin >> t; while (t--) { solve(); } }
2092
A
Kamilka and the Sheep
Kamilka has a flock of $n$ sheep, the $i$-th of which has a beauty level of $a_i$. All $a_i$ are distinct. Morning has come, which means they need to be fed. Kamilka can choose a non-negative integer $d$ and give each sheep $d$ bunches of grass. After that, the beauty level of each sheep increases by $d$. In the evening, Kamilka must choose \textbf{exactly two} sheep and take them to the mountains. If the beauty levels of these two sheep are $x$ and $y$ (after they have been fed), then Kamilka's pleasure from the walk is equal to $\gcd(x, y)$, where $\gcd(x, y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$. The task is to find the maximum possible pleasure that Kamilka can get from the walk.
It's always possible to make Kamilka's pleasure at least $|x - y|$ for any $x, y \in a$. First of all, it can be observed that for any two sheep with beauty levels $x < y$, the maximum possible pleasure cannot exceed $y - x$, since $\gcd(x, y) = \gcd(x, y - x)$. Secondly, we can choose $x = \min(a)$, $y = \max(a)$, and $d = -x \bmod (y - x)$, achieving a pleasure of $\max(a) - \min(a)$. Thus, the answer is $\max(a) - \min(a)$.
[ "greedy", "math", "number theory", "sortings" ]
800
t = int(input()) for test in range(t): n = int(input()) a = [int(i) for i in input().split()] print(max(a) - min(a))
2092
B
Lady Bug
As soon as Dasha Purova crossed the border of France, the villain Markaron kidnapped her and placed her in a prison under his large castle. Fortunately, the wonderful Lady Bug, upon hearing the news about Dasha, immediately ran to save her in Markaron's castle. However, to get there, she needs to crack a complex password. The password consists of two bit strings $a$ and $b$, each of which has a length of $n$. In one operation, Lady Bug can choose any index $2 \le i \le n$ and perform one of the following actions: - swap($a_i$, $b_{i-1}$) (swap the values of $a_i$ and $b_{i-1}$), or - swap($b_i$, $a_{i-1}$) (swap the values of $b_i$ and $a_{i-1}$). Lady Bug can perform any number of operations. The password is considered cracked if she can ensure that the first string consists only of zeros. Help her understand whether or not she will be able to save the unfortunate Dasha.
Note that you can split strings $a$ and $b$ into two "zig-zags": $a_0, b_1, a_2, b_3, \dots$ and $b_0, a_1, b_2, a_3, \dots$ What are the necessary and sufficient conditions for each of these zig-zags? Note that you can split strings $a$ and $b$ into two "zig-zags": $a_0, b_1, a_2, b_3, \dots$ and $b_0, a_1, b_2, a_3, \dots$. For each of these zig-zags, you can achieve any sequence of 0s and 1s, provided that their quantities within the zig-zag are preserved. Therefore, the answer is Yes if and only if the number of 0 is at least $\lceil \frac{n}{2} \rceil$ in the first zig-zag and at least $\lfloor \frac{n}{2} \rfloor$ in the second one.
[ "brute force", "constructive algorithms", "implementation", "math" ]
1,000
t = int(input()) for test in range(t): n = int(input()) a = input() b = input() cnt1, cnt2 = 0, 0 for i in range(n): if i % 2: cnt2 += (a[i] == '0') cnt1 += (b[i] == '0') else: cnt1 += (a[i] == '0') cnt2 += (b[i] == '0') if cnt1 >= (n + 1) // 2 and cnt2 >= n // 2: print("Yes") else: print("No")
2092
C
Asuna and the Mosquitoes
For her birthday, each of Asuna's $n$ admirers gifted her a tower. The height of the tower from the $i$-th admirer is equal to $a_i$. Asuna evaluates the beauty of the received gifts as $\max(a_1, a_2, \ldots, a_n)$. She can perform the following operation an arbitrary number of times (possibly, zero). - Take such $1 \le i \neq j \le n$ that $a_i + a_j$ is odd and $a_i > 0$, then decrease $a_i$ by $1$ and increase $a_j$ by $1$. It is easy to see that the heights of the towers remain non-negative during the operations. Help Asuna find the maximum possible beauty of the gifts after any number of operations!
Consider two cases: first, when all numbers have the same parity; and second, when there is at least one even and one odd number. Let $S$ be the sum of all numbers, and $k$ be the number of odd numbers in the array. Then, in the second case, the answer is $S - k + 1$. Case 1. All numbers in $a$ have the same parity. In this case, it is impossible to perform any operation, so the answer is $\max(a)$. Case 2. There is at least one even and one odd number. Let $S$ be the sum of all numbers, and $k$ be the number of odd numbers in the array. We will now prove that the answer is $S - k + 1$. First of all, the answer cannot exceed $S - k + 1$, since the number of odd elements in the array remains unchanged after performing the operation. Secondly, we will show that $S - k + 1$ is always achievable. Consider an arbitrary odd number $A \in a$. We can then merge all even numbers into $A$ $\left( \text{i.e.} \ (A, 2k) \to (A + 2k, 0) \right)$, resulting in an array consisting of the number $A + 2m$, $k-1$ odd numbers, and zeros for the remaining elements (here $2m$ denotes the sum of all even numbers in the initial array). After this step, for each remaining odd number, we can sacrifice one unit by transferring it to any zero element in the array and then merge the resulting even number into $A$. It's easy to see that there will always be at least one zero available in the array before merging each odd number. Eventually, we will obtain an array consisting of one element equal to $S - k + 1$, $k - 1$ elements equal to one, and zeros filling the remaining positions. Therefore, the answer in this case will be $S-k+1$.
[ "constructive algorithms", "greedy", "math" ]
1,200
t = int(input()) for test in range(t): n = int(input()) a = [int(i) for i in input().split()] ans, cnt = 0, 0 for i in a: ans += i cnt += i % 2 if not cnt or cnt == n: print(max(a)) else: print(ans - cnt + 1)
2092
D
Mishkin Energizer
In anticipation of a duel with his old friend Fernan, Edmond is preparing an energy drink called "Mishkin Energizer". The drink consists of a string $s$ of length $n$, made up only of the characters L, I, and T, which correspond to the content of three different substances in the drink. We call the drink balanced if it contains an equal number of all substances. To boost his aura and ensure victory in the duel, Edmond must make the initial string balanced by applying the following operation: - Choose an index $i$ such that $s_i \neq s_{i+1}$ (where $i + 1$ must not exceed the \textbf{current} size of the string). - Insert a character $x$, either L, I, or T, between them such that $x \neq s_i$ and $x \neq s_{i+1}$. Help Edmond make the drink balanced and win the duel by performing \textbf{no more than $\textbf{2n}$ operations}. If there are multiple solutions, any one of them can be output. If it is impossible, you must report this.
It is impossible to balance the string if and only if all its letters are the same. It is clear that there is no solution if all the letters in $s$ are the same. Let us now prove that a solution always exists in all other cases. While the string remains unbalanced, let us assume that $\text{cnt}(a) \le \text{cnt}(b) \le \text{cnt}(c)$, where $a, b, c \in \lbrace \tt{L}, \tt{I}, \tt{T} \rbrace$, and $\text{cnt}(l)$ denotes the number of occurrences of the letter $l$ in $s$. Consider two cases: The string $s$ contains the substring bc or cb. In this case, we can perform the operation on it to obtain bac or cab. The string $s$ contains the substring bc or cb. In this case, we can perform the operation on it to obtain bac or cab. Otherwise, the string $s$ must contain the substring ca or ac. Without loss of generality, assume that $s$ contains ca. Then we can perform the following sequence of operations: ca $\to$ cba $\to$ cbca $\to$ cbaca $\to$ cabaca. Otherwise, the string $s$ must contain the substring ca or ac. Without loss of generality, assume that $s$ contains ca. Then we can perform the following sequence of operations: ca $\to$ cba $\to$ cbca $\to$ cbaca $\to$ cabaca. It can be observed that after each operation, the value of $2 \cdot \text{cnt}(c) - \text{cnt}(b) - \text{cnt}(a)$ decreases by one. Here, $a$, $b$, and $c$ are always chosen such that $\text{cnt}(a) \le \text{cnt}(b) \le \text{cnt}(c)$. Therefore, the algorithm is guaranteed to terminate, and it does so when $2 \cdot \text{cnt}(c) - \text{cnt}(b) - \text{cnt}(a) = 0$, which implies $\text{cnt}(a) = \text{cnt}(b) = \text{cnt}(c)$. It remains to prove that the number of operations performed by the proposed algorithm does not exceed $2n$. Assume that initially $x = \text{cnt}(a), y = \text{cnt}(b), z = \text{cnt}(c)$, where $\text{cnt}(a) \le \text{cnt}(b) \le \text{cnt}(c)$. Then $x + y + z = n$. While $\text{cnt}(a) < \text{cnt}(b)$, we increment $\text{cnt}(a)$ by one in each step, using no more than $4$ operations per step. Therefore, this phase requires at most $4(y - x)$ operations. Afterwards, the algorithm alternately increments $\text{cnt}(a)$ and $\text{cnt}(b)$ by one until both become equal to $\text{cnt}(c)$. I claim that this phase will use the $4$-operations sequence (i.e., the second case in the algorithm) at most once. Indeed, let us consider the first time we perform the transformation ca $\to$ cabaca. It is easy to see that all subsequent steps will involve only single-operation transformations. Thus, this phase requires no more than $2(z - y) + 3$ operations. Summing up, the total number of operations is bounded above by $4(y - x) + 2(z - y) + 3 = 2z + 2y - 4x + 3$. If $x \neq 0$, this number is less than $2n$ given that $n = x + y + z$. Otherwise, the first step of the algorithm will be either bc $\to$ bac or cb $\to$ cab, requiring only one operation. This improves the estimate for the number of operations in the first phase from $4(y-x)$ to $4(y - x) - 3$. As a result, in the case where $x = 0$, the total number of operations does not exceed $4(y - x) - 3 + 2(z-y) + 3 = 2z + 2y = 2n$. We assume that a solution exists (refer to the beginning of the first solution). Now, at each step, let's greedily find the first position where the rarest letter can be inserted and place it there. If no such position exists during a given iteration, we insert the most frequent letter instead. The algorithm terminates when all letters occur the same number of times. We claim that this greedy strategy performs no more than $2n$ operations. Assume that initially $x = \text{cnt}(a), y = \text{cnt}(b), z = \text{cnt}(c)$, where $\text{cnt}(a) \le \text{cnt}(b) \le \text{cnt}(c)$. Then $x + y + z = n$. Here, $\text{cnt}(l)$ denotes the number of occurrences of the letter $l$ in $s$. Claim 1. If the rarest letter cannot be inserted, there always exists a position where the most frequent letter can be inserted. Suppose not. Then every pair of distinct adjacent letters must contain both a and c. This would imply that the number of bs is zero, which contradicts the condition $y \ge x$. Claim 2. If $x = y$, the solution can always be obtained in exactly $(z - x) + (z - y) = 2z - x - y$ operations. Let's find the first position $i$ such that $s_i \ne s_{i+1}$ and either $s_i$ or $s_{i+1}$ is c. Without loss of generality, assume the substring is of the form cb.... Then, the algorithm performs the following sequence of operations: cb... $\to$ cab... $\to$ cbab... $\to$ cabab $\to$ $\dots$ $\to$ cbababab... Since every two iterations increase the counts of both a and b by one, we will reach a count of $z$ in exactly the required number of steps. Now consider the case when $x < y$. Observe that in two operations, the algorithm increases the count of the rarest letter by one and increases the count of the most frequent letter by at most one. This is true because, after inserting the most frequent letter, we obtain a substring like bc. It is easy to see that a can be inserted into it, and the algorithm, being greedy, will do exactly that. After some number of iterations, $x$ becomes equal to $y$ (note that $y$ remains unchanged throughout the algorithm). Then, by the reasoning above, the final value of $z' = \text{cnt}(c)$ satisfies: $z' \le z + (y - x)$ Applying Claim 2, we get that the total number of operations does not exceed $((z + (y - x)) - y) + ((z + (y - x)) - x) = 2z + y - 3x \le 2n$
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
1,800
#include <vector> #include <string> #include <iostream> #include <set> #include <map> using namespace std; vector<char> a = {'L', 'I', 'T'}; int main() { int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; set<char> se; for (auto u : s) se.insert(u); if (se.size() == 1) { cout << -1 << endl; continue; } vector<int> ans; map<char, int> mp; for (auto u : s) { mp[u]++; } auto func = [&](int i) { for (auto u : a) { if (s[i] != u && s[i + 1] != u) return u; } return '$'; }; while (max({mp['L'], mp['I'], mp['T']}) != min({mp['L'], mp['I'], mp['T']})) { int mn = min({mp['L'], mp['I'], mp['T']}); int mx = max({mp['L'], mp['I'], mp['T']}); int ok = 0; for (int i = 0; i < s.size() - 1; i++) { char x = func(i); if (s[i] != s[i + 1] && mp[x] == mn) { mp[x]++; ok = 1; s.insert(s.begin() + i + 1, x); ans.push_back(i); break; } } if (!ok) { for (int i = 0; i < s.size() - 1; i++) { char x = func(i); if (s[i] != s[i + 1] && mp[x] == mx) { mp[x]++; s.insert(s.begin() + i + 1, x); ans.push_back(i); ok = 1; break; } } } } cout << ans.size() << endl; for (auto u : ans) { cout << u + 1 << endl; } } }
2092
E
She knows...
D. Pippy is preparing for a "black-and-white" party at his home. He only needs to repaint the floor in his basement, which can be represented as a board of size $n \times m$. After the last party, the entire board is painted green, except for some $k$ cells $(x_1, y_1), (x_2, y_2), \ldots, (x_k, y_k)$, each of which is painted either white or black. For the upcoming party, D. Pippy wants to paint \textbf{each} of the remaining green cells either black or white. At the same time, he wants the number of pairs of adjacent cells with different colors on the board to be even after repainting. Formally, if $$A = \left\{((i_1, j_1), (i_2, j_2)) \ | \ 1 \le i_1, i_2 \le n, 1 \le j_1, j_2 \le m, i_1+j_1<i_2+j_2, |i_1-i_2|+|j_1-j_2| = 1, \operatorname{color}(i_1, j_1) \neq \operatorname{color}(i_2, j_2) \right\},$$ where $\operatorname{color}(x, y)$ denotes the color of the cell $(x, y)$, then it is required that $|A|$ be even. Help D. Pippy find the number of ways to repaint the floor so that the condition is satisfied. Since this number can be large, output the remainder of its division by $10^9 + 7$.
If a cell has an even number of neighbours, does its color matter? Let $S$ be the set of cells that have an odd number of neighbouring cells. It is easy to observe that $S$ consists of border cells, excluding the corner ones. More precisely, $S = \{(i, j) \ \vert \ \left( i \in \{1, n\} \right) \ \bigoplus \ \left( j \in \{1, m\} \right) = 1 \}$ Idea 1. I claim that the number of adjacent border cell pairs with different colors is even. Indeed, if we walk along the border-which essentially forms a cycle-starting and ending at $(1, 1)$, we must change color an even number of times. Idea 2. It can be observed that the parity of $|A|$ does not change when flipping the color of any cell not in $S$, since such a cell has an even number of neighbouring cells. Therefore, if we fix the coloring of the border cells, the parity of $|A|$ remains unchanged if we imagine recoloring all non-border cells white. This implies that the parity of $|A|$ depends solely on the parity of the number of black (or white) cells in $S$. Moreover, it can be seen that these parities are actually equal. Idea 3. Now, we are left with counting the number of colorings such that $|S|$ contains an even number of black cells. Let's consider two cases: All cells in $S$ are initially colored. In this case, the answer is $2^{n \cdot m - k}$ if the number of black cells in $S$ is even, and $0$ otherwise, since the colors of the remaining cells do not affect the parity. All cells in $S$ are initially colored. In this case, the answer is $2^{n \cdot m - k}$ if the number of black cells in $S$ is even, and $0$ otherwise, since the colors of the remaining cells do not affect the parity. At least one cell in $S$ is uncolored. In this case, the answer is $2^{n \cdot m - k - 1}$. This follows from the basic identity of the binomial coefficients: At least one cell in $S$ is uncolored. In this case, the answer is $2^{n \cdot m - k - 1}$. This follows from the basic identity of the binomial coefficients: $C^0_n + C^2_n + C^4_n + \dots = C^1_n + C^3_n + C^5_n + \dots$
[ "combinatorics", "constructive algorithms", "graphs", "math" ]
2,100
#include <iostream> #include <vector> using namespace std; using ll = long long; const ll mod = 1000000007; ll binpow (ll a, ll n) { ll res = 1; while (n) { if (n & 1) { res *= a; res %= mod; } a *= a; a %= mod; n >>= 1; } return res; } void solve() { ll n, m, k; cin >> n >> m >> k; int good = 0, sum = 0; for (int i = 0; i < k; ++i) { int x, y, c; cin >> x >> y >> c; if ((x == 1 && y == 1) || (x == 1 && y == m) || (x == n && y == 1) || (x == n && y == m)) continue; if (x == 1 || y == 1 || x == n || y == m) { ++good; sum += c; } } if (good == 2 * (n + m - 4)) { cout << (sum % 2 ? 0 : binpow(2, n * m - k)) << '\n'; } else { cout << binpow(2, n * m - k - 1) << '\n'; } } signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int t; cin >> t; while (t--) solve(); }
2092
F
Andryusha and CCB
Let us define the beauty of a binary string $z$ as the number of indices $i$ such that $1 \le i < |z|$ and $z_i \neq z_{i+1}$. While waiting for his friends from the CCB, Andryusha baked a pie, represented by a binary string $s$ of length $n$. To avoid offending anyone, he wants to divide this string into $k$ substrings such that each digit belongs to exactly one substring, and the beauties of all substrings are the same. Andryusha does not know the exact number of friends from the CCB who will come to his house, so he wants to find the number of values of $k$ for which it is possible to split the pie into exactly $k$ parts with equal beauties. However, Andryusha's brother, Tristan, decided that this formulation of the problem is too simple. Therefore, he wants you to find the number of such values of $k$ \textbf{for each prefix of the string}. In other words, for each $i$ from $1$ to $n$, you need to find the number of values of $k$ for which it is possible to split the prefix $s_1 s_2 \ldots s_i$ into exactly $k$ parts with equal beauties.
It is sufficient to consider only two types of blocks of consecutive 0s and 1s: those of size $1$ and those of size greater than $1$. For a fixed beauty value $m$ of a substring, there are $O\left(\frac{sz}{m}\right)$ possible values of $k$, where $sz$ is the number of blocks of consecutive 0s and 1s. For a fixed pair $(m, k)$, let $S$ be the set of indices $i$ such that it is possible to divide the prefix $[1, i]$ of the string into $k$ substrings of beauty $m$. It is claimed that $S$ forms a continuous segment $[l, r]$ for some $1 \le l \le r \le sz$. First, note that it is sufficient to consider only two types of blocks of consecutive 0s and 1s: those of size $1$ and those of size greater than $1$. Based on this, we construct a new string of length $sz$, consisting of characters 1 and 2, representing the types of blocks. For example, for the original string 00101110, the new string is 21121. Let's fix a value of $m$-the desired beauty of the substrings we are dividing the string into. It is easy to see that there are $O\left(\frac{sz}{m}\right)$ possible values of $k$ (the number of substrings). Now, for a fixed pair $(m, k)$, let $S_k$ be the set of indices $i$ such that it is possible to divide the prefix $[1, i]$ of the new string (representing block types) into $k$ substrings of beauty $m$. It is claimed that $S_k$ forms a continuous segment $[l, r]$ for some $1 \le l \le r \le sz$. Let's prove this by induction. Base case ($k = 1$). We set $l = m$, $r = m$ (0-based indexing). Inductive step ($k \rightarrow k + 1$). Suppose that for every index $i \in [l, r]$, the first $i$ blocks can be divided into $k$ substrings of beauty $m$. Then we can construct a valid division into $k+1$ substrings by: Simply appending a new substring of length $m+1$ starting at block $i+1$, giving us a new upper bound at $i + m + 1$. Simply appending a new substring of length $m+1$ starting at block $i+1$, giving us a new upper bound at $i + m + 1$. Additionally, if block $i$ is of type $2$, we can split it between the $k$-th and $(k+1)$-th substrings, allowing us to finish the $k$-th substring earlier and start the $(k+1)$-th within the same block. This enables us to reach $i + m$ as well. Additionally, if block $i$ is of type $2$, we can split it between the $k$-th and $(k+1)$-th substrings, allowing us to finish the $k$-th substring earlier and start the $(k+1)$-th within the same block. This enables us to reach $i + m$ as well. Thus, we conclude: $S_{k+1} = [l + m, r + m + 1]$ if the $l$-th block is of type 2. $S_{k+1} = [l + m, r + m + 1]$ if the $l$-th block is of type 2. Otherwise, $S_{k+1} = [l + m + 1, r + m + 1]$. Otherwise, $S_{k+1} = [l + m + 1, r + m + 1]$. To compute the full solution, we iterate over all values of $m$ from $1$ to $sz - 1$. For each $m$, we iterate over $k$ until the left bound $l$ of the corresponding segment exceeds $sz$. The special case $m=0$ should be handled separately. For each $k$, we need to increment the answer for all positions from $l$ to $r$ by one. This can be efficiently done by recording the operations $(l, +1)$ and $(r + 1, -1)$ and then applying a scanline technique to process the accumulated changes. Since there are $O\left(\frac{sz}{m}\right)$ possible values of $k$ for each $m$, the total complexity of this solution is $O(n \log n)$.
[ "brute force", "constructive algorithms", "greedy", "math", "number theory", "strings" ]
2,900
#include <iostream> #include <vector> using namespace std; using ll = long long; void solve() { int n; cin >> n; string s; cin >> s; vector <int> a; int curr = 0; for (int i = 0; i < n; ++i) { if (i && s[i] != s[i - 1]) { if (curr) a.push_back(curr); curr = 1; } else ++curr; } a.push_back(curr); int sz = a.size(); vector <int> ans(n, 0), left(sz, 0), right(sz, 0); for (int i = 0; i < sz; ++i) { if (!i) { left[i] = 0; right[i] = a[i] - 1; } else { left[i] = right[i - 1] + 1; right[i] = left[i] + a[i] - 1; } } for (int i = 0; i < sz; ++i) { for (int j = left[i]; j <= right[i]; ++j) { ans[j] += j - i + 1; } } vector <int> add(sz, 0); for (int m = 1; m < sz; ++m) { ll l = m, r = m, k = 1; while (l < sz) { ++add[l]; if (r + 1 < sz) --add[r + 1]; if (a[l] == 1) { l += m + 1; } else { l += m; } r += m + 1; ++k; } } int pref = 0; for (int i = 0; i < sz; ++i) { pref += add[i]; for (int j = left[i]; j <= right[i]; ++j) { ans[j] += pref; } } for (int i = 0; i < n; ++i) { cout << ans[i]; if (i != n - 1) cout << ' '; } cout << '\n'; } signed main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int t; cin >> t; while (t--) { solve(); } }
2093
A
Ideal Generator
We call an array $a$, consisting of $k$ positive integers, palindromic if $[a_1, a_2, \dots, a_k] = [a_k, a_{k-1}, \dots, a_1]$. For example, the arrays $[1, 2, 1]$ and $[5, 1, 1, 5]$ are palindromic, while the arrays $[1, 2, 3]$ and $[21, 12]$ are not. We call a number $k$ an ideal generator if any integer $n$ ($n \ge k$) can be represented as the sum of the elements of a palindromic array of length exactly $k$. Each element of the array must be greater than $0$. For example, the number $1$ is an ideal generator because any natural number $n$ can be generated using the array $[n]$. However, the number $2$ is not an ideal generator — there is no palindromic array of length $2$ that sums to $3$. Determine whether the given number $k$ is an ideal generator.
If we consider some palindromic array $a$ of the form $[a_1, a_2, \dots, a_k]$ and its sum, we should discuss two different cases. When $k$ is even ($k = 2m$), the array $a$ looks as follows: $[a_1, a_2, \dots, a_{m - 1}, a_m, a_m, a_{m - 1}, \dots, a_2, a_1]$. Its sum in this case is the number $2 \cdot (a_1 + a_2 + \dots + a_m)$. This implies that any palindromic array of even length also has an even sum, and thus it is impossible to generate odd numbers $n$ for even values of $k$. On the other hand, if $k$ is an odd number ($k = 2m + 1$), the array $a$ looks like $[a_1, a_2, \dots, a_m, a_{m + 1}, a_m, \dots, a_2, a_1]$. Its sum is the number $a_{m + 1} + 2 \cdot (a_1 + a_2 + \dots + a_m)$. In this case, for any integer $n$, there exists a palindromic array of the form $[1, \dots, 1, n - (k - 1), 1, \dots, 1]$. In conclusion, if $k$ is an odd number, the answer is <<Yes>>, and if $k$ is even, the answer will be <<No>>.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; if (n % 2 == 1) { cout << "YES\n"; } else { cout << "NO\n"; } } return 0; }
2093
B
Expensive Number
The cost of a positive integer $n$ is defined as the result of dividing the number $n$ by the sum of its digits. For example, the cost of the number $104$ is $\frac{104}{1 + 0 + 4} = 20.8$, and the cost of the number $111$ is $\frac{111}{1 + 1 + 1} = 37$. You are given a positive integer $n$ that does not contain leading zeros. You can remove any number of digits from the number $n$ (including none) so that the remaining number contains at least one digit and \textbf{is strictly greater than zero}. The remaining digits \textbf{cannot} be rearranged. As a result, you \textbf{may} end up with a number that has leading zeros. For example, you are given the number $103554$. If you decide to remove the digits $1$, $4$, and one digit $5$, you will end up with the number $035$, whose cost is $\frac{035}{0 + 3 + 5} = 4.375$. What is the minimum number of digits you need to remove from the number so that its cost becomes the minimum possible?
We will prove that the minimum possible cost of the resulting number is always equal to $1$. Consider an arbitrary positive number $n = \overline{a_1a_2\ldots a_k}$, where $a_i$ are its digits in order. We evaluate the cost of this number as $cost(n) = \frac{\overline{a_1a_2\ldots a_k}}{a_1+a_2+\ldots+a_k} = \frac{a_1 \cdot 10^{k - 1} + a_2\cdot 10^{k - 2} + \ldots + a_k}{a_1+a_2+\ldots+a_k} \geq \frac{a_1+a_2+\ldots+a_k}{a_1+a_2+\ldots+a_k} = 1$. We also note that if any of the digits $a_1, a_2, \ldots, a_{k - 1}$ are not equal to zero, then the inequality will be strict. Thus, a cost of $1$ can always be achieved by leaving exactly one non-zero digit and several leading zeros before it. Therefore, our task reduces to leaving some non-zero digit and as many leading zeros as possible before it. To do this, we will keep the rightmost non-zero digit in the number, all the zeros to its left, and remove the other digits.
[ "greedy", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; int n = s.size(); bool met_positive = false; int cnt_zero = 0; for (auto i = n - 1; i >= 0; --i) { if (s[i] != '0') { met_positive = true; } else if (met_positive) { cnt_zero++; } } cout << n - (cnt_zero + 1) << '\n'; } return 0; }
2093
C
Simple Repetition
Pasha loves prime numbers$^{\text{∗}}$! Once again, in his attempts to find a new way to generate prime numbers, he became interested in an algorithm he found on the internet: - To obtain a new number $y$, repeat $k$ times the decimal representation of the number $x$ (without leading zeros). For example, for $x = 52$ and $k = 3$, we get $y = 525252$, and for $x = 6$ and $k = 7$, we get $y = 6666666$. Pasha really wants the resulting number $y$ to be prime, but he doesn't yet know how to check the primality of numbers generated by this algorithm. Help Pasha and tell him whether $y$ is prime! \begin{footnotesize} $^{\text{∗}}$An integer $x$ is considered prime if it has \textbf{exactly} $2$ distinct divisors: $1$ and $x$. For example, $13$ is prime because it has only $2$ divisors: $1$ and $13$. Note that the number $1$ is not prime, as it has only one divisor. \end{footnotesize}
Let the number $x$ have $b$ digits in its decimal representation. What does it mean to write it $k$ times? It can be shown that $y = x \cdot 10^0 + x \cdot 10^b + x \cdot 10^{2b} + \dots + x \cdot 10^{(k - 1)b} = x \cdot (10^0 + 10^b + 10^{2b} + \dots + 10^{(k-1)b})$ We are left to consider 2 cases: $k = 1$, in this case the number $x$ is written 1 time, that is, $y = x$. Thus, it is necessary to simply check the number $x$ for primality, which can be done using a known algorithm in $\mathcal{O}(\sqrt{x})$. $x = 1$, in this case the number looks like: $11\dots11$, that is, it is a number consisting of $k$ ones. This number can be generated and checked for primality in $\mathcal{O}(\sqrt{10^k}) = \mathcal{O}(10^{k/2})$. It is also possible to precompute prime numbers consisting only of ones and notice that for $k \leq 7$, the only prime number occurs when $k = 2$, which is $11$.
[ "math", "number theory" ]
1,000
#include <bits/stdc++.h> using namespace std; bool is_prime(int x) { if (x <= 1) { return false; } for (int i = 2; i * i <= x; i++) { if (x % i == 0) { return false; } } return true; } void solve() { int x, k; cin >> x >> k; if (k > 1 && x > 1) { cout << "NO"; } else if (k == 1) { cout << (is_prime(x) ? "YES" : "NO"); } else { cout << ((k == 2) ? "YES" : "NO"); } } int main() { int tests; cin >> tests; while (tests--) { solve(); cout << '\n'; } }
2093
D
Skibidi Table
Vadim loves filling square tables with integers. But today he came up with a way to do it for fun! Let's take, for example, a table of size $2 \times 2$, with rows numbered from top to bottom and columns numbered from left to right. We place $1$ in the top left cell, $2$ in the bottom right, $3$ in the bottom left, and $4$ in the top right. That's all he needs for fun! Fortunately for Vadim, he has a table of size $2^n \times 2^n$. He plans to fill it with integers from $1$ to $2^{2n}$ in ascending order. To fill such a large table, Vadim will divide it into $4$ equal square tables, filling the top left one first, then the bottom right one, followed by the bottom left one, and finally the top right one. Each smaller table will be divided into even smaller ones as he fills them until he reaches tables of size $2 \times 2$, which he will fill in the order described above. Now Vadim is eager to start filling the table, but he has $q$ questions of two types: - what number will be in the cell at the $x$-th row and $y$-th column; - in which cell coordinates will the number $d$ be located. Help answer Vadim's questions.
Note that there are $4$ possible positions of the cell and the values within it: $x,y \le 2^{n-1} \Leftrightarrow d \le 2^{2n-2}$; $x,y > 2^{n-1} \Leftrightarrow 2^{2n-2} < d \le 2 \cdot 2^{2n-2}$; $x > 2^{n-1}, y \le 2^{n-1} \Leftrightarrow 2 \cdot 2^{2n-2} < d \le 3 \cdot 2^{2n-2}$; $x \le 2^{n-1}, y > 2^{n-1} \Leftrightarrow 3 \cdot 2^{2n-2} < d \le 4 \cdot 2^{2n-2}$. This can be implemented either with a recursive function, or by subtracting the necessary powers of two, or by integer division of the coordinates by $2$ and the value by $4$, or by analyzing the bits in the binary representation of $x-1, y-1$, and $d-1$, or through a kind of binary search. Each of these solutions answers one query in $O(n)$.
[ "bitmasks", "implementation" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, q; cin >> n >> q; while (q--) { string type; cin >> type; if (type == "->") { int x, y; cin >> x >> y; x--, y--; long long num = 0; for (int i = n - 1; i >= 0; --i) { int cur = 1 << i; if (!(x & cur) && !(y & cur)) num ^= 0ll << (2 * i); if ((x & cur) && (y & cur)) num ^= 1ll << (2 * i); if ((x & cur) && !(y & cur)) num ^= 2ll << (2 * i); if (!(x & cur) && (y & cur)) num ^= 3ll << (2 * i); } cout << num + 1 << '\n'; } else { long long num; cin >> num; num--; int x = 0, y = 0; for (int i = n - 1; i >= 0; --i) { long long cur = 3ll << (2 * i); if ((num & cur) >> (2 * i) == 0) x ^= 0 << i, y ^= 0 << i; if ((num & cur) >> (2 * i) == 1) x ^= 1 << i, y ^= 1 << i; if ((num & cur) >> (2 * i) == 2) x ^= 1 << i, y ^= 0 << i; if ((num & cur) >> (2 * i) == 3) x ^= 0 << i, y ^= 1 << i; } cout << x + 1 << ' ' << y + 1 << '\n'; } } } return 0; }