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
1987
E
Wonderful Tree!
\begin{quote} God's Blessing on This ArrayForces! \hfill A Random Pebble \end{quote} You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it. Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$. Find the minimum number of operations needed to make the given tree wonderful! \begin{footnotesize} $^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if: - $u$ and $v$ are connected by an edge, and - $v$ is on the (unique) path from $u$ to the root of the tree. \end{footnotesize}
Let $b_v := \sum_{u \in L}{a_u} - a_v$ if $L$ is not empty and $b_v := +\infty$ otherwise. Then, in one operation we decrease $b_v$ by $1$ and increase $b_{p_v}$ by $1$ ($p_v$ is the parent of $v$), and our objective is to make $b_v \ge 0$ for all vertices $v$ in as few operations as possible. We can actually chain our operations to form a more powerful one. In particular, the new operation becomes: Select two vertices $v$ and $w$ such that $d_v \le d_w$ and $v$ is an ancestor of $w$ by paying $d_w - d_v$ coins, where $d_v$ is the depth of vertex $v$. Decrease $b_w$ by $1$ and increase $b_v$ by $1$. Suppose one optimal sequence of operations applies the operations on the pairs of vertices $(v_1, w_1)$ and $(v_2, w_2)$ and the paths $v_1 \rightarrow w_1$ and $v_2 \rightarrow w_2$ intersect. Then, applying the operations on the pairs of vertices $(v_1, w_2)$ and $(v_2, w_1)$, is not less optimal since $(d_{w_1} - d_{v_1}) + (d_{w_2} - d_{v_2}) = (d_{w_2} - d_{v_1}) + (d_{w_1} - d_{v_2})$. This means that we can choose which operations to apply on lower $v$ without caring about its ancestors. Example of two operations on $(v_1, w_1)$ and $(v_2, w_2)$. Suppose that after some sequence of operations, which includes the operation $(v, w)$, there is a vertex $u$ in the subtree of $v$ with $d_u < d_w$ and $b_u > 0$. Then, it is optimal to apply the operation on $(v, u)$ instead of $(v, w)$. This means that we want to apply the operation on the closest vertices in the subtree of $v$. The two observations above lead to a greedy. We will iterate over all $v$ from $n$ to $1$, and while $b_v$ is less than zero, keep applying the operation on $(v, u)$, where $u$ is the closest vertex in the subtree of $v$ with $b_u > 0$. This is possible to implement in a number of ways, one of them includes running a bfs from each vertex $v$. Complexity: $\mathcal{O}(n^2)$ Note: it is possible to solve this problem faster, up to only $\mathcal{O}(n)$ time.
[ "brute force", "data structures", "dfs and similar", "dsu", "greedy", "trees" ]
2,000
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; const ll inf = 1e15; void solve() { int n; cin >> n; vector<int> a(n); for (auto &x: a) cin >> x; vector<int> d(n); vector<vector<int>> g(n); for (int i = 1; i < n; i++) { int p; cin >> p; p--; g[p].push_back(i); d[i] = d[p] + 1; } vector<ll> b(n); // b[v] = sum(a[u]) - a[v] for (int v = 0; v < n; v++) { if (g[v].empty()) { b[v] = inf; } else { b[v] = -a[v]; for (int u: g[v]) { b[v] += a[u]; } } } ll ans = 0; for (int v = n - 1; v >= 0; v--) { queue<int> q; q.push(v); while (!q.empty()) { int i = q.front(); q.pop(); for (int u: g[i]) { ll delta = min(-b[v], b[u]); if (delta > 0) { b[v] += delta; b[u] -= delta; ans += delta * (d[u] - d[v]); } q.push(u); } } } cout << ans << nl; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { solve(); } }
1987
F2
Interesting Problem (Hard Version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if both versions of the problem are solved.} You are given an array of integers $a$ of length $n$. In one operation, you will perform the following two-step process: - Choose an index $i$ such that $1 \le i < |a|$ and $a_i = i$. - Remove $a_i$ and $a_{i+1}$ from the array and concatenate the remaining parts. Find the maximum number of times that you can perform the operation above.
Balanced bracket sequence analogy Suppose there is a way to remove the entire array. Let's look at the process in reverse. Then, we are effectively inserting pairs of adjacent elements into an array until we get the original one. Let's look at a mirror process, where instead we keep inserting pairs of brackets $()$ to get a balanced bracket sequence. For example, consider the array $[1, 2, 5, 4, 5, 7, 7, 1]$. Then, one possible way to delete it is $[1, 2, 5, 4, 5, 7, \color{red}{7}, \color{blue}{1}] \rightarrow [1, 2, 5, \color{red}{4}, \color{blue}{5}, 7] \rightarrow [1, \color{red}{2}, \color{blue}{5}, 7] \rightarrow [\color{red}{1}, \color{blue}{7}] \rightarrow []$. If we now build our bracket sequence, we get $\emptyset \rightarrow \color{red}{(}\color{blue}{)} \rightarrow (\color{red}{(}\color{blue}{)}) \rightarrow (()\color{red}{(}\color{blue}{)}) \rightarrow (()())\color{red}{(}\color{blue}{)}$. Note that such a bracket sequence doesn't tell us in which order the operation needs to be performed, only on which indices. Solution Let's go back to the original problem. Suppose we want to eventually perform the operation on index $i$ (in the indexation of the original array). Then, two conditions must be met: $a_i \equiv i \pmod{2}$ must hold, since the operation does not change the parity of indices. Exactly $\frac{i - a_i}{2}$ operations must be made to the left of $a_i$ before we apply the operation on it. This, together with the bracket analogy, leads to a pretty natural dynamic programming solution: $dp[l][r] =$ min number of operations that need to be performed to the left of $l$ to be able to remove the subsegment $a_l, \ldots, a_r$. If $l > r$, initialize $dp[l][r] := 0$, else initialize $dp[l][r] := +\infty$. Similar to dps on balanced bracket sequences, for $a_l$, we will iterate over the other element $a_m$ with which we will perform the operation, $l \equiv m \pmod{2}$: If $dp[l+1][m-1]$ is greater than $\frac{l - a_l}{2}$, it is impossible to apply the operation on the pair $(a_l, a_m)$, so we do not update $dp[l][r]$. Else, it will take at least $op := \max(\frac{l - a_l}{2}, dp[m+1][r] - \frac{m-l+1}{2})$ operations to the left of $l$ to delete this subsegment if we want to perform the operation on $(a_l, a_m)$. So we update as follows: $dp[l][r] := \min(dp[l][r], op)$. Suppose we have calculated all the values of $dp[l][r]$. Let's introduce $dp2[r] =$ the maximum number of times that we can perform the operation on the prefix $a_1, a_2, \ldots, a_r$, initially $dp2[r] := 0$ for all $0 \le r \le n$. Then, for some $r$, the transitions are to iterate over all $1 \le l \le r$ and update $dp2[r] := \max(dp2[r], dp2[l - 1] + \frac{r - l + 1}{2})$ if $dp[l][r] \le dp2[l - 1]$ holds. The answer to the problem is $dp2[n]$. It takes $\mathcal{O}(n^3)$ time to calculate the values of $dp[l][r]$, and $\mathcal{O}(n^2)$ time for $dp2[r]$. Complexity: $\mathcal{O}(n^3)$ Note: to solve F1, you can calculate the values of $dp[l][r][k] =$ the maximum number of operations that you can perform on the subsegment $a_l, \ldots, a_r$ if exactly $k$ operations were performed to the left of $l$, which can be done similar to the way above in $O(n^4)$. The answer will be $dp[1][n][0]$.
[ "dp" ]
2,600
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; const int inf = 1e9; void solve() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) cin >> a[i]; vector<vector<int>> dp(n + 1, vector<int> (n + 1, inf)); for (int i = 0; i <= n; i++) { dp[i][i] = 0; } for (int le = 1; le <= n; le++) { for (int l = 0; l + le <= n; l++) { if (a[l] % 2 != (l + 1) % 2) continue; if (a[l] > l + 1) continue; int v = (l + 1 - a[l]) / 2; int r = l + le; for (int m = l + 1; m < r; m += 2) { // index of the closing bracket if (dp[l + 1][m] <= v) { int new_val = max(v, dp[m + 1][r] - (m - l + 1) / 2); dp[l][r] = min(dp[l][r], new_val); } } } } vector<int> dp2(n + 1); for (int i = 0; i < n; i++) { dp2[i + 1] = dp2[i]; for (int j = 0; j < i; j++) { if (dp[j][i + 1] <= dp2[j]) { dp2[i + 1] = max(dp2[i + 1], dp2[j] + (i - j + 1) / 2); } } } cout << dp2[n] << nl; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { solve(); } }
1987
G1
Spinning Round (Easy Version)
\textbf{This is the easy version of the problem. The only difference between the two versions are the allowed characters in $s$. In the easy version, $s$ only contains the character ?. You can make hacks only if both versions of the problem are solved.} You are given a permutation $p$ of length $n$. You are also given a string $s$ of length $n$, consisting only of the character ?. For each $i$ from $1$ to $n$: - Define $l_i$ as the largest index $j < i$ such that $p_j > p_i$. If there is no such index, $l_i := i$. - Define $r_i$ as the smallest index $j > i$ such that $p_j > p_i$. If there is no such index, $r_i := i$. Initially, you have an undirected graph with $n$ vertices (numbered from $1$ to $n$) and no edges. Then, for each $i$ from $1$ to $n$, add one edge to the graph: - If $s_i =$ L, add the edge $(i, l_i)$ to the graph. - If $s_i =$ R, add the edge $(i, r_i)$ to the graph. - If $s_i =$ ?, either add the edge $(i, l_i)$ or the edge $(i, r_i)$ to the graph at your choice. Find the maximum possible diameter$^{\text{∗}}$ over all \textbf{connected} graphs that you can form. Output $-1$ if it is not possible to form any connected graphs. \begin{footnotesize} $^{\text{∗}}$ Let $d(s, t)$ denote the smallest number of edges on any path between $s$ and $t$. The diameter of the graph is defined as the maximum value of $d(s, t)$ over all pairs of vertices $s$ and $t$. \end{footnotesize}
Meow? (Waiting for something to happen?) Consider that the edges are directed from $i \to l_i$ or $i \to r_i$ respectively. So that edges point from vertices with smaller values to vertices with larger values. That is $a \to b$ implies that $p_a < p_b$. Notice that by definition, every vertex must have only $1$ edge that is going out of it. Therefore, if we consider the diameter to be something like $v_1 \to v_2 \to v_3 \to \ldots \to v_k \leftarrow \ldots \leftarrow v_{d-1} \leftarrow v_{d}$, since it is impossible for there to be some $\leftarrow v_i \to$ since each vertex has exactly one edge going out of it. Therefore, it makes that we can split the path into 2 distinct parts: - $v_1 \to v_2 \to v_3 \to \ldots \to v_k$ - $v_d \to v_{d-1} \to \ldots \to v_{k}$ I claim that I can choose some $m$ such that the path $v_1 \to v_2 \to v_3 \to \ldots \to v_{k-1}$ and $v_d \to v_{d-1} \to \ldots \to v_{k+1}$ are in the range $[1,m]$ and $[m+1,n]$ or vice versa. That we are able to cut the array into half and each path will stay on their side. The red line shown above is the cutting line, as described. Proof is at the bottom under Proof 1 for completeness. Now, we want to use this idea to make a meet in the middle solutions where we merge max stacks from both sides. Specifically: - maintain a max stack of elements as we are sweeping from $i=1\ldots n$. - for each element on the max stack, maintain the maximum size of a path that is rooted on that element. Here is an example with $p=[4,1,5,3,2,6]$ $i=1$: $s=[(4,1)]$ $i=2$: $s=[(4,2),(1,1)]$ $i=3$: $s=[(5,3)]$ $i=4$: $s=[(5,3),(3,1)]$ $i=5$: $s=[(5,3),(3,2),(2,1)]$ $i=6$: $s=[(6,4)]$ When we insert a new element $x$, we pop all $(p_i,val)$ with $p_i < p_x$ and add in $(x,\max(val)+1)$ into the stack. Now, all elements of the stack has to updated with $s_{i,1} := \max(s_{i,1},s_{i+1,1}+1)$, which is really updating a suffix of $s_{*,1}$ with $val+k,\ldots,val+1,val$. Firstly, it is clear that the $2$ vertices we merge, should have the biggest $p_i$ value, since a bigger $p_i$ value implies a bigger path size. What we care about is the biggest path size possible only using vertices on $[1,i]$, which we denote array $best$. In the above example, $best = [1,2,3,3,4]$. We really only care about obtaining the array $best$ and not $s$. We can find this array in $O(n \log n)$ using segment trees or even in $O(n)$. However, we cannot directly take the biggest values on each side. Consider $p=[2,1\mid,3,4]$. On the left and right side, the max stacks are $[2,1]$ and $[4,3]$ respectively, but we cannot connect $2$ with $4$ since the $3$ is blocking the $2$. Suppose $a_1,a_2,\ldots,a_s$ are the prefix maximums while $b_1,b_2,\ldots,b_t$ are the suffix maximums. Then, if the dividing line is at $a_i \leq m < a_{i+1}$, we will merge $a_i$ on the left side with $a_{i+1}$ on the right side. Similarly, if the dividing line is at $b_i \leq m < b_{i+1}$, we will merge $b_i$ on the left side with $b_{i+1}$ on the right side. So, if $a_i \leq m < a_{i+1}$, it is equivalent to merging the best path on $[1,m]$ and $(m,a_{i+1})$ since then $a_{i+1}$ will be the root of the best path on the right side. It is similar for $b_i \leq m < b_{i+1}$. Actually, we can prove that instead of $(m,a_{i+1})$, $(m,a_{i})$ is enough, and the proof is left as an exercise. The total complexity becomes $O(n \log n)$ or $O(n)$ depending on how quickly array $best$ is found for subarrays. Suppose that there are 2 paths $a_1 \to a_2 \to \ldots \to a_s$ and $b_1 \to b_2 \to \ldots \to b_t$, $a_1 < b_1$, and $a_s = b_t$ but they do not intersect at any vertices other vertices. Then we will prove that there is no such case where $a_s' > b_t'$. Suppose that it is true that we can find some $a_{s'} > b_{t'}$. Let $(s',t')$ be the minimum counterexample so that $a_{s'} > b_{t'}$ but $a_{s'-1}<b_{t}$. Therefore, we have $a_{s'-1} < b_t < a_{s'}$. By definition, that $r_{a_{s'-1}} = a_{s'}$, we have $p_{b_t} < p_{a_{s'-1}}$. Then, $a_s$ cannot be in between $a_{s'-1}$ and $a_{s'}$ or else $r_{a_{s'-1}} = a_{s} \neq a_{s'}$. But, then we need to find a path from $b_{t'}$ to $b_{t}=a_{s}$ which does not touch either $a_{s'-1}$ or $a_{s'}$ which is impossible.
[ "divide and conquer", "dp", "trees" ]
2,900
#include <bits/stdc++.h> using namespace std; #define ii pair<int,int> #define fi first #define se second #define pub push_back #define pob pop_back #define rep(x,start,end) for(int x=(start)-((start)>(end));x!=(end)-((start)>(end));((start)<(end)?x++:x--)) #define sz(x) (int)(x).size() int n; int arr[400005]; string s; int ans[2][400005]; int t[400005]; vector<int> stk[2]; vector<ii> process(int l,int r,int val[]){ vector<ii> v; int curr=0; rep(x,l,r+1){ ii res={x,0}; while (!v.empty() && arr[v.back().fi]<arr[x]){ int t=v.back().se; v.pob(); if (!v.empty()) v.back().se=max(v.back().se,t+1); res.se=max(res.se,t+1); } v.pub(res); curr=max(curr,res.se+sz(v)); val[x]=curr; } return v; } signed main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin.exceptions(ios::badbit | ios::failbit); int TC; cin>>TC; while (TC--){ cin>>n; rep(x,1,n+1) cin>>arr[x]; cin>>s; rep(z,0,2){ auto v=process(1,n,ans[z]); stk[z].clear(); for (auto [a,b]:v) stk[z].pub(a); reverse(arr+1,arr+n+1); } int mx=ans[0][stk[0][0]]+ans[1][n-stk[0][0]+1]-1; rep(z,0,2){ rep(x,0,sz(stk[z])-1){ process(stk[z][x],stk[z][x+1],t); rep(y,stk[z][x],stk[z][x+1]) mx=max(mx,t[y]+ans[z^1][n-y]); } reverse(arr+1,arr+n+1); } cout<<mx-1<<endl; } }
1987
G2
Spinning Round (Hard Version)
\textbf{This is the hard version of the problem. The only difference between the two versions are the allowed characters in $s$. You can make hacks only if both versions of the problem are solved.} You are given a permutation $p$ of length $n$. You are also given a string $s$ of length $n$, where each character is either L, R, or ?. For each $i$ from $1$ to $n$: - Define $l_i$ as the largest index $j < i$ such that $p_j > p_i$. If there is no such index, $l_i := i$. - Define $r_i$ as the smallest index $j > i$ such that $p_j > p_i$. If there is no such index, $r_i := i$. Initially, you have an undirected graph with $n$ vertices (numbered from $1$ to $n$) and no edges. Then, for each $i$ from $1$ to $n$, add one edge to the graph: - If $s_i =$ L, add the edge $(i, l_i)$ to the graph. - If $s_i =$ R, add the edge $(i, r_i)$ to the graph. - If $s_i =$ ?, either add the edge $(i, l_i)$ or the edge $(i, r_i)$ to the graph at your choice. Find the maximum possible diameter over all \textbf{connected}$^{\text{∗}}$ graphs that you can form. Output $-1$ if it is not possible to form any connected graphs. \begin{footnotesize} $^{\text{∗}}$ Let $d(s, t)$ denote the smallest number of edges on any path between $s$ and $t$. The diameter of the graph is defined as the maximum value of $d(s, t)$ over all pairs of vertices $s$ and $t$. \end{footnotesize}
For simplicity, let $p_0 = p_{n+1} = +\infty$, and let's recalculate the values of $l_i$ and $r_i$. Then, the answer is not $-1$ if for all $1 \le i \le n$ and $p_i < n$: $s_i =~$L $\implies l_i \ge 1$. $s_i =~$R $\implies r_i \le n$. $s_i =~$? $\implies l_i \ge 1$ or $r_i \le n$. Let $dp[tl][tr]$ store some set of pairs $(a, b)$, where for some valid graph: $a$ is a possible depth of a path that starts at index $tl$ and passes only through indices $tl \le i \le tr$. $b$ is a possible depth of a path that starts at index $tr$ and passes only through indices $tl \le i \le tr$. The paths do not intersect. Let's iterate over all $i$ in order of increasing $p_i$. For each $i$ ($tl = l_i$ and $tr = r_i$), we will iterate over all pairs $(d_1, d_2)$ in $dp[tl][i]$ and $(e_1, e_2)$ in $dp[i][tr]$: If $s_i \neq$ R and $tl \ge 1$, we can add the edge $(tl, i)$, so: Update the answer with $\max(ans, d_1 + 1 + \max(d_2, e_1))$. Add the pairs $(d_1, e_2)$, $(d_2 + 1, e_2)$, and $(e_1 + 1, e_2)$ to $dp[tl][tr]$. Update the answer with $\max(ans, d_1 + 1 + \max(d_2, e_1))$. Add the pairs $(d_1, e_2)$, $(d_2 + 1, e_2)$, and $(e_1 + 1, e_2)$ to $dp[tl][tr]$. If $s_i \neq$ L and $tr \le n$, we can add the edge $(i, tr)$, so: Update the answer with $\max(ans, \max(d_2, e_1) + 1 + e_2)$. Add the pairs $(d_1, d_2 + 1)$, $(d_1, e_1 + 1)$, and $(d_1, e_2)$ to $dp[tl][tr]$. Update the answer with $\max(ans, \max(d_2, e_1) + 1 + e_2)$. Add the pairs $(d_1, d_2 + 1)$, $(d_1, e_1 + 1)$, and $(d_1, e_2)$ to $dp[tl][tr]$. Turns out, it is enough to store at most three pairs for each $dp[tl][tr]$. Specifically, it is enough to store: One pair with the maximum possible $a$. One pair with the maximum possible $b$. One pair with the maximum possible $a + b$. If true, this leads to an $\mathcal{O}(n)$ or $\mathcal{O}(n \log n)$ solution, albeit with a large constant factor. Proof We will proceed with a proof by induction. Hypothesis: it is enough to store the three pairs described above. Base case: for $i$ with $l_i = i - 1$ and $r_i = i + 1$, only the pairs $(0, 0)$, $(1, 0)$ and $(0, 1)$ are possible. Induction step: For some $i$, let $dp[tl][i]$ and $dp[i][tr]$ only store the three pairs described above. First of all, we update the answer with the same value: When adding the left edge: If the answer came from $d_1 + 1 + d_2$, we maximize $d_1 + d_2$. If the answer came from $d_1 + 1 + e_1$, we maximize $d_1$ and $e_1$. If the answer came from $d_1 + 1 + d_2$, we maximize $d_1 + d_2$. If the answer came from $d_1 + 1 + e_1$, we maximize $d_1$ and $e_1$. When adding the right edge: If the answer came from $d_2 + 1 + e_2$, we maximize $d_2$ and $e_2$. If the answer came from $e_1 + 1 + e_2$, we maximize $e_1 + e_2$. If the answer came from $d_2 + 1 + e_2$, we maximize $d_2$ and $e_2$. If the answer came from $e_1 + 1 + e_2$, we maximize $e_1 + e_2$. Secondly, $dp[tl][tr]$ will store the pairs with the same values of $\max a$, $\max b$, and $\max (a + b)$; as in the case when all pairs are stored on all previous stages: When adding the left edge, it is clearly not less optimal to add only the pair $(\max(d_1, d_2 + 1, e_1 + 1), e_2)$: When maximizing $a$, we maximize $\max(d_1, d_2 + 1, e_1 + 1)$, which we do by maximizing $d_1$, $d_2$, or $e_1$. When maximizing $b$, we maximize $e_2$. When maximizing $a + b$, we maximize $d_1 + e_2$, $d_2 + e_2$, or $e_1 + e_2$, which we do by induction. When maximizing $a$, we maximize $\max(d_1, d_2 + 1, e_1 + 1)$, which we do by maximizing $d_1$, $d_2$, or $e_1$. When maximizing $b$, we maximize $e_2$. When maximizing $a + b$, we maximize $d_1 + e_2$, $d_2 + e_2$, or $e_1 + e_2$, which we do by induction. When adding the right edge, we can only add the pair $(d_1, \max(d_2 + 1, e_1 + 1, e_2))$: When maximizing $a$, we maximize $d_1$. When maximizing $b$, we maximize $\max(d_2 + 1, e_1 + 1, e_2)$, which we do by maximizing $d_2$, $e_1$, or $e_2$. When maximizing $a + b$, we maximize $d_1 + d_2$, $d_1 + e_1$, or $d_1 + e_2$, which we do by induction. When maximizing $a$, we maximize $d_1$. When maximizing $b$, we maximize $\max(d_2 + 1, e_1 + 1, e_2)$, which we do by maximizing $d_2$, $e_1$, or $e_2$. When maximizing $a + b$, we maximize $d_1 + d_2$, $d_1 + e_1$, or $d_1 + e_2$, which we do by induction. Thus, we achieve the same answer by only storing these pairs, which concludes our proof. Complexity: $\mathcal{O}(n)$ or $\mathcal{O}(n \log n)$ Note: there are a number of other possible solutions, please refer to the comments below.
[ "divide and conquer", "dp", "trees" ]
3,500
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; array<vector<int>, 2> get_l_and_r(vector<int> &p) { int n = p.size(); vector<int> l(n), r(n); stack<int> s; for (int i = 0; i < n; i++) { while (!s.empty() && p[s.top()] < p[i]) s.pop(); if (s.empty()) l[i] = -1; else l[i] = s.top(); s.push(i); } s = {}; for (int i = n - 1; i >= 0; i--) { while (!s.empty() && p[s.top()] < p[i]) s.pop(); if (s.empty()) r[i] = n; else r[i] = s.top(); s.push(i); } return {l, r}; } int ans_l_edge(array<int, 2> d, array<int, 2> e) { return d[0] + 1 + max(d[1], e[0]); } int ans_r_edge(array<int, 2> d, array<int, 2> e) { return e[1] + 1 + max(d[1], e[0]); } array<int, 2> add_l_edge(array<int, 2> d, array<int, 2> e) { return {max({d[0], d[1] + 1, e[0] + 1}), e[1]}; } array<int, 2> add_r_edge(array<int, 2> d, array<int, 2> e) { return {d[0], max({d[1] + 1, e[0] + 1, e[1]})}; } vector<array<int, 2>> process_dp(vector<array<int, 2>> &dp) { array<int, 2> max_a = {-1, -1}, max_b = {-1, -1}, max_s = {-1, -1}; for (auto [a, b]: dp) { if (a > max_a[0] || (a == max_a[0] && b > max_a[1])) { max_a = {a, b}; } if (b > max_b[1] || (b == max_b[1] && a > max_b[0])) { max_b = {a, b}; } if (a + b > max_s[0] + max_s[1]) { max_s = {a, b}; } } return {max_a, max_b, max_s}; } void add_to_map(map<array<int, 2>, int> &dp_ind, int &len_dp, array<int, 2> a) { if (!dp_ind.count(a)) { dp_ind[a] = len_dp++; } } void solve() { int n; cin >> n; vector<int> p(n); for (int i = 0; i < n; i++) cin >> p[i]; string s; cin >> s; auto [l, r] = get_l_and_r(p); for (int i = 0; i < n; i++) { if (p[i] == n) continue; if (l[i] == -1 && s[i] == 'L') { cout << -1 << nl; return; } if (r[i] == n && s[i] == 'R') { cout << -1 << nl; return; } } int ans = 0; vector<int> q(n + 1); for (int i = 0; i < n; i++) { q[p[i]] = i; } int len_dp = 0; map<array<int, 2>, int> dp_ind; for (int x = 1; x <= n; x++) { int i = q[x]; int tl = l[i], tr = r[i]; add_to_map(dp_ind, len_dp, {tl, i}); add_to_map(dp_ind, len_dp, {i, tr}); add_to_map(dp_ind, len_dp, {tl, tr}); } vector<vector<array<int, 2>>> dp(len_dp, {{0, 0}}); for (int x = 1; x <= n; x++) { int i = q[x]; int tl = l[i], tr = r[i]; int ind_l = dp_ind[{tl, i}]; int ind_r = dp_ind[{i, tr}]; int ind_c = dp_ind[{tl, tr}]; for (auto const &d: dp[ind_l]) { for (auto const &e: dp[ind_r]) { ans = max(ans, d[1] + e[0]); if (tl >= 0 && s[i] != 'R') { ans = max(ans, ans_l_edge(d, e)); dp[ind_c].push_back(add_l_edge(d, e)); } if (tr <= n - 1 && s[i] != 'L') { ans = max(ans, ans_r_edge(d, e)); dp[ind_c].push_back(add_r_edge(d, e)); } } } dp[ind_c] = process_dp(dp[ind_c]); } cout << ans << nl; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { solve(); } }
1987
H
Fumo Temple
\begin{quote} This temple only magnifies the mountain's power. \hfill Badeline \end{quote} This is an interactive problem. You are given two positive integers $n$ and $m$ ($\bf{n \le m}$). The jury has hidden from you a rectangular matrix $a$ with $n$ rows and $m$ columns, where $a_{i,j} \in \{ -1, 0, 1 \}$ for all $1 \le i \le n$ and $1 \le j \le m$. The jury has also selected a cell $(i_0, j_0)$. Your goal is to find $(i_0,j_0)$. In one query, you give a cell $(i, j)$, then the jury will reply with an integer. - If $(i, j) = (i_0, j_0)$, the jury will reply with $0$. - Else, let $S$ be the sum of $a_{x,y}$ over all $x$ and $y$ such that $\min(i, i_0) \le x \le \max(i, i_0)$ and $\min(j, j_0) \le y \le \max(j, j_0)$. Then, the jury will reply with $|i - i_0| + |j - j_0| + |S|$. Find $(i_0, j_0)$ by making at most $n + 225$ queries. \textbf{Note: the grader is not adaptive}: $a$ and $(i_0,j_0)$ are fixed before any queries are made.
In this solution, we will assume that there is no matrix $a$ and the interactor just returns some number $x$ between $di + dj \le x \le di + dj + (di + 1)(dj + 1)$, where $di = |i - i_0|$ and $dj = |j - j_0|$. Let's first solve for $n = 1$. Let the hidden cell be $(1, j_0)$. Let $l = 1$ and $r = m$. On each iteration, we will query the cell $(1, l)$, let the result be $x$. If $x = 0$, we are done. Else, we know that $j_0 - l \le x \le j_0 - l + (j_0 - l + 1)$. Transforming, we get $\max(l + 1, \frac{x-1}{2} + l) \le j_0 \le \min(r, x + l)$. So, on each iteration, we at least half the length of $[l; r]$, so we use at most $\lceil \log_2(m) \rceil$ queries. This allows us to solve the problem in $n \cdot \lceil \log_2(m) \rceil$ queries, if for each row we assume that the hidden cell is in it and then run the algorithm above. We will solve the problem recursively, ensuring $n \le m$. If $m \le A$ (we will choose $A$ later), we can solve the problem for the remaining rows in $A \cdot \lceil \log_2(A) \rceil$ queries. Else, our objective is to either decrease $m$ by a lot, or decrease $n$ by a bit and recurse further. To do that, we will query the three cells $(2, \frac{3m}{16}), (2, \frac{m}{2}), (2, \frac{13m}{16})$ (choose integer coordinates + things should be pretty symmetrical). This ensures that for large enough $m$, if we get a large query result $> B$ ($B$ is around $\frac{3m}{4}$), we will know that $i_0 \ge 4$ must hold, and so we will recurse with $n_{new} = n - 3$ and $m_{new} = m$. If not, we will recurse to $n_{new} \le m_{new} \le B$ ($n_{new} \le m_{new}$ since we query on the edge of the matrix). For the model solution below, we take at most $63$ queries to get to $m \le A = 25$, so we solve the problem in at most $n + 3 \cdot 21 + 25 \cdot \lceil \log_2(25) \rceil = n + 188 \le n + 225$ queries. You can get a slightly better constant factor with this solution, or you can even reduce $n$ by a rate of quicker than $1$ per $1$ query. Complexity: $\mathcal{O}(nm)$
[ "interactive" ]
3,500
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() #define allr(x) (x).rbegin(), (x).rend() const char nl = '\n'; typedef long long ll; typedef long double ld; using namespace std; int ans_x = 0, ans_y = 0, cnt_q = 0; // Coordinates are flipped int query(int x, int y) { cnt_q++; int res = 0; cout << "? " << y << ' ' << x << endl; cout.flush(); cin >> res; if (res < 0) { exit(0); } if (res == 0) { ans_x = x; ans_y = y; } return res; } /* Explanation: * Splits the stripe of three into |a-O-a-b-O-b-a-O-a|. * O are the three query points (all in the same column). * Cons: hard to correctly account for errors in a non-bruteforce way. * Pros: gives a better constant factor (3 / 4 of the original length) * Number of queries: n + 3 * 21 + 25 * ceil(log(25, 2)) + eps * Though the binary search part uses less queries than that */ void f(int lx, int rx, int ly, int ry) { int n = rx - lx + 1; // Bruteforce base case (uses binary search) if (n <= 25) { // can be n <= 22 or above for (int x = lx; x <= rx; x++) { int lb = ly, ub = ry; while (lb <= ub) { int res = query(x, lb); int low_y = ((res - 1) + 1) / 2, high_y = res; int new_lb = lb + max(1, low_y), new_ub = min(ub, lb + high_y); lb = new_lb; ub = new_ub; } } return; } // Here, (2a - 1) + (2b - 1) + (2a - 1) = n int a = 3 * (n + 3) / 16; int y = min(ry, ly + 1); int x1 = lx + a - 1; x1 = max(x1, lx); x1 = min(x1, rx); int x2 = (lx + rx) / 2; x2 = max(x2, x1 + 1); x2 = min(x2, rx); int x3 = rx - a + 1; x3 = max(x3, x2 + 1); x3 = min(x3, rx); int m = min(3, ry - ly + 1); vector<vector<bool>> good(n, vector<bool> (m, true)); int new_lx = lx, new_rx = rx; int new_ly = ly, new_ry = ry; for (int x: {x1, x2, x3}) { int res = query(x, y); new_lx = max(new_lx, x - res); new_rx = min(new_rx, x + res); new_ly = max(new_ly, y - res); new_ry = min(new_ry, y + res); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int r_x = lx + i, r_y = ly + j; int dx = abs(r_x - x); int dy = abs(r_y - y); int d = dx + dy; int S = (dx + 1) * (dy + 1); // d <= res <= d + S must hold if (res < d || d + S < res) { good[i][j] = false; } } } } bool has_good = false; for (auto vx: good) { for (auto vy: vx) { if (vy) { has_good = true; } } } good.clear(); good.shrink_to_fit(); if (has_good) { f(new_lx, new_rx, new_ly, new_ry); } else { f(lx, rx, ly + m, ry); } } void solve() { int n, m; cin >> n >> m; ans_x = 0; ans_y = 0; cnt_q = 0; f(1, m, 1, n); cout << "! " << ans_y << ' ' << ans_x << endl; cout.flush(); cerr << n << ' ' << cnt_q << " | " << n + 225 << endl; } int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) { solve(); } }
1988
A
Split the Multiset
A multiset is a set of numbers in which there can be equal elements, and the order of the numbers does not matter. For example, $\{2,2,4\}$ is a multiset. You have a multiset $S$. Initially, the multiset contains only one positive integer $n$. That is, $S=\{n\}$. Additionally, there is a given positive integer $k$. In one operation, you can select any positive integer $u$ in $S$ and remove one copy of $u$ from $S$. Then, insert no more than $k$ positive integers into $S$ so that the sum of all inserted integers is equal to $u$. Find the minimum number of operations to make $S$ contain $n$ ones.
The optimal sequence of operations is very simple. The optimal sequence of operations is adding $k-1$ 1-s into the set each time, at the same time decreasing $n$ by $k-1$. This implies that the answer is $\lceil \frac{n-1}{k-1}\rceil$. I failed to find a Div2-A level proof. If you have a simpler proof please share it in the comments. Consider the number of elements that is $\equiv 1\pmod{(k-1)}$ in the set. The number of such elements increase by at most $k-1$ in each operation, and the aforementioned sequence of operation achieves the maximum increment. A simpler proof in the comments: consider the number of elements in the set. It increases by at most $k-1$ each time, and our construction reaches the maximum increment.
[ "brute force", "greedy", "implementation", "math" ]
900
t = (int)(input()) for _ in range(t): n, k = map(int, input().split()) print((n - 1 + k - 2) // (k - 1))
1988
B
Make Majority
You are given a sequence $[a_1,\ldots,a_n]$ where each element $a_i$ is either $0$ or $1$. You can apply several (possibly zero) operations to the sequence. In each operation, you select two integers $1\le l\le r\le |a|$ (where $|a|$ is the current length of $a$) and replace $[a_l,\ldots,a_r]$ with a single element $x$, where $x$ is the majority of $[a_l,\ldots,a_r]$. Here, the majority of a sequence consisting of $0$ and $1$ is defined as follows: suppose there are $c_0$ zeros and $c_1$ ones in the sequence, respectively. - If $c_0\ge c_1$, the majority is $0$. - If $c_0<c_1$, the majority is $1$. For example, suppose $a=[1,0,0,0,1,1]$. If we select $l=1,r=2$, the resulting sequence will be $[0,0,0,1,1]$. If we select $l=4,r=6$, the resulting sequence will be $[1,0,0,1]$. Determine if you can make $a=[1]$ with a finite number of operations.
"Most sequences" can be transformed into $[1]$. Conditions for a sequence to be un-transformable is stringent. Find several simple substrings that make the string transformable. We list some simple conditions for a string to be transformable: If 111 exists somewhere (as a substring) in the string, the string is always transformable. If 11 appears at least twice in the string, the string is always transformable. If the string both begins and ends with 1, it is always transformable. If the string begins or ends with 1 and 11 exists in the string, it is always transformable. These can be found by simulating the operation for short strings on paper. Contrarily, if a string does not meet any of the four items, it is always not transformable. This can be proved using induction (as an exercise). Observe that the number of 1 never increases in an operation. We can change a continuous segment of zeros into one zero. After that, it suffices to check that the number of occurences of 1 is larger than the number of occurences of 0.
[ "greedy", "implementation" ]
900
t = (int)(input()) for _ in range(t): n = (int)(input()) a = input() ok = 0 if a.count("111") >= 1: ok = 1 if a.count("11") >= 2: ok = 1 if a.count("11") >= 1 and (a[0] == "1" or a[-1] == "1"): ok = 1 if a[0] == "1" and a[-1] == "1": ok = 1 if ok: print("Yes") else: print("No")
1988
C
Increasing Sequence with Fixed OR
You are given a positive integer $n$. Find the \textbf{longest} sequence of positive integers $a=[a_1,a_2,\ldots,a_k]$ that satisfies the following conditions, and print the sequence: - $a_i\le n$ for all $1\le i\le k$. - $a$ is strictly increasing. That is, $a_i>a_{i-1}$ for all $2\le i\le k$. - $a_i\,|\,a_{i-1}=n$ for all $2\le i\le k$, where $|$ denotes the bitwise OR operation.
The answer is a simple construction. The maximum length for $2^k-1\ (k>1)$ is $k+1$. It's obvious that the answer only depends on the popcount of $n$. Below, we assume $n=2^k-1$. If $k=1$, it is shown in the samples that the length is $1$. Otherwise, the maximum sequence length for $2^k-1$ is $k+1$. This can be achived by $a_i=n-2^{i-1}\ (1\le i\le k),a_{k+1}=n$. Consider the value of $a_1$. Note that its $k$-th bit (indexed from $2^0$ to $2^{k-1}$) should be 0, otherwise we would not make use of the largest bit. Since $a_1$ and $a_2$'s OR is $n$, $a_2$'s $k$-th bit should be 1, and thus the construction of $a_2\sim a_{k+1}$ boils down to the subproblem when $n=2^{k-1}-1$. This shows that $f(k)\le f(k-1)+1$ where $k$ is the popcount of $n$ and $f(k)$ is the maximum sequence length. We know that $f(2)=3$, so $f(k)\le k+1$ for all $k\ge 2$.
[ "bitmasks", "constructive algorithms", "greedy" ]
1,300
t = (int)(input()) for _ in range(t): n = (int)(input()) a = [] for i in range(62, -1, -1): x = 1 << i if ((x & n) == x) and (x != n): a.append(n - x) a.append(n) print(len(a)) for i in a: print(i, end=" ") print("")
1988
D
The Omnipotent Monster Killer
You, the monster killer, want to kill a group of monsters. The monsters are on a tree with $n$ vertices. On vertex with number $i$ ($1\le i\le n$), there is a monster with $a_i$ attack points. You want to battle with monsters for $10^{100}$ rounds. In each round, the following happens in order: - All living monsters attack you. Your health decreases by the sum of attack points of all living monsters. - You select some (possibly all or none) monsters and kill them. After being killed, the monster will not be able to do any attacks in the future. There is a restriction: in one round, you cannot kill two monsters that are directly connected by an edge. If you choose what monsters to attack optimally, what is the smallest health decrement you can have after all rounds?
Formulate the problem. Some variables can't be large. Suppose monster $i$ is killed in round $b_i$. Then, the total health decrement is the sum of $a_i\times b_i$. The "independent set" constraint means that for adjacent vertices, their $b$-s must be different. Observation: $b_i$ does not exceed $\lfloor \log_2 n\rfloor+1$. In this problem, $b_i\le 19$ always holds for at least one optimal $a_i$. Let the mex of a set be the smallest positive integer that does not appear in it. Note that in an optimal arrangement, $b_i=\mathrm{mex}_{(j,i)\in E} b_j$. Consider an vertex with the maximum $b$, equal to $u$. Root the tree at this vertex $x$. The vertices connected with $x$ should take all $b$-s from $1$ to $u-1$. Denote $f(u)$ as the minimum number of vertices to make this happen, we have $f(1)=1,\ f(u)\ge 1+\sum_{1\le i<u}f(i)\to f(u)\ge 2^{u-1}$ This ends the proof. By dp, we can find the answer in $O(n\log n)$ or $O(n\log^2 n)$, depending on whether you use prefix/suffix maximums to optimize the taking max part. Bonus: Find a counterexample for $b_i\le 18$ when $n=300000$. (Pretest 2 is one case) Note that $b_x\le \deg x$. By carefully handing the dp transitions, we can achieve a $O(\sum \deg_x)=O(n)$ solution.
[ "brute force", "dfs and similar", "dp", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; typedef long long ll; int n; ll a[300005], f[300005][24], smn[30]; vector<int> g[300005]; void dfs(int x, int fa) { for (int i = 1; i <= 22; i++) f[x][i] = i * a[x]; for (int y : g[x]) { if (y == fa) continue; dfs(y, x); ll tt = 8e18; smn[23] = 8e18; for (int i = 22; i >= 1; i--) { smn[i] = min(smn[i + 1], f[y][i]); } for (int i = 1; i <= 22; i++) { f[x][i] += min(tt, smn[i + 1]); tt = min(tt, f[y][i]); } } } void Solve() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1, x, y; i < n; i++) { cin >> x >> y; g[x].push_back(y), g[y].push_back(x); } dfs(1, 0); cout << *min_element(f[1] + 1, f[1] + 23) << '\n'; for (int i = 1; i <= n; i++) { g[i].clear(); memset(f[i], 0, sizeof(f[i])); } } int main() { ios::sync_with_stdio(0), cin.tie(0); int t; cin >> t; while (t--) Solve(); }
1988
E
Range Minimum Sum
For an array $[a_1,a_2,\ldots,a_n]$ of length $n$, define $f(a)$ as the sum of the minimum element over all subsegments. That is, $$f(a)=\sum_{l=1}^n\sum_{r=l}^n \min_{l\le i\le r}a_i.$$ A permutation is a sequence of integers from $1$ to $n$ of length $n$ containing each number exactly once. You are given a permutation $[a_1,a_2,\ldots,a_n]$. For each $i$, solve the following problem independently: - Erase $a_i$ from $a$, concatenating the remaining parts, resulting in $b = [a_1,a_2,\ldots,a_{i-1},\;a_{i+1},\ldots,a_{n}]$. - Calculate $f(b)$.
Formulate the problem on a cartesian tree. Find a clever bruteforce. Calculate the time complexity carefully. Build the cartesian tree of $a$. Let $lc_x,rc_x$ respectively be $x$'s left and right children. Consider a vertex $x$. If we delete it, what would happen to the tree? Vertices that are on the outside of $x$'s subtree will not be affected. Vertices inside the subtree of $x$ will "merge". Actually, we can see that, only the right chain of $x$'s left child ($lc_x\to rc_{lc_x}\to rc_{rc_{lc_x}}\to \dots$) and the left chain of $x$'s right child will merge in a way like what we do in mergesort. Now, if we merge the chains by bruteforce (use sorting or std::merge), the time complexity is $O(n)$! It's easy to see that each vertex will only be considered $O(1)$ times.
[ "binary search", "brute force", "data structures", "divide and conquer", "implementation" ]
2,300
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pr; int n, a[500005], st[500005], c[500005][2], top, sz[500005]; ll ans[500005], atv[500005], sum; void dfs1(int x) { sz[x] = 1; for (int i = 0; i < 2; i++) if (c[x][i]) dfs1(c[x][i]), sz[x] += sz[c[x][i]]; sum += (atv[x] = (sz[c[x][0]] + 1ll) * (sz[c[x][1]] + 1ll) * a[x]); } void dfs2(int x, ll dlt) { ll val = sum - dlt - atv[x]; vector<int> lr, rl; vector<pr> ve; int y = c[x][0]; while (y) lr.push_back(y), val -= atv[y], y = c[y][1]; y = c[x][1]; while (y) rl.push_back(y), val -= atv[y], y = c[y][0]; { int i = 0, j = 0; while (i < lr.size() || j < rl.size()) { if (j >= rl.size() || (i < lr.size() && j < rl.size() && a[lr[i]] < a[rl[j]])) { ve.push_back(pr(lr[i], 0)); i++; } else { ve.push_back(pr(rl[j], 1)); j++; } } } // cout << x << ' ' << val << '\n'; int cursz = 0; for (int i = (int)ve.size() - 1; i >= 0; i--) { int p = ve[i].first, q = ve[i].second; // cout << "I:" << i << ' ' << cursz << '\n'; val += (cursz + 1ll) * (sz[c[p][q]] + 1ll) * a[p]; cursz += sz[c[p][q]] + 1; } ans[x] = val; for (int i = 0; i < 2; i++) if (c[x][i]) dfs2(c[x][i], dlt + 1ll * (sz[c[x][i ^ 1]] + 1) * a[x]); } void Solve() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); st[top = 0] = 0; for (int i = 1; i <= n; i++) { while (top && a[st[top]] > a[i]) top--; c[i][0] = c[st[top]][1], c[st[top]][1] = i; st[++top] = i; } int rt = st[1]; sum = 0, dfs1(rt), dfs2(rt, 0); for (int i = 1; i <= n; i++) cout << ans[i] << ' '; cout << '\n'; for (int i = 0; i <= n; i++) c[i][0] = c[i][1] = 0; } int main() { int t; scanf("%d", &t); while (t--) Solve(); }
1988
F
Heartbeat
For an array $u_1, u_2, \ldots, u_n$, define - a prefix maximum as an index $i$ such that $u_i>u_j$ for all $j<i$; - a suffix maximum as an index $i$ such that $u_i>u_j$ for all $j>i$; - an ascent as an index $i$ ($i>1$) such that $u_i>u_{i-1}$. You are given three cost arrays: $[a_1, a_2, \ldots, a_n]$, $[b_1, b_2, \ldots, b_n]$, and $[c_0, c_1, \ldots, c_{n-1}]$. Define the cost of an array that has $x$ prefix maximums, $y$ suffix maximums, and $z$ ascents as $a_x\cdot b_y\cdot c_z$. Let the sum of costs of all permutations of $1,2,\ldots,n$ be $f(n)$. Find $f(1)$, $f(2)$, ..., $f(n)$ modulo $998\,244\,353$.
We can use dp to calculate the number of permutations of $1\sim n$ with $i$ prefix maximums and $j$ ascents, $f(n,i,j)$: consider where 1 is inserted, we will have a $O(n^3)$ dp that finds $f(n,i,j)$ for all suitable $(n,i,j)$-s. For suffix maximums, (the number of permutations of $1\sim n$ with $i$ prefix maximums and $j$ ascents, $g(n,i,j)$, we can just reverse some dimension of $f$). To calculate the answer, consider the position of $n$. Suppose it's $p$. The the answer is $\sum_{p=1}^n\sum_{i=0}^{p-1}\sum_{j=0}^{n-p}\sum_{x=0}^{p-1}\sum_{y=0}^{n-p}f(p-1,i,x)g(n-p,j,y)\binom{n-1}{p-1}a_{i+1}b_{j+1}c_{x+y+[p>1]}$ Let $u(x,y)=\sum_{i}f(x,i,y)a_{i+1}$, $v(x,y)=\sum_{z}g(x,i,y)b_{i+1}$ (both of these are calculated in $O(n^3)$), then the answer is $\sum_{p=1}^n\sum_{x=0}^{p-1}\sum_{y=0}^{n-p}u(p-1,x)v(n-p,y)\binom{n-1}{p-1}c_{x+y+[p>1]}$ By seeing $u$ and $v$ as 2D polynomials, this can be calculated with 2D FFT in $O(n^2\log n)$. Of course! This problem can also be solved with modulo $10^9+7$ or on an algebraic structure where FFT is not easy, but interpolation can be successfully carried out. We still need to consider $u(p-1,*)$ and $v(n-p,*)$ as polynomials $\sum_{i}u(p-1,i)x^i,\sum_{i}v(n-p,i)x^i$. Instead of doing FFT, consider substitute $x$ with $0,1,\dots,n+1$, and use interpolation to recover the final coefficients. Suppose we have a value of $x$. Then, calculating $u(p-1)$ and $v(n-p)$ takes $O(n^2)$ in total. For fixed $x$ and $n$, the answer for $n$ is (here, note how $x$ is multiplied) $\sum_{p=1}^nu(p-1)v(n-p)\binom{n-1}{p-1}x^{p>1}$ This also takes $O(n^2)$ in total. So, for each $x$, the calculation is $O(n^2)$. For each $n$, the naive implementation of interpolation runs in $O(n^2)$. After we recover the coefficients, we multiply it with $c$ and update the answer. So, the time complexity is $O(n^3)$. We are trying to iterate over $i,x,j,y$ and do $ans_{i+j}\leftarrow f(i,x)g(j,y)h_{x+y}$. We can achieve this with two steps: first, iterate over $i,x,y$ and do $v_{i,y}\leftarrow f(i,x)h_{x+y}$. Then, iterate over $i,j,y$ and do $ans_{i+j}\leftarrow g(j,y)v_{i,y}$. This runs in $O(n^3)$, and does not need to calculate inverses, and thus can be carried out on any ring.
[ "combinatorics", "dp", "fft", "math" ]
3,000
#include <bits/stdc++.h> using namespace std; const int mod = 998244353, N = 705; int n, a[N + 5], b[N + 5], c[N + 5], f[N + 5][N + 5], u[N + 5][N + 5], v[N + 5][N + 5], C[N + 5][N + 5]; int g[N + 5], h[N + 5], t[N + 5][N + 5], p[N + 5][N + 5], ny[N + 5], o[N + 5]; void upd(int &x, int y) { x += y, (x >= mod && (x -= mod)); } int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= n; i++) cin >> b[i]; for (int i = 0; i < n; i++) cin >> c[i]; f[0][0] = ny[1] = ny[0] = 1; for (int i = 0; i <= n; i++) { C[i][0] = 1; for (int j = 1; j <= i; j++) C[i][j] = (C[i &mdash; 1][j] + C[i &mdash; 1][j &mdash; 1]) % mod; } for (int i = 2; i <= n; i++) ny[i] = 1ll * ny[mod % i] * (mod &mdash; mod / i) % mod; for (int i = 2; i <= n; i++) ny[i] = 1ll * ny[i &mdash; 1] * ny[i] % mod; for (int i = 0; i < n; i++) { for (int j = i; j >= 0; j--) { for (int k = i; k >= 0; k--) { if (!f[j][k]) continue; // cout << i << ' ' << j << ' ' << k << ' ' << f[j][k] << '\n'; upd(u[i][k], 1ll * f[j][k] * a[j + 1] % mod); upd(v[i][k], 1ll * f[j][k] * b[j + 1] % mod); upd(f[j + 1][k + (i != 0)], f[j][k]); upd(f[j][k + 1], 1ll * f[j][k] * (i &mdash; (i != 0) &mdash; k) % mod); f[j][k] = 1ll * f[j][k] * (k + (i != 0)) % mod; } } if (i > 0) reverse(v[i], v[i] + i); } for (int x = 1; x <= n; x++) { for (int i = 0; i < n; i++) { g[i] = h[i] = 0; for (int j = i; j >= 0; j--) { g[i] = (1ll * g[i] * x + u[i][j]) % mod; h[i] = (1ll * h[i] * x + v[i][j]) % mod; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { upd(t[i][x], 1ll * g[j &mdash; 1] * h[i &mdash; j] % mod * C[i &mdash; 1][j &mdash; 1] % mod * (j > 1 ? x : 1) % mod); } } } p[0][0] = 1; for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) p[i][j] = p[0][j], o[j] = 0; for (int j = 0; j <= i; j++) { if (j != i) { for (int k = i &mdash; 1; k >= 0; k--) { upd(p[j][k + 1], p[j][k]); p[j][k] = 1ll * p[j][k] * (mod &mdash; i) % mod; } } if (!j) continue; int s = 1ll * t[i][j] * ny[j &mdash; 1] % mod * ny[i &mdash; j] % mod; if ((i &mdash; j) & 1) s = mod &mdash; s; for (int k = 0; k < i; k++) { upd(o[k], 1ll * s * p[j][k] % mod); } } int ans = 0; for (int k = 0; k < i; k++) { ans = (ans + 1ll * o[k] * c[k]) % mod; } cout << ans << ' '; } }
1989
A
Catch the Coin
Monocarp visited a retro arcade club with arcade cabinets. There got curious about the "Catch the Coin" cabinet. The game is pretty simple. The screen represents a coordinate grid such that: - the X-axis is directed from left to right; - the Y-axis is directed from bottom to top; - the center of the screen has coordinates $(0, 0)$. At the beginning of the game, the character is located in the center, and $n$ coins appear on the screen — the $i$-th coin is at coordinates $(x_i, y_i)$. The coordinates of all coins are different and not equal to $(0, 0)$. In one second, Monocarp can move the character in one of eight directions. If the character is at coordinates $(x, y)$, then it can end up at any of the coordinates $(x, y + 1)$, $(x + 1, y + 1)$, $(x + 1, y)$, $(x + 1, y - 1)$, $(x, y - 1)$, $(x - 1, y - 1)$, $(x - 1, y)$, $(x - 1, y + 1)$. If the character ends up at the coordinates with a coin, then Monocarp collects that coin. After Monocarp makes a move, all coins fall down by $1$, that is, they move from $(x, y)$ to $(x, y - 1)$. You can assume that the game field is infinite in all directions. Monocarp wants to collect at least one coin, but cannot decide which coin to go for. Help him determine, for each coin, whether he can collect it.
At first glance, it's not very convenient that the move consists of two parts: first the character moves, then the coin. Let's try to combine these steps. Since the coin moves down by $1$ each time, we can add this change in the $y$ coordinate to the change in the character's $y$ coordinate. That is, the character can now change its $y$ coordinate not by $-1, 0$, or $1$, but by $0, 1$, or $2$. And the coins will always be in their initial positions. Now it is easy to see that all coins with $y \ge 0$ can be picked up. For example, you can first align with the coin in terms of the $x$ coordinate, and then move up to it. However, in the example, it can be seen that Monocarp can pick up the coin $(-2, -1)$. This happens because the move still consists of two parts. Since the character moves first, and then the coin, we can align with the $x$ coordinate again, and then have the time to move down to it. Thus, all coins with $y \ge -1$ can be picked up. Overall complexity: $O(n)$.
[ "implementation" ]
800
for _ in range(int(input())): x, y = map(int, input().split()) print("YES" if y >= -1 else "NO")
1989
B
Substring and Subsequence
You are given two strings $a$ and $b$, both consisting of lowercase Latin letters. A subsequence of a string is a string which can be obtained by removing several (possibly zero) characters from the original string. A substring of a string is a contiguous subsequence of that string. For example, consider the string abac: - a, b, c, ab, aa, ac, ba, bc, aba, abc, aac, bac and abac are its subsequences; - a, b, c, ab, ba, ac, aba, bac and abac are its substrings. Your task is to calculate the minimum possible length of the string that contains $a$ as a substring and $b$ as a subsequence.
Since the string $a$ is a substring of the answer, the answer can be represented as follows - $x + a + y$, where + denotes string concatenation, and $x$ and $y$ are some, possibly empty, strings. Now, we have to ensure that the string $x+a+y$ contains the string $b$ as a subsequence. Notice that to minimize the length of the answer, it is optimal to choose the strings $x$ and $y$ in such a way that $x$ is a prefix of $b$, and $y$ is a suffix of $b$. This means that we can represent the string $b$ as $x+c+y$. Then, in order for the entire string $x+c+y$ to be a subsequence of the answer $x+a+y$, the string $c$ must be a subsequence of the string $a$. Using the above facts, we can solve the problem as follows: iterate over the length of $x$, iterate over the length of $y$, and then check that the remaining part $c$ is a subsequence of the string $a$. If this is the case, update the answer with the value $|x| + |a| + |y|$. Unfortunately, this solution is too slow, but it can be easily optimized. Since we need to minimize the length of the answer, it is sufficient to iterate over the length of $x$, and consequently the position of the start of the string $c$, and then find the minimum possible length of $y$. To do this, greedily find how many of the following characters in the string $b$ will be a subsequence of the string $a$: we can go through the string $a$ from left to right, and if the current character of the string $a$ matches the next character in the string $b$ that we need, increase the number of found characters in the string $b$ by $1$. All the remaining characters in the string $b$ will form the string $y$.
[ "brute force", "greedy", "strings" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string a, b; cin >> a >> b; int n = a.size(), m = b.size(); int ans = n + m; for (int i = 0; i < m; ++i) { int j = i; for (auto c : a) { if (j < m && c == b[j]) ++j; } ans = min(ans, n + m - (j - i)); } cout << ans << '\n'; } }
1989
C
Two Movies
A movie company has released $2$ movies. These $2$ movies were watched by $n$ people. For each person, we know their attitude towards the first movie (liked it, neutral, or disliked it) and towards the second movie. If a person is asked to leave a review for the movie, then: - if that person liked the movie, they will leave a positive review, and the movie's rating will increase by $1$; - if that person disliked the movie, they will leave a negative review, and the movie's rating will decrease by $1$; - otherwise, they will leave a neutral review, and the movie's rating will not change. Every person will review exactly one movie — and for every person, you can choose which movie they will review. The company's rating is the minimum of the ratings of the two movies. Your task is to calculate the maximum possible rating of the company.
Let's notice an important fact: if $a_i \ne b_i$, it is always optimal to choose a review for the movie with the better rating: taking the worse option doesn't increase the rating of any movie. Using this fact, let's calculate several values: $x$ - the rating of the first movie among people who liked the first movie more than the second one ($a_i > b_i$); $y$ - the rating of the second movie among people who liked the second movie more than the first one ($b_i > a_i$); $neg$ - the number of people who didn't like either movie; $pos$ - the number of people who liked both movies. Now we have to distribute the reviews of the viewers having $a_i=b_i$. To do this, we can iterate the contribution of such viewers to the rating of the first movie (denoted as $i$) from $-neg$ to $pos$. Then, the final rating of the first movie is $x+i$, and the final rating of the second movie is $y+(pos-neg-i)$. Among all the options, choose the one where the minimum of these two values is maximized.
[ "greedy", "math" ]
1,400
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n), b(n); for (auto& x : a) cin >> x; for (auto& x : b) cin >> x; int x = 0, y = 0, neg = 0, pos = 0; for (int i = 0; i < n; ++i) { if (a[i] > b[i]) { x += a[i]; } else if (a[i] < b[i]) { y += b[i]; } else { neg += (a[i] < 0); pos += (a[i] > 0); } } int ans = -1e9; for (int i = -neg; i <= pos; ++i) ans = max(ans, min(x + i, y + (pos - neg - i))); cout << ans << '\n'; } }
1989
D
Smithing Skill
You are playing a famous computer game (that just works) where you have various skills you can level up. Today, you focused on the "Smithing" skill. Your tactic is obvious: forging weapons from ingots and then melting them back to return the materials partially. For simplicity, every time you create an item, you get $1$ experience point, and every time you melt an item, you also get $1$ experience point. There are $n$ classes of weapons you can forge and $m$ types of metal ingots. You can create one weapon of the $i$-th class, spending $a_i$ ingots of metal of the same type. Melting a weapon of the $i$-th class (which you crafted earlier) returns you $b_i$ ingots of the type of metal it was made of. You have $c_j$ metal ingots of the $j$-th type, and you know that you can craft a weapon of any class from any metal type. Each combination of a weapon class and a metal type can be used any number of times. What is the maximum total amount of experience you can earn by crafting and melting weapons?
It's quite obvious that we should melt every weapon we forge, and we can do it as soon as we forge it. So, let's do these actions in pairs: forge a weapon, then instantly melt it. Since you can't use two types of metal while forging one weapon, we can solve our task independently for each metal type. Suppose you have $x$ ingots of the chosen metal. You can act greedily: you can forge only weapons of classes with $a_i \le x$, but among them, it's optimal to chose one that makes us lose the minimum number of ingots by forging it and melting it; so, we need to minimize the value of $a_i - b_i$. However, this greedy solution is too slow when implemented naively. Let's define $A = \max{a_i}$ and look at two cases: $x \le A$ or $x > A$. If $x \le A$, let's just precalculate answers $\mathrm{ans}[x]$ for all $x$ from $0$ to $A$. To do so, let's precalculate another value $\mathrm{best}[x]$ as "the minimum $a_i - b_i$ among all classes $i$ where $a_i \le x$". In other words, $\mathrm{best}[x]$ will be equal to the minimum amount of ingots you'll lose if you have $x$ ingots, and you need to forge-melt one weapon. We can precalculate $\mathrm{best}[x]$ in two steps: for each class $i$, we can set $\mathrm{best}[a_i] = \min{(\mathrm{best}[a_i], a_i - b_i)}$; using approach similar to prefix minima or dynamic programming, we can also update $\mathrm{best}[x] = \min{(\mathrm{best}[x], \mathrm{best}[x - 1])}$ for all $x$ from $1$ to $A$. In case $x > A$, we can forge-melt a weapon with minimum $a_i - b_i$ as many times as we can until $x \le A$. Once $x$ becomes less or equal to $A$, we can take the value $\mathrm{ans}[x]$ and finish processing that metal type. Knowing that the minimum $a_i - b_i$ is just $\mathrm{best}[A]$, we can reformulate our first step as finding minimum $k$ such that $x - k \cdot \mathrm{best}[A] \le A$ or $k \ge \frac{x - A}{\mathrm{best}[A]}$. In other words, we'll make the first step exactly $k = \left\lceil \frac{x - A}{\mathrm{best}[A]} \right\rceil$ times. So we can calculate the final answer as $2k + \mathrm{ans}[x - k \cdot \mathrm{best}[A]]$. As a result, we run precalculating in $O(n + A)$ time and process each metal type in $O(1)$ time. The total complexity is $O(n + m + A)$ time and space.
[ "brute force", "data structures", "dp", "greedy", "math", "sortings", "two pointers" ]
1,900
fun main() { val (n, m) = readln().split(" ").map { it.toInt() } val a = readln().split(" ").map { it.toInt() } val b = readln().split(" ").map { it.toInt() } val c = readln().split(" ").map { it.toInt() } val mx = a.maxOrNull()!! + 1 val best = IntArray(mx) { 1e9.toInt() } val calc = IntArray(mx) { 0 } for (i in a.indices) best[a[i]] = minOf(best[a[i]], a[i] - b[i]) for (v in 1 until mx) best[v] = minOf(best[v], best[v - 1]) for (v in 1 until mx) if (v >= best[v]) calc[v] = 2 + calc[v - best[v]] var ans = 0L for (v in c) { var cur = v if (cur >= mx) { val k = (cur - mx + 1 + best[mx - 1]) / best[mx - 1] ans += 2L * k cur -= k * best[mx - 1] } ans += calc[cur] } println(ans) }
1989
E
Distance to Different
Consider an array $a$ of $n$ integers, where every element is from $1$ to $k$, and every integer from $1$ to $k$ appears \textbf{at least once}. Let the array $b$ be constructed as follows: for the $i$-th element of $a$, $b_i$ is the distance to the closest element in $a$ which is not equal to $a_i$. In other words, $b_i = \min \limits_{j \in [1, n], a_j \ne a_i} |i - j|$. For example, if $a = [1, 1, 2, 3, 3, 3, 3, 1]$, then $b = [2, 1, 1, 1, 2, 2, 1, 1]$. Calculate the number of different arrays $b$ you can obtain if you consider all possible arrays $a$, and print it modulo $998244353$.
Consider a block of equal elements in $a$. If we split $a$ into such blocks, we can consider each block separately - for each element, we need only the distance to the closest border of the block (except for the first and the last block, where we consider only one border). It's quite easy to see that if the length of the block is even (let's say it's $2x$), then the distances for the elements in this block are $[1, 2, 3, \dots, x-1, x, x, x-1, \dots, 3, 2, 1]$. And if the length of the block is odd (let's say it's $2x-1$), the distances are $[1, 2, 3, \dots, x-1, x, x-1, \dots, 3, 2, 1]$. Now we don't need the actual values in $a$, we only need the information about the blocks of equal elements. We need at least $k$ blocks of equal elements in $a$, since if the number of blocks is less than $k$, it's impossible for the array $a$ to have $k$ different values (and if there are at least $k$ blocks, it's possible to assign each block a value so that every integer from $1$ to $k$ appears). So, it looks like we need to calculate the number of ways to split the array into at least $k$ blocks. However, this only works if there is a bijection between the ways to split the array and the resulting arrays $b$. Unfortunately, some ways to split the array might result in the same distance array: for example, the distance array $[1, 1, 1, 1]$ can be obtained either by splitting into four blocks of size $1$, or into three blocks, the middle of which has size $2$. So, if there is a block of size $2$, and it is not the first or the last block in the split, it can be replaced with two blocks of size $1$, and nothing changes (except for the number of blocks, which goes up). Thankfully, this is the only such situation we need to handle: any block longer than $2$ can be uniquely determined by the values in the middle of it (if there is a value $x$ which is greater than both its neighbors, it is the middle of a block of size $2x-1$; and if there is a pair of values $x$ which are greater than both the value to the left and the value to the right, it is the middle of a block of size $2x$). So, we need to count the number of ways to split the array of size $n$ into at least $k$ blocks so that only the first and the last block can have size $2$. This can be done with the following dynamic programming: let $dp_{i,j}$ be the number of ways to split the first $i$ elements into $j$ blocks. This looks like it works in $O(n^3)$, but we can use two improvements to speed this up: the values $j > k$ are treated identically to the values $j=k$, so we can limit the value of $j$ to $k$ and say that $dp_{i,j}$ is the number of ways to split the first $i$ elements into at least $j$ blocks if $j=k$; we can do transitions in $O(1)$ instead of $O(n)$ by using partial sums. Combining these two optimizations, we get a solution in $O(nk)$.
[ "combinatorics", "dp", "math" ]
2,300
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int main() { int n; cin >> n; int k; cin >> k; vector<vector<int>> dp(n + 1, vector<int>(k + 1)); dp[0][0] = 1; vector<int> sum(k + 1); sum[0] = 1; for(int i = 0; i < n; i++) { for(int j = 0; j <= k; j++) { int& d = dp[i + 1][min(j + 1, k)]; d = add(d, sum[j]); if(i >= 2 && i != n - 1) d = add(d, -dp[i - 1][j]); } for(int j = 0; j <= k; j++) sum[j] = add(sum[j], dp[i + 1][j]); } cout << dp[n][k] << endl; }
1989
F
Simultaneous Coloring
You are given a matrix, consisting of $n$ rows and $m$ columns. You can perform two types of actions on it: - paint the entire column in blue; - paint the entire row in red. \textbf{Note that you cannot choose which color to paint the row or column.} In one second, you can perform either one action or multiple actions at the same time. If you perform one action, it will be free. If you perform $k > 1$ actions at the same time, it will cost $k^2$ coins. When multiple actions are performed at the same time, for each cell affected by actions of both types, the color can be chosen independently. You are asked to process $q$ queries. Before each query, all cells become colorless. Initially, there are no restrictions on the color of any cells. In the $i$-th query, a restriction of the following form is added: - $x_i~y_i~c_i$ — the cell in row $x_i$ in column $y_i$ should be painted in color $c_i$. Thus, after $i$ queries, there are $i$ restrictions on the required colors of the matrix cells. After each query, output the minimum cost of painting the matrix according to the restrictions.
The main idea is as follows. Consider any constraint on a cell. If the cell must be red, then the last action on this cell must be coloring the row; otherwise, it should be the column. That is, if the operation is applied to both the row and the column of this cell, then there is a certain order of performing these operations. It is also worth noting that it does not make sense to apply the same operation twice, because the second application of the operation will recolor all the cells. The word "order" should immediately bring to mind thoughts of directed graphs and topological sorting. Let's try to build a graph of operation execution. Create a graph with $n + m$ vertices - one vertex for each row and column. If the cell must be red, then draw a directed edge from its column to its row. Otherwise, draw an edge from its row to its column. Now we would like to perform operations simply in the order of topological sorting. If this is possible (i.e., there are no cycles in the graph), then the answer is just $0$. This means that operations can always be applied one by one. It is also worth noting that we apply the operations that do not color any cells with constraints. Their cost is always $0$, so they do not change the answer. Otherwise, there are some strongly connected components in the graph with size greater than $1$. In these components, we will always have to perform some operations at the same time. Of course, operations can be applied to the entire component at once. The cost will then be equal to the square of the component's size. Doesn't sound optimal but that's one way to satisfy the constraints. Let's show that it is not possible to do it cheaper. Consider the last set of actions on this component. If they do not affect the entire component, then within the affected subset, there will be a vertex with an outgoing edge outside the subset, but inside the component (otherwise it would be two different components). This means that there must be at least one more operation performed on the vertex to which this edge leads. Therefore, the set of actions considered will not be the last one. Then the solution is as follows. After adding each constraint, add the previously described edges and find the condensation of the graph. The answer will be the sum of the squares of the sizes of strongly connected components with size greater than $1$. This solution works in $O(q \cdot (n + m + q))$. To optimize this solution, you can use the technique of incremental condensation. You can read about it in the blog by Radewoosh. Since DSU is used in it, you can maintain the sum of the squares of the component sizes on the fly. The blog describes a solution with a logarithmic time complexity, but the problem did not require an implementation faster than $log^2$. Solutions with a logarithmic memory complexity with a large constant might not pass (the author's solution consumes $O(q \log q)$ memory and fits into $50$ megabytes).
[ "dfs and similar", "divide and conquer", "graphs" ]
3,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct edge{ int v, u; }; vector<vector<int>> g, tg; vector<int> ord; vector<char> used; vector<int> clr; void ts(int v){ used[v] = true; for (int u : g[v]) if (!used[u]) ts(u); ord.push_back(v); } void dfs(int v, int k){ clr[v] = k; for (int u : tg[v]) if (clr[u] == -1) dfs(u, k); } vector<long long> rk, p; long long sum; vector<long long*> where; vector<long long> val; long long cost(int x){ return x == 1 ? 0ll : x * 1ll * x; } int getp(int a){ return a == p[a] ? a : getp(p[a]); } void unite(int a, int b){ a = getp(a), b = getp(b); if (a == b) return; if (clr[a] != clr[b]) return; if (rk[a] < rk[b]) swap(a, b); where.push_back(&sum); val.push_back(sum); sum -= cost(rk[a]); sum -= cost(rk[b]); sum += cost(rk[a] + rk[b]); where.push_back(&rk[a]); val.push_back(rk[a]); rk[a] += rk[b]; where.push_back(&p[b]); val.push_back(p[b]); p[b] = a; } vector<edge> e; vector<long long> ans; void calc(int l, int r, const vector<int> &cur){ if (l == r - 1){ ans.push_back(sum); return; } int m = (l + r) / 2; for (int i : cur) if (i < m){ int v = getp(e[i].v), u = getp(e[i].u); for (int w : {v, u}) if (used[w]){ g[w].clear(); tg[w].clear(); clr[w] = -1; used[w] = false; } g[v].push_back(u); tg[u].push_back(v); } ord.clear(); for (int i : cur) if (i < m){ for (int v : {getp(e[i].v), getp(e[i].u)}) if (!used[v]){ ts(v); } } reverse(ord.begin(), ord.end()); int k = 0; for (int v : ord) if (clr[v] == -1){ dfs(v, k); ++k; } int tim = val.size(); for (int i : cur) if (i < m) unite(e[i].v, e[i].u); vector<int> tol, tor; for (int i : cur){ if (i >= m) tor.push_back(i); else if (getp(e[i].v) == getp(e[i].u)) tol.push_back(i); else tor.push_back(i); } calc(m, r, tor); while (int(val.size()) > tim){ *where.back() = val.back(); where.pop_back(); val.pop_back(); } calc(l, m, tol); } int main() { cin.tie(0); ios::sync_with_stdio(false); int n, m, q; cin >> n >> m >> q; e.resize(q); forn(i, q){ int x, y; char c; cin >> x >> y >> c; --x, --y; if (c == 'R') e[i] = {y + n, x}; else e[i] = {x, y + n}; } rk.resize(n + m, 1); p.resize(n + m); iota(p.begin(), p.end(), 0); used.resize(n + m, 0); clr.resize(n + m, -1); g.resize(n + m); tg.resize(n + m); vector<int> cur(q); iota(cur.begin(), cur.end(), 0); calc(0, q + 1, cur); ans.pop_back(); reverse(ans.begin(), ans.end()); for (long long x : ans) cout << x << '\n'; return 0; }
1990
A
Submission Bait
Alice and Bob are playing a game in an array $a$ of size $n$. They take turns to do operations, with Alice starting first. The player who can not operate will lose. At first, a variable $mx$ is set to $0$. In one operation, a player can do: - Choose an index $i$ ($1 \le i \le n$) such that $a_{i} \geq mx$ and set $mx$ to $a_{i}$. Then, set $a_{i}$ to $0$. Determine whether Alice has a winning strategy.
For Alice, what if choosing the maximum value doesn't work? Consider parity. Case $1$: When all values appear an even number of times, Alice will lose. This is because no matter which number Alice chooses, Bob can mimic Alice's move. Case $2$: When at least one value appears an odd number of times, Alice will win. Alice only needs to choose the maximum value that appears an odd number of times, which will force Bob into Case $1$. Time complexity: $O(n)$. Sort the array $a$ in non-increasing order. We can observe that any state can be represented as a prefix of the array $a$. Consider dynamic programming: let $dp_i$ denote whether the first player is guaranteed to win when the state is $a_{1...i}$ ($dp_i=1$ indicates a guaranteed win for the first player). We have the following formula: $dp_1=1$; $dp_1=1$; $dp_i= \sim (dp_{i-1}$ & $dp_{id_1-1}$ & $dp_{id_2-1} \ldots)$, where $id_j$ satisfies $a_{id_j} \neq a_{id_j+1}$ and $id_j < i$. $dp_i= \sim (dp_{i-1}$ & $dp_{id_1-1}$ & $dp_{id_2-1} \ldots)$, where $id_j$ satisfies $a_{id_j} \neq a_{id_j+1}$ and $id_j < i$. Time complexity: $O(n^2)$.
[ "brute force", "games", "greedy", "sortings" ]
900
#include <bits/stdc++.h> using namespace std; #define m_p make_pair #define all(x) (x).begin(),(x).end() #define sz(x) ((int)(x).size()) #define fi first #define se second typedef long long ll; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); mt19937 rnf(2106); const int N = 55; int n; int q[N]; void solv() { cin >> n; for (int i = 1; i <= n; ++i) q[i] = 0; for (int i = 1; i <= n; ++i) { int x; cin >> x; ++q[x]; } for (int i = 1; i <= n; ++i) { if (q[i] % 2 == 1) { cout << "YES\n"; return; } } cout << "NO\n"; } int main() { #ifdef SOMETHING freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif // SOMETHING ios_base::sync_with_stdio(false), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solv(); } return 0; }
1990
B
Array Craft
For an array $b$ of size $m$, we define: - the \textbf{maximum prefix position} of $b$ is the \textbf{smallest} index $i$ that satisfies $b_1+\ldots+b_i=\max_{j=1}^{m}(b_1+\ldots+b_j)$; - the \textbf{maximum suffix position} of $b$ is the \textbf{largest} index $i$ that satisfies $b_i+\ldots+b_m=\max_{j=1}^{m}(b_j+\ldots+b_m)$. You are given three integers $n$, $x$, and $y$ ($x > y$). Construct an array $a$ of size $n$ satisfying: - $a_i$ is either $1$ or $-1$ for all $1 \le i \le n$; - the \textbf{maximum prefix position} of $a$ is $x$; - the \textbf{maximum suffix position} of $a$ is $y$. If there are multiple arrays that meet the conditions, print any. It can be proven that such an array always exists under the given conditions.
Starting from a trival construction. Utilize the condition $x > y$. First, we consider making $presum_x > presum_j$ for all $x < i \le n$, and similarly for $y$. We can think of a trivial construction: $a[r, \ldots ,l]=[1, \ldots ,1], a[1, \ldots...,r-1]=[-1, \ldots, -1]$ and $a[l+1,\ldots,n]=[-1, \ldots, -1]$. The construction doesn't works when $presum_x<0$, but we are close to the correct solution. Next, we will make a little adjustment: $a[r, \ldots, l]=[1,\ldots,1], a[1, \ldots...,r-1]=[\ldots,1, -1]$ and $a[l+1,\ldots,n]=[-1,1, \ldots]$. It is not hard to see $presum_x \ge presum_j$ for all $x < i \le n$, and for $1 \le i \le y$, $\max(presum_i)-min(presum_i)\le 1$. Thus, we get $presum_x \ge 2+presum_{y-1} \ge 2+min(presum_i) \ge 1+max(presum_i)$. The same applies to the suffix sum as well. Therefore, this construction is valid. Time complexity: $O(n)$. Solve the problem when $x \le y$.
[ "constructive algorithms", "greedy" ]
1,200
#include<bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t>0){ t--; int n,x,y; cin >> n >> x >> y; x--; y--; vector<int> a(n,1); int e; e=-1; for(int i=x+1;i<n;i++){ a[i]=e; e*=-1; } e=-1; for(int i=y-1;i>=0;i--){ a[i]=e; e*=-1; } for(int i=0;i<n;i++){ if(i){cout << " ";} cout << a[i]; }cout << "\n"; } return 0; }
1990
C
Mad MAD Sum
We define the $\operatorname{MAD}$ (Maximum Appearing Duplicate) in an array as the largest number that appears at least twice in the array. Specifically, if there is no number that appears at least twice, the $\operatorname{MAD}$ value is $0$. For example, $\operatorname{MAD}([1, 2, 1]) = 1$, $\operatorname{MAD}([2, 2, 3, 3]) = 3$, $\operatorname{MAD}([1, 2, 3, 4]) = 0$. You are given an array $a$ of size $n$. Initially, a variable $sum$ is set to $0$. The following process will be executed in a sequential loop until all numbers in $a$ become $0$: - Set $sum := sum + \sum_{i=1}^{n} a_i$; - Let $b$ be an array of size $n$. Set $b_i :=\ \operatorname{MAD}([a_1, a_2, \ldots, a_i])$ for all $1 \le i \le n$, and then set $a_i := b_i$ for all $1 \le i \le n$. Find the value of $sum$ after the process.
After one operation, the array becomes non-decreasing. Consider $a_1=a_2=\ldots=a_n$, the operation seems to have shifted the array right. When does the "right shift" parttern happen? Read hints first. Let's consider only non-decreasing arrays. Observe a continuous segments $a[l...r]=x(l<r,x>0)$, after one operation, we get $a[l+1,min(r+1,n)]=x$ holds. We can conclude that if, for all non-zero contiguous segments in the array (except the last one), their lengths are all greater than $1$, then the array follows the "right shift" parttern. Let's say this kind of array "good". The last problem is when will the array become "good". Let's assume we get the array $b$ after one operation on array $a$, we get $b_i<b_{i+1}<b_{i+2}$. We can infer that $b_i=a_i,b_{i+1}=a_{i+1}$ and there is at least $a_j=a_{i+1}(j \le i)$, which shows that $a$ is not non-decreasing. In other words, after two operations, we can always get a "good" array. Then the calculating is trival. Time complexity: $O(n)$. The title "Mad MAD Sum" is not only a pun on the words Mad and MAD (Maximum Appearing Duplicate), but also implies the solution to the problem :)
[ "brute force", "greedy", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; #define m_p make_pair #define all(x) (x).begin(),(x).end() #define sz(x) ((int)(x).size()) #define fi first #define se second typedef long long ll; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); mt19937 rnf(2106); const int N = 200005; int n; int a[N]; bool c[N]; void doit() { for (int i = 1; i <= n; ++i) c[i] = false; int maxu = 0; for (int i = 1; i <= n; ++i) { if (c[a[i]]) maxu = max(maxu, a[i]); c[a[i]] = true; a[i] = maxu; } } void solv() { cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i]; ll ans = 0; for (int i = 1; i <= n; ++i) ans += a[i]; doit(); for (int i = 1; i <= n; ++i) ans += a[i]; doit(); for (int i = 1; i <= n; ++i) ans += (n - i + 1) * 1LL * a[i]; cout << ans << "\n"; } int main() { #ifdef SOMETHING freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif // SOMETHING ios_base::sync_with_stdio(false), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solv(); } return 0; }
1990
D
Grid Puzzle
You are given an array $a$ of size $n$. There is an $n \times n$ grid. In the $i$-th row, the first $a_i$ cells are black and the other cells are white. In other words, note $(i,j)$ as the cell in the $i$-th row and $j$-th column, cells $(i,1), (i,2), \ldots, (i,a_i)$ are black, and cells $(i,a_i+1), \ldots, (i,n)$ are white. You can do the following operations any number of times in any order: - Dye a $2 \times 2$ subgrid white; - Dye a whole row white. Note you can \textbf{not} dye a whole column white. Find the minimum number of operations to dye all cells white.
Obviously, when $a_i$ is large enough, we will definitely use operation $2$ on the $i$-th row. What is its specific value? It is $5$(try to prove it). Now we can only consider $a_i \le 4$ cases. From left to right, consider a greedy solution or a DP solution. Read hints first. For $a_i \ge 5$, we will definitely use operation $2$ on the $i$-th row because at least three $2 \times 2$ subgrid are needed to cover it, which is not better then do three times operation $2$ in the $i-1,i$ and $i+1$ row. Now we can only consider $a_i \le 4$ cases. Let's consider from left to right. In the left most row, there are $3$ cases: there is no black cells Do nothing; there is no black cells Do nothing; there is $\le 2$ black cells. We can put one $2 \times 2$ subgrid greedily; there is $\le 2$ black cells. We can put one $2 \times 2$ subgrid greedily; there is $> 2$ black cells. We just use one time operation $2$ in this row(try to prove it). there is $> 2$ black cells. We just use one time operation $2$ in this row(try to prove it). We can summarize that for the $i$-th row, there are only three situations where it is affected by the $i-1$-th row: it is not affected; it is not affected; the cells in the third and fourth columns have been colored white; the cells in the third and fourth columns have been colored white; the cells in the first and second columns have been colored white. the cells in the first and second columns have been colored white. We can greedily process this process from left to right, or use DP. Time complexity: $O(n)$.
[ "bitmasks", "brute force", "dp", "greedy", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; #define m_p make_pair #define all(x) (x).begin(),(x).end() #define sz(x) ((int)(x).size()) #define fi first #define se second typedef long long ll; mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count()); mt19937 rnf(2106); const int N = 200005; int n; int a[N]; int dp[N]; void minh(int& x, int y) { x = min(x, y); } void solv() { cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i]; int minu[2] = {N, N}; for (int i = 1; i <= n; ++i) { dp[i] = dp[i - 1] + 1; if (a[i] == 0) minh(dp[i], dp[i - 1]); if (a[i] <= 2) minh(dp[i], i + minu[1 - i % 2]); if (a[i] <= 2) minh(minu[i % 2], dp[i - 1] - i); else if (a[i] > 4) minu[0] = minu[1] = N; } cout << dp[n] << "\n"; } int main() { #ifdef SOMETHING freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); #endif // SOMETHING ios_base::sync_with_stdio(false), cin.tie(0); int tt = 1; cin >> tt; while (tt--) { solv(); } return 0; }
1990
E2
Catch the Mole(Hard Version)
\textbf{This is the hard version of the problem. The only difference is the limit on the number of queries.} \textbf{This is an interactive problem.} You are given a tree of $n$ nodes with node $1$ as its root node. There is a hidden mole in one of the nodes. To find its position, you can pick an integer $x$ ($1 \le x \le n$) to make an inquiry to the jury. Next, the jury will return $1$ when the mole is in subtree $x$. Otherwise, the judge will return $0$. If the judge returns $0$ and the mole is not in root node $1$, the mole will move to the parent node of the node it is currently on. Use at most $160$ operations to find the \textbf{current} node where the mole is located.
Consider querying a subtree. If the jury returns $0$, we can delete the entire subtree. We can query any leaf node. If the jury returns $1$, we are done; otherwise, the mole will move up. Consider querying a subtree. If the jury returns $1$, we can "drive" it out of this subtree using the method in hint2. Combime the idea in hint $1$ and $3$. Read hints first. For easy version, we can pick a vertex $v$ such that $maxdep_v-dep_v+1=50$: if the jury returns $0$, we can delete the entire subtree; if the jury returns $0$, we can delete the entire subtree; otherwise, make queries until it is out and answer $fa_v$(a special case is $v=1$); otherwise, make queries until it is out and answer $fa_v$(a special case is $v=1$); if there is no such vertex, then make $100$ queries and answer the root node $1$. This costs about $200$ queries, which can not pass hard version. But we can optimize it. The bottleneck is the step $2$, when we drive away this mole once, we need to immediately check if it is still in the subtree $v$, which can be optimized. In fact, we can drive the mole 50 times and then perform a binary search on the chain from $v$ to the root node. Number of queries: $O(2sqrt(n)+log(n))$ Query any leaf $70$ times, then delete all nodes $x$ such that $maxdep_v-dep_v+1<=70$. Then the tree can be split into $\le 70$ chains. Do binary search for these chains. Solve the problem in $100$ queries.
[ "binary search", "data structures", "dfs and similar", "divide and conquer", "interactive", "trees" ]
2,600
#include<bits/stdc++.h> using namespace std; #define all(a) a.begin(),a.end() #define pb push_back #define sz(a) ((int)a.size()) using ll=long long; using u32=unsigned int; using u64=unsigned long long; using i128=__int128; using u128=unsigned __int128; using f128=__float128; using pii=pair<int,int>; using pll=pair<ll,ll>; template<typename T> using vc=vector<T>; template<typename T> using vvc=vc<vc<T>>; template<typename T> using vvvc=vc<vvc<T>>; using vi=vc<int>; using vll=vc<ll>; using vvi=vc<vi>; using vvll=vc<vll>; #define vv(type,name,n,...) \ vector<vector<type>> name(n,vector<type>(__VA_ARGS__)) #define vvv(type,name,n,m,...) \ vector<vector<vector<type>>> name(n,vector<vector<type>>(m,vector<type>(__VA_ARGS__))) template<typename T> using min_heap=priority_queue<T,vector<T>,greater<T>>; template<typename T> using max_heap=priority_queue<T>; // https://trap.jp/post/1224/ #define rep1(n) for(ll i=0; i<(ll)(n); ++i) #define rep2(i,n) for(ll i=0; i<(ll)(n); ++i) #define rep3(i,a,b) for(ll i=(ll)(a); i<(ll)(b); ++i) #define rep4(i,a,b,c) for(ll i=(ll)(a); i<(ll)(b); i+=(c)) #define cut4(a,b,c,d,e,...) e #define rep(...) cut4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__) #define per1(n) for(ll i=((ll)n)-1; i>=0; --i) #define per2(i,n) for(ll i=((ll)n)-1; i>=0; --i) #define per3(i,a,b) for(ll i=((ll)a)-1; i>=(ll)(b); --i) #define per4(i,a,b,c) for(ll i=((ll)a)-1; i>=(ll)(b); i-=(c)) #define per(...) cut4(__VA_ARGS__,per4,per3,per2,per1)(__VA_ARGS__) #define rep_subset(i,s) for(ll i=(s); i>=0; i=(i==0?-1:(i-1)&(s))) template<typename T, typename S> constexpr T ifloor(const T a, const S b){return a/b-(a%b&&(a^b)<0);} template<typename T, typename S> constexpr T iceil(const T a, const S b){return ifloor(a+b-1,b);} template<typename T> void sort_unique(vector<T> &vec){ sort(vec.begin(),vec.end()); vec.resize(unique(vec.begin(),vec.end())-vec.begin()); } template<typename T, typename S> constexpr bool chmin(T &a, const S b){if(a>b) return a=b,true; return false;} template<typename T, typename S> constexpr bool chmax(T &a, const S b){if(a<b) return a=b,true; return false;} template<typename T, typename S> istream& operator >> (istream& i, pair<T,S> &p){return i >> p.first >> p.second;} template<typename T, typename S> ostream& operator << (ostream& o, const pair<T,S> &p){return o << p.first << ' ' << p.second;} #ifdef i_am_noob #define bug(...) cerr << "#" << __LINE__ << ' ' << #__VA_ARGS__ << "- ", _do(__VA_ARGS__) template<typename T> void _do(vector<T> x){for(auto i: x) cerr << i << ' ';cerr << "\n";} template<typename T> void _do(set<T> x){for(auto i: x) cerr << i << ' ';cerr << "\n";} template<typename T> void _do(unordered_set<T> x){for(auto i: x) cerr << i << ' ';cerr << "\n";} template<typename T> void _do(T && x) {cerr << x << endl;} template<typename T, typename ...S> void _do(T && x, S&&...y) {cerr << x << ", "; _do(y...);} #else #define bug(...) 777771449 #endif template<typename T> void print(vector<T> x){for(auto i: x) cout << i << ' ';cout << "\n";} template<typename T> void print(set<T> x){for(auto i: x) cout << i << ' ';cout << "\n";} template<typename T> void print(unordered_set<T> x){for(auto i: x) cout << i << ' ';cout << "\n";} template<typename T> void print(T && x) {cout << x << "\n";} template<typename T, typename... S> void print(T && x, S&&... y) {cout << x << ' ';print(y...);} template<typename T> istream& operator >> (istream& i, vector<T> &vec){for(auto &x: vec) i >> x; return i;} vvi read_graph(int n, int m, int base=1){ vvi adj(n); for(int i=0,u,v; i<m; ++i){ cin >> u >> v,u-=base,v-=base; adj[u].pb(v),adj[v].pb(u); } return adj; } vvi read_tree(int n, int base=1){return read_graph(n,n-1,base);} template<typename T, typename S> pair<T,S> operator + (const pair<T,S> &a, const pair<T,S> &b){return {a.first+b.first,a.second+b.second};} template<typename T> constexpr T inf=0; template<> constexpr int inf<int> = 0x3f3f3f3f; template<> constexpr ll inf<ll> = 0x3f3f3f3f3f3f3f3f; template<typename T> vector<T> operator += (vector<T> &a, int val){for(auto &i: a) i+=val; return a;} template<typename T> T isqrt(const T &x){T y=sqrt(x+2); while(y*y>x) y--; return y;} #define ykh mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()) //#include<atcoder/all> //using namespace atcoder; //using mint=modint998244353; //using mint=modint1000000007; struct Tree{ int n; vector<vector<int>> adj,anc; vector<int> par,tl,tr,dep,ord,siz,ch,head; Tree(int _n=0){ n=_n; adj.resize(n); } void add_edge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u); } void init(){ par.resize(n),tl.resize(n),tr.resize(n),dep.resize(n),anc.resize(n),siz.resize(n),ch.resize(n),head.resize(n); int cur=-1,m=0; while((1<<m)<=n) m++; for(int i=0; i<n; ++i) anc[i].resize(m),ch[i]=-1; auto dfs1=[&](auto &self, int u, int fa) -> void{ par[u]=fa; siz[u]=1; for(int v: adj[u]) if(v!=fa) self(self,v,u),siz[u]+=siz[v]; for(int v: adj[u]) if(v!=fa&&(ch[u]==-1||siz[v]>siz[ch[u]])) ch[u]=v; }; auto dfs2=[&](auto &self, int u, int fa) -> void{ ord.push_back(u); tl[u]=++cur; anc[u][0]=fa; if(fa==-1) dep[u]=0; else dep[u]=dep[fa]+1; for(int i=1; i<m; ++i){ if(anc[u][i-1]==-1) anc[u][i]=-1; else anc[u][i]=anc[anc[u][i-1]][i-1]; } if(ch[u]!=-1) self(self,ch[u],u); for(int v: adj[u]) if(v!=fa&&v!=ch[u]) self(self,v,u); tr[u]=cur; }; dfs1(dfs1,0,-1); dfs2(dfs2,0,-1); head[0]=0; for(int u: ord){ for(int v: adj[u]) if(v!=par[u]){ if(v==ch[u]) head[v]=head[u]; else head[v]=v; } } } bool is_anc(int u, int v){return tl[u]<=tl[v]&&tr[u]>=tr[v];} int get_anc(int u, int x){ for(int i=anc[0].size()-1; i>=0; --i) if(u!=-1&&(x>>i&1)) u=anc[u][i]; return u; } int lca(int u, int v){ if(is_anc(u,v)) return u; for(int i=anc[0].size()-1; i>=0; --i) if(anc[u][i]!=-1&&!is_anc(anc[u][i],v)) u=anc[u][i]; return par[u]; } }; void ahcorz(){ int lft=150; auto query=[&](int u){ assert(lft>0); cout << "? " << u+1 << endl; lft--; int res; cin >> res; return res; }; int n; cin >> n; Tree tree(n); rep(n-1){ int u,v; cin >> u >> v; u--,v--; tree.add_edge(u,v); } tree.init(); vi vis(n); auto fill_vis=[&](auto &self, int u){ if(vis[u]) return; vis[u]=1; for(int v: tree.adj[u]) if(v!=tree.par[u]) self(self,v); }; vi ord(n); iota(all(ord),0); sort(all(ord),[&](int i, int j){return tree.dep[i]<tree.dep[j];}); per(n){ int u=ord[i]; if(vis[u]) continue; int v=u; rep(_,(lft-1)/2-1){ if(v==0) break; v=tree.par[v]; } if(!query(v)){ fill_vis(fill_vis,v); continue; } int x=tree.ord.back(); int m=tree.dep[u]-tree.dep[v]+1; rep(_,m){ if(query(x)){ cout << "! " << x+1 << endl; return; } if(!query(v)){ int y=tree.par[v]; if(y!=-1) y=tree.par[y]; if(y==-1) y=0; cout << "! " << y+1 << endl; return; } } cout << "! 1" << endl; return; } assert(0); } signed main(){ ios_base::sync_with_stdio(0),cin.tie(0); cout << fixed << setprecision(20); int t=1; cin >> t; while(t--) ahcorz(); }
1990
F
Polygonal Segments
You are given an array $a$ of size $n$. A segment $[l, r](1 \le l < r \le n)$ is called a \textbf{polygonal} segment only if the following conditions hold: - $(r-l+1) \geq 3$; - Considering $a_l, a_{l+1}, \ldots, a_r$ as side lengths, these sides can form a polygon with $(r-l+1)$ sides. Process $q$ queries of two types: - "1 l r": find the length of the longest segment among all \textbf{polygonal} segments $[l_0,r_0]$ satisfying $l \le l_0 \le r_0 \le r$. If there is no such \textbf{polygonal} segment, output $-1$ instead; - "2 i x": assign $a_i := x$.
Consider using a segment tree to solve this problem. We need to merge the information of two intervals. First, we take the maximum value of the answers in the two intervals, and then calculate the polygon segment spanning the two intervals. We notice that a local maximal polygon segment $[l, r]$ must satisfy $min(a_{l-1}, a_{r+1}) >= 2(a_l + ... + a_r)$(or $l=1$,$r=n$). Define the suffix $[i, r]$ of the interval $[l, r]$ as a special suffix if and only if $a_i+ \ldots +a_r$ $\le 2 \cdot a_i$. The same principle applies to special prefixes. We can observe that there are at most $O(log(maxa))$ special suffixes, because the sum of one special suffix is at least twice the sum of the previous special suffix. Therefore, we can merge the special suffixes of the left interval and the special prefixes of the right interval (using the two-pointer algorithm) to obtain the answer spanning the two intervals. Number of queries: $O(nlog^2(n))$ Consider the following process: This looks $O(n^2)$ when $a=[1,2,1,4,1,2,1,8,1,2,1,4,1,2,1,16,... ]$. However, if we store all the ranges which are already calculated, it becomes $O(n log n)$. Why? Let's call a range $[l,r]$ "key range" when $sum(a[l...r])<=2min(a[l-1],a[r+1])$. We can see: 1.There're only $O(n log n)$ different key ranges; 2.We only visit at most $2$ ranges which are not key range in each query. Assume we have changed $a_p$. We need to clear all the answer of key ranges which pass through $p$. We can use interval tree to achieve it.
[ "brute force", "data structures", "divide and conquer", "dp", "greedy", "two pointers" ]
2,800
// #pragma GCC optimize("O3,unroll-loops") // #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt") #include "bits/stdc++.h" using namespace std; using ll = long long int; mt19937_64 RNG(chrono::high_resolution_clock::now().time_since_epoch().count()); /** * Point-update Segment Tree * Source: kactl * Description: Iterative point-update segment tree, ranges are half-open i.e [L, R). * f is any associative function. * Time: O(logn) update/query */ template<class T, T unit = T()> struct SegTree { T f(T a, T b) { a[0] += b[0]; if (a[1] < b[1]) a[1] = b[1], a[2] = b[2]; return a; } vector<T> s; int n; SegTree(int _n = 0, T def = unit) : s(2*_n, def), n(_n) {} void update(int pos, T val) { for (s[pos += n] = val; pos /= 2;) s[pos] = f(s[pos * 2], s[pos * 2 + 1]); } T query(int b, int e) { T ra = unit, rb = unit; for (b += n, e += n; b < e; b /= 2, e /= 2) { if (b % 2) ra = f(ra, s[b++]); if (e % 2) rb = f(s[--e], rb); } return f(ra, rb); } }; #include <ext/pb_ds/assoc_container.hpp> struct splitmix64_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = std::chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; template <typename K, typename V, typename Hash = splitmix64_hash> using hash_map = __gnu_pbds::gp_hash_table<K, V, Hash>; template <typename K, typename Hash = splitmix64_hash> using hash_set = hash_map<K, __gnu_pbds::null_type, Hash>; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n, q; cin >> n >> q; vector<ll> a(n); for (auto &x : a) cin >> x; map<ll, int> cache; struct Node { int L, R, M; // [L, R) set<array<int, 2>> by_l, by_r; void ins(int l, int r) { by_l.insert({l, r}); by_r.insert({r, l}); } void del(int l, int r) { by_l.erase({l, r}); by_r.erase({r, l}); } }; vector<Node> ITree(4*n); auto build = [&] (const auto &self, int node, int l, int r) -> void { int mid = (l + r)/2; ITree[node].L = l; ITree[node].R = r; ITree[node].M = mid; if (l+1 == r) return; self(self, 2*node + 1, l, mid); self(self, 2*node + 2, mid, r); }; build(build, 0, 0, n); auto insert = [&] (const auto &self, int node, int l, int r) -> void { // Insert interval [l, r) into the tree if (ITree[node].L+1 == ITree[node].R) { ITree[node].ins(l, r); return; } if (l >= ITree[node].M) self(self, 2*node+2, l, r); else if (r <= ITree[node].M) self(self, 2*node+1, l, r); else ITree[node].ins(l, r); }; auto erase = [&] (const auto &self, int node, int x) -> void { // Delete all intervals covering point x if (x < ITree[node].M) { // Delete some prefix auto &st = ITree[node].by_l; while (!st.empty()) { auto [l, r] = *begin(st); if (l <= x) { ITree[node].del(l, r); ll id = 1ll*(n+1)*l + r; cache.erase(id); } else break; } } else { // Delete some suffix auto &st = ITree[node].by_r; while (!st.empty()) { auto [r, l] = *rbegin(st); if (r > x) { ITree[node].del(l, r); ll id = 1ll*(n+1)*l + r; cache.erase(id); } else break; } } if (ITree[node].L+1 == ITree[node].R) return; if (x < ITree[node].M) self(self, 2*node+1, x); else self(self, 2*node+2, x); }; constexpr array<ll, 3> unit = {0, 0, -1}; SegTree<array<ll, 3>, unit> seg(n); for (int i = 0; i < n; ++i) seg.update(i, array<ll, 3>{a[i], a[i], i}); auto solve = [&] (const auto &self, int L, int R) -> int { if (R-L <= 2) return -1; ll id = 1ll*L*(n+1) + R; if (cache.find(id) != cache.end()) return cache[id]; auto [sm, mx, pivot] = seg.query(L, R); insert(insert, 0, L, R); if (mx < sm - mx) { return cache[id] = R-L; } else { int ret = self(self, L, pivot); ret = max(ret, self(self, pivot+1, R)); return cache[id] = ret; } }; while (q--) { int type; cin >> type; if (type == 1) { int l, r; cin >> l >> r; cout << solve(solve, l-1, r) << '\n'; } else { ll pos, val; cin >> pos >> val; --pos; erase(erase, 0, pos); if (pos) erase(erase, 0, pos-1); if (pos+1 < n) erase(erase, 0, pos+1); seg.update(pos, array<ll, 3>{val, val, pos}); } } } }
1991
A
Maximize the Last Element
You are given an array $a$ of $n$ integers, where $n$ is \textbf{odd}. In one operation, you will remove two \textbf{adjacent} elements from the array $a$, and then concatenate the remaining parts of the array. For example, given the array $[4,7,4,2,9]$, we can obtain the arrays $[4,2,9]$ and $[4,7,9]$ by the operations $[\underline{4,7}, 4,2,9] \to [4,2,9]$ and $[4,7,\underline{4,2},9] \to [4,7,9]$ respectively. However, we cannot obtain the array $[7,2,9]$ as it requires deleting non-adjacent elements $[\underline{4},7,\underline{4},2,9]$. You will repeatedly perform this operation until exactly one element remains in $a$. Find the maximum possible value of the remaining element in $a$.
Consider the parity of the position. The answer is the maximum value of the elements at odd indices. Proof Any element at an odd index can be preserved until the end. Since each element at an odd index has an even number of elements on both sides, pairs of adjacent elements can be removed from left to right until only the element at the odd index remains. For example, if you want to keep the element at the $i$-th position, you can remove the elements at positions $1$ and $2$, $3$ and $4$, and so on, until the elements at positions $i-2$ and $i-1$ are removed. Then, continue removing elements at positions $i+1$ and $i+2$, and so on, until the elements at positions $n-1$ and $n$ are removed. Therefore, any element at an odd index can be preserved through this method. No element at an even index can be preserved until the end. Since $n$ is odd, there are more elements at odd indices than at even indices. Each operation removes one element at an odd index and one element at an even index. Since there are always more elements at odd indices, the last remaining element must be at an odd index.
[ "greedy", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX_N = 105; int t, n, a[MAX_N]; int main() { cin >> t; while (t--) { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; int max_value = 0; for (int i = 1; i <= n; i += 2) max_value = max(max_value, a[i]); cout << max_value << '\n'; } }
1991
B
AND Reconstruction
You are given an array $b$ of $n - 1$ integers. An array $a$ of $n$ integers is called good if $b_i = a_i \, \& \, a_{i + 1}$ for $1 \le i \le n-1$, where $\&$ denotes the bitwise AND operator. Construct a good array, or report that no good arrays exist.
Consider $b_{i - 1} | b_i$. Let's construct an array $a$ using the formula $a_i = b_{i - 1} | b_i$ (assuming $b_0$ and $b_n$ are $0$). We then verify the condition $b_i = a_i \& a_{i + 1}$ for $1 \le i < n$. If any condition fails, then such an array $a$ does not exist. Explanation Using the above construction method, we get: $a_i \& a_{i + 1} = (b_{i - 1} | b_i) \& (b_i | b_{i + 1}) = b_i | (b_{i - 1} \& b_{i + 1})$ If for any $i$, $b_i | (b_{i - 1} \& b_{i + 1}) \neq b_i$, then the constructed array $a$ does not satisfy the required condition. This indicates that there exists a bit in $b$ where $b_{i - 1} = 1$, $b_i = 0$, and $b_{i + 1} = 1$, which can prove there is no solution. Proof: If $a_{i - 2} \& a_{i - 1} = b_{i - 1} = 1$, then $a_{i - 1} = 1$. Similarly, since $a_i \& a_{i + 1} = b_i = 1$, then $a_i = 1$. However, $a_{i - 1} \& a_i = 1 \& 1 = 1$, which contradicts $b_i = 0$. Therefore, this configuration is unsolvable. This shows that our construction method can construct a valid array $a$, except in cases where the above bit configuration in $b$ makes it unsolvable.
[ "bitmasks", "constructive algorithms", "greedy" ]
1,100
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1e5 + 5; int n, b[MAX_N], a[MAX_N]; void solve() { cin >> n; for (int i = 1; i < n; i++) cin >> b[i]; b[0] = b[n] = 0; for (int i = 1; i <= n; i++) a[i] = b[i - 1] | b[i]; bool valid = true; for (int i = 1; i < n; i++) if ((a[i] & a[i + 1]) != b[i]) { valid = false; break; } if (valid) { for (int i = 1; i <= n; i++) cout << a[i] << ' '; cout << '\n'; } else cout << -1 << endl; } int main() { int t; cin >> t; while (t--) solve(); }
1991
C
Absolute Zero
You are given an array $a$ of $n$ integers. In one operation, you will perform the following two-step move: - Choose an integer $x$ ($0 \le x \le 10^{9}$). - Replace each $a_i$ with $|a_i - x|$, where $|v|$ denotes the absolute value of $v$. For example, by choosing $x = 8$, the array $[5, 7, 10]$ will be changed into $[|5-8|, |7-8|, |10-8|] = [3,1,2]$. Construct a sequence of operations to make all elements of $a$ equal to $0$ in at most $40$ operations or determine that it is impossible. You do \textbf{not} need to minimize the number of operations.
If the array contains both odd and even elements, it is impossible to zero the array. Is there a method to narrow the range of elements after every operation? If the array contains both odd and even numbers, it is impossible to zero the array. This is because any operation will maintain the presence of both odd and even elements. Otherwise, if all elements in the array are either odd or even, it is feasible to zero the array in no more than $31$ operations. The operation strategy works by iteratively narrowing the range of all elements. Initially, the range of all elements is between $[0, 2^{30}]$. Starting from $x = 2^{29}$, we use each power of $2$ as $x$, reducing the exponent by one each time (i.e., $2^{29}, 2^{28}, \ldots, 2^{0}$). After each operation, the range of all elements is halved, narrowed down to $[0, x]$. Continuing this process, after $30$ operations, all elements will become $0$ or $1$. If all elements are $1$ after $30$ operations, perform one last operation with $x = 1$ to turn all $1\text{s}$ into $0\text{s}$.
[ "constructive algorithms", "greedy", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; const int MAX_N = 2e5 + 5; int n, a[MAX_N]; void solve() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; bool has_odd = false, has_even = false; for (int i = 1; i <= n; i++) if (a[i] % 2 == 1) has_odd = true; else has_even = true; if (has_even && has_odd) cout << -1 << '\n'; else { vector<int> operations; for (int i = 29; i >= 0; i--) operations.push_back(1 << i); if (has_even) operations.push_back(1); cout << operations.size() << '\n'; for (int x : operations) cout << x << ' '; cout << '\n'; } } int main() { int t; cin >> t; while (t--) solve(); }
1991
D
Prime XOR Coloring
You are given an undirected graph with $n$ vertices, numbered from $1$ to $n$. There is an edge between vertices $u$ and $v$ if and only if $u \oplus v$ is a prime number, where $\oplus$ denotes the bitwise XOR operator. Color all vertices of the graph using the minimum number of colors, such that no two vertices directly connected by an edge have the same color.
We can use only $4$ colors for all $n$. For $n \ge 6$, the minimum number of colors is always $4$. Proof First, we can show that the number of colors cannot be less than $4$. This is because vertices $1$, $3$, $4$, and $6$ form a clique, meaning they are all connected, so they must have different colors. Next, we can provide a construction where the number of colors is $4$. For the $i$-th vertex, assign the color $i \bmod 4 + 1$. This ensures that any two vertices of the same color have a difference that is a multiple of $4$, so their XOR is a multiple of $4$, which is not a prime number. For $n < 6$, the example provides the coloring for all cases: $n = 1$: A valid coloring is $[1]$. $n = 2$: A valid coloring is $[1, 2]$. $n = 3$: A valid coloring is $[1, 2, 2]$. $n = 4$: A valid coloring is $[1, 2, 2, 3]$. $n = 5$: A valid coloring is $[1, 2, 2, 3, 3]$.
[ "bitmasks", "constructive algorithms", "graphs", "greedy", "math", "number theory" ]
1,900
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; if (n < 6) { if (n == 1) cout << 1 << '\n' << "1" << '\n'; else if (n == 2) cout << 2 << '\n' << "1 2" << '\n'; else if (n == 3) cout << 2 << '\n' << "1 2 2" << '\n'; else if (n == 4) cout << 3 << '\n' << "1 2 2 3" << '\n'; else if (n == 5) cout << 3 << '\n' << "1 2 2 3 3" << '\n'; } else { cout << 4 << '\n'; for (int i = 1; i <= n; i++) cout << i % 4 + 1 << ' '; cout << '\n'; } } int main() { int t; cin >> t; while (t--) solve(); }
1991
E
Coloring Game
This is an interactive problem. Consider an undirected connected graph consisting of $n$ vertices and $m$ edges. Each vertex can be colored with one of three colors: $1$, $2$, or $3$. Initially, all vertices are uncolored. Alice and Bob are playing a game consisting of $n$ rounds. In each round, the following two-step process happens: - Alice chooses two \textbf{different} colors. - Bob chooses an uncolored vertex and colors it with one of the two colors chosen by Alice. Alice wins if there exists an edge connecting two vertices of the same color. Otherwise, Bob wins. You are given the graph. Your task is to decide which player you wish to play as and win the game.
Determine if the graph is bipartite. If the graph is not bipartite, Alice will win. If the graph is bipartite, Bob will win. If the graph is not bipartite, Alice can always choose colors $1$ and $2$. According to the definition of a non-bipartite graph, Bob cannot color the graph with two colors without having two adjacent vertices of the same color. If the graph is bipartite, it can be divided into two parts, Part $1$ and Part $2$, with no edges within each part. If the colors chosen by Alice include color $1$, Bob can paint vertices in part $1$ with color $1$. If the colors chosen by Alice include color $2$, Bob can paint vertices in part $2$ with color $2$. Once one part is completely painted, Bob can use color $3$ or continue using the original color of that part to paint the remaining vertices, ensuring no two adjacent vertices have the same color. In this way, Bob will win.
[ "constructive algorithms", "dfs and similar", "games", "graphs", "greedy", "interactive" ]
1,900
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1e4 + 5; int n, m, color[MAX_N], isBipartite; vector<int> graph[MAX_N]; void dfs(int vertex) { for (auto neighbor: graph[vertex]) if (!color[neighbor]) { color[neighbor] = 3 — color[vertex]; dfs(neighbor); } else if (color[neighbor] + color[vertex] != 3) isBipartite = 0; } void solve() { cin >> n >> m; for (int i = 1; i <= n; i++) { graph[i].clear(); color[i] = 0; } for (int i = 1; i <= m; i++) { int u, v; cin >> u >> v; graph[u].push_back(v); graph[v].push_back(u); } isBipartite = 1; color[1] = 1; dfs(1); if (!isBipartite) { cout << "Alice" << endl; for (int i = 1; i <= n; i++) { cout << 1 << ' ' << 2 << endl; int vertex, chosenColor; cin >> vertex >> chosenColor; } } else { cout << "Bob" << endl; vector<int> part1, part2; for (int i = 1; i <= n; i++) if (color[i] == 1) part1.push_back(i); else part2.push_back(i); for (int i = 1; i <= n; i++) { int color1, color2; cin >> color1 >> color2; if ((color1 == 1 || color2 == 1) && part1.size()) { cout << part1.back() << ' ' << 1 << endl; part1.pop_back(); } else if ((color1 == 2 || color2 == 2) && part2.size()) { cout << part2.back() << ' ' << 2 << endl; part2.pop_back(); } else if (!part1.size()) { int chosenColor = (color1 == 1 ? color2 : color1); cout << part2.back() << ' ' << chosenColor << endl; part2.pop_back(); } else { int chosenColor = (color1 == 2 ? color2 : color1); cout << part1.back() << ' ' << chosenColor << endl; part1.pop_back(); } } } } int main() { int t; cin >> t; while (t--) solve(); }
1991
F
Triangle Formation
You are given $n$ sticks, numbered from $1$ to $n$. The length of the $i$-th stick is $a_i$. You need to answer $q$ queries. In each query, you are given two integers $l$ and $r$ ($1 \le l < r \le n$, $r - l + 1 \ge 6$). Determine whether it is possible to choose $6$ \textbf{distinct} sticks from the sticks numbered $l$ to $r$, to form $2$ \textbf{non-degenerate} triangles$^{\text{∗}}$. \begin{footnotesize} $^{\text{∗}}$A triangle with side lengths $a$, $b$, and $c$ is called non-degenerate if: - $a < b + c$, - $b < a + c$, and - $c < a + b$. \end{footnotesize}
Under the constraints of the problem, there exists a (small) integer $C$ such that for intervals longer than $C$, it is guaranteed to form two triangles. If there are at least $45$ sticks, it is guaranteed to form a triangle. Proof: For any sequence of stick lengths that cannot form a triangle, we can replace it with the Fibonacci sequence. By replacing the sticks in increasing order, the sequence will remain incapable of forming a triangle. This implies that the Fibonacci sequence is one of the longest sequences that cannot form a triangle. The $45$th Fibonacci number exceeds $10^9$. Therefore, having at least $45$ sticks ensures that it is possible to form a triangle. If there are at least $48$ sticks, it is guaranteed to form two triangles. Proof: We can first form the first triangle and remove those sticks. The remaining number of sticks is still at least $45$, which is sufficient to form the second triangle. Therefore, only for intervals with fewer than $48$ sticks, we need to check whether it is possible to form two triangles. First, we sort the sticks within the interval. Then we use the following algorithm to find two triangles: Algorithm 1: Enumerate all possible sets of $6$ consecutive sticks and check if they can form two triangles. Algorithm 2: Identify all possible sets of $3$ consecutive sticks that can form a triangle, and check if there exist two disjoint sets among them. If neither algorithm can find two triangles, then it is impossible to form two triangles within the given interval. Proof: Consider an interval where Algorithm 1 cannot find two triangles. Suppose it is indeed possible to form two triangles; the six sticks must be non-consecutive. For any unselected sticks between the chosen sticks, if there exists a stick to its left and a stick to its right that belongs to the same triangle, we can replace the leftmost stick of this triangle with the unselected stick. Continuing this process, either the six sticks will become consecutive, or the left side will form one triangle and the right side will form another, which can be detected by Algorithm 2.
[ "brute force", "greedy", "implementation", "math", "sortings" ]
2,200
#include <bits/stdc++.h> using namespace std; const int MAX_N = 1e5 + 5; int n, q, a[MAX_N], p[MAX_N]; bool canFormTwoTriangles(int l, int r) { int t = 0; for (int i = l; i <= r; i++) p[++t] = a[i]; sort(p + 1, p + t + 1); for (int i = 1; i <= t - 5; i++) for (int j = i + 1; j <= i + 5; j++) for (int k = j + 1; k <= i + 5; k++) { int q[4], c = 0; for (int m = i + 1; m <= i + 5; m++) if (m != j && m != k) q[++c] = p[m]; if (p[i] + p[j] > p[k] && q[1] + q[2] > q[3]) return true; } int triangleCount = 0; for (int i = 1; i <= t - 2; i++) if (p[i] + p[i + 1] > p[i + 2]) { i += 2; triangleCount++; } return triangleCount > 1; } int main() { cin >> n >> q; for (int i = 1; i <= n; i++) cin >> a[i]; while (q--) { int l, r; cin >> l >> r; if (r — l + 1 >= 48 || canFormTwoTriangles(l, r)) cout << "YES" << '\n'; else cout << "NO" << '\n'; } }
1991
G
Grid Reset
You are given a grid consisting of $n$ rows and $m$ columns, where each cell is initially white. Additionally, you are given an integer $k$, where $1 \le k \le \min(n, m)$. You will process $q$ operations of two types: - $\mathtt{H}$ (horizontal operation) — You choose a $1 \times k$ rectangle completely within the grid, where all cells in this rectangle are white. Then, all cells in this rectangle are changed to black. - $\mathtt{V}$ (vertical operation) — You choose a $k \times 1$ rectangle completely within the grid, where all cells in this rectangle are white. Then, all cells in this rectangle are changed to black. After each operation, if any rows or columns become completely black, all cells in these rows and columns are \textbf{simultaneously} reset to white. Specifically, if all cells in the row and column a cell is contained in become black, all cells in both the row and column will be reset to white. Choose the rectangles in a way that you can perform all given operations, or determine that it is impossible.
Perform horizontal operations only on the leftmost $k$ columns and vertical operations only on the topmost $k$ rows. Prioritize operations that will lead to a reset. Here is a strategy to ensure you can perform operations infinitely: Perform horizontal operations only on the leftmost $k$ columns and vertical operations only on the topmost $k$ rows. Prioritize operations that will lead to a reset. If multiple operations can cause a reset, perform any of them; if no operations can cause a reset, perform any available operation. Proof of Correctness For a $n \times m$ grid, we define it to be in a horizontal state if its black cells can be covered by non-overlapping $1 \times m$ rectangles without gaps. Similarly, the grid is in a vertical state if its black cells can be covered by non-overlapping $n \times 1$ rectangles without gaps. Our strategy ensures the grid always satisfies the following properties: The $k \times k$ region in the top-left corner, the $(n-k) \times k$ region in the bottom-left corner, and the $k \times (m-k)$ region in the top-right corner are either in a horizontal state, vertical state, or both. The top-left and bottom-left regions cannot both be purely in a vertical state; similarly, the top-left and top-right regions cannot both be purely in a horizontal state. We will prove two points: first, when these properties are satisfied, there is always a valid operation; second, after performing operations according to our strategy, the grid still satisfies these properties. Existence of Valid Operations Assume the current operation is horizontal (the proof for vertical operations is similar). If the top-left and bottom-left regions cannot perform a horizontal operation, they must be completely black or in a purely vertical state. If one region is completely black, the other cannot be completely black or purely vertical, because that would have led to a reset earlier. According to the second property, the top-left and bottom-left regions cannot both be in a purely vertical state. Therefore, there is always a valid operation. Maintaining the First Property For the bottom-left and top-right regions, they always satisfy the first property. Proof: Consider the bottom-left region (the proof for the top-right region is similar). It starts as completely white, turning black row by row, maintaining a horizontal state. Once it is completely black, it resets column by column, maintaining a vertical state. Thus, it alternates between horizontal and vertical states. For the top-left region, it always satisfies the first property. Proof: After coloring and before resetting, the top-left region still satisfies the first property. Suppose it is in a horizontal state before resetting (the proof for a vertical state is similar). Since it cannot reset vertically, it remains at least in a horizontal state after resetting. If it becomes completely black and resets horizontally (the proof for a vertical reset is similar), it remains in a horizontal state. Unless $k = 1$, rows and columns cannot reset simultaneously. Suppose both rows and columns can reset, and assume the current operation is horizontal in the top-left region (the proof for a vertical operation is similar). This means the top-left region was in a purely horizontal state before turning completely black. The row in the top-right region was completely black, while other rows were white, contradicting the second property before the operation. Maintaining the Second Property Assume the current operation is horizontal (the proof for vertical operations is similar) and causes a reset, the second property still holds. Proof: If the operation is in the bottom-left region, it was completely black before resetting. After resetting, the top-left region turns completely white, maintaining the second property. We previously proved that unless $k = 1$, rows and columns cannot reset simultaneously. If the horizontal operation is in the top-left region and columns reset, the top-left region was completely black before resetting. After resetting, the top-left region becomes vertical, while the bottom-left region turns white, maintaining the second property. If the horizontal operation is in the top-left region and rows reset, the top-left region remains unchanged, while the row in the top-right region turns white. If the top-right region's state changes and resets to a purely horizontal state (the only possible violation of the second property), the top-right region is completely black before resetting. Thus, the top-left region was not in a purely horizontal state before resetting. Since the top-left region remains unchanged, it cannot be in a purely horizontal state, maintaining the second property. Assume the current operation is horizontal (the proof for vertical operations is similar) and does not cause a reset, the second property still holds. Proof: If the operation is in the bottom-left region, it remains in a horizontal state, maintaining the second property. If the operation is in the top-left region, the only possible violation of the second property is if the top-right region remains in a purely horizontal state while the top-left region becomes purely horizontal. This means the top-left region was completely white before the operation. In this case, we can choose to reset any completely black row in the top-right region. According to the strategy, we prioritize resets, leading to a contradiction. Thus, the second property still holds.
[ "constructive algorithms", "greedy", "implementation" ]
2,700
#include <bits/stdc++.h> using namespace std; const int MAX_SIZE = 105; char operationType; int n, m, k, q, grid[MAX_SIZE][MAX_SIZE]; string s; int calculateSum(int x1, int y1, int x2, int y2) { int sum = 0; for (int i = x1; i <= x2; i++) for (int j = y1; j <= y2; j++) sum += grid[i][j]; return sum; } void performOperation(int x, int y) { cout << x << ' ' << y << '\n'; for (int i = 1; i <= k; i++) { grid[x][y] = 1; if (operationType == 'H') y++; else x++; } int rowSums[MAX_SIZE] = {}, colSums[MAX_SIZE] = {}; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { rowSums[i] += grid[i][j]; colSums[j] += grid[i][j]; } for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (rowSums[i] == m || colSums[j] == n) grid[i][j] = 0; } void solve() { cin >> n >> m >> k >> q >> s; s = ' ' + s; memset(grid, 0, sizeof(grid)); for (int i = 1; i <= q; i++) { operationType = s[i]; if (operationType == 'H') { int row = -1; for (int j = 1; j <= n; j++) if (calculateSum(j, 1, j, k) == 0) { row = j; if (calculateSum(j, 1, j, m) == m - k) { break; } } performOperation(row, 1); } else { int col = -1; for (int j = 1; j <= m; j++) if (calculateSum(1, j, k, j) == 0) { col = j; if (calculateSum(1, j, n, j) == n - k) { break; } } performOperation(1, col); } } } int main() { int t; cin >> t; while (t--) solve(); }
1991
H
Prime Split Game
Alice and Bob are playing a game with $n$ piles of stones, where the $i$-th pile has $a_i$ stones. Players take turns making moves, with Alice going first. On each move, the player does the following three-step process: - Choose an integer $k$ ($1 \leq k \leq \frac n 2$). Note that the value of $k$ can be different for different moves. - Remove $k$ piles of stones. - Choose another $k$ piles of stones and split each pile into two piles. The number of stones in each new pile must be a prime number. The player who is unable to make a move loses. Determine who will win if both players play optimally.
Consider which pairs of numbers an odd number can be split into. What about an even number? Consider a simplified version of the game with only two piles of stones, where the first pile contains $x$ stones, and the second pile contains one stone. Determine all winning positions for this game configuration. For the simplified version of the game, given that we have calculated the odd $x$ which are losing positions, we can quickly determine the winning positions for even $x$ using Fast Fourier Transform or bitset operations. We can determine the winner of most games by considering how many $a_i$ are in winning positions and whether $n$ is odd or even. For games where we currently cannot determine the winner, we can use the number of $a_i$ that can be split into two winning positions to determine the final winner. Let's analyze this problem from simple to complex scenarios. First, let's consider how to split a single number $x$: For an odd number $x$, it can only be split into $x - 2$ and $2$. Proof: An odd number can only be split into an odd and an even number, and the only even prime is $2$. For an even number $x$, apart from $x = 4$ which can be split into $2$ and $2$, it can only be split into two odd numbers. Proof: An even number can only be split into odd and odd, or even and even. The only even prime is $2$, thus only $4$ can be split into even and even. Next, let's consider a simplified version of the game with only two piles of stones, where the first pile contains $x$ stones, and the second pile contains one stone. If Alice wins in this setup, we call $x$ a winning position; otherwise, it is a losing position. We first determine whether an odd $x$ is a winning position, then determine whether an even $x$ is a winning position: For an odd $x$, we need to calculate how many times $2$ stones can be split from $x$ until $x - 2$ is not a prime. If the number of splits is odd, then it is a winning position; otherwise, it is a losing position. For an even $x$, if $x$ can be split into two losing positions, then $x$ is a winning position; otherwise, $x$ is a losing position. Apart from $x = 4$ (a winning position), other even numbers can only be split into two odd numbers. Optimization: Directly checking all ways to split each even number will time out. However, we can use the Fast Fourier Transform (FFT) or bitset operations, based on the losing positions of odd numbers, to determine the winning positions of even numbers. If you are not familiar with this optimization technique, it is recommended to first solve 2014 ICPC SWERC Problem C Golf Bot, the tutorial is here. In summary, the characteristics of winning and losing positions are: losing positions either cannot be split, or they must split out at least one winning position. Winning positions can be split into two losing positions. Let's return to the original game. If all $a_i$ are in losing positions, Bob will win. Proof: No matter how Alice moves, Bob can always turn all $a_i$ back to losing positions. Suppose Alice splits to produce $2 \cdot k$ new piles in one move, then at least $k$ of them will be in winning positions. Bob can split these $k$ piles into $2 \cdot k$ losing positions and remove the remaining $k$ new piles. As a result, all piles will be back in losing positions. This process will continue until no more losing positions can be split, which will lead to Bob's win. Since we now have a general scenario where Bob wins, we can discuss all scenarios that can turn into this scenario with one move. In these scenarios, Alice will win: When $n$ is even and the number of winning positions $a_i$ ranges between $[1, n]$, Alice will win. Proof: Assuming the number of winning positions is $w$, Alice can choose $k = \lceil \frac{w}{2} \rceil$ to select $k$ winning positions and split them into $2 \cdot k$ losing positions. She then removes other winning positions and may remove one extra pile, to sum up $k$ piles. After the move, all piles will be turned into losing positions, ensuring Alice's win. When $n$ is odd and the number of winning positions $a_i$ ranges between $[1, n-1]$, Alice will win. Proof: Similar to the previous proof, Alice can turn all piles into losing positions in one move. The only unresolved case is when $n$ is odd and the number of winning positions $a_i$ equals $n$. Alice cannot turn all positions into losing positions in one move because at most $2 \cdot k$ positions can be changed in a single move. Since $2 \cdot k < n$, it is impossible to change all $n$ positions. In this case, if someone splits a winning position into a losing position, the number of winning positions will drop to $[1, n - 1]$, leading to failure. However, winning positions can sometimes be split into two winning positions. Therefore, we only need to consider this splitting case. A number is called a good position if it can be split into two winning positions; otherwise, it is called a bad position. We find that odd numbers cannot be good positions because they can only be split into $x - 2$ and $2$, and $2$ is not a winning position. Thus, only even numbers can be good positions if they can be split into two odd winning positions. Optimization: Directly checking ways to split each even number will time out. We can use FFT or bitset operations to identify good positions among even numbers. Note that good positions can only be split into two bad positions because even numbers can only be split into odd numbers or $2$, both of which are considered bad positions. Thus, when $n$ is odd and all $a_i$ are in winning positions, we only need to determine the winner based on the number of good positions: If the number of good positions $a_i$ is $0$, Bob will win. Proof: Any move by Alice will produce losing positions, as analyzed earlier, leading to failure. If the number of good positions $a_i$ is between $[1, n - 1]$, Alice will win. Proof: In one move, Alice can turn all numbers into bad positions using a method similar to when $n$ is odd and winning positions are between $[1, n - 1]$. If the number of good positions $a_i$ is $n$, Bob will win. Proof: Any move by Alice will produce losing or bad positions, ultimately leading to the previous scenario and resulting in failure.
[ "bitmasks", "dp", "fft", "games", "math", "number theory" ]
3,300
#include <bits/stdc++.h> using namespace std; const int MAX_N = 2e5 + 5; bitset<MAX_N + 1> isComposite, isWinning, isPrimeLosing, isPrimeWinning, isGoodPosition; void initialize() { isComposite[1] = true; for (int i = 2; i <= MAX_N; i++) for (int j = 2 * i; j <= MAX_N; j += i) isComposite[j] = true; for (int i = 3; i <= MAX_N; i += 2) { int count = 0, j = i; while (!isComposite[j - 2]) { count++; j -= 2; } isWinning[i] = count % 2; isPrimeLosing[i] = !isComposite[i] && !isWinning[i]; } isWinning[4] = true; for (int i = 3; i <= MAX_N; i += 2) if (isPrimeLosing[i]) isWinning |= isPrimeLosing << i; for (int i = 1; i <= MAX_N; ++i) isPrimeWinning[i] = (i % 2) && isWinning[i] && !isComposite[i]; for (int i = 3; i <= MAX_N; i += 2) if (isPrimeWinning[i]) isGoodPosition |= isPrimeWinning << i; } void solve() { int n, x, totalWinning = 0, totalGood = 0; cin >> n; for (int i = 1; i <= n; ++i) { cin >> x; totalWinning += isWinning[x]; totalGood += isGoodPosition[x]; } if (totalWinning <= n - n % 2) cout << (totalWinning ? "Alice" : "Bob") << endl; else cout << (totalGood && totalGood < n ? "Alice" : "Bob") << endl; } int main() { initialize(); int t; cin >> t; while (t--) solve(); }
1991
I
Grid Game
This is an interactive problem. You are given a grid with $n$ rows and $m$ columns. You need to fill each cell with a unique integer from $1$ to $n \cdot m$. After filling the grid, you will play a game on this grid against the interactor. Players take turns selecting one of the previously unselected cells from the grid, with the interactor going first. On the first turn, the interactor can choose any cell from the grid. After that, any chosen cell must be orthogonally adjacent to at least one previously selected cell. Two cells are considered orthogonally adjacent if they share an edge. The game continues until all cells have been selected. Your goal is to let the sum of numbers in the cells selected by you be \textbf{strictly} less than the sum of numbers in the cells selected by the interactor.
Notice that if the problem requires our selected numbers' sum to be greater than the interactor's sum, instead of smaller, the essence of the problem changes. Depending on whether $n \cdot m$ is odd or even, we can use different methods to fill the grid and adapt our game strategy. When $n \cdot m$ is odd, we can adopt a strategy that forces the interactor to choose the largest number, $n \cdot m$. When $n \cdot m$ is even, we can divide the grid into several tiles. After the interactor chooses a number from a tile, we immediately choose from the same tile. We set each tile size to be even, ensuring we always select the second number from each tile. When $n \cdot m$ is even, we can create some T-shaped tiles at the edges of the grid, where each T-shaped tile consists of a cell on the edge and three cells surrounding it. Place a small number in the center of each T-shaped tile, and fill the surrounding three cells with large numbers. This way, we can always select the smallest number from each T-shaped tile, except for the interactor's first choice. When $n \cdot m$ is even, we only need to create $4$ T-shaped tiles and divide the remaining cells into several dominos, each containing two adjacent numbers. This method of filling numbers is sufficient to ensure that the sum of the numbers we choose is smaller. Notice that if the problem requires our selected numbers' sum to be greater than the interactor's sum, instead of smaller, the essence of the problem changes. Specifically, when $n \cdot m$ is odd, the interactor will select one more number than us. If the goal is to have a greater sum of numbers, the interactor will have an advantage; conversely, if the goal is to have a smaller sum, we will have an advantage. Depending on whether $n \cdot m$ is odd or even, we can use different methods to fill the grid and adapt our game strategy. Here, we will explain these two methods and strategies in detail. When $n \cdot m$ is odd, we can adopt a strategy that forces the interactor to choose the largest number, $n \cdot m$. Specifically, we can divide the grid into: $\lfloor \frac{n \cdot m}{2} \rfloor$ dominos ($1 \times 2$ or $2 \times 1$ tiles), each containing two adjacent numbers. In the remaining single cell, we place the largest number. Our strategy is as follows: If the interactor chooses a number from a domino and the other number has not yet been chosen, we choose that number; otherwise, we choose any valid number from the dominos. This ensures that: In each domino, both we and the interactor select one number. Proof: The interactor cannot choose both numbers in a domino because as soon as they choose the first one, we immediately choose the second one. Therefore, we select at least one number in each domino. We cannot select two numbers in any domino because our total number of selections would exceed the number of dominos, which equals our total number of selections. Hence, we exactly select one number in each domino. The interactor will inevitably choose the largest number. Proof: Since we only choose numbers from the dominos, the remaining largest number will not be selected by us. In the worst case, we will choose the larger number in each domino. However, the interactor will always select the largest number. Therefore, in this scenario, our sum will be less than the interactor's sum by $n \cdot m - \lfloor \frac{n \cdot m}{2} \rfloor = \lceil \frac{n \cdot m}{2} \rceil$. When $n \cdot m$ is even, we can divide the grid into several tiles. After the interactor chooses a number from a tile, we immediately choose from the same tile. We set each tile size to be even, ensuring we always select the second number from each tile. If a small number is surrounded by large numbers in a tile, as the second chooser we can choose the small number. We place the small numbers on the edges of the grid, where the number of surrounding cells is odd, ensuring that each tile has an even number of cells. This tiling arrangement gives us a significant advantage; only a few such tiles are needed, while the rest of the grid can be filled with dominos containing adjacent numbers, making our sum of numbers smaller. Here are the detailed descriptions of grid filling and game strategy: We divide the grid into: $4$ T-shaped tiles, each with a small number at the edge of the grid, surrounded by three large numbers. $\frac{n \cdot m - 16}{2}$ dominos, each containing two adjacent numbers. Specifically, we define $[1, 4]$ as small numbers, and $[n \cdot m - 11, n \cdot m]$ as large numbers. Numbers $[n \cdot m - 11, n \cdot m - 9]$ surround number $1$, $[n \cdot m - 8, n \cdot m - 6]$ surround number $2$, $[n \cdot m - 5, n \cdot m - 3]$ surround number $3$, and $[n \cdot m - 2, n \cdot m]$ surround number $4$. Assuming $n \le m$, we divide the grid as follows: For $n = 4$ and $m = 4$, as well as $n = 4$ and $m = 5$, we manually divide the grid. This is a specific layout for a $4 \times 4$ grid, with bold lines indicating tiles division, green cells representing small numbers, and red cells representing large numbers. This is a specific layout for a $4 \times 5$ grid, with additional settings, where yellow cells represent adjacent numbers in dominos. For $m \geq 6$, we place two T-shaped tiles and two dominos in the top left and top right $4 \times 3$ areas. The remaining part of the top four rows can be filled with vertical dominos. For rows beyond the top four, if $m$ is even, we fill them with horizontal dominos; if $m$ is odd, we fill them with vertical dominos. This is a specific layout for a $5 \times 8$ grid, an example where $m$ is even. This is a specific layout for a $6 \times 7$ grid, an example where $m$ is odd. Our strategy is as follows: After the interactor chooses a number from a tile, we will immediately choose the smallest valid number from the same tile. This ensures that the interactor can only start choosing from the large numbers in each T-shaped tile, allowing us to choose the small number, except for the small number that the interactor initially chooses. Next, we will analyze why this strategy ensures a smaller sum. For each T-shaped tile, if the interactor did not initially choose from this tile, we can at least choose the smallest and largest numbers; if the interactor initially chose from this tile, we can at least choose the second smallest and largest numbers. We find that if the interactor chooses to start from the T-shaped tile, they take away our smallest number and give us the second smallest number. Thus, in the worst case, the interactor starts choosing from number $4$, where the difference between the smallest and second smallest numbers in that tile is the largest. In dominos, we assume we will choose the larger number. In the worst case, the calculation of our sum of numbers minus the interactor's sum of numbers is: $(1 - (n \cdot m - 11) - (n \cdot m - 10) + (n \cdot m - 9)) +$ $(2 - (n \cdot m - 8) - (n \cdot m - 7) + (n \cdot m - 6)) +$ $(3 - (n \cdot m - 5) - (n \cdot m - 4) + (n \cdot m - 3)) +$ $(-4 + (n \cdot m - 2) - (n \cdot m - 1) + n \cdot m) +$ $(n \cdot m - 16) / 2 =$ $20 - 1.5 \cdot n \cdot m$ When $n$ and $m$ are at their minimum, this value is the largest and unfavorable for us. However, when $n$ and $m$ are at their minimum of $4$, our sum of numbers is still $4$ less than the interactor's ($20 - 1.5 \cdot 4 \cdot 4 = -4$).
[ "constructive algorithms", "games", "graph matchings", "greedy", "interactive" ]
3,500
#include <bits/stdc++.h> using namespace std; const int MAX_N = 15, dx[] = {-1, 0, 0, 1}, dy[] = {0, -1, 1, 0}; int n, m, x, y, grid[MAX_N][MAX_N], color[MAX_N][MAX_N], visited[MAX_N][MAX_N], currentValue, currentColor, flipCoords; bool isAdjacent(int x, int y) { int nx, ny; for (int i = 0; i < 4; i++) { nx = x + dx[i]; ny = y + dy[i]; if (1 <= nx && nx <= n && 1 <= ny && ny <= m && visited[nx][ny]) return true; } return false; } void interact() { cin >> x >> y; if (flipCoords) swap(x, y); visited[x][y] = 1; } void output(int x, int y) { visited[x][y] = 1; if (flipCoords) cout << y << ' ' << x << endl; else cout << x << ' ' << y << endl; } void placePair(int x1, int y1, int x2, int y2) { grid[x1][y1] = ++currentValue; grid[x2][y2] = ++currentValue; color[x1][y1] = color[x2][y2] = ++currentColor; } void placeTShape(int x, int y) { int largestValue = n * m - 12 + currentColor * 3; grid[x][y] = ++currentValue; color[x][y] = ++currentColor; int nx, ny; for (int i = 0; i < 4; i++) { nx = x + dx[i]; ny = y + dy[i]; if (1 <= nx && nx <= n && 1 <= ny && ny <= m) { grid[nx][ny] = ++largestValue; color[nx][ny] = currentColor; } } } void printGrid() { if (!flipCoords) for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cout << grid[i][j] << ' '; } cout << endl; } else for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { cout << grid[j][i] << ' '; } cout << endl; } } void fillHorizontalPairs() { for (int i = 1; i <= n; i++) for (int j = 1; j < m; j++) if (!grid[i][j] && !grid[i][j + 1]) placePair(i, j, i, j + 1); } void fillVerticalPairs() { for (int i = 1; i < n; i++) for (int j = 1; j <= m; j++) if (!grid[i][j] && !grid[i + 1][j]) placePair(i, j, i + 1, j); } void solve() { cin >> n >> m; memset(grid, 0, sizeof(grid)); memset(color, 0, sizeof(color)); memset(visited, 0, sizeof(visited)); currentColor = currentValue = flipCoords = 0; if (n % 2 == 1 && m % 2 == 1) { for (int i = 1; i <= n; i++) for (int j = 1; j < m; j += 2) placePair(i, j, i, j + 1); for (int i = 1; i <= n; i += 2) placePair(i, m, i + 1, m); grid[n][m] = n * m; printGrid(); for (int i = 1; i < n * m; i += 2) { interact(); bool selected = false; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) if (!visited[i][j] && color[i][j] == color[x][y]) { output(i, j); selected = true; break; } if (selected) break; } if (selected) continue; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (!visited[i][j] && isAdjacent(i, j) && grid[i][j] != n * m) { output(i, j); i = n; j = m; } } cin >> x >> y; return; } if (n > m) { swap(n, m); flipCoords = 1; } if (n == 4 && m == 4) { placeTShape(1, 2); placeTShape(2, 4); placeTShape(3, 1); placeTShape(4, 3); } else if (n == 4 && m == 5) { placeTShape(1, 2); placeTShape(3, 1); placeTShape(3, 5); placeTShape(4, 3); fillHorizontalPairs(); } else { placeTShape(1, 2); placeTShape(3, 1); placeTShape(1, m — 1); placeTShape(3, m); placePair(2, 3, 3, 3); placePair(4, 2, 4, 3); placePair(2, m — 2, 3, m — 2); placePair(4, m — 2, 4, m — 1); if (m % 2 == 0) fillHorizontalPairs(); else fillVerticalPairs(); } printGrid(); for (int i = 1; i <= n * m; i += 2) { interact(); pair bestMove = {-1,-1}; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) if (!visited[i][j] && color[i][j] == color[x][y] && (bestMove.first == -1 || grid[i][j] < grid[bestMove.first][bestMove.second])) bestMove = {i,j}; output(bestMove.first, bestMove.second); } } int main() { int t; cin >> t; while (t--) solve(); }
1992
A
Only Pluses
Kmes has written three integers $a$, $b$ and $c$ in order to remember that he has to give Noobish_Monk $a \times b \times c$ bananas. Noobish_Monk has found these integers and decided to do the following \textbf{at most $5$ times}: - pick one of these integers; - increase it by $1$. For example, if $a = 2$, $b = 3$ and $c = 4$, then one can increase $a$ three times by one and increase $b$ two times. After that $a = 5$, $b = 5$, $c = 4$. Then the total number of bananas will be $5 \times 5 \times 4 = 100$. What is the maximum value of $a \times b \times c$ Noobish_Monk can achieve with these operations?
Let's prove why it's always better to add to the smallest number, let $a \le b \le c$, then compare the three expressions: $(a+1)\times b \times c$, $a \times (b+1) \times c$, and $a \times b \times (c+1)$. Remove the common part $a \times b \times c$, and we get: $b \times c$, $a \times c$, $a \times b$. $b \times c \ge a \times c$, since $a \le b$, similarly, $b \times c \ge a \times b$, since $a \le c$. Therefore, we can simply find the minimum $5$ times and add one to it. And thus, obtain the answer. Another, primitive approach is to simply iterate through what we will add to $a$, $b$, and $c$ with three loops. Since we can only add $5$ times, the time complexity of the solution is $O(1)$.
[ "brute force", "constructive algorithms", "greedy", "math", "sortings" ]
800
for _ in range(int(input())): arr = sorted(list(map(int,input().split()))) for i in range(5): arr[0]+=1 arr.sort() print(arr[0] * arr[1] * arr[2])
1992
B
Angry Monk
To celebrate his recovery, k1o0n has baked an enormous $n$ metres long potato casserole. Turns out, Noobish_Monk just can't stand potatoes, so he decided to ruin k1o0n's meal. He has cut it into $k$ pieces, of lengths $a_1, a_2, \dots, a_k$ meters. k1o0n wasn't keen on that. Luckily, everything can be fixed. In order to do that, k1o0n can do one of the following operations: - Pick a piece with length $a_i \ge 2$ and divide it into two pieces with lengths $1$ and $a_i - 1$. As a result, the number of pieces will increase by $1$; - Pick a slice $a_i$ and another slice with length $a_j=1$ ($i \ne j$) and merge them into one piece with length $a_i+1$. As a result, the number of pieces will decrease by $1$. Help k1o0n to find the minimum number of operations he needs to do in order to merge the casserole into one piece with length $n$. For example, if $n=5$, $k=2$ and $a = [3, 2]$, it is optimal to do the following: - Divide the piece with length $2$ into two pieces with lengths $2-1=1$ and $1$, as a result $a = [3, 1, 1]$. - Merge the piece with length $3$ and the piece with length $1$, as a result $a = [4, 1]$. - Merge the piece with length $4$ and the piece with length $1$, as a result $a = [5]$.
Let's say we want to connect two casseroles with lengths $x$ and $y$. We can disassemble one of them into pieces of length $1$ and then attach them to the casserole of size $y$. In total, we will perform $2x - 1$ operations. Since we want to connect $k$ pieces, at least $k - 1$ of them will have to be disassembled and then attached to something. If we attach something to a piece, there is no point in disassembling it, because to disassemble it, we will need to remove these pieces as well. Therefore, we want to choose a piece to which we will attach all the others. It will be optimal to choose a piece with the maximum size and attach everything to it. Thus, the answer is $2 \cdot (n - mx) - k + 1$, where $mx$ $-$ the length of the maximum piece. Solution complexity: $O(n)$.
[ "greedy", "math", "sortings" ]
800
for _ in range(int(input())): n,k = map(int,input().split()) mx = max(map(int, input().split())) print((n - mx) * 2 - (k - 1))
1992
C
Gorilla and Permutation
Gorilla and Noobish_Monk found three numbers $n$, $m$, and $k$ ($m < k$). They decided to construct a permutation$^{\dagger}$ of length $n$. For the permutation, Noobish_Monk came up with the following function: $g(i)$ is the sum of all the numbers in the permutation on a prefix of length $i$ that are not greater than $m$. Similarly, Gorilla came up with the function $f$, where $f(i)$ is the sum of all the numbers in the permutation on a prefix of length $i$ that are not less than $k$. A prefix of length $i$ is a subarray consisting of the first $i$ elements of the original array. For example, if $n = 5$, $m = 2$, $k = 5$, and the permutation is $[5, 3, 4, 1, 2]$, then: - $f(1) = 5$, because $5 \ge 5$; $g(1) = 0$, because $5 > 2$; - $f(2) = 5$, because $3 < 5$; $g(2) = 0$, because $3 > 2$; - $f(3) = 5$, because $4 < 5$; $g(3) = 0$, because $4 > 2$; - $f(4) = 5$, because $1 < 5$; $g(4) = 1$, because $1 \le 2$; - $f(5) = 5$, because $2 < 5$; $g(5) = 1 + 2 = 3$, because $2 \le 2$. Help them find a permutation for which the value of $\left(\sum_{i=1}^n f(i) - \sum_{i=1}^n g(i)\right)$ is maximized. $^{\dagger}$A permutation of length $n$ is an array consisting of $n$ distinct integers from $1$ to $n$ in any order. For example, $[2,3,1,5,4]$ is a permutation, but $[1,2,2]$ is not a permutation (as $2$ appears twice in the array) and $[1,3,4]$ is also not a permutation (as $n=3$, but $4$ appears in the array).
Let $p$ be some permutation. Let's look at the contribution of the number $p_i$ to the sum $\sum_{i=1}^n {f(i)}$. If it is less than $k$, the contribution is $0$, otherwise the contribution is $p_i \cdot (n - i + 1)$. Similarly, let's look at the contribution of $p_i$ to the sum $\sum_{i=1}^n {g(i)}$. If it is greater than $m$, the contribution is $0$, otherwise it is $p_i \cdot (n - i + 1)$. Since $m < k$, each number gives a contribution greater than $0$ in at most one sum. Therefore, it is advantageous to place numbers not less than $k$ at the beginning, and numbers not greater than $m$ at the end. Also, numbers not less than $k$ should be in descending order to maximize the sum of $f(i)$. Similarly, numbers not greater than $m$ should be in ascending order to minimize the sum of $g(i)$. For example, you can construct such a permutation: $n, n - 1, \ldots, k, m + 1, m + 2, \ldots, k - 1, 1, 2, \ldots, m$. It is easy to see that $\sum_{i=1}^n f(i)$ cannot be greater for any other permutation, and $\sum_{i=1}^n g(i)$ cannot be less for any other permutation, so our answer is optimal. Solution complexity: $O(n)$.
[ "constructive algorithms", "math" ]
900
for _ in range(int(input()): n,m,k = map(int,input().split()) print(*range(n,m,-1), *range(1,m))
1992
D
Test of Love
ErnKor is ready to do anything for Julen, even to swim through crocodile-infested swamps. We decided to test this love. ErnKor will have to swim across a river with a width of $1$ meter and a length of $n$ meters. The river is very cold. Therefore, \textbf{in total} (that is, throughout the entire swim from $0$ to $n+1$) ErnKor can swim in the water for no more than $k$ meters. For the sake of humanity, we have added not only crocodiles to the river, but also logs on which he can jump. Our test is as follows: Initially, ErnKor is on the left bank and needs to reach the right bank. They are located at the $0$ and $n+1$ meters respectively. The river can be represented as $n$ segments, each with a length of $1$ meter. Each segment contains either a log 'L', a crocodile 'C', or just water 'W'. ErnKor can move as follows: - If he is on the surface (i.e., on the bank or on a log), he can jump forward for no more than $m$ ($1 \le m \le 10$) meters (he can jump on the bank, on a log, or in the water). - If he is in the water, he can only swim to the next river segment (or to the bank if he is at the $n$-th meter). - ErnKor cannot land in a segment with a crocodile in any way. Determine if ErnKor can reach the right bank.
In this problem, there are two main solutions: dynamic programming and greedy algorithm. Dynamic programming solution: $dp_i$ $-$ the minimum number of meters that need to be swum to reach the $i$-th cell. The base case of the dynamic programming is $dp_0 = 0$. Then, the update rule is: $\begin{equation*} dp_i = \text{minimum of} \begin{cases} dp_{i-1} + 1& \text{if } A_i = \text{'W'} \\ min(dp_j) & \text{for all } j, \text{where:} \max(0, i - m) \le j < i \text{ and } A_j = \text{'L'} \end{cases} \end{equation*}$ Greedy algorithm solution: If we can jump, we want to jump to the shore if possible. If we can't, we want to jump to any log ahead to jump from it later. If we can't, we jump as far as possible to avoid crocodiles and swim as little as possible. Solution complexity: $O(n)$.
[ "dp", "greedy", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m, k; cin >> n >> m >> k; string s; cin >> s; vector<int> dp(n + 2, -1); dp[0] = k; for (int i = 1; i <= n + 1; i++) { if (i != n + 1 && s[i - 1] == 'C') continue; for (int t = 1; t <= m; t++) if (i - t >= 0 && (i - t == 0 || s[i - t - 1] == 'L')) dp[i] = max(dp[i], dp[i - t]); if (i > 1 && s[i - 2] == 'W') dp[i] = max(dp[i], dp[i - 1] - 1); } if (dp[n + 1] >= 0) cout << "YES\n"; else cout << "NO\n"; } }
1992
E
Novice's Mistake
One of the first programming problems by K1o0n looked like this: "Noobish_Monk has $n$ $(1 \le n \le 100)$ friends. Each of them gave him $a$ $(1 \le a \le 10000)$ apples for his birthday. Delighted with such a gift, Noobish_Monk returned $b$ $(1 \le b \le \min(10000, a \cdot n))$ apples to his friends. How many apples are left with Noobish_Monk?" K1o0n wrote a solution, but accidentally considered the value of $n$ as a string, so the value of $n \cdot a - b$ was calculated differently. Specifically: - when multiplying the string $n$ by the integer $a$, he will get the string $s=\underbrace{n + n + \dots + n + n}_{a\ \text{times}}$ - when subtracting the integer $b$ from the string $s$, the last $b$ characters will be removed from it. If $b$ is greater than or equal to the length of the string $s$, it will become empty. Learning about this, ErnKor became interested in how many pairs $(a, b)$ exist for a given $n$, satisfying the constraints of the problem, on which K1o0n's solution gives the correct answer. "The solution gives the correct answer" means that it outputs a \textbf{non-empty} string, and this string, when converted to an integer, equals the correct answer, i.e., the value of $n \cdot a - b$.
Notice that $n * a - b$ is strictly less than $10^6$, i.e., it has no more than $6$ digits. The number of characters in the strange calculation $n * a - b$ is equal to $|n| * a - b$, where $|n|$ is the number of digits in n. Let's iterate over the value of $a$, and then determine the boundaries $minB$ and $maxB$ for it, such that $|n| * a > maxB$ and $|n| * a - minB \le 6$. Then: $\begin{cases} minB = |n| * a- 6 \\ maxB = |n| * a- 1 \end{cases}$ Solution complexity: $O(a)$.
[ "brute force", "constructive algorithms", "implementation", "math", "strings" ]
1,700
for _ in range(int(input())): n = int(input()) sn = str(n) lenN = len(str(n)) ans = [] for a in range(1, 10001): minB = max(1, lenN * a - 5) maxB = lenN * a for b in range(minB, maxB): x = n * a - b y = 0 for i in range(lenN * a - b): y = y * 10 + int(sn[i % lenN]) if x == y: ans.append((a, b)) print(len(ans)) for p in ans: print(*p)
1992
F
Valuable Cards
In his favorite cafe Kmes once again wanted to try the herring under a fur coat. Previously, it would not have been difficult for him to do this, but the cafe recently introduced a new purchasing policy. Now, in order to make a purchase, Kmes needs to solve the following problem: $n$ cards with prices for different positions are laid out in front of him, on the $i$-th card there is an integer $a_i$, among these prices there is no whole positive integer $x$. Kmes is asked to divide these cards into the minimum number of bad segments (so that each card belongs to exactly one segment). A segment is considered bad if it is impossible to select a subset of cards with a product equal to $x$. All segments, in which Kmes will divide the cards, must be bad. Formally, the segment $(l, r)$ is bad if there are no indices $i_1 < i_2 < \ldots < i_k$ such that $l \le i_1, i_k \le r$, and $a_{i_1} \cdot a_{i_2} \ldots \cdot a_{i_k} = x$. Help Kmes determine the minimum number of bad segments in order to enjoy his favorite dish.
Let's consider the greedy algorithm ``take as long as you can''. Let's prove that it works. In any optimal division, if we take the first segment of non-maximum length, we will not violate the criteria if we transfer one element from the second segment to the first. Therefore, the given greedy algorithm is correct. Now let's figure out how to quickly understand if the segment can be extended. First, find all divisors of the number $x$. If the number $a_i$ is not a divisor of it, then it cannot be included in any set of numbers whose product is equal to $x$, so we can simply add it to the segment. If $a_i$ is a divisor, we need to somehow learn to understand whether it, in combination with some other divisors, gives the number $x$ on the segment. We will maintain a set of divisors that are products of some numbers in the segment. To update the set when adding $a_i$, we will go through all the divisors of this set and for each divisor $d$ add $d \cdot a_i$ to the set. If we added the number $x$ to the set, $a_i$ will already be in the next segment and we need to clear the set. P. S.: About implementation details and runtime. If you maintain the set in a set structure, then we get a runtime of $O(n \cdot d(x) \cdot \log(d(x)))$, where $d(x)$ is the number of divisors of $x$. Instead of a set, you can use, for example, a global array $used$ of size $10^5 + 1$, as well as maintain a vector of reachable divisors. Using these structures, you can achieve a runtime of $O(n \cdot d(x))$.
[ "brute force", "dp", "greedy", "number theory", "two pointers" ]
1,900
#include <iostream> #include <vector> using namespace std; const int A = 1e6 + 1; bool used[A]; bool divs[A]; void solve() { int n, x; cin >> n >> x; vector<int> a(n); vector<int> vecDivs; for (int d = 1; d * d <= x; d++) { if (x % d == 0) { divs[d] = true; vecDivs.push_back(d); if (d * d < x) { vecDivs.push_back(x / d); divs[x / d] = true; } } } for (int i = 0; i < n; i++) cin >> a[i]; int ans = 1; used[1] = true; vector<int> cur{ 1 }; for (int i = 0; i < n; i++) { if (!divs[a[i]]) continue; vector<int> ncur; bool ok = true; for (int d : cur) if (1ll * d * a[i] <= x && divs[d * a[i]] && !used[d * a[i]]) { ncur.push_back(d * a[i]); used[d * a[i]] = true; if (d * a[i] == x) ok = false; } for (int d : ncur) cur.push_back(d); if (!ok) { ans++; for (int d : cur) used[d] = false; used[1] = true; used[a[i]] = true; cur = vector<int>{ 1, a[i] }; } } for (int d : vecDivs) { divs[d] = false; used[d] = false; } cout << ans << '\n'; } signed main() { int T; cin >> T; while (T--) solve(); return 0; }
1992
G
Ultra-Meow
K1o0n gave you an array $a$ of length $n$, consisting of numbers $1, 2, \ldots, n$. Accept it? Of course! But what to do with it? Of course, calculate $\text{MEOW}(a)$. Let $\text{MEX}(S, k)$ be the $k$-th \textbf{positive} (strictly greater than zero) integer in ascending order that is not present in the set $S$. Denote $\text{MEOW}(a)$ as the sum of $\text{MEX}(b, |b| + 1)$, over all \textbf{distinct} subsets $b$ of the array $a$. Examples of $\text{MEX}(S, k)$ values for sets: - $\text{MEX}(\{3,2\}, 1) = 1$, because $1$ is the first positive integer not present in the set; - $\text{MEX}(\{4,2,1\}, 2) = 5$, because the first two positive integers not present in the set are $3$ and $5$; - $\text{MEX}(\{\}, 4) = 4$, because there are no numbers in the empty set, so the first $4$ positive integers not present in it are $1, 2, 3, 4$.
We will iterate over the size of the set $k$ and its $\text{MEOW}$, $m$. If $2k \geqslant n$, then the set $x$ will fill all the remaining numbers up to $n$, and there may still be some larger than $n$ in it, so the $MEOW$ of all such sets will be $2k+1$, and there will be a total of $C(n, k)$ such sets for each $k$. If $2k < n$, $m$ lies in the interval from $k+1$ to $2k+1$. Notice that there can be exactly $m - 1 - k$ numbers before $m$, and correspondingly $2k + 1 - m$ numbers to the right of $m$, so the answer needs to be added with $C_{m - 1}^{m - 1 - k} \cdot C_{n - m}^{2k + 1 - m} \cdot m$. Asymptotic complexity of the solution: $O(n^2)$.
[ "combinatorics", "dp", "math" ]
2,000
#include <iostream> using namespace std; const int mod = 1e9 + 7; int add(int a, int b) { if (a + b >= mod) return a + b - mod; return a + b; } int sub(int a, int b) { if (a < b) return a + mod - b; return a - b; } int mul(int a, int b) { return (int)((1ll * a * b) % mod); } int binpow(int a, int pw) { int b = 1; while (pw) { if (pw & 1) b = mul(b, a); a = mul(a, a); pw >>= 1; } return b; } int inv(int a) { return binpow(a, mod - 2); } const int N = 15000; int f[N], r[N]; void precalc() { f[0] = 1; for (int i = 1; i < N; i++) f[i] = mul(f[i - 1], i); r[N - 1] = inv(f[N - 1]); for (int i = N - 2; i > -1; i--) r[i] = mul(r[i + 1], i + 1); } int C(int n, int k) { if (n < 0 || k < 0 || n < k) return 0; return mul(f[n], mul(r[k], r[n - k])); } inline void solve() { int n; cin >> n; int ans = 1; for (int k = 1; k <= n; k++) { if (2 * k >= n) { ans = add(ans, mul(2 * k + 1, C(n, k))); continue; } for (int m = k + 1; m <= 2 * k + 1; m++) { int c = mul(C(m - 1, m - 1 - k), C(n - m, 2 * k + 1 - m)); ans = add(ans, mul(mul(C(m - 1, m - 1 - k), C(n - m, 2 * k + 1 - m)), m)); } } cout << ans << '\n'; } signed main() { int T = 1; cin >> T; precalc(); while(T--) solve(); return 0; }
1993
A
Question Marks
Tim is doing a test consisting of $4n$ questions; each question has $4$ options: 'A', 'B', 'C', and 'D'. For each option, there are exactly $n$ correct answers corresponding to that option — meaning there are $n$ questions with the answer 'A', $n$ questions with the answer 'B', $n$ questions with the answer 'C', and $n$ questions with the answer 'D'. For each question, Tim wrote his answer on the answer sheet. If he could not figure out the answer, he would leave a question mark '?' for that question. You are given his answer sheet of $4n$ characters. What is the maximum number of correct answers Tim can get?
What is the pattern of Tim's answer sheet that can give him maximum score? Let's say there are $n$ problems take $A$ as the answer, therefore he can only get $n$ points with the answer $A$. The same is correct for $B$, $C$ and $D$. Therefore, the maximum score can be achieved is $min(n, A) + min(n, B) + min(n, C) + min(n, D)$. Time complexity: $O(4n)$
[ "greedy", "implementation" ]
800
t = int(input()) for _ in range(t): n = int(input()) s = input() print(sum(min(n, s.count(c)) for c in "ABCD"))
1993
B
Parity and Sum
Given an array $a$ of $n$ positive integers. In one operation, you can pick any pair of indexes $(i, j)$ such that $a_i$ and $a_j$ have \textbf{distinct} parity, then replace the smaller one with the sum of them. More formally: - If $a_i < a_j$, replace $a_i$ with $a_i + a_j$; - Otherwise, replace $a_j$ with $a_i + a_j$. Find the minimum number of operations needed to make all elements of the array have the same parity.
Find a way to make all the elements even. Then odd. In the worst case, the number of operations required is the number of even elements + 1. Why? First, if all elements already have the same parity, we don't need to do perform any operation. Next, if the array contains both $even$ and $odd$ numbers. In this case, it is impossible to convert all elements to $even$ numbers. If we apply an operation on: two $odd$ elements, one of them remains $odd$. two elements of distinct parities, one of them is replaced with their sum, which is an $odd$ number. This implies even if we want to change an $odd$ element to $even$ number, it fails in both ways possible. So we just want to convert all of them to $odd$ numbers. Now come the greedy part: $even + even = even \longrightarrow$ it doesn't reduce the number of $even$ elements, so skip it. $odd + odd = even \longrightarrow$ this creates another $even$ number, indeed very awful. $even + odd = odd \longrightarrow$ this is great, but only if the sum replaces the $even$ one (which means $even < odd$). Let's find the largest $odd$ element and call it $s$. Then traverse each $even$ elements $t$ in non-decreasing order and apply an operation on $s$ and $t$: If $t < s$, $s+t$ becomes largest odd number. Thus, we set $s := s+t$. This reduce the number of even element by $1$. If $t > s$, before we do this operation, we need to do another on $s$ and the largest even element to make $s$ the largest in the array. Note that this case only happens at most once. As a result, the answer is the number of even elements (plus $1$ if the second case occurs). Time complexity: $O(n\log n)$.
[ "constructive algorithms", "greedy" ]
1,100
t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) s = -1 v = [] for x in a: if x%2 == 0: v.append(x) elif x > s: s = x v.sort() if s == -1 or v == []: print(0) continue ans = len(v) for t in v: if t < s: s += t else: ans += 1 break print(ans)
1993
C
Light Switches
There is an apartment consisting of $n$ rooms, each with its light \textbf{initially turned off}. To control the lights in these rooms, the owner of the apartment decided to install chips in the rooms so that each room has exactly one chip, and the chips are installed at different times. Specifically, these times are represented by the array $a_1, a_2, \ldots, a_n$, where $a_i$ is the time (in minutes) at which a chip is installed in the $i$-th room. As soon as a chip is installed, it changes the room's light status every $k$ minutes — it turns on the light for $k$ minutes, then turns it off for the next $k$ minutes, then turns it back on for the next $k$ minutes, and so on. In other words, the light status is changed by the chip at minute $a_i$, $a_i + k$, $a_i + 2k$, $a_i + 3k$, $\ldots$ for the $i$-th room. What is the earliest moment when all rooms in the apartment have their lights turned on?
Try to find the segments of moments when a light is on. Select this segment from each light. The answer should be the intersection of all of them. As soon as a chip is installed, it changes the light's status every $k$ minutes. Let's first list the segments of the moments when a light is on if we install a chip at moment $x$: $x\rightarrow x+k-1$ $x+2k\rightarrow x+3k-1$ $x+4k\rightarrow x+5k-1$ $\dots$ Have you seen the pattern yet? Apparently each segment in the list (except the first one) is actually the segment before it, shifted by $2k$ minutes. This also means that if we divide by $2k$ and take the remainder at both ends of each segment, all these segments become equal. With that, let's call $(a_i\bmod 2k, (a_i+k-1)\bmod 2k)$ the segment of the $i$-th chip. Our problem is thus simplified to: find the smallest integer $s$ such that: $max(a) \le s$ $s\bmod 2k$ appears in every segments of all chips. In order to satisfy the first condition, it seems if we figure out some $r = s\bmod 2k$ that satisfy the second condition, we may come up with: $s = max(a) + ((r - max(a))\bmod 2k)$ Next, in order for a segment to contain $r$, this inequality must be satisfied: $r-k+1 \le a_i \le r \pmod{2k}$. This is because a light is on only for at most $k$ minutes (before it gets turned off), so it must come not long before the moment $r$. Let's call $d[z]$ the number of chips that has $a_i \equiv z \pmod{2k}$, then in order for all lights to be on at moment $s$, the condition is: $\sum \limits_{z=r-k+1}^{r} d[z] = n$ This idea can be implemented using two-pointer technique, that traverse all $r$ from $0$ to $2k-1$. As there can be many possible values of $r$, we only take one that produces $s$ with minimum value. Be careful when handling signs in problems with modules to avoid unnecessary errors. Time complexity: $O(n)$.
[ "implementation", "math" ]
1,400
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, k, d[2*N]; int main() { cin.tie(0)->sync_with_stdio(0); int t; cin >> t; while (t--) { cin >> n >> k; int mx = -1; fill(d, d + 2*k, 0); for (int i = 0; i < n; i++) { int x; cin >> x; assert(x >= 1); d[x % (2*k)]++; mx = max(mx, x); } int cnt = 0; int ans = INT_MAX; for (int i = 0; i <= k - 2; i++) { cnt += d[i]; } for (int l = 0, r = k-1; l < 2*k; l++, r++) { if (r >= 2*k) r -= 2*k; if (cnt += d[r]; cnt == n) { int wait = (r-mx) % (2*k); if (wait < 0) wait += 2*k; ans = min(ans, mx + wait); } cnt -= d[l]; } if (ans == INT_MAX) { ans = -1; } cout << ans << '\n'; } }
1993
D
Med-imize
Given two positive integers $n$ and $k$, and another array $a$ of $n$ integers. In one operation, you can select any subarray of size $k$ of $a$, then remove it from the array without changing the order of other elements. More formally, let $(l, r)$ be an operation on subarray $a_l, a_{l+1}, \ldots, a_r$ such that $r-l+1=k$, then performing this operation means replacing $a$ with $[a_1, \ldots, a_{l-1}, a_{r+1}, \ldots, a_n]$. For example, if $a=[1,2,3,4,5]$ and we perform operation $(3,5)$ on this array, it will become $a=[1,2]$. Moreover, operation $(2, 4)$ results in $a=[1,5]$, and operation $(1,3)$ results in $a=[4,5]$. You have to repeat the operation while the length of $a$ is greater than $k$ (which means $|a| \gt k$). What is the largest possible median$^\dagger$ of all remaining elements of the array $a$ after the process? $^\dagger$The median of an array of length $n$ is the element whose index is $\left \lfloor (n+1)/2 \right \rfloor$ after we sort the elements in non-decreasing order. For example: $median([2,1,5,4,3]) = 3$, $median([5]) = 5$, and $median([6,8,2,4]) = 4$.
Is there any method to calculate median without sorting? Is there any relationship between the original array with the final array? Note: in order to explain this solution easier, we'll suppose all arrays are 0-indexed. If $n \le k$, we don't have to remove any segment since the statement only tell us to do it while the length of $a$ is greater than $k$. That way, the median of $a$ is fixed. Let's find a way to calculate this value without sorting the array. Given an integer $x$. If $x$ is less than or equal to the median of $a$, then suppose we sort $a$ in increasing order, $x$ is somewhat to the left of $med(a)$. That means the number of elements greater than or equal to $x$ is more than the number of elements less than $x$. Using this observation, we can create another array $b$ of the same size as $a$, such that $b[i] = 1$ if $a[i] \ge x$, otherwise $b[i] = -1$. The trick here is if $sum(b) > 0$, then the condition $x \le med(a)$ is satisfied. Using this trick, we can easily binary search the median of $a$ by fixing value of $x$, checking if $sum(b) > 0$ and adjusting the value range of $med(a)$. How about $n>k$. In this case, we'll keep using the same strategy as above. That is: fix the value of $x$, find a way to delete segments of $a$ so that the array $b$ has largest sum, check if that sum is greater than $0$ and adjust the value range of the answer. Note that each time we delete a segment, the size of $a$ is reduced by $k$. We do that until $|a|\le k$. Let's call the final array $a$ after deleting segments $a'$. After some calculation, we come up with $|a'| = ((n-1)\bmod k) + 1$. Also, it can be seen that the elements $a'[0], \dots, a'[m-1]$ (where $m = |a'|$) always originate from the elements $a[i_0], \dots, a[i_{m-1}]$ such that $i_0\equiv 0\pmod k, i_1\equiv 1\pmod k, \dots, i_{m-1}\equiv m-1\pmod k$. Suppose we want to delete the segment $[i, i+k-1]$ from $a$. This operation shift all the elements from the right by $k$ units to the left, which means the indexes are subtracted by $k$ units. But if we only care about the indexes modulo $k$ before and after deleting the segments, shifting $k$ units doesn't change their modulos at all. With all above observations, we come up with the following DP formula to find the optimal segment deletions: $dp[0] = b[0]$ If $i\equiv 0\pmod k$ and $i > 0$, then $dp[i] = max(dp[i-k], b[i])$ Otherwise $dp[i] = dp[i-1] + b[i]$. If $i > k$ then maximize $dp[i]$ by $dp[i-k]$ Then, the maximum sum of $b$ in the optimal deletions equals to $dp[n-1]$. Time complexity: $O(n\log max(a))$.
[ "binary search", "dp", "greedy" ]
2,200
#include <bits/stdc++.h> using namespace std; const int N = 500005; int n, k, a[N]; int dp[N], b[N]; bool check(int med) { for (int i = 0; i < n; i++) { if (a[i] >= med) { b[i] = 1; } else { b[i] = -1; } } dp[0] = b[0]; for (int i = 1; i < n; i++) { if (i%k == 0) { dp[i] = max(dp[i-k], b[i]); } else { dp[i] = dp[i-1] + b[i]; if (i > k) { dp[i] = max(dp[i], dp[i-k]); } } } return dp[n-1] > 0; } int main() { cin.tie(0)->sync_with_stdio(0); int t; cin >> t; while (t--) { cin >> n >> k; for (int i = 0; i < n; i++) { cin >> a[i]; } int lo = 1, hi = 1e9; while (lo <= hi) { int mid = lo + hi >> 1; if (check(mid)) { lo = mid + 1; } else { hi = mid - 1; } } cout << hi << '\n'; } }
1993
E
Xor-Grid Problem
Given a matrix $a$ of size $n \times m$, each cell of which contains a non-negative integer. The integer lying at the intersection of the $i$-th row and the $j$-th column of the matrix is called $a_{i,j}$. Let's define $f(i)$ and $g(j)$ as the XOR of all integers in the $i$-th row and the $j$-th column, respectively. In one operation, you can either: - Select any row $i$, then assign $a_{i,j} := g(j)$ for each $1 \le j \le m$; or - Select any column $j$, then assign $a_{i,j} := f(i)$ for each $1 \le i \le n$. \begin{center} {\small An example of applying an operation on column $2$ of the matrix.} \end{center} In this example, as we apply an operation on column $2$, all elements in this column are changed: - $a_{1,2} := f(1) = a_{1,1} \oplus a_{1,2} \oplus a_{1,3} \oplus a_{1,4} = 1 \oplus 1 \oplus 1 \oplus 1 = 0$ - $a_{2,2} := f(2) = a_{2,1} \oplus a_{2,2} \oplus a_{2,3} \oplus a_{2,4} = 2 \oplus 3 \oplus 5 \oplus 7 = 3$ - $a_{3,2} := f(3) = a_{3,1} \oplus a_{3,2} \oplus a_{3,3} \oplus a_{3,4} = 2 \oplus 0 \oplus 3 \oplus 0 = 1$ - $a_{4,2} := f(4) = a_{4,1} \oplus a_{4,2} \oplus a_{4,3} \oplus a_{4,4} = 10 \oplus 11 \oplus 12 \oplus 16 = 29$ You can apply the operations any number of times. Then, we calculate the $beauty$ of the final matrix by summing the absolute differences between all pairs of its adjacent cells. More formally, $beauty(a) = \sum|a_{x,y} - a_{r,c}|$ for all cells $(x, y)$ and $(r, c)$ if they are adjacent. Two cells are considered adjacent if they share a side. Find the minimum $beauty$ among all obtainable matrices.
Try applying an operation on the same row twice. Does it change the matrix significantly? Now apply operations on two different rows. Does the second row (that the operation is applied) look familiar? First, let's extend the original matrix by one unit in rows and columns (which means there's an additional $(n+1)$-th row and $(m+1)$-th column). Then, assign $a[i][m+1] = f(i)$ (xorsum of the $i$-th row) and $a[n+1][j] = g(j)$ (xorsum of the $j$-th column). That way, the operation is simplified as follows: The first-type operation becomes swapping the $i$-th row with the $(n+1)$-th row. The second-type operation becomes swapping the $j$-th column with the $(m+1)$-th column. As we know, the first-type operation is to select any row $i$, then assign $a[i][j] = g(j)$ for all index $j$. But after the matrix extension, the value of $g(j)$ is also $a[n+1][j]$ so it means replacing the $i$-th row with the $(n+1)$-th one. But we also need to care about the new value of $g(j)$ for future operations right? Surprisingly, the new value of $g(j)$ is nowhere strange, just the old value of element $a[i][j]$ being replaced right before! This takes advantage of the fact that if we perform the operation on the same row twice, the row become unchanged. After swapping two rows, the value of $a[n+1][j]$ then again become $g(j)$ of the new matrix. The change of the second-type operation can be proven the same way. That way, the matrix can be constructed by the permutation of rows, and the permutation of columns (as we can swap them however we want). After all operations, let's say the rows ordered from the top to the bottom are $r_1, r_2, \dots, r_{n+1}$. Similarly, the columns ordered from the left to the right are $c_1, c_2, \dots, c_{m+1}$. Next thing to consider is: $\text{beauty(a)} = R + C$ - the beauty of the matrix, where: $R = \sum\limits_{i=1}^n \sum\limits_{j=2}^m \big|a[i][j] - a[i][j-1]\big|$ - sum of adjacent cells on the same row. $C = \sum\limits_{j=1}^m \sum\limits_{i=2}^n \big|a[i][j] - a[i-1][j]\big|$ - sum of adjacent cells on the same column. Note that we include neither the $(n+1)$-th row nor the $(m+1)$-th column when calculating $R$ and $C$. That being said, after all operations, the $r_{n+1}$-th row and the $c_{m+1}$-th column is excluded and do not make any effect in further calculations anymore. After that, we calculate two arrays: $dr[u][v] =$ sum of differences between $u$-th row and $v$-th row. $dc[u][v] =$ sum of differences between $u$-th column and $v$-th column. Then, we'll rewrite the formulas of $R$ and $C$ as: $R = \sum\limits_{i=2}^n dr[r_{i-1}][r_i]$ and $C = \sum\limits_{i=2}^m dc[c_{i-1}][c_i]$. From now on, calculating $R$ and $C$ is as easy as solving the Travelling Salesman Problem: finding a good permutation $r_1, \dots, r_n$ that produces the minimum $R$, and a good permutation $c_1, \dots, c_n$ that produces the minimum $C$. At the end, by summing $R + C$ we got the $\text{beauty}$ for a fixed excluded row and column for the matrix $a$. Time complexity: $O((n+1)(m+1)^22^{m+1} + (m+1)(n+1)^22^{n+1})$, or just $O(n^32^n)$.
[ "bitmasks", "constructive algorithms", "dp", "implementation" ]
2,700
#include <bits/stdc++.h> using namespace std; const int N = 16; int n, m; int a[N][N]; int fr[N][N], fc[N][N]; int w[N][N], dp[N][1<<N]; int main() { cin.tie(0)->sync_with_stdio(0); int t; cin >> t; while (t--) { cin >> n >> m; for (int i = 0; i <= n; i++) a[i][m] = 0; for (int j = 0; j <= m; j++) a[n][j] = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> a[i][j]; a[i][m] ^= a[i][j]; a[n][j] ^= a[i][j]; a[n][m] ^= a[i][j]; } } int fullmask_n = (1 << (n+1)) - 1; int fullmask_m = (1 << (m+1)) - 1; for (int rmv = 0; rmv <= m; rmv++) { for (int i = 0; i <= n; i++) { for (int j = i + 1; j <= n; j++) { w[i][j] = 0; for (int l = 0; l <= m; l++) { if (rmv == l) continue; w[i][j] += abs(a[i][l] - a[j][l]); } w[j][i] = w[i][j]; } } for (int i = 0; i <= n; i++) { fill(dp[i], dp[i] + fullmask_n, INT_MAX); dp[i][1 << i] = 0; } for (int mask = 0; mask <= fullmask_n; mask++) { for (int last = 0; last <= n; last++) { if (~mask >> last & 1) continue; if (__builtin_popcount(mask) == n) continue; for (int next = 0; next <= n; next++) { if (mask >> next & 1) continue; int new_mask = mask | 1 << next; dp[next][new_mask] = min( dp[next][new_mask], dp[last][mask] + w[last][next] ); } } } for (int i = 0; i <= n; i++) { fr[i][rmv] = INT_MAX; int mask = fullmask_n ^ 1 << i; for (int last = 0; last <= n; last++) { fr[i][rmv] = min(fr[i][rmv], dp[last][mask]); } } } for (int rmv = 0; rmv <= n; rmv++) { for (int i = 0; i <= m; i++) { for (int j = i + 1; j <= m; j++) { w[i][j] = 0; for (int l = 0; l <= n; l++) { if (rmv == l) continue; w[i][j] += abs(a[l][i] - a[l][j]); } w[j][i] = w[i][j]; } } for (int i = 0; i <= m; i++) { fill(dp[i], dp[i] + fullmask_m, INT_MAX); dp[i][1 << i] = 0; } for (int mask = 0; mask <= fullmask_m; mask++) { for (int last = 0; last <= m; last++) { if (~mask >> last & 1) continue; if (__builtin_popcount(mask) == m) continue; for (int next = 0; next <= m; next++) { if (mask >> next & 1) continue; int new_mask = mask | 1 << next; dp[next][new_mask] = min( dp[next][new_mask], dp[last][mask] + w[last][next] ); } } } for (int i = 0; i <= m; i++) { fc[rmv][i] = INT_MAX; int mask = fullmask_m ^ 1 << i; for (int last = 0; last <= m; last++) { fc[rmv][i] = min(fc[rmv][i], dp[last][mask]); } } } int ans = INT_MAX; for (int i = 0; i <= n; i++) { for (int j = 0; j <= m; j++) { ans = min(ans, fr[i][j] + fc[i][j]); } } cout << ans << '\n'; } }
1993
F1
Dyn-scripted Robot (Easy Version)
\textbf{This is the easy version of the problem. The only difference is that in this version $k \le n$. You can make hacks only if both versions of the problem are solved.} Given a $w \times h$ rectangle on the $Oxy$ plane, with points $(0, 0)$ at the bottom-left and $(w, h)$ at the top-right of the rectangle. You also have a robot initially at point $(0, 0)$ and a script $s$ of $n$ characters. Each character is either L, R, U, or D, which tells the robot to move left, right, up, or down respectively. The robot can only move inside the rectangle; otherwise, it will change the script $s$ as follows: - If it tries to move outside a vertical border, it changes all L characters to R's (and vice versa, all R's to L's). - If it tries to move outside a horizontal border, it changes all U characters to D's (and vice versa, all D's to U's). Then, it will execute the changed script starting from the character which it couldn't execute. \begin{center} {\normalsize An example of the robot's movement process, $s = "ULULURD"$} \end{center} The script $s$ will be executed for $k$ times continuously. All changes to the string $s$ will be retained even when it is repeated. During this process, how many times will the robot move to the point $(0, 0)$ in total? \textbf{Note that the initial position does NOT count}.
Let the robot moves freely (no modification on the script). The new path of the robot is the "mirrored" version of how the robot must go. Imagine we have two robots, let's call them Alex and Bob. Alex is the one who follows the instruction well, but Bob doesn't (if he tries to move outside the box, he keeps going without modifying the script). Then, you follow the path of each robot that is moving. How do you think their paths differ from each other? Yes! Suppose at some moment they reach the top side of the box at the same time. Suddenly, Bob wants to move up while Alex know the discipline and modify the script before executing the command and move down. Then, each of them is $1$ unit away from the top side of the box. If Bob keeps moving up, Alex keep moving down. In case Bob changes his mind and move down then this time Alex changes her mind and move up. What do we learn from this? They move like two objects facing each other through a mirror. Actually there are four mirror of them, placing at the four sides of the box. Now, let's say Bob moves up so much that Alex follows the script and reaches the top side and the bottom side as well. Because of that, she has to change the script once again and start moving up like Bob. When Alex reaches the bottom side at point $(x, 0)$, then Bob should be at point $(x, 2H)$ (prove it yourself!). If Bob keeps moving up to the point $(x, 4H), (x, 6H), or (x, 8H), \dots$, at these moment Alex will also be at point $(x, 0)$. That being said, Alex's position is $(x, 0)$ then Bob's position must be $(x, y)$ where y is a multiple of $2H$. This idea is exactly the same as if Bob were moving sideways (left or right). As we only care about the number of times Alex's position is $(0, 0)$, we know that if we don't change the script at all, the position of the robot must be $(x, y)$ where $x$ is a multiple of $2W$, and $y$ is a multiple of $2H$. So apparently, we need to calculate the number of times the robot reaches $(x, y)$, where $x$ is a multiple of $2W$ and $y$ is a multiple of $2H$ (see the general idea above). Let's call $t_k = (x_k, y_k)$ how much the robot moves (in direction) after executing the first $k$ commands of the script. Then: $t_0 = (0, 0)$ and $t_k$ can be calculated through $t_{k-1}$ and $s_k$. The robot will execute the script $k$ times and the script contains $n$ commands, so we have $nk$ positions to check out. Each position can be represented by: $(x, y) = it_n + t_j = (ix_n + x_j, iy_n + y_j)$ (where $0\le i\le k-1$ and $1\le j\le n$). Besides, we need: $x\equiv 0\pmod{2W} \Longrightarrow ix_n + x_j\equiv 0\pmod{2W} \Longrightarrow x_j\equiv -ix_n\pmod{2W}$ $y\equiv 0\pmod{2H} \Longrightarrow iy_n + y_j\equiv 0\pmod{2H} \Longrightarrow y_j\equiv -iy_n\pmod{2H}$ Lastly, we can traverse all possible $i$ from $0$ to $k-1$ and count the number of $j$ that satisfies the above equivalence. One possible way to do this is to use a map to count each element in the array $t_1, t_2, \dots, t_n$. Summing all the counts will give the answer for this problem. Time complexity: $O((n + k)\log n)$
[ "brute force", "chinese remainder theorem", "constructive algorithms", "math", "number theory" ]
2,400
#include <bits/stdc++.h> using namespace std; using ll = long long; const int N = 1e6 + 5; string s; ll n, k, w, h; ll tx[2*N], ty[2*N]; map<pair<ll, ll>, ll> cnt; int main() { cin.tie(0)->sync_with_stdio(0); int t; cin >> t; while (t--) { cin >> n >> k >> w >> h >> s; cnt.clear(); ll x = 0, y = 0; for (int i = 0; i < n; i++) { if (s[i] == 'L') x--; if (s[i] == 'R') x++; if (s[i] == 'D') y--; if (s[i] == 'U') y++; x = (x + 2*w) % (2*w); y = (y + 2*h) % (2*h); cnt[{x, y}]++; } ll ans = 0; for (int i = 0; i < k; i++) { ll vx = (-i*x%(2*w) + 2*w)%(2*w); ll vy = (-i*y%(2*h) + 2*h)%(2*h); ans += cnt[{vx, vy}]; } cout << ans << '\n'; } }
1993
F2
Dyn-scripted Robot (Hard Version)
\textbf{This is the hard version of the problem. The only difference is that in this version $k \le 10^{12}$. You can make hacks only if both versions of the problem are solved.} Given a $w \times h$ rectangle on the $Oxy$ plane, with points $(0, 0)$ at the bottom-left and $(w, h)$ at the top-right of the rectangle. You also have a robot initially at point $(0, 0)$ and a script $s$ of $n$ characters. Each character is either L, R, U, or D, which tells the robot to move left, right, up, or down respectively. The robot can only move inside the rectangle; otherwise, it will change the script $s$ as follows: - If it tries to move outside a vertical border, it changes all L characters to R's (and vice versa, all R's to L's). - If it tries to move outside a horizontal border, it changes all U characters to D's (and vice versa, all D's to U's). Then, it will execute the changed script starting from the character which it couldn't execute. \begin{center} {\normalsize An example of the robot's movement process, $s = "ULULURD"$} \end{center} The script $s$ will be executed for $k$ times continuously. All changes to the string $s$ will be retained even when it is repeated. During this process, how many times will the robot move to the point $(0, 0)$ in total? \textbf{Note that the initial position does NOT count}.
The idea of this version is almost the same as F1: counting the number of pairs $(i, j)$ that satisfies: $ix_n + x_j\equiv 0\pmod{2W}$, and $iy_n + y_j\equiv 0\pmod{2H}$ However, as $k$ is increased to $10^{12}$ we cannot brute-force the same way as the previous version. Luckily, there is a more efficient way. We need to modify these equivalences a bit: $ix_n \equiv -x_j\pmod{2W}$ $(*)$ $iy_n \equiv -y_j\pmod{2H}$ As we can see, these two equivalences have the same format $ia \equiv b\pmod{M}$. To solve this equivalence for $i$, one way to hang around is to divide $a$, $b$ and $M$ by $\gcd(a, M)$. If $b$ is not divisible, there is no solution! Otherwise, we come up with: $i \equiv ba^{-1}\pmod{M}$ Where $a^{-1}$ is the modular inverse of $a$. We can always calculate it because the condition $\gcd(a, M)=1$ is satisfied. Let's define $g=\gcd(2W, x_n)$, $c_x = -\frac{x_j}g\left(\frac{x_n}g\right)^{-1}$ and $W'=\frac{2W}{g}$ (similar for $c_y$ and $H'$). Then, the solutions of the equivalences at $(*)$ are: $i\equiv c_x\pmod{W'}$ $i\equiv c_y\pmod{H'}$ This system of equivalences can be solved using Chinese Remainder Theorem. After some calculations, we come up with: $i=c_x + zW'$ ($z$ is a non-negative integer). $zW'\equiv c_y-c_x\pmod{H'}$ $(**)$ $(**)$ can be solved for $z$ the same way as $(*)$. Now we know the solution is $i \equiv c_x + zW' \pmod{lcm(W', H')}$, the last thing to do is to count number of such value doesn't exceed $k-1$ and we're done! Time complexity: $O(Nlog(W))$
[ "chinese remainder theorem", "math", "number theory" ]
2,800
#include <bits/stdc++.h> using namespace std; using ll = long long; namespace CRT { // v * inv(v, M) = 1 (mod M) ll inv(ll v, ll M) { ll a = 1, b = 0; for (ll x = v, y = M; x != 0; ) { swap(a, b -= y/x * a); swap(x, y -= y/x * x); } return b + (b<0) * M; } // Minimum x that ax = b (mod c) ll solve_1(ll a, ll b, ll c) { ll g = gcd(a, c); if (b % g != 0) return -1; return b/g * inv(a/g, c/g) % (c/g); } // Minimum x that x%b = a and x%d = c ll solve_2(ll a, ll b, ll c, ll d) { ll t = (c-a)%d; if (t < 0) t += d; ll k = solve_1(b, t, d); return k==-1 ? -1 : a + k*b; } } const int N = 1e6 + 5; ll n, k, w, h; ll x[N], y[N]; int main() { cin.tie(nullptr) -> sync_with_stdio(false); int tc; cin >> tc; while (tc--) { string s; cin >> n >> k >> w >> h >> s; for (int i = 1; i <= n; i++) { x[i] = x[i-1] + (s[i-1] == 'R') - (s[i-1] == 'L'); y[i] = y[i-1] + (s[i-1] == 'U') - (s[i-1] == 'D'); x[i] += (x[i] < 0) * 2*w - (x[i] >= 2*w) * 2*w; y[i] += (y[i] < 0) * 2*h - (y[i] >= 2*h) * 2*h; } ll ww = 2*w / gcd(x[n], 2*w); ll hh = 2*h / gcd(y[n], 2*h); ll ans = 0, l = lcm(ww, hh); for (int i = 1; i <= n; i++) { ll cx = CRT::solve_1(x[n], 2*w - x[i], 2*w); ll cy = CRT::solve_1(y[n], 2*h - y[i], 2*h); if (cx == -1 || cy == -1) continue; ll result = CRT::solve_2(cx, ww, cy, hh); if (result != -1 && result < k) { ans += (k - result - 1) / l + 1; } } cout << ans << '\n'; } }
1994
A
Diverse Game
Petr, watching Sergey's stream, came up with a matrix $a$, consisting of $n$ rows and $m$ columns (the number in the $i$-th row and $j$-th column is denoted as $a_{i, j}$), which contains all integers from $1$ to $n \cdot m$. But he didn't like the arrangement of the numbers, and now he wants to come up with a new matrix $b$, consisting of $n$ rows and $m$ columns, which will also contain all integers from $1$ to $n \cdot m$, such that for any $1 \leq i \leq n, 1 \leq j \leq m$ it holds that $a_{i, j} \ne b_{i, j}$. You are given the matrix $a$, construct \textbf{any} matrix $b$ that meets Petr's requirements, or determine that it is impossible. Hurry up! Otherwise, he will donate all his money to the stream in search of an answer to his question.
If $n = m = 1$, then there is only one possible matrix, so the answer is $-1$. Otherwise, at least one of the numbers $n, m$ is greater than $1$, then one of the solutions is, for example, a matrix $a$ with cyclically shifted rows (if $m > 1$) or columns (if $n > 1$).
[ "constructive algorithms", "greedy", "implementation" ]
800
#include<bits/stdc++.h> using namespace std; int main() { cin.tie(nullptr)->sync_with_stdio(false); int tests; cin >> tests; while (tests--) { int n, m; cin >> n >> m; vector<vector<int>> a(n, vector<int>(m)); for (auto &i: a) { for (auto &j: i) cin >> j; } if (n * m == 1) cout << "-1\n"; else { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cout << a[(i + 1) % n][(j + 1) % m] << ' '; } cout << '\n'; } } } }
1994
B
Fun Game
Vova really loves the XOR operation (denoted as $\oplus$). Recently, when he was going to sleep, he came up with a fun game. At the beginning of the game, Vova chooses two binary sequences $s$ and $t$ of length $n$ and gives them to Vanya. A binary sequence is a sequence consisting only of the numbers $0$ and $1$. Vanya can choose integers $l, r$ such that $1 \leq l \leq r \leq n$, and for all $l \leq i \leq r$ \textbf{simultaneously} replace $s_i$ with $s_i \oplus s_{i - l + 1}$, where $s_i$ is the $i$-th element of the sequence $s$. In order for the game to be interesting, there must be a possibility to win. Vanya wins if, with an \textbf{unlimited} number of actions, he can obtain the sequence $t$ from the sequence $s$. Determine if the game will be interesting for the sequences $s$ and $t$.
If the string $s$ consists entirely of $0$, then obviously no other string can be obtained from it, so the answer is "Yes" only if $s = t$. Otherwise, let $i$ - the index of the first $1$ in $s$. Note that if there is at least one $1$ in $t$ at positions $[1; i)$, then the answer is "No", since $s$ has $0$ at these positions, so some of them must be changed to $1$. However, when applying the operation the first $1$ from position $i$ can change bits only at positions greater than or equal to $i$, i.e. it will not be possible to change $0$ at positions before $i$. If there is only $0$ at positions $[1; i)$ in $t$, then it is possible to change any bit on the segment $[i; n]$ in $s$ to any other bit by choosing segments of length $i$ and acting from the end, i.e. the answer is "Yes".
[ "bitmasks", "constructive algorithms", "greedy", "math" ]
1,100
#include<bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; string s, t; cin >> s >> t; for (int i = 0; i < s.size() && s[i] == '0'; ++i) { if (t[i] != '0') { cout << "NO\n"; return; } } cout << "YES\n"; } int main() { int t; cin >> t; while (t--) solve(); }
1994
C
Hungry Games
Yaroslav is playing a computer game, and at one of the levels, he encountered $n$ mushrooms arranged in a row. Each mushroom has its own level of toxicity; the $i$-th mushroom from the beginning has a toxicity level of $a_i$. Yaroslav can choose two integers $1 \le l \le r \le n$, and then his character will take turns from left to right to eat mushrooms from this subsegment one by one, i.e., the mushrooms with numbers $l, l+1, l+2, \ldots, r$. The character has a toxicity level $g$, initially equal to $0$. The computer game is defined by the number $x$ — the maximum toxicity level at any given time. When eating a mushroom with toxicity level $k$, the following happens: - The toxicity level of the character is increased by $k$. - If $g \leq x$, the process continues; otherwise, $g$ becomes zero and the process continues. Yaroslav became interested in how many ways there are to choose the values of $l$ and $r$ such that the final value of $g$ is not zero. Help Yaroslav find this number!
We'll solve the problem by dynamic programming. Let $dp[i]$ - the number of good subsegments with left boundary at $i$. We will count $dp$ from the end, for each $i$ we will find such a minimum $j$ that the sum on the subsegment $[i; j]$ is greater than $x$. If there is no such $j$, then all right bounds are good, otherwise $dp[i] = dp[j + 1] + j - i$. To search for $j$, we can use a binary search on prefix sums. The answer will be the sum of all $dp$.
[ "binary search", "dp", "two pointers" ]
1,600
#include<bits/stdc++.h> using namespace std; using ll = long long; int main() { cin.tie(nullptr)->sync_with_stdio(false); int tests; cin >> tests; while (tests--) { int n; ll x; cin >> n >> x; vector<ll> a(n + 1); for (int i = 1; i <= n; ++i) cin >> a[i]; partial_sum(a.begin() + 1, a.end(), a.begin() + 1); vector<int> dp(n + 2); for (int i = n - 1; i >= 0; --i) { int q = upper_bound(a.begin(), a.end(), a[i] + x) - a.begin(); dp[i] = dp[q] + q - i - 1; } cout << accumulate(dp.begin(), dp.end(), 0ll) << '\n'; } }
1994
D
Funny Game
Vanya has a graph with $n$ vertices (numbered from $1$ to $n$) and an array $a$ of $n$ integers; initially, there are no edges in the graph. Vanya got bored, and to have fun, he decided to perform $n - 1$ operations. Operation number $x$ (operations are numbered in order starting from $1$) is as follows: - Choose $2$ different numbers $1 \leq u,v \leq n$, such that $|a_u - a_v|$ is divisible by $x$. - Add an undirected edge between vertices $u$ and $v$ to the graph. Help Vanya get a connected$^{\text{∗}}$ graph using the $n - 1$ operations, or determine that it is impossible. \begin{footnotesize} $^{\text{∗}}$A graph is called connected if it is possible to reach any vertex from any other by moving along the edges. \end{footnotesize}
Note that we have only $n - 1$ edges, so after each operation, the number of connectivity components must decrease by $1$. Since the order of operations is not important, we will perform the operations in reverse order. Then after the operation with number $x$, there will be $x + 1$ connectivity components in the graph. For each component, let's take any of its vertices $v$ and look at the number that corresponds to it. Note that we have chosen $x + 1$ numbers, so by the pigeonhole principle, some two numbers will be equal modulo $x$. This means that we find two vertices $u$ and $v$ from different components such that $|a_u - a_v|$ is a multiple of $x$. By drawing an edge between $u$ and $v$, we will achieve what we want - the number of connectivity components will become $1$ less. Now it remains to go through the operations in reverse order and print the answer.
[ "constructive algorithms", "dsu", "graphs", "greedy", "math", "number theory", "trees" ]
1,900
#include<bits/stdc++.h> using namespace std; int main() { int tests; cin >> tests; while (tests--) { int n; cin >> n; vector<int> a(n); for (auto& i : a) cin >> i; vector<int> pos(n); iota(pos.begin(), pos.end(), 0); vector<pair<int, int>> ans; for (int i = n - 1; i; --i) { vector<int> occ(i, -1); for (auto j : pos) { if (occ[a[j] % i] != -1) { ans.emplace_back(j, occ[a[j] % i]); pos.erase(find(pos.begin(), pos.end(), j)); break; } occ[a[j] % i] = j; } } reverse(ans.begin(), ans.end()); cout << "YES\n"; for (auto [x, y] : ans) cout << x + 1 << ' ' << y + 1 << '\n'; } }
1994
E
Wooden Game
You are given a forest of $k$ rooted trees$^{\text{∗}}$. Lumberjack Timofey wants to cut down the entire forest by applying the following operation: - Select a subtree$^{\text{†}}$ of any vertex of one of the trees and remove it from the tree. Timofey loves bitwise operations, so he wants the bitwise OR of the sizes of the subtrees he removed to be maximum. Help him and find the maximum result he can obtain. \begin{footnotesize} $^{\text{∗}}$ A tree is a connected graph without cycles, loops, or multiple edges. In a rooted tree, a selected vertex is called a root. A forest is a collection of one or more trees. $^{\text{†}}$ The subtree of a vertex $v$ is the set of vertices for which $v$ lies on the shortest path from this vertex to the root, including $v$ itself. \end{footnotesize}
We know that the maximal result from one tree is the size of this tree (see hints), but we can make every number from $1$ to the size of the tree. To do that, we can delete leaves until we have the needed value. So the remaining problem is to find the maximal OR if we can choose numbers from $1$ to $a_i$. For every bit, let's count the number of $a_i$, where this bit is set. Find the highest bit which is set in more than one number. Obviously, we can make a suffix of $1$-s from this position. Before this position we need to set bits that are set in one of $a_i$.
[ "bitmasks", "greedy", "math", "trees" ]
2,000
#include<bits/stdc++.h> using namespace std; void solve() { int k; cin >> k; vector<int> a(k); for (int i = 0; i < k; ++i) { cin >> a[i]; for (int j = 0; j < a[i] - 1; ++j) { int trash; cin >> trash; } } sort(a.begin(), a.end(), greater<>()); int ans = 0; for (auto x : a) { for (int h = 23; h >= 0; --h) { int ca = ans >> h & 1, cx = x >> h & 1; if (cx == 0) continue; if (ca == 0) ans |= 1 << h; else { ans |= (1 << h) - 1; break; } } } cout << ans << '\n'; } int main() { int t; cin >> t; while (t--) solve(); }
1994
F
Stardew Valley
Pelican Town represents $n$ houses connected by $m$ bidirectional roads. Some roads have NPCs standing on them. Farmer Buba needs to walk on each road with an NPC and talk to them. Help the farmer find a route satisfying the following properties: - The route starts at some house, follows the roads, and ends at the same house. - The route does not follow any road more than once (in both directions together). - The route follows each road with an NPC exactly once. Note that the route can follow roads without NPCs, and you do \textbf{not} need to minimize the length of the route.It is \textbf{guaranteed} that you can reach any house from any other by walking on the roads with NPCs only.
The edges with $0$ on them will be called black, the other edges will be called white. To find such a route, we need the graph to be Eulerian (degree of each vertex is even). To achieve this, we can remove some black edges. Let's calculate the degree of each vertex (further we will keep this degree in mind) and leave only black edges. Solve the problem independently for each component. If a component has an odd number of vertices with odd degree, we cannot remove edges so that all degrees become even (since removing an edge does not change the parity of the sum of degrees), so in this case the answer is NO. Otherwise, such a route exists. Leave only the spanning tree and run dfs on it. If we leave a vertex and it has an odd degree, we remove an edge to its ancestor. This will work since the sum of the degrees in the component is even. Finally, we need to find the Eulerian cycle in the resulting graph and print it.
[ "constructive algorithms", "dfs and similar", "graphs", "trees" ]
2,500
#include<bits/stdc++.h> using namespace std; int main() { cin.tie(nullptr)->sync_with_stdio(false); int tests; cin >> tests; while (tests--) { int n, m; cin >> n >> m; vector<vector<int>> black(n); vector<int> edg(m); vector<vector<int>> g(n); for (int i = 0; i < m; ++i) { int x, y, c; cin >> x >> y >> c; --x, --y; edg[i] = x ^ y; g[x].push_back(i); g[y].push_back(i); if (c == 0) { black[x].push_back(i); black[y].push_back(i); } } vector<int> deg(n); for (int i = 0; i < n; ++i) deg[i] = g[i].size() & 1; vector<bool> del(m, false), used(n, false); auto dfs = [&](auto dfs, int u) -> void { used[u] = true; for (auto id : black[u]) { int to = edg[id] ^ u; if (used[to]) continue; dfs(dfs, to); if (deg[to]) { del[id] = true; deg[to] ^= 1; deg[u] ^= 1; } } }; bool ok = true; for (int i = 0; i < n; ++i) { if (used[i]) continue; dfs(dfs, i); ok &= !deg[i]; } if (!ok) { cout << "NO\n"; continue; } auto euler = [&](auto euler, int u) -> void { while (!g[u].empty()) { int id = g[u].back(); g[u].pop_back(); int to = edg[id] ^ u; if (del[id]) continue; del[id] = true; euler(euler, to); } cout << u + 1 << ' '; }; cout << "YES\n"; cout << m - accumulate(del.begin(), del.end(), 0) << '\n'; euler(euler, 0); cout << '\n'; } }
1994
G
Minecraft
After winning another Bed Wars game, Masha and Olya wanted to relax and decided to play a new game. Masha gives Olya an array $a$ of length $n$ and a number $s$. Now Olya's task is to find a non-negative number $x$ such that $\displaystyle\sum_{i=1}^{n} a_i \oplus x = s$. But she is very tired after a tight round, so please help her with this. But this task seemed too simple to them, so they decided to make the numbers larger (up to $2^k$) and provide you with their binary representation.
We will do recursion. Let's go from the lower bits to the significant bits. $rec(i, sum)$ means that the first $i$ bits are selected, the sum of them divided by $2^i$ equals $sum$, and the first $i$ bits match the ones we need. Let $cnt_i$ - the number of ones in the numbers in the $i$-th bit. Then we can go from state $(i, sum)$ to $(i + 1, \lfloor \frac{sum + cnt_i}{2} \rfloor)$ and $(i + 1, \lfloor \frac{sum + n - cnt_i}{2} \rfloor)$ if the lowest bit matches the $i$-th bit in $s$. There are at most $nk$ states in such a recursion (proof below). Thus, if we do the memoization, the solution will run $O(nk)$. Proof: $sum$ is always at most $n$. At the beginning of the recursion, $sum = 0$, so the inequality is satisfied. When we go to the next step $\frac{sum + cnt_i}{2}$, $\frac{sum + n - cnt_i}{2} \leq \frac{n + n}{2} = n$, which was required to prove.
[ "bitmasks", "brute force", "dp", "graphs", "math" ]
2,600
#include <bits/stdc++.h> using namespace std; int n, k; vector<vector<bool>> memo; string res; vector<int> cnt; string s; bool rec(int i, int cur) { if (i == k) { if (cur == 0) { return true; } return false; } if (memo[i][cur]) return false; memo[i][cur] = true; for (int c = 0; c < 2; ++c) { int q = cur; if (c == 0) q += cnt[i]; else q += n - cnt[i]; if ((q & 1) == s[i] - '0') { if (rec(i + 1, q / 2)) { res += char(c + '0'); return true; } } } return false; } int main() { cin.tie(nullptr)->sync_with_stdio(false); int tests; cin >> tests; while (tests--) { cin >> n >> k; cin >> s; reverse(s.begin(), s.end()); cnt = vector<int>(k); for (int i = 0; i < n; ++i) { string t; cin >> t; reverse(t.begin(), t.end()); for (int j = 0; j < k; ++j) cnt[j] += t[j] - '0'; } memo = vector<vector<bool>>(k, vector<bool>(n, false)); res = ""; rec(0, 0); if (res.empty()) cout << "-1\n"; else cout << res << '\n'; } }
1994
H
Fortnite
\textbf{This is an interactive problem!} Timofey is writing a competition called Capture the Flag (or CTF for short). He has one task left, which involves hacking a security system. The entire system is based on polynomial hashes$^{\text{∗}}$. Timofey can input a string consisting of lowercase Latin letters into the system, and the system will return its polynomial hash. To hack the system, Timofey needs to find the polynomial hash parameters ($p$ and $m$) that the system uses. Timofey doesn't have much time left, so he will only be able to make $3$ queries. Help him solve the task. \begin{footnotesize} $^{\text{∗}}$ The polynomial hash of a string $s$, consisting of lowercase Latin letters of length $n$, based on $p$ and modulo $m$ is $(\mathrm{ord}(s_1) \cdot p ^ 0 + \mathrm{ord}(s_2) \cdot p ^ 1 + \mathrm{ord}(s_3) \cdot p ^ 2 + \ldots + \mathrm{ord}(s_n) \cdot p ^ {n - 1}) \bmod m$. Where $s_i$ denotes the $i$-th character of the string $s$, $\mathrm{ord}(\mathrm{chr})$ denotes the ordinal number of the character $\mathrm{chr}$ in the English alphabet, and $x \bmod m$ is the remainder of $x$ when divided by $m$. \end{footnotesize}
The first query is $aa$, it can be used to find out $p$. The second query is $zzzzzzzzzz$, let's calculate its hash without modulus, denote h_1, hash with modulus denote a1. Suppose we get a string with hash without modulus from $h_1 - a_1 - m$ to $h_1 - a_1 - 1$, then if we query it, we can easily find out the modulus. Let's find such a string. To do this, let's write $h_1$ in $p$-ary number system, we get $26, 26, .... 26$, and also write $(a1 + 1)$ in $p$-ary notation. Subtract the second one from the first one without transfers, take the leftmost position, where we get $< 1$, and put there and in all the left $26$, as long as the number on the left is $1$, put $26$ in it and stand in it, when the number on the left is not $1$, we just subtract 1 from it. After that we translate it all back into a string. It is claimed that this string fits, let's prove it. Its hash without modulus is obviously not greater than $h_1 - a_1 - 1$. Let's consider $2$ digits, the one in which we made $-1$ and $1$ to the left, let the number of the left digit $i$, then $a_1 + 1 \geq 25 * p^i$, and we subtracted less than $p^{i + 1} - 25 * p^i$, less because either in $i$ that digit was $0$, or $0$ was somewhere to the left, so there could be no equality, $p \leq 50$ by convention, $\geq p^{i + 1} - 25 * p^i \leq 50 * p^i - 25 * p^i = 25 * p^i \leq a_1 + 1$ => we subtracted less than $a_1 + 1$ => not more than $a_1$ => less than m. Let's denote what we subtracted by $x$, then our hash is $h_1 - a_1 - 1 - x = h_1 - a_1 - (x + 1)$. $x < m$ => $x + 1 \leq m$ => $hash \geq h1 - a1 - m$, which is what we needed to prove.
[ "combinatorics", "constructive algorithms", "games", "greedy", "hashing", "interactive", "math", "number theory", "strings" ]
3,500
#include <bits/stdc++.h> using namespace std; using ll = long long; void solve() { cout << "? aa" << endl; int p, v[10]; cin >> p; p--; cout << "? zzzzzzzzzz" << endl; int hsh, hsho; ll nom = 0, cnt = 1; cin >> hsh; hsho = hsh; hsh++; for (int i = 0; i < 10; i++) { nom += 26 * cnt; cnt *= p; v[i] = 26 - (hsh % p); hsh /= p; } string s; cnt = 1; ll ch = 0; for (int i = 0; i < 10; i++) { if (v[i] < 1) { v[i] = 26; v[i + 1]--; } ch += cnt * v[i]; cnt *= p; s += 'a' + (v[i] - 1); } cout << "? " << s << endl; int ans; cin >> ans; cout << "! " << p << ' ' << ans + nom - ch - hsho << endl; } int32_t main() { int t; cin >> t; while (t--) { solve(); } }
1995
A
Diagonals
Vitaly503 is given a checkered board with a side of $n$ and $k$ chips. He realized that all these $k$ chips need to be placed on the cells of the board (no more than one chip can be placed on a single cell). Let's denote the cell in the $i$-th row and $j$-th column as $(i ,j)$. A diagonal is the set of cells for which the value $i + j$ is the same. For example, cells $(3, 1)$, $(2, 2)$, and $(1, 3)$ lie on the same diagonal, but $(1, 2)$ and $(2, 3)$ do not. A diagonal is called occupied if it contains at least one chip. Determine what is the minimum possible number of occupied diagonals among all placements of $k$ chips.
How many described diagonals are there in total? How many cells do they contain? In total we have $2 n - 1$ diagonals. There is only one diagonal that contains $n$ cells, two containing $n - 1$ cells, ..., and two containing only one cell each (namely passing through $(1, n)$ and $(n, 1)$). Obviously, in this case, it is worth filling the largest diagonal with chips, then two that are smaller in size, and so on. The asymptotics turns out to be $O(n)$.
[ "brute force", "greedy", "implementation", "math" ]
800
def solver(): n, k = map(int, input().split()) a, b = n, n - 1 ans = 0 while k > 0: k -= a ans += 1 a, b = b, (b if a != b else b - 1) print(ans) t = int(input()) for _ in range(t): solver()
1995
B1
Bouquet (Easy Version)
\textbf{This is the easy version of the problem. The only difference is that in this version, the flowers are specified by enumeration.} A girl is preparing for her birthday and wants to buy the most beautiful bouquet. There are a total of $n$ flowers in the store, each of which is characterized by the number of petals, and a flower with $k$ petals costs $k$ coins. The girl has decided that the difference in the number of petals between any two flowers she will use in her bouquet should not exceed one. At the same time, the girl wants to assemble a bouquet with the maximum possible number of petals. Unfortunately, she only has $m$ coins, and she cannot spend more. What is the maximum total number of petals she can assemble in the bouquet?
For each number of petals, we can bruteforce the answer for $x, x + 1$ First, we can aggregate number of flowers with $x$ petals into $c_{x}$ (for example, sort the array and then create array of pairs $(x, c_{x})$, where $c_{x}$ is the length of segment with elements equal to $x$). Note that $\sum_{x} c_{x} = n$. Also note that for every $x$ we won't need more than $\left\lfloor\frac{m}{x}\right\rfloor$ flowers (otherwise total number of petals will exceed $m$). Then we iterate through all $x$. Suppose that we want to assemble a bouquet with $x, x + 1$ petals. We can bruteforce the amount of flowers with $x$ petals in $O(c_{x})$. If we have $0 \le k_1 \le min(c_{x}, \left\lfloor\frac{m}{x}\right\rfloor)$ flowers with $x$ petals, we already have $k_1 * x$ petals. There are still $m - k_1 * x$ coins which we can spend for flowers with $x + 1$ petals. There are at most $k_2 = min(c_{x + 1}, \left\lfloor\frac{m - k_1 * x}{x + 1}\right\rfloor)$ flowers with $x + 1$ petal we can buy. So we need to find maximum over all such $k_1 * x + k_2 * (x + 1)$. Total complexity is $O(\sum_{x} c_{x}) = O(n)$ for finding the maximum and $O(n \log n)$ for sorting.
[ "binary search", "brute force", "greedy", "sortings", "two pointers" ]
1,100
tests = int(input()) p = 10 ** 9 + 7 def pow(x, q): if q == 0: return 1 i = pow(x, q // 2) if q % 2 == 0: return (i * i) % p return (i * i * x) % p def solve(): global p n, m = map(int, input().split(" ")) a = list(map(int, input().split(" "))) hs = {} for x in a: if x not in hs: hs[x] = 0 hs[x] += 1 ans = 0 for x in hs: y = hs[x] l = min(m // x, y) ans = max(ans, l * x) if x + 1 not in hs: continue z = hs[x + 1] for i in range(1, y + 1): if i * x > m: break du = m - i * x su = min(du // (x + 1), z) * (x + 1) + i * x ans = max(su, ans) print(ans) for _ in range(tests): solve()
1995
B2
Bouquet (Hard Version)
\textbf{This is the hard version of the problem. The only difference is that in this version, instead of listing the number of petals for each flower, the number of petals and the quantity of flowers in the store is set for all types of flowers.} A girl is preparing for her birthday and wants to buy the most beautiful bouquet. There are a total of $n$ different types of flowers in the store, each of which is characterized by the number of petals and the quantity of this type of flower. A flower with $k$ petals costs $k$ coins. The girl has decided that the difference in the number of petals between any two flowers she will use to decorate her cake should not exceed one. At the same time, the girl wants to assemble a bouquet with the maximum possible number of petals. Unfortunately, she only has $m$ coins, and she cannot spend more. What is the maximum total number of petals she can assemble in the bouquet?
Maybe there is a way to change bruteforce into checking optimal values for counts of $x, x + 1$? Maybe there are only few types of optimal bouquets for $x, x + 1$? We already have a list of $c_x$. We can use hash map to be able to check for any $c_x$ by $x$. We again will try to assemble the bouquet only with flowers with $x, x + 1$ petals. We set $k1 = min(c_{x}, \left\lfloor\frac{m}{x}\right\rfloor)$. Then we have $coins = m - k1 * x$. Let's set $k2 = min(c_{x + 1}, \left\lfloor\frac{coins}{x + 1}\right\rfloor)$. Then we have $coins = m - (k1 * x + k2 * (x + 1))$. Let's substitute flower with $x$ petals with flower with $x + 1$ petals as many times as we can. This can be done $r = min(k1, c_{x + 1} - k2, coins)$ times, as each operation will require us 1 coin, 1 flower in the bouquet with $x$ petals and one 1 flower with $x + 1$ petals not in the bouquet. In total we can get $(k1 - r) * x + (k2 + r) * (x + 1)$ petals. This assembling is optimal. Here is why. Suppose that we have $0 \le b1 \le c_{x}$ flowers with $x$ petals and $0 \le b2 \le c_{x + 1}$ flowers with $x + 1$ petals and greater total value of $b1 * x + b2 * (x + 1)$. We already know that $b1 \le k1$ by choosing of $k1$. If $k1 - r < b1$, then we can ''undo'' our operation $r + b1 - k1$ times, sum is still not greater than $m$, and we know that now there can't be more than $k2 + r + b1 - k1$ flowers with $x + 1$ petals, as otherwise we didn't chose optimal $k2$. If $k2 + r < b2$, then $r \ne c_{x + 1} - k2$, if $r = k1$ then it is just the case when we have only flowers with $x + 1$ petals which will be considered in case $x + 1, x + 2$, if $r = coins$ then $m = (k1 - r) * x + (k2 + r) * (x + 1)$ and we already found the maximum. So $b2 \le k2 + r$ and $b1 \le k1 - r$ and $b1 * x + b2 * (x + 1)$ is not better than optimal. Total time complexity is $O(n)$.
[ "binary search", "data structures", "greedy", "math", "sortings", "two pointers" ]
1,700
def solve(): n, m = map(int, input().split(" ")) a = list(map(int, input().split(" "))) c = list(map(int, input().split(" "))) ch = {} ans = 0 for a1, c1 in zip(a, c): if a1 not in ch: ch[a1] = 0 ch[a1] += c1 for x, c_x in ch.items(): ans = max(ans, min(m // x, c_x) * x) if x + 1 in ch: c_x1 = ch[x + 1] k1 = min(m // x, c_x) pred = x * k1 c_x -= k1 coins = m - pred if coins >= x + 1: k2 = min(coins // (x + 1), c_x1) pred += k2 * (x + 1) c_x1 -= k2 coins = m - pred ans = max(ans, min(m // (x + 1), c_x1)) pred += min([coins, c_x1, k1]) ans = max(pred, ans) print(ans) def main(): tests = int(input()) for _ in range(tests): solve() main()
1995
C
Squaring
ikrpprpp found an array $a$ consisting of integers. He likes justice, so he wants to make $a$ fair — that is, make it non-decreasing. To do that, he can perform an act of justice on an index $1 \le i \le n$ of the array, which will replace $a_i$ with $a_i ^ 2$ (the element at position $i$ with its square). For example, if $a = [2,4,3,3,5,3]$ and ikrpprpp chooses to perform an act of justice on $i = 4$, $a$ becomes $[2,4,3,9,5,3]$. What is the minimum number of acts of justice needed to make the array non-decreasing?
How many times we need to apply the operation to index $i$, so that $a[i - 1] \leq a[i]$? Let's call it $op[i]$ It's easy to calculate these values in no time. Can we just accumulate them? We almost can. But, let's take $[4, 2, 4]$ as an example. op[2] = 1, but we don't want to do anything with a[3]. So, sometimes $a[i - 1] \le a[i]$ and we may not want touch a[i] at all, even if something was applied before it. So, should we consider making $op[i] < 0$ for some $i$? Let's set $op[i]$ to the number of operation we need to apply to index $i$ so that $a[i - 1] \leq a[i]$. But, if $a[i - 1] \ll a[i]$, let's set it to the negative number of times that we can apply the operation to $a[i - 1]$ so that $a[i - 1] \leq a[i]$ still holds. Now let's just calculate the prefix sum $\texttt{prefix_op}$, don't forget to do $\max(0, \texttt{prefix_op}[i])$. The sum of values in $\texttt{prefix_op}$ is the answer. Let's try to go to the logarithmic space to get rid of too big numbers. $\log(x * x) = 2\log(x)$ So, if we replace each value with its logarithm, the operation of squaring becomes multiplying by 2. But this is not good enough, since we may need to do the operation thousands of times, $2^{1000}$ is too big, it doesn't fit into any floating point. So, let's just repeat our trick and go to the log-log space $\log(2 * y) = \log(y) + \log(2)$ Now we see that the operation turns into just adding $\log(2)$. We can afford doing that thousands and millions of times. Let's deine $b[i] = \log{\log{a[i]}}$ So now, we can just go with a for-loop and do $\displaystyle{\left\lceil\frac{b[i] - b[i - 1]}{\log(2)}\right\rceil}$ opeartions with $i$-th element, updating $b[i]$ accordingly. Since initially $b[i] \leq \log(10^6) \leq 20 \log(2)$, we can maintain the invariant that $b[i] \leq (20 + i)\log(2)$ since after applying an operation to $b[i]$ we can't exceed $b[i - 1]$ by more than $\log(2)$. It means that the final numbers in the log-log space won't exceed $(n + 20)\log(2)$. We can maintain $O(n)$ arithmetics using double without any problems.
[ "brute force", "constructive algorithms", "greedy", "implementation", "math", "number theory" ]
1,800
#include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; typedef pair<ll, ll> pll; typedef pair<int, int> pii; const long long kk = 1000; const long long ml = kk * kk; const long long mod = ml * kk + 7; const long long inf = ml * ml * ml + 7; const ld eps = 1e-9; int n; vector<ld> v; void solve() { cin >> n; v.resize(n); for (auto &i : v) cin >> i; reverse(v.begin(), v.end()); while (v.size() && v.back() == 1) v.pop_back(); reverse(v.begin(), v.end()); for (auto i : v) if (i == 1) { cout << "-1\n"; return; } for (auto &i : v) i = log(log(i)); ll ans = 0; for (int i = 1; i < v.size(); i++) { ld need = v[i - 1] - v[i]; if (need > eps) { int cnt = 1 + (need - eps) / log(2); ans += cnt; v[i] += cnt * log(2); } } cout << ans << '\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; cin >> t; while (t--) solve(); }
1995
D
Cases
You're a linguist studying a mysterious ancient language. You know that - Its words consist only of the first $c$ letters of the Latin alphabet. - Each word has a case which can be unambiguously determined by its last letter (different letters correspond to different cases). For example, words "ABACABA" and "ABA" (if they exist) have the same case in this language because they both have the same ending 'A', whereas "ALICE" and "BOB" have different cases. If the language does not have a case corresponding to some letter, it means that the word cannot end with this letter. - The length of each word is $k$ or less. You have a single text written in this language. Unfortunately, as the language is really ancient, spaces between words are missing and all letters are uppercase. You wonder what is the minimum number of cases the language can have. Can you find this out?
If letter is chosen as an ending to some case, each occurrence of this letter may in the text can be considered an ending? The length of the word is something too complex. How can you simplify the restriction? The final letter must be an ending of some case and among any $k$ consecutive letters there must be at least one ending. Now you don't need the text because you can store bitmasks instead of substrings of length $k$. To calculate the bitmasks you can use prefix sums for each of the characters (it will take $O(cn)$ overall). Now you need to find a bitmask with a minimal number of ones which intersects all the stored bitmasks. Identify "bad" bitmask instead of "good" ones. (Read the hints.) $b$ is bad if there exists stored $a$ such that $a \text{&} b = 0$ which is equivalent to $b$ being a submask of $\text{~}a$. All such b can be found using simple dp on bitmasks. The rest $b$ are good. Time complexity: $O(c n + c 2^c)$
[ "bitmasks", "brute force", "dp", "strings" ]
2,300
#include <bits/stdc++.h> using namespace std; void solve() { int n, c, k; cin >> n >> c >> k; string s; cin >> s; vector<vector<int>> cumsums(c, vector<int>(n + 1)); for (int i = 0; i < c; ++i) for (int j = 0; j < n; ++j) cumsums[i][j + 1] = cumsums[i][j] + (s[j] == i + 'A'); vector<bool> bms(1 << c); for (int lo = 0; lo <= n - k; ++lo) { int ms = 0; for (int i = 0; i < c; ++i) if (cumsums[i][lo + k] - cumsums[i][lo] != 0) ms |= (1 << i); bms[ms] = true; } bms[1 << (s.back() - 'A')] = true; vector<bool> bad(1 << c); for (int i = 0; i < (1 << c); ++i) bad[i] = bms[((1 << c) - 1) ^ i]; for (int bm = (1 << c) - 1; bm >= 0; --bm) for (int b = 0; b < c; ++b) bad[bm] = bad[bm | (1 << b)] | bad[bm]; int res = 1'000'000'000; for (int i = 0; i < (1 << c); ++i) if (!bad[i]) res = min(res, __builtin_popcount(i)); cout << res << '\n'; } signed main() { std::ios_base::sync_with_stdio(false); cin.tie(nullptr); int t = 1; cin >> t; while (t--) solve(); return 0; }
1995
E1
Let Me Teach You a Lesson (Easy Version)
\textbf{This is the easy version of a problem. The only difference between an easy and a hard version is the constraints on $t$ and $n$. You can make hacks only if both versions of the problem are solved.} Arthur is giving a lesson to his famous $2 n$ knights. Like any other students, they're sitting at the desks in pairs, but out of habit in a circle. The knight $2 i - 1$ is sitting at the desk with the knight $2 i$. Each knight has intelligence, which can be measured by an integer. Let's denote the intelligence of the $i$-th knight as $a_i$. Arthur wants the maximal difference in total intelligence over all pairs of desks to be as small as possible. More formally, he wants to minimize $\max\limits_{1 \le i \le n} (a_{2 i - 1} + a_{2 i}) - \min\limits_{1 \le i \le n} (a_{2 i - 1} + a_{2 i})$. However, the Code of Chivalry only allows swapping the opposite knights in the circle, i.e., Arthur can simultaneously perform $a_i := a_{i + n}$, $a_{i + n} := a_i$ for any $1 \le i \le n$. Arthur can make any number of such swaps. What is the best result he can achieve?
Consider cases of odd and even $n$. Which one is simpler? Even. In this case you can solve the problem for the opposite desks independently. From now on $n$ is odd. Let a desk have knights with intelligence $a$, $b$ and the opposite one with $c$, $d$. Since $(a + b) + (c + d) = (a + c) + (b + d)$, the minimal total intelligence on these desks is greater iff the maximal total intelligence is less. If you reorder desks/knights in a way that you swap neighbors (i.e. $2$ with $3$, $4$ with $5$, ..., $2 n$ with $1$) instead of opposite knights, it'll probably become easier to think about this problem. We will use this notation from now on. You're allowed to run in $O(n^2)$. Wouldn't it have sense to fix some entity and solve in linear time for fixed entity? Fix the minimal (maximal) desk and the knights who are sitting at it (if the original knights were swapped or not). You'll need to find the minimal maximum on a desk for $4 n$ such cases. DP. (Read the hints.) Let the fixed desk have index $k$. Let $dp_{i, b}$ (where $i$ is the index of the desk and $b$ is $0$ / $1$ which indicates whether the knight $2 i$ was swapped) be the minimal maximum that can be achieved on a segment from $k$ to $i$ (satisfying bit $b$ and the fact that the desk $k$ is actually minimal). Then you can easily make transitions $dp_{i, 0}, dp_{i, 1} \to dp_{i + 1, 0}, dp_{i + 1, 1}$. In the end you'll just need to check $dp_{k - 1, b'}$ where $b'$ indicates whether the knight $2 * k - 1$ was swapped in our choice. (All the indices for the desks are taken modulo $n$ and all the indices for the knights are taken modulo $2 n$.) Time complexity: $O(n^2)$, but the constant is large and $O(n^2\log n)$ solutions with binary search are unlikely to pass.
[ "2-sat", "data structures", "dp", "matrices", "two pointers" ]
2,700
#include <bits/stdc++.h> using namespace std; constexpr int VB = 2'000'000'001; void solve() { #define M(x) (((x) + 2 * n) % (2 * n)) int n; cin >> n; vector<int> v(2 * n); for (auto &e: v) { cin >> e; } if (n % 2 == 0) { int ma = 0; int mi = VB; for (int i = 0; i < n / 2; ++i) { int s[4]{v[2 * i] + v[2 * i + 1], v[2 * i] + v[2 * i + n + 1], v[2 * i + n] + v[2 * i + n + 1], v[2 *i + n] + v[2 * i + 1] }; sort(s, s + 4); ma = max(ma, s[2]); mi = min(mi, s[1]); } cout << ma - mi << '\n'; return; } if (n == 1) { cout << 0 << '\n'; return; } vector<int> r; int cur = 0; for (int i = 0; i < n; ++i) { r.push_back(v[cur]); r.push_back(v[cur ^= 1]); cur = M(cur + n); } int ans = VB; for (int id = 0; id < n; ++id) { for (int m1 = 0; m1 < 2; ++m1) { for (int m2 = 0; m2 < 2; ++m2) { int mi_value = r[M(2 * id - m1)] + r[M(2 * id + 1 + m2)]; vector<int> dp[2]{ vector<int>(n, VB), vector<int>(n, VB)}; dp[m2][id] = mi_value; for (int j = 1; j < n; ++j) { int jd = (id + j) % n; int pd = (id + j - 1) % n; for (int pc = 0; pc < 2; ++pc) { for (int jc = 0; jc < 2; ++jc) { if (dp[pc][pd] != VB && r[M(2 * jd - pc)] + r[M(2 * jd + 1 + jc)] >= mi_value) dp[jc][jd] = min(dp[jc][jd], max(dp[pc][pd], r[M(2 * jd - pc)] + r[M(2 * jd + 1 + jc)])); } } } int pd = (id + n - 1) % n; if (dp[m1][pd] != VB) ans = min(ans, dp[m1][pd] - mi_value); } } } cout << ans << '\n'; } signed main() { std::ios_base::sync_with_stdio(false); cin.tie(nullptr); int t = 1; cin >> t; while (t--) solve(); return 0; }
1995
E2
Let Me Teach You a Lesson (Hard Version)
\textbf{This is the hard version of a problem. The only difference between an easy and a hard version is the constraints on $t$ and $n$. You can make hacks only if both versions of the problem are solved.} Arthur is giving a lesson to his famous $2 n$ knights. Like any other students, they're sitting at the desks in pairs, but out of habit in a circle. The knight $2 i - 1$ is sitting at the desk with the knight $2 i$. Each knight has intelligence, which can be measured by an integer. Let's denote the intelligence of the $i$-th knight as $a_i$. Arthur wants the maximal difference in total intelligence over all pairs of desks to be as small as possible. More formally, he wants to minimize $\max\limits_{1 \le i \le n} (a_{2 i - 1} + a_{2 i}) - \min\limits_{1 \le i \le n} (a_{2 i - 1} + a_{2 i})$. However, the Code of Chivalry only allows swapping the opposite knights in the circle, i.e., Arthur can simultaneously perform $a_i := a_{i + n}$, $a_{i + n} := a_i$ for any $1 \le i \le n$. Arthur can make any number of such swaps. What is the best result he can achieve?
Read the first two hints to E1. There are $4 n$ possible desks in total. One of them will be the minimal desk and another one will be the maximal. What is the common-used technique for such problems? Sort them and then use two pointers. The data structure you need is very famous. (Read the hints.) Assign a boolean matrix $2 \times 2$ to each of the desks. Rows correspond to the first knight at the desk (two rows for each of the events "the knight was swapped" / "the knight was not swapped"), columns correspond to the second one. The value in the intersection is true if under current restrictions (minimum and maximum) both events can happen, i.e. the result on the desk is between minimum and maximum. What is a (boolean) multiplication of matrices from $d_l$ to $d_r$? The matrix where the rows correspond to the knight $2 d_l - 1$ and the columns correspond to the knight $2 d_r$. To determine whether it's possible to swap the knights under current restrictions you can just multiply all the matrices and check if there are ones on the main diagonal. Now using two pointers and a segment tree on these matrices you can solve the problem (basically, when you leave some option for a desk in the sorted array of options, you change one of the values of this matrix from $1$ to $0$, and vice versa).
[ "data structures", "dp", "matrices", "two pointers" ]
2,900
#include <bits/stdc++.h> using namespace std; struct desk { bool t[2][2]{}; desk() = default; desk(bool t11, bool t01, bool t10, bool t00) : t{{t00, t01}, {t10, t11}} { } }; desk operator*(const desk &a, const desk &b) { desk c {a.t[1][1] && b.t[1][1] || a.t[1][0] && b.t[0][1], a.t[0][1] && b.t[1][1] || a.t[0][0] && b.t[0][1], a.t[1][1] && b.t[1][0] || a.t[1][0] && b.t[0][0], a.t[0][0] && b.t[0][0] || a.t[0][1] && b.t[1][0]}; return c; } constexpr int shift = 1 << 17; desk sg[shift << 1]; void sg_set(int index, const desk &d) { index += shift; sg[index] = d; do { index >>= 1; sg[index] = sg[index * 2] * sg[index * 2 + 1]; } while (index > 1); } void sg_clear(int n_indices) { for (int i = 0; i < n_indices; ++i) { sg_set(i, {}); } } desk sg_get(int index) { return sg[index + shift]; } desk sg_get(int lo, int hi) { std::function<desk(int, int)> inner = [&inner](int lo, int hi) -> desk { if (lo == hi - 1) return sg[lo]; if (lo % 2) return sg[lo] * inner(lo + 1, hi); if (hi % 2) return inner(lo, hi - 1) * sg[hi - 1]; return inner(lo / 2, hi / 2); }; return inner(lo + shift, hi + shift); } struct desk_poss { int val = 0; int m1 = 0; int m2 = 0; int di = 0; desk_poss(int val, int m1, int m2, int di) : val(val), m1(m1), m2(m2), di(di) { } }; void solve() { int n; cin >> n; vector<int> v(2 * n); for (auto &e: v) { cin >> e; } if (n % 2 == 0) { int ma = 0; int mi = 2'000'000'001; for (int i = 0; i < n / 2; ++i) { int s[4]{v[2 * i] + v[2 * i + 1], v[2 * i] + v[2 * i + n + 1], v[2 * i + n] + v[2 * i + n + 1], v[2 *i + n] + v[2 * i + 1] }; sort(s, s + 4); ma = max(ma, s[2]); mi = min(mi, s[1]); } cout << ma - mi << '\n'; return; } if (n == 1) { cout << 0 << '\n'; return; } vector<int> r; int cur = 0; for (int i = 0; i < n; ++i) { r.push_back(v[cur]); r.push_back(v[cur ^= 1]); cur = (cur + n) % (2 * n); } vector<desk_poss> posses; for (int d = 0; d < n; ++d) { posses.emplace_back(r[2 * d] + r[2 * d + 1], 1, 1, d); posses.emplace_back(r[(2 * d + 2 * n - 1) % (2 * n)] + r[2 * d + 1], 0, 1, d); posses.emplace_back(r[(2 * d + 2 * n - 1) % (2 * n)] + r[(2 * d + 2) % (2 * n)], 0, 0, d); posses.emplace_back(r[2 * d] + r[(2 * d + 2) % (2 * n)], 1, 0, d); } sg_clear(n); sort(posses.begin(), posses.end(), [](const auto &a,const auto &b) { return a.val < b.val; }); int loi = 0; int hii = 0; int ans = 2'000'000'001; while (true) { auto d = sg_get(0, n); if (d.t[0][0] || d.t[1][1]) { auto lop = posses[loi]; ans = min(ans, posses[hii - 1].val - lop.val); auto extr = sg_get(lop.di); extr.t[lop.m1][lop.m2] = false; sg_set(lop.di, extr); ++loi; } else { if (hii == 4 * n) break; auto hip = posses[hii]; auto extr = sg_get(hip.di); extr.t[hip.m1][hip.m2] = true; sg_set(hip.di, extr); ++hii; } } cout << ans << '\n'; } signed main() { std::ios_base::sync_with_stdio(false); cin.tie(nullptr); int t = 1; cin >> t; while (t--) solve(); return 0; }
1996
A
Legs
It's another beautiful day on Farmer John's farm. After Farmer John arrived at his farm, he counted $n$ legs. It is known only chickens and cows live on the farm, and a chicken has $2$ legs while a cow has $4$. What is the minimum number of animals Farmer John can have on his farm assuming he counted the legs of all animals?
If $n$ is a multiple of $4$, then you can have $\frac{n}{4}$ cows. Otherwise, you must have at least one chicken, so you can have $\frac{n-2}{4}$ cows and $1$ chicken.
[ "binary search", "math", "ternary search" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int tc; cin >> tc; while (tc--){ int n; cin >> n; cout << (n + 2) / 4 << "\n"; } }
1996
B
Scale
Tina has a square grid with $n$ rows and $n$ columns. Each cell in the grid is either $0$ or $1$. Tina wants to reduce the grid by a factor of $k$ (\textbf{$k$ is a \underline{divisor} of $n$}). To do this, Tina splits the grid into $k \times k$ nonoverlapping blocks of cells such that every cell belongs to exactly one block. Tina then replaces each block of cells with a single cell equal to the value of the cells in the block. \textbf{It is guaranteed that every cell in the same block has the same value}. For example, the following demonstration shows a grid being reduced by factor of $3$. \begin{center} \textbf{Original grid} \begin{tabular}{|c||c||c||c||c||c|} \hline $0$ & $0$ & $0$ & $1$ & $1$ & $1$ \ \hline \hline $0$ & $0$ & $0$ & $1$ & $1$ & $1$ \ \hline \hline $0$ & $0$ & $0$ & $1$ & $1$ & $1$ \ \hline \hline $1$ & $1$ & $1$ & $0$ & $0$ & $0$ \ \hline \hline $1$ & $1$ & $1$ & $0$ & $0$ & $0$ \ \hline \hline $1$ & $1$ & $1$ & $0$ & $0$ & $0$ \ \hline \end{tabular} \end{center} \begin{center} \textbf{Reduced grid} \begin{tabular}{|c||c|} \hline $0$ & $1$ \ \hline \hline $1$ & $0$ \ \hline \end{tabular} \end{center} Help Tina reduce the grid by a factor of $k$.
Let's define every $k$ by $k$ block of cells by its value in the top left corner, since all cells in the block must have the same value. So, we can just print out the value of the cell in every $k$'th row and every $k$'th column.
[ "greedy", "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int tc; cin >> tc; while (tc--){ int n, k; cin >> n >> k; char A[n][n]; for (auto &row : A) for (char &c : row) cin >> c; for (int i = 0; i < n; i += k){ for (int j = 0; j < n; j += k){ cout << A[i][j]; } cout << "\n"; } } }
1996
C
Sort
You are given two strings $a$ and $b$ of length $n$. Then, you are (forced against your will) to answer $q$ queries. For each query, you are given a range bounded by $l$ and $r$. In one operation, you can choose an integer $i$ ($l \leq i \leq r$) and set $a_i = x$ where $x$ is any character you desire. Output the minimum number of operations you must perform such that $sorted(a[l..r]) = sorted(b[l..r])$. \textbf{The operations you perform on one query does not affect other queries.} For an arbitrary string $c$, $sorted(c[l..r])$ denotes the substring consisting of characters $c_l, c_{l+1}, ... , c_r$ sorted in lexicographical order.
For two strings to be the same after sorting, they must have the same occurrences of every possible lowercase letter. To answer the query for a range $[l, r]$, we must ensure that after the operations, $cnt_c = cnt2_c$ must where $cnt_c$ is the number of times character $c$ occurs in the range for $a$ and $cnt2_c$ is defined similarly for $b$. Both $cnt_c$ and $cnt2_c$ can be obtained by doing prefix sums for character $c$ specifically. Note that since there are only $26$ possible $c$, you can afford to create $26$ length $n$ prefix sum arrays. In one operation, you can replace one occurrence of a character $c$ with another character $c2$. Essentially, you are subtracting one from $cnt_c$ and adding one to $cnt_{c2}$. Obviously, you must choose $c$ and $c2$ such that $cnt_c > cnt2_c$ and $cnt_{c2} < cnt2_{c2}$. So, we only have to focus on $c$ or $c2$ since one decreasing will automatically lead to the other increase. The answer is just the sum of $cnt_c - cnt2_c$ if $cnt_c > cnt2_c$ over all possible lowercase characters $c$.
[ "dp", "greedy", "sortings", "strings" ]
1,200
#include <bits/stdc++.h> using namespace std; void solve(){ int n, q; cin >> n >> q; vector<vector<int>> pre1(n + 1, vector<int>(26, 0)); vector<vector<int>> pre2(n + 1, vector<int>(26, 0)); for (int i = 1; i <= n; i++){ char c; cin >> c; pre1[i][c - 'a']++; for (int j = 0; j < 26; j++) pre1[i][j] += pre1[i - 1][j]; } for (int i = 1; i <= n; i++){ char c; cin >> c; pre2[i][c - 'a']++; for (int j = 0; j < 26; j++) pre2[i][j] += pre2[i - 1][j]; } while (q--){ int l, r; cin >> l >> r; int dif = 0; for (int c = 0; c < 26; c++){ int v1 = pre1[r][c] - pre1[l - 1][c]; int v2 = pre2[r][c] - pre2[l - 1][c]; dif += abs(v1 - v2); } cout << dif / 2 << "\n"; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int tc; cin >> tc; while (tc--) solve(); }
1996
D
Fun
\begin{quote} Counting is Fun! \hfill — satyam343 \end{quote} Given two integers $n$ and $x$, find the number of triplets ($a,b,c$) of \textbf{positive integers} such that $ab + ac + bc \le n$ and $a + b + c \le x$. Note that order matters (e.g. ($1, 1, 2$) and ($1, 2, 1$) are treated as different) and $a$, $b$, $c$ must be strictly greater than $0$.
There are several solutions to this problem, The easiest way is to just fix either $a$, $b$ or $c$. Let's fix $a$. Since $ab + ac + bc \leq n$, we know at the minimum, $ab \leq n$. Divide on both sides to get $b \leq \frac{n}{a}$. When $a = 1$, there are $n$ choices for $b$. When $a = 2$, there are $\frac{n}{2}$ choices for $b$. So in total, there are $n + \frac{n}{2} + \frac{n}{3} + ... + \frac{n}{n}$ total choices for $b$. This is just the harmonic series, so over all possible $a$, there are about $n \log n$ choices for $b$. Therefore, we can afford to loop through both $a$ and $b$. Now that we have $a$ and $b$, all that's left is to solve for $c$. Let's solve for $c$ in both equations. In the first equation, we can factor $c$ out to obtain $ab + c(a+b) \leq n$. So, $c \leq \frac{n-ab}{a+b}$. In the second equation, $c \leq x - a - b$. Since we want the $c$ to satisfy both inequalities, we must choose the stricter one. So, the number of possible $c$ is $\min(\frac{n-ab}{a+b},x-a-b)$. The answer is the sum of number of possible $c$ over all possible $a$ and $b$.
[ "binary search", "brute force", "combinatorics", "math", "number theory" ]
1,500
#include <bits/stdc++.h> using namespace std; int main(){ int tc; cin >> tc; while (tc--){ int n, x; cin >> n >> x; long long ans = 0; for (int a = 1; a <= min(n, x); a++){ for (int b = 1; a * b <= n and a + b <= x; b++){ int highestC = min((n - a * b) / (a + b), x - (a + b)); ans += highestC; } } cout << ans << "\n"; } }
1996
E
Decode
{In a desperate attempt to obtain your \sout{waifu} favorite character, you have hacked into the source code of the game. After days of struggling, you finally find the binary string that encodes the gacha system of the game. In order to decode it, you must first solve the following problem.} You are given a binary string $s$ of length $n$. For each pair of integers $(l, r)$ $(1 \leq l \leq r \leq n)$, count the number of pairs $(x, y)$ $(l \leq x \leq y \leq r)$ such that the amount of $\mathtt{0}$ equals the amount of $\mathtt{1}$ in the substring $s_xs_{x+1}...s_y$. Output the sum of counts over all possible $(l, r)$ modulo $10^9+7$.
How can we efficiently check if a range contains the same amount of zeroes and ones? Let's create an array $a$ where $a_i = -1$ if $s_i = 0$ and $a_i = 1$ if $s_i = 1$. Let's denote $p$ as the prefix sum array of $a$. We want the contribution of $-1$ by the zeroes to cancel out with the ones, so if $p_r - p_{l-1} = 0$, then the range $[l, r]$ contain equal amounts of zeroes and ones. We can rephrase the problem as the following: for each subrange $[l, r]$, count the number of pairs $(x,y)$ such that $p_{x-1} = p_y$. Let's fix $p_{x-1}$ and keep track of all potential $y$ such that $y > x$ and $p_{x-1} = p_{y}$. How many subarrays will cover $[x, y]$? Well, we have $x+1$ options as $l$ and $n-y+1$ options as $r$, so the range $[x,y]$ contributes to $(x+1) \cdot (n-y+1)$ subarrays. We just need to calculate this expression for all potential $y$ now. Let's denote the all possible $y$ as $y_1, y_2, ... y_k$. We are asked to find the sum of $(x+1) \cdot (n-y_1+1) + (x+1) \cdot (n-y_2+1) + \dots + (x+1) \cdot (n-y_k+1)$. Let's factor $(x+1)$ out, and we have $(x+1) \cdot ((n-y_1+1)+(n-y_2+1)+\dots+(n-y_k+1))$. Since, the second part of the expression is just the sum of all $(n-y_i+1)$, we can first precalculate that sum and since $y > x$, subtract as we sweep from left to right.
[ "combinatorics", "data structures", "implementation", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; #define ll long long const int MOD = 1e9 + 7; void solve(){ string S; cin >> S; int n = S.size(); S = " " + S; vector<int> P(n + 1, 0); for (int i = 1; i <= n; i++){ P[i] = (S[i] == '1' ? 1 : -1) + P[i - 1]; } map<int, ll> cnt; ll ans = 0; for (int i = 0; i <= n; i++){ ans = (ans + (n - i + 1) * cnt[P[i]]) % MOD; cnt[P[i]] = (cnt[P[i]] + (i + 1)) % MOD; } cout << ans << "\n"; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int tc; cin >> tc; while (tc--) solve(); }
1996
F
Bomb
Sparkle gives you two arrays $a$ and $b$ of length $n$. Initially, your score is $0$. In one operation, you can choose an integer $i$ and add $a_i$ to your score. Then, you must set $a_i$ = $\max(0, a_i - b_i)$. You only have time to perform $k$ operations before Sparkle sets off a nuclear bomb! What is the maximum score you can acquire after $k$ operations?
Let's first solve the problem in $\mathcal{O}(k)$. One possible solution is to loop through each operation and take the largest $a_i$ each time, and set $a_i = \max(0, a_i - b_i)$. This can be done with a set or a priority queue. With that in mind, let's binary search for the largest $x$ such that every value we add to our score has been greater or equal to $x$ for all $k$ operations. Define $f(x)$ as the number of operations required for every $a_i$ to be less than $x$. Specifically, $f(x) = \sum_{i=1}^n \lceil \frac{a_i-x}{b_i} \rceil$. We are searching for the smallest $x$ such that $f(x) \leq k$. Once we've found $x$, we can subtract $f(x)$ from $k$. Note that now, $k$ must be less than to $n$ (otherwise we can another operation on all $a_i$). So, it suffices to run the slow solution for these remaining operations (as long as $a_i > 0$). Alternatively, we can notice that the remaining operations will all add $x-1$ to our answer (assuming $x > 0$). To obtain the sum of all $a_i$ we collected when calculating $f(x)$, we can use the arithmetic sequence sum formula. For each $i$, the number of terms in the sequence is $t = \lceil \frac{a_i-x}{b_i} \rceil$. The first term of the sequence is $f = a_i - b_i \cdot (t-1)$. The last term is $a_i$. Using the formula, we can add $\frac{t}{2}(f+a_i)$ to the answer.
[ "binary search", "greedy", "math" ]
1,900
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ int n, k; cin >> n >> k; vector<int> A(n), B(n); for (int &i : A) cin >> i; for (int &i : B) cin >> i; auto getInfo = [&](int cutoff){ ll ops = 0; ll sum = 0; for (int i = 0; i < n; i++){ ll a = A[i]; ll b = B[i]; if (cutoff > a) continue; // a - uses * b >= cutoff ll uses = (a - cutoff) / b; sum += (uses + 1) * a - b * uses * (uses + 1) / 2; ops += uses + 1; sum = min(sum, 2 * (ll)1e18); } return make_pair(sum, ops); }; int L = 0, H = 1e9 + 5; while (L < H){ int M = (L + H) / 2; getInfo(M).second <= k ? H = M : L = M + 1; } auto [ans, opsUse] = getInfo(L); cout << ans + (k - opsUse) * max(L - 1, 0) << "\n"; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int tc; cin >> tc; while (tc--) solve(); }
1996
G
Penacony
On Penacony, The Land of the Dreams, there exists $n$ houses and $n$ roads. There exists a road between house $i$ and $i+1$ for all $1 \leq i \leq n-1$ and a road between house $n$ and house $1$. All roads are bidirectional. However, due to the crisis on Penacony, the overseeing family has gone into debt and may not be able to maintain all roads. There are $m$ pairs of friendships between the residents of Penacony. If the resident living in house $a$ is friends with the resident living in house $b$, there must be a path between houses $a$ and $b$ through maintained roads. What is the minimum number of roads that must be maintained?
There are two configurations to satisfy every friendship $(a, b)$: activate all the roads from $a \rightarrow a+1 \rightarrow \dots \rightarrow b$ or $b \leftarrow \dots \leftarrow n \leftarrow 1 \leftarrow \dots \leftarrow a$. Let's fix a road we deactivate. Say it goes from $i \rightarrow i+1$. Observe that the configuration for all friendships is fixed to one of the two cases. For example, if $a \leq i < b$, then we must use the second configuration. We can try fixing every road and taking the minimum of number of roads. This can be done with sweep line. Once we reach $i = a$ for any friendship, we toggle to the second configuration. Once we reach $b$, we toggle back to the first. We can track maintained roads by performing a range addition on a lazy propagated segment tree for each point covered by the current configuration. The number of roads required is $n$ minus the number of occurrences of zeroes in the segment tree, which can be tracked with Counting Minimums in a Segment Tree. Consider the $n$-gon formed by the houses, with each road becoming an edge of the polygon. We draw diagonals between houses if they are friends. Let each diagonal arbitrarily "cover" one side of the polygon, where every road contained within one section split by the diagonal is covered by the diagonal. We claim that two roads can both be deleted if and only if they are covered by the same set of diagonals. First, this is equivalent to saying that when we draw a line between these two roads, they do not intersect any of our drawn diagonals. (This is since if any diagonal covers one road and not another, then they must be on opposite sides of the diagonal, so drawing a line between the two roads must intersect that diagonal. The converse also holds.) Now note that if two roads are on opposite sides of a diagonal, they cannot both be deleted, as then there is no path along maintained roads that connects the two endpoints of the diagonals, or the two houses that are friends. So it suffices to count the most frequent set of covered diagonals over all roads. We can represent a diagonal cover for some road using a xor hashing, where each diagonal is assigned a random number, and the roads that are covered by that diagonal are xor'd by this number. By using $64$-bit integers, the probability of collision is negligible, as each 64-bit integer has equal probability of representing a unique set of diagonals, and we have at most $n$ represented sets. For each pair of friends, we want to xor all values in a range by some random number. This can be done with a prefix xor array in $\mathcal{O}(1)$ per pair of friends. Counting the most frequent value at the end will take $\mathcal{O}(n \log n)$ time if a map is used or $\mathcal{O}(n)$ if an unordered map is used. In all, this solution runs in $\mathcal{O}(n \log n + m)$ or $\mathcal{O}(n + m)$ time.
[ "brute force", "data structures", "graphs", "greedy", "hashing" ]
2,200
#include <bits/stdc++.h> #define int long long using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); int n,m,a,b,k,t; void solve() { cin >> n >> m; vector<int> v(n); while (m--) { k=rng(); cin >> a >> b; v[a-1]^=k; v[b-1]^=k; } map<int,int> c; for (int r:v) m=max(m,c[a^=r]++); cout << n-m-1 << "\n"; } int32_t main() { ios::sync_with_stdio(0); cin.tie(0); cin >> t; while (t--) solve(); }
1997
A
Strong Password
Monocarp's current password on Codeforces is a string $s$, consisting of lowercase Latin letters. Monocarp thinks that his current password is too weak, so he wants to \textbf{insert exactly one lowercase Latin letter} into the password to make it stronger. Monocarp can choose any letter and insert it anywhere, even before the first character or after the last character. Monocarp thinks that the password's strength is proportional to the time it takes him to type the password. The time it takes to type the password is calculated as follows: - the time to type the first character is $2$ seconds; - for each character other than the first, the time it takes to type it is $1$ second if it is the same as the previous character, or $2$ seconds otherwise. For example, the time it takes to type the password abacaba is $14$; the time it takes to type the password a is $2$; the time it takes to type the password aaabacc is $11$. You have to help Monocarp — insert a lowercase Latin letter into his password so that the resulting password takes the maximum possible amount of time to type.
The time it takes to type a string can actually be calculated as follows: $2 \cdot |s| - p$, where $|s|$ is the number of characters in the string, and $p$ is the number of pairs of adjacent equal characters (usually a character takes $2$ seconds to type, but the right character in every pair of adjacent equal characters takes only $1$, so each pair reduces the total time by $1$). Since we always add a new character, $|s|$ will increase by $1$ no matter what; so we need to minimize $p$. Now there are two cases: if there is a pair of adjacent equal characters in the string, we can decrease $p$ by $1$ by "breaking" it as follows: choose any character different from the characters in that pair, and insert it between them. It's easy to see that we can "break" at most one such pair, so we can't do better; otherwise, $p$ is already $0$, so we just need to keep it equal to $0$. For example, we can choose any character not equal to the last character in the string, and append it to the right of it. There are other solutions as well, like iterating on all possible characters and all possible insertion positions.
[ "brute force", "implementation", "strings" ]
800
#include<bits/stdc++.h> using namespace std; void solve() { string s; cin >> s; int n = s.size(); int idx = -1; for(int i = 0; i + 1 < n; i++) if(s[i] == s[i + 1]) idx = i; if(idx == -1) { if(s.back() == 'a') cout << (s + "b") << endl; else cout << (s + "a") << endl; } else { string t = "a"; if(s[idx] == 'a') t = "b"; cout << s.substr(0, idx + 1) + t + s.substr(idx + 1) << endl; } } int main() { int t; cin >> t; for(int i = 0; i < t; i++) solve(); }
1997
B
Make Three Regions
There is a grid, consisting of $2$ rows and $n$ columns. Each cell of the grid is either free or blocked. A free cell $y$ is reachable from a free cell $x$ if at least one of these conditions holds: - $x$ and $y$ share a side; - there exists a free cell $z$ such that $z$ is reachable from $x$ and $y$ is reachable from $z$. A connected region is a set of free cells of the grid such that all cells in it are reachable from one another, but adding any other free cell to the set violates this rule. For example, consider the following layout, where white cells are free, and dark grey cells are blocked: There are $3$ regions in it, denoted with red, green and blue color respectively: The given grid contains at most $1$ connected region. Your task is to calculate the number of free cells meeting the following constraint: - if this cell is blocked, the number of connected regions becomes exactly $3$.
Since the chosen cell should split a connected region into $3$ non-empty parts, this cell should share a side with all $3$ of them. But any cell has at most $3$ neighbor cells (because there are only $2$ rows), and they should be split from each other by blocked cells. From the above, we can conclude how a pattern of a "good" cell should look like. In fact, there are only $2$ of them (on the layouts below, white cells are free, dark grey cells are blocked, and the red cell is a "good" cell): These patterns are the only possible ones: all $3$ neighbors of a "good" cell should be free (otherwise there will be less than $3$ regions connected to it); and both of the "corner" cells should be blocked (if at least one of them is free, two regions will merge into one, so there will be less than $3$ regions). So the problem becomes to calculate the number of the above patterns inside the given grid.
[ "constructive algorithms", "two pointers" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<string> s(2); for (auto& x : s) cin >> x; int ans = 0; for (int i = 1; i < n - 1; ++i) { bool ok = true; ok &= (s[0][i] == '.' && s[1][i] == '.'); ok &= (s[0][i - 1] != s[1][i - 1]); ok &= (s[0][i + 1] != s[1][i + 1]); ok &= (s[0][i - 1] == s[0][i + 1]); ans += ok; } cout << ans << '\n'; } }
1997
C
Even Positions
Monocarp had a regular bracket sequence $s$ of length $n$ ($n$ is even). He even came up with his own way to calculate its cost. He knows that in a regular bracket sequence (RBS), each opening bracket is paired up with the corresponding closing bracket. So he decided to calculate the cost of RBS as the sum of distances between pairs of corresponding bracket pairs. For example, let's look at RBS (())(). It has three pairs of brackets: - (__)__: the distance between brackets at position $1$ and at $4$ is $4 - 1 = 3$; - _()___: the distance is $3 - 2 = 1$; - ____(): the distance is $6 - 5 = 1$. So the cost of (())() is $3 + 1 + 1 = 5$.Unfortunately, due to data corruption, Monocarp lost all characters on odd positions $s_1, s_3, \dots, s_{n-1}$. Only characters on even positions ($s_2, s_4, \dots, s_{n}$) remain. For example, (())() turned to _(_)_). Monocarp wants to restore his RBS by placing brackets on the odd positions. But since the restored RBS may not be unique, he wants to choose one with \textbf{minimum cost}. It's too hard to do for Monocarp alone, so can you help him? Reminder: A regular bracket sequence is a string consisting of only brackets, such that this sequence, when inserted 1-s and +-s, gives a valid mathematical expression. For example, (), (()) or (()())() are RBS, while ), ()( or ())(() are not.
Let's define a balance of a bracket sequence as the $\texttt{number_of_opening_brackets} - \texttt{number_of_closing_brackets}$. It's a well-known fact that for RBS the balance of all its prefixes must be greater than or equal to zero and the balance of the whole string must be exactly zero. So, if we want to restore RBS from $s$ we shouldn't break that rule. Next, let's define $S_{o}$ as the sum of positions of the opening brackets in RBS and $S_{c}$ as the sum of positions of the closing brackets in RBS. It turns out that the cost defined in the statement is just $S_c - S_o$. Moreover, you can see that $S_c - S_o = 2 S_c - \frac{n (n + 1)}{2}$. It means that in order to minimize the cost, we should minimize $S_c$, or we should try to place closing brackets on the smaller positions. The most interesting part is that it's enough to come up with the right strategy. Let's iterate from left to right, maintaining the current balance and place the closing brackets whenever we can: if the current balance is $0$ we can't place a closing bracket, since it will make the balance negative, so we place an opening bracket; if the current balance is bigger than $0$ we place a closing bracket. Since we need to calculate the cost of the RBS, we can replace the balance counter with a stack containing positions of opening brackets that don't have a pair yet. Each time we meet an opening bracket, we'll push its position to the top of the stack, and each time we meet a closing bracket, we'll take one bracket from the top of the stack. The current balance is just the size of the stack. Here is a sketch of the proof, why the strategy above is correct. Firstly, the strategy creates RBS, because after processing a prefix of even length the current balance will be equal to either $0$ or $2$, while after an odd length prefix it will be always $1$. At the start, the balance is $0$ and we make it $1$, then it either becomes $0$ or $2$, and in both cases we return it to $1$ and so on. Since the last character is always a closing bracket, the total balance will return to $0$. Secondly, to prove that the strategy minimizes the cost, we can use a standard technique of proof by contradiction: suppose there is a better answer, look at the first position of the difference: it will be ) in our string and ( in the answer. Then just find the next ) in the answer and swap them. The answer will stay RBS, while $S_c$ will decrease - contradiction.
[ "constructive algorithms", "data structures", "greedy" ]
1,100
import java.util.LinkedList fun main() { repeat(readln().toInt()) { val n = readln().toInt() val s = readln() var ans = 0L val bracketPositions = LinkedList<Int>() for (i in s.indices) { var c = s[i] if (c == '_') { c = if (bracketPositions.isEmpty()) '(' else ')' } if (c == ')') { ans += i - bracketPositions.pollLast() } else bracketPositions.addLast(i) } println(ans) } }
1997
D
Maximize the Root
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$. The value $a_i$ is written at the $i$-th vertex. You can perform the following operation any number of times (possibly zero): choose a vertex $v$ \textbf{which has at least one child}; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative. Your task is to calculate the maximum possible value written at the root using the aforementioned operation.
We can clearly say that if some value $k$ can be obtained at the root, then any value from $a_1$ to $k$ can also be obtained. Using that fact, we can use binary search to solve the problem. Let's fix some value $\mathit{mid}$ in binary search and check if it is possible to apply an operation from the statement $\mathit{mid}$ times to the root. Let's write the following recursive function: $\mathit{check}(v, x)$ - the function that checks whether it is possible to obtain at least $x$ at all vertices from the subtree of $v$ (including $v$ itself) simultaneously (i. e. we had to make $x$ operations above the current vertex, can the subtree of $v$ "support" them?). Let the current state be $(v, x)$, then there are three cases of transitions: $v$ is a leaf, then $x \le a_v$ should hold; $v$ is not a leaf and $x \le a_v$, then the vertex $v$ is ok, and we have to check its subtree (i. e. $\mathit{check}(u, x)$ should be true for all $u$ that are children of $v$). $v$ is not a leaf and $x > a_v$, then we have to apply the operation $(x - a_v)$ times to the vertex $v$, and that adds an additional constraint on the subtree of $v$; specifically, $\mathit{check}(u, x + (x - a_v))$ should be true for all $u$ that are children of $v$. Be careful with overflows: $x$ might grow exponentially, so you should, for example, return from the function when $x$ becomes very large. When we check a single value of $mid$, this recursive function is called once for each vertex in the tree, so the total time complexity of this solution is $O(n\log{A})$, where $A$ is an upper bound of the values of the array $a$.
[ "binary search", "dfs and similar", "dp", "greedy", "trees" ]
1,500
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (auto& x : a) cin >> x; vector<vector<int>> g(n); for (int i = 1; i < n; ++i) { int p; cin >> p; g[p - 1].push_back(i); } auto check = [&](auto&& self, int v, int x) -> bool { if (x > INF) return false; bool isLeaf = true; if (v) x += max(0, x - a[v]); for (auto u : g[v]) { isLeaf = false; if (!self(self, u, x)) return false; } return (!isLeaf || x <= a[v]); }; int l = 1, r = INF; while (l <= r) { int mid = (l + r) / 2; if (check(check, 0, mid)) { l = mid + 1; } else { r = mid - 1; } } cout << a[0] + l - 1 << '\n'; } }
1997
E
Level Up
Monocarp is playing a computer game. He starts the game being level $1$. He is about to fight $n$ monsters, in order from $1$ to $n$. The level of the $i$-th monster is $a_i$. For each monster in the given order, Monocarp's encounter goes as follows: - if Monocarp's level is strictly higher than the monster's level, the monster flees (runs away); - otherwise, Monocarp fights the monster. After every $k$-th fight with a monster (\textbf{fleeing monsters do not count}), Monocarp's level increases by $1$. So, his level becomes $2$ after $k$ monsters he fights, $3$ after $2k$ monsters, $4$ after $3k$ monsters, and so on. You need to process $q$ queries of the following form: - $i~x$: will Monocarp fight the $i$-th monster (or will this monster flee) if the parameter $k$ is equal to $x$?
I would like to describe two different intended solutions to this problem. Solution One. Let's start with the following idea. How many times can the character's level increase for a fixed $k$? Given that there are $n$ monsters, even if we fight all of them, the level will not exceed $\frac{n}{k}$. That is, if we sum over all $k$, the level will change no more than $O(n \log n)$ times (harmonic series). Let's simulate the process for each $k$ and find out when the level changed. Suppose the character's level became $x$ after fighting monster $i$. Then the level will become $x + 1$ after fighting the $k$-th monster with a level greater than or equal to $x$ after position $i$. That is, if we had an array of positions of monsters with a level greater than or equal to $x$, we could find the position of the level change from it. Unfortunately, it is not possible to keep all such arrays in memory. Instead, let's try to use a more powerful data structure. Now, suppose we want to add or remove positions from the structure and be able to query the $k$-th position greater than $i$. Such structures exist. We can use a segment tree, a BIT, or an ordered_set from pbds. How can we reduce the problem to using this structure? The idea is as follows. Previously, we had the idea to iterate over $k$ and inside that iterate over the current character level. Let's do the opposite. We will iterate over the character level on the outside. And inside, we will update the level for all such $k$ for which the character has not reached the end of the monsters yet. It turns out that this will be a prefix of the $k$. Why is that? For each $x$, the character reaches level $x$ at some $k$ no later than at $k + 1$. Suppose this is not the case. Consider the first such $x$ where the character reached level $x$ at $k$ later than at $k + 1$. That is, he reached level $x - 1$ earlier or at the same time. This means that he will encounter at least all the same monsters at $k$ as at $k + 1$ (since the segment of monsters will start no later and end no earlier). Since at $k + 1$, the character must have encountered at least $k + 1$ monsters of level at least $x$, at $k$ he will definitely encounter at least $k$. Thus, this cannot happen. Then the implementation is as follows. For each $k$, we will maintain the position at which the character reached the current level $x$. Then, for the prefix of $k$, for which this position is within the array, we will update it with the new position for level $k + 1$. For this, we will store the positions of all monsters of level at least $x$ in the data structure. After processing level $x$, we will remove all monsters of this level from the structure. To find the new position, we need to make such queries to the structure: either find the $k$-th position after the current saved one (in the segment tree or Fenwick tree), or find the first (using order_of_key) and move $k - 1$ positions from it (using find_by_order) (in ordered_set). We can answer the queries within the simulation. For each $k$, we will store all queries related to it and sort them in ascending order of $i$. Since within each $k$ we move in the order of increasing level, and thus position, we can answer the queries in that order. While the position of the query is less than or equal to the position where the level will become $x + 1$, we answer the queries by checking that the monster's level at that position is not less than $x$. Overall complexity: $O(n \log^2 n)$. Solution Two. Let's still simulate level increases directly. We will use the square root heuristics. If $k$ is greater than or equal to some constant $B$, then the character will definitely fight all monsters of level at least $\frac{n}{B}$, simply because he cannot become greater than this level himself. That is, if we choose $B$ on the order of $1000$, for example, we only need to know whether the character is fighting a monster, only for monsters of level no higher than $200$. We will solve the problem for all $k$ less than $1000$ in $O(n)$. That is, we will honestly go through the monsters, maintaining the character's level and a counter of fights until the level increases. For larger $k$, we will solve the problem as follows. We will sum the indices of all characters of each level from $1$ to $200$ into separate arrays. We will consider whom the character fought at the end of the game for each level separately. It is obvious that for each level of monsters $x$, the character fought a prefix of these monsters. Since the character's level increases monotonically, at some point the character's level will exceed $x$, and all monsters of level $x$ will flee. Moreover, if the character fought a monster for some $k$, he will also fight it for $k + 1$ (by the proof from the previous solution). Thus, to find out which new monsters the character will fight at level $k$, we can do the following. We will iterate over monster levels up to $200$ and for the first fleeing monster of this level, we will check whether the character will fight it now. For this, we need to find out how many monsters the character fought before this monster. If his level is not less than this number divided by $k$ (rounded down), then he will fight it. Among all the first monsters the character will fight, we will find the minimum. For it, our solution is definitely correct. For the others, this is not necessarily true, because the character's level may increase due to fights to the left of this position. If no such monsters are found, then for this $k$ we have found all. Otherwise, in some data structure, we will mark that the character is fighting with the leftmost found monster. Thus, we need a data structure that can answer prefix sum queries and update an element at a certain position. There are quite a few such structures. However, we have a large number of queries: for each fight, we need to make $200$ queries, that is, a total of $n \cdot 200$ queries. However, there are not so many updates: each position will be updated in the structure no more than once, that is, no more than $n$ updates. Therefore, we would like to have a structure that balances these operations. For example, let the query be $O(1)$, and the update be $O(\sqrt{n})$. We will divide the array into blocks of size $O(\sqrt{n})$. For each block, we will store the sum of elements up to its left boundary. And for each position within each block, we will store the sum up to the left boundary of the block. Then, to query the prefix sum up to $i$, we need to add the sum up to the left position of the block $\frac{i}{\sqrt{n}}$ and the sum from $i$ to the start of this block. To update at position $i$, we need to add one to the first sum for each block from $\frac{i}{\sqrt{n}} + 1$ to the end. And also for each position from $i$ to the end of its block. Queries can be answered as follows. For each monster, we will keep track of the first $k$ at which we will fight it. Then it is sufficient to check that the $k$ from the query is not less than this value. Overall complexity: $O(n \sqrt{n})$.
[ "binary search", "brute force", "data structures", "divide and conquer", "implementation" ]
2,200
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; struct query{ int i, j; }; int main() { cin.tie(0); ios::sync_with_stdio(false); int n, m; cin >> n >> m; vector<int> a(n); forn(i, n) cin >> a[i]; vector<vector<query>> q(n + 1); forn(j, m){ int i, x; cin >> i >> x; --i; q[x].push_back({i, j}); } forn(i, n + 1) sort(q[i].begin(), q[i].end(), [](const query &a, const query &b){ return a.i > b.i; }); int P = min(1000, n + 1); vector<char> ans(m); for (int k = 1; k < P; ++k){ int cur = 1; int cnt = 0; forn(i, n){ bool fl = false; if (a[i] >= cur){ ++cnt; fl = true; if (cnt == k){ ++cur; cnt = 0; } } while (!q[k].empty() && q[k].back().i == i){ ans[q[k].back().j] = fl; q[k].pop_back(); } } } vector<int> sum1(n), sum2(n); int p2 = ceil(sqrt(n + 2)); auto add = [&](int i){ int bl = i / p2; for (int j = bl + 1; j * p2 < n; ++j) ++sum1[j]; for (int j = i; j < (bl + 1) * p2 && j < n; ++j) ++sum2[j]; }; int mx = n / P + 5; vector<vector<int>> pos(mx); forn(i, n){ if (a[i] < mx) pos[a[i]].push_back(i); else add(i); } for (auto &it : pos) reverse(it.begin(), it.end()); for (int k = P; k <= n; ++k){ while (true){ int mn = n; int who = -1; forn(lvl, mx) if (!pos[lvl].empty()){ int i = pos[lvl].back(); if (mn < i) continue; int cnt = sum1[i / p2] + sum2[i]; if (a[i] >= cnt / k + 1){ mn = i; who = lvl; } } if (who == -1) break; add(mn); pos[who].pop_back(); } for (auto it : q[k]){ int lvl = a[it.i]; ans[it.j] = (lvl >= mx || pos[lvl].empty() || pos[lvl].back() > it.i); } } for (auto x : ans) cout << (x ? "YES" : "NO") << '\n'; return 0; }
1997
F
Chips on a Line
You have $n$ chips, and you are going to place all of them in one of $x$ points, numbered from $1$ to $x$. There can be multiple chips in each point. After placing the chips, you can perform the following four operations (in any order, any number of times): - choose a chip in point $i \ge 3$, remove it and place two chips: one in $i-1$, one in $i-2$; - choose two chips in adjacent points $i$ and $i+1$, remove them and place a new chip in $i+2$; - choose a chip in point $1$ and move it to $2$; - choose a chip in point $2$ and move it to $1$. Note that the coordinates of the chips you place during the operations cannot be less than $1$, but can be greater than $x$. Denote the cost of chip placement as the \textbf{minimum} number of chips which can be present on the line after you perform these operations, starting from the placement you've chosen. For example, the cost of placing two chips in points $3$ and one chip in point $5$ is $2$, because you can reduce the number of chips to $2$ as follows: - choose a chip in point $3$, remove it, place a chip in $1$ and another chip in $2$; - choose the chips in points $2$ and $3$, remove them and place a chip in $4$; - choose the chips in points $4$ and $5$, remove them and place a chip in $6$. You are given three integers $n$, $x$ and $m$. Calculate the number of placements of exactly $n$ chips in points from $1$ to $x$ having cost equal to $m$, and print it modulo $998244353$. Two placements are considered different if the number of chips in some point differs between these placements.
The operations described in the statement are kinda similar to the identities for Fibonacci numbers, so maybe the solution will be connected to them. Let's assign each chip placement a weight: if chips are placed in points $x_1, x_2, \dots, x_n$ (repeating if multiple chips are in the same position), the weight of this placement is $f_{x_1} + f_{x_2} + \dots + f_{x_k}$, where $f_i$ is the $i$-th Fibonacci number ($f_1 = f_2 = 1$; $f_{i+2} = f_i + f_{i+1}$). We can show that two placements can be transformed into each other if and only if their weights are identical. First of all, the operations described in the statement don't change the weight, so two placements with different weights cannot be transformed into each other. To show how to transform two placements with identical weight into each other, let's bring them into "canonical" form as follows: while there is a chip with coordinate $i > 2$, convert it into two chips with coordinates $i-1$ and $i-2$; if all remaining chips are in points $1$ and $2$, move all chips from $2$ to $1$. After performing this sequence of actions, we will transform a placement of chips into the form "all chips are in point $1$, and the number of these chips is equal to the weight of the placement". And since all operations we apply are invertible (for every operation, there is an operation which "rolls it back"), we can transform any placement to any other placement with the same weight through this "canonical form". So, instead of counting the placements, let's group them according to their weights and work with them. For every possible weight of a placement (which is an integer from $1$ to $f_x \cdot n$), we need to answer two questions: Is it true that the minimum cost of a placement of this weight is exactly $m$? How many placements with this weight are there? The former is simple: this is just checking that the minimum number of Fibonacci numbers used to represent an integer is equal to $m$. We can precalculate this minimum number of Fibonacci numbers to represent each integer with a simple dynamic programming. The latter is a bit more tricky: we need to count the number of ways to represent the given number as a sum of exactly $n$ Fibonacci numbers from $f_1$ to $f_x$, where the order of these Fibonacci numbers does not matter. There are different ways to calculate it, the model solution uses a dynamic programming which uses $O(f_x \cdot n^2 \cdot x)$ time and $O(f_x \cdot n^2)$ memory. Let $dp_{i,j}$ be the number of ways to partition the integer $i$ into $j$ Fibonacci numbers. Initially, we will consider the situation when we can't use any Fibonacci numbers, so $dp_{0,0} = 1$ and everything else is $0$. And then we will "add" Fibonacci numbers one by one, so first we will update our dynamic programming in such a way that we can only use $f_1$; then, only $f_1$ and/or $f_2$; and so on. Let's show how to "update" our dynamic programming when we can use a new number $k$ in partitions. The simple way to do this is as follows: for every $dp_{i,j}$, iterate on the number $c$ of new elements we will use, and get a partition of integer $i + c \cdot k$ into $j+c$ numbers. However, that is too slow. Instead, let's iterate on the states of our dynamic programming in ascending order of $i$, and in each state, add at most one element to the partition (so, increase $dp_{i+k,j+1}$ by $dp_{i,j}$). At the first glance, it only allows us to use one element equal to $k$; however, when we consider the state $dp_{i+k,j+1}$ we updated, it will already store both the partitions which didn't use elements equal to $k$, and the partitions which used at least one element equal to $k$ (which came from the state $dp_{i,j}$); and by transitioning from $dp_{i+k,j+1}$ to $dp_{i+2k,j+2}$, we will "expand" all these partitions. If the previous paragraph is a bit unclear to you, you can try viewing it as a three-state dynamic programming of the form "let $dp_{i,j,k}$ be the number of partitions of $i$ into $j$ Fibonacci numbers from $f_1$ to $f_k$", where we dropped the third state of our dynamic programming in favor of maintaining only one layer and being more memory efficient.
[ "brute force", "combinatorics", "dp", "greedy", "math" ]
2,700
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int main() { int n, x, m; cin >> n >> x >> m; vector<int> fib = {0, 1}; for(int i = 2; i <= 30; i++) fib.push_back(fib[i - 1] + fib[i - 2]); int max_sum = fib[x] * n; vector<vector<int>> dp(max_sum + 1, vector<int>(n + 1)); dp[0][0] = 1; for(int i = 1; i <= x; i++) for(int j = 0; j < max_sum; j++) for(int k = 0; k < n; k++) { if(j + fib[i] <= max_sum) dp[j + fib[i]][k + 1] = add(dp[j + fib[i]][k + 1], dp[j][k]); } vector<int> cost(max_sum + 1, 1e9); cost[0] = 0; for(int j = 1; j <= max_sum; j++) for(int i = 1; i <= 30; i++) if(j >= fib[i]) cost[j] = min(cost[j], cost[j - fib[i]] + 1); int ans = 0; for(int i = 0; i <= max_sum; i++) if(cost[i] == m) ans = add(ans, dp[i][n]); cout << ans << endl; }
1998
A
Find K Distinct Points with Fixed Center
\begin{quote} I couldn't think of a good title for this problem, so I decided to learn from LeetCode. \hfill — Sun Tzu, The Art of War \end{quote} You are given three integers $x_c$, $y_c$, and $k$ ($-100 \leq x_c, y_c \leq 100$, $1 \leq k \leq 1000$). You need to find $k$ \textbf{distinct} points ($x_1, y_1$), ($x_2, y_2$), $\ldots$, ($x_k, y_k$), having integer coordinates, on the 2D coordinate plane such that: - their center$^{\text{∗}}$ is ($x_c, y_c$) - $-10^9 \leq x_i, y_i \leq 10^9$ for all $i$ from $1$ to $k$ It can be proven that at least one set of $k$ distinct points always exists that satisfies these conditions. \begin{footnotesize} $^{\text{∗}}$The center of $k$ points ($x_1, y_1$), ($x_2, y_2$), $\ldots$, ($x_k, y_k$) is $\left( \frac{x_1 + x_2 + \ldots + x_k}{k}, \frac{y_1 + y_2 + \ldots + y_k}{k} \right)$. \end{footnotesize}
We can construct a solution by fixing all $x_i$ as $x_c$ or all $y_i$ as $y_c$. For example, if we fix all $y_i$ as $y_c$, then we can output pairs $(x_c-1, y_c), (x_c+1, y_c), (x_c-2, y_c), (x_c+2, y_c), ... , (x_c- \lfloor \frac{k}{2} \rfloor, y_c), (x_c + \lfloor \frac{k}{2} \rfloor, y_c)$. If the $k$ is odd, we need one more pair, so just output $(x_c, y_c)$.
[ "constructive algorithms", "implementation", "math" ]
800
#include <iostream> using namespace std; int main() { int t; cin >> t; while(t--){ int x, y, k; cin >> x >> y >> k; for(int i = 0; i < k - k % 2; i++){ cout << x - (i & 1 ? 1 : -1) * (i / 2 + 1) << " " << y << "\n"; } if(k & 1){ cout << x << " " << y << "\n"; } } }
1998
B
Minimize Equal Sum Subarrays
\begin{quote} It is known that Farmer John likes Permutations, but I like them too! \hfill — Sun Tzu, The Art of Constructing Permutations \end{quote} You are given a permutation$^{\text{∗}}$ $p$ of length $n$. Find a permutation $q$ of length $n$ that minimizes the number of pairs ($i, j$) ($1 \leq i \leq j \leq n$) such that $p_i + p_{i+1} + \ldots + p_j = q_i + q_{i+1} + \ldots + q_j$. \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}
We can always construct a solution such that the number of pairs $(i, j)$ is $1$ where the only pair is $(1, n)$. There exists several constructions, such as rotating $p$ once or increment all $p_i$ (and $p_i = n$ turns into $p_i = 1$). Consider the former construction, where $q = [p_2, p_3, ..., p_n, p_1]$. For an arbitrarily interval $[i, j]$, $p[i..j]$ and $q[i..j]$ will have exactly $1$ element that's different, disregarding ordering. Since we have a permutation and all elements are distinct, the sum in the range will never be the same. The only exception is the entire array, of course.
[ "constructive algorithms", "math", "number theory" ]
1,000
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while(t--){ int n; cin >> n; vector<int> p(n); for(int& i: p) cin >> i; rotate(p.begin(), p.begin() + 1, p.end()); for(int i: p) cout << i << " "; cout << "\n"; } }
1998
C
Perform Operations to Maximize Score
\begin{quote} I see satyam343. I'm shaking. Please more median problems this time. I love those. Please satyam343 we believe in you. \hfill — satyam343's biggest fan \end{quote} You are given an array $a$ of length $n$ and an integer $k$. You are also given a binary array $b$ of length $n$. You can perform the following operation at most $k$ times: - Select an index $i$ ($1 \leq i \leq n$) such that $b_i = 1$. Set $a_i = a_i + 1$ (i.e., increase $a_i$ by $1$). Your score is defined to be $\max\limits_{i = 1}^{n} \left( a_i + \operatorname{median}(c_i) \right)$, where $c_i$ denotes the array of length $n-1$ that you get by deleting $a_i$ from $a$. In other words, your score is the maximum value of $a_i + \operatorname{median}(c_i)$ over all $i$ from $1$ to $n$. Find the maximum score that you can achieve if you perform the operations optimally. For an arbitrary array $p$, $\operatorname{median}(p)$ is defined as the $\left\lfloor \frac{|p|+1}{2} \right\rfloor$-th \textbf{smallest} element of $p$. For example, $\operatorname{median} \left( [3,2,1,3] \right) = 2$ and $\operatorname{median} \left( [6,2,4,5,1] \right) = 4$.
satyam343, Dominater069 First, solve for $k = 0$. Find some nice characterization about $med(c_i)$ and thus the maximum score. Divide into $2$ cases where we either increment the max element or the median. Apply binary search Let's forget about the operations of adding $1$ to $a_i$ and figure out how to find an array's score. Assume the array $a$ is sorted in increasing order as the order doesnt change the problem. First observe how $med(c_i)$ changes with respect to $i$. $med(c_i)$ is always either $a_{\lfloor \frac{n}{2} \rfloor}$ or $a_{\lfloor \frac{n + 2}{2} \rfloor}$. You can prove this formally by considering different positions of $i$ with respect to the initial median position. Specifically, for all $i \le \lfloor \frac{n}{2} \rfloor$, $med(c_i) = a_{\lfloor \frac{n + 2}{2} \rfloor}$, and for other $i$, $med(c_i) = a_{\lfloor \frac{n}{2} \rfloor}$. Claim 1 : The score of the final array (after sorting in increasing order) is $a_n + med(c_n)$ There are $2$ cases we need to consider. 1) $med(c_i) = a_{\lfloor \frac{n}{2} \rfloor}$, in which case optimum value of $i$ is $n$ as we want to maximise $a_i$. Thus score in this case is $a_n + a_{\lfloor \frac{n}{2} \rfloor}$. 2) $med(c_i)= a_{\lfloor \frac{n + 2}{2} \rfloor}$, in which case optimum value of $i$ is $\lfloor \frac{n}{2} \rfloor$ as this is the largest value of $i$ which will change median. This obtains a score of $a_{\lfloor \frac{n}{2} \rfloor} + a_{\lfloor \frac{n + 2}{2} \rfloor}$ The score in Case $1$ is clearly larger than Case $2$, hence it is optimal. Hence, our score can be nicely characterized by "max + median of the others". Claim 2 : Either we will use all $k$ operations on the element which eventually becomes max element in our array, or we will use all operations trying to improve $med(c_n)$ and keep max element constant. Suppose we did $x$ ($0 < x < k$) operations on the element which eventually became maximum. Then, we could have done the remaining $(k - x)$ operations on this element too, as this is already the max element and doing operations on it guaranteedly improves our score each time by $1$. Doing operations on any other element can only improve our score by atmost $1$ Thus, we are in $2$ cases now, either increase max, or increase median of the rest. We will solve the problem considering both cases separately. Case $1$ : We do operations on the element which becomes max eventually. Lets fix $i$ to be the index that will become max. Then $b_i = 1$ must hold. We want to find $med(c_i)$, i.e. the median of the other $(n - 1)$ elements. This can be done with the observation mentioned above that $med(c_i)$ is always either $a_{\lfloor \frac{n}{2} \rfloor}$ or $a_{\lfloor \frac{n + 2}{2} \rfloor}$. Another possible way to solve this case is observe that we should only do operations on the largest index $i$ such that $b_i = 1$. While intuitive, the proof is left as an exercise to the reader. Case 2 : We do operations to increase the median of the others. $a_n$ is fixed as the max element in this case, and we want to find the largest possible median by using the $k$ operations on the other $(n - 1)$ elements. Let's binary search! Suppose we want to check if we can get $med(c_n) \ge x$ or not. Some elements are already $\ge x$, and we will not modify them. Some of the other elements can be incremented to become $\ge x$ too. Obviously, we should choose the largest indices $i$ such that $a_i < x$ and $b_i = 1$, and greedily increment as many as possible. Let $z$ be the maximum number of elements which become $\ge x$ at the end. The check is true iff $z \ge \lfloor \frac{n + 1}{2} \rfloor$. Thus, the problem is solved in $O(N \cdot log (MAX))$. The code is nicely written and commented, you may want to check it out.
[ "binary search", "brute force", "constructive algorithms", "greedy", "implementation" ]
1,900
#include <bits/stdc++.h> using namespace std; int main(){ int t; cin >> t; while (t--){ int n, k; cin >> n >> k; vector <pair<int, int>> a(n); for (auto &x : a) cin >> x.first; for (auto &x : a) cin >> x.second; sort(a.begin(), a.end()); long long ans = 0; // case 1 : increment max for (int i = 0; i < n; i++) if (a[i].second == 1){ // find med(c_i) int mc; if (i < n / 2) mc = a[n / 2].first; else mc = a[(n - 2) / 2].first; ans = max(ans, 0LL + a[i].first + k + mc); } // case 2 : increment median int lo = 0, hi = 2e9; while (lo != hi){ int mid = (1LL + lo + hi) / 2; int z = 0; vector <int> smaller_list; for (int i = 0; i < n - 1; i++){ if (a[i].first >= mid){ z++; } else if (a[i].second == 1){ smaller_list.push_back(mid - a[i].first); // list of numbers smaller than x but b[i] = 1 } } reverse(smaller_list.begin(), smaller_list.end()); // list will be sorted in ascending, but we want sorted in descending, as greedily changing largest elements int kk = k; for (auto x : smaller_list) if (kk >= x){ kk -= x; z++; } if (z >= (n + 1) / 2) lo = mid; else hi = mid - 1; } ans = max(ans, 0LL + a[n - 1].first + lo); cout << ans << "\n"; } return 0; }
1998
D
Determine Winning Islands in Race
\begin{quote} MOOOOOOOOOOOOOOOOO \hfill — Bessie the Cow, The Art of Racing on Islands \end{quote} Two of Farmer John's cows, Bessie and Elsie, are planning to race on $n$ islands. There are $n - 1$ main bridges, connecting island $i$ to island $i + 1$ for all $1 \leq i \leq n - 1$. Additionally, there are $m$ alternative bridges. Elsie can use \textbf{both} main and alternative bridges, while Bessie can only use main bridges. All bridges are \textbf{one way} and can only be used to travel from an island with a lower index to an island with a higher index. Initially, Elsie starts on island $1$, and Bessie starts on island $s$. The cows alternate turns, with Bessie making the first turn. Suppose the cow is on island $i$. During a cow's turn, if there are any bridges connecting island $i$ to island $j$, then the cow can move to island $j$. Then, island $i$ collapses, and all bridges connecting to island $i$ also collapse. Also, note the following: - If there are no bridges connecting island $i$ to another island, then island $i$ collapses, and this cow is eliminated from the race. - If the other cow is also on island $i$, then after this cow moves to another island, the island collapses, and the other cow is eliminated from the race. - After an island or bridge collapses, no cows may use them. - If a cow is eliminated, their turn is skipped for the rest of the race. The race ends once either cow reaches island $n$. It can be shown that regardless of the cows' strategies, at least one cow reaches island $n$. Bessie wins if and only if she reaches island $n$ first. For each $1 \leq s \leq n - 1$, determine whether Bessie wins if she starts the race on island $s$. Assume both cows follow optimal strategies to ensure their own respective victories.
First, let's consider if there was no alternative bridges. Then obviously, if Bessie starts at island $i$ and keeps moving forwards, it is impossible for Elsie to move past island $i$ since the bridge would have already collapsed. From this, we can deduce that Bessie cannot let Elsie use these alternative bridges to overtake the island Bessie is on, or else Elsie will always reach the end first. Therefore, Bessie will keep moving right in hopes of breaking enough bridges so that it is impossible to for Elsie to overtake Bessie. This can be simplified to: consider we are at island $i$ and $t$ units of time has passed, for all alternative bridges that Elsie can take with an endpoint $v > i + t$, we have to reach $v$ before her. Let $d_i$ denote the minimum amount of time Elsie takes to reach island $i$. For the first case, consider all bridges with endpoints $v > S$, then $d_v \geq v - S - 1$ must hold true since we want to reach $v$ before Elsie does when we keep going right. We can rearrange the equation as $S \geq v - d_v - 1$. To make sure this holds true for all bridges, we just have to make sure this is true for the maximum value of $v - d_v$. All $d_i$ can be calculated using a linear sweep to the right, and we can track all $v - d_v$ with a sweep to the left. Note that we cannot take a bridge if it starts past $S$, so we need to track the maximum with a multiset and erasing as we sweep. Time Complexity is $\mathcal{O}(n \log n)$. There exists other solutions using prefix sums in $\mathcal{O}(n)$ and segment tree in $\mathcal{O}(n \log n)$
[ "data structures", "dp", "graphs", "greedy", "shortest paths" ]
2,100
#include <bits/stdc++.h> using namespace std; #define pb push_back #define FOR(i,a,b) for(int i = (a); i < (b); ++i) #define ROF(i,a,b) for(int i = (a); i >= (b); --i) #define trav(a,x) for(auto& a: x) void solve() { int n, m; cin >> n >> m; vector<vector<int>> g(n), rg(n); FOR(i,0,m){ int u, v; cin >> u >> v; --u; --v; g[u].pb(v); rg[v].pb(u); } FOR(i,0,n-1) g[i].pb(i+1); vector<int> dist(n, -1); queue<int> q; dist[0] = 0; q.push(0); while(!q.empty()){ int f = q.front(); q.pop(); trav(i, g[f]){ if(dist[i] == -1){ dist[i] = dist[f] + 1; q.push(i); } } } multiset<int> max_good_rights; vector<vector<int>> to_erase(n); string ans = string(n - 1, '0'); ROF(i,n-1,0){ trav(j, rg[i]){ int max_right = i - dist[j]; max_good_rights.insert(max_right); to_erase[j].pb(max_right); } trav(j, to_erase[i]){ max_good_rights.erase(max_good_rights.find(j)); } if(i < n - 1){ int max_good_right = max_good_rights.empty() ? -1 : *prev(max_good_rights.end()); if(i >= max_good_right - 1){ ans[i] = '1'; } } } cout << ans << endl; } signed main() { cin.tie(0) -> sync_with_stdio(0); int t = 1; cin >> t; for(int test = 1; test <= t; test++){ solve(); } }
1998
E1
Eliminating Balls With Merging (Easy Version)
\begin{quote} Drink water. \hfill — Sun Tzu, The Art of Becoming a Healthy Programmer \end{quote} \textbf{This is the easy version of the problem. The only difference is that $x=n$ in this version. You must solve both versions to be able to hack.} You are given two integers $n$ and $x$ ($x=n$). There are $n$ balls lined up in a row, numbered from $1$ to $n$ from left to right. Initially, there is a value $a_i$ written on the $i$-th ball. For each integer $i$ from $1$ to $n$, we define a function $f(i)$ as follows: - Suppose you have a set $S = \{1, 2, \ldots, i\}$. - In each operation, you have to select an integer $l$ ($1 \leq l < i$) from $S$ such that $l$ is not the largest element of $S$. Suppose $r$ is the smallest element in $S$ which is greater than $l$. - If $a_l > a_r$, you set $a_l = a_l + a_r$ and remove $r$ from $S$. - If $a_l < a_r$, you set $a_r = a_l + a_r$ and remove $l$ from $S$. - If $a_l = a_r$, you choose either the integer $l$ or $r$ to remove from $S$: - If you choose to remove $l$ from $S$, you set $a_r = a_l + a_r$ and remove $l$ from $S$. - If you choose to remove $r$ from $S$, you set $a_l = a_l + a_r$ and remove $r$ from $S$. - $f(i)$ denotes the number of integers $j$ ($1 \le j \le i$) such that it is possible to obtain $S = \{j\}$ after performing the above operations exactly $i - 1$ times. For each integer $i$ from $x$ to $n$, you need to find $f(i)$.
Consider the ball with the maximum number. Let this ball be $m$. That ball can clearly be the last ball remaining. And if we are able to merge some ball $i$ with ball $m$ (whilst removing $m$), then ball $i$ can also be the last ball remaining. We can do a divide and conquer solution. For some range $[l,r]$, let $m$ be the ball with the maximum value. Clearly, $m$ can be the last ball remaining if we only consider the range $[l, r]$. Let's first recurse on $[l,m)$ and $(m,r]$. Let $s_l=a_l+a_{l+1}+\cdots+a_{m-1}$ (i.e. the sum of the left half). If $s_l < a_m$ then no ball in the left half can be the last one remaining. Otherwise, the results (i.e. whether each ball can be the last one standing) for range $[l,r]$ for balls in $[l,m)$ is the results we computer when recursing onto $[l,m)$. The same reasoning holds for the right half. We can use a sparse table to find the maximum ball in any range. This leads to a $\mathcal{O}(n\log n)$ solution. For some ball $i$, let $l_i$ and $r_i$ be the first balls on the left and right that have a value greater than $a_i$. Proccess the balls from largest $a_i$ to smallest $a_i$. For each ball $i$, let $\text{ans}_i$ denote whether it can be the last ball remaining. We know that if we merge ball $i$ with some ball $j$ (while discarding $j$) and $\text{ans}_j=1$, then $\text{ans}_i=1$. Furthermore, we know that balls $l_i$ and $r_i$ can freely merge with balls $j$ where $j$ is in interval $[l_i+1 \ldots r_i-1]$ while discarding $j$ (i.e. $\text{ans}_{l_i}$ and $\text{ans}_{r_i}$ would have taken this into account). This motivates the following idea. Let $s$ be the sum of values in $[l_i+1 \ldots r_i-1]$. If $s \geq a_{l_i}$ then we do $\text{ans}_i := \text{ans}_i |\text{ans}_{l_i}$. Similarly, if $s \geq a_{r_i}$, then we do $\text{ans}_i := \text{ans}_i |\text{ans}_{r_i}$. This solution runs in $\mathcal{O}(n \log n)$ due to sorting.
[ "binary search", "brute force", "data structures", "divide and conquer", "greedy" ]
2,200
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ int n, x; cin >> n >> x; vector<int> A(n + 5); vector<ll> P(n + 5); vector<int> ans(n + 5, 0); vector<int> ord(n); set<int> S{0, n + 1}; for (int i = 1; i <= n; i++){ cin >> A[i]; P[i] = P[i - 1] + A[i]; ord.push_back(i); } sort(ord.begin(), ord.end(), [&](int a, int b){ return A[a] > A[b]; }); for (int i : ord){ int l = *(--S.lower_bound(i)); int r = *S.lower_bound(i); ll sum = P[r - 1] - P[l]; if (i == ord[0]) ans[i] = true; if (sum >= A[l]) ans[i] |= ans[l]; if (sum >= A[r]) ans[i] |= ans[r]; S.insert(i); } cout << accumulate(ans.begin(), ans.end(), 0) << "\n"; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int tc; cin >> tc; while (tc--) solve(); }
1998
E2
Eliminating Balls With Merging (Hard Version)
\begin{quote} Drink water. \hfill — Sun Tzu, The Art of Becoming a Healthy Programmer \end{quote} \textbf{This is the hard version of the problem. The only difference is that $x=1$ in this version. You must solve both versions to be able to hack.} You are given two integers $n$ and $x$ ($x=1$). There are $n$ balls lined up in a row, numbered from $1$ to $n$ from left to right. Initially, there is a value $a_i$ written on the $i$-th ball. For each integer $i$ from $1$ to $n$, we define a function $f(i)$ as follows: - Suppose you have a set $S = \{1, 2, \ldots, i\}$. - In each operation, you have to select an integer $l$ ($1 \leq l < i$) from $S$ such that $l$ is not the largest element of $S$. Suppose $r$ is the smallest element in $S$ which is greater than $l$. - If $a_l > a_r$, you set $a_l = a_l + a_r$ and remove $r$ from $S$. - If $a_l < a_r$, you set $a_r = a_l + a_r$ and remove $l$ from $S$. - If $a_l = a_r$, you choose either the integer $l$ or $r$ to remove from $S$: - If you choose to remove $l$ from $S$, you set $a_r = a_l + a_r$ and remove $l$ from $S$. - If you choose to remove $r$ from $S$, you set $a_l = a_l + a_r$ and remove $r$ from $S$. - $f(i)$ denotes the number of integers $j$ ($1 \le j \le i$) such that it is possible to obtain $S = \{j\}$ after performing the above operations exactly $i - 1$ times. For each integer $i$ from $x$ to $n$, you need to find $f(i)$.
Consider the naive greedy solution. We continuously merge with the balls on the left and right without removing our ball until we can't anymore or our ball is the final remaining one. Suppose at some point in this greedy approach, we can not merge with the balls on our left and right anymore without discarding our ball. Let our ball be $i$. Then we have the following cases. There is a ball $l$ on the left of $i$ and ball $r$ on the right of $i$. Then: $\min(a_l,a_r) > a_{l+1}+a_{l+2}+\cdots+a_{r-1}$. There is a ball $l$ on the left of $i$ but no ball on the right of $i$. Then: $a_l > a_{l+1}+a_{l+2}+\cdots+a_{\text{last}}$. There exists no ball on the left of $i$ but a ball $r$ on the right of $i$. Then: $a_r > a_1+a_2+\cdots+a_{r-1}$. For some ball $i$, if there exists some $l$ and/or some $r$ such that one of the above is true, then there exists no way for our ball to be the last one remaining. Otherwise, the ball can be the last one remaining. Let $p$ be the prefix sum array of $a$ (i.e. $p_i=a_1+a_2+\cdots+a_i$). For some ball $i$, we want to do the following. Find the smallest $r_1$ such that there exists some $l$ such that ($l, r_1$) is a pair (i.e. $\min(a_l,a_{r_1}) > a_{l+1}+a_{l+2}+\cdots+a_{r_1-1}$). Finding this is more difficult than the other cases and will be focused on later. Find the smallest $r_2$ such that $a_{r_2} > a_1+a_2+\cdots+a_{{r_r}-1}$. We can rewrite it as as $a_{r_2} > p_{r_2-1}$ and it can easily be found. Find the smallest $r_l$ such that there exists no $l$ on the left of $i$ such that $a_l > a_{l+1}+a_{l+2}+\cdots+a_{r_l}$. We can rewrite the inequality as finding the first $r_l$ such that $p_{r_l} \geq a_l + p_l$ which can be done with binary search. Suppose at some $i$, we know its $r_l$, $r_1$, and $r_{2}$. Then we know ball $i$ can be the last one remaining for prefixes spanning from $r_l$ to $\min(r_1-1, r_{2}-1)$ so we can do a range add with prefix sums. The only thing we have not resolved yet is how to find the smallest $r_1$ for some $i$ such that $\min(a_l,a_{r_1}) > a_{l+1}+a_{l+2}+\cdots+a_{r_1-1}$. Let's iterate over $r$. For each $r$ we want to find the leftmost $l$ such that $\min(a_l,a_{r}) > a_{l+1}+a_{l+2}+\cdots+a_{r-1}$ A key observation is that we can write the following inequality as $a_l > a_{l+1}+a_{l+2}+\cdots+a_{r-1}$ and $a_r > a_{l+1}+a_{l+2}+\cdots+a_{r-1}$ (both have to be true). Using prefix sums, the equations can be rewritten as $a_l + p_l > p_{r-1}$ and $p_l > p_{r-1} - a_r$. So some $(l,r)$ works if the equation above is satisfied. Consider the second part $p_l > p_{r-1} - a_r$. We can binary search to find the range of available $l$ that satisfy this. Specifically, let $l_b$ be the lower bound of the range. Then, any $l$ in $[l_b...i)$ satisfies this. Now, let's try to satisfy $a_l + p_l > p_{r-1}$. Unfortunately, $a_l + p_l$ is not monotonic so the method above will not work. Instead, we can create a sparse table over all $a_i + p_i$. Then we can binary search to find the first $l_{opt}$ such that the maximum in range $[l_b,l_{opt}]$ (which can be found with the sparse table) is greater than $p_{r-1}$. Circling back, $r_1$ is the minimum $r$ of an interval covering $i$ which can be found with things such as sweepline. In all, this solution runs in $\mathcal{O}(n \log n)$ time.
[ "binary search", "brute force", "data structures", "divide and conquer", "greedy", "implementation" ]
2,500
#include <bits/stdc++.h> using namespace std; #define ll long long void solve(){ int n, x; cin >> n >> x; vector<ll> A(n + 5, 0); vector<ll> P(n + 5, 0); vector<vector<ll>> rmq(n + 5, vector<ll>(18, 0)); for (int i = 1; i <= n; i++){ cin >> A[i]; P[i] = P[i - 1] + A[i]; rmq[i][0] = A[i] + P[i]; } for (int j = 1; j <= 17; j++) for (int i = 1; i + (1 << j) - 1 <= n; i++) rmq[i][j] = max(rmq[i][j - 1], rmq[i + (1 << (j - 1))][j - 1]); vector<vector<int>> add(n + 5), rem(n + 5); auto ins = [&](int l, int r, int v){ l = max(l, 1); if (l > r) return; add[l].push_back(v); rem[r + 1].push_back(v); }; for (int r = 1; r <= n; r++){ // r is a roadblock if (A[r] > P[r - 1]) ins(1, r - 1, r); // Find leftmost l possible int lowerB = upper_bound(P.begin() + 1, P.begin() + n + 1, P[r - 1] - A[r]) - P.begin(); int lo = lowerB, hi = r - 1; while (lo < hi){ int mid = (lo + hi) / 2; // Query lowerB...mid int lg = 31 - __builtin_clz(mid - lowerB + 1); ll val = max(rmq[lowerB][lg], rmq[mid - (1 << lg) + 1][lg]); val > P[r - 1] ? hi = mid : lo = mid + 1; } ins(lo + 1, r - 1, r); } multiset<int> badR{n + 1}; vector<int> ans(n + 5, 0); ll worst = 0; for (int i = 1; i <= n; i++){ for (int v : add[i]) badR.insert(v); for (int v : rem[i]) badR.erase(badR.find(v)); int l = lower_bound(P.begin() + i, P.begin() + n + 1, worst) - P.begin(); int r = *badR.begin(); // Active for interval [l...r) if (l <= r){ ans[l]++; ans[r]--; } worst = max(worst, A[i] + P[i]); } for (int i = x; i <= n; i++){ ans[i] += ans[i - 1]; cout << ans[i] << " \n"[i == n]; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int tc; cin >> tc; while (tc--) solve(); }
1999
A
A+B Again?
Given a two-digit positive integer $n$, find the sum of its digits.
You can take the input as a string and output the sum of the two characters in the string. There is also a formula: $\lfloor \frac{n}{10} \rfloor + n \bmod 10$. The first term is the tens digit, the second term - the ones digit.
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; cout << (n / 10) + (n % 10) << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} // solve(); }
1999
B
Card Game
Suneet and Slavic play a card game. The rules of the game are as follows: - Each card has an integer value between $1$ and $10$. - Each player receives $2$ cards which are face-down (so a player doesn't know their cards). - The game is turn-based and consists \textbf{exactly of two turns}. In a round, both players pick a \textbf{random unflipped} card and flip it. The player who flipped a card with a strictly greater number wins the round. In case of equality, no one wins the round. - A player wins a game if he wins the most number of rounds (i.e. strictly greater than the other player). In case of equality, no one wins the game. Since Suneet and Slavic aren't best friends, you need to calculate the number of ways the game could happen that Suneet would end up as the winner. For a better understanding, please check the notes section.
For each test case, we can brute force through all possible games (there are only four of them) and calculate who is the winner of the game by simulating the game.
[ "brute force", "constructive algorithms", "implementation" ]
1,000
def f(a, b): if (a > b): return 1 if (a == b): return 0 if (a < b): return -1 for _ in range(int(input())): a, b, c, d = map(int, input().split()) ans = 0 if f(a, c) + f(b, d) > 0: ans += 1 if f(a, d) + f(b, c) > 0: ans += 1 if f(b, c) + f(a, d) > 0: ans += 1 if f(b, d) + f(a, c) > 0: ans += 1 print(ans)
1999
C
Showering
As a computer science student, Alex faces a hard challenge — showering. He tries to shower daily, but despite his best efforts there are always challenges. He takes $s$ minutes to shower and a day only has $m$ minutes! He already has $n$ tasks planned for the day. Task $i$ is represented as an interval $(l_i$, $r_i)$, which means that Alex is busy and can not take a shower in that time interval (at any point in time strictly between $l_i$ and $r_i$). \textbf{No two tasks overlap.} Given all $n$ time intervals, will Alex be able to shower that day? In other words, will Alex have a free time interval of length at least $s$? \begin{center} {\small In the first test case, Alex can shower for the first $3$ minutes of the day and not miss any of the tasks.} \end{center}
We just need to find the lengths of the gaps between intervals. Note that from the additional constraint on the input, the intervals are in sorted order. So you need to find if for any $i > 1$, $l_i - r_{i - 1} \geq s$, and also if $l_1 \geq s$ (the initial interval), or if $m - r_{n} \geq s$ (the final interval).
[ "greedy", "implementation" ]
800
def solve(): n, s, m = map(int, input().split()) segs = [[0, 0], [m, m]] + [list(map(int, input().split())) for i in range(n)] segs.sort() for i in range(1, n + 2): if segs[i][0] - segs[i - 1][1] >= s: print('YES') return print('NO') #sys.stdin = open('in', 'r') for _ in range(int(input())): solve()
1999
D
Slavic's Exam
Slavic has a very tough exam and needs your help in order to pass it. Here is the question he is struggling with: There exists a string $s$, which consists of lowercase English letters and possibly zero or more "?". Slavic is asked to change each "?" to a lowercase English letter such that string $t$ becomes a subsequence (not necessarily continuous) of the string $s$. Output any such string, or say that it is impossible in case no string that respects the conditions exists.
Let's use a greedy strategy with two pointers, one at the start of $s$ (called $i$) and one at the start of $t$ (called $j$). At each step, advance $i$ by $1$. If $s_i = \texttt{?}$, then we set it to $t_j$ and increment $j$. If $s_i = t_j$ then we also increment $j$ (because there is a match). It works because if there is ever a question mark, it never makes it worse to match the current character in $t$ earlier than later. The complexity is $\mathcal{O}(n)$.
[ "greedy", "implementation", "strings" ]
1,100
#include <bits/stdc++.h> using namespace std; int main() { int test_cases; cin >> test_cases; while(test_cases--) { string s, t; cin >> s >> t; int idx = 0; for(int i = 0; i < (int)s.size(); ++i) { if(s[i] == '?') { if(idx < (int)t.size()) s[i] = t[idx++]; else s[i] = 'a'; } else if(s[i] == t[idx]) ++idx; } if(idx >= t.size()) cout << "YES\n" << s << "\n"; else cout << "NO\n"; } }
1999
E
Triple Operations
On the board Ivy wrote down all integers from $l$ to $r$, inclusive. In an operation, she does the following: - pick two numbers $x$ and $y$ on the board, erase them, and in their place write the numbers $3x$ and $\lfloor \frac{y}{3} \rfloor$. (Here $\lfloor \bullet \rfloor$ denotes rounding down to the nearest integer). What is the minimum number of operations Ivy needs to make all numbers on the board equal $0$? We have a proof that this is always possible.
Consider writing the numbers in ternary (it is like binary but instead we use three digits, and for clarity we will use "digit" in the solution instead of "bit" or "trit"). In the operation, we will add a $0$ to the end of the number $x$ and remove the last digit of $y$. For example, if $x=8$ and $y=11$, then in ternary the numbers are $22_{3}$ and $102_{3}$. After the operation, $x=24$ and $y=3$, and indeed in ternary they are $220_{3}$ and $10_{3}$. (This is because multiplying by $3$ is multiplying by $10_{3}$, and similarly dividing by $3$ is like dividing by $10_{3}$.) This means that the total number of digits across all numbers does not change (since we add one digit and remove one digit). So how is it possible to make all numbers $0$? Well, there is one exception to the above rule: when we use the operation with $x=0$, we add a $0$ to the end of the number $0$, but this added digit doesn't count (because $3 \cdot 0 = 0$). This means that if we ever do the operation with $x=0$, then we will lose one digit total (since $x$ doesn't gain a digit, but $y$ loses a digit). This means the solution is as follows: first, we make one of the numbers equal to $0$. Then, we will use this $0$ to remove all the digits of all other numbers. To use the fewest number of operations possible, we should do the first step on the minimum number, since it has the fewest digits. Let $f(x)$ denote the number of ternary digits in the number $x$ (actually, $f(x) = \lfloor \log_3 (x) \rfloor + 1$). Then the first step takes $f(l)$ operations (since $l$ is the smallest number in the range $[l, r]$), and the second step takes $f(l) + \cdots + f(r)$ operations (since we need to remove all the digits, which is the total number of digits from $l$ to $r$). This means the answer for each test case is $f(l) + f(l) + \cdots + f(r)$. To find this sum quickly, we can compute prefix sums on $f$ so that the answer is simply $f(l) + \mathrm{psum}(r) - \mathrm{psum}(l-1)$, which takes $\mathcal{O}(1)$ time per test case with $\mathcal{O}(n)$ precomputation.
[ "dp", "implementation", "math" ]
1,300
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; int a[MAX], psum[MAX]; int f(int x) { int cnt = 0; while (x) { x /= 3; cnt++; } return cnt; } void solve() { int l, r; cin >> l >> r; cout << psum[r] - psum[l - 1] + a[l] << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); psum[0] = 0; for (int i = 1; i < MAX - 1; i++) { a[i] = f(i); psum[i] = psum[i - 1] + a[i]; } int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} // solve(); }
1999
F
Expected Median
Arul has a \textbf{binary} array$^{\text{∗}}$ $a$ of length $n$. He will take all subsequences$^{\text{†}}$ of length $k$ ($k$ is odd) of this array and find their median.$^{\text{‡}}$ What is the sum of all these values? As this sum can be very large, output it modulo $10^9 + 7$. In other words, print the remainder of this sum when divided by $10^9 + 7$. \begin{footnotesize} $^{\text{∗}}$A binary array is an array consisting only of zeros and ones. $^{\text{†}}$An array $b$ is a subsequence of an array $a$ if $b$ can be obtained from $a$ by the deletion of several (possibly, zero or all) elements. Subsequences \textbf{don't} have to be contiguous. $^{\text{‡}}$The median of an array of odd length $k$ is the $\frac{k+1}{2}$-th element when sorted. \end{footnotesize}
Say the array has $x$ ones and $y$ zeroes. If the median of a subsequence of length $k$ is $1$, then there are at least $\lfloor \frac{k}{2} \rfloor + 1$ ones in the array. Let's iterate over the number of ones in the subsequence from $\lfloor \frac{k}{2} \rfloor + 1$ to $x$. Suppose there are $i$ ones. Then there are $k - i$ zeroes. The number of ways to choose $i$ ones from $x$ is $\binom{x}{i}$, that is, $x$ choose $i$ (this is the so-called binomial coefficient). Similarly, the number of ways to choose $k-i$ zeroes from $y$ of them is $\binom{y}{k-i}$. Therefore the answer is the sum of $\binom{x}{i}\binom{y}{k-i}$ over all $i$ from $\lfloor \frac{k}{2} \rfloor + 1$ to $x$. You can compute binomial coefficients in many ways, for example precomputing all factorials and then using the formula $\binom{n}{k} = \frac{n!}{(n-k)!k!}$. Depending on your implementation, it can take $\mathcal{O}(n \log \mathrm{MOD})$ or $\mathcal{O}(n + \log \mathrm{MOD})$ time. If you don't know how to do that, we recommend you read the article.
[ "combinatorics", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5, mod = 1e9 + 7; int64_t fact[N]; int64_t pw(int64_t a, int64_t b) { int64_t r = 1; while(b > 0) { if(b & 1) r = (r * a) % mod; b /= 2; a = (a * a) % mod; } return r; } int64_t C(int64_t n, int64_t k) { if(n < k) return 0LL; return (fact[n] * pw((fact[n - k] * fact[k]) % mod, mod - 2)) % mod; } int main() { int t; cin >> t; fact[0] = 1; for(int64_t i = 1; i < N; ++i) fact[i] = (fact[i - 1] * i) % mod; while(t--) { int n, k; cin >> n >> k; vector<int> a(n); int ones = 0; for(int i = 0; i < n; ++i) { cin >> a[i]; ones += a[i]; } //at least k/2+1 ones int64_t ans = 0; for(int cnt_ones = k / 2 + 1; cnt_ones <= min(ones, k); ++cnt_ones) { ans += C(ones, cnt_ones) * C(n - ones, k - cnt_ones) % mod; ans %= mod; } cout << ans << "\n"; } }
1999
G1
Ruler (easy version)
This is the easy version of the problem. The only difference between the two versions is that in this version, you can make at most $\mathbf{10}$ queries. This is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants. We have a secret ruler that is missing one number $x$ ($2 \leq x \leq 999$). When you measure an object of length $y$, the ruler reports the following values: - If $y < x$, the ruler (correctly) measures the object as having length $y$. - If $y \geq x$, the ruler incorrectly measures the object as having length $y+1$. \begin{center} {\small The ruler above is missing the number $4$, so it correctly measures the first segment as length $3$ but incorrectly measures the second segment as length $6$ even though it is actually $5$.} \end{center} You need to find the value of $x$. To do that, you can make queries of the following form: - $?~a~b$ — in response, we will measure the side lengths of an $a \times b$ rectangle with our ruler and multiply the results, reporting the measured area of the rectangle back to you. For example, if $x=4$ and you query a $3 \times 5$ rectangle, we will measure its side lengths as $3 \times 6$ and report $18$ back to you. Find the value of $x$. You can ask at most $\mathbf{10}$ queries.
Consider queries of the form $\texttt{?}~~\texttt{1}~~y$. Since $x > 1$, the height of the rectangle is always measured correctly. That means: If $y < x$, the response is $y$. If $y \geq x$, the response is $y+1$.
[ "binary search", "interactive" ]
1,500
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; void solve() { int l = 2, r = 1000; while (l < r) { int mid = l + (r - l) / 2; cout << "? 1 " << mid << endl; int resp; cin >> resp; if (resp == mid) { l = mid + 1; } else { r = mid; } } cout << "! " << l << endl; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} // solve(); }
1999
G2
Ruler (hard version)
This is the hard version of the problem. The only difference between the two versions is that in this version, you can make at most $\mathbf{7}$ queries. This is an interactive problem. If you are unsure how interactive problems work, then it is recommended to read the guide for participants. We have a secret ruler that is missing one number $x$ ($2 \leq x \leq 999$). When you measure an object of length $y$, the ruler reports the following values: - If $y < x$, the ruler (correctly) measures the object as having length $y$. - If $y \geq x$, the ruler incorrectly measures the object as having length $y+1$. \begin{center} {\small The ruler above is missing the number $4$, so it correctly measures the first segment as length $3$ but incorrectly measures the second segment as length $6$ even though it is actually $5$.} \end{center} You need to find the value of $x$. To do that, you can make queries of the following form: - $?~a~b$ — in response, we will measure the side lengths of an $a \times b$ rectangle with our ruler and multiply the results, reporting the measured area of the rectangle back to you. For example, if $x=4$ and you query a $3 \times 5$ rectangle, we will measure its side lengths as $3 \times 6$ and report $18$ back to you. Find the value of $x$. You can ask at most $\mathbf{7}$ queries.
Consider one query of the form $\texttt{?}~~a~~b$ for $a < b$. That means: If $a < b < x$, the response is $a \cdot b$ (both $a$ and $b$ are measured correctly). If $a < x \leq b$, the response is $a \cdot (b + 1)$ ($a$ is measured correctly, but $b$ is not). If $x \leq a < b$, the repsone is $(a + 1) \cdot (b + 1)$ (both $a$ and $b$ are measured incorrectly). If we repeat this, each time dividing the search space into three equal pieces, then the number of queries needed is $\lceil \log_3(1000) \rceil = 7$. This is similar to the so-called ternary search to find the maximum of a unimodal function (although it is slightly different). You should be careful about the small case when there are only two possible values of $x$ left.
[ "binary search", "interactive", "ternary search" ]
1,700
#include <bits/stdc++.h> using namespace std; const int MAX = 200'007; const int MOD = 1'000'000'007; void solve() { int l = 1, r = 999; while (r - l > 2) { int a = (2 * l + r) / 3; int b = (2 * r + l) / 3; cout << "? " << a << ' ' << b << endl; int resp; cin >> resp; if (resp == (a + 1) * (b + 1)) { r = a; } else if (resp == a * b) { l = b; } else { l = a; r = b; } } if (r - l == 2) { cout << "? 1 " << l + 1 << endl; int resp; cin >> resp; if (resp == l + 1) {l = l + 1;} else {r = l + 1;} } cout << "! " << r << endl; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} // solve(); }
2000
A
Primary Task
Dmitry wrote down $t$ integers on the board, and that is good. He is sure that he lost an important integer $n$ among them, and that is bad. The integer $n$ had the form $\text{10^x}$ ($x \ge 2$), where the symbol '$\text{^}$' denotes exponentiation.. Something went wrong, and Dmitry missed the symbol '$\text{^}$' when writing the important integer. For example, instead of the integer $10^5$, he would have written $105$, and instead of $10^{19}$, he would have written $1019$. Dmitry wants to understand which of the integers on the board could have been the important integer and which could not.
You need to check that the number has the form '$\text{10x}$', where $x$ is an integer without leading zeros. This means it must start with '10'; if the length of the number is $3$, then the third digit must be at least $2$; if the length is greater, then the third digit must be at least $1$ (all such numbers $x$ are at least $10$). Additionally, under these constraints, you can simply check that for the given number $a$, either $102 \le a \le 109$ or $1010 \le a \le 1099$ holds true.
[ "implementation", "math", "strings" ]
800
for _ in range(int(input())): a = int(input()) if 102 <= a <= 109 or 1010 <= a <= 1099: print("YES") else: print("NO")
2000
B
Seating in a Bus
In Berland, a bus consists of a row of $n$ seats numbered from $1$ to $n$. Passengers are advised to always board the bus following these rules: - If there are no occupied seats in the bus, a passenger can sit in any free seat; - Otherwise, a passenger should sit in any free seat that has at least one occupied neighboring seat. In other words, a passenger can sit in a seat with index $i$ ($1 \le i \le n$) only if at least one of the seats with indices $i-1$ or $i+1$ is occupied. Today, $n$ passengers boarded the bus. The array $a$ chronologically records the seat numbers they occupied. That is, $a_1$ contains the seat number where the first passenger sat, $a_2$ — the seat number where the second passenger sat, and so on. You know the contents of the array $a$. Determine whether all passengers followed the recommendations. For example, if $n = 5$, and $a$ = [$5, 4, 2, 1, 3$], then the recommendations were not followed, as the $3$-rd passenger sat in seat number $2$, while the neighboring seats with numbers $1$ and $3$ were free.
To solve the problem, it is enough to use an array $used$ of size $2 \cdot 10^5 + 1$ (maximal value $n + 1$) consisting of boolean variables. When a passenger gets on the bus to seat $a_i$, we will replace the value of $used[a_i]$ with true. Then, for all passengers, starting from the second one, we should check that at least one of the existing elements $used[a_i - 1]$ or $used[a_i + 1]$ has the value true. If this condition is not satisfied, the answer to the problem is "NO". If at least $1$ occupied neighbouring seat always existed for all passengers at the moment they took their seat - the answer is "YES".
[ "two pointers" ]
800
#include <bits/stdc++.h> using namespace std; void solve(){ int n; cin >> n; vector<int>a(n); for(auto &i : a) cin >> i; int left = a[0], right = a[0]; for(int i = 1; i < n; i++){ if(a[i] + 1 == left) left = a[i]; else if(a[i] - 1 == right) right = a[i]; else { cout << "NO\n"; return; } } cout << "YES\n"; } int main(){ int t; cin >> t; while (t--) { solve(); } return 0; }
2000
C
Numeric String Template
Kristina has an array $a$, called a template, consisting of $n$ integers. She also has $m$ strings, each consisting only of lowercase Latin letters. The strings are numbered from $1$ to $m$. She wants to check which strings match the template. A string $s$ is considered to match the template if all of the following conditions are simultaneously satisfied: - The length of the string $s$ is equal to the number of elements in the array $a$. - The same numbers from $a$ correspond to the same symbols from $s$. So, if $a_i = a_j$, then $s_i = s_j$ for ($1 \le i, j \le n$). - The same symbols from $s$ correspond to the same numbers from $a$. So, if $s_i = s_j$, then $a_i = a_j$ for ($1 \le i, j \le n$). In other words, there must be a one-to-one correspondence between the characters of the string and the elements of the array.For example, if $a$ = [$3, 5, 2, 1, 3$], then the string "abfda" matches the template, while the string "afbfa" does not, since the character "f" corresponds to both numbers $1$ and $5$.
To solve the problem, we can use two dictionaries (map): match the characters of the string to the numbers of the array in the map $m_1$ and the numbers of the array to the characters of the string in the map $m_2$. First, we check the length of the string to see if it is equal to the number $n$. If the string is longer or shorter, the answer is "NO". Otherwise, we will loop through the characters of the string and check the following conditions: The map $m_1$ does not contain the character $s_i$ as a key, and the map $m_2$ does not contain the number $a_i$ as a key. Then let's perform the assignments $m_1[s_i] = a_i$ and $m_2[a_i] = s_i$. One of the maps contains the current array element or string character as a key, but its value does not match the character or number in the current position. Then the answer to the problem is - "NO", you can break the loop. If the loop reaches the end of the line, the answer to the problem is "YES".
[ "data structures", "strings" ]
1,000
def solve(): n = int(input()) a = list(map(int, input().split())) m = int(input()) for _ in range(m): m_1 = {} m_2 = {} s = input().strip() if len(s) != n: print("NO") continue ok = True for j in range(n): if s[j] not in m_1 and a[j] not in m_2: m_1[s[j]] = a[j] m_2[a[j]] = s[j] elif (s[j] in m_1 and m_1[s[j]] != a[j]) or (a[j] in m_2 and m_2[a[j]] != s[j]): ok = False break print("YES" if ok else "NO") t = int(input()) for _ in range(t): solve()
2000
D
Right Left Wrong
Vlad found a strip of $n$ cells, numbered from left to right from $1$ to $n$. In the $i$-th cell, there is a positive integer $a_i$ and a letter $s_i$, where all $s_i$ are either 'L' or 'R'. Vlad invites you to try to score the maximum possible points by performing any (possibly zero) number of operations. In one operation, you can choose two indices $l$ and $r$ ($1 \le l < r \le n$) such that $s_l$ = 'L' and $s_r$ = 'R' and do the following: - add $a_l + a_{l + 1} + \dots + a_{r - 1} + a_r$ points to the current score; - replace $s_i$ with '.' for all $l \le i \le r$, meaning you can no longer choose these indices. For example, consider the following strip: \begin{center} \begin{tabular}{|c||c||c||c||c||c|} \hline $3$ & $5$ & $1$ & $4$ & $3$ & $2$ \ \hline \hline L & R & L & L & L & R \ \hline \end{tabular} \end{center} You can first choose $l = 1$, $r = 2$ and add $3 + 5 = 8$ to your score. \begin{center} \begin{tabular}{|c||c||c||c||c||c|} \hline $3$ & $5$ & $1$ & $4$ & $3$ & $2$ \ \hline \hline . & . & L & L & L & R \ \hline \end{tabular} \end{center} Then choose $l = 3$, $r = 6$ and add $1 + 4 + 3 + 2 = 10$ to your score. \begin{center} \begin{tabular}{|c||c||c||c||c||c|} \hline $3$ & $5$ & $1$ & $4$ & $3$ & $2$ \ \hline \hline . & . & . & . & . & . \ \hline \end{tabular} \end{center} As a result, it is impossible to perform another operation, and the final score is $18$. What is the maximum score that can be achieved?
Note that since all characters of the selected segment of the string $s$ are erased after applying the operation, the segments we choose cannot overlap. However, they can be nested if we first choose an inner segment and then an outer one. Since all numbers in the array are positive, it is always beneficial to take the largest possible segment in the answer, that is, from the first 'L' to the last 'R'. By choosing this segment, we can only select segments within it. We will continue to choose such segments within the last selected one as long as possible. To quickly find the sums of the segments, we will calculate the prefix sums of the array $a$.
[ "greedy", "implementation", "two pointers" ]
1,200
def solve(): n = int(input()) a = [0] for x in input().split(): x = int(x) a.append(a[-1] + x) s = input() ans = 0 l = 0 r = n - 1 while r > l: while l < n and s[l] == 'R': l += 1 while r >= 0 and s[r] == 'L': r -= 1 if l < r: ans += a[r + 1] - a[l] l += 1 r -= 1 print(ans) t = int(input()) for _ in range(t): solve()
2000
E
Photoshoot for Gorillas
You really love gorillas, so you decided to organize a photoshoot for them. Gorillas live in the jungle. The jungle is represented as a grid of $n$ rows and $m$ columns. $w$ gorillas agreed to participate in the photoshoot, and the gorilla with index $i$ ($1 \le i \le w$) has a height of $a_i$. You want to place \textbf{all} the gorillas in the cells of the grid such that there is \textbf{no more than one gorilla} in each cell. The spectacle of the arrangement is equal to the sum of the spectacles of all sub-squares of the grid with a side length of $k$. The spectacle of a sub-square is equal to the sum of the heights of the gorillas in it. From all suitable arrangements, choose the arrangement with the \textbf{maximum} spectacle.
We will learn how to find the number of sub-squares that cover the cell $(i, j)$: $(\min(i, n - k) - \max(-1, i - k)) \cdot (\min(j, m - k) - \max(-1, j - k))$. Next, we will use a straightforward greedy algorithm: we will place the tallest gorillas in the cells covered by the maximum number of squares. This can be done using two std::sort operations and a linear pass. The time complexity of the solution is: $O(n \cdot m \log (n \cdot m) + w \log w)$.
[ "combinatorics", "data structures", "greedy", "math" ]
1,400
#include <bits/stdc++.h> #define int long long using namespace std; #define MAXW 200200 #define MAXNM 200200 int n, m, k, w, p; int arr[MAXW], prr[MAXNM]; static inline int calcc(int i, int j) { int upr = min(i, n - k); int leftr = min(j, m - k); int upl = max(-1LL, i - k); int leftl = max(-1LL, j - k); return (upr - upl) * (leftr - leftl); } void build() { sort(arr, arr + w); reverse(arr, arr + w); p = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) prr[p++] = calcc(i, j); sort(prr, prr + p); reverse(prr, prr + p); } int solve() { int sum = 0; for (int i = 0; i < w; ++i) sum += prr[i] * arr[i]; return sum; } signed main() { int t; cin >> t; while (t--) { cin >> n >> m >> k >> w; for (int i = 0; i < w; ++i) cin >> arr[i]; build(); cout << solve() << endl; } }
2000
F
Color Rows and Columns
You have $n$ rectangles, the $i$-th of which has a width of $a_i$ and a height of $b_i$. You can perform the following operation an unlimited number of times: choose a rectangle and a cell in it, and then color it. Each time you completely color any row or column, you earn $1$ point. Your task is to score at least $k$ points with as few operations as possible. Suppose you have a rectangle with a width of $6$ and a height of $3$. You can score $4$ points by coloring all the cells in any $4$ columns, thus performing $12$ operations.
We will use the idea from the knapsack problem: let $dp[i][j]$ be the minimum number of operations required to achieve $j$ points using the first $i$ rectangles. To calculate the next value, we will iterate over the number of points scored in the $i$-th rectangle. To count the number of operations, we note that it is always better to paint the outer row of the smaller side of the unpainted part of the rectangle (which may change after painting the row).
[ "dp", "greedy", "implementation", "math" ]
1,900
#include <iostream> #include <algorithm> #include <vector> using namespace std; void solve() { int n, k; cin >> n >> k; vector<int> a(n), b(n); for (int i = 0; i < n; ++i) { cin >> a[i] >> b[i]; } vector<vector<int>> dp(n + 1, vector<int>(k + 1, 1e9)); dp[0][0] = 0; for (int i = 0; i < n; ++i) { int x = a[i], y = b[i]; int xy = x + y; int cost = 0; for (int j = 0; j <= xy; ++j) { for (int j1 = 0; j1 + j <= k; ++j1) { dp[i + 1][j1 + j] = min(dp[i + 1][j1 + j], dp[i][j1] + cost); } if (j < xy) { if (x >= y) { x--, cost += y; } else { y--, cost += x; } } } } cout << (dp[n][k] == 1e9 ? -1 : dp[n][k]) << '\n'; } int main() { int t; cin >> t; for (int i = 0; i < t; ++i) { solve(); } return 0; }
2000
G
Call During the Journey
You live in a city consisting of $n$ intersections and $m$ streets connecting some pairs of intersections. You can travel in either direction on each street. No two streets connect the same pair of intersections, and no street connects an intersection to itself. You can reach any intersection from any other, possibly passing through some other intersections. Every minute, you can board a bus at intersection $u_i$ and travel for $l_{i1}$ minutes to intersection $v_i$. Conversely, you can travel from intersection $v_i$ to intersection $u_i$ in $l_{i1}$ minutes. You can only board and exit the bus at intersections. You can only board the bus at an intersection if you are currently there. You can also walk along each street, which takes $l_{i2} > l_{i1}$ minutes. You can make stops at intersections. You live at intersection number $1$. Today you woke up at time $0$, and you have an important event scheduled at intersection number $n$, which you must reach no later than time $t_0$. You also have a phone call planned that will last from $t_1$ to $t_2$ minutes ($t_1 < t_2 < t_0$). During the phone call, you cannot ride the bus, but you can walk along any streets, make stops, or stay at home. You can exit the bus at minute $t_1$ and board the bus again at minute $t_2$. Since you want to get enough sleep, you became curious — how late can you leave home to have time to talk on the phone and still not be late for the event?
Let's find the maximum time $ans_i$ for each vertex, at which it is possible to leave from it and reach vertex $n$ at time $t_0$. To find this value, we will run Dijkstra's algorithm from the last vertex. When processing the next edge, we will check if it is possible to travel by bus during the time interval from $ans_v - l_{i1}$ to $ans_v$. If it is possible, we will travel by bus; otherwise, we will either walk or wait at this vertex and then go by bus.
[ "binary search", "brute force", "graphs", "greedy", "shortest paths" ]
2,100
#include <iostream> #include <vector> #include <set> using namespace std; void solve() { int n, m; cin >> n >> m; int t0, t1, t2; cin >> t0 >> t1 >> t2; vector<vector<vector<int>>> g(n); for (int i = 0; i < m; ++i) { int u, v, l1, l2; cin >> u >> v >> l1 >> l2; u--, v--; g[u].push_back({v, l1, l2}); g[v].push_back({u, l1, l2}); } set<pair<int, int>> prq; prq.insert({t0, n - 1}); for (int i = 0; i + 1 < n; ++i) { prq.insert({-1e9, i}); } vector<int> dist(n, -1e9); dist[n - 1] = t0; while (!prq.empty()) { auto p = *prq.rbegin(); prq.erase(p); int d = p.first, u = p.second; for (auto e: g[u]) { int v = e[0], l1 = e[1], l2 = e[2]; int d1 = (d - l1 >= t2 || d <= t1) ? d - l1 : d - l2; if(d1 == d - l2) d1 = max(d1, t1 - l1); if (dist[v] < d1) { prq.erase({dist[v], v}); dist[v] = d1; prq.insert({d1, v}); } } } cout << (dist[0] >= 0 ? dist[0] : -1) << '\n'; } int main() { int t; cin >> t; for (int i = 0; i < t; ++i) { solve(); } return 0; }
2000
H
Ksyusha and the Loaded Set
Ksyusha decided to start a game development company. To stand out among competitors and achieve success, she decided to write her own game engine. The engine must support a set initially consisting of $n$ distinct integers $a_1, a_2, \ldots, a_n$. The set will undergo $m$ operations sequentially. The operations can be of the following types: - Insert element $x$ into the set; - Remove element $x$ from the set; - Report the $k$-load of the set. The $k$-load of the set is defined as the \textbf{minimum} \textbf{positive} integer $d$ such that the integers $d, d + 1, \ldots, d + (k - 1)$ do not appear in this set. For example, the $3$-load of the set $\{3, 4, 6, 11\}$ is $7$, since the integers $7, 8, 9$ are absent from the set, and no smaller value fits. Ksyusha is busy with management tasks, so you will have to write the engine. Implement efficient support for the described operations.
We will maintain the elements of a set in std::set. We will also maintain a std::set of free segments (in the form of half-intervals). These segments can be easily updated during insertion and deletion operations. In one case, we need to remove a large segment and insert two small ones; in another case, we need to remove two small ones and insert one large segment. We will find suitable segments using std::set::lower_bound. To answer the query ?, we will maintain a Cartesian tree, where the keys are pairs (length, left boundary). Additionally, we will store the minimum of all left boundaries at the nodes. Now, to answer the query, it is sufficient to cut the Cartesian tree at $k$ and take the minimum from the stored minimums. The time complexity of the solution is: $O(n \log n + m \log n)$.
[ "binary search", "brute force", "data structures", "implementation" ]
2,200
#pragma GCC optimize("O3,unroll-loops") #include <bits/stdc++.h> #define endl '\n' using namespace std; typedef pair<int, int> ipair; #define INF 1'000'000'009 #define MAXN 200200 #define MAXMEM 5'000'000 #define MAXLEN 2'000'100 #define X first #define Y second mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); struct node { node *lv = nullptr, *rv = nullptr; ipair key; int prior; int minl = INF; node(const ipair& key) : key(key), prior(rng()), minl(key.Y) {} }; static inline int minl(node *v) { return (v == nullptr ? INF : v->minl); } static inline void upd(node *v) { v->minl = min(v->key.Y, min(minl(v->lv), minl(v->rv))); } node *merge(node *s1, node *s2) { if (s1 == nullptr) return s2; if (s2 == nullptr) return s1; if (s1->prior > s2->prior) { s1->rv = merge(s1->rv, s2); upd(s1); return s1; } else { s2->lv = merge(s1, s2->lv); upd(s2); return s2; } } pair<node*, node*> split(node* &v, ipair x) { if (v == nullptr) { return {nullptr, nullptr}; } if (v->key < x) { auto [s1, s2] = split(v->rv, x); v->rv = s1; upd(v); return {v, s2}; } else { auto [s1, s2] = split(v->lv, x); v->lv = s2; upd(v); return {s1, v}; } } int n, m; int arr[MAXN]; node *mem = (node*)calloc(MAXMEM, sizeof(*mem)); node *mpos = mem; node *root; set<int> M; // [l..r) void add_seg(int l, int r) { if (l >= r) return; ipair p {r - l, l}; auto [s1, s2] = split(root, p); node *v = mpos++; *v = node(p); root = merge(merge(s1, v), s2); } void rem_dek(node* &v, const ipair& x) { if (v == nullptr) return; if (v->key == x) { v = merge(v->lv, v->rv); if (v) upd(v); return; } if (v->key < x) rem_dek(v->rv, x); else rem_dek(v->lv, x); upd(v); } // [l..r) void rem_seg(int l, int r) { if (l >= r) return; ipair p {r - l, l}; rem_dek(root, p); } void add_val(int x) { auto it = M.lower_bound(x); int clsl = (it == M.begin() ? 0 : *prev(it)); int clsr = (it == M.end() ? INF : *it); rem_seg(clsl + 1, clsr); add_seg(clsl + 1, x); if (clsr != INF) add_seg(x + 1, clsr); M.insert(x); } void rem_val(int x) { auto it = M.lower_bound(x); int clsl = (it == M.begin() ? 0 : *prev(it)); int clsr = (next(it) == M.end() ? INF : *next(it)); rem_seg(clsl + 1, x); rem_seg(x + 1, clsr); if (clsr != INF) add_seg(clsl + 1, clsr); M.erase(x); } int query(int k) { if (M.empty()) return 1; auto [s1, s2] = split(root, make_pair(k, -1)); fprintf(stderr, "AMOGUS: %p, %p\n", s1, s2); int ans = min(*M.rbegin() + 1, minl(s2)); root = merge(s1, s2); return ans; } void init() { root = nullptr; mpos = mem; M = {arr, arr + n}; add_seg(1, *M.begin()); for (auto it = M.begin(); next(it) != M.end(); ++it) add_seg(*it + 1, *next(it)); } signed main() { int t; cin >> t; while (t--) { cin >> n; for (int i = 0; i < n; ++i) cin >> arr[i]; init(); cin >> m; for (int j = 0; j < m; ++j) { char tp; cin >> tp; int x, k; switch (tp) { case '+': cin >> x; add_val(x); break; case '-': cin >> x; rem_val(x); break; case '?': cin >> k; cout << query(k) << " "; break; } } cout << endl; } }
2001
A
Make All Equal
You are given a cyclic array $a_1, a_2, \ldots, a_n$. You can perform the following operation on $a$ at most $n - 1$ times: - Let $m$ be the current size of $a$, you can choose any two adjacent elements where the previous one is no greater than the latter one (In particular, $a_m$ and $a_1$ are adjacent and $a_m$ is the previous one), and delete exactly one of them. In other words, choose an integer $i$ ($1 \leq i \leq m$) where $a_i \leq a_{(i \bmod m) + 1}$ holds, and delete exactly one of $a_i$ or $a_{(i \bmod m) + 1}$ from $a$. Your goal is to find the minimum number of operations needed to make all elements in $a$ equal.
What's the most obvious lower bound of the answer? Is the lower bound achievable? One standard way to solve optimization problem is to make observation on lower(upper) bound of the answer and prove such bound is achievable, it's useful in lot of problems. Let $x$ be one of the most frequent elements in $a$, then the answer must be at least $(n - \text{frequency of } x)$, and this lower bound is always achievable by keep erasing a non-$x$ element from $a$, and we can prove it's always possible to do so. proof: If all elements of $a$ are $x$, we are done. Otherwise, let $y$ denote all the elements that are not $x$, then $a$ would have some subarray of the form $x \ldots x, y \ldots y, x \ldots x$. In this subarray, there must exist adjacent elements that satisfy $a_i \leq a_{(i \bmod m) + 1}$, otherwise we would have $x > y > \ldots > y > x$ implying $x > x$ which leads to a contradiction.
[ "greedy", "implementation" ]
800
#include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false), cin.tie(NULL); int t; cin >> t; while(t--) { int n; cin >> n; vector<int> a(n); for(int &x : a) cin >> x; vector<int> freq(n + 1); for(int x : a) freq[x]++; cout << n - (*max_element(freq.begin(), freq.end())) << '\n'; } }
2001
B
Generate Permutation
There is an integer sequence $a$ of length $n$, where each element is initially $-1$. Misuki has two typewriters where the first one writes letters from left to right, with a pointer initially pointing to $1$, and another writes letters from right to left with a pointer initially pointing to $n$. Misuki would choose one of the typewriters and use it to perform the following operations until $a$ becomes a permutation of $[1, 2, \ldots, n]$ - write number: write the minimum \textbf{positive} integer that isn't present in the array $a$ to the element $a_i$, $i$ is the position where the pointer points at. Such operation can be performed only when $a_i = -1$. - carriage return: return the pointer to its initial position (i.e. $1$ for the first typewriter, $n$ for the second) - move pointer: move the pointer to the next position, let $i$ be the position the pointer points at before this operation, if Misuki is using the first typewriter, $i := i + 1$ would happen, and $i := i - 1$ otherwise. Such operation can be performed only if after the operation, $1 \le i \le n$ holds. Your task is to construct any permutation $p$ of length $n$, such that the minimum number of carriage return operations needed to make $a = p$ is the same no matter which typewriter Misuki is using.
Write a few small cases (ex. $n = 3, 4, 5$) and play with it, can you notice something interesting about the cost function? Write a few examples and play with it is a good start to solve ad-hoc problems. Consider subtask - decision version of the problem (i.e. yes/no problem) as follow: "Given a fixed $p$, check if this permutation is valid." The above problem would reduce to finding minimum number of carriage return operations needed for each typewriter. Now you know how to solve above problem, do you notice something interesting about the cost function? In lot of problems, decision version of the problem is usually a useful subtask to consider. Let $c_1, c_2$ denote the minimum number of carriage return operations needed to make $a = p$ if Misuki is using first/second typewritter. Let's consider how to calculate them. For $c_1$, we need to do carriage return operation whenever the position of value $x + 1$ is before $x$, for all $x \in [1, n - 1]$, so $c_1 = (\text{#}x \in [1, n - 1] \text{ such that } \mathrm{pos}_x > \mathrm{pos}_{x + 1})$. Similarly, $c_2 = (\text{#}x \in [1, n - 1] \text{ such that } \mathrm{pos}_x < \mathrm{pos}_{x + 1})$. Since for $x \in [1, n - 1]$, either $\mathrm{pos}_x < \mathrm{pos}_{x + 1}$ or $\mathrm{pos}_x > \mathrm{pos}_{x + 1}$ would hold, so we have $c_1 + c_2 = n - 1$, which is a constant, and $c_1 = c_2 \leftrightarrow c_1 = \frac{n - 1}{2}$, which only has solution when $n$ is odd, and such $p$ can be constructed easily (for example, ${n - 1, n, n - 3, n - 2, ..., 4, 5, 2, 3, 1}$).
[ "constructive algorithms" ]
800
#include <iostream> #include <numeric> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false), cin.tie(NULL); int t; cin >> t; while(t--) { int n; cin >> n; if (n % 2 == 0) { cout << -1 << '\n'; } else { vector<int> p(n); iota(p.begin(), p.end(), 1); for(int i = 1; i < n; i += 2) swap(p[i], p[i + 1]); for(int i = 0; i < n; i++) cout << p[i] << " \n"[i + 1 == n]; } } }
2001
C
Guess The Tree
This is an interactive problem. Misuki has chosen a secret tree with $n$ nodes, indexed from $1$ to $n$, and asked you to guess it by using queries of the following type: - "? a b" — Misuki will tell you which node $x$ minimizes $|d(a,x) - d(b,x)|$, where $d(x,y)$ is the distance between nodes $x$ and $y$. If more than one such node exists, Misuki will tell you the one which minimizes $d(a,x)$. Find out the structure of Misuki's secret tree using at most $15n$ queries!
Imagine we have $n$ isolated vertices initially, can you find any edge connect two component using reasonable number of queries? Use binary search. It's easy to verify that querying $a$ and $b$ will return the midpoint of the path between $a$ and $b$. In case the path has odd length, the node closer to $a$ of the two central nodes will be returned. We will now construct the tree by expanding a connected component. Let $A = \{1\}$ and $B = \{2,\ldots,n\}$. While $B$ is not empty, choose any $b \in B$ and $a \in A$. Let $P$ be the path between $a$ and $b$. By construction, $P$ will consist of a prefix contained in $A$ and a suffix contained in $B$. We can binary search for the first $i$ such that $P_i \in B$. This will take at most $\lceil log(|P|) \rceil + 2$ queries. Then, $(P_{i-1}, P_i)$ will be an edge of the tree, so we will set $A = A \cup {P_i}$ and $B = B \backslash {P_i}$. The total number of queries will be smaller than $n \lceil log(n) \rceil + 2n = 12000$. Consider we have $n$ isolated vertices initially, and try to keep finding an edge connect two different component. Assume $u, v$ is at different component, then we have the following possible cases for the answer $x$. $x = u$: which means $u, v$ are connected by an edge and we are done. $x$ belongs to same component of $u$, seting $u := x$. $x$ belongs to same component of $v$, seting $v := x$. $x$ belongs to other component than $u, v$, in such case, either setting $u := x$ or $v := x$. in case 1. we are done, and in case 2, 3, 4, we shorten the distance between $u, v$ by about half while keeping them not belongs to same component, so we can find an edge connect two component in $O(\lg n)$ queries and we are done.
[ "binary search", "brute force", "dfs and similar", "divide and conquer", "dsu", "greedy", "interactive", "trees" ]
1,500
#include <iostream> #include <numeric> #include <vector> #include <array> using namespace std; int query(int u, int v) { cout << "? " << u + 1 << ' ' << v + 1 << '\n'; int x; cin >> x; return x - 1; } int main() { int t; cin >> t; while(t--) { int n; cin >> n; vector<array<int, 2>> e; vector<int> c(n); iota(c.begin(), c.end(), 0); auto addEdge = [&](int u, int v) { e.push_back({u, v}); vector<int> cand; for(int i = 0; i < n; i++) if (c[i] == c[v]) cand.emplace_back(i); for(int i : cand) c[i] = c[u]; }; for(int i = 0; i < n - 1; i++) { int u = 0, v = 0; while(c[v] == c[u]) v++; int x; while((x = query(u, v)) != u) { if (c[u] == c[x]) u = x; else v = x; } addEdge(u, v); } cout << "!"; for(auto [u, v] : e) cout << ' ' << u + 1 << ' ' << v + 1; cout << '\n'; } }
2001
D
Longest Max Min Subsequence
You are given an integer sequence $a_1, a_2, \ldots, a_n$. Let $S$ be the set of all possible non-empty subsequences of $a$ without duplicate elements. Your goal is to find the longest sequence in $S$. If there are multiple of them, find the one that minimizes lexicographical order after multiplying terms at odd positions by $-1$. For example, given $a = [3, 2, 3, 1]$, $S = \{[1], [2], [3], [2, 1], [2, 3], [3, 1], [3, 2], [2, 3, 1], [3, 2, 1]\}$. Then $[2, 3, 1]$ and $[3, 2, 1]$ would be the longest, and $[3, 2, 1]$ would be the answer since $[-3, 2, -1]$ is lexicographically smaller than $[-2, 3, -1]$. A sequence $c$ is a subsequence of a sequence $d$ if $c$ can be obtained from $d$ by the deletion of several (possibly, zero or all) elements. A sequence $c$ is lexicographically smaller than a sequence $d$ if and only if one of the following holds: - $c$ is a prefix of $d$, but $c \ne d$; - in the first position where $c$ and $d$ differ, the sequence $c$ has a smaller element than the corresponding element in $d$.
Forget about minimize lexicographical order. What's the size of longest $b$ we can get? It's the number of different elements. Try to minimize/maximize first element in $b$ without reducing the max size of $b$ we can get. When solving problem asking for minimize/maximize lexicographical order of something, we can often construct them by minimize/maximize first element greedily. Let's ignore the constraint where $b$ should be lexicographically smallest. How can we find the length of $b$? Apparently, it is the number of distinct elements in $a$. Let's call it $k$. Now we know how to find the maximum possible length of $b$. Let's try to construct $b$ from left to right without worsening the answer, and greedily minimize its lexicographical order. Assume we pick $a_i$ as the $j$-th element in $b$, then there should be $k - j$ distinct elements in the subarray $a[i + 1, n]$ after deleting all elements that appear in the subarray $b[1, j]$. Assume we already construct $b_1, b_2, \ldots, b_j$ where $b_j = a_i$ and we want to find $b_{j + 1}$, and let $l_x$ be the last position where $x$ occurs in the subarray $a[i + 1, n]$ or $\infty$ if it doesn't exist, then we can choose anything in $a[i + 1, \min\limits_{1 \le x \le n}(l_x)]$. And to minimize lexicographical order, we need to choose the maximum element in it if $(j + 1)$ is odd, or the minimum element otherwise. If there are multiple of them, choose the leftmost one of them is optimal since we would have a longer suffix of $a$ for future construction. Then observe for the candidate window (i.e. $a[i + 1, \min\limits_{1 \le x \le n}(l_x)]$), its left bound and right bound are non-decreasing, so we can use priority queues or set to maintain all possible candidates by storing $(a_{pos}, pos)$, and another priority queue or set to maintain all $l_x > i$. And the total time complexity is $O(nlgn)$.
[ "brute force", "constructive algorithms", "data structures", "greedy", "implementation" ]
1,900
#include <cstdint> #include <iostream> #include <set> #include <vector> using namespace std; void solve() { int N; cin >> N; vector<int> A(N); for (int &x : A) cin >> x, --x; vector<int> cnt(N, 0), is_last(N, 0), last_pos(N, -1); for (int i = N-1; i >= 0; --i) { if (!cnt[A[i]]++) is_last[i] = 1, last_pos[A[i]] = i; } vector<int> ans; multiset<int> st; int l = 0, r = -1, flag = 0; while (r+1 < N) { while (r+1 < N and (r == -1 or !is_last[r])) { ++r; if (is_last[last_pos[A[r]]]) st.emplace(A[r]); } if (st.size()) { ans.emplace_back(flag ? *begin(st) : *rbegin(st)), flag ^= 1; is_last[last_pos[ans.back()]] = 0; while (A[l] != ans.back()) { if (auto it = st.find(A[l++]); it != end(st)) st.erase(it); } st.erase(A[l++]); // no find } } int M = ans.size(); cout << M << '\n'; for (int i = 0; i < M; ++i) cout << ans[i] + 1 << " \n"[i == M-1]; } int32_t main() { ios_base::sync_with_stdio(0), cin.tie(0); int t = 1; cin >> t; for (int _ = 1; _ <= t; ++_) solve(); return 0; }