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
⌀ |
|---|---|---|---|---|---|---|---|
1856
|
E1
|
PermuTree (easy version)
|
\textbf{This is the easy version of the problem. The differences between the two versions are the constraint on $n$ and the time limit. You can make hacks only if both versions of the problem are solved.}
You are given a tree with $n$ vertices rooted at vertex $1$.
For some permutation$^\dagger$ $a$ of length $n$, let $f(a)$ be the number of pairs of vertices $(u, v)$ such that $a_u < a_{\operatorname{lca}(u, v)} < a_v$. Here, $\operatorname{lca}(u,v)$ denotes the lowest common ancestor of vertices $u$ and $v$.
Find the maximum possible value of $f(a)$ over all permutations $a$ of length $n$.
$^\dagger$ 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).
|
Let's consider the subproblem of maximizing the number of suitable pairs for some fixed $\operatorname{lca}(u, v) = x$. Then, we want to maximize the number of pairs $(u, v)$ such that $a_u < a_x < a_v$ and $u$ and $v$ are in different subtrees of $x$. So for each subtree of $x$, we only care about the number of vertices with $a_v > a_{x}$ and about the number of vertices with $a_v < a_x$. Suppose vertex $x$ has $m$ subtrees and the $i$-th of them has $s_i$ vertices in it and $b_i$ vertices less with $a_v < a_x$. We will prove later that a suitable permutation $a$ exists for all possible correct values of $b_i$ (that is $0 \le b_i \le s_i$). Then, the total number of suitable pairs (and the value we are trying to maximize) is equal to: $(s_1 - b_1) \cdot(0 + b_2 + \ldots + b_m) + (s_2 - b_2) \cdot(b_1 + 0 + \ldots + b_m) + \ldots + (s_m - b_m) \cdot(b_1 + b_2 + \ldots + 0)$. Let $dp[i][B]$ be the maximum possible number of suitable pairs such that $u$ and $v$ lie in the first $i$ subtrees and $b_1 + b_2 + \cdots + b_i = B$ ($0 \le b_j \le s_j$ for all $1 \le j \le i$). Also define $S_i := s_1 + s_2 + \ldots + s_i$. Then: $dp[1][B] := 0$ for $0 \le B \le s_1$. $dp[i][B] := \max\limits_{\max(0, B - S_{i-1}) \le b_i \le \min(s_i, B)}{(dp[i - 1][B - b_i] + b_i \cdot (S_{i-1} - (B - b_i)) + (s_i - b_i) \cdot (B - b_i))}$ for $2 \le i \le m$ and $0 \le B \le S_{i}$. In the statement above: The limits for $b_i$ are $\max(0, B - S_{i-1}) \le b_i \le \min(s_i, B)$ because: $0 \le b_i \le s_i$ must hold, $0 \le B - b_i \le S_{i - 1}$ must hold. $0 \le b_i \le s_i$ must hold, $0 \le B - b_i \le S_{i - 1}$ must hold. $dp[i - 1][B - b_i]$ is the number of suitable pairs $(u, v)$ in the first $i - 1$ subtrees. $b_i \cdot (S_{i-1} - (B - b_i))$ is the number of suitable pairs $(u, v)$ where $u$ lies in the $i$-th subtree and $v$ lies in the first $i - 1$ subtrees. $(s_i - b_i) \cdot (B - b_i)$ is the number of suitable pairs $(u, v)$ where $v$ lies in the $i$-th subtree and $u$ lies in the first $i - 1$ subtrees. The maximum possible number of suitable pairs is equal to $\max\limits_{0 \le B \le S_m}{dp[m][B]}$. Let's calculate the complexity of this dynamic programming subproblem. To do that, it's easier to consider iterating over $b_i$ and then iterating over all suitable values of $B$. Then, from the condition $0 \le b_i \le s_i$ we get $s_i + 1$ values of $b_i$, and from the condition $0 \le B - b_i \le S_{i - 1} \implies b_i \le B \le b_i + S_{i - 1}$ we get $S_{i - 1} + 1$ suitable values of $B$ for each $b_i$. Taking into account that the $dp[i][B]$ array has $m \cdot (S_m + 1)$ values, adding everything up, the number of "operations" we get is equal to: $m \cdot (S_m + 1) + (s_2 + 1) \cdot (S_1 + 1) + (s_3 + 1) \cdot (S_2 + 1) + \ldots + (s_m + 1) \cdot (S_{m - 1} + 1) =$ $m \cdot (S_m + 1) + (s_2 \cdot S_1 + s_3 \cdot S_2 + \ldots + s_m \cdot S_{m-1}) + (s2 + \ldots + s_m) + (S_1 + \ldots + S_{m-1}) + (m - 1) \le$ $m \cdot S_m + m + (s_2 \cdot S_1 + s_3 \cdot S_2 + \ldots + s_m \cdot S_{m-1}) + S_m + (m - 1) \cdot S_m + m =$ $2m \cdot (S_m + 1) + (s_2 \cdot S_1 + s_3 \cdot S_2 + \ldots + s_m \cdot S_{m-1}) \le$ $2mn + (s_2 \cdot S_1 + s_3 \cdot S_2 + \ldots + s_m \cdot S_{m-1})$ Returning to the original problem, let's solve the subproblem for each $x$ from $1$ to $n$ and add up the results. This is the upper bound on the answer, and we will prove a bit later that a suitable permutation $a$ exists. Let's change our notation a bit: $m_x$ is the number of subtrees of vertex $x$. $s_{x,i}$ is the size of the $i$-th subtree of vertex $x$. $S_{x,i}$ is equal to $s_{x,1} + s_{x,2} + \ldots + s_{x,i}$. $b_{x,i}$ is the number of vertices in the $i$-th subtree for which $a_v < a_x$. Adding up the number of "operations" for all subproblems, we get: $\displaystyle\sum_{x=1} ^{n} (2m_xn + s_{x,2} \cdot S_{x,1} + s_{x,3} \cdot S_{x,2} + \ldots + s_{x,m_x} \cdot S_{x,m_x-1}) =$ $2n \cdot (n - 1) + \displaystyle\sum_{x=1} ^{n} (s_{x,2} \cdot S_{x,1} + s_{x,3} \cdot S_{x,2} + \ldots + s_{x,m_x} \cdot S_{x,m_x-1})$ Consider an undirected graph with $n$ vertices where there are initially no edges. You can think of the value of $s_{x,j} \cdot S_{x,j-1}$ as the number of edges added between each vertex of the first $j-1$ subtrees of $x$ and the $j$-th subtree of $x$. Since each pair of $(x, j)$ accounts for a unique set of edges of size $s_{x,j} \cdot S_{x,j-1}$, the sum $\sum_{x=1} ^{n} (\ldots)$ can be bounded above by $\frac{n \cdot (n - 1)}{2}$, the maximum number of unique edges in a graph with $n$ vertices: $2n \cdot (n - 1) + \displaystyle\sum_{x=1} ^{n} (s_{x,2} \cdot S_{x,1} + s_{x,3} \cdot S_{x,2} + \ldots + s_{x,m_x} \cdot S_{x,m_x-1}) \le$ $2n \cdot (n - 1) + \frac{n \cdot (n - 1)}{2}$ So we get a complexity of $\mathcal{O}(n^2)$. You can read more about this complexity analysis in section 7 of this Codeforces blog. We solve independently for each value of $\operatorname{lca}(u,v)$ and add up the answers to get an upper bound for $f(a)$. We will prove by constructing $a$ that this bound is achievable. Let $g(x, L)$ be a function that takes a vertex $x$ and a set of integers $L$, assigns some value from $L$ to $a_x$, and then calls $g(y, L_y)$ for all children of $x$ (direct descendants), where the sets $L_y$ do not intersect and their union is equal to $L \setminus \{ a_x \}$. How it works: Let $y_{1}, \ldots y_{m_x}$ be the children of vertex $x$ and $L_{y_i}$ initially be empty sets. Suppose that for vertex $x$ it is optimal to have the values of $b_{x,1}, b_{x,2}, \ldots, b_{x,m_x}$ be equal to $c_1, c_2, \ldots, c_{m_x}$ respectively. For each $i$ from $1$ to $m_x$, take the $c_i$ smallest values from $L$, remove them from $L$, and add them to the set $L_{y_i}$. Set $a_x$ to the smallest value in $L$ and remove it from the set. For each $i$ from $1$ to $m_x$, take the $s_i - c_i$ smallest values from $L$, remove them from $L$, and add them to the set $L_{y_i}$. For each $i$ from $1$ to $m_x$, call $g(y_i, L_{y_i})$. Calling $g(x, \{1, 2, \ldots n \})$ constructs an optimal permutation $a$ for the given tree. Complexity: $\mathcal{O}(n^2)$ Note: you can change $dp[i][B]$ to $dp[B]$ and iterate $B$ from $S_i$ to $0$. This improves the memory usage, but does not change the time complexity.
|
[
"dfs and similar",
"dp",
"trees"
] | 1,800
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
const int maxn = 1000000;
vector<int> g[maxn];
int s[maxn];
ll ans = 0;
void dfs(int v, int p = -1) {
vector<ll> a;
s[v] = 1;
for (int u: g[v]) {
if (u == p) continue;
dfs(u, v);
s[v] += s[u];
a.push_back(s[u]);
}
vector<ll> dp(s[v]);
ll cs = 0;
for (int x: a) {
for (ll i = cs + x; i >= 0; i--) {
for (ll pr = min(cs, i); pr >= max(0LL, i - x); pr--) {
ll j = i - pr;
dp[i] = max(dp[i], dp[pr] + j * (cs - pr) + pr * (x - j));
}
}
cs += x;
}
ans += *max_element(all(dp));
dp.clear();
a.clear();
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n;
cin >> n;
for (int i = 1; i < n; i++) {
int x;
cin >> x;
g[x - 1].push_back(i);
}
dfs(0);
cout << ans << nl;
}
|
1856
|
E2
|
PermuTree (hard version)
|
\textbf{This is the hard version of the problem. The differences between the two versions are the constraint on $n$ and the time limit. You can make hacks only if both versions of the problem are solved.}
You are given a tree with $n$ vertices rooted at vertex $1$.
For some permutation$^\dagger$ $a$ of length $n$, let $f(a)$ be the number of pairs of vertices $(u, v)$ such that $a_u < a_{\operatorname{lca}(u, v)} < a_v$. Here, $\operatorname{lca}(u,v)$ denotes the lowest common ancestor of vertices $u$ and $v$.
Find the maximum possible value of $f(a)$ over all permutations $a$ of length $n$.
$^\dagger$ 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).
|
First of all, the most important takeaways from the editorial for the easy version: For each $x$ from $1$ to $n$, you can solve $n$ independent subproblems of maximizing the number of suitable pairs for a fixed value of $\operatorname{lca}(u, v) = x$, and then add up the results to get the final answer. For each subproblem, the number of suitable pairs of vertices can be calculate based on the sizes of all the child subtrees $s_{x,i}$ and the number of vertices with $a_v < a_x$ in each of them, which we will call $b_{x,i}$. Consider the subproblem for some $x$. Let $m_x$ be the number of child subtrees of vertex $x$. Suppose some optimal values of $b_{x,1}, b_{x,2}, \ldots b_{x,m_x}$ that maximize the number of suitable pairs are $c_1, c_2, \ldots c_{m_x}$ respectively. Claim: there exists an optimal solution where $c_i = 0$ or $c_i = s_{x,i}$ for all $i$ from $1$ to $m_x$. Proof: let's consider some optimal solution $c_1, c_2, \ldots c_{m_x}$ where $0 < c_i < s_{x,i}$ for some $i$. Suppose $D$ is the number of suitable pairs of vertices such that both $u$ and $v$ don't lie in the $i$-th child's subtree. Then, the total number of suitable pairs is equal to: $D + c_i \cdot \sum_{j \neq i}{(s_{x, j} - c_j)} + (s_{x, i} - c_i) \cdot \sum_{j \neq i} c_j$ $D + c_i \cdot C_1 + (s_{x, i} - c_i) \cdot C_2 =$ $(D + C_2 \cdot s_{x,i}) + c_i \cdot (C_1 - C_2)$ The values of $(D + C_2 \cdot s_{x,i})$, $C_1$, and $C_2$ don't depend on the value of $c_i$, so we can freely change it to anything from $[0; s_{x, i}]$ to maximize the value of the formula. So: If $C_1 \ge C_2$, the value of the formula will not decrease if we set $c_i$ to $s_{x,i}$. If $C_1 \le C_2$, the value of the formula will not decrease if we set $c_i$ to $0$. Since at least one of this conditions has to be true, we can always take some optimal solution with $k$ indices such that $0 < c_i < s_{x, i}$ and get an optimal solution with $k - 1$ such indices. We repeat this process until $k$ becomes $0$, which means that $c_i = 0$ or $c_i = s_{x, i}$ for all $i$ from $1$ to $m_x$, as was stated in the claim. Consider an optimal solution $c_1, c_2, \ldots c_{m_x}$ where $c_i$ is equal to either $0$ or $s_{i, x}$. Let $S_1$ be the sum of $s_{i, x}$ over all $i$ such that $c_i = 0$ and $S_2$ be the sum of $s_{i, x}$ over all $i$ such that $c_i = s_{x, i}$. Then, the number of suitable pairs is equal to: $S_1 \cdot S_2$ If we define $S$ as $s_{x, 1} + s_{x, 2} + \ldots s_{x,m_x}$, we can see that $S_2$ is equal to $S - S_1$, so we are actually maximizing the value of: $S_1 \cdot (S - S_1)$ To do this, we can iterate $S_1$ from $0$ to $S$, find if it is possible to choose some subset of indices $I \subseteq \{1, 2, \ldots, m_x \}$ such that $\displaystyle\sum_{i \in I}{s_{x,i}} = S_1$, and update the current best answer if such a set $I$ exists. Doing this efficiently is known as the subset sum problem (or some variation of it). One of the simplest ways to solve it in this particular case with a $\mathcal{O}(m_x \cdot S)$ dynamic programming solution: $dp[j][S_1]$ is equal to $1$ if there exists a set of indices $I \subseteq \{ 1, 2, \ldots, j \}$ such that $\displaystyle\sum_{i \in I}{s_{x,i}} = S_1$ and is equal to $0$ otherwise. We will proceed to optimize it. The first standard optimization will bring the complexity down to $\mathcal{O}(S \sqrt S)$, you can read about it in Section 3 of this Codeforces blog or in the "Subset Sum Speedup 1" section of this Codeforces blog. Since we are trying to maximize the value of $S_1 \cdot (S - S_1)$, the optimal choice will also minimize the value of $| (S - S_1) - S_1 | = | S - 2S_1 |$. Claim: denote $\max(s_{x,1}, \ldots, s_{x,m_x})$ as $M_x$. If $M_x \ge \frac{S}{2}$, the smallest possible value of $| S - 2S_1 |$ is achieved with $S_1 = M_x$ or $S_1 = S - M_x$. Proof: it is clearly possible to get $S_1 = M_x$. Suppose it is possible to get some value of $S_1$ in the segment $[S - M_x + 1; M_x - 1]$. Then, $M_x$ did not contribute to the sum $S_1$, and so $S_1 + M_x$ can't exceed $S$. But $S_1 + M_x \ge S - M_x + 1 + M_x = S + 1$, so we get a contradiction, hence it is not possible to get some $S_1 \in [S - M_x + 1; M_x - 1]$. So if we have $M_x \ge \frac{S}{2}$, we actually don't have to run the dynamic programming part. We will now analyze the complexity of the solution with this optimization. Let's now define $S_x$ as $s_{x, 1} + \ldots + s_{x, m_x}$. Let's also call a vertex $x$ heavy if $M_x \ge \frac{S_x}{2}$ and light otherwise. Suppose that vertex $x$ has $k$ light ancestors on it's path to the root: Every subtree of a light vertex $v$ has at most $\frac{S_v}{2}$ vertices in it. Every subtree of a heavy vertex $v$ has at most $S_v - 1$ vertices in it. For each $k$ from $0$ to $n$, let $L_k$ be the set of light vertices with exactly $k$ light ancestors (a vertex doesn't count as it's own ancestor): Note that if two light vertices $u$ and $v$ are in the same set $L_k$, one can't be the ancestor of the other. So, the sum $\sum_{x \in L_{k}} S_x$ does not exceed $n$. $S_x \le \frac{n}{2^k}$ for all $x \in L_{k}$. For some $k$, let's calculate the total number of "operations" taken in the dynamic programming part for all $x \in L_k$. To do that, we: Iterate over the number of vertices in the set $L_{k}$, let's call it $p$, from $0$ to $n$. Let $d_1, d_2, \ldots, d_p$ be the sizes of the subtrees of vertices in $L_{k}$. Then we need to maximize the value of: $d_1 \sqrt d_1 + d_2 \sqrt d_2 + \ldots + d_p \sqrt d_p$ over all $d_1, d_2, \ldots, d_p$ such that $1 \le d_n \le \frac{n}{2^k}$ and $d_1 + \ldots + d_n \le n$. $d_1 \sqrt d_1 + d_2 \sqrt d_2 + \ldots + d_p \sqrt d_p$ You might have noticed that the above process can be simplified by allowing $d_i$ to be equal to $0$. In that case, the number of vertices $p$ is equal to the number of positive integers in $d_1, d_2, \ldots, d_n$, and we need to maximize: $d_1 \sqrt d_1 + d_2 \sqrt d_2 + \ldots + d_n \sqrt d_n$ over all integer $d_1, d_2, \ldots , d_n$ such that $0 \le d_n \le \frac{n}{2^k}$ and $d_1 + \ldots + d_n \le n$. Let $t := \left\lfloor \frac{n}{2^k} \right\rfloor$. We'll assume $t \ge 1$, otherwise, $d_i$ is equal to $0$ for all $1 \le i \le n$ and the sum is always equal to $0$. Lemma 1: it is optimal to have $d_1 + d_2 + \ldots + d_n = n$. Proof: if we can increase some $d_i$, it is clearly optimal to do so. Lemma 2: suppose the maximum is achieved on the set of values $e_1, e_2, \ldots, e_n$. Then there does not exist a pair of indices $i$ and $j$ such that $0 < e_i \le e_j < t$. Proof: define $f(x) := \left( x + 1 \right) \sqrt {x + 1} - x \sqrt x$. Note that $f(x)$ is a monotonically increasing function for all $x \ge 0$. You can prove it by, for example, analyzing it's derivative: $\frac{3}{2} (\sqrt {x + 1} - \sqrt x)$. If we decrease $e_i$ by $1$ and increase $e_j$ by $1$, the sum changes by: $(e_j + 1) \sqrt {e_j + 1} + (e_i - 1) \sqrt {e_i - 1} - e_j \sqrt e_j - e_i \sqrt e_i =$ $f(e_j) - f(e_i - 1) > 0$ By doing this, we haven't broken any constraints on the values of $e_i$, but have increased the total sum, so the previous values of $e$ couldn't have been optimal. This lemma gives us the nice property that the optimal values of $e_1, e_2, \ldots, e_n$ look something like $t, \ldots, t, y, 0, \ldots, 0$; where $0 < y < t$. With this we can conclude that the total number of "operations" performed for all vertices in $L_k$ is at most: $\left\lceil \frac{n}{t} \right\rceil \cdot t \sqrt t \le \left( \frac{n}{t} + 1 \right) \cdot t \sqrt t \le (n + t) \sqrt t \le 2n \sqrt t$ Adding this up over all $k$ with $t \ge 1$, we get: $2n \cdot \left(\sqrt{\left\lfloor \frac{n}{1} \right\rfloor} + \sqrt{\left\lfloor \frac{n}{2} \right\rfloor} + \sqrt{\left\lfloor \frac{n}{4} \right\rfloor} + \sqrt{\left\lfloor \frac{n}{8} \right\rfloor} + \ldots + 1 \right) \le$ $2n \cdot \left( \sqrt{\frac{n}{1}} + \sqrt{\frac{n}{2}} + \sqrt{\frac{n}{4}} + \sqrt{\frac{n}{8}} + \ldots \right) =$ $2n \sqrt n \cdot \left(1 + \frac{1}{\sqrt{2}} + \frac{1}{\sqrt{4}} + \frac{1}{\sqrt{8}} + \ldots \right)$ We can notice that the sum in the brackets in bounded by the sum of an infinite geometric progression with a sum of $\frac{\sqrt{2}}{\sqrt{2} - 1} \le 4$, so the total sum is: $\le 2n \sqrt n \cdot 4 = 8n \sqrt n = \mathcal{O}(n \sqrt n)$ Finally, we will also use bitsets to speed up our dynamic programming part and bring the complexity down to $\mathcal{O}(\frac{n \sqrt n}{w})$, where $w$ is the word size, usually $32$ or $64$. You can learn about bitsets in this Codeforces blog. To get a simple variable length bitset in C++, refer to this comment. Complexity: $\mathcal{O}(\frac{n \sqrt n}{w})$.
|
[
"bitmasks",
"dfs and similar",
"dp",
"fft",
"greedy",
"implementation",
"math",
"trees"
] | 2,700
|
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
#define allr(x) (x).rbegin(), (x).rend()
#define gsize(x) (int)((x).size())
const char nl = '\n';
typedef long long ll;
typedef long double ld;
using namespace std;
const int maxn = 1000000;
vector<int> g[maxn];
int s[maxn];
ll ans = 0;
vector<ll> b;
ll closest;
template <int len = 1>
void subset_sum(int n) {
if (n >= len) {
subset_sum<std::min(len*2, maxn)>(n);
return;
}
bitset<len> dp;
dp[0] = 1;
for (ll x: b) {
dp = dp | (dp << x);
}
ll cv = n;
closest = 0;
for (int i = 0; i <= n; i++) {
if (dp[i] && abs(i - (n - i)) < cv) {
closest = i;
cv = abs(i - (n - i));
}
}
}
ll solve(vector<ll> &a) {
if (a.empty()) return 0;
sort(allr(a));
ll cs = 0;
for (ll x: a) cs += x;
if (a[0] * 2 >= cs) {
return a[0];
}
int n = gsize(a);
a.push_back(0);
b.clear();
int pi = 0;
for (int i = 1; i <= n; i++) {
if (a[i] != a[i - 1]) {
ll cnt = i - pi;
ll x = a[i - 1];
ll j = 1;
while (j < cnt) {
b.push_back(x * j);
cnt -= j;
j *= 2;
}
b.push_back(x * cnt);
pi = i;
}
}
subset_sum(cs);
return closest;
}
void dfs(int v, int p = -1) {
vector<ll> a;
s[v] = 1;
for (int u: g[v]) {
if (u == p) continue;
dfs(u, v);
s[v] += s[u];
a.push_back(s[u]);
}
ll x = solve(a);
ans += x * (s[v] - 1 - x);
a.clear();
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n;
cin >> n;
for (int i = 1; i < n; i++) {
int x;
cin >> x;
g[x - 1].push_back(i);
}
dfs(0);
cout << ans << nl;
}
|
1857
|
A
|
Array Coloring
|
You are given an array consisting of $n$ integers. Your task is to determine whether it is possible to color all its elements in two colors in such a way that the sums of the elements of both colors have the same parity and each color has at least one element colored.
For example, if the array is [$1,2,4,3,2,3,5,4$], we can color it as follows: [$\textcolor{blue}{1},\textcolor{blue}{2},\textcolor{red}{4},\textcolor{blue}{3},\textcolor{red}{2},\textcolor{red}{3},\textcolor{red}{5},\textcolor{red}{4}$], where the sum of the blue elements is $6$ and the sum of the red elements is $18$.
|
Let's analyze the impact of adding odd or even numbers to a set with sum $S$: If you add an even element to the set, the parity of $S$ remains unchanged. If you add an odd element to the set, the parity of $S$ changes. Based on this observation, let's focus on the coloring of odd elements in the array. The number of odd elements colored in blue and the number of odd elements colored in red must have the same parity for a valid coloring. This is because we need to divide the odd elements into two parts (blue and red). To achieve the same parity for both blue and red odd elements, the total number of odd elements in the array must be even. If it is not even, we won't be able to create two sets with the same parity. Hence, the answer is "YES" if the number of odd elements in the array is even, and "NO" otherwise.
|
[
"greedy",
"math"
] | 800
|
for i in range(int(input())):
n=int(input())
a=[*map(int,input().split())]
cnt=0
for i in range(n):
if a[i]%2!=0:cnt+=1
if cnt%2==0:print('YES')
else:print('NO')
|
1857
|
B
|
Maximum Rounding
|
Given a natural number $x$. You can perform the following operation:
- choose a positive integer $k$ and round $x$ to the $k$-th digit
Note that the positions are numbered from right to left, starting from zero. If the number has $k$ digits, it is considered that the digit at the $k$-th position is equal to $0$.
The rounding is done as follows:
- if the digit at the $(k-1)$-th position is greater than or equal to $5$, then the digit at the $k$-th position is increased by $1$, otherwise the digit at the $k$-th position remains unchanged (mathematical rounding is used).
- if before the operations the digit at the $k$-th position was $9$, and it should be increased by $1$, then we search for the least position $k'$ ($k'>k$), where the digit at the $k'$-th position is less than $9$ and add $1$ to the digit at the $k'$-th position. Then we assign $k=k'$.
- after that, all digits which positions are less than $k$ are replaced with zeros.
Your task is to make $x$ as large as possible, if you can perform the operation as many times as you want.
For example, if $x$ is equal to $3451$, then if you choose consecutively:
- $k=1$, then after the operation $x$ will become $3450$
- $k=2$, then after the operation $x$ will become $3500$
- $k=3$, then after the operation $x$ will become $4000$
- $k=4$, then after the operation $x$ will become $0$
To maximize the answer, you need to choose $k=2$ first, and then $k=3$, then the number will become $4000$.
|
First, sorry for the unclear statement. We have rewritten it for several times and have chosen the best one. Let's define $n$ as the length of the $x$. Notice, that after applying the rounding to $k$, all the digits to the right of $k$ become $0$. If the $k$-th digit is less than $5$, after the rounding it'll only worsen the answer. On the other side, if the $k$-th digit is not less than $5$, than rounding to the $k$-th digit always leads to better answer, because after the operation $x$ will increase. From these observations, we can come up with the following greedy algorithm: look through all $k$ from $1$ to $n$, and if the $k$-th digit is not less than $5$, we use the rounding operation adding one to the ($k+1$)-th digit. And don't worry if that digit which must be increased by one is $9$, because in such case we always use the rounding operation on the next step.
|
[
"greedy",
"implementation",
"math"
] | 1,100
|
for i in range(int(input())):
s=[0]+[*map(int,list(input()))]
k=len(s)
for i in range(len(s)-1,0,-1):
if s[i]>4:s[i-1]+=1;k=i
if s[0]!=0:print(s[0],end='')
s=[*map(str,s)]
print(''.join(s[1:k]+['0']*(len(s)-k)))
|
1857
|
C
|
Assembly via Minimums
|
Sasha has an array $a$ of $n$ integers. He got bored and for all $i$, $j$ ($i < j$), he wrote down the minimum value of $a_i$ and $a_j$. He obtained a new array $b$ of size $\frac{n\cdot (n-1)}{2}$.
For example, if $a=$ [$2,3,5,1$], he would write [$\min(2, 3), \min(2, 5), \min(2, 1), \min(3, 5), \min(3, 1), min(5, 1)$] $=$ [$2, 2, 1, 3, 1, 1$].
Then, he randomly \textbf{shuffled} all the elements of the array $b$.
Unfortunately, he forgot the array $a$, and your task is to restore any possible array $a$ from which the array $b$ could have been obtained.
\textbf{The elements of array $a$ should be in the range $[-10^9,10^9]$}.
|
Suppose we have an array $a$ that we want to construct, with elements $a_1, a_2, \dots, a_n$. To simplify the process, let's assume that the elements of $a$ are sorted in non-decreasing order, meaning $a_1 \le a_2 \le \dots \le a_n$. Let's start with $a_1$. Since the elements of $a$ are sorted, the pairs $(a_1, a_2), (a_1, a_3), \dots, (a_1, a_n)$ will have $a_1$ as the smallest element in each pair. Therefore, the number of occurrences of $a_1$ in array $b$ will be $n-1$. Moving on to $a_2$, we already know that $a_1$ appears $n-1$ times in $b$. Since the elements of $a$ are sorted, all pairs involving $a_2$ will have $a_2$ as the second smallest element. This means $a_2$ will appear $n-2$ times in array $b$. We continue this process for each element $a_i$ in $a$. The number of occurrences of $a_i$ in array $b$ will be $n-i$. We can't determine the exact value of $a_n$ , because it won't be written to array b. Therefore, for $a_n$ we can choose any number in the range $[a_{n-1};10^9]$. In case there are multiple elements $b_i$ in array $b$ that satisfy the condition for a particular $a_i$, we choose the smallest $b_i$. This greedy approach works, because we are constructing $a$ in non-decreasing order. The complexity is $O(n^2 \log n)$.
|
[
"greedy",
"sortings"
] | 1,200
|
for _ in range(int(input())):
n=int(input())
l=sorted(map(int,input().split()))
j=0
for i in range(n-1,0,-1):
print(l[j],end=' ')
j+=i
print(l[-1])
|
1857
|
D
|
Strong Vertices
|
Given two arrays $a$ and $b$, both of length $n$. Elements of both arrays indexed from $1$ to $n$. You are constructing a directed graph, where edge from $u$ to $v$ ($u\neq v$) exists if $a_u-a_v \ge b_u-b_v$.
A vertex $V$ is called strong if there exists a path from $V$ to all other vertices.
A path in a directed graph is a chain of several vertices, connected by edges, such that moving from the vertex $u$, along the directions of the edges, the vertex $v$ can be reached.
Your task is to find all strong vertices.
For example, if $a=[3,1,2,4]$ and $b=[4,3,2,1]$, the graph will look like this:
\begin{center}
{\small The graph has only one strong vertex with number $4$}
\end{center}
|
The first step is to modify the inequality. $a_u-a_v \geq b_u-b_v \Leftrightarrow a_u-b_u \geq a_v-b_v$. We can create a new array $c$, where $c_i=a_i-b_i$ and our inequality is transformed to $c_u\geq c_v$. Suppose the set $p_1,\dots p_m$ is the set of such vertices $v$ that $c_v$ is maximum possible. From each $p_i$ there will be a path to all other vertices, because $c_{p_i}$ is not less than any other $c_u$, so the set $p$ is guaranteed will be in our answer. Now the question is whether there are other vertices in our answer? Let's prove that from any such vertex $v$, that is not maximum, there is no path to any vertex from $p$. The first observation, that there is no edge between $v$ and any $p_i$. So the path must go through other vertices. But even if there exist a path to another vertex $u$, $c_u$ will be still less that $c_{p_i}$, so it is impossible to get any $p_i$. In such way we proved that the answer will always be the set of such $v$, that $c_v$ is maximized. The complexity is $O(n)$.
|
[
"math",
"sortings",
"trees"
] | 1,300
|
for _ in range(int(input())):
n=int(input())
a=[*map(int,input().split())]
b=[*map(int,input().split())]
c=[a[i]-b[i] for i in range(n)]
mx=max(c)
ans=[]
for i in range(n):
if c[i]==mx:ans.append(i+1)
print(len(ans))
print(*ans)
|
1857
|
E
|
Power of Points
|
You are given $n$ points with integer coordinates $x_1,\dots x_n$, which lie on a number line.
For some integer $s$, we construct segments [$s,x_1$], [$s,x_2$], $\dots$, [$s,x_n$]. Note that if $x_i<s$, then the segment will look like [$x_i,s$]. The segment [$a, b$] covers all integer points $a, a+1, a+2, \dots, b$.
We define the power of a point $p$ as the number of segments that intersect the point with coordinate $p$, denoted as $f_p$.
Your task is to compute $\sum\limits_{p=1}^{10^9}f_p$ for each $s \in \{x_1,\dots,x_n\}$, i.e., the sum of $f_p$ for all integer points from $1$ to $10^9$.
For example, if the initial coordinates are $[1,2,5,7,1]$ and we choose $s=5$, then the segments will be: $[1,5]$,$[2,5]$,$[5,5]$,$[5,7]$,$[1,5]$. And the powers of the points will be: $f_1=2, f_2=3, f_3=3, f_4=3, f_5=5, f_6=1, f_7=1, f_8=0, \dots, f_{10^9}=0$. Their sum is $2+3+3+3+5+1+1=18$.
|
If we have the segments $[l_1,r_1],\dots,[l_n,r_n]$, the sum of $f_p$ is the sum of the segments' lengths. That's because a segment $[a,b]$ intersect exactly $b-a+1$ points. Now we can find the answer for fixed $s$ in $O(N)$. How to do it more efficiently? Let's sort the given points so that $x_1\le x_2\le \dots \le x_n$. Processing $s=x_i$ we get that for all $j\le i$ the segments are $[x_j,s]$ and for all $j>i$ the segments are $[s,x_j]$. We need to summarize their lengths. Formally we need to calculate $\sum\limits_{j=1}^{i}(s-x_j+1)+\sum\limits_{j=i+1}^{n}(x_j-s+1)=$ $n+s \cdot i-\sum\limits_{j=1}^{i}x_j+\sum\limits_{j=i+1}^{n}x_j -s(n-i)=$ $n+s(2\cdot i-n)-\sum\limits_{j=1}^{i}x_j+\sum\limits_{j=i+1}^{n}x_j$ We can maintain the sum of coordinates on the prefix and suffix, and calculate this formula for fixed $s$ in $O(1)$. The total complexity is $O(n\log n)$.
|
[
"math",
"sortings"
] | 1,500
|
for i in range(int(input())):
n=int(input())
a=sorted([(b,i)for i,b in enumerate(map(int,input().split()))])
ans=[0]*n
s1=0
s2=sum(a[i][0] for i in range(n))
for i in range(n):
ans[a[i][1]]=s2-a[i][0]*(n-i)+n-i+a[i][0]*i-s1+i
s1+=a[i][0]
s2-=a[i][0]
print(*ans)
|
1857
|
F
|
Sum and Product
|
You have an array $a$ of length $n$.
Your task is to answer $q$ queries: given $x,y$, find the number of pairs $i$ and $j$ ($1 \le i < j \le n$) that both $a_i + a_j = x$ and $a_i \cdot a_j = y$.
That is, for the array $[1,3,2]$ and asking for $x=3,y=2$ the answer is $1$:
- $i=1$ and $j=2$ fail because $1 + 3 = 4$ and not $3,$ also $1 \cdot 3=3$ and not $2$;
- $i=1$ and $j=3$ satisfies both conditions;
- $i=2$ and $j=3$ fail because $3 + 2 = 5$ and not $3,$ also $3 \cdot 2=6$ and not $2$;
|
The system of equations in the statement resembles Vieta's formula for quadratic equations. If we have $\begin{cases} a_i + a_j = b \\ a_i \cdot a_j = c \end{cases}$ To find the roots of the quadratic equation, we can use the discriminant formula, $D = b^2 - 4ac$. The roots will then be $x_1 = \frac{b - \sqrt{D}}{2}$ and $x_2 = \frac{b + \sqrt{D}}{2}$. Once we have the potential integer values for $a_i$ and $a_j$, we can calculate the number of pairs by multiplying the number of occurrences, respectively. However, remember to consider some special cases: If $D < 0$, the equation won't have real roots. If $D = 0$, then $x_1 = x_2$, the formula for counting pairs in this case is different. The complexity of this solution is $O((n + q) \log n)$, using maps to store integer occurrences.
|
[
"binary search",
"data structures",
"math"
] | 1,600
|
from collections import Counter
from math import sqrt
for _ in range(int(input())):
n=int(input())
a=[*map(int,input().split())]
d=Counter(map(str,a))
for i in range(int(input())):
x,y=map(int,input().split())
if x*x-4*y<0:print(0);continue
D=int(sqrt(x*x-4*y))
x1=(x+D)//2
x2=(x-D)//2
if x1+x2!=x or x1*x2!=y:print(0);continue
if x1!=x2:print(d[str(x1)]*d[str(x2)])
else:print(d[str(x1)]*(d[str(x1)]-1)//2)
|
1857
|
G
|
Counting Graphs
|
Given a tree consisting of $n$ vertices. A tree is a connected undirected graph without cycles. Each edge of the tree has its weight, $w_i$.
Your task is to count the number of different graphs that satisfy all four conditions:
- The graph does not have self-loops and multiple edges.
- The weights on the edges of the graph are integers and do not exceed $S$.
- The graph has \textbf{exactly one} minimum spanning tree.
- The minimum spanning tree of the graph is the given tree.
Two graphs are considered different if their sets of edges are different, taking into account the weights of the edges.
The answer can be large, output it modulo $998244353$.
|
The first observation is that the graphs will consist of $n$ vertices because the MST is fixed. Hence, the graphs will look like the given tree with some new vertices connected. The next step is to determine the possible weights of a new edge between vertices $u$ and $v$. Let $P(u,v)$ be the maximum weight on the simple path from $u$ to $v$. I assume that we can add a new edge between vertices $u$ and $v$ with any weight in the range $[P(u,v)+1,S]$. This becomes clear when we consider some examples. If the edge has a weight less or equal than $P(u,v)$, the MST will change by taking the new edge instead of the edge with the maximal weight on the path. Notice that if we add a new edge, and it doesn't affect the MST, we can add one more edge independently from the previous. So now the task is to calculate $\prod\limits_{1\le u < v \le n}{} (S-P(u,v)+1)$, because for each pair of vertices, we can assign a new weight from the range, which gives us $S-P(u,v)$ cases, or we can choose not to add any edge, which is one more case. Now, let's discuss how to calculate the formula efficiently: Sort the given edges in ascending order according to their weights: $w_1\le w_2\le \dots \le w_{n-1}$. We'll begin from the graph without edges, and add new ones step by step. Suppose, we already added all the edges up to $u_i,v_i,w_i$. Now, we want to add the $i$-th one. Notice that $w_i$ is greater than any of the weights before, and $u_i$ and $v_i$ are from different components. After adding the edge, we need to calculate the number of paths that go through this edge. If we know the sizes of the components containing $u_i$ and $v_i$, denoted as $s_u$ and $s_v$ respectively, then there exist $s_u\cdot s_v-1$ paths through edge $u_i,v_i$ without including the path formed by these two vertices. We know the number of paths, and on each of these paths, we can determine the weight we can put on the edge. Thus, we need to multiply answer by $(S-w_i+1)^{s_u\cdot s_v-1}$, using binary exponentiation. To add edges and find the sizes of the components efficiently, you can use DSU (Disjoint Set Union). The complexity of this approach is $O(n\log n)$.
|
[
"combinatorics",
"divide and conquer",
"dsu",
"graphs",
"greedy",
"sortings",
"trees"
] | 2,000
|
mod=998244353
def find_(v):
stack=[v]
while dsu[v]!=v:
stack.append(dsu[v])
v=stack[-1]
while stack:
dsu[stack[-1]]=dsu[v]
v=stack.pop()
return dsu[v]
for i in range(int(input())):
n,S=map(int,input().split())
l=[tuple(map(int,input().split()))for i in range(n-1)]
l.sort(key=lambda x:x[2])
ans=1
dsu=[i for i in range(n)]
coun=[1]*n
for a,b,c in l:
a-=1;b-=1
if find_(a)!=find_(b):
ans=ans*pow(S-c+1,coun[dsu[a]]*coun[dsu[b]]-1,mod)
ans%=mod
coun[dsu[a]]+=coun[dsu[b]]
coun[dsu[b]]=0
dsu[b]=dsu[a]
print(ans)
|
1858
|
A
|
Buttons
|
Anna and Katie ended up in a secret laboratory.
There are $a+b+c$ buttons in the laboratory. It turned out that $a$ buttons can only be pressed by Anna, $b$ buttons can only be pressed by Katie, and $c$ buttons can be pressed by either of them. Anna and Katie decided to play a game, taking turns pressing these buttons. Anna makes the first turn. Each button can be pressed at most once, so at some point, one of the girls will not be able to make her turn.
The girl who cannot press a button loses. Determine who will win if both girls play optimally.
|
On each turn, the current player gets rid of one of the buttons available to them. At the same time, if you press the "common" button, the enemy will not be able to press it as well. Since each player wants to leave their opponent without buttons to press before they run out of those themselves, they will click on the "common" buttons as long as there is at least one available. The number of the player who clicks on their (not the general) button first depends on $c$. It can be noticed that this player will win if and only if they have strictly more buttons than their opponent.
|
[
"games",
"greedy",
"math"
] | 800
|
t = int(input())
for i in range(t):
a, b, c = map(int, input().split())
if c % 2 == 0:
if a > b:
print("First")
else:
print("Second")
else:
if b > a:
print("Second")
else:
print("First")
|
1858
|
B
|
The Walkway
|
There are $n$ benches near the Main Walkway in Summer Infomatics School. These benches are numbered by integers from $1$ to $n$ in order they follow. Also there are $m$ cookie sellers near the Walkway. The $i$-th ($1 \le i \le m$) cookie sellers is located near the $s_i$-th bench.
Petya is standing in the beginning of the Walkway. He will pass near all benches starting from the $1$-st bench and ending with the $n$-th bench. Petya passes the distance between two consecutive benches in $1$ minute. He has a knapsack with an infinite amount of cookies. Petya is going to eat cookies from his knapsack and buy them from cookie sellers during the walk.
Petya eats cookies only near the benches according to the following rule: he will eat the cookie near the $i$-th ($1 \le i \le n$) bench if and only if \textbf{at least one} of the following conditions holds:
- There is a cookie seller near the $i$-th bench. Then Petya will buy a cookie from cookie seller and eat it immediately.
- Petya has not yet eaten a cookie. Then Petya will take a cookie from his knapsack and eat it immediately.
- At least $d$ minutes passed since Petya ate the previous cookie. In other words, Petya has not eaten a cookie near the benches $i-1, i-2, \ldots, \max(i-d+1, 1)$. Then Petya will take a cookie from his knapsack and eat it immediately.
You may assume that Petya eats cookies instantly. Petya will not eat two or more cookies near the same bench.
You want to \textbf{minimize} the number of cookies Petya will eat during his walk. In order to do this, you will ask the administration of the Summer Informatics School to remove \textbf{exactly one} cookie seller from the Walkway before Petya starts his walk.
Please determine the minimum possible number of cookies Petya can eat after removing exactly one cookie seller. Also determine the number of cookie sellers, such that if you remove one of them, Petya will eat the minimum possible number of cookies.
|
First, let's calculate how many cookies Petya will eat if we don't remove the cookie sellers at all (we will later refer to this value as $res$). Note that since the cookie sellers reset the time elapsed since the last eaten cookie, the number of cookies eaten on all segments between adjacent cookie sellers are counted independently. Therefore, we can easily calculate $res$: let's iterate through the cookie sellers from $1$ to $m-1$. For each of them, we should add the number $\left( \left\lfloor\frac{s_{i+1}-s_{i}-1}{d}\right\rfloor + 1 \right)$ to $res$. We should also carefully take into account the cookies that Petya will eat on the segments $[1;s_{1}-1]$ and $[s_{m}, n]$ (it might help to assume that there are two more cookie sellers at positions $1-d$ and $n+1$). In order to find the minimum possible number of cookies eaten by Petya, we will fix the cookie seller that we remove. Let it be the cookie seller $i$. Then the number of cookies eaten by Petya will be $res - \left\lfloor\frac{s_{i}-s_{i-1}-1}{d}\right\rfloor - \left\lfloor\frac{s_{i+1}-s_{i}-1}{d}\right\rfloor + \left\lfloor\frac{s_{i+1}-s_{i-1}-1}{d}\right\rfloor - 1$ The final complexity of the solution is $\mathcal{O}(m)$ (because array $s$ is sorted in the input).
|
[
"brute force",
"dp",
"greedy",
"math",
"number theory"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
int solve(int d, vector<int> x)
{
int ans = 0;
for (int i = 1; i < x.size(); i++)
{
ans += (x[i] - x[i - 1] - 1) / d;
}
ans += int(x.size()) - 2;
return ans;
}
void solve()
{
#define tests
int n, m, d;
cin >> n >> m >> d;
vector<int> r(m);
for (int i = 0; i < m; i++) cin >> r[i];
r.insert(r.begin(), 1 - d);
r.push_back(n + 1);
int ans = 2e9;
vector<int> res;
for (int i = 1; i <= m; i++)
{
int A = r[i] - r[i - 1] - 1;
int B = r[i + 1] - r[i] - 1;
int C = r[i + 1] - r[i - 1] - 1;
int D = C / d - (A / d + B / d);
if (D < ans)
{
ans = D;
res.clear();
}
if (D == ans)
{
res.push_back(r[i]);
}
}
cout << ans + solve(d, r) - 1 << ' ' << res.size() << endl;
}
int main()
{
int t = 1;
#ifdef tests
cin >> t;
#endif
while (t--)
{
solve();
}
}
|
1858
|
C
|
Yet Another Permutation Problem
|
Alex got a new game called "GCD permutations" as a birthday present. Each round of this game proceeds as follows:
- First, Alex chooses a permutation$^{\dagger}$ $a_1, a_2, \ldots, a_n$ of integers from $1$ to $n$.
- Then, for each $i$ from $1$ to $n$, an integer $d_i = \gcd(a_i, a_{(i \bmod n) + 1})$ is calculated.
- The score of the round is the number of distinct numbers among $d_1, d_2, \ldots, d_n$.
Alex has already played several rounds so he decided to find a permutation $a_1, a_2, \ldots, a_n$ such that its score is as large as possible.
Recall that $\gcd(x, y)$ denotes the greatest common divisor (GCD) of numbers $x$ and $y$, and $x \bmod y$ denotes the remainder of dividing $x$ by $y$.
$^{\dagger}$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).
|
It is impossible to get $d_i = \gcd(a_i, a_{(i\mod n) + 1}) > \left\lfloor \frac{n}{2}\right\rfloor$: otherwise, at least one of the numbers in $a$ would be divisible by $d_i$ and would be greater than $d_i$ at the same time, so it would be at least $2 \cdot d_i$, which is greater than $n$. Therefore, the maximum possible score is no more than $\left\lfloor\frac{n}{2}\right\rfloor$. Actually, we can always get a score equal to $\left\lfloor\frac{n}{2}\right\rfloor$. How do we get such score? Let's set $a_1= 1$. After that, we put the powers of $2$ less or equal $n$ sequentially. Then we put $3$ and powers of $2$ multiplied by $3$, then $5$ and so on (for example, for $n=12$, we will get an array $a=[1,2,4,8,3,6,12,5,10,7,9,11]$). Then, for each number $a_i = x \leq \lfloor \frac{n}{2} \rfloor$, the next number will be $a_{(i\bmod n) + 1} = x \cdot 2 \leq n$. Their $\gcd$ will be exactly $x$, so there will be a pair of adjacent elements of $a$ with greatest common divisor equal to $x$ for all $1 \leq x \leq \lfloor\frac{n}{2}\rfloor$.
|
[
"constructive algorithms",
"greedy",
"math",
"number theory"
] | 1,000
|
#include<iostream>
#include<vector>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n);
int cur = 0;
for (int i = 1; i <= n; i += 2) {
for (int j = i; j <= n; j *= 2) {
a[cur++] = j;
}
}
for (int i = 0; i<n; ++i) {
cout << a[i] << " ";
}
cout << '\n';
}
return 0;
}
|
1858
|
D
|
Trees and Segments
|
The teachers of the Summer Informatics School decided to plant $n$ trees in a row, and it was decided to plant only oaks and firs. To do this, they made a plan, which can be represented as a binary string $s$ of length $n$. If $s_i = 0$, then the $i$-th tree in the row should be an oak, and if $s_i = 1$, then the $i$-th tree in the row should be a fir.
The day of tree planting is tomorrow, and the day after tomorrow an inspector will come to the School. The inspector loves nature very much, and he will evaluate the beauty of the row as follows:
- First, he will calculate $l_0$ as the maximum number of consecutive oaks in the row (the maximum substring consisting of zeros in the plan $s$). If there are no oaks in the row, then $l_0 = 0$.
- Then, he will calculate $l_1$ as the maximum number of consecutive firs in the row (the maximum substring consisting of ones in the plan $s$). If there are no firs in the row, then $l_1 = 0$.
- Finally, he will calculate the beauty of the row as $a \cdot l_0 + l_1$ for some $a$ — the inspector's favourite number.
The teachers know the value of the parameter $a$, but for security reasons they cannot tell it to you. They only told you that $a$ is an integer from $1$ to $n$.
Since the trees have not yet been planted, the teachers decided to change the type of no more than $k$ trees to the opposite (i.e., change $s_i$ from $0$ to $1$ or from $1$ to $0$ in the plan) in order to maximize the beauty of the row of trees according to the inspector.
For each integer $j$ from $1$ to $n$ answer the following question \textbf{independently}:
- What is the maximum beauty of the row of trees that the teachers can achieve by changing the type of no more than $k$ trees if the inspector's favourite number $a$ is equal to $j$?
|
There are many various dynamic programming solutions of this problem. We will describe one of them. Let's calculate the dynamics $pref_{i, \ j}$ = the length of the longest subsegment of zeros that can be obtained on the prefix up to $i$, which ends at index $i$ and costs exactly $j$ operations. Similarly, $suf_{i, \ j}$ is the length of the longest subsegment of zeros on the suffix starting at $i$, which starts at index $i$ and costs exactly $j$ operations. Such dynamics can be easily computed: $pref_{i, \ j} = \left\{ \begin{array} \\ pref_{i - 1, \ j} + 1 & \text{if} & s_i = 0 \\ pref_{i - 1, \ j - 1} + 1 & \text{if} & s_i = 1 & \text{and} & j > 0 \\ 0 & \text{otherwise} \end{array}\right.$ Now let's consider a subsegment [$l, \ r]$ that we want to convert into a segment of ones. We can easily calculate the number of operations $x$ that we will need (we'll just need to calculate the number of zeros in such a segment). Now, calculate the new dynamics $dp_{len}$ for the length $len = r - l + 1$ of the segment of ones, which equals the maximum length of a subsegment of zeros that we can obtain. Update this value with $\max(pref_{l - 1, k - x}, suf_{r + 1, k - x})$. Then, to answer the question for a fixed number $a$, we can iterate over the length $len$ of the segment of ones that will be in our answer and update the answer with the value $a \cdot dp_{len} + len$, if there exists a value for $len$ in the dynamics $dp$. The complexity is $O(nk + n^2)$. Solutions with complexity $O(nk \log n)$ and $O(nk)$ using various optimizations of the dynamics (convex hull trick, D&C) also exist.
|
[
"brute force",
"data structures",
"dp",
"greedy",
"two pointers"
] | 2,200
|
#include <bits/stdc++.h>
#define int long long
using namespace std;
using ll = long long;
void solve();
template<typename ...Args>
void println(Args... args) {
apply([](auto &&... args) { ((cout << args << ' '), ...); }, tuple(args...));
cout << '\n';
}
int32_t main() {
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
int t = 1;
cin >> t;
for (int tc = 0; tc < t; ++tc) {
solve();
}
return 0;
}
void solve() {
int n, k;
cin >> n >> k;
string s;
cin >> s;
vector<int> max0by1(n + 1, -1e9);
vector<vector<int>> max0pref(n + 1, vector<int>(n + 1));
vector<vector<int>> max0suf(n + 1, vector<int>(n + 1));
for (int l = 0; l < n; ++l) {
int cnt1 = 0;
for (int r = l + 1; r <= n; ++r) {
cnt1 += s[r - 1] == '1';
max0pref[r][cnt1] = max(max0pref[r][cnt1], r - l);
max0suf[l][cnt1] = max(max0suf[l][cnt1], r - l);
}
}
for (int r = 0; r <= n; ++r) {
for (int cnt = 0; cnt <= n; ++cnt) {
if (r) max0pref[r][cnt] = max(max0pref[r][cnt], max0pref[r - 1][cnt]);
if (cnt) max0pref[r][cnt] = max(max0pref[r][cnt], max0pref[r][cnt - 1]);
}
}
for (int l = n; l >= 0; --l) {
for (int cnt = 0; cnt <= n; ++cnt) {
if (l + 1 <= n) max0suf[l][cnt] = max(max0suf[l][cnt], max0suf[l + 1][cnt]);
if (cnt) max0suf[l][cnt] = max(max0suf[l][cnt], max0suf[l][cnt - 1]);
}
}
vector<int> ans(n + 1, -1e9);
for (int l = 0; l < n; ++l) {
int cnt0 = 0;
for (int r = l; r <= n; ++r) {
if (r > l) cnt0 += s[r - 1] == '0';
if (cnt0 > k) break;
max0by1[r - l] = max(max0by1[r - l], max0pref[l][k - cnt0]);
max0by1[r - l] = max(max0by1[r - l], max0suf[r][k - cnt0]);
}
}
for (int i = 0; i <= n; ++i) {
for (int a = 1; a <= n; ++a) ans[a] = max(ans[a], i + max0by1[i] * a);
}
for (int i = 1; i <= n; ++i) cout << ans[i] << ' ';
cout << '\n';
}
|
1858
|
E2
|
Rollbacks (Hard Version)
|
This is a hard version of this problem. The only difference between the versions is that you have to solve the hard version in online mode. You can make hacks only if both versions of the problem are solved.
You have an array $a$, which is initially empty. You need to process queries of the following types:
- + $x$ — add the integer $x$ to the end of the array $a$.
- - $k$ — remove the last $k$ numbers from the array $a$.
- ! — roll back the last active change (i.e., make the array $a$ the way it was before the change). In this problem, only queries of the first two types (+ and -) are considered as changes.
- ? — find the number of distinct numbers in the array $a$.
|
First, let's learn how to solve the problem without rollbacks. Let $b$ be an array of the same length as $a$, where $b_i=1$ if $i$ is the minimum position at which the number $a_i$ is in the array $a$, and $b_i=0$ otherwise. Then the number of different numbers in the array $a$ is equal to the sum of all the elements of the array $b$. The $b$ array can be maintained using a Fenwick tree, a segment tree, or any other data structure that supports point updates and range sum queries. The author's solution uses the Fenwick tree. Let's use the method that is often used when implementing a stack or a deque: we create a large array $A$ and at each moment we store the index of the last "existing" element $r$ (this is just the size of the array $a$ at this moment). The array $a$ itself will be a prefix of $A$, that is, $a_{i}=A_{i}$ for $i\leq len(a)$. Also, for each value $val$ we maintain std::set of indexes on which the $val$ value is located in the $A$ array (in $A$, not in $a$). Then for the operation of removing $k$ elements from the end of the array $a$, it is enough to reduce the value of the index $r$ by $k$. This operation works in $O(1)$. When adding one element $x$ to the end of the array, we need to check if it has been encountered before, and change one element in the Fenwick tree accordingly. This can be done in $O(\log{q})$ using std::set for the corresponding value. You also need to increase $r$ by 1, assign $A_{r} =x$ after that, and update the corresponding std::set. This operation works for $O(\log{q})$. In order to find the number of different numbers in $a$, we need to find the sum in the Fenwick tree on the prefix of length $r$ in the array $b$. This operation works in $O(\log{q})$. Now, we need to learn how to roll back operations. Note that we perform the deletion operation in $O(1)$, and the addition operation in $O(\log{q})$, so we can roll back these operations with the same asymptotics. We can just store a stack of all changes, and remember everything that we changed during the operations. The final asymptotics is $O(q\log{q})$. Note: At about 20 minutes into the round one of our testers (SomethingNew) came up with a linear solution for problem E2, and jiangly implemented the same solution shortly after the contest! For further details, see 219001999. The main idea (as jiangly pointed out in the comments) is that we can use prefix sums instead of the Fenwick tree.
|
[
"data structures",
"interactive",
"trees"
] | 2,600
|
#include <bits/stdc++.h>
using i64 = long long;
constexpr int N = 1 << 20;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int q;
std::cin >> q;
std::vector<int> pos(N, q);
int n = 0;
std::vector<std::array<int, 5>> a;
std::vector<int> b(q), c(q + 1);
c[q] = n;
std::vector<int> s(q + 1);
for (int i = 0; i < q; i++) {
char o;
std::cin >> o;
if (o == '+') {
int x;
std::cin >> x;
a.push_back({x, pos[x], b[n], pos[b[n]], s[n + 1]});
if (pos[b[n]] == n) {
c[pos[b[n]]] -= 1;
pos[b[n]] = q;
c[pos[b[n]]] += 1;
}
if (pos[x] > n) {
c[pos[x]] -= 1;
pos[x] = n;
c[pos[x]] += 1;
}
s[n + 1] = s[n] + c[n];
b[n] = x;
n += 1;
} else if (o == '-') {
int k;
std::cin >> k;
n -= k;
a.push_back({-1, k});
} else if (o == '?') {
int ans = s[n];
std::cout << ans << std::endl;
} else {
auto [x, y, z, w, t] = a.back();
a.pop_back();
if (x == -1) {
n += y;
} else {
n -= 1;
b[n] = z;
s[n + 1] = t;
if (pos[x] != y) {
c[pos[x]] -= 1;
pos[x] = y;
c[pos[x]] += 1;
}
if (pos[z] != w) {
c[pos[z]] -= 1;
pos[z] = w;
c[pos[z]] += 1;
}
}
}
}
return 0;
}
|
1859
|
A
|
United We Stand
|
Given an array $a$ of length $n$, containing integers. And there are two initially empty arrays $b$ and $c$. You need to add each element of array $a$ to \textbf{exactly one} of the arrays $b$ or $c$, in order to satisfy the following conditions:
- Both arrays $b$ and $c$ are non-empty. More formally, let $l_b$ be the length of array $b$, and $l_c$ be the length of array $c$. Then $l_b, l_c \ge 1$.
- For any two indices $i$ and $j$ ($1 \le i \le l_b, 1 \le j \le l_c$), $c_j$ \textbf{is not} a divisor of $b_i$.
Output the arrays $b$ and $c$ that can be obtained, or output $-1$ if they do not exist.
|
What does it mean that $A$ divides $B$? First, if all numbers are equal, then there is no answer (since $a$ is divisible by $a$, if both arrays are non-empty, then $c_1$ is a divisor of $b_1$). Second, if $a$ is divisible by $b$ and they are both natural numbers, then the following equality holds: $b \le a$ (by definition, if $a$ is divisible by $b$, then $a$ can be represented as $k \dot b$, where $k$ is a natural number). Now we can place all instances of the smallest number into $b$, and all other numbers into $c$. It can be seen that such a construction always gives a valid answer.
|
[
"constructive algorithms",
"math",
"number theory"
] | 800
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void solve() {
int n = 0; cin >> n;
vector<int> inp; inp.assign(n, 0);
for (auto& x : inp) cin >> x;
sort(inp.begin(), inp.end());
if (inp.back() == inp[0]) {
cout << "-1\n";
return;
}
else {
int it = 0;
while (inp[it] == inp[0]) it++;
cout << it << " " << n - it << "\n";
for (int j = 0; j < it; ++j) cout << inp[j] << " ";
for (int j = it; j < n; ++j) cout << inp[j] << " ";
}
}
int main() {
int t = 0; cin >> t;
while (t--) solve();
return 0;
}
|
1859
|
B
|
Olya and Game with Arrays
|
Artem suggested a game to the girl Olya. There is a list of $n$ arrays, where the $i$-th array contains $m_i \ge 2$ positive integers $a_{i,1}, a_{i,2}, \ldots, a_{i,m_i}$.
Olya can move \textbf{at most one} (possibly $0$) integer from \textbf{each} array to another array. Note that integers can be moved from one array only once, but integers can be added to one array \textbf{multiple times}, and all the movements are done \textbf{at the same time}.
The beauty of the list of arrays is defined as the sum $\sum_{i=1}^n \min_{j=1}^{m_i} a_{i,j}$. In other words, for each array, we find the minimum value in it and then sum up these values.
The goal of the game is to maximize the beauty of the list of arrays. Help Olya win this challenging game!
|
Do all numbers in a single array really matter? If only the first minimum and the second minimum matter, what is the only way to increase a single array's beauty? What can we say about the array which will have the smallest number in the end? To increase the answer for each array separately, it is necessary to move the minimum to another array. Then, notice that it is optimal to move all the minimums to one array. Let's figure out which array. After moving the minimum from an array, the second minimum in the original array becomes the new minimum. Then, it is easy to notice that it is optimal to move all the minimums to the array with the smallest second minimum. After all the movements, we will have one array where the minimum element is the smallest number among all the arrays, and $n-1$ arrays where the minimum element is the second minimum in the original array. Therefore, the answer to the problem will be $M + K - S$, where $M$ is the minimum element among all the arrays, $K$ is the sum of all the second minimums, and $S$ is the smallest second minimum.
|
[
"constructive algorithms",
"greedy",
"math",
"sortings"
] | 1,000
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
#define all(v) v.begin(), v.end()
typedef long long ll;
const int INF = 1e9 + 7;
void solve() {
int n;
cin >> n;
int minn = INF;
vector<int> min2;
for (int i = 0 ; i < n ; i++) {
int m;
cin >> m;
vector<int> v(m);
for (auto &el : v) cin >> el;
int minel = *min_element(all(v));
minn = min(minn, minel);
v.erase(find(all(v), minel));
min2.push_back(*min_element(all(v)));
}
cout << minn + (ll) accumulate(all(min2), 0ll) - *min_element(all(min2)) << "\n";
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
#ifdef LOCAL
freopen("a.in", "r", stdin);
#endif
int t = 1;
cin >> t;
while (t--)
solve();
return 0;
}
|
1859
|
C
|
Another Permutation Problem
|
Andrey is just starting to come up with problems, and it's difficult for him. That's why he came up with a strange problem about permutations$^{\dagger}$ and asks you to solve it. Can you do it?
Let's call the cost of a permutation $p$ of length $n$ the value of the expression:
\begin{center}
$(\sum_{i = 1}^{n} p_i \cdot i) - (\max_{j = 1}^{n} p_j \cdot j)$.
\end{center}
Find the maximum cost among all permutations of length $n$.
$^{\dagger}$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).
|
What if we fix the maximum element in the resulting array? Try using greedy. Optimize the log factor away by noticing a certain fact. Let's fix the maximum element in an array - let it be $M$. Now, let's iterate from $n$ to $1$. Let the current chosen number be $i$. I claim that if we maintain the remaining available numbers to multiply by, then it is optimal to take the maximum such number $x$ that $x * i \le M$. Proof: let's say that this is not correct. Then, let's say that we pair $i$ with another number $x1$, and $x$ gets paired with some other number $i1$. Then, $i1 < i$, because it was chosen later, and $x1 < x$ (otherwise $i * x1 > M$). Now let's swap $x$ with $x1$. The sum is increased by $i * x - i * x1 - i1 * x + i1 * x1 = (i - i1)(x - x1) > 0$, and all of the numbers are less or equal to $M$. Now the task can be solved in $O(N^3logN)$ by simply iterating on the maximum from $N^2$ to $1$, while maintaining the remaining numbers with a set. In order to squeeze it in the TL, you can only consider such maximums that they can be represented as $i * j, 1 \le i, j \le n$. In order to optimize it to $O(N^3)$, let's notice that for each number $x$, it can be paired with any number from $1$ to $\frac{M} {x}$. Now just maintain a stack of all available elements at the current moment, add all numbers that possible, and pop the maximum number for all $i$ from $1$ to $N$.
|
[
"brute force",
"dp",
"greedy",
"math"
] | 1,200
|
#include <iostream>
#include <algorithm>
#include <set>
#include <stack>
#include <vector>
using namespace std;
void solve() {
int N = 0; cin >> N;
int ans = 0;
vector<int> pr;
pr.assign(N * N, -1);
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= N; ++j) {
pr[i * j - 1] = 1;
}
}
for (int mx = N * N; mx >= 1; --mx) {
if (pr[mx - 1] == -1) continue;
vector<vector<int>> a;
int curans = -mx;
bool br = false;
a.assign(N, vector<int>());
for (int j = N; j >= 1; --j) {
int num = min(mx / j, N);
if (num < 1) {
br = true;
break;
}
a[num - 1].push_back(j);
}
if (br) break;
stack<int> s;
for (int i = 0; i < N; ++i) {
s.push(i + 1);
bool brk = false;
for (auto x : a[i]) {
if (s.empty()) {
brk = true; break;
}
curans += s.top() * x;
s.pop();
}
if (brk) break;
}
ans = max(ans, curans);
}
cout << ans << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 0; cin >> t;
while (t--) solve();
return 0;
}
|
1859
|
D
|
Andrey and Escape from Capygrad
|
An incident occurred in Capygrad, the capital of Tyagoland, where all the capybaras in the city went crazy and started throwing mandarins. Andrey was forced to escape from the city as far as possible, using portals.
Tyagoland is represented by a number line, and the city of Capygrad is located at point $0$. There are $n$ portals all over Tyagoland, each of which is characterised by four integers $l_i$, $r_i$, $a_i$ and $b_i$ ($1 \le l_i \le a_i \le b_i \le r_i \le 10^9$). Note that the segment $[a_i, b_i]$ \textbf{is contained} in the segment $[l_i, r_i]$.
If Andrey is on the segment $[l_i, r_i]$, then the portal can teleport him to any point on the segment $[a_i, b_i]$. Andrey has a pass that allows him to use the portals an unlimited number of times.
Andrey thinks that the point $x$ is on the segment $[l, r]$ if the inequality $l \le x \le r$ is satisfied.
Andrey has $q$ options for where to start his escape, each option is characterized by a single integer $x_i$ — the starting position of the escape. He wants to escape from Capygrad as far as possible (to the point with the maximum possible coordinate). Help Andrey determine how far he could escape from Capygrad, starting at each of the $q$ positions.
|
What if we use greedy a bit? Where it is always beneficial to teleport? Use scanline Statement: It is always beneficial to teleport to point $b_i$. Proof: Let's assume that we were able to teleport from point $X$ to the right of $b_i$, but not from $b_i$. Then we used some segment $A$ that covers point $X$, but does not cover point $b$, and ends to the right of $b$. This is a contradiction. Let $ans_i$ be the maximum coordinate we can reach while being on segment $i$, and let $p_j$ be the answer to the $j$-th query. Then we notice that the answer to query $p_j = \max(x_j, \max_{i = 1}^n {ans_i \vert l_i \le x_j \le r_i})$. We will use the scanline method from the end. Events: $l_i$, $b_i$, $r_i$, $x_j$. We notice that events of type $r_i$ are not important to us when scanning from the end (according to statement number 1). It is important for us that we process events of type $b_i$ first, then events of type $x_j$, and then events of type $l_i$ (closing the segment in the scanline). We will go through the events of the scanline, processing them in the order of $b_i$, then events of type $x_j$, and then events of type $l_i$. We assume that there is a data structure that allows us to add elements, remove elements, and quickly output the maximum. For each event of type $b_i$, update the value of $ans_i$ - take the maximum value of $ans$ of all open segments from the structure. For each event of type $b_i$, update the value of $ans_i$ - take the maximum value of $ans$ of all open segments from the structure. For each event of type $x_j$, update the value of $p_j$ - take the maximum value of $ans$ of all open segments from the structure, as well as $x_j$. For each event of type $x_j$, update the value of $p_j$ - take the maximum value of $ans$ of all open segments from the structure, as well as $x_j$. For each event of type $l_i$, remove $ans_i$ from the structure. For each event of type $l_i$, remove $ans_i$ from the structure. We notice that to solve this problem, we can use the std::multiset} container, which automatically sorts elements in ascending order. We can store in $multiset$ $ans_i$ of all open segments. And then, when processing events, extract the maximum from $multiset$, all operations are performed in $O(\log n)$. This allows us to solve the problem in $O((n + q) \log n)$ time and $O(n)$ memory.
|
[
"binary search",
"data structures",
"dp",
"dsu",
"greedy",
"sortings"
] | 1,800
|
#include <iostream>
#include <vector>
#include <set>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <map>
#include <stack>
#include <cassert>
#include <unordered_map>
#include <bitset>
#include <random>
#include <unordered_set>
#include <chrono>
using namespace std;
#define all(a) a.begin(), a.end()
void solve() {
int n;
cin >> n;
vector<int> ans(n);
vector<tuple<int, int, int>> events;
for (int i = 0 ; i < n ; i++) {
int l, r, a, b;
cin >> l >> r >> a >> b;
ans[i] = b;
events.emplace_back(b, 1, i);
events.emplace_back(l, -1, i);
}
int q;
cin >> q;
vector<int> queries(q);
for (int i = 0 ; i < q ; i++) {
int x;
cin >> x;
queries[i] = x;
events.emplace_back(x, 0, i);
}
sort(all(events));
reverse(all(events));
multiset<int> s;
for (auto [x, type, ind] : events) {
if (type == 1) {
if (!s.empty()) {
ans[ind] = *s.rbegin();
}
s.insert(ans[ind]);
} else if (type == 0) {
if (!s.empty()) {
queries[ind] = max(queries[ind], *s.rbegin());
}
} else {
s.extract(ans[ind]);
}
}
for (auto el : queries)
cout << el << " ";
cout << "\n";
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
cin >> t;
while (t--)
solve();
return 0;
}
|
1859
|
E
|
Maximum Monogonosity
|
You are given an array $a$ of length $n$ and an array $b$ of length $n$. The cost of a segment $[l, r]$, $1 \le l \le r \le n$, is defined as $|b_l - a_r| + |b_r - a_l|$.
Recall that two segments $[l_1, r_1]$, $1 \le l_1 \le r_1 \le n$, and $[l_2, r_2]$, $1 \le l_2 \le r_2 \le n$, are non-intersecting if one of the following conditions is satisfied: $r_1 < l_2$ or $r_2 < l_1$.
The length of a segment $[l, r]$, $1 \le l \le r \le n$, is defined as $r - l + 1$.
Find the maximum possible sum of costs of non-intersecting segments $[l_j, r_j]$, $1 \le l_j \le r_j \le n$, whose total length is equal to $k$.
|
Maybe we can relax some conditions? Do we really need to always correctly calculate all sums? Optimize the obvious dp. Let's call the value of a segment $[l; r]$ $f(l, r) = abs(a_l - b_r) + abs(a_r - b_l)$. Let's write $dp[n1][k1]$ - maximum value of segments of total length $k1$ that end before $n1$. The obvious way to recalc is the following: $dp[n1][k1] = max(dp[n1 - 1][k1], dp[n1 - l][k1 - l] + f(n1 - l + 1, n1), 1 \le l \le k1)$. This works in $O(NK^2)$ and is too slow. Now let's consider the following: instead of getting the absolute value of segment $[l; r]$, we consider the maximum of the following four combinations: $b_l - a_r + b_r - a_l$, $b_l - a_r - b_r + a_l$, $-b_l + a_r + b_r - a_l$, $-b_l + a_r - b_r + a_l$. We can see that this always gives us the correct answer to the absolute value, since we check all of the possibilities. Now we can look at out dp states as a table, and notice that we recalc over the diagonal (we recalc over all states that have the same value of n1 - k1). Now, for each "diagonal", we maintain four maximum combinations: $dp[n1][k1] + b_{k1} + a_{k1}, dp[n1][k1] - b_{k1} + a_{k1}, dp[n1][k1] + b_{k1} - a_{k1}, dp[n1][k1] - b_{k1} - a_{k1}$, and when we want to recalc state $dp[n2][k2]$, we just consider all of the four possibilities.
|
[
"brute force",
"dp",
"math"
] | 2,500
|
#include <iostream>
#include <vector>
using namespace std;
const long long INF = 1e18;
#define int long long
void solve() {
int N = 0, K = 0; cin >> N >> K;
vector<int> a;
vector<int> b;
a.assign(N, 0);
b.assign(N, 0);
for (int i = 0; i < N; ++i) {
cin >> a[i];
}
for (int i = 0; i < N; ++i) {
cin >> b[i];
}
vector<long long> mx1; // max of (b_l + a_l) + corresponding dp
vector<long long> mx2; // max of (b_l - a_l) + corresponding dp
vector<long long> mn1; // min of (b_l + a_l) + corresponding dp
vector<long long> mn2; // min of (b_l - a_l) + corresponding dp
vector<vector<long long>> dp;
mx1.assign(N + 1, -INF); mx2.assign(N + 1, -INF);
mn1.assign(N + 1, INF); mn2.assign(N + 1, INF);
dp.assign(N + 1, vector<long long>(K + 1, 0));
for (int i = 0; i <= N; ++i) {
for (int j = 0; j <= min(i, K); ++j) {
if (i != 0) dp[i][j] = dp[i - 1][j];
int diag_val = i - j;
if (i != 0) {
dp[i][j] = max(dp[i][j], b[i - 1] + a[i - 1] - mn1[diag_val]);
dp[i][j] = max(dp[i][j], -b[i - 1] - a[i - 1] + mx1[diag_val]);
dp[i][j] = max(dp[i][j], a[i - 1] - b[i - 1] - mn2[diag_val]);
dp[i][j] = max(dp[i][j], b[i - 1] - a[i - 1] + mx2[diag_val]);
}
if (i != N) {
mn1[diag_val] = min(mn1[diag_val], b[i] + a[i] - dp[i][j]);
mx1[diag_val] = max(mx1[diag_val], b[i] + a[i] + dp[i][j]);
mn2[diag_val] = min(mn2[diag_val], b[i] - a[i] - dp[i][j]);
mx2[diag_val] = max(mx2[diag_val], b[i] - a[i] + dp[i][j]);
}
}
}
cout << dp[N][K] << "\n";
}
signed main() {
int T = 1;
cin >> T;
while (T--) {
solve();
}
}
|
1859
|
F
|
Teleportation in Byteland
|
There are $n$ cities in Byteland, some of which are connected by roads, which can be traversed in any direction. The $i$-th road has its own hardness parameter $w_i$. Time spent on traversing a road with its hardness equal to $w_i$ is $\lceil\frac{w_i}{c}\rceil$, where $c$ is the current driving skill.
The travel network of Byteland is a tree. In other words, between any pair of cities, there is exactly one path that passes through each city at most once.
In some cities you can visit driving courses. A single course takes $T$ time to complete, and after completing the course the driver's skill $c$ is increased by $2$ times. Notice that the time $T$ required to complete a course is the same in all cities, and courses can be completed in the same city more than once.
You need to answer the $q$ queries: what is the minimum time it takes to get from the city $a$ to city $b$ if you start the travelling with driving skill $c = 1$?
|
How many times do we really need to take driving courses? Can you think how would an optimal answer path look like? Can you recalculate the distances required to get to a city from every vertex? Root the tree arbitrarily. First, we can notice that there is no need to take driving courses more than $log{maxW}$ times. Now, let's iterate for the number of driving courses we take from $0$ to $20$ ($2^{20} > 1000000$). For each number we solve separately. Let us fix the number of taken as $q$. Now the path looks like the following: we go over the simple path, then we veer off to take courses in some town, then we come back to the path and finish it. Let's call $d[x]$ the minimum distance required to get from $x$ to a town which offers driving courses and then come back to the same town. We can recalculate $d[x]$ with multi-source BFS. Now, let's look at the vertex $v1$ on the path, from which we will start going off the path. Then, the cost of the path is $d[v1]$ + distance from $a$ to $v1$ on the original edges (with $c = 1$) + distance from $v1$ to $b$ on the modified edges(with $c = 2^{q}$). Now let's look at some cases, let $LCA$ be the LCA of $a$ and $b$, $h1[x]$ - the sum of all original edges from the root downwards to $x$, $h2[x]$ - the sum of all modified edges from the root downwards to $x$. If $v1$ is between $LCA$ and $a$, the cost is $h1[a] - h1[v1] + d1[v1] - h2[LCA] + h2[v1] + h2[b] - h2[LCA]$. If $v1$ is between $LCA$ and $a$, the cost is $h1[a] - h1[LCA] + h1[v1] - h1[LCA] + d1[v1] + h2[b] - h2[v1]$. Now we simply need to consider the terms which depend only on $v1$, and then we need to take the maximum value on a path. For that we can use binary lifting, and for LCA as well.
|
[
"data structures",
"dfs and similar",
"divide and conquer",
"graphs",
"shortest paths",
"trees"
] | 3,200
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <set>
#include <map>
#include <cmath>
#include <stack>
#include <deque>
#include <string>
#include <ctime>
#include <bitset>
#include <queue>
#include <cassert>
#include<unordered_set>
#include<unordered_map>
#include<string.h>
#include <random>
#include <chrono>
#include <math.h>
using namespace std;
#define pi pair<int, int>
#define ll long long
#define pll pair<ll, ll>
const ll INF = 1e18;
vector<vector<pi>> g;
vector<int> is_special;
vector<vector<int>> bin_lift;
vector<vector<pi>> new_g;
vector<int> tin;
vector<int> tout;
vector<ll> ans;
vector<pi> req;
vector<ll> h_orig;
vector<ll> h_new;
vector<ll> d;
vector<bool> used_bfs;
vector<vector<pll>> bin_lift_2;
vector<int> lc;
vector<int> top_order;
vector<pair<int, int>> pr;
int TIMER = 0;
void DFS(int v, int p) {
top_order.push_back(v);
tin[v] = TIMER++;
bin_lift[v][0] = p;
for (int i = 1; i < 17; ++i) {
if (bin_lift[v][i - 1] == -1) break;
bin_lift[v][i] = bin_lift[bin_lift[v][i - 1]][i - 1];
}
for (auto& x : g[v]) {
if (x.first == p) {
pr.push_back(x);
continue;
}
}
for (auto& x : g[v]) {
if (x.first == p) continue;
h_orig[x.first] = h_orig[v] + x.second;
DFS(x.first, v);
}
tout[v] = TIMER;
}
void BFS(int N) {
priority_queue<pll> q;
for (int i = 0; i < N; ++i) {
if (is_special[i]) {
q.push({ -0, i });
d[i] = 0;
}
}
while (!q.empty()) {
int v = q.top().second; q.pop();
if (used_bfs[v]) continue;
used_bfs[v] = true;
for (auto& x : new_g[v]) {
if (d[x.first] > d[v] + x.second) {
d[x.first] = d[v] + x.second;
q.push({ -d[x.first], x.first });
}
}
}
}
inline bool isIn(int a, int b) {
return tin[a] <= tin[b] && tout[a] >= tout[b];
}
int gLCA(int a, int b) {
if (isIn(a, b)) return a;
if (isIn(b, a)) return b;
int cB = b;
for (int i = 16; i >= 0; --i) {
if (bin_lift[cB][i] == -1) continue;
if (!isIn(bin_lift[cB][i], a)) cB = bin_lift[cB][i];
}
return bin_lift[cB][0];
}
ll g1(int a, int LCA) {
ll mn = d[a] + h_new[a] - h_orig[a];
int cK = a;
for (int i = 16; i >= 0; --i) {
if (bin_lift[cK][i] == -1) continue;
if (!isIn(LCA, bin_lift[cK][i])) continue;
mn = min(mn, bin_lift_2[cK][i].first);
cK = bin_lift[cK][i];
}
return mn;
}
ll g2(int a, int LCA) {
ll mn = d[a] + h_orig[a] - h_new[a];
int cK = a;
for (int i = 16; i >= 0; --i) {
if (bin_lift[cK][i] == -1) continue;
if (!isIn(LCA, bin_lift[cK][i])) continue;
mn = min(mn, bin_lift_2[cK][i].second);
cK = bin_lift[cK][i];
}
return mn;
}
void solve() {
top_order.clear();
pr.clear();
int N = 0, T = 0; cin >> N >> T;
g.assign(N, vector<pi>());
for (int j = 0; j < N - 1; ++j) {
int u = 0, v = 0, w = 0; cin >> u >> v >> w;
u--; v--;
g[u].push_back({ v, w }); g[v].push_back({ u, w });
}
is_special.assign(N, 0);
string s = ""; cin >> s;
for (int i = 0; i < N; ++i) is_special[i] = s[i] - '0';
tin.assign(N, 0); tout.assign(N, 0);
bin_lift.assign(N, vector<int>(17, -1));
TIMER = 0;
h_orig.assign(N, 0);
DFS(0, -1);
int Q = 0; cin >> Q;
ans.assign(Q, INF);
req.clear();
lc.clear();
for (int j = 0; j < Q; ++j) {
int u = 0, v = 0; cin >> u >> v;
u--; v--;
req.push_back({ u, v });
lc.push_back(gLCA(u, v));
}
bin_lift_2.assign(N, vector<pll>(17, pll(INF, INF)));
h_new.assign(N, 0);
for (ll level = 1; level <= 20; ++level) {
const int w = (1ll << level);
new_g.assign(N, vector<pi>());
for (int i = 0; i < N; ++i) {
for (int j = 0; j < g[i].size(); ++j) {
new_g[i].push_back({ g[i][j].first, g[i][j].second + ((g[i][j].second + w - 1) / w) });
}
}
d.assign(N, INF);
used_bfs.assign(N, false);
BFS(N);
h_new[0] = 0;
for (int n = 1; n < N; ++n) {
h_new[top_order[n]] = h_new[pr[n - 1].first] + (pr[n - 1].second + w - 1) / w;
int p = pr[n - 1].first;
int v = top_order[n];
bin_lift_2[v][0] = { d[p] + h_new[p] - h_orig[p], d[p] + h_orig[p] - h_new[p] };
for (int i = 1; i < 17; ++i) {
if (bin_lift[v][i] == -1) break;
bin_lift_2[v][i].first = min(bin_lift_2[v][i - 1].first, bin_lift_2[bin_lift[v][i - 1]][i - 1].first);
bin_lift_2[v][i].second = min(bin_lift_2[v][i - 1].second, bin_lift_2[bin_lift[v][i - 1]][i - 1].second);
}
}
for (int j = 0; j < Q; ++j) {
int a1 = req[j].first; int b1 = req[j].second;
int LCA = lc[j];
ans[j] = min(ans[j], g1(a1, LCA) + h_orig[a1] - h_new[LCA] + h_new[b1] - h_new[LCA] + level * T);
ans[j] = min(ans[j], g2(b1, LCA) + h_orig[a1] - h_orig[LCA] - h_orig[LCA] + h_new[b1] + level * T);
}
}
for (int i = 0; i < Q; ++i) {
ans[i] = min(ans[i], h_orig[req[i].first] + h_orig[req[i].second] - 2 * h_orig[lc[i]]);
cout << ans[i] << "\n";
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << setprecision(12);
int T = 1;
cin >> T;
while (T--) {
solve();
}
return 0;
}
|
1860
|
A
|
Not a Substring
|
A bracket sequence is a string consisting of characters '(' and/or ')'. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example:
- bracket sequences "()()" and "(())" are regular (they can be transformed into "(1)+(1)" and "((1+1)+1)", respectively);
- bracket sequences ")(", "(" and ")" are not regular.
You are given a bracket sequence $s$; let's define its length as $n$. Your task is to find a regular bracket sequence $t$ of length $2n$ such that $s$ \textbf{does not} occur in $t$ as a \textbf{contiguous substring}, or report that there is no such sequence.
|
Let's consider the following two cases: the string $s$ contains two consecutive equal characters, for example, ")(((" or "())". In this case, we can choose a string $t$ of the form "()()()", since it does not contain a substring of two equal characters, therefore $s$ is not a substring of $t$; in the string $s$, all adjacent characters are different, i.e., it is alternating. In this case, we can choose a string $t$ of the form "((()))", since here the length of the longest alternating substring is $2$. The only alternating substring it contains is "()", which is a part of every regular bracket sequence. Thus, it is sufficient to consider the answer among only two candidates - "()()()" and "((()))" of length $2n$.
|
[
"constructive algorithms",
"strings"
] | 900
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
int n = s.size();
string a, b;
for (int i = 0; i < 2 * n; ++i) {
a += "()"[i & 1];
b += ")("[i < n];
}
if (a.find(s) == string::npos) {
cout << "YES\n" << a << '\n';
} else if (b.find(s) == string::npos) {
cout << "YES\n" << b << '\n';
} else {
cout << "NO\n";
}
}
}
|
1860
|
B
|
Fancy Coins
|
Monocarp is going to make a purchase with cost of exactly $m$ burles.
He has two types of coins, in the following quantities:
- coins worth $1$ burle: $a_1$ regular coins and infinitely many fancy coins;
- coins worth $k$ burles: $a_k$ regular coins and infinitely many fancy coins.
Monocarp wants to make his purchase in such a way that there's \textbf{no change} — the total worth of provided coins is \textbf{exactly} $m$. He can use both regular and fancy coins. However, he wants to spend as little fancy coins as possible.
What's the smallest total number of fancy coins he can use to make a purchase?
|
There are two ways to approach this problem: a mathematical way and an algorithmic way. Approach 1 Let's start by looking at the possible ways to represent $m$ burles with our coins. For example, we could try to use as many coins of value $k$ as possible: then, the number of coins of value $k$ will be $\lfloor\frac{m}{k}\rfloor$, and the number of coins of value $1$ will be $m \bmod k$. Now suppose it's not optimal to use that many coins of value $k$; what if it's better to use more coins of value $1$ and fewer coins of value $k$? Well, we can still start with using $\lfloor\frac{m}{k}\rfloor$ coins of value $k$ and $m \bmod k$ coins of value $1$, and then try to replace one coin of value $k$ with $k$ coins of value $1$ several times (maybe zero). How many times should we do this, and when should we stop to get an optimal solution? Well, firstly, let's make sure that we have already taken as many regular coins as possible. Then, if we have at least $k$ leftover coins of value $1$ which are regular (not fancy), and we have taken at least one fancy coin of value $k$, it's better to replace that coin. It's easy to see that there's no need for any replacements if that's not the case: if we don't have $k$ regular coins which are currently unused, then at least one of the replacement coins will be fancy; and if the coin of value $k$ we want to replace is not fancy, why replacing it at all? So, we could write a while-loop that keeps track how many coins of which types we have taken, and replaces one fancy coin of value $k$ with $k$ regular coins of value $1$ until it's impossible. Unfortunately, this is too slow. But instead of running this loop, we can calculate the number of times we make that replacement in $O(1)$: it is the minimum of the number of regular coins of value $1$ we aren't using, divided by $k$, and the number of fancy coins of value $k$ we are using. So, the outline of the solution is the following: start by taking as many coins of value $k$ as possible, and calculate how many coins of which value we have taken; calculate how many regular and fancy coins of both types we have taken; calculate how many "replacements" (discard one fancy coin of value $k$, add $k$ regular coins of value $1$) we can make. Approach 2 The second approach also starts with analyzing how many coins of value $1$ and how many coins of value $k$ we can take. The minimum number of coins of value $k$ we can take is $0$, and the maximum number of such coins is $\lfloor\frac{m}{k}\rfloor$. Let $f(x)$ denote the number of fancy coins we use, if we take exactly $x$ coins of value $k$. This function can easily be calculated because we know how many coins of both types we take, if $x$ is fixed. We need to find the minimum of this function on $[0, \lfloor\frac{m}{k}\rfloor]$. How does $f(x + 1) - f(x)$ behave? The meaning of going from $f(x)$ to $f(x + 1)$ is just replacing $k$ coins of value $1$ with one coin of value $k$. When we increase $x$, obviously, we should try to discard fancy coins of value $1$ first, then regular coins of value $1$ (and the number of fancy coins we will discard will never increase when we increase $x$). Similarly, we should try to take regular coins of value $k$ first, then fancy ones (and the number of fancy coins we take will never decrease when we increase $x$). So, the value of $f(x+1) - f(x)$ does not decrease when $x$ increases. All of this means that the minimum value of $f(x)$ can be found using ternary search.
|
[
"binary search",
"brute force",
"greedy",
"math"
] | 1,200
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
for(int i = 0; i < t; i++)
{
int m, k, a1, ak;
cin >> m >> k >> a1 >> ak;
// function which calculates the number of fancy coins taken
// if we take exactly x coins of value k
auto f = [m, k, a1, ak](int x)
{
int taken_1 = m - k * x;
return max(0, taken_1 - a1) + max(0, x - ak);
};
int lf = 0;
int rg = m / k;
while(rg - lf > 2)
{
int mid = (lf + rg) / 2;
if(f(mid) < f(mid + 1))
rg = mid + 1;
else
lf = mid;
}
int ans = 1e9;
for(int i = lf; i <= rg; i++) ans = min(ans, f(i));
cout << ans << endl;
}
}
|
1860
|
C
|
Game on Permutation
|
Alice and Bob are playing a game. They have a permutation $p$ of size $n$ (a permutation of size $n$ is an array of size $n$ where each element from $1$ to $n$ occurs exactly once). They also have a chip, which can be placed on any element of the permutation.
Alice and Bob make alternating moves: Alice makes the first move, then Bob makes the second move, then Alice makes the third move, and so on. During the first move, Alice chooses any element of the permutation and places the chip on that element. During each of the next moves, the current player \textbf{has to} move the chip to any element that is simultaneously to the left and strictly less than the current element (i. e. if the chip is on the $i$-th element, it can be moved to the $j$-th element if $j < i$ and $p_j < p_i$). If a player cannot make a move (it is impossible to move the chip according to the rules of the game), that player \textbf{wins} the game.
Let's say that the $i$-th element of the permutation is \textbf{lucky} if the following condition holds:
- if Alice places the chip on the $i$-th element during her first move, she can win the game no matter how Bob plays (i. e. she has a winning strategy).
You have to calculate the number of lucky elements in the permutation.
|
For each position $i$, let's determine its status: whether this position is winning or losing for the player who moved the chip into that position. Since a player can only move a chip into a position with smaller index, we can determine the statuses of positions in the order from $1$ to $n$. You can treat it as dynamic programming. If there is no such $j$ that $j < i$ and $p_j < p_i$, then this position is a losing one, because the other player cannot make a move, which means they win (and the player who placed the chip in that position loses). Otherwise, the other player can make a move. And we already know whether the player wins if they place a chip for all previous positions. If there exists a position $j$ where a move can be made and $j$ is a winning position, then $i$ is a losing one (because our opponent will move there). Otherwise, $i$ is a winning position. Thus, we have a solution with a time complexity of $O(n^2)$, for each position $i$, we need to iterate through all possible transitions $j$. However, we can notice that we are only interested in two simple properties to determine the status of each position: whether a move can be made from the current position, and whether a move can be made into a winning position. The first property can be easily checked if we maintain the minimum element up to the current position $i$, let's call it $mn$. And for the second property, it is sufficient to maintain the minimum element among winning positions, let's call it $mnWin$. Then, position $i$ is winning if $mn < p_i$ and $mnWin > p_i$. Thus, the time complexity of the solution is $O(n)$.
|
[
"data structures",
"dp",
"games",
"greedy"
] | 1,400
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int ans = 0;
int mn = n + 1, mnWin = n + 1;
while (n--) {
int x;
cin >> x;
if (mn < x && x < mnWin) {
ans += 1;
mnWin = x;
}
mn = min(mn, x);
}
cout << ans << '\n';
}
}
|
1860
|
D
|
Balanced String
|
You are given a binary string $s$ (a binary string is a string consisting of characters 0 and/or 1).
Let's call a binary string \textbf{balanced} if the number of subsequences 01 (the number of indices $i$ and $j$ such that $1 \le i < j \le n$, $s_i=0$ and $s_j=1$) equals to the number of subsequences 10 (the number of indices $k$ and $l$ such that $1 \le k < l \le n$, $s_k=1$ and $s_l=0$) in it.
For example, the string 1000110 is balanced, because both the number of subsequences 01 and the number of subsequences 10 are equal to $6$. On the other hand, 11010 is not balanced, because the number of subsequences 01 is $1$, but the number of subsequences 10 is $5$.
You can perform the following operation any number of times: choose two characters in $s$ and swap them. Your task is to calculate the minimum number of operations to make the string $s$ balanced.
|
Let's calculate the following dynamic programming: $dp_{i, cnt0, cnt01}$ - the minimum number of changes in string $s$ if we consider only $i$ first characters of it, the number of characters 0 on that prefix is $cnt0$, and the number of subsequences 01 on that prefix is equal to $cnt01$. The transitions are pretty simple. Let's look at the transitions according to the character we are trying to place at the next position: if it is 0, then there is transition from the state $(i, cnt0, cnt01)$ to the state $(i + 1, cnt0 + 1, cnt01)$ and the value of $dp$ depends on $s_i$ (the value stays the same if $s_i=0$, and increases by $1$ otherwise); if it is 1, then there is transition from the state $(i, cnt0, cnt01)$ to the state $(i + 1, cnt0, cnt01 + cnt0)$, and the value of $dp$ depends on $s_i$ (the value stays the same if $s_i=1$ and increases by $1$ otherwise). So, this dynamic programming works in $O(n^4)$. It remains us to get the answer to the problem from that dynamic programming. It is stored in $dp_{n, cnt0, need}$, where $cnt0$ is equal to the number of characters 0 in the string $s$, and $need=\frac{cnt0 \cdot cnt1}{2}$ (because the number of subsequences 01 should be equal to the number of subsequences 10). But our dynamic programming stores the number of changes in the string, and the problems asks for the minimum number of swaps. However, we can easily get it from the $dp$ value. Since the amounts of zeroes and ones are fixed in the string, then the number of changes from 0 to 1 equals to the number of changes from 1 to 0 and we can pair them up. So, the answer to the problem is the half of the $dp$ value.
|
[
"dp"
] | 2,200
|
#include <bits/stdc++.h>
using namespace std;
using li = long long;
const int N = 111;
int n;
string s;
int dp[2][N][N * N];
int main() {
cin >> s;
n = s.size();
dp[0][0][0] = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= i + 1; ++j) {
for (int cnt = 0; cnt <= j * (i + 1 - j); ++cnt) {
dp[1][j][cnt] = n;
}
}
for (int j = 0; j <= i; ++j) {
for (int cnt = 0; cnt <= j * (i - j); ++cnt) {
dp[1][j + 1][cnt] = min(dp[1][j + 1][cnt], dp[0][j][cnt] + (s[i] != '0'));
dp[1][j][cnt + j] = min(dp[1][j][cnt + j], dp[0][j][cnt] + (s[i] != '1'));
}
}
swap(dp[0], dp[1]);
}
int cnt0 = count(s.begin(), s.end(), '0');
cout << dp[0][cnt0][cnt0 * (n - cnt0) / 2] / 2 << '\n';
}
|
1860
|
E
|
Fast Travel Text Editor
|
You are given a string $s$, consisting of lowercase Latin letters.
There's a cursor, initially placed between two adjacent letters of the string. The cursor can't be placed before the first or after the last letter.
In one move, you can perform one of three actions:
- move a cursor one position to the left (if that doesn't place it before the first letter);
- move a cursor one position to the right (if that doesn't place it after the last letter);
- let $x$ be the letter immediately to the left of the cursor, and $y$ be the letter immediately to the right of the cursor. Choose any pair of \textbf{adjacent} letters in the string such that the \textbf{left} of them is $x$ and the \textbf{right} of them is $y$, and move the cursor to the position between these two letters.
You are asked $m$ queries. In each query, you are given two integers $f$ and $t$, which correspond to two valid positions of the cursor in the string. In response to the query, you have to calculate the minimum number of operations required to move the cursor from position $f$ to position $t$.
|
Let's start with the easiest slow solution. We can basically treat the problem as a graph one. There are $n-1$ vertices and the operations represent edges: from $i$ to $i+1$, from $i+1$ to $i$ and from $i$ to $j$ if $s_i = s_j$ and $s_{i+1} = s_{j+1}$. Then, for a query, we can run any algorithm that finds the shortest path. For example, BFS. That will be $n^2$ per query in the worst case, because the third type of actions produces a lot of edges. Let's try to optimize the third action. If you look at the edges between all positions linked by the third action, they just form cliques. So the distance between every pair of vertices should be equal to $1$. Instead of having a lot of edges, we can add a dummy vertex that simulates this behavior. For example, add a directed edge from each vertex in the clique to the dummy vertex of weight $1$ and a directed edge back of weight $0$. Now, you can travel from one vertex to another in the clique in $1$, but only use $O(n)$ edges in total. Thus, the BFS for each query will be linear. Well, a couple of things are wrong with that statement... First, not a regular BFS, of course, but a 0-1 BFS now, since there are edges of weight $0$. Second, there are also some dummy vertices. How many of them? Each clique is induced by all positions that have the same letters to the left and to the right of them. So, there are $|A|^2$ options, where $|A| = 26$, and $n + |A|^2$ vertices in total. To optimize further, let's investigate the structure of the path. There are trivial paths: they just go left or right without using the third action. We can initialize the answer with them. Otherwise, a path uses the jump to the dummy node at least once. Let that node be $s$. So, the path looks like $f \rightarrow s$, then $s \rightarrow t$. Let's use the fact that there are not that many candidates for $s$. We can iterate over $s$ and update the answer with each of them. If the optimal path goes through any of them, we will find it. And calculating $f \rightarrow s$ or $s \rightarrow t$ is way easier. First, $f \rightarrow s$ is the same as $s \rightarrow f$ in a transposed graph (all edges are reversed). Second, we can calculate the shortest path from $s$ to all vertices with a single 0-1 BFS. Thus, we get a solution in $O(|A|^2 \cdot (n + |A|^2 + q))$. We can either run $|A|^2$ BFS's before reading the queries and save the results, using $O(|A|^2 \cdot n)$ memory. Alternatively, we can read the queries, then run each BFS and update the answer with its results immediately for $O(n + |A|^2)$ memory. The second option will generally also be faster by a constant factor, since there are fewer cache misses.
|
[
"data structures",
"dfs and similar",
"graphs",
"shortest paths"
] | 2,400
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int INF = 1e9;
const int AL = 26;
struct query{
int f, t, ans;
};
struct edge{
int u, w;
};
int main() {
cin.tie(0);
iostream::sync_with_stdio(false);
string s;
cin >> s;
int n = s.size();
int m;
cin >> m;
vector<query> a(m);
forn(i, m){
cin >> a[i].f >> a[i].t;
--a[i].f, --a[i].t;
a[i].ans = abs(a[i].f - a[i].t);
}
int k = n - 1 + AL * AL;
vector<vector<edge>> g(k);
forn(i, n - 1){
int j = n - 1 + (s[i] - 'a') * AL + (s[i + 1] - 'a');
g[i].push_back({j, 0});
g[j].push_back({i, 1});
if (i > 0){
g[i].push_back({i - 1, 1});
g[i - 1].push_back({i, 1});
}
}
for (int st = n - 1; st < k; ++st){
vector<int> d(k, INF);
d[st] = 0;
deque<int> q;
q.push_back(st);
while (!q.empty()){
int v = q.front();
q.pop_front();
for (auto it : g[v]){
if (d[it.u] <= d[v] + it.w) continue;
d[it.u] = d[v] + it.w;
if (it.w == 0) q.push_front(it.u);
else q.push_back(it.u);
}
}
forn(i, m){
a[i].ans = min(a[i].ans, d[a[i].f] + d[a[i].t] - 1);
}
}
forn(i, m) cout << a[i].ans << '\n';
return 0;
}
|
1860
|
F
|
Evaluate RBS
|
You are given $2n$ tuples of values $(a, b, c)$, where $a$ and $b$ are positive integers and $c$ is a bracket '(' or ')'. Exactly $n$ tuples have $c = $'(' and the other $n$ tuples have $c =$ ')'.
You are asked to choose two positive values $x$ and $y$ ($x > 0$ and $y > 0$; \textbf{not necessarily integers}) and sort the tuples in the increasing value of $a \cdot x + b \cdot y$. If several tuples have the same value, you can place them in any order among themselves.
Is it possible to choose such $x$ and $y$ that taking brackets $c$ from the tuples in the resulting order produces a regular bracket sequence?
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence.
|
Think of this as a geometry problem. If that's a revelation for you, don't worry, you'll start seeing it with more experience. We have some points $(a, b)$, are asked to choose a vector $(x, y)$ and sort the points by a dot product of $(a, b)$ and $(x, y)$. What exactly is a dot product? Well, $A \cdot B = |A| \cdot |B| \cdot \cos \alpha$. Obviously, $(a, b)$ will always be the same length no matter what $(x, y)$ we choose. At the same time, the length of $(x, y)$ will also be the same for a fixed $(x, y)$. So, a dot product only depends on an angle between $(x, y)$ and $(a, b)$. Thus, the vector $(x, y)$ can always be a unit one. Imagine iterating over all vectors $(x, y)$ in the increasing order of their angle. Consider a pair of different points $(a_1, b_1)$ and $(a_2, b_2)$. When does one go before the other in the order? We can compare their angles to $(x, y)$. So, if we keep rotating $(x, y)$, the order of two points will be changing when their angles to $(x, y)$ are the same. That happens exactly twice, and both events correspond to the opposite vectors. Both of them lie on the line perpendicular to the one $(a_1, b_1)$ and $(a_2, b_2)$ are on. Now imagine that rotating $(x, y)$ idea as an actual algorithm. We'd want to iterate over all $(x, y)$ while maintaining the order of points. When we encounter $(x, y)$ on a line where two points swap, we swap. For each $(x, y)$ we check if current order of points produces an RBS. For points with the same dot product (so when $(x, y)$ is on a line where these swap), we arrange them in such an order that the opening bracket goes first, then the closing bracket. That must be pretty obvious from any RBS intuition. Obviously, we don't care about all $(x, y)$ (also there are infinitely many of them). We only care about ones where something happens. Now, that algorithm is called a radial sweepline. Very commonly not the prettiest thing to code, but I'll share some implementation details that help with this one. I'll also call vectors $(x, y)$ events from now on sometimes. First, generate all interesting $(x, y)$, arrange them by their angle and save what happens for each of them. Get rid of pairs with non-positive $x$ or $y$. Now, arranging by angle can be done with just a cross product. Also, with that, you don't even have to normalize the vectors. You can use a map from points to events with a comparator using cross product (and no additional tie-breaks). Second, instead of swapping pairs one by one on each angle (which might turn very annoying very fast), let's process them all in bulk. When there are multiple pairs of points swapping on the same angle, extract all of them from the current order, sort them on their own and insert them back. Notice that it doesn't produce exactly the same outcome. It rearranges the points as if all points with equal dot product are free among each other until the next event. However, if we turn $(x, y)$ just a bit further, they will get in their true places. But our algorithm will just skip to the next event without fixing the order. It's actually quite easy to fix the issue. Along with sorting points that swap on the current event, take also points that had to be swapped on the previous event. Sort them all together. That won't increase the complexity (however, will increase the constant factor), but will fix the order of the previous event points. The sorting is best done with an inverse permutation of the order. For each point, remember its current place in the order. Now, we can find where each point is, and we can easily update the inverse permutation after the rearrangement. Since every pair of point appears at most $O(1)$ times, the total size of arrays to sort is $O(n^2)$. Finally, how to check for an RBS every time? We can't afford $O(n)$, so we must maintain something. For a sequence to be an RBS, all prefix balances of brackets should be non-negative (since we are already guaranteed by the input that the final balance is $0$). The idea is easy. Notice how the points that are swapped on each event actually represent some segments of the order. And all swaps are performed within these segments. Thus, the prefix balances are only updated for the positions of the swapping points. Basically, we can maintain the entire array of the prefix balances and the number of negative elements in it. On each event, recalculate its entire parts corresponding to the positions of the sorted points. If the number of negative elements becomes $0$, then we found the answer. Overall complexity: $O(n^2 \log n)$.
|
[
"data structures",
"geometry",
"implementation",
"math",
"sortings"
] | 2,900
|
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < int(n); i++)
using namespace std;
const int INF = 1e9;
struct bracket{
int a, b, c;
};
struct point{
int x, y;
};
long long cross(const point &a, const point &b){
return a.x * 1ll * b.y - a.y * 1ll * b.x;
}
long long dot(const point &a, const bracket &b){
return a.x * 1ll * b.a + a.y * 1ll * b.b;
}
bool operator <(const point &a, const point &b){
return cross(a, b) > 0;
}
int main() {
int t;
cin >> t;
while (t--){
int n;
cin >> n;
vector<bracket> val;
forn(i, 2 * n){
int a, b;
string c;
cin >> a >> b >> c;
val.push_back({a, b, c[0] == '(' ? 1 : -1});
}
map<point, vector<int>> opts;
forn(i, 2 * n) forn(j, 2 * n){
int dx = val[i].b - val[j].b;
int dy = val[j].a - val[i].a;
if (dx <= 0 || dy <= 0) continue;
opts[{dx, dy}].push_back(i);
opts[{dx, dy}].push_back(j);
}
opts[{1, INF}];
vector<int> ord(2 * n), rord(2 * n);
iota(ord.begin(), ord.end(), 0);
sort(ord.begin(), ord.end(), [&](int i, int j){
long long di = dot({INF, 1}, val[i]);
long long dj = dot({INF, 1}, val[j]);
if (di != dj) return di < dj;
return val[i].c > val[j].c;
});
forn(i, 2 * n) rord[ord[i]] = i;
int neg = 0, cur = 0;
vector<int> bal(1, 0);
for (int i : ord){
cur += val[i].c;
bal.push_back(cur);
neg += cur < 0;
}
bool ans = neg == 0;
vector<int> prv;
for (auto it : opts){
vector<int> tot = prv;
for (int x : it.second) tot.push_back(x);
sort(tot.begin(), tot.end(), [&](int i, int j){
return rord[i] < rord[j];
});
tot.resize(unique(tot.begin(), tot.end()) - tot.begin());
for (int x : tot) neg -= bal[rord[x] + 1] < 0;
vector<int> tmp = tot;
sort(tot.begin(), tot.end(), [&](int i, int j){
long long di = dot(it.first, val[i]);
long long dj = dot(it.first, val[j]);
if (di != dj) return di < dj;
return val[i].c > val[j].c;
});
vector<int> nrord(tot.size());
forn(i, tot.size()) nrord[i] = rord[tmp[i]];
forn(i, tot.size()) rord[tot[i]] = nrord[i];
for (int x : tot){
bal[rord[x] + 1] = bal[rord[x]] + val[x].c;
neg += bal[rord[x] + 1] < 0;
}
if (neg == 0){
ans = true;
break;
}
prv = it.second;
}
puts(ans ? "YES" : "NO");
}
return 0;
}
|
1861
|
A
|
Prime Deletion
|
A prime number is a positive integer that has exactly two different positive divisors: $1$ and the integer itself. For example, $2$, $3$, $13$ and $101$ are prime numbers; $1$, $4$, $6$ and $42$ are not.
You are given a sequence of digits from $1$ to $9$, in which \textbf{every digit from $1$ to $9$ appears exactly once}.
You are allowed to do the following operation \textbf{several (maybe zero) times}: choose any digit from the sequence and delete it. \textbf{However, you cannot perform this operation if the sequence consists of only two digits.}
Your goal is to obtain a sequence which represents a prime number. Note that you cannot reorder the digits in the sequence.
Print the resulting sequence, or report that it is impossible to perform the operations so that the resulting sequence is a prime number.
|
There are many possible approaches to this problem. For example, you could use brute force to solve it: iterate on every integer from $1$, check that it is a prime number by iterating on its divisors, and check that it appears as a subsequence in the given digit sequence. If you find the answer, break the loop and print the number you found. But that's a bit lengthy to code. Let's try something different. We can try looking for a small set of primes such that at least one of the primes from that set appears in the given sequence. Let's try short primes, they are easier to work with. If there exist two prime numbers of length $2$ consisting of digits $x$ and $y$, one of them is $xy$, and the other of them is $yx$, then one of them will definitely appear in our sequence. If $x$ comes earlier than $y$, then $xy$ appears in the sequence, otherwise it's $yx$. Thankfully, it's possible to find these two primes. For example, you can use $13$ and $31$; one of them will definitely appear in the sequence. So, the easiest solution is to find whether $1$ is earlier than $3$ in the sequence. If $1$ is earlier, then $13$ is the answer, otherwise it's $31$.
|
[
"constructive algorithms",
"math"
] | 800
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
for(int i = 0; i < t; i++)
{
string s;
cin >> s;
if(s.find("1") < s.find("3"))
cout << 13;
else
cout << 31;
cout << endl;
}
}
|
1861
|
B
|
Two Binary Strings
|
You are given two strings $a$ and $b$ of equal length, consisting of only characters 0 and/or 1; both strings start with character 0 and end with character 1.
You can perform the following operation any number of times (possibly zero):
- choose one of the strings and two \textbf{equal} characters in it; then turn all characters between them into those characters.
Formally, you choose one of these two strings (let the chosen string be $s$), then pick two integers $l$ and $r$ such that $1 \le l < r \le |s|$ and $s_l = s_r$, then replace every character $s_i$ such that $l < i < r$ with $s_l$.
For example, if the chosen string is 010101, you can transform it into one of the following strings by applying one operation:
- 000101 if you choose $l = 1$ and $r = 3$;
- 000001 if you choose $l = 1$ and $r = 5$;
- 010001 if you choose $l = 3$ and $r = 5$;
- 010111 if you choose $l = 4$ and $r = 6$;
- 011111 if you choose $l = 2$ and $r = 6$;
- 011101 if you choose $l = 2$ and $r = 4$.
You have to determine if it's possible to make the given strings equal by applying this operation any number of times.
|
If the answer is YES, we can always bring both strings to the form $00 \dots 01 \dots 11$ (some prefix consists of zeros, some suffix consists of ones, and all zeroes are before all ones). It's true because after we make both strings equal, we can apply another operation with $l = i, r = |a|$, where $i$ is the minimum index where both strings have $1$ after we made them equal. For example, in the first test case, the strings are equal to $01110001$ after applying all operations considered in the statement. We can turn them into the string $01111111$ by applying operation with $l = 2, r = 8$. Okay, now let's try to find out when we can transform a string into the form $00 \dots 0011 \dots 11$. We claim that it's possible to transform the string $s$ into the form "$i$ first elements are zeroes, all the remaining elements are ones" if and only if $s_i = 0$ and $s_{i+1} = 1$: if $s_i = 0$ and $s_{i+1} = 1$, we can apply two operations with $l = 1, r = i$ and $l = i+1, r = |s|$, and the string turns into the form "$i$ first elements are zeroes, all the remaining elements are ones"; however, if that's not the case, then either $s_i = s_{i+1}$, or $s_i = 1$ and $s_{i+1} = 0$. In the former case, we need to change one of these two elements; but since they are equal and adjacent, every operation on them will affect them both, so it's impossible to change only one of them. In the latter case, we need to set either $s_i$ to $0$ or $s_{i+1}$ to $1$ first; and when we do it, the elements become equal, and every operation on them will affect them both. So, it's impossible to bring the string into the form "$i$ first elements are zeroes, all the remaining elements are ones". So, the answer is YES if there is an index $i$ such that $a_i = b_i = 0$ and $a_{i+1} = b_{i+1} = 1$. Otherwise, the answer is NO.
|
[
"constructive algorithms",
"dp",
"greedy"
] | 1,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
for (int tc = 0; tc < t; ++tc) {
string a, b;
cin >> a >> b;
bool ok = false;
for (int i = 0; i + 1 < a.size(); ++i) {
if (a[i] == b[i] && a[i] == '0' && a[i + 1] == b[i + 1] && a[i + 1] == '1') {
ok = true;
}
}
if (ok)
puts("YES");
else
puts("NO");
}
return 0;
}
|
1861
|
C
|
Queries for the Array
|
Monocarp had an array $a$ consisting of integers. Initially, \textbf{this array was empty}.
Monocarp performed three types of queries to this array:
- choose an integer and append it \textbf{to the end of the array}. Each time Monocarp performed a query of this type, he wrote out a character +;
- remove \textbf{the last element} from the array. Each time Monocarp performed a query of this type, he wrote out a character -. Monocarp never performed this query on an empty array;
- check if the array is sorted in non-descending order, i.,e. $a_1 \le a_2 \le \dots \le a_k$, where $k$ is the number of elements in the array currently. \textbf{Every array with less than $2$ elements is considered sorted}. If the array was sorted by the time Monocarp was performing that query, he wrote out a character 1. Otherwise, he wrote out a character 0.
You are given a sequence $s$ of $q$ characters 0, 1, + and/or -. These are the characters that were written out by Monocarp, given in the exact order he wrote them out.
You have to check if this sequence is consistent, i. e. it was possible for Monocarp to perform the queries so that the sequence of characters he wrote out is exactly $s$.
|
First of all, let's analyze which situations cause the answer to be NO. There are two types: if the number of elements in the array is currently less than $2$, the array is definitely sorted. So, if we get a 0 and the number of elements is $0$ or $1$, the answer is NO; if the array is sorted, but some prefix of it (maybe coinciding with the whole array) is not sorted, this is also a NO. These are the only two situations that cause a NO. We can prove that if none of this occurs, the answer is YES, using the following construction: every time there is a + query, we will add $1$ to the array; every time there is a 0 query, and the current array is sorted, we will change the last element of the array to $0$ (and assume we added $0$ instead of $1$ in the query it was added). That way, we can ensure that the array stays sorted as long as possible. The only cases when this construction doesn't work are: we try to change an element to $0$, but there is no such element (the array is empty), or the array stays sorted after the change (we change the first element). This is exactly when a query 0 appears and the current number of elements is less than $2$; we change an element to $0$, and it makes the current array non-sorted, but it has to be sorted due to a query of type 1 affecting it. This is exactly when we have a sorted array with a non-sorted prefix. Okay, now we have to check these two conditions somehow. The first one is quite easy: just keep track of the number of elements in the array; every time you process +, increase it; every time you process -, decrease it; every time you process 0, check the number of elements. The second condition is tricky. There are many approaches on how to handle it; I will describe two of them. Approach $1$ (Roms) We are interested in a situation when a sorted array has an unsorted prefix. Suppose there is a state of our array when this happens. In case when this array has multiple prefixes for which we know that they are sorted, which one should we choose? It should be the longest sorted prefix, because we want an unsorted prefix to be shorter (or have the same length). And among all non-sorted prefixes, we are interested in the shortest one, for the same reason. So, let's go over the queries and keep track of the shortest non-sorted prefix and the longest sorted prefix of our array. Let's analyze how our queries affect these two values. when we append a new element (query of type +), we no longer know that the current array is sorted, but its longest sorted prefix stays the same, and its shortest non-sorted prefix also stays the same. So, we don't need to update these values; when we delete the last element (query of type -), the length of the sorted prefix might change. If it was equal to the number of elements before the query, it should decrease by $1$, because the last element on that prefix was deleted, and the prefix no longer exists. As for the length of the shortest unsorted prefix, if it was equal to the number of elements in the array before the query, it should be set to $0$ - because maybe the last element of the array made the array unsorted, and we don't know anything about the prefixes before it. when we process a query of type 0 or 1, we should update the shortest non-sorted prefix or the longest sorted prefix accordingly. After each query, we can just check that the longest sorted prefix is shorter than the shortest non-sorted prefix (or one of them doesn't exist). Approach $2$ (BledDest) BledDest is a graph theory lunatic, so naturally, he designed a graph-related solution to this problem. Let's visualize all states of the array using a rooted tree. Every moment of time after a query corresponds to some vertex in this tree, and one vertex $x$ is a parent of another vertex $y$ if the array in the state represented by $x$ is the same as the array represented by $y$, but without the last element. For example, if the string of queries is ++-++---+-+, the tree looks like this (the labels on the vertices correspond to the number of queries after which the array is in that state): This tree can be constructed from the query string as follows. Start with the root vertex, which represents the state when the array is empty. Every time you get a query +, you need to go down the tree. You create a new vertex to go into, because if you go down the tree to an existing vertex, it means that the states will coincide - and the arrays in these two states are not necessarily similar. If you get a query -, you go up the tree - so you either maintain the current path in the tree in a stack, or store a parent for each vertex, to know where to go when you go up. Okay, now what about queries of type 0 and 1? Every time we process such a query, we mark the current vertex to remember that it has a 0 or a 1 in it. For example, you can store two boolean arrays that give you the information whether a vertex is marked with 0 and whether a vertex is marked with 1. So, how does this tree help us in solving the problem? Recall what we're trying to check: we want to find out if a sorted array has a non-sorted prefix. In terms of our tree, it means that a vertex marked with 0 has an ancestor (possibly itself) marked with 1. To check that in $O(n)$, you can, for example, run a series of DFS traversals from all vertices marked with 1 and make sure that you don't visit any vertices marked with 0. Or you could do it in a single DFS (as the model solution does) which, for each vertex in the tree, computes if it has a vertex marked with 0 in its subtree.
|
[
"data structures",
"dfs and similar",
"implementation",
"strings",
"trees"
] | 1,600
|
#include<bits/stdc++.h>
using namespace std;
vector<int> has0, has1;
vector<vector<int>> g;
bool ans;
bool dfs(int x, int d)
{
if(has0[x] && (has1[x] || d <= 1))
ans = false;
bool res = false;
for(auto y : g[x])
res |= dfs(y, d + 1);
if(has0[x] && res)
ans = false;
return res || has1[x];
}
void solve()
{
ans = true;
has0.push_back(0);
has1.push_back(0);
g.push_back(vector<int>());
int ts = 1;
string s;
cin >> s;
vector<int> st = {0};
for(auto x : s)
{
int cur = st.back();
if(x == '0')
has0[cur] = 1;
if(x == '1')
has1[cur] = 1;
if(x == '+')
{
g[cur].push_back(ts);
st.push_back(ts);
ts++;
has0.push_back(0);
has1.push_back(0);
g.push_back(vector<int>());
}
if(x == '-')
st.pop_back();
}
dfs(0, 0);
cout << (ans ? "YES\n" : "NO\n");
has0.clear();
has1.clear();
g.clear();
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
for(int i = 0; i < t; i++)
solve();
}
|
1861
|
D
|
Sorting By Multiplication
|
You are given an array $a$ of length $n$, consisting of \textbf{positive integers}.
You can perform the following operation on this array any number of times (possibly zero):
- choose three integers $l$, $r$ and $x$ such that $1 \le l \le r \le n$, and multiply every $a_i$ such that $l \le i \le r$ by $x$.
Note that you can choose \textbf{any} integer as $x$, it doesn't have to be positive.
You have to calculate the minimum number of operations to make the array $a$ sorted in \textbf{strictly ascending} order (i. e. the condition $a_1 < a_2 < \dots < a_n$ must be satisfied).
|
At first, let's figure out which multiplications by negative values we perform. After a few multiplications, some subarrays of the array $a$ might become negative. If there is more than one such negative subarray (and there are non-negative elements between them), then the array cannot be sorted by multiplication by non-negative values. If there is one such subarray, then it must be a prefix of the array. Let's try solving this problem in $O(n^2)$. Let's iterate over the length of the negative prefix and solve the problem for some fixed negative prefix. Make all the elements on this prefix negative (for example, by multiplying by $-1$), and then iterate over indices of the array in ascending order. If $a_i < a_{i + 1}$ (where $i$ is the current index), then we just go to the next index. Otherwise, we can always multiply the prefix (if $a_i < 0$) or the suffix (if $a_i > 0$) by some positive value so that the prefix $a_1, \dots, a_i, a_{i + 1}$ becomes sorted. Note that if we fixed the negative prefix, we cannot restore the condition $a_i < a_{i+1}$ on multiple indices $i$ with just one operation. For example, if $a_i, a_{i+1}, a_j$ and $a_{j+1}$ are all positive, $a_i \ge a_{i+1}$ and $a_j \ge a_{j+1}$, we need at least two operations to ensure that $a_i < a_{i+1}$ and $a_j < a_{j+1}$. In the first operation, we should choose $l = i+1$, and in the second operation, we should choose $l = j+1$, so that both $a_{i+1}$ becomes greater than $a_i$ and $a_{j+1}$ becomes greater than $a_j$. For example, if the array $a$ is $[-1, -2, -3, 2, 1, 3]$ (after we fixed that the first $3$ elements will be negative). we perform the following sequence of actions: $i = 1$, $a_1 \ge a_2$ and $a_1 < 0$, so we just multiply the prefix $a_1, \dots, a_1$ by some positive value (for example $4$); after that the current array $a = [-4, -2, -3, 2, 1, 3]$; $i = 2$, $a_2 \ge a_3$ and $a_2 < 0$, so we just multiply the prefix $a_1, \dots, a_2$ by some positive value (for example $2$); after that the current array $a = [-8, -4, -3, 2, 1, 3]$; $i = 3$, $a_3 < a_4$ so we just go to the next index; $i = 4$, $a_4 \ge a_5$ and $a_4 > 0$, so we just multiply the suffix $a_5, \dots, a_6$ by some positive value (for example $10$); after that, the current array $a = [-8, -4, -3, 2, 10, 30]$; $i = 5$, $a_5 < a_6$ so we just go to the next index; $i = 6$, so the array is sorted. To solve the problem in $O(n)$, we need the following observation: if the negative prefix has length $x$, we perform the operations in two cases: if $a_i \le a_{i+1}$ (in the original array) and $i+1 \le x$; if $a_i \ge a_{i+1}$ and $i \ge x$. So, we can iterate on the length of negative prefix $x$ and maintain the number of indices $i$ such that $a_{i-1} \le a_i$ and $i < x$; and the number of indices $j$ such that $a_{j} \ge a_{j+1}$ and $j \ge x$. Don't forget the case when $x = 0$, then we don't need an extra operation to make the prefix negative.
|
[
"dp",
"greedy"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
const int N = 200 * 1000 + 5;
int t;
int n;
int a[N];
int main() {
cin >> t;
for (int tc = 0; tc < t; ++tc){
cin >> n;
for (int i = 0; i < n; ++i)
cin >> a[i];
int cnt = 0;
for (int i = 1; i < n; ++i)
cnt += (a[i - 1] >= a[i]);
int res = n, cnt2 = 0;
for (int i = 0; i <= n; ++i) {
bool isMultipliedByNegative = (i > 0);
res = min(res, isMultipliedByNegative + cnt + cnt2);
if (i + 1 < n)
cnt -= (a[i] >= a[i + 1]);
if (i > 0)
cnt2 += (a[i - 1] <= a[i]);
}
cout << res << endl;
}
}
|
1861
|
E
|
Non-Intersecting Subpermutations
|
You are given two integers $n$ and $k$.
For an array of length $n$, let's define its cost as the maximum number of contiguous subarrays of this array that can be chosen so that:
- each element belongs to at most one subarray;
- the length of each subarray is exactly $k$;
- each subarray contains each integer from $1$ to $k$ exactly once.
For example, if $n = 10$, $k = 3$ and the array is $[1, 2, 1, 3, 2, 3, 2, 3, 1, 3]$, its cost is $2$ because, for example, we can choose the subarrays from the $2$-nd element to the $4$-th element and from the $7$-th element to the $9$-th element, and we can show that it's impossible to choose more than $2$ subarrays.
Calculate the sum of costs over all arrays of length $n$ consisting of integers from $1$ to $k$, and print it modulo $998244353$.
|
Let's try to solve another problem first: we are given an array and a value of $k$, we need to compute its cost. How can we do it? We can solve it greedily: find the leftmost subarray of length $k$ that contains all values from $1$ to $k$ and doesn't intersect with previously added subarrays, add it to the answer, rinse and repeat. How do we search for the subarray with $k$ distinct values? Let's go through the array from left to right and maintain the maximum number of last elements that are distinct, i. e. the longest suffix that consists of pairwise distinct elements. When this number of elements reaches $k$, we add $1$ to the cost of the array, and drop the number of pairwise distinct elements on suffix to $0$ (because we can't reuse them). When we meet an element that already belongs to the longest suffix we maintain, we need to shorten this suffix (it should start right after the last occurrence of that element). Okay. Now back to the original problem. Let's try to design a dynamic programming solution that will use the number of last distinct elements we can use as one of the states. For example, it could be something like this: $dp_{i,x,c}$ - how many arrays of length $i$ exist such that the number of elements on the suffix we can use is $x$, and the current cost of the array is $c$?; The transitions can be done as follows. When we transition from $dp_{i,x,c}$ to $dp_{i+1,x',c'}$, we need to consider two cases: the new element does not appear among the last $x$ elements. The number of ways to choose it is $(k-x)$, and we transition either to $dp_{i+1,x+1,c}$, or to $dp_{i+1,0,c+1}$ (the latter transition is used when $x = k - 1$, since we increase the cost by $1$ and cannot reuse the elements); the new element appears among the last $x$ elements. Let's iterate which of them is that element: let it be the $j$-th element from the back, then the current number of elements we can use becomes $j$, and we transition to $dp_{i+1,j,c}$. However, this is $O(n^2 \cdot k)$, since the number of states is $O(n^2)$ (the second state is up to $k$, the third state is up to $\frac{n}{k}$). Let's optimize it to $O(n^2)$. The transitions that actually make our solution slow are the transitions of the second type. Let's look at them in detail. From $dp_{i,x,c}$, there are transitions of the second type to every state $dp_{i+1,j,c}$ such that $j \le x$, and in every such transition, the new element is chosen uniquely (so they have the same coefficient equal to $1$). This means that we can compute all of those transitions efficiently using partial sums: the difference between the value of $dp_{i+1,j,c}$ and the value of $dp_{i+1,j+1,c}$ (if we don't consider the transitions of the first type) is just $dp_{i,j,c}$. So, all transitions of the second type can be handled in $O(n^2)$, and there are only $O(n^2)$ transitions of the first type. This is enough to solve the problem, but I want to add one final touch that allows to implement the solution much easier. We don't actually need the third state. We can use Contribution To The Sum technique: let's rewrite our dynamic programming without the third state, and every time we try to increase the second state to $k$, instead of increasing the third state, we calculate how many arrays have this subarray contributing to the cost. This is just the current value of dynamic programming, multiplied by the number of ways we can choose the remaining elements (which is $k^{n-i-1}$). That way, the implementation becomes much simpler, and the complexity of the solution is now $O(nk)$.
|
[
"combinatorics",
"dp",
"implementation",
"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 sub(int x, int y)
{
return add(x, -y);
}
int mul(int x, int y)
{
return (x * 1ll * y) % MOD;
}
int binpow(int x, int y)
{
int z = 1;
while(y > 0)
{
if(y & 1) z = mul(z, x);
x = mul(x, x);
y /= 2;
}
return z;
}
int main()
{
int n, k;
cin >> n >> k;
int ans = 0;
vector<vector<int>> dp(n + 1, vector<int>(k, 0));
dp[0][0] = 1;
for(int i = 0; i < n; i++)
{
int cur = 0;
for(int j = k - 1; j >= 1; j--)
{
cur = add(cur, dp[i][j]);
dp[i + 1][j] = cur;
}
for(int j = k - 1; j >= 0; j--)
{
int nxt = (j + 1) % k;
dp[i + 1][nxt] = add(dp[i + 1][nxt], mul(dp[i][j], k - j));
}
ans = add(ans, mul(dp[i + 1][0], binpow(k, n - (i + 1))));
}
cout << ans << endl;
}
|
1861
|
F
|
Four Suits
|
The game of Berland poker is played as follows. There are $n+1$ people: $n$ players, numbered from $1$ to $n$, and the dealer. The dealer has a deck which contains cards of four different suits (the number of cards of each suit \textbf{is not necessarily the same}); the number of cards in the deck is divisible by $n$. The dealer gives all cards to the players, so that \textbf{every player receives the same number of cards, and the whole deck is used}.
After the cards are dealt, every player chooses one of four suits (independently) and discards all cards from their hand which do not belong to their chosen suit. The winner of the game is the player with the maximum number of cards left in their hand. The number of points the winner receives is $x - y$, where $x$ is the number of cards in the winner's hand, and $y$ is the maximum number of cards among all \textbf{other} players; everyone else receives $0$ points. Note that it means that \textbf{if there are multiple players with the maximum number of cards}, everyone receives $0$ points.
Since every player wants to maximize their odds to win, \textbf{they will choose a suit with the maximum number of cards in their hand}.
Monocarp is the dealer. He has already given some cards to the players; the $i$-th player received $a_{i,j}$ cards of suit $j$. Note that \textbf{the number of cards in players' hands don't have to be the same at this moment}. Monocarp has $b_1, b_2, b_3, b_4$ cards of suit $1, 2, 3, 4$ respectively left in his deck. He has to give them to the players so that, after all cards are dealt, every player has the same number of cards.
For each player, calculate the maximum number of points they can receive among all ways to deal the remaining cards according to the rules of the game.
|
As far as I am concerned, fully greedy solutions don't work in this problem. However, we can try employing some greedy ideas. First of all, let's calculate how many cards each player should receive. I will call it $remain_i$ for the $i$-th player. Suppose we want to maximize the answer for the $i$-th player. Let's iterate on the suit $j$ for which that player will have the maximum number of cards. We can assign as many cards of suit $j$ as possible from the deck to the $i$-th player: suppose we have given a card of suit $j$ to another player, and a card of another suit to the $i$-th player. If we exchange them, the answer won't become worse. Okay, now we want to find the minimum possible maximum number of cards (after the players discard some of their cards) that the other players can have. Let's suppose it's $x$. There should be a way to assign the remaining cards from the deck so that every player $k$ gets exactly $remain_k$ cards, and no player has more than $x$ cards in any suit (except for the $i$-th player). The good thing is that if it's possible to assign cards for some value of $x$, it's also possible for $x+1$. So, we can find this $x$ with binary search. Now we have to solve the following problem: check if there exists an assignment of cards from the deck for a particular $x$. We can model it using maximum flow: create a network with a source, sink, a vertex for every player except for $i$, and a vertex for every suit; for every suit, create a directed edge from the source to that suit with capacity equal to the number of cards of that suit left in the deck (don't forget that we greedily assigned some cards to the $i$-th player!); for every player $k$ except $i = k$, create a directed edge from that player to the sink with capacity equal to $remain_k$; for every suit and every player except $i$, create a directed edge from the suit to the player with capacity equal to the maximum number of cards of that suit the player can receive; check that the maximum flow in this network saturates all edges going into the sink (i. e. is equal to the sum of $remain_k$ for all players except the $i$-th one). However, simply building this network is too slow, let alone finding the maximum flow in it. We need something faster. If you're thinking about using Hall's theorem, then unfortunately, it doesn't work since it cannot handle the constraint on $x$. But you're thinking in the right direction. Let's try to find the minimum cut in this network. To do this, iterate on the $mask$ of the suits that will be in the set $S$ in the minimum cut, add the capacities of other suits to the value of the cut, and for every player, determine if it's better to have them in the set $S$ or in the set $T$ of the cut. The key thing is that if we fix the mask of suits and the value of $x$, it is uniquely determined. Let the number of suits in the mask be $suits$, and the total number of cards the $k$-th player has from those suits be $alreadyHas_{mask,k}$. The total capacity of all edges going into the $k$-th player that we need to cut is $suits \cdot x - alreadyHas_{mask,k}$, and the capacity of the outgoing edge is $remain_k$. So, the value the $k$-th player adds to the cut is $\min(remain_k, suits \cdot x - alreadyHas_{mask,k})$, and we need to compute the sum of these values for all players (except for the player $i$) efficiently. This is basically the outline of the solution. Now the implementation part follows. To be honest, I think that the model solution is a bit too complicated, some solutions I've seen during the contest are shorter and cleaner. But I will explain it nevertheless. For every $mask$ and every value of $x$, let's try to find the sum of $\min(suits \cdot x - alreadyHas_{mask,k}, remain_k)$ over all players. To do this, for every player, find the maximum value of $x$ such that $suits \cdot x - alreadyHas_{mask,k}$ is less than $remain_k$. For the value of $x$ not greater than this value, the player adds $suits \cdot x - alreadyHas_{mask,k}$ to the cut; for greater values, the player adds $remain_k$. Both of those are linear functions, and for every $x$, we can compute the sum of those linear functions for all players using difference arrays. I calculate these sums of linear functions in all values of $x$ up to $2 \cdot 10^6$, because there might be situations when a player has more than $10^6$ cards of a particular suit. That way, when we want to compute the minimum cut for the $i$-th player, chosen mask of suits and the value of $x$, we can use the already computed sum of those functions to find the total value all players add to the cut, and then subtract the value that the $i$-th player added (since we need to discard that player from the network). The rest of the implementation is fairly straightforward, you can see the reference code for details (I hope I commented it well enough). One final note: when choosing the left border for binary search, I compute the maximum number of cards among all suits that the other players have, to make sure that I don't choose the value of $x$ that leads to edges having negative capacity in the network. But I think it's not actually required, so you can try discarding it from the solution. The model implementation works in something like $O(2^K \cdot (n \cdot K + A))$ for precalculation of linear functions plus $O(n \cdot 2^K \cdot K^2 \cdot \log A)$ for actually solving the problem, where $A$ is the maximum number of cards of a particular suit a player can have ($A \le 2 \cdot 10^6$).
|
[
"binary search",
"bitmasks",
"flows",
"greedy"
] | 3,200
|
#include<bits/stdc++.h>
using namespace std;
const int K = 4;
const int N = 2 * int(1e6) + 43;
pair<long long, long long> operator+(const pair<long long, long long>& a, const pair<long long, long long>& b)
{
return make_pair(a.first + b.first, a.second + b.second);
}
pair<long long, long long> operator-(const pair<long long, long long>& a, const pair<long long, long long>& b)
{
return make_pair(a.first - b.first, a.second - b.second);
}
// prefix sums for an array of pairs
vector<pair<long long, long long>> pref_sums(const vector<pair<long long, long long>>& a)
{
int n = a.size();
vector<pair<long long, long long>> ans(n);
ans[0] = a[0];
for(int i = 1; i < n; i++)
ans[i] = ans[i - 1] + a[i];
return ans;
}
// for an array of pairs denoting linear functions, evaluate
// them in the corresponding points
vector<long long> eval(const vector<pair<long long, long long>>& a)
{
int n = a.size();
vector<long long> ans(n);
for(int i = 0; i < n; i++)
ans[i] = a[i].first * i + a[i].second;
return ans;
}
void solve()
{
int n;
scanf("%d", &n);
vector<vector<int>> a(n, vector<int>(K));
for(int i = 0; i < n; i++)
for(int j = 0; j < K; j++)
scanf("%d", &a[i][j]);
vector<int> b(K);
for(int i = 0; i < K; i++)
scanf("%d", &b[i]);
int deck_size = 0;
for(int i = 0; i < K; i++)
deck_size += b[i];
// calculate the remaining number of cards for each player
long long full = deck_size;
for(int i = 0; i < n; i++)
for(int j = 0; j < K; j++)
full += a[i][j];
vector<int> remain(n, full / n);
for(int i = 0; i < n; i++)
for(int j = 0; j < K; j++)
remain[i] -= a[i][j];
// for every player, calculate the maximum number of cards
// they already have among all suits
// and store it in a multiset
vector<int> min_val(n);
for(int i = 0; i < n; i++)
min_val[i] = *max_element(a[i].begin(), a[i].end());
multiset<int> min_vals;
for(int i = 0; i < n; i++)
min_vals.insert(min_val[i]);
// for every mask of suits and every player, calculate
// the number of cards in those suits they already have
vector<vector<int>> already_has(1 << K, vector<int>(n));
for(int mask = 0; mask < (1 << K); mask++)
for(int i = 0; i < n; i++)
for(int j = 0; j < K; j++)
if(mask & (1 << j))
already_has[mask][i] += a[i][j];
// for every mask of suits and every player, calculate the
// maximum value of x such that if that player can receive
// no more than x cards in each suit, the vertex of that
// player should belong to T in the cut
vector<vector<int>> max_x(1 << K, vector<int>(n));
for(int mask = 0; mask < (1 << K); mask++)
for(int i = 0; i < n; i++)
{
int suits = __builtin_popcount(mask);
if (suits == 0) max_x[mask][i] = N - 2;
else
{
// incoming edges have capacity of
// x - a[i][j]
int incoming = -already_has[mask][i];
// outgoing edge has capacity of remain[i]
// find the maximum x such that
// suits * x + incoming < remains[i]
int x = (remain[i] - incoming) / suits;
x = min(x, N - 2);
max_x[mask][i] = x;
}
}
// for every mask and for all players, calculate the sum of
// values they add to the cut if they can have no more than
// x cards of each suit in the mask
vector<vector<long long>> add_to_cut(1 << K, vector<long long>(N));
for(int mask = 0; mask < (1 << K); mask++)
{
int suits = __builtin_popcount(mask);
vector<pair<long long, long long>> aux(N);
for(int i = 0; i < n; i++)
{
// for the i-th player, they add remains[i] to
// the minimum cut if x > max_x[mask][i]
// otherwise, they add
// suits * x - already_has[mask][i]
int incoming = -already_has[mask][i];
// add [suits * x - incoming] on segment [0, max_x]
int x = max_x[mask][i];
pair<long long, long long> f1 = {suits, incoming};
aux[0] = aux[0] + f1;
aux[x + 1] = aux[x + 1] - f1;
// add remain[i] on [max_x + 1, N)
pair<long long, long long> f2 = {0, remain[i]};
aux[x + 1] = aux[x + 1] + f2;
aux[N - 1] = aux[N - 1] - f2;
}
// sum up those functions and evaluate them
add_to_cut[mask] = eval(pref_sums(aux));
}
// now we're ready to solve the problem!
vector<int> ans(n);
// iterate on the player we want to maximize
for(int i = 0; i < n; i++)
{
// iterate on the suits they will maximize
for(int j = 0; j < K; j++)
{
int d = min(remain[i], b[j]);
int max_cards = a[i][j] + d;
b[j] -= d;
// find the maximum current score over all others
min_vals.erase(min_vals.find(min_val[i]));
int max_rival = *min_vals.rbegin();
min_vals.insert(min_val[i]);
if(max_rival >= max_cards)
ans[i] = max(ans[i], 0);
else
{
// binary search on the maximum cards over all
// opponents
int L = max_rival - 1;
int R = max_cards;
while(R - L > 1)
{
int mid = (L + R) / 2;
long long min_cut = 1e18;
long long req_flow = deck_size - remain[i];
// iterate on the mask of suit vertices
// which belong to S
for(int mask = 0; mask < (1 << K); mask++)
{
int suits = __builtin_popcount(mask);
long long cur_cut = 0;
for(int z = 0; z < K; z++)
if(!(mask & (1 << z)))
cur_cut += b[z];
cur_cut += add_to_cut[mask][mid];
// don't forget to discard our player
// from the flow network!
if(mid > max_x[mask][i])
cur_cut -= remain[i];
else
{
long long add = mid * suits - already_has[mask][i];
cur_cut -= add;
}
min_cut = min(min_cut, cur_cut);
}
if(min_cut < req_flow)
L = mid;
else
R = mid;
}
ans[i] = max(ans[i], max_cards - R);
}
b[j] += d;
}
}
for(int i = 0; i < n; i++)
printf("%d ", ans[i]);
puts("");
}
int main()
{
int t = 1;
for(int i = 0; i < t; i++) solve();
}
|
1862
|
A
|
Gift Carpet
|
Recently, Tema and Vika celebrated Family Day. Their friend Arina gave them a carpet, which can be represented as an $n \cdot m$ table of lowercase Latin letters.
Vika hasn't seen the gift yet, but Tema knows what kind of carpets she likes. Vika will like the carpet if she can read her name on. She reads column by column from left to right and chooses one or zero letters from current column.
Formally, the girl will like the carpet if it is possible to select four distinct columns in order from left to right such that the first column contains "v", the second one contains "i", the third one contains "k", and the fourth one contains "a".
Help Tema understand in advance whether Vika will like Arina's gift.
|
Note that if the answer is <<YES>>, then there exists a reading of the word <<vika>> in which the leftmost letter <<v>> is included. Among such readings, we can also consider the one in which the leftmost letter <<i>> is included, which is located to the right of the first occurrence of <<v>>. Similarly, we can do the same for the remaining letters. Therefore, it is sufficient to greedily search for the characters in order. Let's store the input data in a 2D array and process it by going through the columns from left to right. First, we will search for the character <<v>> by iterating through all the characters in each processed column. Once we find the character <<v>>, we will similarly search for the character <<i>> and so on.
|
[
"dp",
"greedy",
"implementation",
"strings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main() {
int q;
cin >> q;
while (q--) {
int n, m;
cin >> n >> m;
vector<string> carpet(n);
for (int i = 0; i < n; ++i) {
cin >> carpet[i];
}
string vika = "vika";
int fnd = 0;
for (int i = 0; i < m; ++i) {
bool check = false;
for (int j = 0; j < n; ++j) {
if (carpet[j][i] == vika[fnd]) {
check = true;
}
}
if (check) {
++fnd;
if (fnd == 4) {
break;
}
}
}
if (fnd == 4) {
cout << "YES\n";
} else {
cout << "NO\n";
}
}
return 0;
}
|
1862
|
B
|
Sequence Game
|
Tema and Vika are playing the following game.
First, Vika comes up with a sequence of positive integers $a$ of length $m$ and writes it down on a piece of paper. Then she takes a new piece of paper and writes down the sequence $b$ according to the following rule:
- First, she writes down $a_1$.
- Then, she writes down only those $a_i$ ($2 \le i \le m$) such that $a_{i - 1} \le a_i$. Let the length of this sequence be denoted as $n$.
For example, from the sequence $a=[4, 3, 2, 6, 3, 3]$, Vika will obtain the sequence $b=[4, 6, 3]$.
She then gives the piece of paper with the sequence $b$ to Tema. He, in turn, tries to guess the sequence $a$.
Tema considers winning in such a game highly unlikely, but still wants to find at least one sequence $a$ that could have been originally chosen by Vika. Help him and output any such sequence.
\textbf{Note that the length of the sequence you output should not exceed the input sequence length by more than two times.}
|
Let's compare each pair of adjacent numbers. If the left number is smaller than the right number, then the right number is at least $2$. We will insert $1$ between them. Now, for each pair of numbers, it is true that either these two numbers were originally in the sequence, or one of them is $1$. In this case, if two numbers were originally in the sequence, then the left number is not smaller than the right number. If the left number is $1$, then it is smaller than the right number, since the right number was at least $2$. If the right number is $1$, then the left number in the pair is not smaller than the right number. We have checked all cases. It is evident that such a sequence is valid, as Vika would have only removed all the $1$ we added and nothing more.
|
[
"constructive algorithms"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main() {
int q;
cin >> q;
while (q--) {
int n;
cin >> n;
vector<int> a;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (i && a.back() > x) {
a.push_back(1);
}
a.push_back(x);
}
cout << a.size() << "\n";
for (int el : a)
cout << el << " ";
cout << "\n";
}
return 0;
}
|
1862
|
C
|
Flower City Fence
|
Anya lives in the Flower City. By order of the city mayor, she has to build a fence for herself.
The fence consists of $n$ planks, each with a height of $a_i$ meters. According to the order, the heights of the planks must \textbf{not increase}. In other words, it is true that $a_i \ge a_j$ for all $i < j$.
Anya became curious whether her fence is symmetrical with respect to the diagonal. In other words, will she get the same fence if she lays all the planks horizontally in the same order.
For example, for $n = 5$, $a = [5, 4, 3, 2, 1]$, the fence is symmetrical. Because if all the planks are laid horizontally, the fence will be $[5, 4, 3, 2, 1]$, as shown in the diagram.
\begin{center}
{\small On the left is the fence $[5, 4, 3, 2, 1]$, on the right is the same fence laid horizontally}
\end{center}
But for $n = 3$, $a = [4, 2, 1]$, the fence is not symmetrical. Because if all the planks are laid horizontally, the fence will be $[3, 2, 1, 1]$, as shown in the diagram.
\begin{center}
{\small On the left is the fence $[4, 2, 1]$, on the right is the same fence laid horizontally}
\end{center}
Help Anya and determine whether her fence is symmetrical.
|
Obviously, if $a_1 \neq n$, then this fence is not symmetric, because the fence $a$ has a length of $n$, while the horizontally laid fence has a length of $a_1 \neq n$. Now let's build a fence $b$ using horizontal boards that would match the original fence $a$. And let's check if the arrays $a$ and $b$ are equal. If they are equal, then the fence is symmetric; otherwise, it is not. There won't be any memory issues since all $a_i \le n$, which means the length of array $b$ does not exceed $n$.
|
[
"binary search",
"data structures",
"implementation",
"sortings"
] | 1,100
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
if (a[1] != n) {
cout << "NO" << '\n';
continue;
}
vector<int> b;
for (int i = n; i >= 1; i--) {
while (b.size() < a[i]) {
b.push_back(i);
}
}
bool meow = true;
for (int i = 1; i <= n; i++) {
if (a[i] != b[i - 1]) {
cout << "NO" << '\n';
meow = false;
break;
}
}
if (meow) {
cout << "YES" << '\n';
}
}
return 0;
}
|
1862
|
D
|
Ice Cream Balls
|
Tema decided to improve his ice cream making skills. He has already learned how to make ice cream in a cone \textbf{using exactly two} balls.
Before his ice cream obsession, Tema was interested in mathematics. Therefore, he is curious about the \textbf{minimum} number of balls he needs to have in order to make \textbf{exactly} $n$ \textbf{different} types of ice cream.
There are plenty possible ice cream flavours: $1, 2, 3, \dots$. Tema can make two-balls ice cream with any flavours (probably the same).
Two ice creams are considered different if their sets of ball flavours are different. For example, $\{1, 2\} = \{2, 1\}$, but $\{1, 1\} \neq \{1, 2\}$.
For example, having the following ice cream balls: $\{1, 1, 2\}$, Tema can make only two types of ice cream: $\{1, 1\}$ and $\{1, 2\}$.
\textbf{Note, that Tema do not need to make all the ice cream cones at the same time. This means that he making ice cream cones independently. Also in order to make a following cone $\{x, x\}$ for some $x$, Tema needs at least $2$ balls of type $x$}.
Help Tema answer this question. It can be shown that answer always exist.
|
First, let's note that having more than two balls of the same type is meaningless. Let's denote $x$ as the number of flavours of balls represented by two instances of each ball. Let $y$ denote the number of flavours represented by a single instance. Let's calculate the number of different ways to make an ice cream from these balls: we can make $x$ ice creams from balls of the same flavour and $\dfrac{(x + y) \cdot (x + y - 1)}{2}$ ice creams from balls of different flavours. In the problem, we are asked to select balls in such a way that $x + \dfrac{(x + y) \cdot (x + y - 1)}{2} = n$. Note that for a fixed sum of $x + y$, we can uniquely determine $x$ and therefore $y$ (or determine that there is no solution for that sum). Let's assume we have found an answer with a minimum sum of $x + y = k$. This means $\dfrac{k \cdot (k - 1)}{2} \leq n \leq \dfrac{k \cdot (k - 1)}{2} + k$. Moreover, if we find an answer with a sum of $x + y = k + 1$, then $k + \dfrac{k \cdot (k - 1)}{2} \leq n \leq k + \dfrac{k \cdot (k - 1)}{2} + k + 1$. From this, we can see that this is only possible when $n = k + \dfrac{k \cdot (k - 1)}{2}$. It is also evident that there are no answers with a sum greater than $k + 2$. Now, all we need to do is perform a binary search on the sum of $x + y$ and then determine $x$ and $y$. And don't forget to consider the case when two sums of $x + y$ may be suitable, in order to choose the one with the fewest number of balls.
|
[
"binary search",
"combinatorics",
"constructive algorithms",
"math"
] | 1,300
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main() {
int q;
cin >> q;
while (q--) {
int n;
cin >> n;
int l = 0, r = min<int>(2e9, 2 * n);
while (r - l > 1) {
int m = (l + r) >> 1;
// m = x + y, answer = x + 2 * y
if (m * (m - 1) / 2 + m < n) {
l = m;
} else {
r = m;
}
}
int y = n - r * (r - 1) / 2;
if ((r + 1) * r / 2 <= n) {
cout << min(r + y, r + 1 + n - (r + 1) * r / 2) << "\n";
} else {
cout << r + y << "\n";
}
}
return 0;
}
|
1862
|
E
|
Kolya and Movie Theatre
|
Recently, Kolya found out that a new movie theatre is going to be opened in his city soon, which will show a new movie every day for $n$ days. So, on the day with the number $1 \le i \le n$, the movie theatre will show the premiere of the $i$-th movie. Also, Kolya found out the schedule of the movies and assigned the entertainment value to each movie, denoted by $a_i$.
However, the longer Kolya stays without visiting a movie theatre, the larger the decrease in entertainment value of the next movie. That decrease is equivalent to $d \cdot cnt$, where $d$ is a predetermined value and $cnt$ is the number of days since the last visit to the movie theatre. It is also known that Kolya managed to visit another movie theatre a day before the new one opened — the day with the number $0$. \textbf{So if we visit the movie theatre the first time on the day with the number $i$, then $cnt$ — the number of days since the last visit to the movie theatre will be equal to $i$}.
For example, if $d = 2$ and $a = [3, 2, 5, 4, 6]$, then by visiting movies with indices $1$ and $3$, $cnt$ value for the day $1$ will be equal to $1 - 0 = 1$ and $cnt$ value for the day $3$ will be $3 - 1 = 2$, so the total entertainment value of the movies will be $a_1 - d \cdot 1 + a_3 - d \cdot 2 = 3 - 2 \cdot 1 + 5 - 2 \cdot 2 = 2$.
Unfortunately, Kolya only has time to visit \textbf{at most $m$ movies}. Help him create a plan to visit the cinema in such a way that the total entertainment value of all the movies he visits is maximized.
|
Let's notice that if we visit the cinema on days with numbers $i_1, i_2, \ldots, i_k$, the total entertainment value of the visited movies will be equal to $(a_{i_1} - d \cdot i_1) + (a_{i_2} - d \cdot (i_2 - i_1)) + \ldots + (a_{i_k} - d \cdot (i_k - i_{k-1})) = (a_{i_1} + a_{i_2} + \ldots + a_{i_k}) - d \cdot i_k$. Thus, it is sufficient to iterate over the day when Kolya will visit the cinema for the last time - $i_k$, and maintain the maximum $m - 1$ non-negative elements on the prefix $[1, i_k - 1]$. This can be done, for example, using std::multiset. The total complexity of the solution will be $O(n \log{n})$.
|
[
"constructive algorithms",
"data structures",
"greedy"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main() {
int t;
cin >> t;
for (int _ = 0; _ < t; ++_) {
int n, m, d;
cin >> n >> m >> d;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int ans = 0;
set<pair<int, int>> s;
int sum = 0;
for (int i = 0; i < n; ++i) {
int cur = sum + a[i] - d * (i + 1);
ans = max(ans, cur);
if (a[i] > 0) {
s.insert({a[i], i});
sum += a[i];
if (s.size() >= m) {
sum -= (s.begin()->first);
s.erase(s.begin());
}
}
}
cout << ans << endl;
}
return 0;
}
|
1862
|
F
|
Magic Will Save the World
|
A portal of dark forces has opened at the border of worlds, and now the whole world is under a terrible threat. To close the portal and save the world, you need to defeat $n$ monsters that emerge from the portal one after another.
Only the sorceress Vika can handle this. She possesses two magical powers — water magic and fire magic. In one second, Vika can generate $w$ units of water mana and $f$ units of fire mana. She will need mana to cast spells. Initially Vika have $0$ units of water mana and $0$ units of fire mana.
Each of the $n$ monsters that emerge from the portal has its own strength, expressed as a positive integer. To defeat the $i$-th monster with strength $s_i$, Vika needs to cast a water spell or a fire spell of at least the same strength. In other words, Vika can spend at least $s_i$ units of water mana on a water spell, or at least $s_i$ units of fire mana on a fire spell.
Vika can create and cast spells instantly. Vika can cast an unlimited number of spells every second as long she has enough mana for that.
The sorceress wants to save the world as quickly as possible, so tell her how much time she will need.
|
First, let's note that Vika can defeat all the monsters at once, in the last second. There is no point in spending mana gradually. Now, let's say we know how many seconds Vika will accumulate mana before spending it. Then we also know how much mana she will have accumulated by that time. How should she spend it? Note that the total strength of the monsters is given to us. Therefore, it is enough for us to spend as much of the available water mana as possible, so that there is enough fire mana left for the remaining monsters. This is a well-known knapsack problem. Finally, let's note that we don't need to iterate over the number of seconds and build the knapsack each time. It is enough to build it initially, and then iterate over how much water mana we will spend and whether we will have enough fire mana left for the rest.
|
[
"binary search",
"bitmasks",
"brute force",
"dp"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main() {
int q;
cin >> q;
while (q--) {
int w, f, n;
cin >> w >> f >> n;
vector<int> s(n);
int sum_s = 0;
for (int i = 0; i < n; ++i) {
cin >> s[i];
sum_s += s[i];
}
vector<bool> dp(sum_s + 1);
dp[0] = true;
for (int i = 0; i < n; ++i) {
for (int w = sum_s; w - s[i] >= 0; --w) {
dp[w] = dp[w] || dp[w - s[i]];
}
}
int ans = 2e9;
for (int i = 0; i <= sum_s; ++i) {
if (dp[i]) {
ans = min(ans, max((i + w - 1) / w, (sum_s - i + f - 1) / f));
}
}
cout << ans << "\n";
}
return 0;
}
|
1862
|
G
|
The Great Equalizer
|
Tema bought an old device with a small screen and a worn-out inscription "The Great Equalizer" on the side.
The seller said that the device needs to be given an array $a$ of integers as input, after which "The Great Equalizer" will work as follows:
- Sort the current array in non-decreasing order and remove duplicate elements leaving only one occurrence of each element.
- If the current length of the array is equal to $1$, the device stops working and outputs the single number in the array — output value of the device.
- Add an arithmetic progression {$n,\ n - 1,\ n - 2,\ \ldots,\ 1$} to the current array, where $n$ is the length of the current array. In other words, $n - i$ is added to the $i$-th element of the array, when indexed from zero.
- Go to the first step.
To test the operation of the device, Tema came up with a certain array of integers $a$, and then wanted to perform $q$ operations on the array $a$ of the following type:
- Assign the value $x$ ($1 \le x \le 10^9$) to the element $a_i$ ($1 \le i \le n$).
- Give the array $a$ as input to the device and find out the result of the device's operation, \textbf{while the array $a$ remains unchanged during the operation of the device}.
Help Tema find out the output values of the device after each operation.
|
Let's take a look at the maximum difference between adjacent numbers in a sorted sequence. Each cycle it decreases by $1$. This helps us understand the main observation: the answer for the sequence is the maximum number in it + the maximum difference between adjacent numbers in sorted order. To answer queries, it is sufficient to maintain these two values. To maintain the maximum number, we will store the numbers in std::multiset. And to maintain the maximum difference, we will maintain std::multiset of differences. When replacing a number, we will remove the old number and replace the difference between it and its neighbors with the difference between the neighbors. Then we will add the new number and replace the difference between its neighbors with the difference between the added number and each of the neighbors. All of this is implemented through working with std::multiset, which you can see, for example, in the author's solution.
|
[
"binary search",
"data structures",
"math",
"sortings"
] | 2,000
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
scanf("%d", &n);
vector<int> a(n);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
if (n == 1) {
int q;
scanf("%d", &q);
while (q--) {
int pos, val;
scanf("%d %d", &pos, &val);
cout << val << " ";
}
cout << "\n";
continue;
}
multiset<int> aset;
for (int i = 0; i < n; ++i) {
aset.insert(a[i]);
}
multiset<int> deltas;
for (auto it = ++aset.begin(); it != aset.end(); ++it) {
auto prev = it;
--prev;
deltas.insert(*it - *prev);
}
int q;
scanf("%d", &q);
while (q--) {
int pos, val;
scanf("%d %d", &pos, &val);
auto it = aset.find(a[pos - 1]);
auto nxt = it, prev = it;
++nxt; --prev;
if (it == aset.begin()) {
deltas.erase(deltas.find(*nxt - *it));
} else if (it == --aset.end()) {
deltas.erase(deltas.find(*it - *prev));
} else {
deltas.erase(deltas.find(*nxt - *it));
deltas.erase(deltas.find(*it - *prev));
deltas.insert(*nxt - *prev);
}
aset.erase(it);
aset.insert(val);
it = aset.find(val);
nxt = it, prev = it;
++nxt; --prev;
if (it == aset.begin()) {
deltas.insert(*nxt - *it);
} else if (it == --aset.end()) {
deltas.insert(*it - *prev);
} else {
deltas.insert(*nxt - *it);
deltas.insert(*it - *prev);
deltas.erase(deltas.find(*nxt - *prev));
}
a[pos - 1] = val;
cout << *--aset.end() + *--deltas.end() << " ";
}
cout << "\n";
}
return 0;
}
|
1863
|
A
|
Channel
|
Petya is an administrator of a channel in one of the messengers. A total of $n$ people are subscribed to his channel, and Petya is not considered a subscriber.
Petya has published a new post on the channel. At the moment of the publication, there were $a$ subscribers online. We assume that every subscriber always reads all posts in the channel if they are online.
After this, Petya starts monitoring the number of subscribers online. He consecutively receives $q$ notifications of the form "a subscriber went offline" or "a subscriber went online". Petya does not know which exact subscriber goes online or offline. It is guaranteed that such a sequence of notifications could have indeed been received.
Petya wonders if all of his subscribers have read the new post. Help him by determining one of the following:
- it is impossible that all $n$ subscribers have read the post;
- it is possible that all $n$ subscribers have read the post;
- it is guaranteed that all $n$ subscribers have read the post.
|
Let $p$ be the total number of + signs in the notification string. If $a + p < n$, then the answer is clearly "NO". Now let's look at the current number of users online. Initially there are $a$ of them. Each notification either increases this number by $1$, or decreases it by $1$. If at some moment of time the number of users online is $n$, then all users are online, thus, everyone must have read the post. The answer is "YES" in this case. Otherwise the answer is "MAYBE". Indeed, suppose that the number of users online never hits $n$, but $a + p \ge n$. On the one hand, if the first $(n - a)$ notifications of the + type correspond to new users, then all subscribers will have read the post. On the other hand, a situation when the $n$-th user never log in is also possible.
|
[
"greedy",
"implementation"
] | 800
| null |
1863
|
B
|
Split Sort
|
You are given a permutation$^{\dagger}$ $p_1, p_2, \ldots, p_n$ of integers $1$ to $n$.
You can change the current permutation by applying the following operation several (possibly, zero) times:
- choose some $x$ ($2 \le x \le n$);
- create a new permutation by:
- first, writing down all elements of $p$ that are less than $x$, without changing their order;
- second, writing down all elements of $p$ that are greater than or equal to $x$, without changing their order;
- replace $p$ with the newly created permutation.
For example, if the permutation used to be $[6, 4, 3, 5, 2, 1]$ and you choose $x = 4$, then you will first write down $[3, 2, 1]$, then append this with $[6, 4, 5]$. So the initial permutation will be replaced by $[3, 2, 1, 6, 4, 5]$.
Find the minimum number of operations you need to achieve $p_i = i$ for $i = 1, 2, \ldots, n$. We can show that it is always possible to do so.
$^{\dagger}$ 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).
|
For every $k$ such that $a_i = k$, $a_j = k + 1$ and $i > j$ we have to choose $x = k + 1$ at least once for these elements to be in the correct order. It is easy to see that if we choose all such $x = k + 1$ for all such $k$ exactly once in any order, we will get the identity permutation.
|
[
"greedy",
"math",
"sortings"
] | 1,100
| null |
1863
|
C
|
MEX Repetition
|
You are given an array $a_1,a_2,\ldots, a_n$ of \textbf{pairwise distinct} integers from $0$ to $n$. Consider the following operation:
- consecutively for each $i$ from $1$ to $n$ in this order, replace $a_i$ with $\operatorname{MEX}(a_1, a_2, \ldots, a_n)$.
Here $\operatorname{MEX}$ of a collection of integers $c_1, c_2, \ldots, c_m$ is defined as the smallest non-negative integer $x$ which does not occur in the collection $c$. For example, $\operatorname{MEX}(0, 2, 2, 1, 4) = 3$ and $\operatorname{MEX}(1, 2) = 0$.
Print the array after applying $k$ such operations.
|
Append the initial array $a_1, \ldots, a_n$ with $a_{n+1} = \operatorname{MEX}(a_1, \ldots, a_n)$. It is easy to see that $a_1, \ldots, a_{n+1}$ is a permutation of $0, 1, \ldots, n$. In this case setting $a_i = \operatorname{MEX}(a_1, \ldots, a_n)$ is basically equivalent $a_i = a_{n+1}$, but after this the new $\operatorname{MEX}(a_1, \ldots, a_n)$ is changed. In fact, it becomes equal to the old value of $a_i$, since this value is not now present in the array. In other words, performing the operation on $a_i$ is equivalent to swapping $a_i$ and $a_{n+1}$. Performing the operation on $i = 1, 2, \ldots, n$ can be viewed as $n$ swaps. It means that the array changes from $[a_1, a_2, \ldots, a_{n+1}]$ to $[a_{n+1}, a_1, a_2, \ldots, a_n]$, i. e. we simply perform the cyclic shift to the right. To finish up the solution, first, calculate $a_{n+1} = \operatorname{MEX}(a_1, \ldots, a_n)$ (you can do so, for example, by setting $a_{n+1} = \frac{n(n+1)}{2} - \sum\limits_{i=1}^{n} a_i$). Second, calculate $k \% (n+1)$ and then perform the cyclic shift in $O(n)$.
|
[
"implementation",
"math"
] | 1,100
| null |
1863
|
D
|
Two-Colored Dominoes
|
There is an $n\times m$ board divided into cells. There are also some dominoes on this board. Each domino covers two adjacent cells (that is, two cells that share a side), and no two dominoes overlap.
Piet thinks that this board is too boring and it needs to be painted. He will paint the cells of the dominoes black and white. He calls the painting beautiful if all of the following conditions hold:
- for each domino, one of its cells is painted white and the other is painted black;
- for each row, the number of black cells in this row equals the number of white cells in this row;
- for each column, the number of black cells in this column equals the number of white cells in this column.
Note that the cells that are not covered by dominoes are not painted at all, they are counted as neither black nor white.
Help Piet produce a beautiful painting or tell that it is impossible.
|
Let's consider the requirement on the rows. Clearly, all horizontal dominoes (since each of them has $1$ black and $1$ white cell) do not influence the black-white balance for the rows. Thus, we are only interested in vertical dominoes. Consider the first row and the vertical dominoes that intersect this row. Their number has to be even, otherwise, the first row has an odd number of cells covered by dominoes and the solution is clearly impossible. But if there is an even number of such dominoes, we have to paint half of them black-white, and half of them white-black. What's more, it doesn't actually matter the exact order we paint them in, because vertical dominoes do not affect the columns' balance and we will not influence the balance of the second row anyway. So we can freely paint them however we like. The same logic applies for rows $2, \ldots, n$. Now we turn to horizontal dominoes. In the first row, there once again has to be an even number of dominoes which intersect this column. And we can paint half them black-white, and half of them white-black, and it doesn't matter which exact way we choose. Do the same for columns $2, \ldots, m$.
|
[
"constructive algorithms",
"greedy"
] | 1,400
| null |
1863
|
E
|
Speedrun
|
You are playing a video game. The game has $n$ quests that need to be completed. However, the $j$-th quest can only be completed at the beginning of hour $h_j$ of a game day. The game day is $k$ hours long. The hours of each game day are numbered $0, 1, \ldots, k - 1$. After the first day ends, a new one starts, and so on.
Also, there are dependencies between the quests, that is, for some pairs $(a_i, b_i)$ the $b_i$-th quest can only be completed after the $a_i$-th quest. It is guaranteed that there are \textbf{no circular dependencies}, as otherwise the game would be unbeatable and nobody would play it.
You are skilled enough to complete any number of quests in a negligible amount of time (i. e. you can complete any number of quests at the beginning of the same hour, even if there are dependencies between them). You want to complete all quests as fast as possible. To do this, you can complete the quests in any valid order. The completion time is equal to the difference between the time of completing the last quest and the time of completing the first quest in this order.
Find the least amount of time you need to complete the game.
|
First of all, assume that the first quest we complete is at the hour $x$. We can assume that $0\leq x < k$, as increasing it by $k$ just shifts all the times by $k$. In this case one can greedily find the completion times for all the quests: essentially, for every quest $v$, if we know that the quests it depends on are completed at hours $c_1$, ..., $c_d$, then the quest $v$ cannot be completed earlier than $\max(c_1, \ldots, c_d)$. So if we define $f(x, y)$ to be the smallest $z\geq x$ such that $z\equiv y\pmod{k}$, then the completion time of $v$ is $f(\max(c_1, \ldots, c_d), h_v)$. If the quest $v$ does not depend on anything, then, obviously, the time if simply $f(x, h_v)$. The problem is that we don't know which starting time $x$ is optimal. On the other hand, we know that it can be assumed to be from $[0, k)$. Also, there is no sense in $x$ not being $h_v$ for any quest $v$ without incoming dependencies. So we can do the following: first assume that $x = 0$ and find all the completion times for the quests, denote them by $c_i$. Then consequently increase $x$ until it becomes $k$. Sometimes $x$ becomes equal to some $h_v$ where $v$ is a quest that could theoretically be completed first. At these moments we know that the answer is no more than $\max c_i - x$. When we increase $x$ again, such quests can no longer have $c_i = x$, and thus some values $c_i$ increase by some multiple of $k$. However, for $x = k$ all $c_i$ are exactly $k$ more than when $x = 0$. Therefore, each value of $c_i$ in this process increases exactly once and exactly by $k$. Now there are two ways to finish the solution. Sort all events of type "some $c_i$, where quest $i$ doesn't have incoming dependencies, increase by $k$". For each such event, we run DFS from such vertices to see if some the quests depending on them must also be completed $k$ hours later. One can see that this DFS will be run from each vertex exactly once throughout the process, thus resulting in $O(n + m)$ time complexity. When building all $c_i$ the first time, also find for each vertex $v$ the first $x$ when its $c_v$ must change. If we denote it with $w_v$ then it can be expressed as $\max\{w_u\,\colon\,u\to v, c_u + k > c_v\}$. Then sort all events of type "some $c_i$, where quest $i$ may or may not have incoming dependencies, increase by $k$". In both approaches one can easily maintain $\max c_i$ as this value can only increase.
|
[
"brute force",
"dfs and similar",
"dp",
"graphs",
"greedy",
"math",
"sortings",
"two pointers"
] | 2,100
| null |
1863
|
F
|
Divide, XOR, and Conquer
|
You are given an array of $n$ integers $a_1, a_2, \ldots, a_n$.
In one operation you split the array into two parts: a non-empty prefix and a non-empty suffix. The value of each part is the bitwise XOR of all elements in it. Next, discard the part with the smaller value. If both parts have equal values, you can choose which one to discard. Replace the array with the remaining part.
The operations are being performed until the length of the array becomes $1$. For each $i$ ($1 \le i \le n$), determine whether it is possible to achieve the state when only the $i$-th element (with respect to the original numbering) remains.
Formally, you have two numbers $l$ and $r$, initially $l = 1$ and $r = n$. The current state of the array is $[a_l, a_{l+1}, \ldots, a_r]$.
As long as $l < r$, you apply the following operation:
- Choose an arbitrary $k$ from the set $\{l, l + 1, \ldots, r - 1\}$. Denote $x = a_l \oplus a_{l + 1} \oplus \ldots \oplus a_k$ and $y = a_{k + 1} \oplus a_{k + 2} \oplus \ldots \oplus a_{r}$, where $\oplus$ denotes the bitwise XOR operation.
- If $x < y$, set $l = k + 1$.
- If $x > y$, set $r = k$.
- If $x = y$, either set $l = k + 1$, or set $r = k$.
For each $i$ ($1 \le i \le n$), determine whether it is possible to achieve $l = r = i$.
|
Let $s = a_l \oplus a_{l + 1} \oplus \ldots \oplus a_r$, $x = a_l \oplus a_{l + 1} \oplus \ldots \oplus a_k$, $y = a_{k + 1} \oplus a_{k + 2} \oplus \ldots \oplus a_{r}$. If $s$ is zero, than we can choose any $k$ and any side because $s = x \oplus y = 0 \implies x = y$. If $s$ is not zero we can choose such $k$ for the left side that the most significant bit of $s$ is the same as the most significant bit of $x$ because $y = s \oplus x$ does not have this bit, and therefore less than $x$. Same for the right side. We will iterate over all subarrays in non-increasing order of length and will calculate two set of bits $mask\_start_i$ and $mask\_end_i$ for each position of array - bits, one of which must contain the XOR of subarray numbers to start/end at that position. To check that we can achieve $l$, $r$ we need to check that $s \land mask\_start_l > 0$ or $s \land mask\_end_r > 0$ or any segment can start/end in these positions, since there was a segment with zero XOR with such start/end. If we can achieve $[l; r]$ than: if $s \neq 0$ add the most significant bit of $s$ to $mask\_start_l$ and $mask\_end_r$; if $s = 0$ remember that any subarray of shorter length can start/end at these positions. The time complexity is $O(n^2)$, the space complexity is $O(n)$.
|
[
"bitmasks",
"dp",
"math"
] | 2,600
| null |
1863
|
G
|
Swaps
|
You are given an array of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$). You can perform the following operation several (possibly, zero) times:
- pick an arbitrary $i$ and perform swap$(a_i, a_{a_i})$.
How many distinct arrays is it possible to attain? Output the answer modulo $(10^9 + 7)$.
|
Consider a directed graph with $n$ vertices, where for each vertex $i$ there is an edge $i\to a_i$. This is a functional graph, that is, every vertex has exactly one edge outgoing from it. Let's see how our operations affect the graph. We will write $u\to v$ to illustrate the fact that $a_u = v$. Call the operation $\mathrm{swap}(a_i, a_{a_i})$ picking vertex $i$. We can assume that we never picked such $u$ that the operation didn't change the permutation, that is, $u\to v\to v$. We will mark some edges in the graph as bold. Initially no edge is bold. When we pick vertex $v$, one of the following can happen: If no bold edges pass into $v$, go along the bold edges until we can. Let's say the vertex we reached is $u$. Then mark the edge from $u$ bold. If $v$ has an incoming bold edge, do nothing. At every moment of time, the graph corresponds to the permutation in the following way: if $v$ has an incoming bold edge then $a_v = v$, otherwise, if $u$ is the vertex we reach by going from $v$ along the bold edges, and $u\to w$, then $a_v = w$. Also, one can see that according to the algorithm of making edges bold no vertex ever has more than one incoming bold edge. It is clear that each valid subset of bold edges corresponds to a unique permutation. However, one can see that the same permutation can correspond to multiple subsets. In particular, for a component of the graph, if $a_v = v$ for all vertices of the cycle in this component, then the boldness of all edges outside the cycle is uniquely determined, but for the edges of the cycle any subset of these edges that doesn't include exactly one of them corresponds to this permutation. To avoid this uncertainty, we say that this permutation will correspond to the subset of bold edges where all the edges from the cycle are bold (this is an invalid subset, because there is no sequence of operations that would mark it bold). Now we want to calculate the number of possible subsets of bold edges. Each vertex can have either no incoming bold edges (there is $1$ way to do this) or any one of them can be bold ($\mathrm{in}_v$ ways to do this for vertex $v$). So the answer could be just $\prod_{v}(\mathrm{in}_v + 1)$. However, since some of the configurations are invalid, we need to modify the answer. In particular, consider any cycle $c_1\to\ldots\to c_k\to c_1$. All excluded subsets of edges correspond to exactly one of $c_{i+1}$ having either no bold edge incoming, or any edge except $c_i\to c_{i+1}$. Therefore, the number of ways to choose the bold edges among the ones incoming to this cycle is $\prod_{i=1}^k(\mathrm{in}_{c_i} + 1) - \sum_{i=1}^k\mathrm{in}_{c_i}.$ Thus, the final answer is $\prod_{\text{cycles}}\left(\prod_{i=1}^k(\mathrm{in}_{c_i} + 1) - \sum_{i=1}^k\mathrm{in}_{c_i}\right)\cdot\prod_{\text{other }v}(\mathrm{in}_v + 1).$
|
[
"combinatorics",
"dp",
"graphs",
"math"
] | 2,800
| null |
1863
|
H
|
Goldberg Machine 3
|
There is a complete rooted binary tree, that is, a rooted tree in which each vertex has either $0$ or $2$ children. The root of the tree is vertex $1$. A node without children is called a leaf. Each leaf has a hunger value, we denote the hunger value of leaf $v$ by $h_v$.
Each inner vertex of the tree has a selector pointing to one of the children of the vertex.
This tree accepts cookies. Before launching the process you can choose the initial state of each selector individually. The process is as follows:
- Initially there are no cookies in vertices.
- You insert cookies into the root one by one.
- As long as the cookie is not in a leaf, it falls to the child defined by the selector in the current vertex. This selector then changes its state to the opposite one, i. e. it starts pointing to the other child of the vertex.
- You stop inserting cookies when each leaf $v$ has at least $h_v$ cookies in it. In this case, we say that the tree is filled up.
You have $q$ queries. Each query changes the value of $h_v$ for some leaf $v$. You need to print $q + 1$ numbers, the $i$-th of them being the minimum number of cookies required to fill up the machine after $(i - 1)$ updates if you can pick any initial state for every selector. Since these numbers may be very large, print the answers modulo $998\,244\,353$.
Please note that you can choose the initial state of all selectors independently between queries. However, the queries themselves are not independent: when answering the $i$-th query, you should also consider the effect of queries $1, 2, \ldots, i - 1$.
|
Let's consider a dynamic programming approach: for leaves, set $dp_v = a_v$, and for an internal vertex $v$ with children $u$ and $w$, set $dp_v = 2 \max(dp_u, dp_w)-[dp_u \neq dp_w]$ we use an indicator notation $[\ldots]$. Let $d_v = dp_v - 1$, then the update becomes $d_v = 2 \max(d_u, d_w) + [d_u = d_w]$. Let $h_v$ denote the distance from the root to $v$, and $D_v = d_v \cdot 2^{h_v}$. Then $D_v = \max(D_u, D_w) + 2^{h_v} [D_u = D_w]$. Notice that the binary representation of $D_v$ contains at most $\log_2 A + \log_2 n$ ones ($A = \max a_i$). This can be easily proven by induction: suppose the minimum size of a tree that can result in $D_v$ having $k$ ones is $f(k)$. Then, $f(k) = 1$ when $k \le \log_2 A$, and $f(k) \ge 2f(k - 1)$ otherwise, since $D_v$ must be constructed from equal $Du$ and $Dw$ from independent subtrees. We'll maintain a set $S$ of pairs $(v, D)$, where $D$ is a lower bound on $D_v$. Initially, put pairs $(v,(a_v - 1)\cdot 2^{h_v})$ into $S$ for all leaves with $a_v > 0$, and if there are $(v, D)$ and $(u, D)$ in $S$ ($v \neq u$), put $(w, D + 2^{h_w})$ into $S$, where $w = \text{lca}(v, u)$. The answer is $1 +$ the maximum $D$ among all pairs in $S$ (if $S$ is empty, the answer is obviously $0$). Start with an empty $S$ and add all the leaves to it. A new pair $(v, D)$ can create at most one new lca with pairs $(u, D)$, and at most one new pair $(w, D + 2^k)$, where $k$ is necessarily a new bit. The process of creating new pairs continues, but it will finish in $O(\log A + \log n)$ iterations since there cannot be more bits. Different $D$ values can be stored in a trie based on bit positions from most significant to least significant (or by some hashing), and vertex sets in the trie nodes can be stored in the order of entry time. To change $a_v$, remove the old pair from $S$ (similarly to adding) and add the new one. All together requires $O(\log n \cdot (\log A + \log n))$ operations.
|
[
"dp",
"trees"
] | 3,500
| null |
1863
|
I
|
Redundant Routes
|
You are given a tree with $n$ vertices labeled $1, 2, \ldots, n$. The length of a simple path in the tree is the number of vertices in it.
You are to select a set of simple paths of length at least $2$ each, but you cannot simultaneously select two distinct paths contained one in another. Find the largest possible size of such a set.
Formally, a set $S$ of vertices is called a route if it contains \textbf{at least two vertices} and coincides with the set of vertices of a simple path in the tree. A collection of distinct routes is called a timetable. A route $S$ in a timetable $T$ is called redundant if there is a different route $S' \in T$ such that $S \subset S'$. A timetable is called efficient if it contains no redundant routes. Find the largest possible number of routes in an efficient timetable.
|
Let's call two paths adjacent if one can be obtained from the other by adding an edge to one end and removing an edge from the other end. Proposition. There exists an optimal solution in which each pair of adjacent paths is either simultaneously chosen or simultaneously not chosen. Proof. Consider an optimal solution that maximizes the total length of paths in it. Let's assume that in such a solution, we have taken some path $ab$, but its adjacent path $cd$ is not included (here, assume $a \not\in cd$ and $d \not\in ab$). Why can't we add $cd$? If $cd$ contains a shorter path, it must end at $d$ (since all other paths are also contained in $ab$). In that case, we can extend the shorter path $ed$ to $cd$, which contradicts the maximization of the sum of lengths. If $cd$ is contained within a longer path, it must start at $c$ (since all other paths are also contained in $ab$). In this case, we can extend $ab$. In the rooted tree, we'll call a class vertical if it contains at least one vertical path. To reduce the number of vertical classes, we'll root the tree by the midpoint of its diameter (if the diameter is of odd length, consider the root as an edge). Now, all vertical paths of the same length are equivalent (since a vertical path can always be moved to another subtree of the root). Thus, for each length, there is at most one vertical class. How do we determine if a path belongs to some vertical class? We'll attempt to greedily pull the path: first lower one end of the path to the deepest available vertex, then the other end, and so on. In the end, either the path becomes vertical or we encounter an obstacle of the following form: the endpoints are in non-intersecting subtrees of the same depth $h$, whose roots are at distance $d$ apart, and the path length is $h + d$. Moreover, any such pair of subtrees describes a non-vertical class of paths, and no other classes exist, as paths from a non-vertical class must hit such an obstacle. Note. A class doesn't necessarily consist of all paths between subtrees of length $h + d$. This is because an obstacle might exist lower down for some of these paths. Nonetheless, at least one representative for any pair of subtrees will definitely exist (for instance, the root of one subtree and the deepest leaf of the other). Let's define non-vertical classes with a pair of root vertices of subtrees $(v, u)$ (with the convention $tin(v) < tin(u)$), and define the class length as $L(v, u) = h + d$. We'll introduce a forest structure on non-vertical classes: a pair $(v, u)$ is an ancestor of $(v', u')$ if $v$ is an ancestor of $v'$ and $u$ is an ancestor of $u'$. All classes, together with this forest, can be constructed using DFS in $O(n^2)$ time, simultaneously traversing $v$ and $u$. Moreover, we can quickly compute the size of each such class. Let $S(v, u)$ denote the number of all paths of length $L(v, u)$ between subtrees $v$ and $u$. Then, the size of class $N(v, u)$ is $S(v, u) - \sum_{(v', u')} N(v', u')$, where the summation is over all classes $(v', u')$ that are proper descendants of $(v, u)$ such that $L(v', u') = L(v, u)$. Thus, we need to compute all $S(v, u)$. If we compute this for each class in $O(h)$ time, the total time will be $O(n^2)$ (exercise for the reader). Which non-vertical classes can't be taken simultaneously? If between classes $a = (v, u)$ and $b = (v', u')$ neither is an ancestor of the other, then nested paths can't exist in them (due to the construction of the forest, there's a branching somewhere that's common to all paths). Proposition. Let class $a$ be an ancestor of class $b$. Then, a pair of nested paths between them can exist if and only if for all classes $c$ on the path between $a$ and $b$ (including $b$ but excluding $a$), $L(c) > L(a)$. Proof. Paths within $b$ cannot come out of subtrees $v', u'$. If $L(a) \leq L(b)$, then a path of length $L(a)$ containing something from $b$ must also go between subtrees $v', u'$, but it can't extend beyond subtrees $v, u$ (since shorter paths from $b$ can't). Thus, it can't belong to $a$. Otherwise, if we attempt to pull a path of length $L(a)$ nested within $b$ upwards until encountering an obstacle at $a$, this can only happen if $a$ is the first significant obstacle. How do we include vertical classes? Clearly, we can take at most one vertical class. Using similar reasoning as above, if $a$ is a non-vertical class and $\ell$ is the length of a vertical class, then $a$ can be taken with a vertical class if there are no classes $c$ among the ancestors of $a$ (including $a$) with $L(c) \leq \ell$. Constructing a bamboo structure out of all vertical classes (shorter classes on top) and attaching the roots from the forest of non-vertical classes at the bottom of this bamboo, the criterion remains the same as in the proposition. Now we can forget about the original problem and solve a new one: given a rooted tree, with numbers $L_v$ and $N_v$ assigned to each vertex, we need to select a set of vertices to maximize the sum of $N_v$, while satisfying the criterion. Consider the vertex $v$ with the minimum $L_v$ among all vertices (considering the deepest among such vertices, if there are several options). It's easy to see that: Vertices outside the subtree rooted at $v$ cannot prevent us from choosing vertices within the subtree rooted at $v$. If we choose $v$, we can't choose anything else in its subtree. Divide the set of all vertices $V$ into $T_v - v$ and $V - T_v$, where $T_v$ is the subtree rooted at $v$, and solve the problem independently for them. The final answer will be $ans(V - T_v) + \max(N_v, ans(T_v))$. This process can be conveniently done in reverse, for instance, using DSU. It's also possible to carefully determine, during the forest construction, which components will merge, and solve the problem in $O(n^2)$ time using just bucket sort without any additional data structures or sorting.
|
[
"constructive algorithms",
"dp",
"trees"
] | 3,500
| null |
1864
|
A
|
Increasing and Decreasing
|
You are given three integers $x$, $y$, and $n$.
Your task is to construct an array $a$ consisting of $n$ integers which satisfies the following conditions:
- $a_1=x$, $a_n=y$;
- $a$ is \textbf{strictly} increasing (i.e. $a_1 < a_2 < \ldots < a_n$);
- if we denote $b_i=a_{i+1}-a_{i}$ for $1 \leq i \leq n-1$, then $b$ is \textbf{strictly} decreasing (i.e. $b_1 > b_2 > \ldots > b_{n-1}$).
If there is no such array $a$, print a single integer $-1$.
|
We use the following greedy construction: For all $i$ ($1<i<n$), set $a_i=a_{i+1}-(n-i)$. If $a_2-a_1 \geq n-1$, we've found a solution, otherwise there is no solution. Proof. Assume there's a solution which includes an index $i$ ($1<i<n$) such that $a_{i+1}-a_i>n-i$. We can make $a_j:=a_j+\Delta$ for all $j$ ($2 \le j \le i$), where $\Delta=a_{i+1}-a_i-(n-i)$. After several processes like this, we get a solution the same as greedy construction gives. This leads to a contradiction.
|
[
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 800
|
#include <bits/stdc++.h>
#define all(a) (a).begin(), (a).end()
#define sz(a) (int)(a).size()
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tt;
cin >> tt;
while (tt--) {
int x, y, n;
cin >> x >> y >> n;
vector<int> a(n);
a[0] = x, a[n - 1] = y;
int d = 1;
for (int i = n - 2; i >= 1; --i) {
a[i] = a[i + 1] - d;
++d;
}
bool ok = true;
for (int i = 0; i + 1 < n; ++i) {
if (a[i + 1] <= a[i]) {
ok = false;
}
}
for (int i = 0; i + 2 < n; ++i) {
int p = a[i + 1] - a[i];
int q = a[i + 2] - a[i + 1];
if (p <= q) {
ok = false;
}
}
if (!ok) {
cout << "-1\n";
continue;
}
for (int i = 0; i < n; ++i) {
cout << a[i] << " ";
}
cout << "\n";
}
}
|
1864
|
B
|
Swap and Reverse
|
You are given a string $s$ of length $n$ consisting of lowercase English letters, and an integer $k$. In one step you can perform \textbf{any one} of the two operations below:
- Pick an index $i$ ($1 \le i \le n - 2$) and swap $s_{i}$ and $s_{i+2}$.
- Pick an index $i$ ($1 \le i \le n-k+1$) and reverse the order of letters formed by the range $[i,i+k-1]$ of the string. Formally, if the string currently is equal to $s_1\ldots s_{i-1}s_is_{i+1}\ldots s_{i+k-2}s_{i+k-1}s_{i+k}\ldots s_{n-1}s_n$, change it to $s_1\ldots s_{i-1}s_{i+k-1}s_{i+k-2}\ldots s_{i+1}s_is_{i+k}\ldots s_{n-1}s_n$.
You can make as many steps as you want (possibly, zero). Your task is to find the lexicographically \textbf{smallest} string you can obtain after some number of steps.
A string $a$ is lexicographically smaller than a string $b$ of the same length if and only if the following holds:
- in the first position where $a$ and $b$ differ, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$.
|
By the first kind of operation, we already know that every odd index (same for the even ones) can be swapped with each other freely. Therefore, let us write down the values of the indices modulo $2$. For example, if $n$ is $10$, the indices modulo $2$ are $[1,0,1,0,1,0,1,0,1,0]$. Now, we consider the two cases. When $k$ is odd. We can find out that after reversing any subarray of length $k$, the indices modulo $2$ do not change. So in this case, any series of the second operation is identical to some series of the first operation. Therefore, you should sort the odd indices and the even indices separately, and output the result of merging them into one string. When $k$ is even. Let us observe how we can swap two adjacent indices in this case. First, reverse $[i,i+k-1]$, and then reverse $[i+1,i+k]$. If we do this on $[1,0,1,0,1,0,1,0,1,0]$, assuming $i=1$ and $k=6$, the indices modulo $2$ turn into $[0,1,0,1,0,1,1,0,1,0]$, and then $[0,1,1,0,1,0,1,0,1,0]$. Using these two steps and some series of the first operation, we can see that we can swap any two adjacent indices as a result. And such a series of operation is always possible, as $k<n$. Therefore, we can sort the entire string, and output the result. Try to solve the problem if $n = k$ was allowed.
|
[
"constructive algorithms",
"greedy",
"sortings",
"strings"
] | 1,100
|
#include <bits/stdc++.h>
#define all(a) (a).begin(), (a).end()
#define sz(a) (int)(a).size()
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tt;
cin >> tt;
while (tt--) {
int n, k;
cin >> n >> k;
string s;
cin >> s;
vector<char> odd, even;
for (int i = 0; i < n; ++i) {
if (i % 2 == 0) {
even.pb(s[i]);
} else {
odd.pb(s[i]);
}
}
sort(all(even));
sort(all(odd));
string ans1 = "";
for (int i = 0, j = 0; i < sz(even) || j < sz(odd); ++i, ++j) {
if (i < sz(even)) {
ans1 += even[i];
}
if (j < sz(odd)) {
ans1 += odd[i];
}
}
if (k % 2 == 0) {
sort(all(s));
cout << s << "\n";
continue;
}
cout << ans1 << "\n";
}
}
|
1864
|
C
|
Divisor Chain
|
You are given an integer $x$. Your task is to reduce $x$ to $1$.
To do that, you can do the following operation:
- select a divisor $d$ of $x$, then change $x$ to $x-d$, i.e. reduce $x$ by $d$. (We say that $d$ is a divisor of $x$ if $d$ is an positive integer and there exists an integer $q$ such that $x = d \cdot q$.)
There is an additional constraint: you \textbf{cannot} select the same value of $d$ \textbf{more than twice}.
For example, for $x=5$, the following scheme is \textbf{invalid} because $1$ is selected more than twice: $5\xrightarrow{-1}4\xrightarrow{-1}3\xrightarrow{-1}2\xrightarrow{-1}1$. The following scheme is however a valid one: $5\xrightarrow{-1}4\xrightarrow{-2}2\xrightarrow{-1}1$.
Output any scheme which reduces $x$ to $1$ with at most $1000$ operations. It can be proved that such a scheme always exists.
|
Let us divide the task into two steps, on each step we will use each divisor at most once. For convenience, let us denote $L$ as the largest value, such that $2^L \le x$ holds. The two steps are as follows. Reduce $x$ to $2^L$. Given any integer $x$, we can see that its lowest significant bit is a divisor of $x$. If $x$ has more than one bit, we can repeatedly subtract the value corresponding to the lowest significant bit of $x$. When $x$ finally has only one bit, finish the first step. In this step, we have only used each significant bit of $x$ at most once. Reduce $2^L$ to $1$. We can find a way to reduce $2^L$ to $1$ by using each bit exactly once. Formally, if $k \ge 0$, then $2^{k+1}-2^k=2^k$, and $2^k$ is a divisor of $2^{k+1}$. Thus, by subtracting $2^{L-1},2^{L-2},\ldots,1$ in order, we reach $1$ from $2^L$ by using each bit from the $0$-th bit to the $(L-1)$-st bit exactly once. As a result, we can reduce $x$ to $1$ by using each power of $2$ at most twice (once from the first step, once from the second step). Since we used each bit at most twice, the time complexity for solving one test case is $O(\log x)$. Due to the lenient constraints, some solutions with $O(\sqrt x)$ time complexity should pass as well (as long as they fit into the $1000$ operations limit).
|
[
"bitmasks",
"constructive algorithms",
"math",
"number theory"
] | 1,300
|
#include <bits/stdc++.h>
#define all(a) (a).begin(), (a).end()
#define sz(a) (int)(a).size()
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
bool bit(int mask, int pos) {
return (mask >> pos) & 1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tt;
cin >> tt;
while (tt--) {
int x;
cin >> x;
int p;
vector<int> ans;
ans.pb(x);
for (int i = 0; ; ++i) {
if (bit(x, i)) {
if (x == (1 << i)) {
p = i;
break;
}
x -= (1 << i);
ans.pb(x);
}
}
while (p > 0) {
x -= (1 << (p - 1));
ans.pb(x);
--p;
}
cout << sz(ans) << "\n";
for (int y : ans) {
cout << y << " ";
}
cout << "\n";
}
}
|
1864
|
D
|
Matrix Cascade
|
There is a matrix of size $n \times n$ which consists of 0s and 1s. The rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. The cell at the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$.
AquaMoon wants to turn all elements of the matrix to 0s. In one step she can perform the following operation:
- Select an arbitrary cell, let it be $(i, j)$, then invert the element in $(i, j)$ and also invert all elements in cells $(x, y)$ for $x > i$ and $x - i \ge \left|y - j\right|$. To invert a value means to change it to the opposite: 0 changes to 1, 1 changes to 0.
Help AquaMoon determine the minimum number of steps she need to perform to turn all elements of the matrix to 0s. We can show that an answer always exists.
|
Firstly, the first row has some elements that are $\text{1}$ s and some elements that are $\text{0}$ s. The elements that are $\text{1}$ can only be turned into $\text{0}$ by operating on the corresponding cell an odd number of times, and the elements that are $\text{0}$ can only be turned into $\text{0}$ by operating on the corresponding cell an even number of times. Two operations on the same cell are equivalent to no operation, so only one operation is performed on the corresponding cell of the element that is $\text{1}$ in the first row. Thus, the operation on the first row is deterministic. Subsequent rows are affected by the operations in the first row, so it is sufficient to proceed to consider rows $2$ to $n$ in the same way. Now consider how to quickly deal with the effect of the preceding rows on the following rows. An operation on position $(x,y)$ will simultaneously invert all the elements from column $y-1$ to column $y+1$ in row $x+1$, and from column $y-2$ to column $y+2$ in row $x+2$, and son on. Thus, the elements being inverted are exactly the portion of the matrix sandwiched between lines passing through $(x,y)$ with slopes $1$ and $-1$. Let $b$ denote the effect of the line with slope $1$ from all predecing rows, and let $c$ denote the effect of the line with slope $-1$ from all preceding rows. % To optimize complexity, $b$, $c$ are both obtained using difference arrays to the current line using prefix sums to obtain the $b,c$ values at that time. After an operation on $(i,j)$, $b[i+1][j-1]$ is marked, and $c[i+1][j+2]$ is marked. Next, $b[i][j]$ inherits $b[i-1][j+1]$, and $c[i][j]$ inherits $c[i-1][j-1]$. For the current row, the effect of the previous rows is obtained by maintaining the prefix sums on $b$ and $c$. The total complexity is $O(n^2)$.
|
[
"brute force",
"constructive algorithms",
"data structures",
"dp",
"greedy",
"math"
] | 1,700
|
#include <bits/stdc++.h>
#define all(a) (a).begin(), (a).end()
#define sz(a) (int)(a).size()
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<string> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int ans = 0;
vector<vector<int> > val(n, vector<int>(n, 0));
vector<vector<int> > sum(n, vector<int>(n, 0));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i == 0) {
} else if (i == 1) {
for (int k = max(0, j - 1); k <= min(j + 1, n - 1); ++k) {
sum[i][j] ^= sum[i - 1][k];
}
} else {
if (j == 0) {
sum[i][j] ^= sum[i - 2][j];
} else {
sum[i][j] ^= sum[i - 1][j - 1];
}
if (j == n - 1) {
sum[i][j] ^= sum[i - 2][j];
} else {
sum[i][j] ^= sum[i - 1][j + 1];
}
sum[i][j] ^= sum[i - 2][j];
sum[i][j] ^= val[i - 1][j];
}
if (sum[i][j] ^ (a[i][j] - '0')) {
++ans;
sum[i][j] ^= 1;
val[i][j] = 1;
}
}
}
cout << ans << "\n";
}
}
|
1864
|
E
|
Guess Game
|
Carol has a sequence $s$ of $n$ non-negative integers. She wants to play the "Guess Game" with Alice and Bob.
To play the game, Carol will \textbf{randomly} select two integer indices $i_a$ and $i_b$ within the range $[1, n]$, and set $a=s_{i_a}$, $b=s_{i_b}$. Please note that $i_a$ and $i_b$ may coincide.
Carol will tell:
- the value of $a$ to Alice;
- the value of $b$ to Bob;
- the value of $a \mid b$ to both Alice and Bob, where $|$ denotes the bitwise OR operation.
Please note that Carol will \textbf{not} tell any information about $s$ to either Alice or Bob.
Then the guessing starts. The two players take turns making guesses, with Alice starting first. The goal of both players is to establish which of the following is true: $a < b$, $a > b$, or $a = b$.
In their turn, a player can do one of the following two things:
- say "I don't know", and pass the turn to the other player;
- say "I know", followed by the answer "$a<b$", "$a>b$", or "$a=b$"; then the game ends.
Alice and Bob hear what each other says, and can use this information to deduce the answer. Both Alice and Bob are smart enough and only say "I know" when they are completely sure.
You need to calculate the expected value of the number of turns taken by players in the game. Output the answer modulo $998\,244\,353$.
Formally, let $M = 998\,244\,353$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output such an integer $x$ that $0 \le x < M$ and $x \cdot q \equiv p \pmod{M}$.
|
First, let's analize a single game for fixed $a$, $b$, and how many turns it takes. Consider the binary representation of $a \mid b$. We consider bits from highest to lowest. For bits with a value of $0$, we can ignore it because it firmly tells us that both bits of $a$ and $b$ are $0$. For convenience, we assume that all bits of $a \mid b$ are $1$. In the first round, if the highest bit of $a$ is $0$, then Alice can immediately say that $a<b$. Otherwise, in the second round of the game, Bob knows that the highest bit of $a$ is not $0$. If the highest or the second highest bit of b is $0$, then Bob can immediately say that $a>b$. Otherwise, in the third round of the game, Alice knows that the highest and the second highest bits of $b$ are not $0$, and so on. Consider only set bits in $a \mid b$. Let's enumerate these bits from highest to lowest. After some observation, we can conclude that: If $a<b$ and the $i$-th bit in $a$ is zero, then the answer is $i+1-(i\%2 == 1)$; If $a=b$, then the answer is $k+1$, where $k$ is the number of set bits in $a \mid b$; If $a>b$ and the $i$-th bit in $b$ is zero, then the answer is $i+(i\%2 == 1)$. Now that we have a brute force algorithm for $O (n^2 \log A)$, how can we optimize it? We can build a bit trie and traverse all nodes. We can easily calculate the number of $1$s that pass from a node to the root node, as well as the number of numbers prefixed with it and followed by $0$ (or $1$). Use this information to calculate the answer.
|
[
"bitmasks",
"data structures",
"games",
"math",
"probabilities",
"sortings",
"strings",
"trees"
] | 2,100
|
#include <bits/stdc++.h>
#define all(a) (a).begin(), (a).end()
#define sz(a) (int)(a).size()
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
struct node {
int to[2];
int cnt;
node() {
to[0] = to[1] = -1;
cnt = 0;
}
};
bool bit(int mask, int pos) {
return (mask >> pos) & 1;
}
vector<node> t;
void add(int x) {
int v = 0;
for (int i = 29; i >= 0; --i) {
int b = bit(x, i);
if (t[v].to[b] == -1) {
t[v].to[b] = sz(t);
t.pb(node());
}
++t[v].cnt;
v = t[v].to[b];
}
++t[v].cnt;
}
const int mod = 998244353;
void mul(int& a, int b) {
ll c = ll(a) * b;
if (c >= mod) {
c %= mod;
}
a = c;
}
int binpow(int a, int n) {
int ans = 1;
while (n) {
if (n & 1) {
mul(ans, a);
}
mul(a, a);
n >>= 1;
}
return ans;
}
void solve(int v, int k, ll& ans) {
if (t[v].to[0] != -1 && t[v].to[1] != -1) {
ll i = k + 1;
ans += (2 * (i / 2) + 1) * t[t[v].to[0]].cnt * t[t[v].to[1]].cnt;
ans += 2 * ((i + 1) / 2) * t[t[v].to[0]].cnt * t[t[v].to[1]].cnt;
}
if (t[v].to[0] == -1 && t[v].to[1] == -1) {
ll i = k + 1;
ans += i * t[v].cnt * t[v].cnt;
}
if (t[v].to[0] != -1) {
solve(t[v].to[0], k, ans);
}
if (t[v].to[1] != -1) {
solve(t[v].to[1], k + 1, ans);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int tt;
cin >> tt;
while (tt--) {
t.clear();
t.pb(node());
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
int a;
cin >> a;
add(a);
}
ll x = 0;
solve(0, 0, x);
int ans = x % mod;
mul(ans, binpow(n, mod - 2));
mul(ans, binpow(n, mod - 2));
cout << ans << "\n";
}
}
|
1864
|
F
|
Exotic Queries
|
AquaMoon gives RiverHamster a sequence of integers $a_1,a_2,\dots,a_n$, and RiverHamster gives you $q$ queries. Each query is expressed by two integers $l$ and $r$.
For each query independently, you can take any continuous segment of the sequence and subtract an identical non-negative value from all the numbers of this segment. You can do so multiple (possibly, zero) times. However, you may not choose two intersecting segments which are not included in one another. Your goal is to convert to $0$ all numbers whose initial \textbf{value} was within the range $[l, r]$. You must do so in the minimum number of operations.
Please note that the queries are independent, the numbers in the array are restored to their initial values between the queries.
Formally, for each query, you are to find the smallest $m$ such that there exists a sequence $\{(x_j,y_j,z_j)\}_{j=1}^{m}$ satisfying the following conditions:
- for any $1 \le j \leq m$, $z_j \ge 0$ and $1 \le x_j \le y_j \leq n$ (here $[x_j, y_j]$ correspond to the segment of the sequence);
- for any $1 \le j < k \le m$, it is true that $[x_j,y_j]\subseteq[x_{k},y_{k}]$, or $[x_k,y_k]\subseteq[x_{j},y_{j}]$, or $[x_j,y_j]\cap[x_{k},y_{k}]=\varnothing$;
- for any $1 \le i \le n$, such that $l \le a_i \leq r$, it is true that $${\large a_i = \sum\limits_{\substack {1 \le j \le m \\ x_j \le i \le y_j}} z_j. }$$
|
The final solution is irrelevant to Cartesian trees. First, we consider only the sequence of elements to be manipulated. We claim that it is optimal to operate on the whole sequence so that the minimum elements are all decreased to $0$, and then solve the problem on the segments separated by the $0$s recursively. A straightforward corollary of the claim is that two equal elements between which there are no smaller elements are handled in a single operation, so the final answer is $\ell$ (the number of elements to be manipulated) minus the number of such adjacent pairs. Proof: Define $S(l, r)$ to be the answer for the segment $[l, r]$. Do induction on the length of the segment. If the first operation does not manipulate the whole segment, the segment will be separated into several independent parts by the first operation, for the non-inclusive operations cannot intersect, and the final answer, which is the sum of $S$ of the parts, will not be less than the initial answer according to the corollary, for some of the equal pairs are separated. Now the original problem is converted into a data structure task. Consider all adjacent equal pairs $(l, r)$, and $m$ is the maximum element between $(l, r)$, $m < a_l$. $(l, r)$ decrease the answer if and only if $m < L \le a_l = a_r \le R$, which can be easily calculated with a segment tree and sweeping lines.
|
[
"data structures",
"implementation",
"sortings"
] | 2,300
|
#include <bits/stdc++.h>
#define all(a) (a).begin(), (a).end()
#define sz(a) (int)(a).size()
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
vector<int> sum;
int N;
void updSumTree(int pos) {
for (pos += N; pos; pos >>= 1) {
++sum[pos];
}
}
int getSumTree(int l, int r) {
int ans = 0;
for (l += N, r += N; l <= r; l = (l + 1) >> 1, r = (r — 1) >> 1) {
if (l & 1) {
ans += sum[l];
}
if (!(r & 1)) {
ans += sum[r];
}
}
return ans;
}
vector<int> t;
int n;
void updTree(int pos, int val) {
for (pos += n; pos; pos >>= 1) {
t[pos] = max(t[pos], val);
}
}
int getTree(int l, int r) {
int ans = 0;
for (l += n, r += n; l <= r; l = (l + 1) >> 1, r = (r — 1) >> 1) {
if (l & 1) {
ans = max(ans, t[l]);
}
if (!(r & 1)) {
ans = max(ans, t[r]);
}
}
return ans;
}
const int nmax = 1e6 + 100;
vector<int> pos[nmax];
int cnt[nmax];
int distinct[nmax];
struct query {
int l, r, id;
bool operator<(const query& other) const {
return l < other.l;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int q;
cin >> n >> q;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
t.assign(4 * n, 0);
for (int i = 0; i < n; ++i) {
pos[a[i]].pb(i);
}
vector<pii> pts;
for (int x = 1; x <= n; ++x) {
for (int i = 0; i + 1 < sz(pos[x]); ++i) {
int lf = pos[x][i], rg = pos[x][i + 1];
++lf, --rg;
if (lf > rg) {
continue;
}
int y = getTree(lf, rg);
//cout << x << " " << y << endl;
if (y == 0) {
continue;
}
pts.pb({n - y, x});
}
for (int p : pos[x]) {
updTree(p, x);
}
}
cnt[0] = 0;
distinct[0] = 0;
for (int x = 1; x <= n; ++x) {
cnt[x] = cnt[x - 1] + sz(pos[x]);
distinct[x] = distinct[x - 1] + (!pos[x].empty());
}
sort(all(pts));
int ptr = 0;
vector<query> queries(q);
vector<int> ans(q);
for (int i = 0; i < q; ++i) {
int l, r;
cin >> l >> r;
queries[i] = {n - l, r, i};
ans[i] = distinct[r] - distinct[l - 1];
}
sort(all(queries));
N = n + 1;
sum.assign(2 * N, 0);
for (int i = 0; i < q; ++i) {
while (ptr < sz(pts) && pts[ptr].first <= queries[i].l) {
updSumTree(pts[ptr].second);
++ptr;
}
ans[queries[i].id] += getSumTree(0, queries[i].r);
}
for (int i = 0; i < q; ++i) {
cout << ans[i] << "\n";
}
}
|
1864
|
G
|
Magic Square
|
Aquamoon has a Rubik's Square which can be seen as an $n \times n$ matrix, the elements of the matrix constitute a permutation of numbers $1, \ldots, n^2$.
Aquamoon can perform two operations on the matrix:
- Row shift, i.e. shift an entire row of the matrix several positions (at least $1$ and at most $n-1$) to the right. The elements that come out of the right border of the matrix are moved to the beginning of the row. For example, shifting a row $\begin{pmatrix} a & b & c \end{pmatrix}$ by $2$ positions would result in $\begin{pmatrix} b & c & a \end{pmatrix}$;
- Column shift, i.e. shift an entire column of the matrix several positions (at least $1$ and at most $n-1$) downwards. The elements that come out of the lower border of the matrix are moved to the beginning of the column. For example, shifting a column $\begin{pmatrix} a \\ b \\ c \end{pmatrix}$ by $2$ positions would result in $\begin{pmatrix} b\\c\\a \end{pmatrix}$.
The rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. The cell at the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$.
Aquamoon can perform several (possibly, zero) operations, but she has to obey the following restrictions:
- each row and each column can be shifted at most once;
- each integer of the matrix can be moved at most twice;
- the offsets of any two integers moved twice cannot be the same. Formally, if integers $a$ and $b$ have been moved twice, assuming $a$ has changed its position from $(x_1,y_1)$ to $(x_2,y_2)$, and $b$ has changed its position from $(x_3,y_3)$ to $(x_4,y_4)$, then $x_2-x_1 \not\equiv x_4-x_3 \pmod{n}$ or $y_2-y_1 \not\equiv y_4-y_3 \pmod{n}$.
Aquamoon wonders in how many ways she can transform the Rubik's Square from the given initial state to a given target state. Two ways are considered different if the sequences of applied operations are different. Since the answer can be very large, print the result modulo $998\,244\,353$.
|
Theorem 1: After a row shift, all numbers moved are in the correct column. Proof 1: Suppose a number moved after a row shift is not in the correct column, if it is not in the correct row, it needs at least two more moves to its target position, otherwise it needs at least three more moves because the row cannot be shifted again. Also, after a column shift, all numbers moved are in the correct row. Theorem 2: If both row shift and column shift are performed, two rows cannot have equal shift distance. Proof 2: If row $i$ is shifted by $x$ and column $j$ is shifted by $y$, regardless of their order, then there is a number with offset $(y, x)$. If row $i_1$ and row $i_2$ are shifted by $x$ and column $j$ is shifted by $y$, regardless of their order, then there are two numbers with the same offset $(y, x)$ (if two number coincide, it was moved at least three times). In the same way, if both row shift and column shift are performed, two columns cannot have equal shift distance. If after a row shift, all numbers moved are in the correct column, we call such rows available. Similarly, if after a column shift, all numbers moved are in the correct row, we call such columns available. Theorem 3: If there is an available row and an available column at the same time, then there is no solution. Proof 3: If row $i$ can be shifted by $x$ and column $j$ can be shifted by $y$, the number in $(i, j)$ has offset $(y, x)$. Assume that the number in $(i, j)$ is moved to $(i+y, j)$ and then to $(i+y, j+x)$. Row $i+y$ is shifted by $x$, no other row can be shifted by $x$. Consider the number in $(i,j+1)$, it needs to be shifted by $x$ in some row, so it must be moved to row $i+y$ before row $i+y$ shifts. Then the numbers in $(i, j)$ and $(i+1, j)$ have the same offset $(y, x)$. Similarly, if the number in $(i, j)$ is moved to $(i, j+x)$ and then to $(i+y, j+x)$, there is no solution. We can use the following method to solve this problem: For each row and each column, check if it is available. If there are both available rows and available columns, there is no solution. If no rows or columns are available, the matrix is already equal to the target one, or there is no solution. If there are only available rows or available columns, their order doesn't matter, so if there $s$ choices, the answer should be multiplied by $s!$. Apply all available operations and check again. Total complexity: $O(n^3)$ or $O(n^2)$ if maintaining row/column offsets in each row/column.
|
[
"combinatorics",
"constructive algorithms",
"implementation"
] | 3,100
|
#include <bits/stdc++.h>
#define all(a) (a).begin(), (a).end()
#define sz(a) (int)(a).size()
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
const int mod = 998244353;
const int nmax = 600;
int fact[nmax];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
fact[0] = 1;
for (int i = 1; i < nmax; ++i) {
fact[i] = ll(fact[i - 1]) * i % mod;
}
int tt;
cin >> tt;
while (tt--) {
int n;
cin >> n;
vector<vector<int> > a(n, vector<int>(n));
set<int> seta;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> a[i][j];
seta.insert(a[i][j]);
}
}
assert(sz(seta) == n * n);
vector<vector<int> > b(n, vector<int>(n));
set<int> setb;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> b[i][j];
setb.insert(b[i][j]);
}
}
assert(sz(setb) == n * n);
assert(seta == setb);
vector<int> vct;
for (int x : seta) {
vct.pb(x);
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
a[i][j] = lower_bound(all(vct), a[i][j]) - vct.begin();
b[i][j] = lower_bound(all(vct), b[i][j]) - vct.begin();
}
}
vector<pii> posa(n * n);
vector<pii> posb(n * n);
set<pii> off;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
posa[a[i][j]] = {i, j};
posb[b[i][j]] = {i, j};
}
}
bool valid = true;
for (int x = 0; x < n * n; ++x) {
pii p = posa[x], q = posb[x];
if (p.first != q.first && p.second != q.second) {
pii s = {(q.first - p.first + n) % n, (q.second - p.second + n) % n};
if (off.count(s)) {
valid = false;
} else {
off.insert(s);
}
}
}
if (!valid) {
cout << "0\n";
continue;
}
int cnt = 0;
ll ans = 1;
while (a != b) {
vector<pii> rows;
for (int i = 0; i < n; ++i) {
int shift = posb[a[i][0]].second;
bool ok = true;
for (int j = 0; j < n; ++j) {
int x = a[i][j];
if (posb[x].second != (j + shift) % n) {
ok = false;
break;
}
}
if (ok && shift) {
rows.pb({i, shift});
}
}
vector<pii> cols;
for (int j = 0; j < n; ++j) {
int shift = posb[a[0][j]].first;
bool ok = true;
for (int i = 0; i < n; ++i) {
int x = a[i][j];
if (posb[x].first != (i + shift) % n) {
ok = false;
break;
}
}
if (ok && shift) {
cols.pb({j, shift});
}
}
if (cols.empty() && rows.empty()) {
valid = false;
break;
}
if (!(cols.empty() ^ rows.empty())) {
valid = false;
break;
}
if (!rows.empty()) {
cnt += sz(rows);
ans *= fact[sz(rows)];
ans %= mod;
for (pii p : rows) {
int i = p.first;
int shift = p.second;
vector<int> v = a[i];
for (int j = 0; j < n; ++j) {
int x = v[j];
a[i][(j + shift) % n] = x;
posa[x] = {i, (j + shift) % n};
}
}
} else {
cnt += sz(cols);
ans *= fact[sz(cols)];
ans %= mod;
for (pii p : cols) {
int j = p.first;
int shift = p.second;
vector<int> v;
for (int i = 0; i < n; ++i) {
v.pb(a[i][j]);
}
for (int i = 0; i < n; ++i) {
int x = v[i];
a[(i + shift) % n][j] = x;
posa[x] = {(i + shift) % n, j};
}
}
}
}
if (!valid) {
cout << "0\n";
continue;
}
cout << ans << '\n';
// cout << cnt << " " << ans << "\n";
}
}
|
1864
|
H
|
Asterism Stream
|
Bogocubic is playing a game with amenotiomoi. First, Bogocubic fixed an integer $n$, and then he gave amenotiomoi an integer $x$ which is initially equal to $1$.
In one move amenotiomoi performs \textbf{one} of the following operations with the same probability:
- increase $x$ by $1$;
- multiply $x$ by $2$.
Bogocubic wants to find the expected number of moves amenotiomoi has to do to make $x$ greater than or equal to $n$. Help him find this number modulo $998\,244\,353$.
Formally, let $M = 998\,244\,353$. It can be shown that the answer can be expressed as an irreducible fraction $\frac{p}{q}$, where $p$ and $q$ are integers and $q \not \equiv 0 \pmod{M}$. Output the integer equal to $p \cdot q^{-1} \bmod M$. In other words, output such an integer $y$ that $0 \le y < M$ and $y \cdot q \equiv p \pmod{M}$.
|
Here is a basic $\Theta(n)$ dp solution. Before that let $k = \frac{1}{2}$. At the same time, because a special geometric sequence $f(x)=ak^{bx}$ will be frequently used next, it is defined as $\{a,b\}$. Let $f(x)$ be the expected number of moves needed if we start with $x$. Obviously, there is the following formula: $f(x)=\begin{cases}0&n\leqslant x\\k(f(x+1)+f(2x))+1&x<n\end{cases}$ It's easy to see that for the interval $[n, 2n]$ value of $f(x)$ is $0$. If for an interval $[2l,2r]$, it can already be represented by the sum of several ${a,b}$, then it can be represented by a small number of new $\{a,b\}$ for all $f(x)$, where $x\in[l,r]$ First there is $f(r)=kf(r+1)+kf(2r)+1$. So, $r-1$ can be represented as $f(r-1)=k^2f(r+1)+ kf(2r-2)+k^2f(2r)+k+1$. By analogy, one can get $f(r-x)=k^{x+1}f(r+1)+\sum\limits_{i=0}^xk^{i+1}f(2r-2x+2i)+\sum\limits_{i=0}^xk^i$ by substitution, it can be shown as $f(x)=k^{r-x+1}f(r+1)+\sum\limits_{i=0}^{r-x}k^{i+1}f(2x+2i)+\sum\limits_{i=0}^{r-x}k^i$ Because $\{a,b\}$ of the interval where $f(r+1)$ is already known, the value of $f(r+1)$ can be calculated quickly. So, the first term of $f(x)$ can be represented as below: $k^{r-x+1}f(r+1)=k^{r+1}f(r+1) \cdot k^{-x}=\{k^{r+1}f(r+1),-1\}$ Then the last term of $f(x)$, $\sum\limits_{i=0}^{r-x}k^i$ is sum of an ordinary geometric sequence. So, after applying the formula it can represented as $\{2,0\}+\{-k^r,-1\}$. For the second term $\sum\limits_{i=0}^{r-x}k^{i+1}f(2x+2i)$, it has been assumed that $f(2x+2i)$ is $\sum\{a,b\}$, so split it into the following form (the derivation process depends on $k^{2b+1}\neq1$): $\!\begin{aligned} \sum\limits_{i=0}^{r-x}k^{i+1}f(2x+2i)&=\sum\limits_{i=0}^{r-x}k^{i+1}\sum\limits_f\{a,b\}\\ &=\sum\limits_{i=0}^{r-x}k^{i+1}\sum\limits_fak^{b(2x+2i)}\\ &=\sum\limits_f\sum\limits_{i=0}^{r-x}k^{i+1}ak^{b(2x+2i)}\\ &=\sum\limits_f\sum\limits_{i=0}^{r-x}ak^{2bx+1} \cdot k^{i+2bi}\\ &=\sum\limits_fak^{2bx+1}\sum\limits_{i=0}^{r-x}(k^{2b+1})^i\\ &=\sum\limits_fak^{2bx+1}\cdot\frac{k^{(2b+1)(r-x+1)}-1}{k^{2b+1}-1}\\ &=\sum\limits_f\frac{ak^{(2b+1)(n+1)+1}}{k^{2b+1}-1}\cdot k^{-x}+\frac{-ak}{k^{2b+1}-1}\cdot k^{2bx}\\ &=\sum\limits_f\{\frac{ak^{(2b+1)(n+1)+1}}{k^{2b+1}-1},-1\}+\{\frac{-ak}{k^{2b+1}-1},2b\} \end{aligned}$ Because of the obvious combination law $\{a,b\}+\{c,b\}=\{a+c,b\}$, the number of its geometric series is linear with the number of recursions. For $x\in[n,2n], f(x)=0$, which can be represented as $f(x)=\{0,0\}$, so this recursive rule can always be used, Until the $x\in[1,1]$ is obtained, to get the result. The complexity varies depending on the implementation $\Theta(T\log^3n)$ or $\Theta(T\log^2n)$.
|
[
"dp",
"math",
"matrices"
] | 3,200
|
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast", "inline", "-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#define int long long
const int MOD = 998244353;
int n, k;
long long power(int x, int p)
{
if (p < 0)
return power(power(x, MOD - 2), -p);
int answer = 1;
x %= MOD;
while (p)
{
if (p & 1)
answer = answer * x % MOD;
x = x * x % MOD;
p >>= 1;
}
return answer;
}
void Delta()
{
cin >> n;
k = power(2, MOD - 2);
int l = n, r = max(1ll, (n - 1) * 2), n0 = 0, s;
vector<int> Q;
while (l > 1)
{
vector<int> P;
l = (l + 1) / 2;
r /= 2;
s = n0;
for (int i = 0, t = k - 1; i < (int)Q.size(); ++i)
{
s = (s + Q[i] * power(power(k, -(1ll << i)), r + 1)) % MOD;
t = t * t % MOD;
}
P.push_back(((power(k, r + 1) * s - power(k, r)) % MOD + MOD) % MOD);
for (int i = 0; i < (int)Q.size(); ++i)
{
P[0] += power(power(k, 1 - (1ll << (i + 1))) - 1, MOD - 2) * Q[i] % MOD * power(power(k, 1 - (1ll << (i + 1))), r + 1) % MOD * k % MOD;
P.push_back(((MOD - Q[i] * k % MOD * power(power(k, 1 - (1ll << (i + 1))) - 1, MOD - 2) % MOD) % MOD + MOD) % MOD);
}
P[0] += (MOD - n0) * power(k, r + 1) % MOD;
for (int &i : P)
i %= MOD;
Q = P;
n0 += 2;
}
s = n0;
for (int i = 0, t = k - 1; i < (int)Q.size(); ++i)
{
s = (s + Q[i] * power(power(k, -(1ll << i)), 1)) % MOD;
t = t * t % MOD;
}
cout << s << endl;
}
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--)
Delta();
}
|
1864
|
I
|
Future Dominators
|
Dhruvil and amenotiomoi are sitting in different countries and chatting online. Initially, amenotiomoi has an empty board of size $n \times n$, and Dhruvil has a sequence of integers $1, 2, \ldots, n^2$, each number occurring exactly once. The numbers may be placed in the cells of the board, each cell is either empty or contains exactly one number.
The current state of the board is called \textbf{good}, if there is a way of placing the remaining numbers in empty cells so that all numbers except $1$ have a neighbor with a smaller value. Two cells are neighbors if they share an edge.
The rows are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $n$ from left to right. The cell at the intersection of the $x$-th row and the $y$-th column is denoted as $(x, y)$.
To chat, amenotiomoi asks $q$ queries to Dhruvil. Each time he provides Dhruvil with an empty cell $(x, y)$. Dhruvil has to place one of the remaining numbers in this cell so that the board is still good. Among all ways to do this, he chooses the largest possible number he can place and sends this number to amenotiomoi as the answer to the query.
Since amenotiomoi knows the correct answer every time, he tells Dhruvil $(x \oplus k,y \oplus k)$ instead of $(x, y)$, where $k$ is the answer for the previous query. If amenotiomoi is sending the first query, he considers $k = 0$. Each time Dhruvil has to decode the query and send the answer to amenotiomoi. Here $\oplus$ denotes the bitwise XOR operation.
Help Dhruvil reply to all amenotiomoi's queries.
|
This problem is based on a method of online edge deletion and querying connectivity of a planar graph. Firstly, if this vertex is not an articulation point, it will not cause any change in connectivity. Therefore, the algorithm needs to determine whether a certain vertex is an articulation point. Thinking about using a data structure called union-find to keep track of the deleted points, we can identify a clear condition: if a vertex has two neighbors with the same union-find value among its $8$-connected neighbors, then it becomes an articulation point. This is easy to understand: When the values in the union-find are the same, it means there's a loop forming, and this messes up how things are connected inside and outside the loop. But if all the values in the union-find are different, no loops will form, and we can find a way to connect these points to each other. For points which are not articulation points, the greedy way to do it is to put the biggest number in the component of points that are already connected. This helps keep things organized and efficient. Now, let's think about the case of articulation points. If we've already decided to put a $1$ in the connected group before the articulation point, it's pretty clear that, in order to get the largest overall value, we should put the $1$ in the smallest connected component. And the remaining connected components will then share the largest value. In other words, when we pick the largest number for one component, the largest numbers for the other components will decrease at the same time. If we're sure that a particular component won't have the number $1$ placed in it, then the point we're looking at can only hold the value which is one more than the maximum value in the connected component formed by removing this point. It might sound a bit complicated, but I'll show you a picture to make it clearer. In simpler words, the value we put in that point is fixed. It's just the right amount to make sure it matches the sum of all the values in the connected group above it, instead of picking the smallest group. To make this work, we have to keep track of where the smallest value is located inside that connected component. The method we discussed is quite slow, around $O(n^3)$. Now, let's talk about how to make it much faster, around $O(n^2 log n)$. Firstly, for every cell, we keep a pointer that points to the information about its connected component. So, whenever we update any cell, the entire connected component gets updated automatically. When dealing with articulation points, it's important to quickly update the pointer information. One effective way is to use a clever merging technique. This involves simultaneously performing a breadth-first search on multiple connected components. If only one connected component remains incomplete in the search, we immediately stop all calculations. One of the things we need to do is to launch the BFS from the new connected components which arise after fixing a certain cell. In particular, we don't want to launch two parallel BFS which start in different cells but sooner or later are merged into one component. So among the $4$ side-neighbors of the cell being fixed, we need to segregate them based on the remaining connectivity, considering the removal of the current cell. To facilitate this segregation, we examine the 8 corner- or side-neighbors and analyze their DSU values. For instance, if all these DSU values are distinct from each other, it implies that the empty neighboring cells belong to a unified component. Conversely, if certain DSU values occur multiple times, it signifies the existence of a planar cycle that becomes linked through the cell being fixed. Consequently, cells within and outside this cycle must be assigned to separate connected components. To manage this, we iterate through pairs of $8-$neighbors sharing the same DSU value and classify the $4-$neighbors into those situated within the cycle and those outside it. During the pointer update process, we handle smaller connected components by updating their pointers in a straightforward manner. For larger connected components, we retain their original pointers and make necessary adjustments. It's easy to show that this approach updates pointers efficiently (each time a connected group is encountered in the search, its size at least doubles). This helps us achieve a time complexity of $O(n^2 log n)$. Next, we also need to determine whether two cells are part of the same connected component. This is necessary for calculating the situation represented in the previous image. This step is quite simple because we ensured earlier that pointers of different connected components are always different. So, all we need to do is compare the pointer values to check if two cells belong to the same connected component. For the connected components that share the largest value, there are several ways to handle them. One approach is to use the *int data type for the maximum value, so changing one value directly changes the shared value. Another method is to use a vector to store the pointers that share the value, and when updating, you iterate through this vector to update them. It's easy to prove that the maximum shared values can only exist in a maximum of $O(1)$ components simultaneously. This is because they only arise when cutting an articulation point in a connected component where the value is not $1$, and these components cannot merge together. So, the total time complexity will be $O(n^2logn)$.
|
[
"graphs",
"greedy"
] | 3,500
|
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
struct node {
int mx,sz;bool bg;
pair<int,int> mn;
vector<node*> cp;
void cln(){for(node* i:cp)i->cp.erase(find(i->cp.begin(),i->cp.end(),this));cp.clear();}
void fresh() {
if(!bg) return;
bg=false;int sum=0;node* lt=nullptr;
for(node* i:cp)if(i->bg){lt=i;sum++;}
if(sum==1){lt->mx=lt->sz;lt->bg=false;lt->cln();}
}
~node(){cln();}
};
int prevAns;
pair<int,int> fa[1002][1002];
pair<int,int> getfa(pair<int,int> x) {
if(fa[x.first][x.second]==x) return x;
return fa[x.first][x.second]=getfa(fa[x.first][x.second]);
}
void merge(pair<int,int> x,pair<int,int> y) {
pair<int,int> t=getfa(x);
fa[t.first][t.second]=getfa(y);
}
int n,q;
node* bk[1002][1002];
bool vis[1002][1002];
vector<pair<int,int>> dxy={{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}},xy={{-1,0},{0,1},{1,0},{0,-1}};
void Delta() {
cin >> n >> q;
bk[1][1]=new node{n*n,n*n,false,{0,0},{}};
for(int i=0;i<=n+1;++i)
for(int j=0;j<=n+1;++j) {
fa[i][j]={i,j};
if(i==0||j==0||i==n+1||j==n+1) {
fa[i][j]={0,0};
vis[i][j]=true;
bk[i][j]=nullptr;
} else {
bk[i][j]=bk[1][1];
vis[i][j]=false;
}
}
prevAns=0;
while(q--) {
int x,y,cnt=1;cin >> x >> y;
x^=prevAns;
y^=prevAns;
pair<int,int> Q[8];
int P[4]={0,0,0,0};
for(int i=0;i<8;++i)
Q[i]=getfa({x+dxy[i].first,y+dxy[i].second});
for(int i=0;i<8;++i)
for(int j=1;j<8;++j)
if(Q[i]==Q[(i+j)%8]) {
cnt++;
for(int k=(i+1)%8;k!=(i+j)%8;k=(k+1)%8)
if(k%2==1)
P[k/2]+=1ll<<cnt;
break;
}
vis[x][y]=true;
for(pair<int,int> i:dxy)
if(vis[x+i.first][y+i.second])
merge({x,y},{x+i.first,y+i.second});
bk[x][y]->fresh();
if((P[0]&P[1]&P[2]&P[3])==max({P[0],P[1],P[2],P[3]})) {
prevAns=bk[x][y]->mx;
cout << prevAns << ' ';
bk[x][y]->mx--;bk[x][y]->sz--;
for(node* i:bk[x][y]->cp) i->mx--;
if(bk[x][y]->sz==0) delete bk[x][y];
} else {
vector<pair<int,int>> s[4];
queue<pair<int,int>> q[4];
pair<int,int> id[4];
int cnt,dc=0;
{
vector<int> R;
for(int i=0;i<4;++i) R.push_back(P[i]);
sort(R.begin(),R.end());
R.resize(unique(R.begin(),R.end())-R.begin());
cnt=R.size();
for(int i=0;i<4;++i)
P[i]=lower_bound(R.begin(),R.end(),P[i])-R.begin();
}
for(int i=0;i<cnt;++i) {
for(int j=0;j<4;++j)
if(P[j]==i&&!vis[x+xy[j].first][y+xy[j].second]) {
id[i]={x+xy[j].first,y+xy[j].second};
if(!vis[id[i].first][id[i].second]) {
q[i].push(id[i]);
s[i].push_back(id[i]);
vis[id[i].first][id[i].second]=true;
dc++;
}
break;
}
}
while(dc>1)
for(int i=0;i<4;++i)
if(q[i].size()!=0) {
pair<int,int> t=q[i].front();q[i].pop();
for(int j=0;j<4;++j) {
pair<int,int> p={t.first+xy[j].first,t.second+xy[j].second};
if(!vis[p.first][p.second]) {
q[i].push(p);s[i].push_back(p);
vis[p.first][p.second]=true;
}
}
if(q[i].empty()) --dc;
}
vector<int> sm,bg;node* tp[4];
if(bk[x][y]->mx==bk[x][y]->sz) {
if(dc==1) {
for(int i=0;i<4;++i)
if(!q[i].empty()) bg.push_back(i);
else if(!s[i].empty()) sm.push_back(i);
for(int i:sm) {
tp[i]=new node{bk[x][y]->mx,(int)s[i].size(),false,{x,y},{}};
for(pair<int,int> j:s[i])
bk[j.first][j.second]=tp[i];
}
for(int i:sm) {
for(int j:sm)
if(i!=j) tp[i]->cp.push_back(tp[j]);
bk[x][y]->sz-=s[i].size();
}
prevAns=bk[x][y]->sz;
cout<< prevAns << ' ';
bk[x][y]->sz--;bk[x][y]->mx=bk[x][y]->sz;
} else {
int mxz=0;
for(int i=0;i<4;++i)
if(!s[i].empty()) {
sm.push_back(i);
mxz=max(mxz,(int)s[i].size());
}
prevAns=mxz+1;
cout << prevAns << ' ';
for(int i:sm) {
tp[i]=new node{bk[x][y]->mx,(int)s[i].size(),(int)s[i].size()==mxz,{x,y},{}};
for(pair<int,int> j:s[i])
bk[j.first][j.second]=tp[i];
}
for(int i:sm)
for(int j:sm)
if(i!=j) tp[i]->cp.push_back(tp[j]);
delete bk[x][y];
}
} else {
vector<node*> ar;vector<int> lt,ult;
if(dc==1) {
int sult=1,ty=bk[x][y]->mx;
pair<int,int> pmn=bk[x][y]->mn;
bk[x][y]->mn={x,y};bk[x][y]->sz--;
for(int i=0;i<4;++i)
if(!s[i].empty()) {
if(!q[i].empty()) {
bg.push_back(i);
tp[i]=bk[x][y];
}
else {
tp[i]=new node{bk[x][y]->mx,(int)s[i].size(),false,{x,y},{}};
sm.push_back(i);
bk[x][y]->sz-=(int)s[i].size();
for(pair<int,int> j:s[i])
bk[j.first][j.second]=tp[i];
}
}
pair<int,int> tmp=pmn;
for(pair<int,int> i:xy) {
node* t=bk[i.first+tmp.first][i.second+tmp.second];
if(t!=nullptr&&pair<int,int>{i.first+tmp.first,i.second+tmp.second}!=pair<int,int>{x,y}) {
ar.push_back(t);
}
}
vector<node*> cp=bk[x][y]->cp;
for(node* i:cp) i->cp.erase(find(i->cp.begin(),i->cp.end(),bk[x][y]));
bk[x][y]->cp.clear();
for(int i=0;i<4;++i) {
if(!s[i].empty()) {
if(id[i]==tmp||find(ar.begin(),ar.end(),bk[id[i].first][id[i].second])!=ar.end()) {
tp[i]->mn=pmn;
lt.push_back(i);
} else {
ult.push_back(i);
sult+=tp[i]->sz;
}
}
}
for(int i:ult)
for(int j:ult)
if(i!=j) tp[i]->cp.push_back(tp[j]);
for(node* i:cp) {
for(int j:lt) {
i->cp.push_back(tp[j]);
tp[j]->cp.push_back(i);
}
i->mx-=sult;
}
prevAns=ty-sult+1;
cout << prevAns << ' ';
for(int i:lt) {
for(int j:lt)
if(i!=j) tp[i]->cp.push_back(tp[j]);
tp[i]->mx-=sult;
}
} else {
pair<int,int> pmn=bk[x][y]->mn;
int sult=1;
for(int i=0;i<4;++i)
if(!s[i].empty()) {
tp[i]=new node{bk[x][y]->mx,(int)s[i].size(),false,{x,y},{}};
for(pair<int,int> j:s[i])
bk[j.first][j.second]=tp[i];
}
pair<int,int> tmp=bk[x][y]->mn;
for(pair<int,int> i:xy) {
node* t=bk[i.first+tmp.first][i.second+tmp.second];
if(t!=nullptr&&pair<int,int>{i.first+tmp.first,i.second+tmp.second}!=pair<int,int>{x,y})
ar.push_back(t);
}
for(int i=0;i<4;++i)
if(!s[i].empty()) {
if(id[i]==tmp||find(ar.begin(),ar.end(),bk[id[i].first][id[i].second])!=ar.end()) {
tp[i]->mn=pmn;
lt.push_back(i);
} else {
ult.push_back(i);
sult+=(int)s[i].size();
}
}
for(int i:ult)
for(int j:ult)
if(i!=j) tp[i]->cp.push_back(tp[j]);
for(node* i:bk[x][y]->cp) {
for(int j:lt) {
i->cp.push_back(tp[j]);
tp[j]->cp.push_back(i);
}
i->mx-=sult;
}
for(int i:lt) {
for(int j:lt)
if(i!=j) tp[i]->cp.push_back(tp[j]);
tp[i]->mx-=sult;
}
prevAns=bk[x][y]->mx-sult+1;
cout << prevAns << ' ';
delete bk[x][y];
}
}
for(int i=0;i<4;++i)
for(pair<int,int> j:s[i])
vis[j.first][j.second]=false;
}
bk[x][y]=nullptr;
}
set<node*> _;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
_.insert(bk[i][j]);
for(node* i:_)
if(i!=nullptr) delete i;
cout << endl;
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int T;cin >> T;
while(T--) Delta();
}
|
1866
|
A
|
Ambitious Kid
|
Chaneka, Pak Chanek's child, is an ambitious kid, so Pak Chanek gives her the following problem to test her ambition.
Given an array of integers $[A_1, A_2, A_3, \ldots, A_N]$. In one operation, Chaneka can choose one element, then increase or decrease the element's value by $1$. Chaneka can do that operation multiple times, even for different elements.
What is the minimum number of operations that must be done to make it such that $A_1 \times A_2 \times A_3 \times \ldots \times A_N = 0$?
|
In order to have the product of all elements be $0$, at least one element must be $0$. For each element $A_i$, the minimum number of operations to turn it into $0$ is $|A_i|$. Therefore, the minimum number of operations to turn at least one element into $0$ is the minimum value of $|A_i|$ out of all elements. Time complexity: $O(N)$
|
[
"math"
] | 800
| null |
1866
|
B
|
Battling with Numbers
|
On the trip to campus during the mid semester exam period, Chaneka thinks of two positive integers $X$ and $Y$. Since the two integers can be very big, both are represented using their prime factorisations, such that:
- $X=A_1^{B_1}\times A_2^{B_2}\times\ldots\times A_N^{B_N}$ (each $A_i$ is prime, each $B_i$ is positive, and $A_1<A_2<\ldots<A_N$)
- $Y=C_1^{D_1}\times C_2^{D_2}\times\ldots\times C_M^{D_M}$ (each $C_j$ is prime, each $D_j$ is positive, and $C_1<C_2<\ldots<C_M$)
Chaneka ponders about these two integers for too long throughout the trip, so Chaneka's friend commands her "Gece, deh!" (move fast) in order to not be late for the exam.
Because of that command, Chaneka comes up with a problem, how many pairs of positive integers $p$ and $q$ such that $\text{LCM}(p, q) = X$ and $\text{GCD}(p, q) = Y$. Since the answer can be very big, output the answer modulo $998\,244\,353$.
Notes:
- $\text{LCM}(p, q)$ is the smallest positive integer that is simultaneously divisible by $p$ and $q$.
- $\text{GCD}(p, q)$ is the biggest positive integer that simultaneously divides $p$ and $q$.
|
For a prime $k$, let $f_k(w)$ be the exponent of $k$ in the factorisation of $w$. In particular, if the factorisation of $w$ does not contain $k$, then $f_k(w)=0$. We can obtain that for any prime $k$, it holds that: $f_k(X)=f_k(\text{LCM}(p,q))=\max(f_k(p),f_k(q))$ $f_k(Y)=f_k(\text{GCD}(p,q))=\min(f_k(p),f_k(q))$ For each prime $k$, there are three cases: If $f_k(X)<f_k(Y)$, then it is impossible to assign the exponents since $\max(f_k(p),f_k(q))<\min(f_k(p),f_k(q))$ cannot be satsified. If $f_k(X)=f_k(Y)$, then there is only one way to assign the exponents, which is $f_k(p)=f_k(q)=f_k(X)$. If $f_k(X)>f_k(Y)$, then there are two ways to assign the exponents, which are the following: $f_k(p)=f_k(X)$, $f_k(q)=f_k(Y)$ $f_k(p)=f_k(Y)$, $f_k(q)=f_k(X)$ $f_k(p)=f_k(X)$, $f_k(q)=f_k(Y)$ $f_k(p)=f_k(Y)$, $f_k(q)=f_k(X)$ This means, if there is at least one prime $k$ such that $f_k(X)<f_k(Y)$, the answer is $0$. Otherwise, the answer is $2$ to the power of the number of primes $k$ such that $f_k(X)>f_k(Y)$. To maintain the values of $f_k(X)$ and $f_k(Y)$, you can use two pointers, the map data structure, or other methods. Time complexity: $O(N)$
|
[
"combinatorics",
"math",
"number theory"
] | 1,400
| null |
1866
|
C
|
Completely Searching for Inversions
|
Pak Chanek has a directed acyclic graph (a directed graph that does not have any cycles) containing $N$ vertices. Vertex $i$ has $S_i$ edges directed away from that vertex. The $j$-th edge of vertex $i$ that is directed away from it, is directed towards vertex $L_{i,j}$ and has an integer $W_{i,j}$ ($0\leq W_{i,j}\leq1$). Another information about the graph is that the graph is shaped in such a way such that each vertex can be reached from vertex $1$ via zero or more directed edges.
Pak Chanek has an array $Z$ that is initially empty.
Pak Chanek defines the function dfs as follows:
\begin{verbatim}
// dfs from vertex i
void dfs(int i) {
// iterate each edge of vertex i that is directed away from it
for(int j = 1; j <= S[i]; j++) {
Z.push_back(W[i][j]); // add the integer in the edge to the end of Z
dfs(L[i][j]); // recurse to the next vertex
}
}
\end{verbatim}
Note that the function does not keep track of which vertices have been visited, so each vertex can be processed more than once.
Let's say Pak Chanek does dfs(1) once. After that, Pak Chanek will get an array $Z$ containing some elements $0$ or $1$. Define an inversion in array $Z$ as a pair of indices $(x, y)$ ($x < y$) such that $Z_x > Z_y$. How many different inversions in $Z$ are there if Pak Chanek does dfs(1) once? Since the answer can be very big, output the answer modulo $998\,244\,353$.
|
Note that during the entire process, each time we do dfs(x) for the same value of $x$, the sequence of values appended to the end of $Z$ is always the same. So, for each vertex $x$, we want to obtain some properties about the sequence of values that will be appended if we do dfs(x). Since we want to calculate the number of inversions in a sequence of $0$ and $1$ elements, for each $x$, we want to calculate: $f_0[x]$: the number of $0$ elements appended. $f_1[x]$: the number of $1$ elements appended. $\text{inv}[x]$: the number of inversions completely within the sequence appended. Then, we can solve the problem using dynamic programming on directed acyclic graph. For a vertex $x$, we iterate each vertex $y$ that it is directed towards (following the order given in the input). If the integer in the current edge is $w$, then we temporarily add $f_w[y]$ by $1$ and if $w=1$, then we temporarily add $\text{inv}[y]$ by $f_0[y]$. Then, we do the following transitions: Add $\text{inv}[x]$ by $\text{inv}[y]+f_1(x)\times f_0(y)$. Add $f_0[x]$ by $f_0[y]$. Add $f_1[x]$ by $f_1[y]$. The answer is $\text{inv}[1]$. Time complexity: $O(N+\sum S)$
|
[
"dfs and similar",
"dp",
"graphs"
] | 1,900
| null |
1866
|
D
|
Digital Wallet
|
There are $N$ arrays, each array has $M$ positive integer elements The $j$-th element of the $i$-th array is $A_{i,j}$.
Initially, Chaneka's digital wallet contains $0$ money. Given an integer $K$. Chaneka will do $M-K+1$ operations. In the $p$-th operation, Chaneka does the following procedure:
- Choose any array. Let's say Chaneka chooses the $x$-th array.
- Choose an index $y$ in that array such that $p \leq y \leq p+K-1$.
- Add the value of $A_{x, y}$ to the total money in the wallet.
- Change the value of $A_{x, y}$ into $0$.
Determine the maximum total money that can be earned!
|
First, notice that since the initial value of all elements are positive, it is always optimal to always choose an element that has not been chosen before in each operation. Let's look at the $N$ arrays as a grid of $N$ rows and $M$ columns. We can solve this problem by iterating each column from left to right and using dynamic programming. Define the following: $\text{dp}[i][j]$: the maximum money Chaneka can earn by only taking the elements of the first $i$ columns in $j$ operations. When we iterate a new column $i$, we can choose to choose $c$ elements in that column for some value $c$ ($0\leq c\leq N$). If we choose to choose $c$ elements in that column, it is always the most optimal to choose the $c$ biggest elements in that column. Notice that if we only consider the first $i$ columns, in the optimal strategy, we must do a minimum of $i-K+1$ operations and a maximum of $i$ operations. So there are only a maximum of $K$ different values of $j$ we need to consider when calculating all values of $\text{dp}[i][j]$ for each new column $i$. For each $\text{dp}[i][j]$, there are only $N+1$ possibilities for the number of elements we choose in column $i$, and each of them can be handled in $O(1)$. Time complexity: $O(NMK)$
|
[
"dp",
"greedy"
] | 2,300
| null |
1866
|
E
|
Elevators of Tamem
|
There is a building named Taman Membeku (shortened as Tamem). The building has $N$ floors numbered from $1$ to $N$ from bottom to top. The only way to move between floors in the building is to use elevators. There are $3$ elevators available in Tamem, namely elevators $1$, $2$, and $3$.
Pak Chanek works as an elevator operator in Tamem. Pak Chanek will work for $Q$ days. Initially, each elevator is in floor $1$ and all elevators are on. On each day, exactly one of the following will happen:
- 1 x y – There is a person currently in floor $x$ who wants to go to floor $y$. ($1\leq x,y\leq N$; $x\neq y$)
- 2 p – Elevator $p$ changes state \textbf{at the start of the day}. If previously it is on, then it will turn off. If previously it is off, then it will turn on. ($1\leq p\leq3$)
For each day, Pak Chanek can control the movement of all elevators as he pleases. However, for each day where there is a person currently in floor $x$ who wants to go to floor $y$, among all elevator movements done by Pak Chanek, the following must happen:
- One elevator moves to floor $x$.
- The person gets into the elevator.
- The elevator moves to floor $y$.
- The person gets out of the elevator.
For each day, Pak Chanek can only move the elevators that are currently on. Note that, since a change in state happens at the start of the day, this means that an elevator that turns off on some day starts becoming unusable from that day itself. Conversely, an elevator that turns on on some day starts becoming usable from that day itself.
It is known that the electricity fee for each day is different. More specifically, on the $j$-th day, the fee needed to move one elevator up or down by one floor is $A_j$.
From the start, Pak Chanek already knows the electricity fees and the sequence of events that will happen on the $Q$ days, so Pak Chanek can operate the elevators strategically. What is the minimum possible electricity fee to fulfill all needs of the people who want to move between floors in Tamem? Note: in the end, each elevator does not have to go back to floor $1$.
|
First, let's solve the problem if there are no events of type $2$. We can solve this problem using dynamic programming. First, define: $\text{enter}[e]$: the initial floor of the person in the $e$-th event. $\text{exit}[e]$: the desired floor of the person in the $e$-th event. Then, define $\text{dp}[i][j][k]$ as the minimum electricity fee if: Elevator $1$ last moved at the $i$-th event (last at floor $\text{exit}[i]$). Elevator $2$ last moved at the $j$-th event (last at floor $\text{exit}[j]$). Elevator $3$ last moved at the $k$-th event (last at floor $\text{exit}[k]$). Let's say we have handled all events from the $1$-st to the ($e-1$)-th and now we want to handle the $e$-th event. This means the electricity fee for the the current condition is a value of $\text{dp}[i][j][k]$ with $\max(i,j,k)=e-1$ and we want to choose one elevator to handle the $e$-th event. If we choose elevator $1$, then it can move between the $i$-th day and $e$-th day to prepare for the person in the $e$-th event. So the minimum electricity fee for elevator $1$ to handle this is $|\text{exit}[i]-\text{enter}[e]|\times\min(A_i,A_{i+1},\ldots,A_e)+|\text{enter}[e]-\text{exit}[e]|\times A_e$. So we add that value with $\text{dp}[i][j][k]$ for a candidate value of $\text{dp}[e][j][k]$. We do a similar thing for elevators $2$ and $3$. Since we can precompute all values of $\min(A_i,A_{i+1},\ldots,A_e)$ naively, we can do the transition of each state in $O(1)$. In order to handle the events of type $2$, we can just write down the electricity fee for each elevator in each day. If that elevator is off on that day, we set the electricity fee of that elevator to be $\infty$. Time complexity: $O(Q^3)$
|
[
"dp"
] | 2,700
| null |
1866
|
F
|
Freak Joker Process
|
After the success of the basketball teams formed and trained by Pak Chanek last year (Basketball Together), Pak Chanek wants to measure the performance of each player that is considered as a superstar.
There are $N$ superstar players that have been trained by Pak Chanek. At the end of the season, some calculations will be made on the performance of the $N$ players using an international method. Each player has two values $A_i$ and $B_i$ where each represents the offensive and defensive value of that player.
Define $\text{RankA}(i)$ as the offensive ranking of the $i$-th player, whose value is $c+1$ with $c$ here representing the number of $j$ ($1 \leq j \leq N$) such that $A_j>A_i$. Define $\text{RankB}(i)$ as the defensive ranking of the $i$-th player, whose value is $c+1$ with $c$ here representing the number of $j$ ($1 \leq j \leq N$) such that $B_j>B_i$.
Define $\text{RankOverall}(i)$ as the overall ranking of the $i$-th player, whose value is $c+1$ with $c$ here representing the number of $j$ ($1 \leq j \leq N$) such that $\text{RankA}(j)+\text{RankB}(j)<\text{RankA}(i)+\text{RankB}(i)$.
During the next $Q$ days, exactly one event will happen on each day. Each event is one of the three following possibilities:
- 1 k c – If $c$ is +, then $A_k$ increases by $1$. If $c$ is -, then $A_k$ decreases by $1$. ($1\leq k\leq N$; $c$ is + or -)
- 2 k c – If $c$ is +, then $B_k$ increases by $1$. If $c$ is -, then $B_k$ decreases by $1$. ($1\leq k\leq N$; $c$ is + or -)
- 3 k – Pak Chanek wants to know the value of $\text{RankOverall}(k)$ at that moment. ($1\leq k\leq N$)
|
We can solve this problem using square root decomposition. First we group the events into $\sqrt Q$ blocks of sizes $\sqrt Q$ and solve for each block independently. For the start of each block, we can calculate all values of $A$ and $B$ easily. Additionally, we can calculate: $\text{biggerA}[x]$: the number of values of $A$ bigger than $x$. $\text{biggerB}[x]$: the number of values of $B$ bigger than $x$. So, $\text{RankA}(i)=\text{biggerA}[A_i]+1$ and $\text{RankB}(i)=\text{biggerB}[B_i]+1$. Notice that if we increase or decrease a value of $A$ by $1$, only one value of $\text{biggerA}$ changes. This means, the values of $\text{RankA}$ that change are only the changed $A$ value itself and a group of players with the same value of $A$. The same thing also applies for $B$, $\text{biggerB}$ and $\text{RankB}$. For a single block, let's simulate the changes in $A$ and $B$ and keep track of which players change value at least once in the block. Additionally, keep track of which indices in $\text{biggerA}$ and $\text{biggerB}$ change at least once in the block and denote these indices as special values in each of $\text{biggerA}$ and $\text{biggerB}$. For a single block, let's group the players into several types: A blue player is a player that changes value at least once in the block. An orange player is a non-blue player that has both of its $A$ and $B$ values as special values in each of $\text{biggerA}$ and $\text{biggerB}$. A yellow player is a non-blue player that has exactly one of its $A$ and $B$ values as a special value in $\text{biggerA}$ or $\text{biggerB}$ respectively. The rest are white players. Notice that there are at most $\sqrt Q$ blue players and at most $\sqrt Q$ special values in each of $\text{biggerA}$ and $\text{biggerB}$. Before simulating the events in the block, we must do some precomputations. For orange and white players only, calculate the following: $\text{smallerOverall}[x]$: the number of orange and white players with $\text{RankA}+\text{RankB}<x$. In order to maintain the value above, for orange players, calculate the following: $\text{cnt}[i][j]$: the number of orange players whose values of $A$ and $B$ are the $i$-th and $j$-th special values in $\text{biggerA}$ and $\text{biggerB}$ respectively. For each special value in $\text{biggerA}$, consider every yellow player that has that value of $A$. Notice that their values of $\text{RankB}$ will not change in the block. So we can precompute their values of $\text{RankB}$ and maintain them in a sorted array. We do a similar thing for the special values in $\text{biggerB}$ and their yellow players. After doing all those precomputations, we simulate each event in the block. We do each change while maintaining all values of $A$, $B$, $\text{biggerA}$, $\text{biggerB}$, and $\text{smallerOverall}$. To maintain $\text{smallerOverall}$ while considering orange players, notice that we can update it naively using the values of $\text{cnt}$ since there are at most $\sqrt Q$ different values of $\text{RankA}+\text{RankB}$ of orange players that change in each change event (because there are at most $\sqrt Q$ special values) and each change in $\text{RankA}+\text{RankB}$ only changes one value of $\text{smallerOverall}$. For each query event asking $\text{RankOverall}(k)$, do the following: Calculate $w=\text{RankA}(k)+\text{RankB}(k)$. For each blue player, calculate its $\text{RankA}+\text{RankB}$ and check if its value is smaller than $w$. For the orange and white players, just use the value of $\text{smallerOverall}(w)$. For the yellow players, for each special value, use binary search to find the number of players with $\text{RankA}+\text{RankB}<w$ (use $\text{RankB}<w-\text{RankA}$ for the special values in $\text{biggerA}$). The value of $\text{RankOverall}(k)$ can be calculated using all values above. Notice that there is a log factor for sorting and binary search. Time complexity: $O((N+Q)\sqrt{Q}\log N)$ Note: There is a $O((N+Q)\sqrt{Q})$ solution but the implementation sounds very heavy and tedious so it is not necessary to get accepted.
|
[
"binary search",
"data structures",
"sortings"
] | 3,100
| null |
1866
|
G
|
Grouped Carriages
|
Pak Chanek observes that the carriages of a train is always full on morning departure hours and afternoon departure hours. Therefore, the balance between carriages is needed so that it is not too crowded in only a few carriages.
A train contains $N$ carriages that are numbered from $1$ to $N$ from left to right. Carriage $i$ initially contains $A_i$ passengers. All carriages are connected by carriage doors, namely for each $i$ ($1\leq i\leq N-1$), carriage $i$ and carriage $i+1$ are connected by a two-way door.
Each passenger can move between carriages, but train regulation regulates that for each $i$, a passenger that \textbf{starts from carriage $i$} cannot go through more than $D_i$ doors.
Define $Z$ as the most number of passengers in one same carriage after moving. Pak Chanek asks, what is the minimum possible value of $Z$?
|
Suppose we set the maximum number of passengers in the same carriage to be at most $Z$. If there is a valid strategy to fit the constraint, doing the same strategy for every maximum number of passengers in the same carriage that is greater than $Z$ is also possible. Hence, we can try to find the answer by doing binary search the answer. Note that a passenger from carriage $i$ can move to carriage $j$ as long as $i-D_i \leq j \leq i+D_i$. So for each initial carriage $i$, create a segment $[i-D_i,i+D_i]$. Suppose we try to find a valid strategy for moving the passengers with the constraint that the maximum number of passengers in the same carriage is at most $Z$. We can solve this greedily. Iterate the destination carriages from left to right to be filled with passengers. The initial carriages that can fill the current carriage are only the ones whose segments contain the current carriage. Note that it is always optimal to take passengers from the segments with the smallest right endpoints first. We take the passengers until the current destination carriage reaches $Z$ passengers or there are no more segments to take from. If there exists a non-empty segment of an initial carriage that cannot donate its passengers anywhere, then it is impossible. We can do something like line sweep and prioritise the segments based on their right endpoints using priority queue or other data structures. Time complexity: $O(N\log N\log\max(A))$
|
[
"binary search",
"data structures",
"dp",
"flows",
"greedy"
] | 2,100
| null |
1866
|
H
|
Happy Sets
|
Define a set $A$ as a child of set $B$ if and only if for each element of value $x$ that is in $A$, there exists an element of value $x+1$ that is in $B$.
Given integers $N$ and $K$. In order to make Chaneka happy, you must find the number of different arrays containing $N$ sets $[S_1, S_2, S_3, \ldots, S_N]$ such that: - Each set can only contain zero or more different integers from $1$ to $K$. - There exists a way to rearrange the order of the array of sets into $[S'_1, S'_2, S'_3, \ldots, S'_N]$ such that $S'_i$ is a child of $S'_{i+1}$ for each $1\leq i\leq N-1$.
Print the answer modulo $998\,244\,353$.
Two sets are considered different if and only if there is at least one value that only occurs in one of the two sets.
Two arrays of sets are considered different if and only if there is at least one index $i$ such that the sets at index $i$ in the two arrays are different.
|
First, consider all possible arrays $S'$ (the array of sets after rearranging). For each valid $S'$, we want to find the number of ways to shuffle it. The answer to the original problem is equal to the sum of ways to shuffle each possible $S'$, since for each shuffled $S'$ it can be shown that there is only one way to rearrange it into a valid $S'$. Notice that a valid $S'$ always consists of a group of empty sets and a group of pairwise distinct non-empty sets. That means, if there are $e$ empty sets, then there are $\frac{N!}{e!}$ ways to shuffle $S'$. From the knowledge above, we can group all possible valid arrays $S'$ into groups based on the number of empty sets and count the number of valid arrays $S'$ in each group. Then for each group, multiply the number of valid arrays $S'$ by the number of ways to shuffle $S'$ for that number of empty sets, then add it to the answer. Now, define $f(e)$ as the number of valid arrays $S'$ with exactly $e$ empty sets. Define $g(e)$ as the number of valid arrays $S'$ with at least $e$ empty sets. We get that $f(e)=g(e)-g(e+1)$. Let's calculate $g(e)$. For an array of sets $S'$, we can consider it as a set of pairs $(p,x)$, where each pair $(p,x)$ denotes that $S'_p$ contains $x$. Notice that for some value $x$: $(N-1,x-1)$ can only exist if $(N,x)$ exists. $(N-2,x-2)$ can only exist if $(N-1,x-1)$ exists. $(N-3,x-3)$ can only exist if $(N-2,x-2)$ exists. And so on. Therefore, we can group the possible pairs into groups $[(N,x),(N-1,x-1),(N-2,x-2),\ldots]$ and for every group, if it has $c$ pairs, then there are only $c+1$ configurations for that group (only the first $i$ pairs exist for every $0\leq i\leq c$). The total number of configurations is the product of $c+1$ for every group. Consider the size of each group. There are only $K$ groups, each starts with $(N,x)$ for every $1\leq x\leq K$. The group that starts with $(N,x)$ has $\min(x,N-e)$ possible pairs. That means, the size of each group is $[1,2,3,\ldots,N-e-2,N-e-1,N-e,N-e,N-e,\ldots]$. Therefore, $g(e)=(N-e+1)!(N-e+1)^{(K-(N-e))}$. We can calculate all values of $g(e)$ using factorial precomputation and binary exponentiation. Time complexity: $O(N\log K)$
|
[
"combinatorics"
] | 2,100
| null |
1866
|
I
|
Imagination Castle
|
Given a chessboard of size $N \times M$ ($N$ rows and $M$ columns). Each row is numbered from $1$ to $N$ from top to bottom and each column is numbered from $1$ to $M$ from left to right. The tile in row $r$ and column $c$ is denoted as $(r,c)$. There exists $K$ distinct special tiles on the chessboard with the $i$-th special tile being tile $(X_i,Y_i)$. It is guaranteed that tile $(1,1)$ is not a special tile.
A new chess piece has been invented, which is the castle. The castle moves similarly to a rook in regular chess, but slightly differently. In one move, a castle that is on some tile can only move to another tile in the same row or in the same column, but only in the right direction or the down direction. Formally, in one move, the castle on tile $(r,c)$ can only move to tile $(r',c')$ if and only if one of the following two conditions is satisfied:
- $r'=r$ and $c'>c$.
- $c'=c$ and $r'>r$.
Chaneka and Bhinneka will play a game. In the beginning of the game, there is a castle in tile $(1,1)$. The two players will play alternatingly with Chaneka going first. In one turn, the player on that turn must move the castle following the movement rules of the castle.
If a player moves the castle to a special tile on her turn, then that player wins the game and the game ends. If on a turn, the castle cannot be moved, the player on that turn loses and the game ends.
Given the size of the board and the locations of each special tile. Determine the winner of this game if Chaneka and Bhinneka plays optimally.
|
Define a winning tile as a tile where if a player starts a turn with the castle in that tile, she will have a strategy to win. Define a losing tile as a tile where if a player starts a turn with the castle in that tile, no matter what she does, the other player will always have a strategy to win. We can see each special tile as a losing tile. We can solve the problem by finding which tiles are the losing tiles. We can do that by doing "backtrack" from the bottom right corner of the board. Maintain a pointer $(r,c)$ which means that we have solved all tiles $(r',c')$ with $r'>r$ or $c'>c$. So initially, $(r,c)=(N,M)$ (no tiles are solved). There are three cases for each iteration of the pointer: If there is at least one special tile $(r',c')$ satisfying $r'=r$ and $c'\geq c$, then all non-special tiles $(r' ',c' ')$ satisfying $r' '=r$ and $c' '<c$ are winning tiles. Then, move $(r,c)$ one step up. If there is at least one special tile $(r',c')$ satisfying $c'=c$ and $r'\geq r$, then all non-special tiles $(r' ',c' ')$ satisfying $c' '=c$ and $r' '<r$ are winning tiles. Then, move $(r,c)$ one step to the left. If neither of the cases above holds, then $(r,c)$ itself is a losing tile and all non-special tiles $(r' ',c' ')$ satisfying one of the following is a winning tile: $r' '=r$ and $c' '<c$ $c' '=c$ and $r' '<r$ Then, move $(r,c)$ one step up and to the left. $r' '=r$ and $c' '<c$ $c' '=c$ and $r' '<r$ Chaneka wins if $(1,1)$ is a winning tile. Bhinneka wins if $(1,1)$ is a losing tile. Time complexity: $O(N+M+K)$
|
[
"dp",
"games",
"two pointers"
] | 2,300
| null |
1866
|
J
|
Jackets and Packets
|
Pak Chanek has $N$ jackets that are stored in a wardrobe. Pak Chanek's wardrobe has enough room for two stacks of jackets, namely the left stack and the right stack. Initially, all $N$ jackets are in the left stack, while the right stack is empty. Initially, the $i$-th jacket from the top of the left stack has colour $C_i$.
Pak Chanek wants to pack all of those jackets into some packets, such that the jackets in the same packet has the same colour. However, it is possible for two jackets with the same colour to be in different packets.
Pak Chanek can do two kinds of operations:
- Pak Chanek can pick \textbf{any number of jackets from the top} from \textbf{one stack} as long as the colour is the same, then take those jackets out of the stack and pack them into a packet. This packing operation takes $X$ minutes, no matter how many jackets are packed.
- Pak Chanek can move \textbf{one topmost jacket} from one stack to the top of the other stack (\textbf{possibly right to left or left to right}). This moving operation takes $Y$ minutes.
Determine the minimum time to pack all jackets!
|
Instead of looking at the two stacks as two separate arrays, consider them as a single array $A$ whose elements are the colours of the jackets in the right stack from bottom to top, then the colours of the jackets in the left stack from top to bottom. Also maintain a pointer that indicates the separation point between the right and left stack parts of the the array (the pointer is located at the gap between two adjacent elements instead of at an element). So, $A$ is initially equal to $C$ with the pointer located directly to the left of the leftmost element. Notice that a movement operation is equivalent to moving the pointer one step to the left or right. A packing operation is equivalent to erasing a contiguous group of elements of the same value directly to the left or to the right of the pointer. We can solve this problem using dynamic programming. Define the following values: $\text{dp}[l][r]$: the minimum time to erase all elements if the array is $A[l..r]$ and the pointer is located directly to the left of the leftmost element. Now, consider the two transition cases for $\text{dp}[l][r]$. If $A_l$ does not get erased in the same operation as $A_r$, then optimally, there must be a prefix of $A[l..r]$ (let's say it is $A[l..p]$) that gets entirely erased before doing anything with the rest of $A[l..r]$. For a particular partition of prefix, we must solve for that prefix, then solve for the rest. So to calculate for this case, we must find the minimum of all values of $\text{dp}[l][p]+\text{dp}[p+1][r]$. If $A_l$ gets erased in the same operation as $A_r$ (can only happen when $A_l=A_r$), then there must be a set of disjoint segments entirely within segment $[l,r]$ where every single one of those segment gets entirely erased before the one single packing operation that simultaneously erases $A_l$ and $A_r$. It must hold that every element outside of the segments has the same value as $A_l$ and $A_r$. For the case above, notice that in the optimal way, we repeatedly iterate the pointer directly to the left of each segment and completely erase the segment before going for the next segment. After all that, we can choose to move the pointer either directly to the left of $A_l$ or to the right of $A_r$, then erase the rest of $A[l..r]$ in one packing operation. To handle this, we define two new DP values for the case where $A_l$ and $A_r$ get erased in the same operation: $\text{dpA}[l][r]$: the minimum time for this case if after erasing the last segment, the pointer moves to the right of $A_r$. $\text{dpB}[l][r]$: the minimum time for this case if after erasing the last segment, the pointer moves to the left of $A_l$. The transitions for $\text{dpA}$ are: If all elements of $A[l..r]$ have the same value, then $\text{dpA}[l][r]=Y\times(r-l+1)+X$ (the pointer moves to the very right, then erases all elements). Else, then we check every possible index $p$ for the next index in $A[l..r]$ not in the set of segments after $l$. So $\text{dpA}[l][r]$ is the minimum of $Y+\text{dpA}[l+1][r]$ and all values of $Y+\text{dp}[l+1][p-1]+\text{dpA}[p][r]$ for all $A_p=A_l$ (the pointer moves one step to the right, then solves $A[l+1..p-1]$, then continues to solve the rest of $A[l..r]$ knowing that $A_l$ will get erased along with $A_r$ in the end). The transitions for $\text{dpB}$ are: If all elements of $A[l..r]$ have the same value, then $\text{dpB}[l][r]=X$ (the pointer moves to the very left, then erases all elements). Else, then we check every possible index $p$ for the next index in $A[l..r]$ not in the set of segments after $l$. So $\text{dpB}[l][r]$ is the minimum of $Y\times2+\text{dpB}[l+1][r]$ and all values of $Y\times2+\text{dp}[l+1][p-1]+\text{dpB}[p][r]$ for all $A_p=A_l$ (the pointer moves one step to the right, then solves $A[l+1..p-1]$, then continues to solve the rest of $A[l..r]$, then moves the pointer all the way to the left passing through $A_l$ once again, before erasing the initial $A_l$ and $A_r$ in one packing operation). Time complexity: $O(N^3)$
|
[
"dp"
] | 2,800
| null |
1866
|
K
|
Keen Tree Calculation
|
There is a tree of $N$ vertices and $N-1$ edges. The $i$-th edge connects vertices $U_i$ and $V_i$ and has a length of $W_i$.
Chaneka, the owner of the tree, asks you $Q$ times. For the $j$-th question, the following is the question format:
- $X_j$ $K_j$ – If each edge that contains vertex $X_j$ has its length multiplied by $K_j$, what is the diameter of the tree?
Notes:
- Each of Chaneka's question is \textbf{independent}, which means the changes in edge length do not influence the next questions.
- The diameter of a tree is the maximum possible distance between two different vertices in the tree.
|
First, calculate the diameter of the initial tree. For a question involving some vertex $p$. There are only two cases to consider: The diameter is the same as the diameter of the initial tree. The diameter goes through vertex $p$. If the diameter goes through vertex $p$, then the diameter consists of two paths, each of them is from vertex $p$ to some other vertex, but the vertex immediately next to vertex $p$ in the two paths must be different. Consider a vertex $p$. Let $q_1,q_2,q_3,\ldots,q_{\text{deg}[p]}$ be the vertices adjacent to $p$ with $\text{deg}[p]$ being the degree of $p$. For each $q_i$, calculate: $m_i$: The length of the edge connecting vertices $p$ and $q_i$. $c_i$: The maximum length of a path from $q_i$ to another vertex that does not pass through $p$. All values of $c_i$ can be calculated using dynamic programming on tree with rerooting. Notice that for a query involving vertex $p$ with a multiplier of $x$. The diameter that goes through vertex $p$ is the sum of the two biggest values of $m_i\times x+c_i$. From this knowledge, we can consider each vertex $q_i$ as a line equation of $y=m_i\times x+c_i$. In order to be able to find the biggest value of $m_i\times x+c_i$ for any $x$, we maintain the maximum convex hull out of all those lines and we answer each query using binary search. In order to be able to find the second biggest value of $m_i\times x+c_i$ for any $x$, we maintain several more convex hulls. Let $h_1,h_2,h_3,\ldots$ be the indices of the lines in the maximum convex hull sorted from the smallest $m$ to the biggest $m$. Then, for each $h_j$, we maintain a new maximum convex hull out of all lines $i$ with $m_{h_{j-1}}\leq m_i\leq m_{h_{j+1}}$ other than line $h_j$. We do that to maintain the candidate lines of the second biggest value if the biggest value is taken from line $h_j$. This can be done because lines $h_{j-1}$ and $h_{j+1}$ are two of the candidate lines, so the only other possible candidate lines that can produce bigger values in this particular location are lines $i$ with $m_{h_{j-1}}\leq m_i\leq m_{h_{j+1}}$. Each line can only be in at most three different convex hulls, so the total number of lines to be considered in the making of all convex hulls for vertex $p$ is $O(\text{deg}[p]$). So in total, for all vertices $p$, the total number of lines is $O(N)$. Time complexity: $O((N+Q)\log N)$
|
[
"binary search",
"data structures",
"dp",
"geometry",
"graphs",
"implementation",
"trees"
] | 2,500
| null |
1866
|
L
|
Lihmuf Balling
|
After working at a factory (Lihmuf Sorting), Lihmuf wants to play a game with his good friend, Pak Chanek. There are $N$ boxes numbered from $1$ to $N$. The $i$-th box contains $i$ balls. Pak Chanek and Lihmuf will play a game using those boxes.
There will be $N$ turns numbered from $1$ to $N$. On each turn, Pak Chanek chooses one box and takes all balls from that box, then Lihmuf does the same thing for one box he chooses (it is possible that the two chosen boxes are the same).
Given an integer $M$. Before the game begins, Lihmuf must choose an integer $K$ satisfying $1 \leq K \leq M$. It is known that on the $j$-th turn, Pak Chanek will choose the $j$-th box, while Lihmuf will choose the $y$-th box, with $y=((j \times K - 1) \bmod N) + 1$. Help Lihmuf choose the correct value of $K$ so that he will get as many balls as possible! If there are more than one possible values of $K$ that result in the maximum total balls, find the minimum such value of $K$.
Keep in mind that each box can be chosen more than once, but after a box is chosen for the first time, the box becomes empty.
|
To solve this, we just need to find the total number of balls Lihmuf will earn for each possible value of $K$ from $1$ to $M$. If $K=1$, then Lihmuf gets $0$ balls. If $K>1$ and $K$ is a factor of $N$, then Lihmuf will get all balls in the boxes with indices that are multiples of $K$. If $K$ is not coprime to $N$, then Lihmuf can only possibly get the balls in the boxes with indices that are multiples of a factor of $N$ greater than $1$, which is already covered by the case above, so this is always not optimal. Then, that leaves us with the case where $K>1$ and $K$ is coprime to $N$. Notice that in this case, Lihmuf will access each box exactly once. For this case, consider the sequence of indices of the boxes accessed by Lihmuf. We can group this sequence into exactly $K$ groups, where each group consists of a sequence of indices $c$, $c+K$, $c+2K$, $c+3K$, and so on for some value $1\leq c\leq K$. For each group, while Lihmuf is accessing the boxes in the group, at the same time, Pak Chanek is accessing boxes $d$, $d+1$, $d+2$, $d+3$, and so on for some value $d$. For this case, since $K>1$, that means at some point, Lihmuf will overtake Pak Chanek in the index of the box he accesses. That happens once $c+K\times p>d+p$ for some $p\geq0$. From that point on, Lihmuf will get all balls in the boxes he accesses in that group. The number of balls earned by Lihmuf in each group can be calculated in $O(1)$ using simple math and using the formula for the sum of an arithmetic sequence. The total time complexity to calculate for a single value of $K$ is $O(K)$, so the total time complexity is $O(M^2)$. Time complexity: $O(M^2)$
|
[
"binary search",
"brute force",
"math"
] | 2,400
| null |
1866
|
M
|
Mighty Rock Tower
|
Pak Chanek comes up with an idea in the midst of boredom to play a game. The game is a rock tower game. There is a big rock that is used as a base. There are also $N$ small identical rocks that Pak Chanek will use to build a rock tower with a height of $N$ above the base rock.
Initially, there are no small rocks that are located above the base rock. In other words, the height of the tower above the base rock is initially $0$. In one move, Pak Chanek can place one small rock onto the top of the tower which makes the height of the tower above the base rock increase by $1$. Each time Pak Chanek place one small rock, the following will happen after the small rock is placed:
- Let's say $x$ is the height of the tower above the base rock \textbf{right after the small rock is placed}.
- There is a probability of $P_x$ percent that the topmost rock falls.
- If $x \geq 2$ and the topmost rock falls, then there is another probability of $P_x$ percent that the $2$-nd topmost rock also falls.
- If $x \geq 3$ and the $2$-nd topmost rock falls, then there is another probability of $P_x$ percent that the $3$-rd topmost rock also falls.
- If $x \geq 4$ and the $3$-rd topmost rock falls, then there is another probability of $P_x$ percent that the $4$-th topmost rock also falls.
- And so on.
If the tower successfully reaches a height of $N$ without any rocks falling after that, then the game is ended.
If given an integer array $[P_1, P_2, \ldots, P_N]$, what is the expected value of the number of moves that Pak Chanek needs to do to end the game? It can be proven that the expected value can be represented as an simple fraction $\frac{P}{Q}$ where $Q$ is coprime to $998\,244\,353$. Output the value of $P \times Q^{-1}$ modulo $998\,244\,353$.
|
Let $f(x)$ be the the expected number of moves to turn a tower of height $x-1$ into $x$. In order to calculate that, let's say the tower's current height is $x-1$ and we want to make it into $x$. If we place one small rock, then the following cases can happen: With a probability of $(P_x\%)^k(1-P_x\%)$, exactly $k$ rocks fall for some $0\leq k\leq x-1$. With a probability of $(P_x\%)^x$, exactly $x$ rocks fall. After moving once, if exactly $k$ rocks fall for some $1\leq k\leq x$, then the expected number of moves to make the height of the tower become $x$ is $f(x)+f(x-1)+f(x-2)+\ldots+f(x-k+1)$. From the knowledge above, we get the following formula: $f(x)=1+(P_x\%)^x(f(x)+f(x-1)+\ldots+f(1))$$+\sum_{k=1}^{x-1}(P_x\%)^k(1-P_x\%)(f(x)+f(x-1)+\ldots+f(x-k+1))$ If we split each term of $f$ and count the contribution for each of them in the sum, then we will get the following: $f(x)=1+\sum_{k=1}^x(P_x\%)^kf(x-k+1)$ $f(x)=1+(P_x\%)f(x)+\sum_{k=2}^x(P_x\%)^kf(x-k+1)$ $(1-P_x\%)f(x)=1+\sum_{k=2}^x(P_x\%)^kf(x-k+1)$ $f(x)=\frac{1+\sum_{k=2}^x(P_x\%)^kf(x-k+1)}{1-P_x\%}$ Now, we must know how to calculate $\sum_{k=2}^x(P_x\%)^kf(x-k+1)$ quickly. Notice that there are only $100$ possible different values of $P_x$. So we can precompute the values $S$ with $S_{i,j}=\sum_{k=2}^j(i\%)^kf(j-k+1)$ for every $0\leq i\leq99$. We can calculate each value in $O(1)$ from each previous value if we precompute the values of $i\%$ for every $0\leq i\leq99$. The answer to the original problem is $f(1)+f(2)+f(3)+\ldots+f(N)$. Time complexity: $O(N\max(P))$
|
[
"brute force",
"combinatorics",
"dp",
"math",
"probabilities"
] | 2,400
| null |
1867
|
A
|
green_gold_dog, array and permutation
|
green_gold_dog has an array $a$ of length $n$, and he wants to find a permutation $b$ of length $n$ such that the number of distinct numbers in the element-wise difference between array $a$ and permutation $b$ is maximized.
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).
The element-wise difference between two arrays $a$ and $b$ of length $n$ is an array $c$ of length $n$, where $c_i$ = $a_i - b_i$ ($1 \leq i \leq n$).
|
Let's subtract $n$ from the minimum number, subtract $n - 1$ from the second minimum, $n - 2$ from the third $\ldots$, and subtract $1$ from the maximum. Then the number of distinct elements will be $n$. Obviously, it is impossible to achieve a better result. Let's prove that the number of distinct elements will be equal to $n$. Suppose $c_i = c_j$, then without loss of generality, let's say that $b_i > b_j$, then $a_i \leq a_j$, which means $c_i = a_i - b_i$ < $a_j - b_j = c_j$. Contradiction. Time Complexity: $O(n \log n)$ per test case.
|
[
"constructive algorithms",
"sortings"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve() {
ll n;
cin >> n;
vector<pair<ll, ll>> arr(n);
for (ll i = 0; i < n; i++) {
ll x;
cin >> x;
arr[i].first = x;
arr[i].second = i;
}
vector<ll> ans(n);
sort(arr.begin(), arr.end());
reverse(arr.begin(),arr.end());
for (ll i = 0; i < n; i++) {
ans[arr[i].second] = i + 1;
}
for (auto i : ans) {
cout << i << ' ';
}
cout << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll t = 1;
cin >> t;
for (ll i = 0; i < t; i++) {
solve();
}
}
|
1867
|
B
|
XOR Palindromes
|
You are given a binary string $s$ of length $n$ (a string that consists only of $0$ and $1$). A number $x$ is good if there exists a binary string $l$ of length $n$, containing $x$ ones, such that if each symbol $s_i$ is replaced by $s_i \oplus l_i$ (where $\oplus$ denotes the bitwise XOR operation), then the string $s$ becomes a palindrome.
You need to output a binary string $t$ of length $n+1$, where $t_i$ ($0 \leq i \leq n$) is equal to $1$ if number $i$ is good, and $0$ otherwise.
A palindrome is a string that reads the same from left to right as from right to left. For example, 01010, 1111, 0110 are palindromes.
|
Firstly, a string is a palindrome if and only if for any $i$ ($1 \leq i \leq n$) $s_i = s_{n-i+1}$ (because when reversed, $s_i$ becomes $s_{n-i+1}$). We can divide the characters into pairs, where each pair consists of $s_i$ and $s_{n-i+1}$. If $s_i = s_{n-i+1}$, then we need to have $l_i = l_{n-i+1}$ in order to obtain equal elements after XOR. Therefore, either $l_i = l_{n-i+1} = 0$ (with $0$ ones) or $l_i = l_{n-i+1} = 1$ (with $2$ ones). If $s_i \neq s_{n-i+1}$, then $l_i \neq l_{n-i+1}$ must hold ($1$ one in any case). Additionally, if $n$ is odd, then $l_{n/2+1}$ can be either $0$ or $1$ (with $0$ or $1$ ones). We can iterate over the number of pairs where $l_i = l_{n-i+1}$ will have two ones, as well as whether there will be a one in the center or not. This way, we can obtain all possible numbers of ones in $l$, i.e., all good $i$. Time Complexity: $O(n)$ per test case.
|
[
"bitmasks",
"constructive algorithms",
"strings"
] | 1,100
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
string s;
cin >> s;
string t(n+1,'0');
int ans = 0;
int max_1 = 0;
int max_2 = 0;
for(int i = 0;i <= n/2-1;++i)
{
if(s[i] == s[n-i-1])
max_2++;
else
ans++;
}
if(n%2 == 1)
max_1++;
for(int j = 0;j <= max_2;++j)
{
for(int k = 0;k <= max_1;++k)
{
t[ans + j*2 + k] = '1';
}
}
cout << t << "\n";
}
}
|
1867
|
C
|
Salyg1n and the MEX Game
|
\textbf{This is an interactive problem!}
salyg1n gave Alice a set $S$ of $n$ distinct integers $s_1, s_2, \ldots, s_n$ ($0 \leq s_i \leq 10^9$). Alice decided to play a game with this set against Bob. The rules of the game are as follows:
- Players take turns, with Alice going first.
- In one move, Alice adds one number $x$ ($0 \leq x \leq 10^9$) to the set $S$. The set $S$ must not contain the number $x$ at the time of the move.
- In one move, Bob removes one number $y$ from the set $S$. The set $S$ must contain the number $y$ at the time of the move. Additionally, the number $y$ must be \textbf{strictly smaller} than the last number added by Alice.
- The game ends when Bob cannot make a move or after $2 \cdot n + 1$ moves (in which case Alice's move will be the last one).
- The result of the game is $\operatorname{MEX}\dagger(S)$ ($S$ at the end of the game).
- Alice aims to maximize the result, while Bob aims to minimize it.
Let $R$ be the result when both players play optimally. \textbf{In this problem, you play as Alice against the jury program playing as Bob.} Your task is to implement a strategy for Alice such that the result of the game is always at least $R$.
$\dagger$ $\operatorname{MEX}$ of a set of integers $c_1, c_2, \ldots, c_k$ is defined as the smallest non-negative integer $x$ which does not occur in the set $c$. For example, $\operatorname{MEX}(\{0, 1, 2, 4\})$ $=$ $3$.
|
The correct strategy for Alice is to add the number $\operatorname{MEX}(S)$ to the set $S$ on the first move, and add the last removed number on the remaining moves. Let m = $\operatorname{MEX}(S \cup {\operatorname{MEX}(S)})$, at the start of the game. In other words, m is equal to the second $\operatorname{MEX}$ of the set $S$. $m \geq 1$. Notice that after the first move, $\operatorname{MEX}(S) = m$, and no matter what Bob removes, we will return that number to the set, so the result of the game will always be equal to $m$. Let's prove that with Bob's optimal play, we cannot achieve a result greater than m. Notice that the $\operatorname{MEX}$ of a set is the largest number k such that all numbers from $0$ to $k-1$ inclusive are present in the set. Let $p_i$ be the number of numbers from $0$ to $i-1$ inclusive that appear in the set $S$. Then $\operatorname{MEX}(S)$ is equal to the maximum $i$ such that $p_i = i$. If Bob removes the number $y$ during his turn, he decreases all values $p_i$ where $i > y$ by $1$. So, if $y = \operatorname{min}(S)$, Bob decreases all non-zero values $p_i$ by $1$. Alice can increase some values $p_i$ by $1$ during her turn. Therefore, after Alice's first move, $\operatorname{MEX}(S)$ will no longer increase if Bob keeps removing the minimum, because no non-zero values of $p_i$ will increase (Bob decreases them by $1$, and Alice increases them by at most $1$). It is obvious that in order to maximize $\operatorname{MEX}(S)$ after the first move, Alice needs to add the number $\operatorname{MEX}(S)$ to the set $S$. We have proven that $R \leq m$ and provided a strategy that achieves a result of $m$. Time Complexity: $O(n)$ per test case.
|
[
"constructive algorithms",
"data structures",
"games",
"greedy",
"interactive"
] | 1,300
|
#include <iostream>
#include <vector>
using namespace std;
void solve() {
int n;
cin >> n;
vector<int> s(n);
for (int i = 0; i < n; ++i)
cin >> s[i];
int mex = -1;
for (int i = 0; i < n; ++i) {
if (i == 0 && s[i] != 0) {
mex = 0;
break;
}
if (i > 0 && s[i] != s[i - 1] + 1) {
mex = s[i - 1] + 1;
break;
}
}
if (mex == -1)
mex = s[n - 1] + 1;
cout << mex << endl;
int y;
cin >> y;
while (y != -1) {
cout << y << endl;
cin >> y;
}
}
int main() {
int t;
cin >> t;
while (t--)
solve();
return 0;
}
|
1867
|
D
|
Cyclic Operations
|
Egor has an array $a$ of length $n$, initially consisting of zeros. However, he wanted to turn it into another array $b$ of length $n$.
Since Egor doesn't take easy paths, only the following operation can be used (possibly zero or several times):
- choose an array $l$ of length $k$ ($1 \leq l_i \leq n$, all $l_i$ are \textbf{distinct}) and change each element $a_{l_i}$ to $l_{(i\%k)+1}$ ($1 \leq i \leq k$).
He became interested in whether it is possible to get the array $b$ using only these operations. Since Egor is still a beginner programmer, he asked you to help him solve this problem.
The operation $\%$ means taking the remainder, that is, $a\%b$ is equal to the remainder of dividing the number $a$ by the number $b$.
|
If $k = 1$, then we can change $b_i$ to $i$, so the answer is YES only if $b_i = i$, otherwise the answer is NO. Otherwise, let's build an undirected graph with $n$ vertices and edges ($i, b_i$). Any component of this graph will look like a cycle (possibly of size $1$) to each vertex of which a tree is attached (possibly empty). Let's assume that there are $x$ vertices in a component, then there are also $x$ edges in it (since each vertex has exactly one outgoing edge). We can construct a depth-first search (DFS) tree for this component, which will have $x - 1$ edges. Now, when we add the remaining edge ($u, v$), a cycle is formed in the component (formed by the edge ($u, v$) and the path between $u$ and $v$ in the DFS tree). Each vertex will have a tree attached to it, because before adding the edge, we had a tree. Now it is claimed that if the cycle in each component has a size exactly $k$, then the answer is YES, otherwise NO. Let's first consider the situation where the size of the cycle in some component is not $k$. Let the cycle contain vertices $v_1, v_2, \cdots, v_x$ in that order. Now let's look at the last operation in which one of the $l_i$ was equal to some element from the cycle. If the size of the cycle is less than $k$, then in the last operation there will be at least one vertex not from the cycle, which means that at least one vertex from the cycle will be replaced by a number that is not the next vertex in the cycle, which is incorrect because each vertex from the cycle should be replaced by the next vertex after it. If the size of the cycle is greater than $k$, then we will have a vertex from the cycle that will be replaced by a vertex that is not the next vertex in the cycle (otherwise we would have used all the vertices of the cycle, and there are more than $k$ of them). Therefore, in any case, there is no valid last operation with vertices from the cycle, so the answer is NO. If the size of the cycle in a component is equal to $k$, then we can apply the following algorithm: While there is at least one vertex $v$ in the component that is a leaf, we will perform the operation with $l = [v, b_v, b_{b_v}, \cdots]$ (all elements are distinct because we will enter the cycle and it has a size of $k$). After this operation, we will have $a_v = b_v$, and we can remove vertex $v$ (it had only $1$ outgoing edge). When only the cycle remains, we can apply the operation for the vertices in the cycle, preserving the order, and then for all vertices in the component, we will have $a_v = b_v$. By doing this for all components, we will get $a = b$, which is what we wanted, so the answer is YES. Time Complexity: $O(n)$ per test case.
|
[
"brute force",
"constructive algorithms",
"dfs and similar",
"graphs",
"greedy",
"implementation"
] | 1,800
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while(t--)
{
int n,k;
cin >> n >> k;
int b[n];
int vis[n];
for(int j = 0;j < n;++j)
{
cin >> b[j];
vis[j] = 0;
}
if(k == 1)
{
int no = 0;
for(int j = 0;j < n;++j)
{
if(b[j] != j+1)
{
no = 1;
}
}
cout << (no ? "NO\n" : "YES\n");
continue;
}
int num[n];
int no = 0;
int tgr = 1;
for(int j = 0;j < n;++j)
{
if(!vis[j])
{
int ind = j;
int cnum = 0;
while(!vis[ind])
{
vis[ind] = tgr;
num[ind] = cnum++;
ind = b[ind]-1;
}
if(vis[ind] != tgr)
{
tgr++;
continue;
}
if(cnum-num[ind] != k)
{
no = 1;
break;
}
tgr++;
}
}
cout << (no ? "NO\n" : "YES\n");
}
}
|
1867
|
E1
|
Salyg1n and Array (simple version)
|
\textbf{This is the simple version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 100 queries. You can make hacks only if both versions of the problem are solved.}
\textbf{This is an interactive problem!}
salyg1n has given you a positive integer $k$ and wants to play a game with you. He has chosen an array of $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$). You must print $a_1 \oplus a_2 \oplus \ldots \oplus a_n$, where $\oplus$ denotes the bitwise XOR operation. You can make queries of the following type:
- $?$ $i$: in response to this query, you will receive $a_i \oplus a_{i + 1} \oplus \ldots \oplus a_{i + k - 1}$. Also, after this query, the subarray $a_i, a_{i + 1}, \ldots, a_{i + k - 1}$ will be reversed, i.e., the chosen array $a$ will become: $a_1, a_2, \ldots a_{i - 1}, a_{i + k - 1}, a_{i + k - 2}, \ldots, a_{i + 1}, a_i, a_{i + k}, \ldots, a_n$.
You can make no more than $100$ queries to answer the problem.
|
Let's make queries to subarrays starting at positions $1$, $k + 1$, $2k + 1$, $\ldots$ $m \cdot k + 1$, as long as these queries are valid, meaning their right boundary does not exceed $n$. Let's save the $\operatorname{XOR}$ of all the answers to these queries. We will call these queries primary. Now, we will shift the last subarray of the query one unit to the right and make a new query, as long as the right boundary does not exceed $n$. We will call these queries secondary. It is claimed that the $\operatorname{XOR}$ of the entire array will be equal to the $\operatorname{XOR}$ of all the queries. Let's prove this. Let $i$ be the position at which the first secondary query starts. Notice that after this query, the subarray [$i$; $i + k - 2$] will turn into the subarray [$i + 1$; $i + k - 1$] and reverse. After the next query, the same thing will happen, the subarray will shift one unit to the right and reverse. Therefore, the prefixes of length $k-1$ of each secondary query will be the same, up to the reversal, which does not affect the $\operatorname{XOR}$. Since the number of secondary queries is equal to $n \operatorname{mod} k$, which is an even number, the $\operatorname{XOR}$ of these prefixes will not affect the $\operatorname{XOR}$ of all the secondary queries, which will therefore be equal to the $\operatorname{XOR}$ of the elements [$a_{i + k - 1}$; $a_n$], that is, all the elements that we did not consider in the primary queries. The number of primary queries is equal to $\lfloor \frac{n}{k} \rfloor \leq k \leq 50$, since $n \leq k^2 \leq 2500$. The number of secondary queries is equal to $n \operatorname{mod} k < k <= 50$, since $k^2 \leq 2500$. The total number of queries does not exceed $100$.
|
[
"constructive algorithms",
"interactive",
"math"
] | 2,000
|
#include <iostream>
using namespace std;
int ask(int i) {
cout << "? " << i << endl;
int x;
cin >> x;
return x;
}
void solve() {
int n, k;
cin >> n >> k;
int res = 0;
int i;
for (i = 1; i + k - 1 <= n; i += k)
res ^= ask(i);
for (; i <= n; ++i)
res ^= ask(i - k + 1);
cout << "! " << res << endl;
}
int main() {
int t;
cin >> t;
while (t--)
solve();
return 0;
}
|
1867
|
E2
|
Salyg1n and Array (hard version)
|
\textbf{This is the hard version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 57 queries. You can make hacks only if both versions of the problem are solved.}
\textbf{This is an interactive problem!}
salyg1n has given you a positive integer $k$ and wants to play a game with you. He has chosen an array of $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq 10^9$). You must print $a_1 \oplus a_2 \oplus \ldots \oplus a_n$, where $\oplus$ denotes the bitwise XOR operation. You can make queries of the following type:
- $?$ $i$: in response to this query, you will receive $a_i \oplus a_{i + 1} \oplus \ldots \oplus a_{i + k - 1}$. Also, after this query, the subarray $a_i, a_{i + 1}, \ldots, a_{i + k - 1}$ will be reversed, i.e., the chosen array $a$ will become: $a_1, a_2, \ldots a_{i - 1}, a_{i + k - 1}, a_{i + k - 2}, \ldots, a_{i + 1}, a_i, a_{i + k}, \ldots, a_n$.
You can make no more than $57$ queries to answer the problem.
|
Let's make queries to subarrays starting at positions $1$, $k + 1$, $2k + 1$, $\ldots$ $m \cdot k + 1$, such that the size of the uncovered part is greater than $2 \cdot k$ and not greater than $3 \cdot k$. In other words, $2 \cdot k < n - (m + 1) \cdot k \le 3 \cdot k$. Let's keep the $\operatorname{XOR}$ of all the answers to these queries. We will call these queries primary. Let the size of the remaining (uncovered) part be $x$ ($2 \cdot k < x \le 3 \cdot k$). Let's learn how to solve the problem for an array of size $x$ in three queries. If $x = 3 \cdot k$, simply make queries to positions $1$, $k + 1$, $2 \cdot k + 1$. Otherwise, let $y = x - k$. Note that $y$ is even, since $x$ and $k$ are even. Make queries at positions $1$, $1 + \frac{y}{2}$, $1 + y$. Note that after this query, the subarray [$1$; $k - \frac{y}{2}$] will turn into the subarray [$y/2 + 1$; $k$] and reverse. After the next query, the same thing will happen, the subarray will shift one unit to the right and reverse. Therefore, the prefixes of length $k - \frac{y}{2}$ for each query are the same, up to the reversal, which does not affect the $\operatorname{XOR}$. Since the number of queries in the second group is $3$, which is an odd number, the $\operatorname{XOR}$ of these prefixes will be taken into account exactly once in the $\operatorname{XOR}$ of all the queries, which will therefore be equal to the $\operatorname{XOR}$ of the elements. The number of primary queries does not exceed $\lfloor \frac{n}{k} \rfloor \leq k \leq 50$, since $n \leq k^2 \leq 2500$. The total number of queries does not exceed $53$.
|
[
"constructive algorithms",
"interactive"
] | 2,200
|
#include <iostream>
using namespace std;
int ask(int i) {
cout << "? " << i << endl;
int x;
cin >> x;
return x;
}
void solve() {
int n, k;
cin >> n >> k;
int res = 0;
int i;
for (i = 1; n - i + 1 >= 2 * k; i += k)
res ^= ask(i);
if (n - i + 1 == k) {
res ^= ask(i);
cout << "! " << res << endl;
return;
}
int y = (n - i + 1 - k) / 2;
res ^= ask(i);
res ^= ask(i + y);
res ^= ask(i + 2 * y);
cout << "! " << res << endl;
}
int main() {
int t;
cin >> t;
while (t--)
solve();
return 0;
}
|
1867
|
F
|
Most Different Tree
|
Given a tree with $n$ vertices rooted at vertex $1$, denote it as $G$. Also denote $P(G)$ as the multiset of subtrees of all vertices in tree $G$. You need to find a tree $G'$ of size $n$ rooted at vertex $1$ such that the number of subtrees in $P(G')$ that are isomorphic to any subtree in $P(G)$ is minimized.
A subtree of vertex $v$ is a graph that contains all vertices for which vertex $v$ lies on the path from the root of the tree to itself, as well as all edges between these vertices.
Two rooted trees are considered isomorphic if it is possible to relabel the vertices of one of them so that it becomes equal to the other, with the root of the first tree receiving the number of the root of the second tree.
|
Here we say that the answer for tree $G'$ is the number of subtrees in $P(G')$ that have an isomorphic subtree in $P(G)$. Let's find a tree $T$ of minimum size that has no isomorphic tree in $P(G)$. Let the size of tree $T$ be $x$. Then take a chain of size $n - x$, and let the root of $T$ be the kid of the last vertex on the chain. We say that this is the tree $G'$ we were looking for (with the root of $G'$ being the first vertex of the chain). The number of matching subtrees will be at most $x - 1$, since all subtrees of the vertices on the chain and the subtree $T$ itself will not have isomorphic trees in $P(G)$, because $T$ lies entirely in them, and $T$ has no isomorphic tree in $P(G)$. Therefore, the answer is not greater than $n - (n - x) - 1 = x - 1$. Let's prove why the answer cannot be less than $x - 1$: suppose there exists a tree $G*$ for which the answer is less than $x - 1$. Let's find a subtree of minimum size whose size is at least $x$ (it always exists, since we can take the entire tree for example). In this subtree, there are at least $x - 1$ other subtrees, whose sizes are less than $x$ (because in the previous step we chose a subtree of minimum size not less than $x$). And since all trees of size less than $x$ have isomorphic trees in $P(G)$ (by definition $T$ is the tree of minimum size that has no isomorphic tree in $P(G)$ and its size is $x$), the number of matching subtrees in tree $G*$ is at least $x - 1$, which is a contradiction. Therefore in our case the answer is $x - 1$. Now let's solve the second part of the problem - finding $T$. To do this, let's first find all trees of size 1, then of size 2, then 3, 4 and so on until we find a tree that has no isomorphic subtree in $P(G)$. One can see that if we generate all trees of size up to 15 we will definitely find $T$ there. Within each size, let's number the trees in the order in which we've generated them. To find all trees of size $x$ if we are given all trees of size $x - 1$ and smaller, let's say that the sizes of the children of the root of the tree we generate must not decrease, and if the sizes are the same, their positions in the order must not decrease. Then, we can iterate over the first child, then among the smaller and suitable ones, the second child, then the third, and so on until the total size of the tree becomes exactly $x$. This way, we will enumerate all trees of size $x$ in complexity of their total number (since we will not consider any tree twice and will not consider any extra trees). Let's do this until we find a tree that is not in $P(G)$. Hashes can be used to compare trees for isomorphism. For more details, read the blog post Time Complexity: $O(n \log n)$.
|
[
"brute force",
"constructive algorithms",
"dfs and similar",
"greedy",
"hashing"
] | 2,700
|
#include <bits/stdc++.h>
using namespace std;
const int MAXSZ = 15;
void rec(int ns, int last, vector<int>& now, vector<vector<int>>& aint, vector<int>& col, vector<int>& sz, int& ss, int sns) {
if (ss < 0) {
return;
}
if (ns == 0) {
col.back()++;
aint.push_back(now);
ss -= sns;
return;
}
for (int i = min(last, col[ns] - 1); i >= 0; i--) {
now.push_back(i);
rec(ns - sz[i], i, now, aint, col, sz, ss, sns);
now.pop_back();
}
}
void dfs(int v, int p, vector<vector<int>>& arr, vector<int>& num, map<vector<int>, int>& m, vector<int>& sz) {
vector<int> now;
sz[v] = 1;
for (auto i : arr[v]) {
if (i != p) {
dfs(i, v, arr, num, m, sz);
sz[v] += sz[i];
if (sz[v] <= MAXSZ) {
now.push_back(num[i]);
}
}
}
if (sz[v] > MAXSZ) {
num[v] = -1;
return;
}
stable_sort(now.begin(), now.end());
reverse(now.begin(), now.end());
num[v] = m[now] - 1;
}
void dfs2(int x, int p, vector<vector<int>>& aint, vector<int>& ans) {
if (p >= 0) {
ans.push_back(p);
}
int now = ans.size();
for (auto i : aint[x]) {
dfs2(i, now, aint, ans);
}
}
void solve() {
int n;
cin >> n;
vector<vector<int>> aint(1);
vector<vector<int>> arr(n);
for (int i = 1; i < n; i++) {
int a, b;
cin >> a >> b;
a--;
b--;
arr[a].push_back(b);
arr[b].push_back(a);
}
map<vector<int>, int> m;
vector<int> col(1, 0), sz(1, 1);
col.push_back(1);
for (int i = 2; i <= MAXSZ; i++) {
vector<int> now;
col.push_back(col.back());
int ss = n;
rec(i - 1, aint.size() - 1, now, aint, col, sz, ss, i);
while (sz.size() < col.back()) {
sz.push_back(i);
}
if (ss < 0) {
break;
}
}
for (int i = 0; i < col.back(); i++) {
m[aint[i]] = i + 1;
}
vector<int> num(n), szi(n, 1);
dfs(0, 0, arr, num, m, szi);
set<int> s;
for (int i = 0; i < col.back(); i++) {
s.insert(i);
}
for (auto i : num) {
s.erase(i);
}
int x = *s.begin();
vector<int> ans;
if (sz[x] > n) {
for (int i = 0; i < n; i++) {
for (auto j : arr[i]) {
if (i < j) {
cout << i + 1 << ' ' << j + 1 << '\n';
}
}
}
return;
}
for (int i = 0; i < n - sz[x] - 1; i++) {
ans.push_back(i);
}
dfs2(x, n - sz[x] - 1, aint, ans);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] + 1 << ' ' << i + 2 << '\n';
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
//cin >> t;
for (int i = 0; i < t; i++) {
solve();
}
}
|
1868
|
A
|
Fill in the Matrix
|
There is an empty matrix $M$ of size $n\times m$.
Zhongkao examination is over, and Daniel would like to do some puzzle games. He is going to fill in the matrix $M$ using permutations of length $m$. That is, each row of $M$ must be a permutation of length $m^\dagger$.
Define the value of the $i$-th column in $M$ as $v_i=\operatorname{MEX}(M_{1,i},M_{2,i},\ldots,M_{n,i})^\ddagger$. Since Daniel likes diversity, the beauty of $M$ is $s=\operatorname{MEX}(v_1,v_2,\cdots,v_m)$.
You have to help Daniel fill in the matrix $M$ and \textbf{maximize} its beauty.
$^\dagger$ A permutation of length $m$ is an array consisting of $m$ distinct integers from $0$ to $m-1$ in arbitrary order. For example, $[1,2,0,4,3]$ is a permutation, but $[0,1,1]$ is not a permutation ($1$ appears twice in the array), and $[0,1,3]$ is also not a permutation ($m-1=2$ but there is $3$ in the array).
$^\ddagger$ The $\operatorname{MEX}$ of an array is the smallest non-negative integer that does not belong to the array. For example, $\operatorname{MEX}(2,2,1)=0$ because $0$ does not belong to the array, and $\operatorname{MEX}(0,3,1,2)=4$ because $0$, $1$, $2$ and $3$ appear in the array, but $4$ does not.
|
On one hand, the matrix $M$ has $n$ rows, so the maxmium $v_i$ does not exceed $\operatorname{MEX}(0,1,\cdots,n-1)=n$, and $s$ does not exceed $n+1$. On the other hand, the matrix $M$ has $m$ columns, and there are only $m$ numbers in the array $v$, so $s$ must not exceed $m$. Therefore, the upper bound of $s$ is $\min(n+1,m)$. How can we reach the upper bound? If $m=1$, then the only possible $M=\begin{pmatrix} 0\\ 0\\ \vdots\\ 0 \end{pmatrix}$, in this case, $v_1=1$, so $s$ must be $0$, which unfortunately cannot reach the upper bound. Sadly, many participants failed on pretest 2 because of it. I've added this test to examples:) If $m>1$, let's construct the $M$ in two cases: Case 1. $m\ge n+1$.In this case, we can construct $M$ like following: $M= \begin{pmatrix} 0&1&\cdots&m-2&m-1\\ 1&2&\cdots&m-1&0\\ 2&3&\cdots&0&1\\ \vdots&\vdots&\ddots&\vdots&\vdots\\ n-1&n&\cdots &n-3 & n-2 \end{pmatrix}$ More formally, $M_{i,j}=(i+j-1)\bmod m$. Note that in this case $n-1< m-1$, so we have $v_1=n$, $v_2=v_{3}=\cdots=v_{m-n-1}=0$, $v_{m-n}=1,v_{m-n+1}=2,\cdots,v_m=n-1$. Then $s=n+1$, which reaches the upper bound. In this case, we can construct $M$ like following: $M= \begin{pmatrix} 0&1&\cdots&m-2&m-1\\ 1&2&\cdots&m-1&0\\ 2&3&\cdots&0&1\\ \vdots&\vdots&\ddots&\vdots&\vdots\\ n-1&n&\cdots &n-3 & n-2 \end{pmatrix}$ More formally, $M_{i,j}=(i+j-1)\bmod m$. Note that in this case $n-1< m-1$, so we have $v_1=n$, $v_2=v_{3}=\cdots=v_{m-n-1}=0$, $v_{m-n}=1,v_{m-n+1}=2,\cdots,v_m=n-1$. Then $s=n+1$, which reaches the upper bound. Case 2. $m<n+1$.In this case, we can construct $M$ like following: $M= \begin{pmatrix} 0&1&\cdots&m-2&m-1\\ 1&2&\cdots&m-1&0\\ 2&3&\cdots&0&1\\ \vdots&\vdots&\ddots&\vdots&\vdots\\ m-2&m-1&\cdots &m-4 & m-3\\ 0&1&\cdots&m-2&m-1\\ 0&1&\cdots&m-2&m-1\\ \vdots&\vdots&\ddots&\vdots&\vdots\\ 0&1&\cdots&m-2&m-1\\ \end{pmatrix}$ More formally, for $1\le j\le m-1$, $M_{i,j}=(i+j-1)\bmod m$, for $m\le j\le n$, $M_{i,j}=(j-1)\bmod m$. Note that $m>1$, and $m-2\ge 0$. Similarly to case 1 we can get $s=m$, which also reaches the upper bound. In this case, we can construct $M$ like following: $M= \begin{pmatrix} 0&1&\cdots&m-2&m-1\\ 1&2&\cdots&m-1&0\\ 2&3&\cdots&0&1\\ \vdots&\vdots&\ddots&\vdots&\vdots\\ m-2&m-1&\cdots &m-4 & m-3\\ 0&1&\cdots&m-2&m-1\\ 0&1&\cdots&m-2&m-1\\ \vdots&\vdots&\ddots&\vdots&\vdots\\ 0&1&\cdots&m-2&m-1\\ \end{pmatrix}$ More formally, for $1\le j\le m-1$, $M_{i,j}=(i+j-1)\bmod m$, for $m\le j\le n$, $M_{i,j}=(j-1)\bmod m$. Note that $m>1$, and $m-2\ge 0$. Similarly to case 1 we can get $s=m$, which also reaches the upper bound. Time Complexity: $\mathcal{O}(n\cdot m)$ per test case.
|
[
"constructive algorithms",
"implementation"
] | 1,300
|
#include <bits/stdc++.h>
#define all(s) s.begin(), s.end()
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int _N = 1e5 + 5;
int T;
void solve() {
int n, m;
cin >> n >> m;
if (m == 1) cout << 0 << '\n';
else if (n > m - 1) cout << m << '\n';
else cout << n + 1 << '\n';
for (int i = 0; i < min(m - 1, n); i++) {
for (int j = 0; j < m; j++) {
cout << (j + i) % m << ' ';
}
cout << '\n';
}
if (n > m - 1) {
for (int i = m - 1; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << j << ' ';
}
cout << '\n';
}
}
return;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> T;
while (T--) {
solve();
}
}
|
1868
|
B1
|
Candy Party (Easy Version)
|
{This is the easy version of the problem. The only difference is that in this version everyone must give candies to \textbf{exactly one} person and receive candies from \textbf{exactly one} person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if both versions of the problem are solved.}
After Zhongkao examination, Daniel and his friends are going to have a party. Everyone will come with some candies.
There will be $n$ people at the party. Initially, the $i$-th person has $a_i$ candies. During the party, they will swap their candies. To do this, they will line up \textbf{in an arbitrary order} and everyone will do the following \textbf{exactly once}:
- Choose an integer $p$ ($1 \le p \le n$) and a \textbf{non-negative} integer $x$, then give his $2^{x}$ candies to the $p$-th person. Note that one \textbf{cannot} give more candies than currently he has (he might receive candies from someone else before) and he \textbf{cannot} give candies to himself.
Daniel likes fairness, so he will be happy if and only if everyone receives candies from \textbf{exactly one person}. Meanwhile, his friend Tom likes average, so he will be happy if and only if all the people have the same number of candies after all swaps.
Determine whether there exists a way to swap candies, so that both Daniel and Tom will be happy after the swaps.
|
Denote $s$ as $\frac{1}{n}\sum_{i=1}^n a_i$. If $s$ is not an integer, then it will be impossible to make all people have the same number of candies, so the answer is "No". Since a person gives candies to and receives candies from exactly one person, suppose he gives away $2^x$ candies and receives $2^y$ candies, then we get this equation: $a_i-2^{x_i}+2^{y_i}=s.$ If $s=a_i$, there is an infinite set of solutions: $x_i=y_i$. Otherwise, $s\ne a_i$, then we have $a_i-s=2^{x_i}-2^{y_i}$. For different pairs $(x, y)$ ($x\ne y$), the values of $2^x - 2^y$ are pairwise different, so there will be at most $1$ solution to this equation. Thus, if there exists a possible solution, the number of candies each person receives and gives away is determined for $a_i\ne s$. If an equation has no solution, then obviously the answer is "No". Otherwise, let's maintain two multisets $S$ and $T$. For each person, let's add $x_i$ to $S$ and $y_i$ to $T$. Omitting the condition "one cannot give more candies than currently he has" $(1)$, we can claim that the answer is "Yes" if and only if $S=T$. The proof is left to readers as an exercise. :) Now let's think about the condition $(1)$. Build a directed graph with $n$ nodes. For two persons $i$ and $j$, if person $i$ gives $x>0$ candies to person $j$, then we add an edge from node $i$ to node $j$ with weight $x$. All nodes with $a_i\ne s$ must have exactly $1$ in degree and $1$ out degree. So the graph must consist of several cycles. Let's prove that we can always choose a starting point properly for any cycle, so that the condition $(1)$ is satisfied. Pick the largest $a_i$ in the cycle, and we must have $a_i>s$. Suppose the $i$-th person gives candies to the $j$-th person ($1\le a_j\le a_i$, $x_i\ne x_j$), then we have: $a_i-2^{x_i}+2^{y_i}=s,\tag{2}$ $a_j-2^{x_j}+2^{x_i}=s,\tag{3}$ Suppose $a_i<2^{x_i}$, then we must have $y_i<x_i$, so $2^{y_i}\le 2^{x_i}/2$. If $x_i<x_j$, that is, $2\cdot 2^{x_i}\le 2^{x_j}$: $\begin{aligned} (2)-(3)&\implies a_i-a_j-2^{x_i}+2^{x_j}+2^{y_i}-2^{x_i}=0\\ &\implies a_i-a_j+\underbrace{(2^{x_j}-2\cdot 2^{x_i})+2^{y_i}}_{>0}=0\\ &\implies a_i<a_j, \end{aligned}$ Similarly we can prove that when $x_i>x_j$, $a_j<0$. In both cases the condition $1\le a_j\le a_i$ has been violated. So we proved that $a_i-2^{x_i}>0$. Thus, we proved the the claim. And we can easily add those nodes with $a_i=s$ into cycles: suppose the node is $p$, if there is an edge $a\to b$ with weight $w$, we add two edge $a\to p$ and $p\to b$, both weights are $w$, and delect the original edge $a\to b$. So we can solve this problem by simply maintaining $S$ and $T$, which can be done in $\mathcal{O}(n\log V)$. $\mathcal{O}(n\log^2 V)$ solutions can fit in the TL well, too.
|
[
"bitmasks",
"constructive algorithms",
"graphs",
"greedy",
"implementation",
"math"
] | 1,700
|
#include <bits/stdc++.h>
#define all(s) s.begin(), s.end()
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int _N = 1e5 + 5;
int T;
void solve() {
int n; cin >> n;
vector<ll> a(n); ll sum = 0;
for (int i = 0; i < n; i++) cin >> a[i], sum += a[i];
if (sum % n) return cout << "No" << '\n', void();
sum /= n;
vector<int> bit(31, 0);
auto lowbit = [](int x) {
return x & (-x);
};
for (int i = 0; i < n; i++) {
if (a[i] == sum) continue;
int d = abs(a[i] - sum);
int p = lowbit(d);
int e = d + p;
if (__builtin_popcount(e) == 1) {
if (a[i] > sum) bit[__lg(e)]++, bit[__lg(p)]--;
else bit[__lg(e)]--, bit[__lg(p)]++;
} else {
cout << "No" << '\n';
return;
}
}
for (int i = 0; i < 31; i++) {
if (bit[i]) {
cout << "No" << '\n';
return;
}
}
cout << "Yes" << '\n';
return;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> T;
while (T--) {
solve();
}
}
|
1868
|
B2
|
Candy Party (Hard Version)
|
{This is the hard version of the problem. The only difference is that in this version everyone must give candies to \textbf{no more than one} person and receive candies from \textbf{no more than one} person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if both versions of the problem are solved.}
After Zhongkao examination, Daniel and his friends are going to have a party. Everyone will come with some candies.
There will be $n$ people at the party. Initially, the $i$-th person has $a_i$ candies. During the party, they will swap their candies. To do this, they will line up \textbf{in an arbitrary order} and everyone will do the following \textbf{no more than once}:
- Choose an integer $p$ ($1 \le p \le n$) and a \textbf{non-negative} integer $x$, then give his $2^{x}$ candies to the $p$-th person. Note that one \textbf{cannot} give more candies than currently he has (he might receive candies from someone else before) and he \textbf{cannot} give candies to himself.
Daniel likes fairness, so he will be happy if and only if everyone receives candies from \textbf{no more than one person}. Meanwhile, his friend Tom likes average, so he will be happy if and only if all the people have the same number of candies after all swaps.
Determine whether there exists a way to swap candies, so that both Daniel and Tom will be happy after the swaps.
|
Read the tutorial for D1 first. Consider the graph we built in this version. It should only consist of chains and cycles. For the start nodes of chains and the end nodes of chains, $|a_i-s|=2^d$ must hold. Thus, for $|a_i-s|\ne 2^d$, we sill have only one way to decide the number of candies given away and received (the same as D1). However, for $|a_i-s|=2^d$, we have two ways: the same way as D1 (use the equation $a_i-2^{x_i}+2^{y_i}=s$); let this person be the start or end node of chains, that is, $a_i-2^{x_i}=s$ or $a_i-2^{x_i}=s$. (Suppose $2^{x_i}$ is the number of candies he gives away or receives) Again, let's omit those nodes with $|a_i-s|=2^d$ first. Then we can similarly maintain two sets $S$ and $T$ to D1. Let $cntS_i$ be the number of $i$-s in set $S$ and $cntT_i$ be the number of $i$-s in $T$. Note that now we omit nodes with $|s-a_i|=2^d$ when maintaining both sets. Let $cntDS_k$ be the number of nodes with $a_i-s=2^k$ and $cntDT_i$ be the number of nodes with $s-a_i=2^{k}$. For nodes with $|a_i-s|=2^{x_i}$, the two ways are: $a_i-2^{x_i}=s$, or $a_i+2^{x_i}=s$; $a_i+2^{x_i}-2^{x_i+1}=s$, or $a_i-2^{x_i-1}+2^{x_i}$. To make the two sets $S$ and $T$ equal, we must make $cntS_k=cntT_k$ for all $0\le k\le 30$. Now consider nodes with $|a_i-s|=2^d$. We can determine bit-by-bit. Let's start from the first bit. Consider $cntDS_i$: if we choose $x\le cntDS_i$ elements to use the first way, then: $cntS_i:=cntS_i+x$; $cntS_{i+1}:=cntS_{i+1}+x$; $cntT_i:=cntT_i+(cntDS_i-x)$. Consider $cntDT_i$: if we choose $x\le cntDT_i$ elements to use the first way, then: $cntT_i:=cntT_i+x$; $cntT_{i-1}:=cntT_{i-1}+x$; $cntT_i:=cntT_i+(cntDT_i-x)$. Let's consider the highest bit. All elements in $cntDS_i$ must be chosen the second way ($x=0$), otherwise, it will influence $cntS_{i+1}$. Then we can determine the $x$ for $cntDT_i$, then $cntDS_{i-1},cntDT_{i-1},...,cntDS_0,cntDT_0$. At last, we check if $cntS_0=cntT_0$ (we have made $cntS_i=cntT_i$ for all $i>0$). If so, the answer is "Yes", otherwise the answer is "No".
|
[
"bitmasks",
"constructive algorithms",
"dp",
"greedy",
"implementation",
"math"
] | 2,100
|
#include <bits/stdc++.h>
#define all(s) s.begin(), s.end()
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int _N = 1e5 + 5;
int T;
void solve() {
int n; cin >> n;
vector<ll> a(n); ll sum = 0;
for (int i = 0; i < n; i++) cin >> a[i], sum += a[i];
if (sum % n) return cout << "No" << '\n', void();
sum /= n;
vector<int> bit(31, 0), pow1(31, 0), pow2(31, 0);
for (int i = 0; i < n; i++) {
int flag = 0;
if (a[i] == sum) continue;
for (int j = 0; j < 31; j++) {
if (a[i] + (1 << j) == sum) {
pow1[j]++;
flag = 1;
continue;
}
if (a[i] - (1 << j) == sum) {
pow2[j]++;
flag = 1;
continue;
}
}
if (flag) continue;
flag = 0;
for (int j = 0; j < 31; j++) {
for (int k = 0; k < 31; k++) {
if (a[i] + (1 << j) - (1 << k) == sum) {
flag = 1;
bit[j]++;
bit[k]--;
}
}
}
if (!flag) {
cout << "No" << '\n';
return;
}
}
for (int i = 30; i >= 0; i--) {
bit[i] += (pow1[i] - pow2[i]);
if (i == 0) break;
if (bit[i] < 0) {
pow1[i - 1] -= -bit[i];
bit[i - 1] -= -bit[i];
if (pow1[i - 1] < 0) {
cout << "No" << '\n';
return;
}
} else {
pow2[i - 1] -= bit[i];
bit[i - 1] += bit[i];
if (pow2[i - 1] < 0) {
cout << "No" << '\n';
return;
}
}
}
if (bit[0] == 0) cout << "Yes" << '\n';
else cout << "No" << '\n';
return;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> T;
while (T--) {
solve();
}
}
|
1868
|
C
|
Travel Plan
|
During the summer vacation after Zhongkao examination, Tom and Daniel are planning to go traveling.
There are $n$ cities in their country, numbered from $1$ to $n$. And the traffic system in the country is very special. For each city $i$ ($1 \le i \le n$), there is
- a road between city $i$ and $2i$, if $2i\le n$;
- a road between city $i$ and $2i+1$, if $2i+1\le n$.
Making a travel plan, Daniel chooses some integer value between $1$ and $m$ for each city, for the $i$-th city we denote it by $a_i$.
Let $s_{i,j}$ be the maximum value of cities in the simple$^\dagger$ path between cities $i$ and $j$. The score of the travel plan is $\sum_{i=1}^n\sum_{j=i}^n s_{i,j}$.
Tom wants to know the sum of scores of all possible travel plans. Daniel asks you to help him find it. You just need to tell him the answer modulo $998\,244\,353$.
$^\dagger$ A simple path between cities $x$ and $y$ is a path between them that passes through each city at most once.
|
For any path of length $t$, the number of assignments in which the maximum value of cities is no bigger than $k$ is $k^t$. As a result, the number of assignments in which the maximum value of cities is exactly $k$ is $k^t-(k-1)^t$, while the sum of the maximum value of cities in all assignments is $\sum_{k=1}^m(k^t-(k-1)^t)k$. We can solve this in $\mathcal O(m\log n)$. Then, we need to calculate the number of paths of length $t$ for each $t$. Claim. There are $\mathcal O(\log n)$ different subtrees in this tree. Proof. It's easy to see that this tree can be seen as a full binary tree with one row of extra leaves. Let the number of leaves in each subtree be $lf_i$. If $lf_i=2^p$, the subtree of $i$ is a full binary tree with depth $p$. Also, for each subtree satisfying $lf_i\neq 2^p$, either $lf_{2i}=2^{p'}$ or $lf_{2i+1}=2^{p'}$, which means that for each depth, there is at most one subtree satisfying $lf_i\neq2^p$. As the depth of the whole tree is $\mathcal O(\log n)$, the total number of different subtrees is also $\mathcal O(\log n)$. Then, let $dp_{i,j}$ stand for the number of paths length $j$ in a subtree with $i$ vertices, and $f_{i,j}$ stand for the number of paths with one end being $i$ and length $j$ in a subtree with $i$ vertices. We can simply do a memorization search to solve this part in $\mathcal O(\log^3 n)$. To optimize the first part, we can transform the formula to $m^t\times m-\sum_{k=1}^{m-1}k^t$. For the second part, we can use interpolation, dp, or polynomial to solve this in $\mathcal O(\log n)$ or $\mathcal O(\log^2 n)$. To optimize the second part, we can divide the paths into three types: no end on the extra leaves, one end on the extra leaves, and two ends on the extra leaves. For the first two types, we can simply see the paths as going up and going down so we can enumerate the distance going up and down. Then we can calculate them in $\mathcal O(\log^2 n)$. For the third part, a dp just like the above will work. The only difference is that only one $f_{i,j}$ is not $0$ under this circumstance and we can solve it in $\mathcal O(\log^2 n)$. It's also possible to solve this second part in $\mathcal O(\log n)$ by further optimization of the calculation of the three types of paths. $\mathcal O(\sum(m\log n+\log^3n))$ solution by programpiggy: $\mathcal O(\sum \log^3n)$ solution by sszcdjr: $\mathcal O(\sum \log^2n)$ solution by sszcdjr: $\mathcal O(\sum m\log n)$ solution by ling_luo:
|
[
"combinatorics",
"dp",
"implementation",
"math",
"trees"
] | 2,400
|
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0,_##i##__end=(n);i<_##i##__end;++i)
#define rep1(i,n) for(int i=1,_##i##__end=(n);i<=_##i##__end;++i)
#define mp make_pair
#define fi first
#define se second
typedef long long ll;
using namespace std;
const ll mod1=998244353;
int t;
ll n;
int m;
ll qkpw(ll a,ll b)
{
ll ret=1;
while(b)
{
if(b&1) ret=ret*a%mod1;
a=a*a%mod1;
b>>=1;
}
return ret;
}
ll val_full[114];
ll val_link[114];
pair<ll,ll> realget(ll P,unsigned long long c)
{
if((c&(c+1))==0)
return mp(val_link[bit_width(c)-1],val_full[bit_width(c)-1]);
if(c==2)
return mp((P*P+P)%mod1,(P*P+P+P)%mod1);
if(c&(bit_floor(c)>>1))
{
pair<ll,ll> A=realget(P,bit_floor(c)-1),B=realget(P,c-bit_floor(c));
return mp((A.fi+B.fi+1)*P%mod1,(A.se+B.se+(1+A.fi)*(1+B.fi)%mod1*P)%mod1);
}
pair<ll,ll> A=realget(P,c-(bit_floor(c)>>1)),B=realget(P,(bit_floor(c)>>1)-1);
return mp((A.fi+B.fi+1)*P%mod1,(A.se+B.se+(1+A.fi)*(1+B.fi)%mod1*P)%mod1);
}
ll get_value(ll P,ll c)
{
val_full[0]=P;val_link[0]=P;
rep1(i,64)
{
val_full[i]=(val_full[i-1]*2+(1+val_link[i-1])*(1+val_link[i-1])%mod1*P)%mod1;
val_link[i]=((val_link[i-1]*2+1)*P)%mod1;
}
return realget(P,c).second;
}
void Q()
{
cin>>n>>m;
ll cur=((n%mod1)*(n%mod1+1)/2%mod1)*qkpw(m,n+1)%mod1;
ll INV_M=qkpw(m,mod1-2);
rep(i,m) cur=(cur-qkpw(m,n)*get_value(i*INV_M%mod1,n)%mod1+mod1)%mod1;
cout<<cur<<endl;
}
int main()
{
cin>>t;while(t--)Q();
}
|
1868
|
D
|
Flower-like Pseudotree
|
A pseudotree is a connected graph which has \textbf{exactly one} cycle and \textbf{no} self-loops. Note that a pseudotree \textbf{may contain multiple-edges}. It can be shown that a pseudotree with $n$ vertices always contains $n$ edges.
After deleting all edges on the cycle in the pseudotree, a forest$^{\dagger}$ will be formed. It can be shown that each tree in the forest will contain exactly one vertex which is on cycle before removing the edges. If all trees in the forest have the same depth$^{\ddagger}$ when picking the vertex on cycle as root, we call the original pseudotree flower-like.
Our friend sszcdjr, had a flower-like pseudotree with $n$ vertices and $n$ edges. However, he forgot all the edges in the pseudotree. Fortunately, he still remembers the degrees of vertices. Specifically, the degree of the $i$-th vertex is $d_i$.
You have to help sszcdjr construct a possible flower-like pseudotree with $n$ vertices, where the degree of the $i$-th vertex is \textbf{exactly} $d_i$, or tell him that it is impossible.
$^{\dagger}$ A forest is a graph in which all connectivity components are trees. A connected graph without cycles and self-loops is called a tree.
$^{\ddagger}$ The depth of a tree with a root is the maximum distance from the root to the vertex of this tree.
|
If $\sum_{i=1}^n d_i\neq 2n$, it's obviously impossible to construct a flower-like psuedotree. So let's just consider the situation when $\sum_{i=1}^n d_i=2n$. Sort $d_i$ from largest to smallest. If $d_1=d_2=\dots=d_n=2$, we can simply construct a cycle. Otherwise $d_1>2$, in which case there must be at least two $d_i>2$ and the vertices on the cycle must satisfy $d_i>2$. Ignore all vertices with $d_i=1$ as we can just hang them under all the other vertices. The following pictures don't show vertices with $d_i=1$ and the edges with weight $2$ are two multi-edges. Let $cnt$ be the number of vertices with $d_i>1$. If $cnt$ is even, we can make a cycle using $d_1$ and $d_2$, with two chains of equal length hanging from $d_1$ and $d_2$. The multi-edges have a number $2$ on them. If $cnt$ is odd and $d_1>3$, it's easy to see that we can hang two vertices below $d_1$ to transform it to the situation where $cnt$ is even. However, we need at least $5$ vertices to make the psuedotree flower-like, which means that $cnt\geq5$ must be satisfied. (In the picture, at least vertices $1\sim5$ are needed.) If $cnt$ is odd, $d_1>3$ and $cnt=3$, it's impossible for us to simply build a cycle length $2$. Thus, we can try to put $d_1,d_2,d_3$ in one cycle and the condition is $d_3>2$. If $cnt$ is odd and $d_1=3$, it's impossible for us to do the operation above, because we can't hang two vertices under $d_1$. It's easy to see that we can't balance the two trees if $d_3=2$. For $d_3=3$, we can hang $d_3,d_4$ under $d_1,d_2$, $d_5,d_6$ under $d_3$ and $d_7$ under $d_4$ to make the psuedotree flower-like. However, we need at least $7$ vertices to make it balanced, which means $cnt\geq7$ must be satisfied. If $cnt$ is odd, $d_1=3$ and $cnt=5$, there are three cases: $d_1=d_2=d_3=3,d_4=d_5=2$: It can be proven that there isn't such a psuedotree. $d_1=d_2=d_3=d_4=3,d_5=2$: It can be proven that there isn't such a psuedotree. $d_1=d_2=d_3=d_4=d_5=3$: We can simply build a cycle of length $5$. If $cnt$ is odd, $d_1=3$ and $cnt=3$, there's only one case: $d_1=d_2=d_3=3$: We can simply build a cycle of length $3$. The total complexity depends on the sorting part, which is $\mathcal O(n\log n)$ if you use std::sort or std::stable_sort, and $\mathcal O(n)$ if you use bucket sorting.
|
[
"constructive algorithms",
"graphs",
"greedy",
"implementation",
"trees"
] | 3,000
|
#include <bits/stdc++.h>
#define int long long
#define double long double
using namespace std;
struct node{
int d,pos;
}a[1000005];
bool cmp(node x,node y){
return x.d>y.d;
}
void pe(int x,int y){
cout<<a[x].pos<<" "<<a[y].pos<<"\n";
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int t; cin>>t;
while(t--){
int n,tot=0; cin>>n; for(int i=1;i<=n;i++) cin>>a[i].d,a[i].pos=i,tot+=a[i].d;
if(tot!=2*n){
cout<<"No\n"; continue;
}
if(n==1){
cout<<"No\n"; continue;
}
sort(a+1,a+n+1,cmp);
if(a[1].d==2){
cout<<"Yes\n";
for(int i=1;i<=n;i++) pe(i,i%n+1);
continue;
}
if(a[2].d==2){
cout<<"No\n"; continue;
}
int cntb=0;
for(int i=3;i<=n;i++) cntb+=(a[i].d>1);
int num[n+1]; for(int i=1;i<=n;i++) num[i]=a[i].d;
if(!(cntb&1)){
cout<<"Yes\n";
pe(1,2),pe(1,2);
num[1]-=2,num[2]-=2;
for(int i=3;i<=cntb+2;i++) pe(i,i-2),num[i]--,num[i-2]--;
int it=1;
for(int i=cntb+3;i<=n;i++){
while(!num[it]) it++;
num[it]--,pe(i,it);
}
continue;
}
if(a[1].d==3){
if(a[3].d==2){
cout<<"No\n"; continue;
}
if(cntb==1){
cout<<"Yes\n";
pe(1,2),pe(2,3),pe(3,1);
pe(1,4),pe(2,5),pe(3,6);
continue;
}
if(a[5].d==2&&cntb==3){
cout<<"No\n"; continue;
}
if(cntb==3){
cout<<"Yes\n";
pe(1,2),pe(2,3),pe(3,4),pe(4,5),pe(5,1);
pe(1,6),pe(2,7),pe(3,8),pe(4,9),pe(5,10);
continue;
}
cout<<"Yes\n";
pe(1,2),pe(1,2),pe(1,3),pe(2,4),pe(3,5),pe(3,6),pe(4,7);
num[1]-=3,num[2]-=3,num[3]-=3,num[4]-=2,num[5]--,num[6]--,num[7]--;
for(int i=8;i<=cntb+2;i++) pe(i-2,i),num[i]--,num[i-2]--;
int it=1;
for(int i=cntb+3;i<=n;i++){
while(!num[it]) it++;
num[it]--,pe(i,it);
}
continue;
}
else{
if(a[3].d==2&&cntb==1){
cout<<"No\n"; continue;
}
if(cntb==1){
cout<<"Yes\n";
pe(1,2),pe(2,3),pe(3,1);
num[1]-=2,num[2]-=2,num[3]-=2;
int it=1;
for(int i=4;i<=n;i++){
while(!num[it]) it++;
num[it]--,pe(i,it);
}
continue;
}
cout<<"Yes\n";
pe(1,2),pe(1,2),pe(1,3),pe(1,4),pe(2,5);
num[1]-=4,num[2]-=3,num[3]-=1,num[4]-=1,num[5]-=1;
for(int i=6;i<=cntb+2;i++) pe(i,i-2),num[i]--,num[i-2]--;
int it=1;
for(int i=cntb+3;i<=n;i++){
while(!num[it]) it++;
num[it]--,pe(i,it);
}
continue;
}
}
return 0;
}
|
1868
|
E
|
Min-Sum-Max
|
Tom is waiting for his results of Zhongkao examination. To ease the tense atmosphere, his friend, Daniel, decided to play a game with him. This game is called "Divide the Array".
The game is about the array $a$ consisting of $n$ integers. Denote $[l,r]$ as the subsegment consisting of integers $a_l,a_{l+1},\ldots,a_r$.
Tom will divide the array into contiguous subsegments $[l_1,r_1],[l_2,r_2],\ldots,[l_m,r_m]$, such that each integer is in exactly one subsegment. More formally:
- For all $1\le i\le m$, $1\le l_i\le r_i\le n$;
- $l_1=1$, $r_m=n$;
- For all $1< i\le m$, $l_i=r_{i-1}+1$.
Denote $s_{i}=\sum_{k=l_i}^{r_i} a_k$, that is, $s_i$ is the sum of integers in the $i$-th subsegment. For all $1\le i\le j\le m$, the following condition must hold:
$$ \min_{i\le k\le j} s_k \le \sum_{k=i}^j s_k \le \max_{i\le k\le j} s_k. $$
Tom believes that the more subsegments the array $a$ is divided into, the better results he will get. So he asks Daniel to find the \textbf{maximum} number of subsegments among all possible ways to divide the array $a$. You have to help him find it.
|
Let $s$ be the suffix sum array of array $a$. That is, $s_i=\sum_{j=1}^ia_i$ and $s_0=0$. Let the partition point of the array be $r_0,r_1,\dots,r_m$, where $r_0=0$ and $r_m=n$. Pick one of the maximums of $s_{r_0},s_{r_1},\dots,s_{r_m}$ and let it be $s_{r_x}$. Similarly, let the minimum be $s_{r_y}$. If $|x-y|\geq 2$, there must be some $k$ ($k<x<y$) which satisfies that $s_{r_k}=s_{r_x}$ or $s_{r_k}=s_{r_y}$, or it's easy to see that the subsegment $[x+1,y]$ is invalid. Using the induction method, we can show that there exists a pair $(i,i+1)$ such that $s_{r_i}$ and $s_{r_{i+1}}$ are the maximum and the minimum in a valid subsegment in a partition. As a result, after enumerating $r_i,r_{i+1}$, the two parts $[1,r_i]$ and $[r_{i+1},n]$ are separate subproblems with constraints $s_{r_i}\leq r_t\leq s_{r_{i+1}}$. Let $dp_{i,j,k,l}$ be the maximum number of $r_t$ we can select in the segment $[i,j]$ with all $k\leq s_{r_t}\leq l$ and positions $i,j$ must be selected. Enumerate the maximum and minimum $s_{r_t}$ in all the selected $r_t$ and let them be $s_x$ and $s_y$. Then we get the transitions: $\forall k\le s_x,l\ge s_y,dp_{i,j,k,l}\gets dp_{i,x,s_x,s_y}+dp_{y,j,s_x,s_y}$ After compressing the coordinates of the array $s$ and changing the meaning of $k,l$ to the $k$-th,$l$-th small $s_i$ after coordinate compression, we can solve this problem in $\mathcal{O}(n^6)$, and $\mathcal{O}(n^4)$ with 2D prefix maximum. Consider the optimization. It's easy to see that the states used in the transformation all satisfy $k=s_i$ or $l=s_i$ or $k=s_j$ or $l=s_j$. Let's replace $dp_{i,j,s_i,k}$ by $f_{i,j,k}$ and replace $dp_{i,j,k,s_i}$ by $g_{i,j,k}$, and the transitions only relieve on $f_{i,j,k}$ and $g_{i,j,k}$, so the number of states was reduced to $\mathcal{O}(n^3)$. Consider the transitions of $f_{i,j,k}$ as $g_{i,j,k}$ is similar. Since the minimum $s_{r_t}$ is greater than $s_i$ and the position $i$ must be selected, the minimum $s_{r_t}$ is $s_i$. Enumerate $x$ and let $s_x$ be the maximum $s_{r_t}$. We need to find the best position $y$ where $s_y$ is minimum, i.e. $s_y=s_i$ and transform the segment $[i,x],[y,j]$ or $[i,y],[x,j]$ to $[i,j]$. It's easy to see that selecting the first $s_y=s_i$ on the left/right of $x$ is always the best choice. Let $y_1,y_2$ be the first on the left/right, then the transitions are: $\forall k\ge s_x$ $f_{i,j,k}\leftarrow\max\{f_{i,y_1,s_x}+g_{x,j,s_i}\}$ $f_{i,j,k}\leftarrow\max\{f_{i,x,s_x}+f_{y_2,j,s_x}\}$ Thus, the total time complexity is $\mathcal{O}(n^3)$ per test case.
|
[
"constructive algorithms",
"dp",
"greedy"
] | 3,500
|
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <math.h>
#include <iomanip>
#include <bitset>
#include <random>
#include <ctime>
#include <string_view>
#include <queue>
#include <cassert>
using namespace std;
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define pb emplace_back
#define ll long long
#define mp make_pair
#define pii pair<int, int>
#define ld long double
const int INF = 1e9 + 1;
const ll INFLL = 1e18;
bool contains(ll x, ll l, ll r) {
return (x >= l) && (x <= r);
}
void solve() {
int n;
cin >> n;
vector<ll> a(n + 1);
for (int i = 1; i <= n; i++) cin >> a[i];
if (n == 1) {
cout << 1 << "\n";
return;
}
vector<ll> pr(n + 1);
for (int i = 0; i < n; i++) pr[i + 1] = pr[i] + a[i + 1];
vector<vector<vector<int>>> dp_leftmin(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, -INF)));
vector<vector<vector<int>>> dp_leftmax(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, -INF)));
vector<vector<vector<int>>> dp_rightmin(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, -INF)));
vector<vector<vector<int>>> dp_rightmax(n + 1, vector<vector<int>>(n + 1, vector<int>(n + 1, -INF)));
vector<pair<ll, int>> b(n + 1);
for (int i = 0; i <= n; i++) b[i] = mp(pr[i], i);
sort(all(b));
vector<vector<int>> next_left(n + 1, vector<int>(n + 1, -1));
vector<vector<int>> next_right(n + 1, vector<int>(n + 1, -1));
for (int i = 0; i <= n; i++) {
int prev = -1;
for (int j = 0; j <= n; j++) {
next_left[i][j] = prev;
if (pr[j] == pr[i]) prev = j;
}
prev = n + 1;
for (int j = n; j >= 0; j--) {
next_right[i][j] = prev;
if (pr[j] == pr[i]) prev = j;
}
}
for (int len = 0; len <= n; len++) {
for (int i = 0; i <= n && i + len <= n; i++) {
int j = i + len;
for (int k = 0; k <= n; k++) {
if (contains(pr[i], pr[i], pr[k]) && contains(pr[j], pr[i], pr[k])) dp_leftmin[i][j][k] = min(len, 1);
if (contains(pr[i], pr[k], pr[i]) && contains(pr[j], pr[k], pr[i])) dp_leftmax[i][j][k] = min(len, 1);
if (contains(pr[i], pr[j], pr[k]) && contains(pr[j], pr[j], pr[k])) dp_rightmin[i][j][k] = min(len, 1);
if (contains(pr[i], pr[k], pr[j]) && contains(pr[j], pr[k], pr[j])) dp_rightmax[i][j][k] = min(len, 1);
}
if (len <= 1) continue;
for (int x = i; x <= j; x++) {
if (next_left[i][x] >= i) {
int y = next_left[i][x];
if (pr[x] >= pr[i]) dp_leftmin[i][j][x] = max(dp_leftmin[i][j][x], dp_leftmin[i][y][x] + dp_leftmax[x][j][i] + 1);
if (pr[x] <= pr[i]) dp_leftmax[i][j][x] = max(dp_leftmax[i][j][x], dp_leftmax[i][y][x] + dp_leftmin[x][j][i] + 1);
}
if (next_left[j][x] >= i) {
int y = next_left[j][x];
if (pr[x] >= pr[j]) dp_rightmin[i][j][x] = max(dp_rightmin[i][j][x], dp_rightmin[x][j][x] + dp_rightmin[i][y][x] + 1);
if (pr[x] <= pr[j]) dp_rightmax[i][j][x] = max(dp_rightmax[i][j][x], dp_rightmax[x][j][x] + dp_rightmax[i][y][x] + 1);
}
if (next_right[i][x] <= j) {
int y = next_right[i][x];
if (pr[x] >= pr[i]) dp_leftmin[i][j][x] = max(dp_leftmin[i][j][x], dp_leftmin[i][x][x] + dp_leftmin[y][j][x] + 1);
if (pr[x] <= pr[i]) dp_leftmax[i][j][x] = max(dp_leftmax[i][j][x], dp_leftmax[i][x][x] + dp_leftmax[y][j][x] + 1);
}
if (next_right[j][x] <= j) {
int y = next_right[j][x];
if (pr[x] >= pr[j]) dp_rightmin[i][j][x] = max(dp_rightmin[i][j][x], dp_rightmin[y][j][x] + dp_rightmax[i][x][j] + 1);
if (pr[x] <= pr[j]) dp_rightmax[i][j][x] = max(dp_rightmax[i][j][x], dp_rightmax[y][j][x] + dp_rightmin[i][x][j] + 1);
}
}
int mx_left = -INF;
int mx_right = -INF;
for (int k = 0; k <= n; k++) {
int p = k;
while (p <= n && b[p].fi == b[k].fi) {
mx_left = max(mx_left, dp_leftmin[i][j][b[p].se]);
mx_right = max(mx_right, dp_rightmin[i][j][b[p].se]);
p++;
}
for (int l = k; l < p; l++) {
dp_leftmin[i][j][b[l].se] = mx_left;
dp_rightmin[i][j][b[l].se] = mx_right;
}
k = p - 1;
}
mx_left = -INF;
mx_right = -INF;
for (int k = n; k >= 0; k--) {
int p = k;
while (p >= 0 && b[p].fi == b[k].fi) {
mx_left = max(mx_left, dp_leftmax[i][j][b[p].se]);
mx_right = max(mx_right, dp_rightmax[i][j][b[p].se]);
p--;
}
for (int l = k; l > p; l--) {
dp_leftmax[i][j][b[l].se] = mx_left;
dp_rightmax[i][j][b[l].se] = mx_right;
}
k = p + 1;
}
}
}
int ans = -INF;
ans = max(ans, dp_leftmin[0][n][n]);
ans = max(ans, dp_leftmax[0][n][n]);
for (int x = 0; x <= n; x++) {
for (int y = x + 1; y <= n; y++) {
ans = max(ans, dp_rightmin[0][x][y] + dp_leftmax[y][n][x] + 1);
ans = max(ans, dp_rightmax[0][x][y] + dp_leftmin[y][n][x] + 1);
}
}
cout << ans << "\n";
}
int main() {
#ifdef LOCAL
freopen("input", "r", stdin);
freopen("output", "w", stdout);
#else
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#endif
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
|
1868
|
F
|
LIS?
|
Entering senior high school life, Tom is attracted by LIS problems, not only the Longest Increasing Subsequence problem, but also the Largest Interval Sum problem. Now he gets a really interesting problem from his friend Daniel. However, it seems too hard for him to solve it, so he asks you for help.
Given an array $a$ consisting of $n$ integers.
In one operation, you do the following:
- Select an interval $[l,r]$ ($1\le l\le r\le n$), such that the sum of the interval is the largest among \textbf{all intervals} in the array $a$. More formally, $\displaystyle\sum_{i=l}^r a_i=\max_{1\le l'\le r'\le n}\sum_{i=l'}^{r'} a_i$.
- Then subtract $1$ from all elements $a_l,a_{l+1},\ldots,a_r$.
Find the minimum number of operations you need to perform to make $a_i<0$ for every $1\le i\le n$.
|
Call an interval candidate good if and only if it has no prefixes or suffixes with sum $<0$. For a candidate good interval $[l,r]$, if there is no $l'<l$ or $r'>r$ such that $[l',r]$, $[l,r']$ or $[l',r']$ is also a candidate good interval, we call it good interval. It's easy to show that all intervals which satisfy the condition in the statement are candidate good intervals and at least one of them is a good interval. Lemma 1. For two good intervals $[l_1,r_1]$ and $[l_2,r_2]$, they will never intersect. More formally: either $r_1<l_2$ or $r_2<l_1$; or $l_2 \le l_1\le r_1\le r_2$. Greedy Algorithm. In each operation, we choose one good interval that satisfies the condition in the statement. This will give the minimum answer. Following our process of the greedy algorithm, it's easy to see that the intervals on which we perform operations each time will form a tree structure. If we do the operation on one such interval, then one of the following happens: The interval remains good; The interval is no longer good, and we can split it into several good intervals. In the first case, we can keep doing operations on this interval without thinking whether it will have the largest sum among all intervals since it remains good, and all good intervals must be split into shorter good intervals unless it has length $1$. In this case, we can simply do the operations until the only element falls $\le0$. In the second case, let $(L_i,d)$ means that if all the elements in the interval decrease $d$ ($d$ is the smallest integer which meets with the following), then $s(L_i,r)>s(l,r)$. That is, $d=\min_{l <l'\le r}\frac{s_r-s_{l'-1}}{r-l'},$ Have you noticed that it is very similar to the slope between points $(l'-1,s_{l'-1})$ and $(r,s_r)$ on a 2-D plane? So what we need to find is just the first point before $(r,s_r)$ (after $(l,s_l)$) in the convex hull for points $(l,s_l),(l+1,s_{l+1}),...,(r,r_s)$. To find it, we can use a segment tree to directly maintain the convex hull for certain intervals, each time we query $\mathcal{O}(\log n)$ intervals and do ternary search on the convex hull of each interval. This step will cost $\mathcal{O}(\log^2 n)$. In each split, the number of good intervals increases $1$, so we do at most $n$ splits. Overall time complexity is $\mathcal{O}(n\log^2 n)$.
|
[
"data structures",
"greedy",
"implementation"
] | 3,500
|
/*
hmz is cute!
--------------------------------------------
You've got to have faith
Don't let them cut you down cut you down once more
*/
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include<bits/stdc++.h>
using namespace std;
#define TY long long
#define IL inline
#define umap unordered_map
#define ull unsigned long long
#define pq priority_queue
#define mp make_pair
#define pb push_back
#define mod (TY)(1e9+7)
#define MAXN 500005
#define MAXM 200005
#define MAXK 27
#define INF (TY)(1e9)
#define block 300
#define For(i,a,b) for(TY i=(a);i<=(b);++i)
#define FOR(i,a,b) for(TY i=(a);i<(b);++i)
#define Rof(i,a,b) for(TY i=(a);i>=(b);--i)
#define ROF(i,a,b) for(TY i=(a);i>(b);--i)
IL TY qr(){
TY x=0,f=1;char op=getchar();
for(;op<'0'||op>'9';op=getchar())if(op=='-')f=-1;
for(;op>='0'&&op<='9';op=getchar())x=x*10+(op^48);
return x*f;
}IL bool ischar(char op){
if(op>='a'&&op<='z')return true;
if(op>='A'&&op<='Z')return true;
return false;
}IL char getc(){
char op=getchar();
while(!ischar(op))op=getchar();
return op;
}IL string qs(){
string op="";char u=getchar();
while(!ischar(u))u=getchar();
while(ischar(u))op+=u,u=getchar();
return op;
}IL void qw(long long x){
if(!x){putchar('0');return;}
if(x<0)putchar('-'),x=-x;
if(x>=10)qw(x/10);putchar(x%10+'0');
}IL void qw(long long x,char op){qw(x),putchar(op);}
IL void ws(string s){FOR(i,0,s.size())putchar(s[i]);}
IL TY Ceil(TY a,TY b){return a/b+(a%b!=0);}
IL TY Mod(TY a){return (a>=mod?a-mod:a);}
IL TY Abs(TY a,TY b){return a>b?a-b:b-a;}
IL TY Pow(TY a,TY b){
TY ans=1,base=a;
while(b){
if(b&1)ans=ans*base%mod;
base=base*base%mod;b>>=1;
}return ans;
}TY n,a[MAXN],b[MAXN],sum[MAXN],lenx[MAXN],leny[MAXN],ans;
vector<signed> e1[MAXN],e2[MAXN],HH;
TY Sum[MAXN],SSum[MAXN];
bool vis[MAXN];
signed L[MAXN],R[MAXN],LL[MAXN],RR[MAXN],ok[MAXN],nxtx[MAXN],nxty[MAXN];
struct node{TY l,r,tag,op;};queue<node> q;
IL void init(TY l,TY r,TY tag){
For(i,l,r)e1[i].clear(),e2[i].clear();
vector<pair<TY,TY> > pre,nxt;
For(i,l,r){
while(!pre.empty()){
TY ch=(pre.back().second*-1+tag)*(i-pre.back().first)+sum[i]-sum[pre.back().first];
if(ch<0){
nxtx[pre.back().first]=i;
pre.pop_back();continue;
}else{
lenx[i]=pre.back().second+Ceil(ch+1,i-pre.back().first);
pre.push_back({i,pre.back().second+Ceil(ch+1,i-pre.back().first)});
break;
}
}if(pre.empty()){
lenx[i]=Ceil(sum[i]-sum[l-1]+tag*(i-l+1)+1,i-l+1);
pre.push_back({i,Ceil(sum[i]-sum[l-1]+tag*(i-l+1)+1,i-l+1)});
}
}while(!pre.empty())nxtx[pre.back().first]=r+1,pre.pop_back();
Rof(i,r,l){
while(!nxt.empty()){
TY ch=(nxt.back().second*-1+tag)*(nxt.back().first-i)-sum[i-1]+sum[nxt.back().first-1];
if(ch<0){
nxty[nxt.back().first]=i;
nxt.pop_back();continue;
}else{
leny[i]=nxt.back().second+Ceil(ch+1,nxt.back().first-i);
nxt.push_back({i,nxt.back().second+Ceil(ch+1,nxt.back().first-i)});
break;
}
}if(nxt.empty()){
leny[i]=Ceil(sum[r]-sum[i-1]+tag*(r-i+1)+1,r-i+1);
nxt.push_back({i,Ceil(sum[r]-sum[i-1]+tag*(r-i+1)+1,r-i+1)});
}
}while(!nxt.empty())nxty[nxt.back().first]=l-1,nxt.pop_back();
For(i,l,r)if(nxtx[i]!=r+1)e1[nxtx[i]].pb(i);
Rof(i,r,l)if(nxty[i]!=l-1)e2[nxty[i]].pb(i);
}int main(){
//freopen("data.in","r",stdin);
/* init */
n=qr();For(i,1,n)a[i]=qr(),sum[i]=sum[i-1]+a[i];
q.push({1,n,0,0});
while(!q.empty()){
TY l=q.front().l,r=q.front().r,tag=q.front().tag,op=q.front().op;
if(l>r||l<=0||r>n)continue;
q.pop();
if(op==0){
vector<pair<TY,TY> > tmp;
TY c=0;TY lst=-1;
For(i,l,r)b[i]=a[i]+tag;
For(i,l,r){
if((b[i]>=0)!=lst){
lst=(b[i]>=0);
++c;L[c]=R[c]=i;
Sum[c]=b[i];
}else R[c]=i,Sum[c]+=b[i];
}For(i,1,c)LL[i]=i,RR[i]=i,SSum[i]=Sum[i],ok[i]=0,vis[i]=1;
Sum[c+1]=0;RR[c+1]=INF;
For(i,1,c)if(Sum[i]<0){
ok[i]=(Sum[i-1]+Sum[i]>=0)+(Sum[i+1]+Sum[i]>=0);
if(ok[i]==2)HH.pb(i),ok[i]=INF;
}else{
ok[i]=(Sum[i-1]+Sum[i]<0)+(Sum[i+1]+Sum[i]<0);
if(ok[i]==2)HH.pb(i),ok[i]=INF;
}while(!HH.empty()){
TY now=HH.back(),nowL=LL[now],nowR=RR[now];
TY k=SSum[nowL]+SSum[nowL-1]+SSum[nowR+1],pre=LL[LL[nowL-1]-1],nxt=RR[nowR+1]+1;
HH.pop_back();
if(SSum[nowL]>=0){
if(pre>=1&&nxt<=c){
ok[LL[nowL-1]]=(k+SSum[pre]>=0)+(k+SSum[nxt]>=0);
if(ok[LL[nowL-1]]==2)HH.pb(LL[nowL-1]),ok[LL[nowL-1]]=INF;
}else ok[LL[nowL-1]]=INF;
if(pre>=1){
ok[pre]+=-(SSum[nowL-1]+SSum[pre]<0)+(SSum[pre]+k<0);
if(ok[pre]==2&&SSum[nowL-1]+SSum[pre]>=0)HH.pb(pre),ok[pre]=INF;
}if(nxt<=c){
ok[nxt]+=-(SSum[nowR+1]+SSum[nxt]<0)+(SSum[nxt]+k<0);
if(ok[nxt]==2&&SSum[nowR+1]+SSum[nxt]>=0)HH.pb(nxt),ok[nxt]=INF;
}
}else{
if(pre>=1&&nxt<=c){
ok[LL[nowL-1]]=(k+SSum[pre]<0)+(k+SSum[nxt]<0);
if(ok[LL[nowL-1]]==2)HH.pb(LL[nowL-1]),ok[LL[nowL-1]]=INF;
}else ok[LL[nowL-1]]=INF;
if(pre>=1){
ok[pre]+=-(SSum[nowL-1]+SSum[pre]>=0)+(SSum[pre]+k>=0);
if(ok[pre]==2&&SSum[nowL-1]+SSum[pre]<0)HH.pb(pre),ok[pre]=INF;
}if(nxt<=c){
ok[nxt]+=-(SSum[nowR+1]+SSum[nxt]>=0)+(SSum[nxt]+k>=0);
if(ok[nxt]==2&&SSum[nowR+1]+SSum[nxt]<0)HH.pb(nxt),ok[nxt]=INF;
}
}SSum[LL[nowL-1]]=SSum[RR[nowR+1]]=k;
RR[LL[nowL-1]]=RR[nowR+1];
LL[RR[nowR+1]]=LL[nowL-1];
}Rof(i,c,1)if(Sum[i]>=0&&vis[i]){
Rof(j,i,LL[i])vis[j]=0;
tmp.pb({L[LL[i]],R[RR[i]]});
}Rof(i,tmp.size()-1,0)q.push({tmp[i].first,tmp[i].second,tag,1});
}else{
if(l==r){
ans+=a[l]+tag+1;
continue;
}queue<TY> fir,sec;
init(l,r,tag);
For(i,l,r)if(nxtx[i]==r+1)fir.push(i);
Rof(i,r,l)if(nxty[i]==l-1)sec.push(i);
TY lstl=l,lstr=r,lstcnt=0;
while(lstl<lstr){
while(!fir.empty()&&(lstl>fir.front()||fir.front()>lstr))fir.pop();
while(!sec.empty()&&(lstl>sec.front()||sec.front()>lstr))sec.pop();
TY id1=(fir.empty()?INF:fir.front()),id2=(sec.empty()?INF:sec.front());
TY cnt1=(id1==INF?INF:lenx[id1]-lstcnt);
TY cnt2=(id2==INF?INF:leny[id2]-lstcnt);
if(cnt1<=cnt2){
fir.pop();
lstcnt=lenx[id1];
For(j,lstl,id1){FOR(i,0,e2[j].size())sec.push(e2[j][i]);e2[j].clear();}
q.push({lstl,id1,-lstcnt+tag,0});
lstl=id1+1;
}else{
sec.pop();
lstcnt=leny[id2];
Rof(j,lstr,id2){FOR(i,0,e1[j].size())fir.push(e1[j][i]);e1[j].clear();}
q.push({id2,lstr,-lstcnt+tag,0});
lstr=id2-1;
}
}if(lstl==lstr)q.push({lstl,lstl,-lstcnt+tag,1});
ans+=lstcnt;
}
}qw(ans);
return 0;
}
|
1869
|
A
|
Make It Zero
|
During Zhongkao examination, Reycloer met an interesting problem, but he cannot come up with a solution immediately. Time is running out! Please help him.
Initially, you are given an array $a$ consisting of $n \ge 2$ integers, and you want to change all elements in it to $0$.
In one operation, you select two indices $l$ and $r$ ($1\le l\le r\le n$) and do the following:
- Let $s=a_l\oplus a_{l+1}\oplus \ldots \oplus a_r$, where $\oplus$ denotes the bitwise XOR operation;
- Then, for all $l\le i\le r$, replace $a_i$ with $s$.
You can use the operation above in any order at most $8$ times in total.
Find a sequence of operations, such that after performing the operations in order, all elements in $a$ are equal to $0$. It can be proven that the solution always exists.
|
Note that $\underbrace{x\oplus x\oplus \cdots\oplus x}_{\text{even times}}=0,$ So if $r-l+1$ is even, after performing the operation on $[l,r]$ twice, the subarray $a[l;r]$ will all become $0$. When $n$ is even, we can perform the operation on $[1,n]$ twice. When $n$ is odd, we can perform the operation on $[1,n-1]$ twice. After that the array becomes $[0,0,\ldots,0,a_n]$. Then perform the operation on $[n-1,n]$ twice. Time Complexity: $\mathcal{O}(n)$ per test case.
|
[
"constructive algorithms"
] | 900
|
#include <bits/stdc++.h>
#define all(s) s.begin(), s.end()
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int _N = 1e5 + 5;
int T;
void solve() {
int n; cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
if (n & 1) {
cout << "4" << '\n';
cout << "1 " << n - 1 << '\n';
cout << "1 " << n - 1 << '\n';
cout << n - 1 << ' ' << n << '\n';
cout << n - 1 << ' ' << n << '\n';
} else {
cout << "2" << '\n';
cout << "1 " << n << '\n';
cout << "1 " << n << '\n';
}
return;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> T;
while (T--) {
solve();
}
}
|
1869
|
B
|
2D Traveling
|
Piggy lives on an infinite plane with the Cartesian coordinate system on it.
There are $n$ cities on the plane, numbered from $1$ to $n$, and the first $k$ cities are defined as major cities. The coordinates of the $i$-th city are $(x_i,y_i)$.
Piggy, as a well-experienced traveller, wants to have a relaxing trip after Zhongkao examination. Currently, he is in city $a$, and he wants to travel to city $b$ by air. You can fly between any two cities, and you can visit several cities in any order while travelling, but the final destination must be city $b$.
Because of active trade between major cities, it's possible to travel by plane between them for free. Formally, the price of an air ticket $f(i,j)$ between two cities $i$ and $j$ is defined as follows:
$$ f(i,j)= \begin{cases} 0, & \text{if cities }i \text{ and }j \text{ are both major cities} \\ |x_i-x_j|+|y_i-y_j|, & \text{otherwise} \end{cases} $$
Piggy doesn't want to save time, but he wants to save money. So you need to tell him the \textbf{minimum} value of the total cost of all air tickets if he can take any number of flights.
|
First of all, it's easy to see that if there are no major cities, the minimum value of the total cost should be $|x_a-x_b|+|y_a-y_b|$ - the optimal choice is to fly directly from city $a$ to city $b$. Claim. Piggy will pass through a maximum of $2$ major cities. Proof. If he passes through $3$ or more major cities in a row, then he can fly directly from the first one to the last one. If he passes through $2$ major cities and passes an ordinary city between them, the cost must be higher than flying directly between these two major cities. So the optimal choice always consists of no more than $2$ major cities, and they are in a row. Thus, you can express the optimal choice as $a(\to s)(\to t)\to b$, where $s$ and $t$ are both major cities. If you naively enumerate $s$ and $t$, the total complexity of the solution will be $\mathcal O(k^2)$. But after seeing that $s$ and $t$ work independently, we can enumerate them separately. The total complexity decreases to $\mathcal O(n+k)$.
|
[
"geometry",
"math",
"shortest paths",
"sortings"
] | 1,100
|
#include <bits/stdc++.h>
#define all(s) s.begin(), s.end()
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int _N = 1e5 + 5;
int T;
void solve() {
int n, k, s, t; cin >> n >> k >> s >> t;
vector<int> x(n + 1), y(n + 1);
for (int i = 1; i <= n; i++) cin >> x[i] >> y[i];
ll ans = llabs(x[s] - x[t]) + llabs(y[s] - y[t]);
ll mins = LLONG_MAX / 2, mint = LLONG_MAX / 2;
for (int i = 1; i <= k; i++) {
mins = min(mins, llabs(x[s] - x[i]) + llabs(y[s] - y[i]));
mint = min(mint, llabs(x[t] - x[i]) + llabs(y[t] - y[i]));
}
ans = min(ans, mins + mint);
cout << ans << '\n';
return;
}
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> T;
while (T--) {
solve();
}
}
|
1870
|
A
|
MEXanized Array
|
You are given three non-negative integers $n$, $k$, and $x$. Find the maximum possible sum of elements in an array consisting of non-negative integers, which has $n$ elements, its MEX is equal to $k$, and all its elements do not exceed $x$. If such an array does not exist, output $-1$.
The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:
- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.
- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.
- The MEX of $[0,3,1,2]$ is $4$, because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.
|
Note that if $min(n, x+1) < k$, then the answer is $-1$. Otherwise, there are two cases: If $k=x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, \dots, k-1]$. If $k=x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, \dots, k-1]$. If $k \ne x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, x, \dots, x]$. If $k \ne x$, then the suitable array looks like $[0, 1, 2, \dots, k-1, x, \dots, x]$. In both cases, we can construct the array and calculate its sum in linear time. The overall complexity is $O(n \cdot t)$.
|
[
"constructive algorithms",
"greedy",
"math"
] | 800
| null |
1870
|
B
|
Friendly Arrays
|
You are given two arrays of integers — $a_1, \ldots, a_n$ of length $n$, and $b_1, \ldots, b_m$ of length $m$. You can choose any element $b_j$ from array $b$ ($1 \leq j \leq m$), and for \textbf{all} $1 \leq i \leq n$ perform $a_i = a_i | b_j$. You can perform any number of such operations.
After all the operations, the value of $x = a_1 \oplus a_2 \oplus \ldots \oplus a_n$ will be calculated. Find the minimum and maximum values of $x$ that could be obtained after performing any set of operations.
Above, $|$ is the bitwise OR operation, and $\oplus$ is the bitwise XOR operation.
|
Note that after performing the operation on $b_j$, which has some bit set to 1, this bit will become 1 for all numbers in $a$ (and will remain so, as a bit cannot change from 1 to 0 in the result of an OR operation). If $n$ is even, then in the final XOR, this bit will become 0, as it will be equal to the XOR of an even number of ones. If $n$ is odd, then this bit will be 1 in the final XOR. Therefore, if $n$ is even, by performing the operation on $b_j$, we set all the bits that are 1 in $b_j$ to 0 in the final XOR. If $n$ is odd, we do the opposite and set these bits to 1. So, if $n$ is even, the XOR does not increase when applying the operation, which means that to obtain the minimum possible XOR, we need to apply the operation to all the numbers in $b$, and the maximum XOR will be the original XOR. For odd $n$, it is the opposite: the minimum is the original XOR, and the maximum is obtained after applying the operation to all elements in $b$. To apply the operation to all elements in $b$, it is sufficient to calculate their bitwise OR and apply the operation to the array $a$ with it.
|
[
"bitmasks",
"greedy",
"math"
] | 1,200
| null |
1870
|
C
|
Colorful Table
|
You are given two integers $n$ and $k$. You are also given an array of integers $a_1, a_2, \ldots, a_n$ of size $n$. It is known that for all $1 \leq i \leq n$, $1 \leq a_i \leq k$.
Define a two-dimensional array $b$ of size $n \times n$ as follows: $b_{i, j} = \min(a_i, a_j)$. Represent array $b$ as a square, where the upper left cell is $b_{1, 1}$, rows are numbered from top to bottom from $1$ to $n$, and columns are numbered from left to right from $1$ to $n$. Let the color of a cell be the number written in it (for a cell with coordinates $(i, j)$, this is $b_{i, j}$).
For each color from $1$ to $k$, find the smallest rectangle in the array $b$ containing all cells of this color. Output the sum of width and height of this rectangle.
|
Let's fix the color $x$ for which we will calculate the answer. If there is no $a_i = x$, then there will be no cells of color $x$, and the answer is $0$. Otherwise, there is at least one cell of color $x$. To find the minimum rectangle containing all cells of this color, we need to find the topmost, bottommost, leftmost, and rightmost cells of this color in the array $b$. Let's find the prefix in $a$ of the maximum length, where all numbers are strictly less than $x$. Let the length of this prefix be $L$. Then in the first $L$ rows and columns of the array $b$, there will be no cells of color $x$, because for all these cells, the formula $b_{i, j} = min(a_i, a_j)$ will have a number from the prefix, and all numbers on it are less than $x$. In the $L+1$-th row and $L+1$-th column, there will be cells of color $x$, because $a_{L+1} \geq x$. Thus, we have found the topmost and leftmost cells of color $x$. To find the bottom and right cells, we need to find the longest suffix where all numbers are less than $x$. Now we need to learn how to quickly find prefixes and suffixes for all colors. Notice that the prefix for color $x$ is not shorter than the prefix for color $x + 1$, so all prefixes can be calculated in just one pass through the array, similarly for suffixes.
|
[
"binary search",
"data structures",
"dp",
"implementation",
"math",
"two pointers"
] | 1,300
| null |
1870
|
D
|
Prefix Purchase
|
You have an array $a$ of size $n$, initially filled with zeros ($a_1 = a_2 = \ldots = a_n = 0$). You also have an array of integers $c$ of size $n$.
Initially, you have $k$ coins. By paying $c_i$ coins, you can add $1$ to all elements of the array $a$ from the first to the $i$-th element ($a_j \mathrel{+}= 1$ for all $1 \leq j \leq i$). You can buy any $c_i$ any number of times. A purchase is only possible if $k \geq c_i$, meaning that at any moment $k \geq 0$ must hold true.
Find the lexicographically largest array $a$ that can be obtained.
An array $a$ is lexicographically smaller than an array $b$ of the same length if and only if in the first position where $a$ and $b$ differ, the element in array $a$ is smaller than the corresponding element in $b$.
|
Note that if there is a prefix for which there is a longer prefix that costs less, then it is useless to buy the shorter prefix. All its purchases can be replaced with purchases of the longer prefix, and the answer will only improve. Therefore, we can replace each $c_i$ with the minimum $c_j$ among $i \leq j \leq n$ (the minimum price of a prefix of length at least $i$). After this, we will have $c_i \leq c_{i+1}$. Now let's solve the problem greedily. We want to maximize the first element of the resulting array. It will be equal to $k / c_1$, since we cannot buy more prefixes of length $1$ ($c_1$ is the smallest price). After buying $k / c_1$ prefixes of length $1$, we will have some coins left. Now we can replace some purchases of $c_1$ with purchases of longer prefixes to improve the answer. How much will it cost to replace $c_1$ with $c_i$? It will cost $c_i - c_1$ coins. Moreover, note that to replace $c_1$ with $c_i$, we can sequentially replace $c_1$ with $c_2$, $c_2$ with $c_3$, $\ldots$, $c_{i-1}$ with $c_i$ (since $c_1 \leq c_2 \leq \ldots \leq c_i$). This means that we can make only replacements of purchases of $c_{i-1}$ with purchases of $c_i$. Let's say we have maximized the first $i-1$ elements of the answer, and we have $x$ coins left. Now we want to replace some purchases of $c_{i-1}$ with $c_i$. How many replacements can we make? We can afford to make no more than $\frac{x}{c_i - c_{i-1}}$ replacements (if $c_{i-1} = c_i$, then we can replace all $c_{i-1}$), and we cannot replace more purchases than we have made, so no more than $a_{i-1}$ replacements (this is the number of purchases of $c_{i-1}$). Therefore, $a_i = \min(a_{i-1}, \frac{x}{c_i - c_{i-1}})$, as we want to maximize $a_i$. Finally, subtract the cost of replacements from the number of coins and move on to $c_{i+1}$.
|
[
"greedy",
"implementation",
"sortings"
] | 1,800
| null |
1870
|
E
|
Another MEX Problem
|
You are given an array of integers $a$ of size $n$. You can choose a set of non-overlapping subarrays of the given array (note that some elements may be not included in any subarray, this is allowed). For each selected subarray, calculate the MEX of its elements, and then calculate the bitwise XOR of all the obtained MEX values. What is the maximum bitwise XOR that can be obtained?
The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:
- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.
- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.
- The MEX of $[0,3,1,2]$ is $4$, because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.
|
Let's solve the problem using dynamic programming, let's store $dp[i][j]$ such that $dp[i][j]=1$ if it is possible to obtain an $XOR$ of $MEX$ values from the prefix up to $i$ (excluding $i$) equal to $j$, and $0$ otherwise. Notice that the answer cannot be greater than $n$. Therefore, the size of this two-dimensional array is $O(n^2)$. Let's learn how to solve this in $O(n^3)$: We iterate over $l$ from $1$ to $n$, and inside that, we iterate over $r$ from $l$ to $n$, maintaining the value $x=MEX([a_l, a_{l+1}, \dots, a_r])$. Then, for all $j$ from $0$ to $n$, we update $dp[r+1][j \oplus x]=1$ if $dp[l][j]=1$. This way, we update based on the case when the resulting set includes the set $[a_l, a_{l+1}, \dots, a_r]$. We also need to update if $dp[l][x]=1$, we assign $dp[l+1][x]=1$. This accounts for the case when we do not include $a_l$ in the answer. Let's define $MEX(l, r) = MEX([a_l, a_{l+1}, \dots, a_r])$, this will make the following text clearer. Let's consider the segment $l, r$. Notice that if there exist $l_2$ and $r_2$ ($l \leq l_2 \leq r_2 \leq r$) such that $l_2 \ne l$ or $r_2 \ne r$ and $MEX(l, r)=MEX(l_2, r_2)$, then we can take the segment $l_2, r_2$ instead of the segment $l, r$ in the set of $MEX$ values, and the answer will remain the same. If, however, there is no such segment $l_2, r_2$ for the segment $l, r$, then we call this segment $l, r$ irreplaceable. Now let's prove that there are no more than $n \cdot 2$ irreplaceable segments. For each irreplaceable segment, let's look at the larger element of the pair $a_l, a_r$, let's assume $a_l$ is larger (the other case is symmetric). Now, let's prove that there is at most one segment where $a_l$ is the left element and $a_l \geq a_r$, by contradiction: Suppose there are at least 2 such segments, let's call their right boundaries $r_1, r_2$ ($r_1 < r_2$). Notice that $MEX(l, r_1) > a_l$, otherwise the segment $l, r_1$ would not be irreplaceable (we could remove $a_l$). Since $a_l \geq a_{r_2}$, then $MEX(l, r_1) > a_{r_2}$. It is obvious that $a_{r_2}$ appears among the elements $[a_l, \dots, a_{r_1}]$, and therefore $MEX(l, r_2-1) = MEX(l, r_2)$, which means that the segment $l, r_2$ is not irreplaceable, contradiction. For each $a_i$, there is at most one irreplaceable segment where it is the smaller of the two extremes, and at most one where it is the larger. Therefore, the total number of irreplaceable segments is no more than $2 \cdot n$. Let's update the DP only through the irreplaceable segments, then the solution works in $O(n^2+n \cdot C)$ time, where $C$ is the number of irreplaceable segments. However, we have already proven that $C\leq 2n$, so the overall time complexity is $O(n^2)$.
|
[
"bitmasks",
"brute force",
"dp",
"shortest paths"
] | 2,300
| null |
1870
|
F
|
Lazy Numbers
|
You are given positive integers $n$ and $k$. For each number from $1$ to $n$, we write its representation in the number system with base $k$ (without leading zeros) and then sort the resulting array in lexicographic order as strings. In the sorted array, we number the elements from $1$ to $n$ (i.e., indexing starts from $1$). Find the number of values $i$ such that the representation of number $i$ is at the $i$-th position in the sorted array of representations.
Examples of representations: $1$ in any number system is equal to $1$, $7$ with $k = 3$ is written as $21$, and $81$ with $k = 9$ is written as $100$.
|
Let's store all the number entries in a trie. Consider two traversals of this trie - depth-first search (DFS) and breadth-first search (BFS). In both traversals, we go to the children of a node in ascending order of the number on the edge (in the trie). Let the index of the node representing the number $x$ in the DFS traversal be $dfs(x)$, and in the BFS traversal be $bfs(x)$. Then notice that $x = bfs(x)$, as in BFS on the trie, we simply look at all the number entries with a certain length in order (lengths are concidered in increasing order). On the other hand, $dfs(x)$ is the index of the number entry $x$ in the sorted array. Therefore, we want to calculate the number of $x$ for which $dfs(x) = bfs(x)$. Let's fix a layer in the trie, meaning we only consider numbers with a fixed, equal length of representation. Then let's look at $dfs(x) - bfs(x)$ for the numbers in this layer. Notice that for two numbers $y$ and $y + 1$ in this layer, it holds that $bfs(y + 1) - bfs(y) = 1$, and $dfs(y + 1) - dfs(y) \geq 1$. This means that for a fixed layer, the function $dfs(x) - bfs(x)$ is non-decreasing. Therefore, we can find the $0$ of this function using binary search on each layer. Now let's learn how to calculate $dfs(x) - bfs(x)$. $bfs(x) = x$, which we can calculate. To find $dfs(x)$, we can traverse up from the trie node corresponding to $x$, and at each step, add the sizes of the subtrees that we have traversed in DFS before the subtree with the node $x$. The trie has a depth of $O(\log(n))$, binary search takes the same time, so the overall asymptotic complexity of the solution is $O(\log^3(n))$. I apologize for the issues some participants faced with the time limit, if they implemented the author's idea suboptimally.
|
[
"binary search",
"math"
] | 2,900
| null |
1870
|
G
|
MEXanization
|
Let's define $f(S)$. Let $S$ be a multiset (i.e., it can contain repeated elements) of non-negative integers. In one operation, you can choose any non-empty subset of $S$ (which can also contain repeated elements), remove this subset (all elements in it) from $S$, and add the MEX of the removed subset to $S$. You can perform any number of such operations. After all the operations, $S$ should contain exactly $1$ number. $f(S)$ is the largest number that could remain in $S$ after any sequence of operations.
You are given an array of non-negative integers $a$ of length $n$. For each of its $n$ prefixes, calculate $f(S)$ if $S$ is the corresponding prefix (for the $i$-th prefix, $S$ consists of the first $i$ elements of array $a$).
The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:
- The MEX of $[2,2,1]$ is $0$, because $0$ does not belong to the array.
- The MEX of $[3,1,0,1]$ is $2$, because $0$ and $1$ belong to the array, but $2$ does not.
- The MEX of $[0,3,1,2]$ is $4$, because $0$, $1$, $2$ and $3$ belong to the array, but $4$ does not.
|
Let's start by introducing a more convenient way to store numbers - an array $cnt$, where $cnt[x]$ represents the number of occurrences of $x$ in the prefix for which we are finding the answer. All $x$ such that $x > n$ will be added to $cnt[0]$ because applying the operation to ${x}$ in such cases is optimal. Let's introduce a few array operations that will be sufficient to solve the problem. Create the number $x$. Apply the operation to the set of numbers ${0, 1, 2, \dots, x-1}$. In terms of the array $cnt$, this is equivalent to subtracting $1$ from the range $0$ to $x-1$ and adding $1$ to $cnt[x]$. Turn the number $x$ into $0$. To do this, apply the operation to ${x}$. In terms of the array $cnt$, this is equivalent to subtracting $1$ from $cnt[x]$ and adding $1$ to $cnt[0]$. Create the number $x$ and clear the multiset. This is the same as creating the number $x$, but we apply the operation to all other numbers, leaving only the single number $x$ (or a larger number) in the set. It can be proven that by using only operations of this kind, we can always obtain the optimal answer. Now we can forget about the original condition and solve the problem for the array. Let's learn how to check if it is possible to create the number $k$ and clear the multiset: First, let's try to create the number $k$. If it is possible, the answer is yes. Otherwise, we look at the rightmost number that is missing (or in other words, the rightmost $0$). We try to create it, and now we need to find the rightmost element $\leq 1$ to the left of it, and so on. To implement this, we need to maintain a number $p$ such that we subtract $p$ from all elements in the prefix (initially $p=1$), iterate through the array from right to left, and if $cnt[i]<p$, assign $p \mathrel{{+}{=}} (p-cnt[i])$. When we reach zero, $p$ may be greater than $cnt[0]$, in which case we need to use the operation to turn any number into $0$. To do this, simply check that the remaining number of elements in the array is greater than or equal to $p$. This currently works in $O(k)$ time, which is not very efficient. Optimization techniques: First, let's maintain the sum of elements $sm$ and as soon as it becomes negative, terminate the process. To achieve this, when subtracting $p-cnt[i]$ from $p$, let's subtract $(p-cnt[i])\cdot(i-1)$ from $sm$. Now let's use a bottom-up segment tree to find the nearest number smaller than $p$ to the left in $O(\log(i))$ time. Now let's notice that when we update through $cnt[i]$, we subtract at least $i-1$ from $sm$, so there can't be more than $O(\sqrt{n})$ different values of $i$ through which we will update. Now we can answer for a specific $k$ in $O(\sqrt{n} \cdot \log(n))$ time, but in reality, the complexity is $O(\sqrt{n})$ (due to the peculiarities of the bottom-up segment tree), and the authors have a proof for this, but they are afraid that you will find an error in it, so they decided not to provide it(we will add proof later). Now let's see how to solve the full problem: Initially, the answer is $0$, and we notice that it does not decrease. So after each addition, we will check if it is possible to increase the answer and increase it as long as possible. The answer cannot exceed $n$, so we will perform no more than $2 \cdot n$ checks. Overall, the solution works in $O(n \cdot \sqrt{n})$ time. That's how it is. Let's consider that in our query, the segment tree processed $k$ nodes $[x_1, x_2, \dots, x_k]$ from the bottom. Then, the number of operations is the sum of $dist(x_i, x_{i+1})$ for $i$ from 1 to $k-1$, and $dist(0, x_1)$, where $dist$ represents the length of the path between nodes in the segment tree. Now, let's notice that for the query $dist(a, b)$, we enter the segment tree node responsible for a block of length $2^t$ only if $a$ and $b$ are in different blocks of length $2^{t-1}$, which is logical. Also, let's notice that this doesn't happen very often, specifically, the numbers $[x_1, x_2, \dots, x_k]$ can be part of a maximum of $\sqrt{\frac{n}{2^t}}$ blocks of length $2^t$ (asymptotically). Therefore, the sum of all queries is asymptotically equal to the sum of $\sqrt{\frac{n}{2^t}}$ for $t$ from 0 to 20, which is a geometric progression with a ratio of $\frac{1}{\sqrt{2}}$. Hence, the sum is asymptotically equal to $\sqrt{n}$. Proof completed.
|
[
"data structures"
] | 3,300
| null |
1870
|
H
|
Standard Graph Problem
|
You are given a weighted directed graph with $n$ vertices and $m$ edges. Each vertex in the graph can be either highlighted or normal. Initially, all vertices are normal. The cost of the graph is defined as the minimum sum of edge weights that need to be selected so that from each normal vertex one can reach at least one highlighted vertex using the selected edges only. If it is not possible to select the edges, the cost is $-1$ instead.
Your task is to compute the cost of the graph after each of the $q$ queries. The queries can be of two types:
- $+\;v_i$ makes vertex $v_i$ highlighted; it is guaranteed that the vertex is normal before the query.
- $-\;v_i$ makes vertex $v_i$ normal; it is guaranteed that the vertex is highlighted before the query.
Output the cost of the graph after each of the $q$ queries.
|
Let's unfold all the edges, now we need to ensure that all regular vertices are reachable from the selected vertices. First, you should familiarize yourself with the algorithm for finding the ordered minimum spanning tree, also known as the Edmonds' algorithm (I will refer to his work here and without knowledge of it, the solution cannot be understood). Next, it is worth noting that the compressions in the process of this algorithm (almost) do not depend on the root, and all compressions can be performed as if there is no root (previously creating dummy edges from $i$ to $i+1$ for $i$ from $1$ to $n-1$ and from vertex $n$ to vertex $1$ with a cost of $n * max(a_i)+1$). Then, after all the compressions, only one vertex will remain. Note that the difference from Edmonds' algorithm is that if at any step of the algorithm the minimum edge from a vertex leads to the root, compression is not necessary. So, let's maintain a tree in which each vertex corresponds to its corresponding compressed vertex or to the original vertex, and the children of vertex $v$ are all the vertices that we compressed to obtain vertex $v$. It is implied that with each compression, we create a new vertex. Let's call the cost of vertex $v$ the minimum cost of an edge leaving vertex $v$ in the process of Edmonds' algorithm (taking into account changes in edge costs during compression in Edmonds' algorithm). Then we need to maintain the sum of the costs of the vertices in the tree, in the subtrees of which there are no selected vertices (where the selected vertices can only be leaves). This can be easily done using a segment tree.
|
[
"data structures",
"graphs",
"greedy",
"trees"
] | 3,500
| null |
1872
|
A
|
Two Vessels
|
You have two vessels with water. The first vessel contains $a$ grams of water, and the second vessel contains $b$ grams of water. Both vessels are very large and can hold any amount of water.
You also have an empty cup that can hold \textbf{up to} $c$ grams of water.
In one move, you can scoop \textbf{up to} $c$ grams of water from any vessel and pour it into \textbf{the other} vessel. Note that the mass of water poured in one move \textbf{does not have to be an integer}.
What is the minimum number of moves required to make the masses of water in the vessels equal? Note that you cannot perform any actions other than the described moves.
|
Let $d = a - b$, the difference in masses of water in the vessels. Our goal is to make $d$ equal to $0$. Note that with one pouring, we can add any number from the range $[-2 \cdot c; 2 \cdot c]$ to $d$. Therefore, the answer to the problem will be $\lceil \frac{|d|}{2 \cdot c} \rceil$.
|
[
"brute force",
"greedy",
"math"
] | 800
|
for _ in range(int(input())):
a, b, c = map(int, input().split())
print((abs(a - b) + 2 * c - 1) // (2 * c))
|
1872
|
B
|
The Corridor or There and Back Again
|
You are in a corridor that extends infinitely to the right, divided into square rooms. You start in room $1$, proceed to room $k$, and then return to room $1$. You can choose the value of $k$. Moving to an adjacent room takes $1$ second.
Additionally, there are $n$ traps in the corridor: the $i$-th trap is located in room $d_i$ and will be activated $s_i$ seconds \textbf{after you enter the room} $\boldsymbol{d_i}$. Once a trap is activated, you cannot enter or exit a room with that trap.
\begin{center}
{\small A schematic representation of a possible corridor and your path to room $k$ and back.}
\end{center}
Determine the maximum value of $k$ that allows you to travel from room $1$ to room $k$ and then return to room $1$ safely.
For instance, if $n=1$ and $d_1=2, s_1=2$, you can proceed to room $k=2$ and return safely (the trap will activate at the moment $1+s_1=1+2=3$, it can't prevent you to return back). But if you attempt to reach room $k=3$, the trap will activate at the moment $1+s_1=1+2=3$, preventing your return (you would attempt to enter room $2$ on your way back at second $3$, but the activated trap would block you). Any larger value for $k$ is also not feasible. Thus, the answer is $k=2$.
|
Let's see when we can reach room $k$ and return back. In this case, the time difference between entering and exiting room $1 \le x \le k$ is equal to $2 \cdot (k - x)$. Therefore, it is necessary for all traps to satisfy: $s_i > 2 \cdot (k - d_i)$. Now we need to find the maximum $k$ that satisfies these conditions. To do this, we can either iterate through all $k$ from $1$ to $300$, or use binary search for the answer, or notice that $s_i > 2 \cdot (k - d_i) \to s_i + 2 \cdot d_i > 2 \cdot k \to d_i + \frac{s_i}{2} > k \to d_i + \frac{s_i - 1}{2} \geq k$
|
[
"greedy",
"implementation"
] | 900
|
for _ in range(int(input())):
n = int(input())
ans = 2 * 10 ** 9
for i in range(n):
d, s = map(int, input().split())
ans = min(ans, d + (s - 1) // 2)
print(ans)
|
1872
|
C
|
Non-coprime Split
|
You are given two integers $l \le r$. You need to find \textbf{positive} integers $a$ and $b$ such that the following conditions are simultaneously satisfied:
- $l \le a + b \le r$
- $\gcd(a, b) \neq 1$
or report that they do not exist.
$\gcd(a, b)$ denotes the greatest common divisor of numbers $a$ and $b$. For example, $\gcd(6, 9) = 3$, $\gcd(8, 9) = 1$, $\gcd(4, 2) = 2$.
|
To begin with, let's learn how to solve the problem when $l = r$. In other words, we need to find a value $1 \le a < l$ such that $\gcd(a, l - a) \neq 1$. Notice that $\gcd(a, l - a) = \gcd(a, l)$. Then it is easy to see that if $l$ is prime, then $\gcd(a, l) = 1$ for any $1 \le a < l$, otherwise any divisor of $l$ (except $1$ and $l$) will work as $a$. Thus, we can solve the problem when $l = r$ using the standard algorithm for primality testing in $O(\sqrt{r})$ time. Next, we can solve the problem in several ways: Sequentially check for primality all numbers from $l$ to $r$, and stop and output the answer as soon as we find the first composite number. This works faster than $O(r \sqrt r)$ because there are no two adjacent prime numbers starting from $3$, so the answer will be found very quickly. Handle the case $l = r$ separately. Also, separately consider the case $r \le 3$, in which the answer is $-1$. Otherwise, notice that since there are at least $2$ numbers in the interval $[l, r]$, there must be an even number in this interval. And for $r \ge 4$, the maximum even number in the interval, $s$, will be $\ge 4$, so for example, $a = \frac{s}{2}, b = \frac{s}{2}$ will be a valid answer. To find the maximum even number in the interval $l < r$, we can use the formula $r - r \% 2$.
|
[
"math",
"number theory"
] | 1,100
|
def min_divisor(n):
for d in range(2, round(n ** 0.5) + 1):
if n % d == 0:
return d
return n
for _ in range(int(input())):
l, r = map(int, input().split())
for x in range(l, r + 1):
md = min_divisor(x)
if md != x:
print(md, x - md)
break
else:
print(-1)
|
1872
|
D
|
Plus Minus Permutation
|
You are given $3$ integers — $n$, $x$, $y$. Let's call the score of a permutation$^\dagger$ $p_1, \ldots, p_n$ the following value:
$$(p_{1 \cdot x} + p_{2 \cdot x} + \ldots + p_{\lfloor \frac{n}{x} \rfloor \cdot x}) - (p_{1 \cdot y} + p_{2 \cdot y} + \ldots + p_{\lfloor \frac{n}{y} \rfloor \cdot y})$$
In other words, the score of a permutation is the sum of $p_i$ for all indices $i$ divisible by $x$, minus the sum of $p_i$ for all indices $i$ divisible by $y$.
You need to find the maximum possible score among all permutations of length $n$.
For example, if $n = 7$, $x = 2$, $y = 3$, the maximum score is achieved by the permutation $[2,\textcolor{red}{\underline{\color{black}{6}}},\textcolor{blue}{\underline{\color{black}{1}}},\textcolor{red}{\underline{\color{black}{7}}},5,\textcolor{blue}{\underline{\color{red}{\underline{\textcolor{black}{4}}}}},3]$ and is equal to $(6 + 7 + 4) - (1 + 4) = 17 - 5 = 12$.
$^\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 (the number $2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$, but the array contains $4$).
|
Let's call a number red if it is divisible by $x$. Let's call a number blue if it is divisible by $y$. Let's call a number purple if it is both red and blue at the same time. The score of a permutation, by definition, is the sum of $p_i$ for all red numbers $i$ from $1$ to $n$, minus the sum of $p_i$ for all blue numbers $i$ from $1$ to $n$. It is easy to see that $p_i$ at purple indices $i$ does not affect the score of the permutation: they are included in the sum once with a plus sign and once with a minus sign. Therefore, the score of the permutation is the sum of $p_i$ for "red but not purple indices" minus the sum of $p_i$ for "blue but not purple indices". Notice that the set of "red but not purple indices" and the set of "blue but not purple indices" cannot intersect, because if they had a common index, it would be purple. Therefore, it is obviously optimal to place the largest numbers possible on "red but not purple indices" and the smallest numbers possible on "blue but not purple indices". To calculate the number of indices that are "red but not purple", we can calculate the number of red indices and subtract the number of purple indices. The number of red indices is $\lfloor \frac{n}{x} \rfloor$, and the number of blue indices is calculated similarly. To calculate the number of purple indices, we need to notice that the condition "index is divisible by both $x$ and $y$" is equivalent to "index is divisible by $\operatorname{lcm}(x, y)$", where $\operatorname{lcm}$ denotes the least common multiple. Therefore, the number of purple indices is $\lfloor \frac{n}{\operatorname{lcm}(x, y)} \rfloor$. Let $R$ be the number of "red but not purple" indices, and let $B$ be the number of "blue but not purple" indices. Then it is not difficult to see that the maximum score is $(n + (n - 1) + \ldots + (n - (R - 1)) - (1 + 2 + \ldots + B)$. To quickly find this sum, we can use the formula for the sum of an arithmetic progression: $l + (l + 1) + \ldots + r = \frac{(l + r) \cdot (r - l + 1)}{2}$
|
[
"math"
] | 1,200
|
from math import gcd
def lcm(a, b):
return a * b // gcd(a, b)
def range_sum(l, r):
if l > r:
return 0
return (l + r) * (r - l + 1) // 2
for _ in range(int(input())):
n, x, y = map(int, input().split())
l = lcm(x, y)
plus = n // x - n // l
minus = n // y - n // l
print(range_sum(n - plus + 1, n) - range_sum(1, minus))
|
1872
|
E
|
Data Structures Fan
|
You are given an array of integers $a_1, a_2, \ldots, a_n$, as well as a binary string$^{\dagger}$ $s$ consisting of $n$ characters.
Augustin is a big fan of data structures. Therefore, he asked you to implement a data structure that can answer $q$ queries. There are two types of queries:
- "1 $l$ $r$" ($1\le l \le r \le n$) — replace each character $s_i$ for $l \le i \le r$ with its opposite. That is, replace all $0$ with $1$ and all $1$ with $0$.
- "2 $g$" ($g \in \{0, 1\}$) — calculate the value of the bitwise XOR of the numbers $a_i$ for all indices $i$ such that $s_i = g$. Note that the $\operatorname{XOR}$ of an empty set of numbers is considered to be equal to $0$.
Please help Augustin to answer all the queries!
For example, if $n = 4$, $a = [1, 2, 3, 6]$, $s = 1001$, consider the following series of queries:
- "2 $0$" — we are interested in the indices $i$ for which $s_i = \tt{0}$, since $s = \tt{1001}$, these are the indices $2$ and $3$, so the answer to the query will be $a_2 \oplus a_3 = 2 \oplus 3 = 1$.
- "1 $1$ $3$" — we need to replace the characters $s_1, s_2, s_3$ with their opposites, so before the query $s = \tt{1001}$, and after the query: $s = \tt{0111}$.
- "2 $1$" — we are interested in the indices $i$ for which $s_i = \tt{1}$, since $s = \tt{0111}$, these are the indices $2$, $3$, and $4$, so the answer to the query will be $a_2 \oplus a_3 \oplus a_4 = 2 \oplus 3 \oplus 6 = 7$.
- "1 $2$ $4$" — $s = \tt{0111}$ $\to$ $s = \tt{0000}$.
- "2 $1$" — $s = \tt{0000}$, there are no indices with $s_i = \tt{1}$, so since the $\operatorname{XOR}$ of an empty set of numbers is considered to be equal to $0$, the answer to this query is $0$.
$^{\dagger}$ A binary string is a string containing only characters $0$ or $1$.
|
Of course this problem has solutions that use data structures. For example, you can use a segment tree with range updates to solve it in $O((n + q) \log n)$ time, or you can use a square root decomposition to solve it in $O((n + q) \sqrt{n})$ time. However, of course, we do not expect participants in Div3 to have knowledge of these advanced data structures, so there is a simpler solution. We will store 2 variables: $X_0, X_1$, which represent the XOR of all numbers from group $0$ and group $1$, respectively. When answering a query of type 2, we will simply output either $X_0$ or $X_1$. Now we need to understand how to update $X_0$ and $X_1$ after receiving a query of type 1. Let's first solve a simplified version: suppose that in type 1 queries, only a single character of the string $s$ is inverted, i.e., $l = r$ in all type 1 queries. Let's see how $X_0$ and $X_1$ change after this query. If $s_i$ was $0$ and became $1$, then the number $a_i$ will be removed from group $0$. So, we need to invert "XOR $a_i$" from $X_0$. Since XOR is its own inverse operation ($w \oplus w = 0$), we can do this with $X_0 = X_0 \oplus a_i$. And in $X_1$, we need to add the number $a_i$, since now $s_i = 1$. And we can do this with $X_1 = X_1 \oplus a_i$. The same thing happens if $s_i$ was $1$. This is the key observation: when we invert $s_i$, $X_0$ and $X_1$ change in the same way, regardless of whether this inversion was from $0$ to $1$ or from $1$ to $0$. Therefore, to update $X_0$ and $X_1$ after a query of type 1 with parameters $l, r$, we need to do this: $X_0 = X_0 \oplus (a_l \oplus \ldots \oplus a_r)$, and the same for $X_1$. To quickly find the XOR value on a subsegment of the array $a$, we can use a prefix XOR array. If $p_i = a_1 \oplus \ldots a_i$, then: $a_l \oplus \ldots \oplus a_r = p_r \oplus p_{l-1}$.
|
[
"binary search",
"bitmasks",
"data structures",
"dp"
] | 1,500
|
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
s = input()
q = int(input())
ans = [0, 0]
a = [0] + a
s = '0' + s
pref = [0] * (n + 1)
for i in range(1, n + 1):
ans[int(s[i])] ^= a[i]
pref[i] = pref[i - 1] ^ a[i]
massxor = 0
for __ in range(q):
query = list(map(int, input().split()))
tp = query[0]
if tp == 1:
l = query[1]
r = query[2]
massxor ^= pref[r] ^ pref[l - 1]
else:
g = query[1]
print(massxor ^ ans[g])
|
1872
|
F
|
Selling a Menagerie
|
You are the owner of a menagerie consisting of $n$ animals numbered from $1$ to $n$. However, maintaining the menagerie is quite expensive, so you have decided to sell it!
It is known that each animal is afraid of exactly one other animal. More precisely, animal $i$ is afraid of animal $a_i$ ($a_i \neq i$). Also, the cost of each animal is known, for animal $i$ it is equal to $c_i$.
You will sell all your animals in some fixed order. Formally, you will need to choose some permutation$^\dagger$ $p_1, p_2, \ldots, p_n$, and sell animal $p_1$ first, then animal $p_2$, and so on, selling animal $p_n$ last.
When you sell animal $i$, there are two possible outcomes:
- If animal $a_i$ was sold \textbf{before} animal $i$, you receive $c_i$ money for selling animal $i$.
- If animal $a_i$ was \textbf{not} sold \textbf{before} animal $i$, you receive $2 \cdot c_i$ money for selling animal $i$. (Surprisingly, animals that are currently afraid are more valuable).
Your task is to choose the order of selling the animals in order to maximize the total profit.
For example, if $a = [3, 4, 4, 1, 3]$, $c = [3, 4, 5, 6, 7]$, and the permutation you choose is $[4, 2, 5, 1, 3]$, then:
- The first animal to be sold is animal $4$. Animal $a_4 = 1$ was not sold before, so you receive $2 \cdot c_4 = 12$ money for selling it.
- The second animal to be sold is animal $2$. Animal $a_2 = 4$ was sold before, so you receive $c_2 = 4$ money for selling it.
- The third animal to be sold is animal $5$. Animal $a_5 = 3$ was not sold before, so you receive $2 \cdot c_5 = 14$ money for selling it.
- The fourth animal to be sold is animal $1$. Animal $a_1 = 3$ was not sold before, so you receive $2 \cdot c_1 = 6$ money for selling it.
- The fifth animal to be sold is animal $3$. Animal $a_3 = 4$ was sold before, so you receive $c_3 = 5$ money for selling it.
Your total profit, with this choice of permutation, is $12 + 4 + 14 + 6 + 5 = 41$. Note that $41$ is \textbf{not} the maximum possible profit in this example.
$^\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 ($2$ appears twice in the array) and $[1,3,4]$ is also not a permutation ($n=3$, but $4$ is present in the array).
|
Simple greedy observation: if at some point in time there exists an animal $i$ such that no one fears it (there is no index $a_j = i$), then it is optimal to sell that animal first. Let's iteratively sell such animals as long as they exist. After selling animal $i$, we must additionally check if animal $a_i$ has become such that no one fears it, and if so, add it to the list for sale. What will we get when we sell all such animals? Note that when there are no such animals left, $a_i$ will form a permutation, as each animal must be feared by at least one other animal. As it is known, a permutation consists of cycles of the form $i \to a_i \to a_{a_i} \to \ldots \to i$. Obviously, for each cycle we must solve the problem independently, and then combine the answers in any order. Note that if we sell animals in the order of the cycle, we will only receive a single payment for the last animal sold. At the same time, it is not possible to obtain double payment for all animals in any case: the last animal sold from the cycle will always be sold for a single payment. Therefore, it is optimal to sell all animals in the order of the cycle so that the animal with the minimum cost ends up being the last in this order. You can see the implementation details in the code.
|
[
"dfs and similar",
"dsu",
"graphs",
"implementation",
"math"
] | 1,800
|
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
c = list(map(int, input().split()))
sons = [0] * n
for i in range(n):
a[i] -= 1
sons[a[i]] += 1
q = []
for i in range(n):
if sons[i] == 0:
q.append(i)
ans = []
added = [0] * n
while q:
v = q.pop()
ans.append(v)
added[v] = 1
sons[a[v]] -= 1
if sons[a[v]] == 0:
q.append(a[v])
for v in range(n):
if not added[v]:
v2 = a[v]
cycle = [v]
while v2 != v:
cycle.append(v2)
v2 = a[v2]
minc = 10 ** 9
for u in cycle:
added[u] = 1
minc = min(minc, c[u])
for i in range(len(cycle)):
if c[cycle[i]] == minc:
ans += cycle[i + 1:]
ans += cycle[:i + 1]
break
print(*map(lambda x: x + 1, ans))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.