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
1552
H
Guess the Perimeter
Let us call a point of the plane admissible if its coordinates are positive integers less than or equal to $200$. There is an invisible rectangle such that: - its vertices are all admissible; - its sides are parallel to the coordinate axes; - its area is strictly positive. Your task is to guess the perimeter of this rectangle.In order to guess it, you may ask at most $4$ queries. In each query, you choose a nonempty subset of the admissible points and you are told how many of the chosen points are inside or on the boundary of the invisible rectangle.
Let $b$ and $h$ be the lengths of base and height of the rectangle. We will solve a harder problem, that is, finding the explicit values of $b$ and $h$. For a positive integer $d$, define $S(d)$ as the set of admissible points $(x, \, y)$ with $d \mid x$, and define $f(d)$ as the answer to the query with subset $S(d)$. Then $f(1) = (b + 1)(h + 1)$. Lemma 1. We have $d\cdot f(d) = f(1)$ if and only if $d \mid b + 1$. Proof. Consider the set $\{d, \, 2d, \, 3d, \, \dots\}$ of all positive multiples of $d$, and let $n$ be the number of such multiples that are the $x$-coordinate of at least one point of the rectangle. Then $f(d) = n(h + 1)$. We notice that $n = \frac{b + 1}{d} \iff d \mid b + 1$ (indeed, the "if" statement is trivial, since $n$ must be integer; the converse is true because we can split the base in $\frac{b + 1}{d}$ segments, and each segment contains exactly one point whose $x$-coordinate is a multiple of $d$). On the other hand, $df(d) = f(1) \iff dn(h + 1) = (b + 1)(h + 1) \iff n = \frac{b + 1}{d}$. This completes the proof. Lemma 2. Let $p = 2^k$ be the highest power of $2$ which divides $b + 1$. Then $\left\lvert 2f(2p) - \frac{f(1)}{p} \right\rvert = h + 1$. Proof. Let $n = \frac{f(p)}{h + 1}$ be as in the previous Lemma, and let $n' = \frac{f(2p)}{h + 1}$. Then it is easy to see that $n' = \frac{n \pm 1}{2}$, which means that $2f(2p) = 2n'(h + 1) = (n \pm 1)(h + 1)$. But, since $p \mid b + 1$, $n(h + 1) = \frac{b + 1}{p}(h + 1) = \frac{f(1)}{p}$. Finally, $\left\lvert 2f(2p) - \frac{f(1)}{p} \right\rvert = \left\lvert n(h + 1) \pm (h + 1) - \frac{f(1)}{p} \right\rvert = \left\lvert \frac{f(1)}{p} \pm (h + 1) - \frac{f(1)}{p} \right\rvert = h + 1.$ Now it suffices to ask for $f(1)$ (one query), and then binary-search the value of $p$ from the set $\{1, \, 2, \, 2^2, \, \dots, \, 2^7\}$, which takes $3$ queries. Note that, when we find $p$, we have already computed $f(2p)$ (except when $p = 2^7$, but in this case $f(2p) = 0$), so no further query is required.
[ "binary search", "interactive", "number theory" ]
3,300
#include <iostream> #include <vector> using namespace std; vector<pair<int, int>> get_S(int d) { vector<pair<int, int>> S; for (int i = d; i <= 200; i += d) for (int j = 1; j <= 200; j++) S.push_back(make_pair(i, j)); return S; } int query(int d) { vector<pair<int, int>> S = get_S(d); cout << "? " << S.size() << endl; for (auto [x, y] : S) cout << x << " " << y << " "; cout << endl; cout.flush(); int ans; cin >> ans; return ans; } int main() { vector<int> f(9, 0); f[0] = query(1); int l = 1, r = 8; while (l < r) { int m = (l + r) / 2; int d = (1 << m); f[m] = query(d); if (d * f[m] == f[0]) l = m + 1; else r = m; } int k = l - 1; int h = abs(2 * f[k + 1] - f[0] / (1 << k)); int b = f[0] / h; cout << "! " << 2 * (b + h - 2) << endl; cout.flush(); return 0; }
1552
I
Organizing a Music Festival
You are the organizer of the famous "Zurich Music Festival". There will be $n$ singers who will perform at the festival, identified by the integers $1$, $2$, $\dots$, $n$. You must choose in which order they are going to perform on stage. You have $m$ friends and each of them has a set of favourite singers. More precisely, for each $1\le i\le m$, the $i$-th friend likes singers $s_{i,1}, \, s_{i, 2}, \, \dots, \,s_{i, q_i}$. A friend of yours is happy if the singers he likes perform consecutively (in an arbitrary order). An ordering of the singers is valid if it makes all your friends happy. Compute the number of valid orderings modulo $998\,244\,353$.
Let $S_i := \{s_{i,1}, \, s_{i,2}, \, \dots, \, s_{i, q_i}\}$. Consider the graph on the subsets $S_1, \, S_2, \, \dots, \, S_k$ such that $S_i$ is adjacent to $S_j$ if and only if $S_i \cap S_j \ne \varnothing, \, S_i, \, S_j$. Without loss of generality we can assume that the sets $S_1, \, S_2, \, \dots, \, S_m$ are distinct. Consider a connected component $\mathcal C$ in such a graph (that is, $\mathcal C$ is a family of subsets). Let $P(\mathcal C) := \bigcup_{S\in\mathcal C} S$ be the union of all sets in $\mathcal C$. For each $x \in P(\mathcal C)$, let $\mathcal C_x := \{S \in \mathcal C: x \in S\}$. Notice that $\mathcal C_x = \mathcal C_y$ if and only if the elements $x, \, y$ belongs to exactly the same set in $\mathcal C$. Consider the equivalence relationship on $P(\mathcal C)$ induced by the function $x \mapsto \mathcal C_x$ (i.e., $x \equiv y \iff \mathcal C_x = \mathcal C_y$). Lemma. If $|\mathcal C| \ge 2$, there is either $0$ or exactly $2$ (one is the reversal of the other) ways to order the equivalence classes so that any subset $T \in \mathcal C$ is the union of a contiguous (in the ordering) interval of equivalence classes. Proof. This can be proven by induction on the number of sets in $\mathcal C$. If $|\mathcal C| = 2$, assume $\mathcal C = \{S_1, \, S_2\}$. The possible values of $\mathcal C_x$ are $\{S_1\}$, $\{S_2\}$, $\{S_1, \, S_2\}$. For sure the equivalence class corresponding to $\{S_1, \, S_2\}$ is nonempty and, without loss of generality, we may also assume that the equivalence class corresponding to $\{S_1\}$ is nonempty. Then the valid orderings are exactly $\{S_1\}\ - \ \{S_1, \, S_2\}\ - \ \{S_2\}$ and its reversal. Now, assume that $|\mathcal C| \ge 3$. Take $S \in \mathcal C$ so that $\mathcal C' := \mathcal C \setminus \{S\}$ is still connected. Notice that the equivalence classes induced by $\mathcal C'$ may be less refined than those induced by $\mathcal C$ (moreover, the elements in $S \setminus P(\mathcal C')$ are not even considered). If already there is no good ordering of the equivalence classes induced by $\mathcal C'$, then the same holds for the equivalence classes induced by $\mathcal C$. Otherwise, by induction, we may assume that there is a unique (up to reversal) ordering of the equivalence classes induced by $\mathcal C'$. Let $Z_1, \, Z_2, \, \dots, \, Z_k$ be the equivalence classes induced by $\mathcal C'$ on $P(\mathcal C')$ in the correct order. What changes when we consider also the set $S$? Each $Z_i$ splits into two (possibly empty) equivalence classes $Z_i' := Z_i \cap S$ and $Z_i' ' := Z_i \setminus S$. Moreover, we have to take care of the (possibly empty) new equivalence class $Z_0 := S \setminus P(\mathcal C')$. Consider the set of indices $I$ so that $i \in I$ if and only if both sets $Z_i \cap S$ and $Z_i \setminus S$ are nonempty. Let us consider various cases: If $I=\varnothing$, then there is a valid ordering if and only if the set $\{1 \le i \le k: Z_i \cap S \ne \varnothing\}$ is a prefix or a suffix of $\{1,2,\dots,k\}$ or it is a contiguous interval and $Z_0=\varnothing$. If $|I| \ge 3$, then there is no good ordering. If $|I| = 2$, assume that $I= \{l, \, r\}$ and $l < r$. Then there is a valid ordering if and only if the set $\{1 \le i \le k: Z_i \cap S \ne \varnothing\}$ coincides with $[l, \, r]$ and $Z_0 = \varnothing$. In such case, the unique valid ordering (up to reversal) is given by: $Z_1, \, Z_2, \, \dots, \, Z_{l - 1}, \, Z_l' ', \, Z_l', \, Z_{l + 1}, \, \dots, \, Z_{r - 1}, \, Z_r', \, Z_r' ', \, Z_{r+1}, \, \dots, \, Z_n.$ $Z_1, \, Z_2, \, \dots, \, Z_{l - 1}, \, Z_l' ', \, Z_l', \, Z_{l + 1}, \, \dots, \, Z_{r - 1}, \, Z_r', \, Z_r' ', \, Z_{r+1}, \, \dots, \, Z_n.$ If $|I| = 1$, assume that $I = \{t\}$. Then there is a valid ordering if and only if the set $\{1 \le i \le k: Z_i \cap S \ne \varnothing\}$ coincides with $[1, \, t]$ or $[t, \, k]$; or if such set is $\{t\}$ and also $Z_0$ is empty. In the first case (the other cases are analogous), the unique valid ordering (up to reversal) is given by: $Z_0, \, Z_1, \, Z_2, \, \dots, \, Z_{t - 1}, \, Z_t', \, Z_t' ', \, Z_{t + 1}, \, \dots, \, Z_k.$ $Z_0, \, Z_1, \, Z_2, \, \dots, \, Z_{t - 1}, \, Z_t', \, Z_t' ', \, Z_{t + 1}, \, \dots, \, Z_k.$ The lemma teaches us how to handle a single component (of course, one has to compute also the number of possible orderings of each equivalence class, which is just the factorial of its size). What about the interaction between components? It is not hard to check that if $\mathcal C, \, \mathcal D$ are two distinct connected components then either $P(\mathcal C) \cap P(\mathcal D) = \varnothing$ or $P(\mathcal C) \subseteq P(\mathcal D)$ or $P(\mathcal D) \subseteq P(\mathcal C)$. Moreover, if $P(\mathcal C) = P(\mathcal D)$ then either $\mathcal C$ or $\mathcal D$ contains only one subset. Let us consider the forest on the connected components such that $\mathcal C$ is an ancestor of $\mathcal D$ if and only if $P(\mathcal D) \subseteq P(\mathcal C)$ (if $P(\mathcal C) = P(\mathcal D)$ then we require additionally that $\mathcal C$ contains only one subset). It is not hard to check that this ancestorship is induced by a forest. By adding (if necessary) to the initial family the subset $S_{k + 1} = \{1, \, 2, \, \dots, \, n\}$, we may assume that this forest is a tree. The number of valid permutations is given by the product of the contributions of each connected component $\mathcal C$. The contribution of a connected component $\mathcal C$ is the product of the contributions of the equivalence classes of $P(\mathcal C)$ (and, if there is more than one equivalence class, a factor $2$). Given an equivalence class $E$ of $P(\mathcal C)$, its contribution is the factorial of $|P(\mathcal C)| - \sum_{\substack{\mathcal D \in \text{sons}(\mathcal C) \\ P(\mathcal D)\subseteq E}} \big(|P(\mathcal D)|-1\big).$ Complexity: $O\left(\frac{k^2n}{64}\right)$ (using bitsets to store the subsets and implementing everything naively).
[ "dfs and similar", "math" ]
3,400
#define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define SZ(x) ((int)((x).size())) // Returns the time elapsed in nanoseconds from 1 January 1970, at 00:00:00. LL get_time() { return chrono::duration_cast<chrono::nanoseconds>( chrono::steady_clock::now().time_since_epoch()) .count(); } template <typename T1, typename T2> string print_iterable(T1 begin_iter, T2 end_iter, int counter) { bool done_something = false; stringstream res; res << "["; for (; begin_iter != end_iter and counter; ++begin_iter) { done_something = true; counter--; res << *begin_iter << ", "; } string str = res.str(); if (done_something) { str.pop_back(); str.pop_back(); } str += "]"; return str; } template <typename S, typename T> ostream& operator <<(ostream& out, const pair<S, T>& p) { out << "{" << p.first << ", " << p.second << "}"; return out; } template <typename T> ostream& operator <<(ostream& out, const vector<T>& v) { out << "["; for (int i = 0; i < (int)v.size(); i++) { out << v[i]; if (i != (int)v.size()-1) out << ", "; } out << "]"; return out; } template<class TH> void _dbg(const char* name, TH val){ clog << name << ": " << val << endl; } template<class TH, class... TA> void _dbg(const char* names, TH curr_val, TA... vals) { while(*names != ',') clog << *names++; clog << ": " << curr_val << ", "; _dbg(names+1, vals...); } #if DEBUG && !ONLINE_JUDGE ifstream input_from_file("input.txt"); #define cin input_from_file #define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__) #define dbg_arr(x, len) clog << #x << ": " << print_iterable(x, x+len, -1) << endl; #else #define dbg(...) #define dbg_arr(x, len) #endif /////////////////////////////////////////////////////////////////////////// //////////////////// DO NOT TOUCH BEFORE THIS LINE //////////////////////// /////////////////////////////////////////////////////////////////////////// const LL mod = 998244353; const int MAXN = 100; const int MAXM = 100; typedef bitset<MAXN> Subset; int N; bool visited[MAXM]; vector<int> aa[MAXM]; int M; Subset S[MAXM]; bool dfs(int v, vector<Subset>& E) { visited[v] = true; string intersection_type(E.size(), '-'); Subset A = S[v]; for (int i = 0; i < SZ(E); i++) { Subset inter = A & E[i]; if (inter.none()) intersection_type[i] = '0'; else if (inter != E[i]) intersection_type[i] = '1'; else intersection_type[i] = '2'; A = A & ~inter; } bool is_prefix = regex_match(intersection_type, regex("2*1?0*")); bool is_suffix = regex_match(intersection_type, regex("0*1?2*")); bool is_interval = regex_match(intersection_type, regex("0*1?2*1?0*")); if (!is_interval) return false; if (!is_prefix and !is_suffix and A.any()) return false; if (!is_suffix and A.any()) { reverse(E.begin(), E.end()); reverse(intersection_type.begin(), intersection_type.end()); } if (A.any()) { E.push_back(A); intersection_type += '2'; } for (int i = SZ(E)-1; i >= 0; i--) { if (intersection_type[i] == '1') { Subset e1 = S[v] & E[i]; Subset e2 = E[i] & ~S[v]; E.erase(E.begin() + i); if (i >= 1 and intersection_type[i-1] != '0') { E.insert(E.begin() + i, e2); E.insert(E.begin() + i, e1); } else if (i < SZ(intersection_type)-1 and intersection_type[i+1] != '0') { E.insert(E.begin() + i, e1); E.insert(E.begin() + i, e2); } else assert(0); } } for (int a: aa[v]) { if (visited[a]) continue; if (!dfs(a, E)) return false; } return true; } LL solve() { for (int i = 0; i < M; i++) aa[i].clear(), visited[i] = false; for (int i = 0; i < M; i++) { for (int j = i+1; j < M; j++) { Subset inter = S[i]&S[j]; if (inter.any() and inter != S[i] and inter != S[j]) { aa[i].push_back(j); aa[j].push_back(i); } } } typedef pair<Subset, vector<Subset>> psvs; vector<psvs> equiv; for (int i = 0; i < M; i++) { if (visited[i]) continue; vector<Subset> E; if (!dfs(i, E)) return 0; Subset PP; for (auto e: E) PP |= e; equiv.push_back({PP, E}); } Subset full_set; for (int i = 0; i < N; i++) full_set[i] = 1; equiv.emplace_back(full_set, vector<Subset>{full_set}); sort(equiv.begin(), equiv.end(), [&](const psvs& A, const psvs& B) { if (A.first.count() != B.first.count()) return A.first.count() > B.first.count(); return A.second.size() < B.second.size(); }); LL res = 1; for (int i = 0; i < SZ(equiv); i++) { if (equiv[i].second.size() >= 2) res *= 2; for (Subset A: equiv[i].second) { int cnt = A.count(); for (int j = i+1; j < SZ(equiv); j++) { Subset P = equiv[j].first; if ((P & A) == P) { cnt -= P.count() - 1; A &= ~P; } } for (int m = 1; m <= cnt; m++) res = res * m % mod; } } return res; } int main() { ios::sync_with_stdio(false); cin.tie(0); // Remove in problems with online queries! cin >> N >> M; for (int i = 0; i < M; i++) { int q; cin >> q; for (int j = 0; j < q; j++) { int s; cin >> s; S[i][s-1] = 1; } } cout << solve() << "\n"; }
1553
A
Digits Sum
Let's define $S(x)$ to be the sum of digits of number $x$ written in decimal system. For example, $S(5) = 5$, $S(10) = 1$, $S(322) = 7$. We will call an integer $x$ \textbf{interesting} if $S(x + 1) < S(x)$. In each test you will be given one integer $n$. Your task is to calculate the number of integers $x$ such that $1 \le x \le n$ and $x$ is interesting.
Let's think: what properties do all interesting numbers have? Well, if a number $x$ does not end with $9$, we can say for sure that $f(x+1) = f(x) + 1$, because the last digit will get increased. What if the number ends with $9$? Then the last digit will become $0$, so, no matter what happens to other digits, we can say that $f(x+1)$ will surely be less than $f(x)$. So the problem asks us to count all numbers $1 \le x \le n$ with the last digit equal to $9$. It is not hard to see that the answer is equal to $\lfloor \frac{n + 1}{10} \rfloor$. This concludes the solution, as we are now able to answer all testcases in $O(1)$, resulting in total $O(t)$ runtime.
[ "math", "number theory" ]
800
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { //freopen("input.txt", "r", stdin); ios_base::sync_with_stdio(false); int tst; cin >> tst; while (tst--) { int n; cin >> n; cout << (n + 1) / 10 << '\n'; } }
1553
B
Reverse String
You have a string $s$ and a chip, which you can place onto any character of this string. After placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $i$, you move it to the position $i + 1$. Of course, moving the chip to the right is impossible if it is already in the last position. After moving the chip to the right, you move it to the left several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $i$, you move it to the position $i - 1$. Of course, moving the chip to the left is impossible if it is already in the first position. When you place a chip or move it, you write down the character where the chip ends up after your action. For example, if $s$ is abcdef, you place the chip onto the $3$-rd character, move it to the right $2$ times and then move it to the left $3$ times, you write down the string cdedcb. You are given two strings $s$ and $t$. Your task is to determine whether it's possible to perform the described operations with $s$ so that you write down the string $t$ as a result.
Let's iterate over starting positions, the number of times we go to the right and the number of times we go to the left. After that we can check that resulting string is equal to the needed one. This solution works in $O(n^4)$, since there are $O(n^3)$ possible combinations of starting position, number of moves to the right and left and each check can take up to $O(n)$ time. To optimize this solution we can notice that if we know number of moves to the right then we can recover number of moves to the left(because we know the length of needed string). So, we have $O(n^2)$ possible combinations, that's why this solution works in $O(n^3)$, which is enough to pass tests. Can you solve this problem in $O(n^2)$ time? Maybe even faster?
[ "brute force", "dp", "hashing", "implementation", "strings" ]
1,300
q = int(input()) for i in range(q): s = input() t = input() n = len(s) m = len(t) ans = False for i in range(n): for j in range(0, n - i): k = m - 1 - j if i + j < k: continue l1 = i r = i + j l2 = r - k if s[l1:r+1] + s[l2:r][::-1] == t: ans = True print('YES' if ans else 'NO')
1553
C
Penalty
Consider a simplified penalty phase at the end of a football match. A penalty phase consists of at most $10$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (\textbf{note that it goes against the usual football rules}). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the $7$-th kick the first team has scored $1$ goal, and the second team has scored $3$ goals, the penalty phase ends — the first team cannot reach $3$ goals. You know which player will be taking each kick, so you have your predictions for each of the $10$ kicks. These predictions are represented by a string $s$ consisting of $10$ characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way: - if $s_i$ is 1, then the $i$-th kick will definitely score a goal; - if $s_i$ is 0, then the $i$-th kick definitely won't score a goal; - if $s_i$ is ?, then the $i$-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that \textbf{the referee doesn't take into account any predictions when deciding to stop the penalty phase} — you may know that some kick will/won't be scored, but the referee doesn't.
After you have fixed the values of ? you can easily find the number of kicks needed to decide the winners in constant time. If you iterate over all possible values of ? you can get solution which works in $O(2^10 \cdot check)$ for one testcase, which is enough to pass. The other possible solution is to notice that it's optimal to change ? of one team to 1 and to 0 for other. So you only have two candidates to check.
[ "bitmasks", "brute force", "dp", "greedy" ]
1,200
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { string s; cin >> s; int ans = 9; { int cnt0 = 0, cnt1 = 0; for (int i = 0; i < 10; ++i) { if (i % 2 == 0) cnt0 += s[i] != '0'; else cnt1 += s[i] == '1'; if (cnt0 > cnt1 + (10 - i) / 2) ans = min(ans, i); if (cnt1 > cnt0 + (9 - i) / 2) ans = min(ans, i); } } { int cnt0 = 0, cnt1 = 0; for (int i = 0; i < 10; ++i) { if (i % 2 == 0) cnt0 += s[i] == '1'; else cnt1 += s[i] != '0'; if (cnt0 > cnt1 + (10 - i) / 2) ans = min(ans, i); if (cnt1 > cnt0 + (9 - i) / 2) ans = min(ans, i); } } cout << ans + 1 << '\n'; } }
1553
D
Backspace
You are given two strings $s$ and $t$, both consisting of lowercase English letters. You are going to type the string $s$ character by character, from the first character to the last one. When typing a character, instead of pressing the button corresponding to it, you can press the "Backspace" button. It deletes the last character you have typed among those that aren't deleted yet (or does nothing if there are no characters in the current string). For example, if $s$ is "abcbd" and you press Backspace instead of typing the first and the fourth characters, you will get the string "bd" (the first press of Backspace deletes no character, and the second press deletes the character 'c'). Another example, if $s$ is "abcaa" and you press Backspace instead of the last two letters, then the resulting text is "a". Your task is to determine whether you can obtain the string $t$, if you type the string $s$ and press "Backspace" instead of typing several (maybe zero) characters of $s$.
The main idea of the problem is that backspace results in losing $2$ characters, the one we intended to type (which we replace with a backspace) and the character that the backspace will remove. In general, the idea is to compare every letter $s_i$ with $t_j$ starting from right to left, if they match we will move to compare $s_{i-1}$ with $t_{j-1}$ in the next step, else if they don't match we will delete $s_{i}$ and $s_{i-1}$, then compare $s_{i-2}$ with $t_j$ in the next step and so on. If we successfully matched all characters in $t$ we will print $YES$, $NO$ otherwise.
[ "dp", "greedy", "strings", "two pointers" ]
1,500
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> #include <random> #include <bitset> using namespace std; #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__);fflush(stderr); #else #define eprintf(...) 42 #endif using ll = long long; using ld = long double; using uint = unsigned int; using ull = unsigned long long; template<typename T> using pair2 = pair<T, T>; using pii = pair<int, int>; using pli = pair<ll, int>; using pll = pair<ll, ll>; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); ll myRand(ll B) { return (ull)rng() % B; } #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second clock_t startTime; double getCurrentTime() { return (double)(clock() - startTime) / CLOCKS_PER_SEC; } const int N = 200200; int n, m; char s[N], t[N]; bool solve() { scanf("%s %s", s, t); n = strlen(s); m = strlen(t); if (n < m) return false; int p = (n - m) & 1; int q = 0; int k = 0; for (int i = p; i < n; i++) { if (k == 1) { k = 0; continue; } if (q < m && s[i] == t[q]) { q++; } else { k++; } } return q == m; } int main() { startTime = clock(); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int T; scanf("%d", &T); while(T--) { if (solve()) printf("YES\n"); else printf("NO\n"); } return 0; }
1553
E
Permutation Shift
An identity permutation of length $n$ is an array $[1, 2, 3, \dots, n]$. We performed the following operations to an identity permutation of length $n$: - firstly, we cyclically shifted it to the right by $k$ positions, where $k$ is unknown to you (the only thing you know is that $0 \le k \le n - 1$). When an array is cyclically shifted to the right by $k$ positions, the resulting array is formed by taking $k$ last elements of the original array (without changing their relative order), and then appending $n - k$ first elements to the right of them (without changing relative order of the first $n - k$ elements as well). For example, if we cyclically shift the identity permutation of length $6$ by $2$ positions, we get the array $[5, 6, 1, 2, 3, 4]$; - secondly, we performed the following operation \textbf{at most} $m$ times: pick any two elements of the array and swap them. You are given the values of $n$ and $m$, and the resulting array. Your task is to find all possible values of $k$ in the cyclic shift operation.
Let's decrease all numbers by $1$ and start the numeration from $0$, because cyclic shifts are very easy to describe this way. Let's observe for $n = 4$: $k = 0$. $p = [0, 1, 2, 3]$. So, $p_i = i$. $k = 1$. $p = [3, 0, 1, 2]$. So, $p_i = (i-1) \bmod n$. ... Continuing this process, we verify that indeed, $p_i = (i-k) \bmod n$. Very simple! Now suppose we have some value $0 \le k \le n - 1$ and we want to check if it is possible to obtain $p$ from $k$-th cyclic shift by doing at most $m$ swaps. For this, we can calculate the minimum number of swaps and check it is not more than $m$. So, how to calculate the minimum number of swaps needed to transform a permutation $a$ to another permutation $b$? This is actually a well-known problem. The idea is, we build a graph with undirected edges $(a_i, b_i)$. The minimum number of swaps will be equal to $n - c$, where $c$ is equal to the number of connected components in the resulting graph. Nice, now we can check if some $k$ is good in $O(n)$ time. But we can't check all of them, right? Here comes the crucial observation: Suppose you get a permutation $a$ after a cyclic shift. Then you make at most $m$ swaps and obtain $b$. This means at most $2 \cdot m$ numbers will be out of order! That is, there will be at least $n - 2 \cdot m$ indices $i$ such that $a_i = b_i$. So can we calculate the number $cnt_k$ - the count of integers in position for each cyclic shift $k$? Yes, we can! For an arbitrary $i$, there is exactly one $k$ such that $p_i = (i-k) \bmod n$. But wait, it means there are in total only $n$ good positions because $\sum cnt_i = n$! And we check only those $k$ for which it is true that $cnt_k \ge n - 2 \cdot m$. Remember that weird constraint $m \le \frac{n}{3}$? Well, turns out there are at most $\frac{n}{n - \frac{2n}{3}} = 3$ different $k$ to consider! So we know we check at most $3$ different values and we know how to check in $O(n)$ time. That concludes the solution. The time and space complexities are $O(n)$.
[ "brute force", "combinatorics", "constructive algorithms", "dfs and similar", "dsu", "graphs", "math" ]
2,100
#include <bits/stdc++.h> using namespace std; int cycle_count(vector<int> q, int n) { for(int i = 0; i < n; i++) q[i]--; vector<int> used(n); int ans = 0; for(int i = 0; i < n; i++) { if(used[i] == 1) continue; int j = i; while(used[j] == 0) { used[j] = 1; j = q[j]; } ans++; } return ans; } bool check(int n, int m, int k, vector<int> p) { vector<int> q; for(int i = k; i < n; i++) q.push_back(p[i]); for(int i = 0; i < k; i++) q.push_back(p[i]); return n - cycle_count(q, n) <= m; } void solve() { int n, m; scanf("%d %d", &n, &m); vector<int> p(n); for(int i = 0; i < n; i++) scanf("%d", &p[i]); vector<int> cnt(n); for(int i = 0; i < n; i++) { int offset = i + 1 - p[i]; if(offset < 0) offset += n; cnt[offset]++; } vector<int> ans; for(int i = 0; i < n; i++) if(cnt[i] + 2 * m >= n && check(n, m, i, p)) ans.push_back(i); printf("%d", ans.size()); for(auto x : ans) printf(" %d", x); puts(""); } int main() { int t; scanf("%d", &t); for(int i = 0; i < t; i++) { solve(); } }
1553
F
Pairwise Modulo
You have an array $a$ consisting of $n$ distinct positive integers, numbered from $1$ to $n$. Define $p_k$ as $$p_k = \sum_{1 \le i, j \le k} a_i \bmod a_j,$$ where $x \bmod y$ denotes the remainder when $x$ is divided by $y$. You have to find and print $p_1, p_2, \ldots, p_n$.
First of all, we have to get rid of the mod operation. The following formula helps very much: $x \bmod y = x - y \cdot \lfloor \frac{x}{y} \rfloor$. Since the sum is hard to deal with, we will divide it into two separate sums $s_k$ and $t_k$ defined as: $s_k = \sum_{1 \le i, j \le k, i > j} (a_i \bmod a_j),$ $t_k = \sum_{1 \le i, j \le k, i < j} (a_i \bmod a_j).$ How to calculate $s_k$? Well, we know that $s_k = s_{k-1} + \sum_{i=1}^{k-1} (a_k \bmod a_i) = s_{k-1} + \sum_{i=1}^{k-1} (a_k - a_i \cdot \lfloor \frac{a_k}{a_i} \rfloor)$. Take $a_k$ out of the sum and you get $s_k = s_{k-1} + a_k \cdot (k-1) - \sum_{i=1}^{k-1} (a_i \cdot \lfloor \frac{a_k}{a_i} \rfloor)$. So, it is still not clear how to calculate it fast. Let's turn things around. Fix some arbitrary $a_i$ and try to calculate its contribution to all $s_k$ where $k > i$. For all $a_k$ in range $[a_i, 2 \cdot a_i)$ the contribution is $-a_i$. For all $a_k$ in range $[2 \cdot a_i, 3 \cdot a_i)$ the contribution is $-2 \cdot a_i$. ... For all $a_k$ in range $[d \cdot a_i, (d+1) \cdot a_i)$ the contribution is $-d \cdot a_i$. This means we can just brute force all reasonable $d$ and perform updates of the kind: add $x$ to all numbers in range $[l, r]$ which is clearly possible using segment tree or Fenwick tree which allows range updates and point queries. The only question is: how fast is this? Denote $M$ as $3 \cdot 10^5$. Remember the constraint that all $a_i$ are distinct? It means in the worst-case scenario we will have $\frac{M}{1} + \ldots + \frac{M}{n} = M \cdot (\frac{1}{1} + \ldots + \frac{1}{n})$ updates. The summation inside the brackets is known as a Harmonic number which is bounded by $O(\log n)$. So we have $O(M \log n)$ updates. Each update takes $O(\log M)$ time, thus the overall time to calculate $s_k$ is $O(M \log M \log n)$. Not bad. Will we be able to calculate $t_k$ with the same efficiency though? Well, the only difference between $s_k$ and $t_k$ is the order of indices, so the solution should be almost the same, right? Exactly. But this time, instead of having range updates and point queries, we will have to deal with point updates and range queries. Let's get into details. $t_k = t_{k-1} + \sum_{i=1}^{k-1} (a_i \bmod a_k) = t_{k-1} + \sum_{i=1}^{k-1} (a_i - a_k \cdot \lfloor \frac{a_i}{a_k} \rfloor)$. Separate $a_i$ and you get $t_k = t_{k-1} + \sum_{i=1}^{k-1}a_i - \sum_{i=1}^{k-1} (a_k \cdot \lfloor \frac{a_i}{a_k} \rfloor)$. Almost the same thing. This time, we will go over all multiples of $a_k$: All $a_i$ in range $[a_k, 2 \cdot a_k)$ contribute $-a_k$. All $a_i$ in range $[2 \cdot a_k, 3 \cdot a_k)$ contribute $-2 \cdot a_k$. ... All $a_i$ in range $[d \cdot a_k, (d+1) \cdot a_k)$ contribute $-d \cdot a_k$. It should be crystal clear by now that we are dealing with point updates and range queries here. The time complexity is the same. So, in total we get $O(M \log M \log n)$ time complexity and $O(n + M)$ space complexity. Be careful with segment trees, though. Using the classical recursive segment tree with pushes will probably result in a big constant and time out. Just remember that we are not dealing with advanced stuff there, so there is no need for pushes.
[ "data structures", "math" ]
2,300
// chrono::system_clock::now().time_since_epoch().count() #include <bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define sz(x) (int)(x).size() #define rep(i, a, b) for (int i = (a); i < (b); ++i) #define debug(x) cerr << #x << " = " << x << endl using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; const int M = (int)3e5; namespace A { ll t[M * 4]; void update(int l, int r, ll x, int v = 1, int tl = 1, int tr = M) { if (l > r || tl > r || tr < l) { return; } if (l <= tl && tr <= r) { t[v] += x; return; } int mid = (tl + tr) >> 1; int c1 = (v << 1), c2 = (c1 | 1); update(l, r, x, c1, tl, mid); update(l, r, x, c2, mid + 1, tr); } ll get(int p, int v = 1, int tl = 1, int tr = M) { if (tl == tr) { return t[v]; } int mid = (tl + tr) >> 1; int c1 = (v << 1), c2 = (c1 | 1); if (p <= mid) { return t[v] + get(p, c1, tl, mid); } else { return t[v] + get(p, c2, mid + 1, tr); } } } namespace B { ll t[M * 4]; void update(int p, ll x, int v = 1, int tl = 1, int tr = M) { if (tl == tr) { t[v] += x; return; } int mid = (tl + tr) >> 1; int c1 = (v << 1), c2 = (c1 | 1); if (p <= mid) { update(p, x, c1, tl, mid); } else { update(p, x, c2, mid + 1, tr); } t[v] = t[c1] + t[c2]; } ll get(int l, int r, int v = 1, int tl = 1, int tr = M) { if (l > r || tl > r || tr < l) { return 0ll; } if (l <= tl && tr <= r) { return t[v]; } int mid = (tl + tr) >> 1; int c1 = (v << 1), c2 = (c1 | 1); return get(l, r, c1, tl, mid) + get(l, r, c2, mid + 1, tr); } } int n; void solve() { cin >> n; ll pref = 0, ans = 0; rep (i, 1, n + 1) { int x; cin >> x; ans += x * (i - 1ll); ans += A::get(x); ans += pref; pref += x; for (int j = x; j <= M; j += x) { int l = j, r = min(M, j + x - 1); ans -= x * B::get(l, r) * (j / x); A::update(l, r, -x * (j / x)); } B::update(x, 1); cout << ans << " \n"[i == n]; } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tt = 1; for (int i = 1; i <= tt; ++i) { solve(); } return 0; }
1553
G
Common Divisor Graph
Consider a sequence of distinct integers $a_1, \ldots, a_n$, each representing one node of a graph. There is an edge between two nodes if the two values are not coprime, i. e. they have a common divisor greater than $1$. There are $q$ queries, in each query, you want to get from one given node $a_s$ to another $a_t$. In order to achieve that, you can choose an existing value $a_i$ and create new value $a_{n+1} = a_i \cdot (1 + a_i)$, with edges to all values that are not coprime with $a_{n+1}$. Also, $n$ gets increased by $1$. You can repeat that operation multiple times, possibly making the sequence much longer and getting huge or repeated values. What's the minimum possible number of newly created nodes so that $a_t$ is reachable from $a_s$? Queries are independent. In each query, you start with the initial sequence $a$ given in the input.
tl;dr - Find initial CCs. Then for every $a_i$, find prime divisors of $a_i+1$ and draw new edges of cost 1 between each pair of those primes, and between $a_i$ and those primes. Part 1, notation and observations Two numbers are not coprime iff they have a common prime divisor. Let $P(x)$ denote distinct prime divisors of $x$. For example $P(100) = \{2, 5\}$. You can run prime sieve to find $P(x)$ for all $x \in [2, 10^6 + 1]$. Useful interpretation: Creating $a_i \cdot (a_i + 1)$ is like creating $(a_i + 1)$ and drawing an extra edge between $a_i$ and $(a_i + 1)$. Observation: answer doesn't exceed two because you can move between even values. If the starting node isn't even, use one operation to create $a_s + 1$. If the target node isn't even, use one operation to create $a_t + 1$. Now you can move between them. So we just need to check if answer is 0 or 1. Part 2, checking if answer is 0 Let's find CCs (connected components) of the initial graph. Creates a node for each prime, even if it's not in the input. For each $a_i$, connect it to all values from $P(a_i)$. Use DFS or DSU to find CCs. Given a query, check if two nodes belong to the same CC. If so, the answer is 0. Part 3, checking if answer is 1. Let's say that $a_s$ and $a_t$ belong to two different CC, denoted cc1 and cc2. The answer is 1 in three cases: we spend one operation on a node from cc1, or a node from cc2, or a node from a completely different CC. The last case is needed e.g. for input $n = 3$, $a = (3, 7, 20)$. You need to replicate $20$ into $21$ in order to make $3$ and $7$ reachable from one another. For every $a_i$, let's consider replicating it into $a_i + 1$. Let's draw new edges of cost 1 between CC of $a_i$ and all CCs of values $P(a_i + 1)$. In the drawing, gray areas are initial CCs. Green edges have cost 1. For example, 9 can create 10, so we connect the whole CC with (9, 21, 27, 33) with the whole CC of prime 5, which contains the input value (25). You can't get from 169 to 9 with cost though. That would be possible if 25 replicated into 26 would be connected to both (9, 21, 27, 33) and to (169). To consider such cases, we need to draw green edges between all pairs of $P(a_i + 1)$ too. For example, if $a_i = 9$, then $P(a_i + 1) = \{2, 5\}$ so we draw green edges 2-5, 2-3, 3-5. Given a query, check if there is a green edge between the two CCs. If so, the answer is 1. - (should be in spoiler tags) A note about the worst case and preparing tests. One type of max tests is created by choosing $n$ values $x \leq 10^6$ with most distinct prime divisors of $x + 1$. With few exceptions, that means four or five primes, e.g. $2 \cdot 3 \cdot 5 \cdot 7 \cdot 11 = 2310$, and on average $5 \cdot 4 / 2 = 10$ edges of cost 1. It could happen though that choosing such values yields a small number of CCs and thus the solution is actually faster. What if there are some other tests that will make the intended solution significantly slower? In particular, only one CC would mean no edges at all. To check that, we run the intended solution and modified the code of "edges of cost 1" part to pretend that all numbers $a_i$ are coprime. That requires around 1'700'000 inserts to a set and takes less than 1 second. It's much faster if you use vector and then sort it. This "pretend" part couldn't be used in the testset but it was needed to see that the intended solution can for sure solve any test within TL.
[ "brute force", "constructive algorithms", "dsu", "graphs", "hashing", "math", "number theory" ]
2,700
// gcd, AC, O((N+Q) * log^2), by Errichto #include <bits/stdc++.h> using namespace std; #define sim template < class c #define ris return * this #define dor > debug & operator << #define eni(x) sim > typename \ enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) { sim > struct rge { c b, e; }; sim > rge<c> range(c i, c j) { return rge<c>{i, j}; } sim > auto dud(c* x) -> decltype(cerr << *x, 0); sim > char dud(...); struct debug { #ifdef LOCAL ~debug() { cerr << endl; } eni(!=) cerr << boolalpha << i; ris; } eni(==) ris << range(begin(i), end(i)); } sim, class b dor(pair < b, c > d) { ris << "(" << d.first << ", " << d.second << ")"; } sim dor(rge<c> d) { *this << "["; for (auto it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; ris << "]"; } #else sim dor(const c&) { ris; } #endif }; #define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] " // debug & operator << (debug & dd, P p) { dd << "(" << p.x << ", " << p.y << ")"; return dd; } struct DSU { vector<int> parent; DSU(int m) { parent.resize(m + 1); for(int i = 0; i <= m; ++i) { parent[i] = i; } } int find(int a) { if(a == parent[a]) { return a; } return parent[a] = find(parent[a]); } void uni(int a, int b) { parent[find(a)] = find(b); } }; int main() { // 1) read input int n, q; scanf("%d%d", &n, &q); vector<int> a(n); for(int i = 0; i < n; ++i) { scanf("%d", &a[i]); } int m = *max_element(a.begin(), a.end()); // 2) prime sieve vector<vector<int>> prime_divisors(m + 2); for(int p = 2; p <= m + 1; ++p) { if(prime_divisors[p].empty()) { for(int j = p; j <= m + 1; j += p) { prime_divisors[j].push_back(p); } } } // 3) DSU, find initial connected components DSU dsu(m + 2); for(int x : a) { for(int p : prime_divisors[x]) { dsu.uni(x, p); } } // 4) DSU, find edges of cost 1 set<pair<int,int>> edges; for(int x : a) { vector<int> nodes = prime_divisors[x+1]; nodes.push_back(x); for(int& node : nodes) { node = dsu.find(node); } for(int i = 0; i < (int) nodes.size(); ++i) { for(int j = i + 1; j < (int) nodes.size(); ++j) { int one = nodes[i]; int two = nodes[j]; if(one != two) { if(one > two) { swap(one, two); } edges.insert({one, two}); } } } } debug() << imie(edges); cerr << imie(edges.size()) << endl; // 5) answer queries while(q--) { int s, t; scanf("%d%d", &s, &t); --s; --t; s = dsu.find(a[s]); t = dsu.find(a[t]); if(s == t) { puts("0"); } else if(edges.count({min(s, t), max(s, t)})) { puts("1"); } else { puts("2"); } } }
1553
H
XOR and Distance
You are given an array $a$ consisting of $n$ distinct elements and an integer $k$. Each element in the array is a non-negative integer not exceeding $2^k-1$. Let's define the XOR distance for a number $x$ as the value of $$f(x) = \min\limits_{i = 1}^{n} \min\limits_{j = i + 1}^{n} |(a_i \oplus x) - (a_j \oplus x)|,$$ where $\oplus$ denotes the bitwise XOR operation. For every integer $x$ from $0$ to $2^k-1$, you have to calculate $f(x)$.
There are two main approaches to this problem, both of them utilize the same data structure - a trie. But not the usual trie. We will build a trie with each node storing the following four values. Let the interval represented by a node be $[L, R)$, then the values are: $minval$ - minimum existing value in the segment relative to $L$, so, for example, if $L = 4$ and the minimum number in the segment is $5$, then $minval = 1$; $maxval$ - maximum existing value in the segment. Relative to $L$ as well; $ans$ - the minimum distance between two existing values in the subtree; $len$ - the size of the segment represented by the node. We build this structure for $x = 0$, so we just add all the values of the original array into the trie. What happens to this structure when we flip some bit $x$? Let's say that the bit $k-1$ is flipped. It means that we have to swap the left child and the right child of the root of the trie. If we flip the bit $k-2$, we need to swap the neighboring nodes in this trie on depth $2$, and so on. When we flip the $k-i$-th bit, it means that we have to rebuild the first $i + 1$ layers of the trie, which have $2^{i+1} - 1$ nodes. So we need to iterate through all possible values of $x$ while rebuilding the data structure in some way that our rebuilds are not too costly. One of the ways to do it is to use Gray code. If we iterate on $x$ using a variation of Gray code where we start from most significant bits instead of the least significant bits, the bit $k-1$ will be swapped $2^{k-1}$ times (and the total rebuild time for these swaps will be $2^{k-1} \cdot 3 < 2^{k+1}$), the bit $k-2$ will be swapped $2^{k-2}$ times (and the total rebuild time for these swaps will be $2^{k-2} \cdot 7 < 2^{k+1}$), and so on. So, the total rebuild time for the whole process will be $O(2^k \cdot k)$. Brief description of the second approach: for each node, we can store multiple versions of that node. A version of a node is another node which represents the same subtree having all of the numbers XOR'ed by some number $x$. We can see that if we try to XOR all numbers of a node representing a segment of size $4$ by, for example, $8$, nothing changes, and if we try to XOR all numbers by, for example, $11$, the result for this subtree will be the same as if we XOR it by $3$. So, for a subtree of size $m$, we store $m$ versions of it, so the whole structure contains $2^k \cdot k$ versions of nodes.
[ "bitmasks", "divide and conquer", "trees" ]
2,900
#include<bits/stdc++.h> using namespace std; const int INF = int(1e9); const int K = 20; struct node { int max_val, min_val, ans, len; node(const node& left, const node& right) { len = left.len + right.len; max_val = max(left.max_val, right.max_val + left.len); min_val = min(left.min_val, right.min_val + left.len); ans = min(min(left.ans, right.ans), min(INF, right.min_val - left.max_val + left.len)); } node(int x) { ans = INF; len = 1; if(x == 1) max_val = min_val = 0; else { max_val = -INF; min_val = INF; } } node() {}; }; int cnt[1 << K]; vector<node> tree[2 << K]; void build(int v, int l, int r) { tree[v].resize(r - l); if(l == r - 1) { tree[v][0] = node(cnt[l]); } else { int m = (l + r) / 2; build(v * 2 + 1, l, m); build(v * 2 + 2, m, r); for(int i = 0; i < m - l; i++) { tree[v][i] = node(tree[v * 2 + 1][i], tree[v * 2 + 2][i]); tree[v][i + (m - l)] = node(tree[v * 2 + 2][i], tree[v * 2 + 1][i]); } } } int main() { int n, k; scanf("%d %d", &n, &k); for(int i = 0; i < n; i++) { int x; scanf("%d", &x); cnt[x]++; } int m = 1 << k; build(0, 0, m); for(int i = 0; i < m; i++) printf("%d ", tree[0][i].ans); puts(""); }
1553
I
Stairs
For a permutation $p$ of numbers $1$ through $n$, we define a stair array $a$ as follows: $a_i$ is length of the longest segment of permutation which contains position $i$ and is made of consecutive values in sorted order: $[x, x+1, \ldots, y-1, y]$ or $[y, y-1, \ldots, x+1, x]$ for some $x \leq y$. For example, for permutation $p = [4, 1, 2, 3, 7, 6, 5]$ we have $a = [1, 3, 3, 3, 3, 3, 3]$. You are given the stair array $a$. Your task is to calculate the number of permutations which have stair array equal to $a$. Since the number can be big, compute it modulo $998\,244\,353$. Note that this number can be equal to zero.
First of all, we need to transform the stair array into some other structure. Let's show that for each number, there is only one longest stair covering it, and these longest stairs are disjoint. Suppose that some number $x$ belongs to two different ascending stairs. We can easily expand these stairs to the left and to the right and find the longest ascending stair covering the number. So, it means that the longest ascending stair covering a number is unique. The same for descending stairs. Now suppose that some number $x$ belongs to an ascending stair of length $\ge 2$ and a descending stair of length $\ge 2$. It is impossible because it would mean that we have consecutive values $[x-1, x, x-1]$ or $[x+1, x, x+1]$ in the permutation, but since it is a permutation, all values should be distinct. So, the longest stair covering each number is unique. Let's split the stair array into this sequence of longest stairs. The first element of the stair array belongs to some stair. If $a_1 = k$, then the first $k$ elements form a stair. Let's check that all these $k$ elements are equal to $k$ and split them into a stair of length $k$, then continue the same algorithm from $a_{k+1}$. Okay, now we have an array of the lengths of the longest stairs. Each stair represents some segment of numbers, and all stairs can be enumerated by the index of their value segment. So, it looks like the number of permutations that yeild this array of longest stairs is $s! 2^{s'}$, where $s$ is the number of stairs and $s'$ is the number of stairs having length $\ge 2$. The reasoning behind this formula is that each stair gets assigned an index corresponding to the index of its value segment in the sorted order, and for stairs of length $\ge 2$, we can choose whether they are ascending or descending. Is that formula right? Unfortunately, no. The fact that we have the array of longest stairs means that we need to ensure that no pair of adjacent stairs merge. And there's no easy way to change this formula, unfortunately. Let's use inclusion-exclusion to eliminate all "bad" permutations. We have $s-1$ constraints that shouldn't be violated: stairs $1$ and $2$ shouldn't merge; stairs $2$ and $3$ shouldn't merge; ...; stairs $s-1$ and $s$ shouldn't merge. For every $i$ from $0$ to $s-1$, we can calculate the number of ways to choose $i$ constraints to be violated and a permutation that violates these constrains (and maybe some others), like in the usual inclusion-exclusion formula applications. These values can be calculated with the following dynamic programming: $dp_{n,k,t}$ is the number of ways to choose this set of $k$ violated constraints and a permutation for $n$ first stairs, and $t$ represents the type of the last stair (ascending/descending or having size $1$). What are the transitions in this dynamic programming? When placing a new stair, we may choose either to explicitly violate the constraint on merging it with the previous one (so, we transition to a state $dp_{n+1,k+1,t'}$ and maybe multiply/divide the value by $2$ if we are merging two size-$1$ stairs or merging two stairs with different types). Or we can choose to just make an entirely new stair, choosing one of $n-k+1$ values for it (since we already have $n-k$ stairs), choosing its type if its length is $\ge 2$, and transitioning to $dp_{n+1,k,t'}$. The main drawback of this solution is that it's $O(n^2)$. Let's find a way to optimize it. Let's calculate this dynamic programming in a divide-and-conquer fashion. Let's say that for some segment $[l, r]$ of stairs, we will calculate a three-dimensional array $dp_{tl,tr,i}$ - the number of ways to violate $i$ constraints in this segment so that the leftmost stair in this segment has type $tl$, and the rightmost stair in this segment has type $tr$. Suppose we want to merge these two segments. We either merge the leftmost stair of the right segment with the rightmost stair of the left segment, or don't. Let's analyze the case when we don't merge them. Let's analyze the value of $dp_{tl, tr, i}$ in the resulting array. Suppose we violate $k$ constraints in the left segment, this leaves us to violate $i-k$ constraints in the right segment. So, the value of $dp_{tl,tr,i}$ in the resulting merged structure will be the sum of $dp_{tl,?,k}$ from the left segment multiplied by $dp_{?,tr,i-k}$ from the right segment (where $?$ can represent any type). And if we treat the values from the left and the right segment as polynomials (where value of $dp_{tl,?,k}$ or $dp_{?,tr,k}$ is the coefficient for $x^k$), merging them is exactly polynomial multiplication! So we can use FFT so speed up the merging. If we want to merge two segments while explicitly violating the constraint that the rightmost stair in the left segment and the leftmost stair in the right segment shouldn't be merged into one, it can be done with polynomial multiplication as well, but you also have to multiply the result by some coefficient that arises from merging those two stairs (if both of them had size $1$, then we multiply the result by $2$ since we can choose whether the resulting stair is ascending or descending; and if both of them had size $\ge 1$, we divide the result by $2$ since we cannot merge an ascending stair with a descending one). So, this optimization allows us to merge two segments of length $n$ in time $O(n \log n)$, and as the usual FFT + D&C combination, this results in a complexity of $O(n \log^2 n)$, though with a fairly large constant factor.
[ "combinatorics", "divide and conquer", "dp", "fft", "math" ]
3,400
#include<bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) #define sz(a) ((int)((a).size())) #define fore(i, l, r) for(int i = int(l); i < int(r); i++) template<const int &MOD> struct _m_int { int val; _m_int(int64_t v = 0) { if (v < 0) v = v % MOD + MOD; if (v >= MOD) v %= MOD; val = int(v); } _m_int(uint64_t v) { if (v >= MOD) v %= MOD; val = int(v); } _m_int(int v) : _m_int(int64_t(v)) {} _m_int(unsigned v) : _m_int(uint64_t(v)) {} static int inv_mod(int a, int m = MOD) { int g = m, r = a, x = 0, y = 1; while (r != 0) { int q = g / r; g %= r; swap(g, r); x -= q * y; swap(x, y); } return x < 0 ? x + m : x; } explicit operator int() const { return val; } explicit operator unsigned() const { return val; } explicit operator int64_t() const { return val; } explicit operator uint64_t() const { return val; } explicit operator double() const { return val; } explicit operator long double() const { return val; } _m_int& operator+=(const _m_int &other) { val -= MOD - other.val; if (val < 0) val += MOD; return *this; } _m_int& operator-=(const _m_int &other) { val -= other.val; if (val < 0) val += MOD; return *this; } static unsigned fast_mod(uint64_t x, unsigned m = MOD) { #if !defined(_WIN32) || defined(_WIN64) return unsigned(x % m); #endif // Optimized mod for Codeforces 32-bit machines. // x must be less than 2^32 * m for this to work, so that x / m fits in an unsigned 32-bit int. unsigned x_high = unsigned(x >> 32), x_low = unsigned(x); unsigned quot, rem; asm("divl %4\n" : "=a" (quot), "=d" (rem) : "d" (x_high), "a" (x_low), "r" (m)); return rem; } _m_int& operator*=(const _m_int &other) { val = fast_mod(uint64_t(val) * other.val); return *this; } _m_int& operator/=(const _m_int &other) { return *this *= other.inv(); } friend _m_int operator+(const _m_int &a, const _m_int &b) { return _m_int(a) += b; } friend _m_int operator-(const _m_int &a, const _m_int &b) { return _m_int(a) -= b; } friend _m_int operator*(const _m_int &a, const _m_int &b) { return _m_int(a) *= b; } friend _m_int operator/(const _m_int &a, const _m_int &b) { return _m_int(a) /= b; } _m_int& operator++() { val = val == MOD - 1 ? 0 : val + 1; return *this; } _m_int& operator--() { val = val == 0 ? MOD - 1 : val - 1; return *this; } _m_int operator++(int) { _m_int before = *this; ++*this; return before; } _m_int operator--(int) { _m_int before = *this; --*this; return before; } _m_int operator-() const { return val == 0 ? 0 : MOD - val; } friend bool operator==(const _m_int &a, const _m_int &b) { return a.val == b.val; } friend bool operator!=(const _m_int &a, const _m_int &b) { return a.val != b.val; } friend bool operator<(const _m_int &a, const _m_int &b) { return a.val < b.val; } friend bool operator>(const _m_int &a, const _m_int &b) { return a.val > b.val; } friend bool operator<=(const _m_int &a, const _m_int &b) { return a.val <= b.val; } friend bool operator>=(const _m_int &a, const _m_int &b) { return a.val >= b.val; } _m_int inv() const { return inv_mod(val); } _m_int pow(int64_t p) const { if (p < 0) return inv().pow(-p); _m_int a = *this, result = 1; while (p > 0) { if (p & 1) result *= a; a *= a; p >>= 1; } return result; } friend ostream& operator<<(ostream &os, const _m_int &m) { return os << m.val; } }; extern const int MOD = 998244353; using Mint = _m_int<MOD>; const int LOGN = 19; const int N = (1 << LOGN); const int T = 2; Mint g = 3; vector<Mint> w[LOGN]; vector<int> rv[LOGN]; void precalc() { Mint wb = Mint(g).pow((MOD - 1) / (1 << LOGN)); forn(st, LOGN - 1) { w[st].assign(1 << st, 1); Mint bw = wb.pow(1 << (LOGN - st - 1)); Mint cw = 1; forn(k, 1 << st) { w[st][k] = cw; cw *= bw; } } forn(st, LOGN) { rv[st].assign(1 << st, 0); if (st == 0) { rv[st][0] = 0; continue; } int h = (1 << (st - 1)); forn(k, 1 << st) rv[st][k] = (rv[st - 1][k & (h - 1)] << 1) | (k >= h); } } void ntt(vector<Mint> &a, bool inv) { int n = sz(a); int ln = __builtin_ctz(n); forn(i, n) { int ni = rv[ln][i]; if (i < ni) swap(a[i], a[ni]); } forn(st, ln) { int len = 1 << st; for (int k = 0; k < n; k += (len << 1)) { fore(pos, k, k + len){ Mint l = a[pos]; Mint r = a[pos + len] * w[st][pos - k]; a[pos] = l + r; a[pos + len] = l - r; } } } if (inv) { Mint rn = Mint(n).inv(); forn(i, n) a[i] *= rn; reverse(a.begin() + 1, a.end()); } } vector<Mint> mul(vector<Mint> a, vector<Mint> b) { int cnt = 1 << (32 - __builtin_clz(sz(a) + sz(b) - 1)); a.resize(cnt); b.resize(cnt); ntt(a, false); ntt(b, false); vector<Mint> c(cnt); forn(i, cnt) c[i] = a[i] * b[i]; ntt(c, true); while(c.size() > 1 && c.back() == 0) c.pop_back(); return c; } struct dp { vector<Mint> val[T][T]; bool is_unit; dp() {}; dp(int len) { is_unit = len == 1; for(int j = 0; j < T; j++) for(int k = 0; k < T; k++) val[j][k] = {0}; if(len == 1) val[0][0][0] = 1; else val[1][1][0] = 2; } dp(const dp& a, const dp& b) { is_unit = false; for(int l1 = 0; l1 < T; l1++) for(int r1 = 0; r1 < T; r1++) for(int l2 = 0; l2 < T; l2++) for(int r2 = 0; r2 < T; r2++) { vector<Mint> cur = mul(a.val[l1][r1], b.val[l2][r2]); if(val[l1][r2].size() < cur.size()) val[l1][r2].resize(cur.size()); for(int i = 0; i < cur.size(); i++) val[l1][r2][i] += cur[i]; Mint merge_coeff = 2; if(r1 == 1) merge_coeff /= 2; if(l2 == 1) merge_coeff /= 2; cur.insert(cur.begin(), 0); for(int i = 0; i < cur.size(); i++) cur[i] *= merge_coeff; int L1 = l1; int R2 = r2; if(a.is_unit) L1 = 1; if(b.is_unit) R2 = 1; if(val[L1][R2].size() < cur.size()) val[L1][R2].resize(cur.size()); for(int i = 0; i < cur.size(); i++) { val[L1][R2][i] += cur[i]; } } } }; ostream& operator<<(ostream& out, const dp& a) { for(int i = 0; i < T; i++) for(int j = 0; j < T; j++) { out << "[" << i << "][" << j << "]"; for(auto x : a.val[i][j]) out << " " << x; out << endl; } return out; } int a[N]; int len[N]; Mint fact[N]; int n; int s; dp build(int l, int r) { if(l == r - 1) { dp res(len[l]); //cerr << l << " " << r << endl; //cerr << res; return res; } else { int m = (l + r) / 2; dp res(build(l, m), build(m, r)); //cerr << l << " " << r << endl; //cerr << res; return res; } } int main() { precalc(); scanf("%d", &n); for(int i = 0; i < n; i++) scanf("%d", &a[i]); int cur = 0; while(cur != n) { if(cur + a[cur] > n) { cout << 0 << endl; return 0; } for(int l = cur; l < cur + a[cur]; l++) if(a[l] != a[cur]) { cout << 0 << endl; return 0; } len[s++] = a[cur]; cur += a[cur]; } fact[0] = 1; for(int i = 1; i <= s; i++) fact[i] = i * fact[i - 1]; dp res = build(0, s); Mint ans = 0; for(int i = 0; i < s; i++) for(int j = 0; j < T; j++) for(int k = 0; k < T; k++) if(res.val[j][k].size() > i) ans += fact[s - i] * res.val[j][k][i] * (i % 2 == 0 ? 1 : MOD - 1); cout << ans << endl; }
1554
A
Cherry
You are given $n$ integers $a_1, a_2, \ldots, a_n$. Find the maximum value of $max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r)$ over all pairs $(l, r)$ of integers for which $1 \le l < r \le n$.
Do we really need to check all the subarrays? Consider a subarray $(a_i, a_{i + 1}, \ldots, a_{j})$. If we add a new element $a_{j + 1}$, when will the new subarray $(a_i, a_{i + 1}, \ldots, a_{j}, a_{j + 1})$ give a better result? Pause and think. The minimum of the new subarray can't get better(the minimum of a smaller subarray $\ge$ the minimum of a larger subarray). So only when $a_{j + 1}$ is greater than the previous maximum, then it will give a better result. But in that case, do we really need to check the whole subarray to get that result? Can we get the same or a better result from a smaller subarray? Think. Here the maximum is $a_{j + 1}$. So if the minimum is not $a_i$, then the subarray $(a_{i + 1}, a_{i + 2}, \ldots, a_{j + 1})$ will give the same result. Otherwise, the minimum of $(a_{i + 1}, a_{i + 2}, \ldots, a_{j + 1})$ will not be smaller which implies that $(a_{i + 1}, a_{i + 2}, \ldots, a_{j + 1})$ will give a better result! So if we add a new element, we don't have to check the whole subarray, checking $(a_i, a_{i + 1}, \ldots, a_{j})$ and $(a_{i + 1}, a_{i + 2}, \ldots, a_{j + 1})$ is enough. What good this observation just brought to this world? Think. Yes, we don't have to check subarrays with length $> 2$, because according to the observation, $(a_1, a_2, a_3)$ won't give a better result than $(a_1, a_2)$ and $(a_2, a_3)$. And subarrays with length $4$ won't give a better result than subarrays with length $3$ and subarrays with length $3$ won't give a better result than subarrays with length $2$. You got the idea, right? Another thing to notice here is that the product of maximum and minimum of two integers is just the product of two integers. So the answer to the problem is the maximum of the products of adjacent elements in $a$. Time Complexity: $\mathcal{O}(n)$
[ "greedy" ]
800
import sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) ans = 0 for i in range(n - 1): ans = max(ans, a[i] * a[i + 1]) print(ans)
1554
B
Cobb
You are given $n$ integers $a_1, a_2, \ldots, a_n$ and an integer $k$. Find the maximum value of $i \cdot j - k \cdot (a_i | a_j)$ over all pairs $(i, j)$ of integers with $1 \le i < j \le n$. Here, $|$ is the bitwise OR operator.
Let $f(i, j) = i \cdot j - k \cdot (a_i | a_j)$ for $i < j$. Do we really need to check all pairs? The value of $k$ is small, which is suspicious. There must be something revolving around it. What can that be? In the equation, $i \cdot j$ can be $\mathcal{O}(n^2)$, but $k \cdot (a_i | a_j)$ is $\mathcal{O}(n \cdot 100)$. That means the value of $f(i, j)$ must be larger for bigger $i, j$. Can you deduce something from this? What is the smallest $i$ which can contribute to the result($f(i, j): i < j$ is the maximum)? Pause and think. Hint: try to maximize $f(i, j)$ and minimize the heaviest pair, that is, $f(n - 1, n)$, and compare them. Let's find it. What is the maximum possible value of a pair containing $i$?. It's when $i$ pairs with $n$ and $a_i = a_n = 0$. So, $f(i, n) = i \cdot n - k \cdot 0 = i \cdot n$. What is the minimum possible value of the heaviest pair $f(n - 1, n)$? It's when $a_{n - 1} | a_n$ is maximum. And, since $0 \le a_i \le n$, the maximum possible of value any $a_i | a_j$ is $\le 2n$. So $f(n - 1, n) = (n - 1) \cdot n - k \cdot 2n = n^2 - 2kn - n$. For $i$ to contribute to the result, $f(i, n)$ must be $\gt f(n - 1, n)$. And, when $f(i, n) \gt f(n - 1, n)$, then $i \cdot n \gt n^2 - 2kn - n$, or $i \gt n - 2k -1$. So any of $f(i, j)$ such that $i < n - 2k$ won't generate a value greater than $f(n - 1, n)$!. This indicates us that we just have to check the pairs $f(i, j)$ such that $i, j \ge n - 2k$. And, there are only $\mathcal{O}(k^2)$ such pairs, so we can brute-force. We have also allowed $\mathcal{O}(n \cdot k)$ solutions to pass i.e. brute-forcing over all pairs such that $1 \le i \le n$ and $n - 2k \le j \le n$. Time Complexity: $\mathcal{O}(k^2)$
[ "bitmasks", "brute force", "greedy", "math" ]
1,700
import sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) l = max(0, n - 2 * k - 1) ans = -1e12 for i in range(l, n): for j in range(i + 1, n): ans = max(ans, (i + 1) * (j + 1) - k * (a[i] | a[j])) print(ans)
1554
C
Mikasa
You are given two integers $n$ and $m$. Find the $\operatorname{MEX}$ of the sequence $n \oplus 0, n \oplus 1, \ldots, n \oplus m$. Here, $\oplus$ is the bitwise XOR operator. $\operatorname{MEX}$ of the sequence of non-negative integers is the smallest non-negative integer that doesn't appear in this sequence. For example, $\operatorname{MEX}(0, 1, 2, 4) = 3$, and $\operatorname{MEX}(1, 2021) = 0$.
How can we check if $k$ is present in the sequence $n\oplus 0,n\oplus 1,...,n\oplus m$ ? Think. If $k$ is present in the sequence, then there must be some $x$ such that $0 \le x \le m$ and $n\oplus x = k$, right? Did you know that $n\oplus k = x$ is equivalent to $n\oplus x = k$ ? So we can just check if $n\oplus k \le m$ or not! Pretty simple! So the modified problem is to find the smallest non-negative integer $k$ such that $n\oplus k \ge m+1$. Can you solve it now? Think using bits. Let $p = m+1$ and $t_i$ be the $i$-th bit of $t$. We will find the smallest $k$ such that $n\oplus k \ge p$. Let's build $k$ greedily from the highest bit to the lowest bit. Let's say we will find the $i$-th bit of $k$ and the higher bits have already been generated. Obviously, we will try to make this bit off if possible. When will it be impossible? Think. If $n_i = p_i$, we can set $k_i = 0$ as $n_i \oplus 0 = n_i \ge p_i$. If $n_i = 1$ and $p_i = 0$, we can break here by setting the remaining bits of $k$ off as no matter what the remaining bits of $n$ are, $n \oplus k$ will always be greater than $p$. Finally, if $n_i = 0$ and $p_i = 1$, we must set $k_i = 1$, as we have no other options. Check my solution for more clarity. Time Complexity: $\mathcal{O}(log(n))$ per test case.
[ "binary search", "bitmasks", "greedy", "implementation" ]
1,800
import sys input = sys.stdin.buffer.readline t = int(input()) for _ in range(t): n, m = map(int, input().split()) m += 1 ans = 0 for k in range(30, -1, -1): if (n >= m): break if ((n >> k & 1) == (m >> k & 1)): continue if (m >> k & 1): ans |= 1 << k n |= 1 << k print(ans)
1554
D
Diane
You are given an integer $n$. Find any string $s$ of length $n$ consisting only of English lowercase letters such that each non-empty substring of $s$ occurs in $s$ an \textbf{odd} number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Consider the strings of type "$aa \ldots a$". Which substring occurs in which parity? Observe. Play with them. Consider the string "$aa \ldots a$" ($k$ times '$a$'). WLOG Let $k$ be an odd integer. In this string "$a$" occurs $k$ times, "$aa$" occurs $k - 1$ times and so on. So "$a$", "$aa$", "$aaa$", $\ldots$ occurs odd, even, odd, even, $\ldots$ times, respectively. Now let's look at the string "$aa \ldots a$" ($k - 1$ times '$a$'). In this string, "$a$", "$aa$", "$aaa$", $\ldots$ occurs even, odd, even, odd, $\ldots$ times, respectively. What can be done now? Did you know that odd $+$ even $=$ odd? Pause and think. Let's merge both strings! If we merge them with "$b$" in-between i.e. "$\underbrace{aaa \ldots aaa}_\text{k times} b \underbrace{aaa\ldots aa}_\text{k - 1 times}$", then each substring will occur an odd number of times. Thats because each of "$a$", "$aa$", "$aaa$", $\ldots$ occurs odd $+$ even $=$ odd times, and each newly created substring occurs exactly once. What will happen if we set $k = \left \lfloor{\frac{n}{2}}\right \rfloor$? So here is the solution to the problem: "$\underbrace{aaa \ldots aaa}_\text{k times} + b | bc + \underbrace{aaa\ldots aa}_\text{k- 1 times}$", where $k = \left \lfloor{\frac{n}{2}}\right \rfloor$ and "$b$" when $n$ is even and "$bc$" when $n$ is odd. For example, if $n = 6$, answer is "$aaabaa$" and if $n = 7$, answer is "$aaabcaa$". Time Complexity: $\mathcal{O}(n)$ If you are wondering(as you always do) about the checker: Write a suffix automata and check if every node occurs an odd number of times.
[ "constructive algorithms", "greedy", "strings" ]
1,800
#include<bits/stdc++.h> #include "testlib.h" using namespace std; // len -> largest string length of the corresponding endpos-equivalent class // link -> longest suffix that is another endpos-equivalent class. // firstpos -> 1 indexed end position of the first occurrence of the largest string of that node // minlen(v) -> smallest string of node v = len(link(v)) + 1 // terminal nodes -> store the suffixes struct SuffixAutomaton { struct node { int len, link, firstpos; map<char, int> nxt; }; int sz, last; vector<node> t; vector<int> terminal; vector<int> dp; vector<vector<int>> g; SuffixAutomaton() {} SuffixAutomaton(int n) { t.resize(2 * n); terminal.resize(2 * n, 0); dp.resize(2 * n, -1); sz = 1; last = 0; g.resize(2 * n); t[0].len = 0; t[0].link = -1; t[0].firstpos = 0; } void extend(char c) { int p = last; int cur = sz++; t[cur].len = t[last].len + 1; t[cur].firstpos = t[cur].len; p = last; while (p != -1 && !t[p].nxt.count(c)) { t[p].nxt[c] = cur; p = t[p].link; } if (p == -1) t[cur].link = 0; else { int q = t[p].nxt[c]; if (t[p].len + 1 == t[q].len) t[cur].link = q; else { int clone = sz++; t[clone] = t[q]; t[clone].len = t[p].len + 1; while (p != -1 && t[p].nxt[c] == q) { t[p].nxt[c] = clone; p = t[p].link; } t[q].link = t[cur].link = clone; } } last = cur; } void build_tree() { for (int i = 1; i < sz; i++) g[t[i].link].push_back(i); } void build(string &s) { for (auto x: s) { extend(x); terminal[last] = 1; } build_tree(); } int cnt(int i) { // number of times i-th node occurs in the string if (dp[i] != -1) return dp[i]; int ret = terminal[i]; for (auto &x: g[i]) ret += cnt(x); return dp[i] = ret; } }; pair<int, int> ok(string s) { int n = s.size(); SuffixAutomaton sa(n); sa.build(s); for (int i = 1; i < sa.sz; i++) { if (sa.cnt(i) % 2 == 0) { return {sa.t[i].firstpos - sa.t[i].len, sa.t[i].firstpos - 1}; } } return {-1, -1}; } int main(int argc, char* argv[]) { registerTestlibCmd(argc, argv); int t = inf.readInt(); inf.readEoln(); for (int test = 1; test <= t; test++) { setTestCase(test); int n = inf.readInt(); inf.readEoln(); string s = ouf.readToken(); if (s.size() != n) { quitf(_wa, "the length of s should be exactly %d", n); } for (int i = 0; i < n; i++) { if (!(s[i] >= 'a' and s[i] <= 'z')) { quitf(_wa, "s contains %c which is not an English lowercase character", s[i]); } } auto p = ok(s); if (p.first != -1) { quitf(_wa, "the substring s[%d, %d] (0-indexed) occurs even number of times in s :\"(", p.first, p.second); } } quitf(_ok, "you are the best problem solver ever UwU"); return 0; }
1554
E
You
You are given a tree with $n$ nodes. As a reminder, a tree is a connected undirected graph without cycles. Let $a_1, a_2, \ldots, a_n$ be a sequence of integers. Perform the following operation \textbf{exactly} $n$ times: - Select an \textbf{unerased} node $u$. Assign $a_u :=$ number of \textbf{unerased} nodes adjacent to $u$. Then, erase the node $u$ along with all edges that have it as an endpoint. For each integer $k$ from $1$ to $n$, find the number, modulo $998\,244\,353$, of different sequences $a_1, a_2, \ldots, a_n$ that satisfy the following conditions: - it is possible to obtain $a$ by performing the aforementioned operations \textbf{exactly} $n$ times in some order. - $\operatorname{gcd}(a_1, a_2, \ldots, a_n) = k$. Here, $\operatorname{gcd}$ means the greatest common divisor of the elements in $a$.
Let's find which sequences of $a$ are possible to obtain by performing the mentioned operations exactly $n$ times in some order. (Critical) Observation 1: Consider all $a_i = 0$ initially. For each edge $(u, v)$, either increase $a_u$ by $1$ (assign $(u, v)$ to $u$) or increase $a_v$ by $1$ ((assign $(u, v)$ to $v$). The final sequences are the only possible sequences that $a$ can possibly be. You can observe it by noticing that when we select a node and delete it, the existing edges adjacent to the node gets assigned to it. Notice that, the final sequences are unique. So there are $2^{n - 1}$ distinct sequences possible. That's because there are $n - 1$ edges and for each edge $(u, v)$ we have $2$ options - either assign it to $u$ or $v$. Now for each $k$ from $1$ to $n$, we have to find the number of sequences which has gcd equals to $k$. Instead, let's find the number of sequences such that each of its values is divisible by $k$. Let it be $f_k$. For $k = 1$, all sequences are valid. So $f_1 = 2^{n - 1}$. Assume $k > 1$. Let's construct a sequence $a$ such that each $a_i$ is divisible by $k$. First, root the tree at node $1$. We will build the array in a bottom-up manner. Let $g_u$ be the set of childs of $u$ and $p_u$ be the parent of $u$. Assume that we have set the values for each $v \in g_u$. Now we will set the value of $a_u$. For each edge $(u, v)$ such that $v \in g_u$, if we have assigned this edge to $v$, then do nothing, otherwise we must assign it to $u$ i.e increase $a_u$ by $1$. After we are done with all the edges, if $a_u$ is divisible by $k$, then we can't assign the edge $(p_u, u)$ to $u$ because $a_u$ will be increased by $1$ and as $a_u$ is divisible by $k$, $(a_u + 1)$ will not be divisible by $k$ because $k > 1$. if $a_u$ is not divisible by $k$, then we must assign the edge $(p_u, u)$ to $u$ and thus increasing $a_u$ by $1$. If now $a_u$ is divisible by $k$, then we are done, otherwise we can't make $a_u$ divisible by $k$. So we terminate here. If we can successfully set the values of $a_i$ for each $i$ from $1$ to $n$, then $f_k$ will be non-zero. Observation 2: $f_k$ for $k > 1$ is either $0$ or $1$. We can say this by observing the building process of $a_i$ that has been discussed already. So for each $k$ from $1$ to $n$, we can find the value of $f_k$ in $\mathcal{O}(n)$ by performing a simple dfs. So all $f_k$ can be found in $\mathcal{O}(n^2)$. Observation 3: If $k$ doesn't divide $n - 1$, then $f_k = 0$. Proof: Notice that $\sum\limits_{i = 1}^{n}{a_i} = n - 1$. So for any integer $k$, if each $a_i$ is divisible $k$, then $k$ must divide $n - 1$. Similarly, if $k$ doesn't divide $n - 1$, then each $a_i$ will not be divisible by $k$ and $f_k$ will be $0$. So we only have to perform a dfs when $k$ divides $n - 1$. So all $f_k$ can be found in $\mathcal{O}(n \cdot \sigma_0 (n - 1))$ where $\sigma_0(x)$ is the number of divisors of $x$. Let $h_k$ be the number of sequences which has gcd equals to $k$. We can notice that $h_k = f_k - \sum\limits_{i = 2}^{\left \lfloor{\frac{n}{k}}\right \rfloor}{h_{i \cdot k}}$. So we can find $h_k$ for each $k$ from $1$ to $n$ in $\mathcal{O}(n \cdot log(n))$. Time Complexity: $\mathcal{O}(n \cdot \sigma_0 (n - 1) + n \cdot log(n))$
[ "dfs and similar", "dp", "math", "number theory" ]
2,600
#include<bits/stdc++.h> using namespace std; const int N = 1e5 + 9, mod = 998244353; vector<int> g[N]; int dp[N], d, ok, ans[N]; void dfs(int u, int p = 0) { if (!ok) return; for (auto v: g[u]) { if (v ^ p) { dfs(v, u); } } if (dp[u] % d != 0) { if (p) { dp[u]++; } if (dp[u] % d != 0) { ok = 0; return; } } else { dp[p]++; } } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); } for (int i = 1; i <= n; i++) { ans[i] = 0; } ans[1] = 1; for (int k = 1; k <= n - 1; k++) { ans[1] = (ans[1] + ans[1]) % mod; } for (d = 2; d <= n - 1; d++) { if ((n - 1) % d == 0) { ok = 1; dfs(1); ans[d] = ok; for (int i = 0; i <= n; i++) { dp[i] = 0; } } } for (int i = n; i >= 1; i--) { for (int j = i + i; j <= n; j += i) { ans[i] = (ans[i] - ans[j] + mod) % mod; } } for (int i = 1; i <= n; i++) { if (i > 1) cout << ' '; cout << ans[i]; } cout << '\n'; for (int i = 1; i <= n; i++) { g[i].clear(); } } return 0; }
1555
A
PizzaForces
PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of $6$ slices, medium ones consist of $8$ slices, and large pizzas consist of $10$ slices each. Baking them takes $15$, $20$ and $25$ minutes, respectively. Petya's birthday is today, and $n$ of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order. Your task is to determine the minimum number of minutes that is needed to make pizzas containing at least $n$ slices in total. For example: - if $12$ friends come to Petya's birthday, he has to order pizzas containing at least $12$ slices in total. He can order two small pizzas, containing exactly $12$ slices, and the time to bake them is $30$ minutes; - if $15$ friends come to Petya's birthday, he has to order pizzas containing at least $15$ slices in total. He can order a small pizza and a large pizza, containing $16$ slices, and the time to bake them is $40$ minutes; - if $300$ friends come to Petya's birthday, he has to order pizzas containing at least $300$ slices in total. He can order $15$ small pizzas, $10$ medium pizzas and $13$ large pizzas, in total they contain $15 \cdot 6 + 10 \cdot 8 + 13 \cdot 10 = 300$ slices, and the total time to bake them is $15 \cdot 15 + 10 \cdot 20 + 13 \cdot 25 = 750$ minutes; - if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is $15$ minutes.
Note that the "speed" of cooking $1$ slice of pizza is the same for all sizes - $1$ slice of pizza for $2.5$ minutes. If $n$ is odd, then we will increase it by $1$ (since the pizza is cooked only with an even number of pieces). Now the value of $n$ is always even. If $n < 6$, then for such $n$ the answer is equal to the answer for $n=6$, so we can say that $n = \max(n, 6)$. While $n \ge 12$ we can order a small pizza. Eventually the value of $n$ will be equal to $6$, $8$ or $10$. This means that for any $n$ there will be a set of pizzas with exactly $n$ slices. Then the answer is $n * 2.5$ (in the solution, it is better to use the formula $n / 2 * 5$).
[ "brute force", "math" ]
900
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { long long n; cin >> n; cout << max(6LL, n + 1) / 2 * 5 << '\n'; } }
1555
B
Two Tables
You have an axis-aligned rectangle room with width $W$ and height $H$, so the lower left corner is in point $(0, 0)$ and the upper right corner is in $(W, H)$. There is a rectangular table standing in this room. The sides of the table are parallel to the walls, the lower left corner is in $(x_1, y_1)$, and the upper right corner in $(x_2, y_2)$. You want to place another rectangular table in this room with width $w$ and height $h$ with the width of the table parallel to the width of the room. The problem is that sometimes there is not enough space to place the second table without intersecting with the first one (there are no problems with tables touching, though). You \textbf{can't rotate} any of the tables, but you can move the first table inside the room. \begin{center} {\small Example of how you may move the first table.} \end{center} What is the minimum distance you should move the first table to free enough space for the second one?
Firstly, let's notice the next property: if two axis-aligned rectangles don't intersect, then we can draw a vertical or horizontal line between them. In other words, either $\max(x_1, x_2) \le \min(x_3, x_4)$ or $\max(x_3, x_4) \le \min(x_1, x_2)$ if $x_1$ and $x_2$ are coordinates of the one rectangle and $x_3$ and $x_4$ of the other one (analogically, for $y$ coordinates). Now, suppose you want to move the first table by $(dx, dy)$. Note that if in result they will be divided by vertical line then we can set $dy = 0$ - they still will be divided, but the total distance will decrease. Analogically, if divided by horizontal line, we can set $dx = 0$. In other words, it's always optimal to move the table either horizontally or vertically. Let's look at the case of horizontal move: at first, we need to check that both tables can fit in the room, or their total width $w + (x_2 - x_1) \le W$. If yes, then we calculate the movement distance $dx$ as follows: if we move the table right then there should be at least $w$ to the left of it, or $w \le x_1 + dx$ $\Leftrightarrow$ $dx \ge w - x_1$. Since we want to minimize $dx$ then we take $dx = \max(0, w - x_1)$. If we want to move the table left, then there should be at least $w$ to the right, or $x_2 - dx \le W - w$ $\Leftrightarrow$ $dx \ge x_2 - (W - w)$, minimizing $dx$ means taking $dx = \max(0, x_2 - (W - w))$. So, the result is $\min(\max(0, w - x_1), \max(0, x_2 - (W - w)))$. The vertical case can be handled in the same manner, if $h + (y_2 - y_1) \le H$ then the result is $\min(\max(0, h - y_1), \max(0, y_2 - (H - h)))$. The answer is the minimum among all possible variants, or $-1$ if both cases are impossible.
[ "brute force" ]
1,300
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; const int INF = int(1e9); int W, H; int x1, y1, x2, y2; int w, h; inline bool read() { if(!(cin >> W >> H)) return false; cin >> x1 >> y1 >> x2 >> y2; cin >> w >> h; return true; } inline void solve() { int ans = INF; if (x2 - x1 + w <= W) { ans = min(ans, max(0, w - x1)); ans = min(ans, max(0, x2 - (W - w))); } if (y2 - y1 + h <= H) { ans = min(ans, max(0, h - y1)); ans = min(ans, max(0, y2 - (H - h))); } if (ans == INF) cout << -1 << endl; else cout << double(ans) << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); #endif cout << fixed << setprecision(9); int t; cin >> t; while(t--) { (read()); solve(); } return 0; }
1555
C
Coin Rows
Alice and Bob are playing a game on a matrix, consisting of $2$ rows and $m$ columns. The cell in the $i$-th row in the $j$-th column contains $a_{i, j}$ coins in it. Initially, both Alice and Bob are standing in a cell $(1, 1)$. They are going to perform a sequence of moves to reach a cell $(2, m)$. The possible moves are: - Move right — from some cell $(x, y)$ to $(x, y + 1)$; - Move down — from some cell $(x, y)$ to $(x + 1, y)$. First, Alice makes \textbf{all her moves} until she reaches $(2, m)$. She collects the coins in all cells she visit (including the starting cell). When Alice finishes, Bob starts his journey. He also performs the moves to reach $(2, m)$ and collects the coins in all cells that he visited, \textbf{but Alice didn't}. The score of the game is the total number of coins Bob collects. Alice wants to minimize the score. Bob wants to maximize the score. What will the score of the game be if both players play optimally?
First, observe that each of the players has only $m$ options for their path - which column to go down in. Let's consider a Bob's response to a strategy chosen by Alice. The easiest way to approach that is to look at the picture of the Alice's path. The path clearly separates the field into two independent pieces - suffix of the first row and the prefix of the second row. Bob can't grab the coins from both of them at once. However, he can grab either of them fully. So the optimal path for him will be one of these two options. You can precalculate some prefix sums and become able to get the Bob's score given the Alice's path. Alice has $m$ possibly paths, so you can iterate over them and choose the minimum answer. However, prefix sums are not required, since you can quickly recalculate both needed sums while iterating over the Alice's column to go down in. Overall complexity: $O(m)$ per testcase.
[ "brute force", "constructive algorithms", "dp", "implementation" ]
1,300
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 2e9 + 10; int main() { int t; scanf("%d", &t); forn(_, t){ int n; scanf("%d", &n); vector<vector<int>> a(2, vector<int>(n)); forn(i, 2) forn(j, n) scanf("%d", &a[i][j]); int ans = INF; int sum1 = 0, sum2 = 0; forn(i, n) sum1 += a[0][i]; forn(i, n){ sum1 -= a[0][i]; ans = min(ans, max(sum1, sum2)); sum2 += a[1][i]; } printf("%d\n", ans); } }
1555
D
Say No to Palindromes
Let's call the string \textbf{beautiful} if it does not contain a substring of length at least $2$, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not. Let's define \textbf{cost} of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first $3$ letters of the Latin alphabet (in lowercase). You are given a string $s$ of length $n$, each character of the string is one of the first $3$ letters of the Latin alphabet (in lowercase). You have to answer $m$ queries — calculate the cost of the substring of the string $s$ from $l_i$-th to $r_i$-th position, inclusive.
Note that in the beautiful string $s_i \neq s_{i-1}$ (because it is a palindrome of length $2$) and $s_i \neq s_{i-2}$ (because it is a palindrome of length $3$). This means $s_i = s_{i-3}$, i.e. a beautiful string has the form abcabcabc..., up to the permutation of the letters a, b and c. For each permutation of the letters a, b and c, we will construct a string $t$, of the form abcabcabc... of length $n$. Let's define an array $a$ of length $n$ as follows: $a_i = 0$ if $s_i = t_i$ (i.e. the character at the $i$-th position does not need to be changed) and $a_i = 1$ otherwise. Let's build an array $pr$ of prefix sums of the array $a$. Now you can process a query of the number of positions that need to be replaced for the current line $t$ in $O(1)$.
[ "brute force", "constructive algorithms", "dp", "strings" ]
1,600
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; string s; cin >> s; vector<vector<int>> pr(6, vector<int>(n + 1)); string t = "abc"; int cur = 0; do { for (int i = 0; i < n; ++i) pr[cur][i + 1] = pr[cur][i] + (s[i] != t[i % 3]); ++cur; } while (next_permutation(t.begin(), t.end())); while (m--) { int l, r; cin >> l >> r; int ans = n; for (int i = 0; i < 6; ++i) ans = min(ans, pr[i][r] - pr[i][l - 1]); cout << ans << "\n"; } }
1555
E
Boring Segments
You are given $n$ segments on a number line, numbered from $1$ to $n$. The $i$-th segments covers all integer points from $l_i$ to $r_i$ and has a value $w_i$. You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a selected segment that covers both of them. A subset is good if it's possible to reach point $m$ starting from point $1$ in arbitrary number of moves. The cost of the subset is the difference between the maximum and the minimum values of segments in it. Find the minimum cost of a good subset. In every test there exists at least one good subset.
Take a look at the condition for a good subset. The major implication it makes is that every point (even non-integer) of the segment $[1; m]$ should be covered by at least one segment. If some point isn't, then there is no way to jump across the gap it produces. At the same time, this condition is enough to have a path, since for every half-integer point ($0.5$, $1.5$ and so on) there exists a segment that covers it. So you can take that segment to go from $1$ to $2$, then from $2$ to $3$ and so on. Thus, we are asked to select a subset of segments that covers the entire segment $[1; m]$ in its union. The main prerequisite to the following solution is knowing the way to maintain the union of segments. For now, I can tell you that there is a data structure that allows you to add a segment, remove a segment and query the length of the current union. Let's continue with making some observations on the cost function. If you fix the minimum and the maximum value, you are free to select all segments that have their value in-between. That allows us to transition from selecting a subset of segment to an interval, if you sort the segments by their weight. If you fix only minimum, then the required maximum should be as small as possible. However, if some value suffices as a maximum, then any value greater than it also suffices (since it only adds extra segments to the subset). This makes the function on the maximum monotonous. So the binary search applicable. You could iterate over the minimum and binary search the maximum. However, it's not too clear how to make a check function. You would need to find a union of some interval of segments quickly. I don't really know a way to do that, so let's try something different. Instead, let's forget about binary search and try to reach a two pointers solution. Let $f(x)$ be the smallest possible maximum, given the fixed minimum is $x$. We want $f(x + 1)$ to be greater than or equal than $f(x)$ for two pointers to be applicable. That condition indeed holds. Imagine if $f(x + 1)$ is smaller than $f(x)$. So there exists some optimal subset for $x + 1$. Add all segments with weight $x$ to that subset. That brings the minimum to $x$. However, it doesn't change the maximum, so $f(x)$ is at least equal to $f(x + 1)$, what contradicts the assumption. Finally, the solution comes up to the following. Iterate over the minimum value $x$, while maintaining $f(x)$. When going from $x$ to $x + 1$, keep increasing the value of $f$ until the union of the segments is exactly $m$. Going from $x$ to $x+1$ and increasing the value of $f$ is actually removing some segments and adding some segments to the data structure. The data structure that helps us with that is a segment tree. The $i$-th leaf of the tree holds the number of segments that cover the interval $(i; i + 1)$. Add/remove segment makes it add/subtract on a range. The union is full if the there are no intervals that are covered by zero segments. Thus, let's store the minimum of the subtree in every intermediate node. If the minimum on the tree is above zero, then the current subset is good. Instead of applying two pointers on the values of the segments, let's apply them on the sorted segments themselves. That makes moving the pointer exactly one update to the segtree. Overall complexity: $O(n \log n + n \log m)$.
[ "data structures", "sortings", "trees", "two pointers" ]
2,100
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int INF = 1e9; vector<int> t, ps; void push(int v){ if (v * 2 + 1 < int(ps.size())){ ps[v * 2] += ps[v]; ps[v * 2 + 1] += ps[v]; } t[v] += ps[v]; ps[v] = 0; } void upd(int v, int l, int r, int L, int R, int val){ push(v); if (L >= R) return; if (l == L && r == R){ ps[v] += val; push(v); return; } int m = (l + r) / 2; upd(v * 2, l, m, L, min(m, R), val); upd(v * 2 + 1, m, r, max(m, L), R, val); t[v] = min(t[v * 2], t[v * 2 + 1]); } int get(){ return t[1] + ps[1]; } struct seg{ int l, r, w; }; int main() { int n, m; scanf("%d%d", &n, &m); vector<seg> a(n); forn(i, n){ scanf("%d%d%d", &a[i].l, &a[i].r, &a[i].w); --a[i].l, --a[i].r; } --m; sort(a.begin(), a.end(), [](const seg &a, const seg &b){ return a.w < b.w; }); t.resize(4 * m); ps.resize(4 * m); int ans = INF; int j = 0; forn(i, n){ while (j < n && get() == 0){ upd(1, 0, m, a[j].l, a[j].r, 1); ++j; } if (get() == 0){ break; } ans = min(ans, a[j - 1].w - a[i].w); upd(1, 0, m, a[i].l, a[i].r, -1); } printf("%d\n", ans); return 0; }
1555
F
Good Graph
You have an undirected graph consisting of $n$ vertices with weighted edges. A simple cycle is a cycle of the graph without repeated vertices. Let the weight of the cycle be the XOR of weights of edges it consists of. Let's say the graph is good if all its simple cycles have weight $1$. A graph is bad if it's not good. Initially, the graph is empty. Then $q$ queries follow. Each query has the next type: - $u$ $v$ $x$ — add edge between vertices $u$ and $v$ of weight $x$ if it doesn't make the graph bad. For each query print, was the edge added or not.
Firstly, let's prove that a good graph has one important property: any two of its simple cycles intersect by at most one vertex, i. e. there is no edge that belongs to more than one simple cycle (cactus definition, yeah). Let's prove it by showing that if two simple cycles of weight $k > 0$ intersects (by edges) then they will induce a simple cycle of weight $\neq k$. There are two cases: if cycles intersect by a single path, then we can create a new cycle by merging parts of cycles excluding the intersecting path - it will be simple and will have weight $k \oplus k = 0 \neq k$; if cycles intersect by more than one path, we can do the next transformation: suppose the common paths are $u_1 - v_1$, $u_2 - v_2$, $\dots$, and they are ordered in the way how they lie on the first cycle. Let's create a third cycle using two paths from $v_1$ to $u_2$: from the first cycle and from the second cycle. It's easy to see that the third cycle is simple, and more over it has only one common path with the second cycle. So, it's either the third cycle has weight not equal to $k$ or the case $1$. Okay, let's analyze the edges we try to add. Let's divide all edges in two types: tree edges and all other edges (we will name them cycle edges). Let's name an edge as a tree edge if it connects two different components at a moment when we are trying to add it in the graph. It's obvious that we will add all tree edges in the graph, since they can't make it bad (since they don't induce new cycles). But there is a more interesting observation: when we try to add a cycle edge $(u, v)$, it should induce an only one simple cycle where all other edges are tree edges and these tree edges can't be used in any other cycle. It induces at least one "all-tree-edge" cycle, since $u$ and $v$ are already connected. It can't induce more than one "all-tree-edge" cycle, since it contradicts with tree edge definition, and if it induces a cycle with some other cycle edge, then we can replace that cycle edge with its own tree-edge path: our cycle will become "all-tree-edge" cycle, but it will use already used tree edges. In other words, it's enough to consider only one "all-tree-edge" cycle induced by any cycle edge. The final trick is to calculate the answer in two steps: at the first step, we will find only tree edges (using DSU) that will form a spanning forest in our graph. The second step is for each cycle edge $(u, v)$ to calculate the $\operatorname{XOR}$ $X$ on a path between $u$ and $v$ in our spanning forest, check that $X \oplus \text{edge_weight} = 1$ and check that none of edges on the path from $u$ to $v$ are used in other cycle. Calculating $X$ is easy: if we precalculate for each vertex $v$ the $\operatorname{XOR}$ on path from $v$ to root $\mathit{xr}[v]$ then $X = \mathit{xr}[u] \oplus \mathit{xr}[v]$. Checking that none of the edges are used on the path from $u$ to $v$ is a bit tricky: if we mark an edge by adding $1$ to it, then we should be able to take a sum on path and add on path. There are structures that are capable of it (like HLD and other), but let's look closely. Note that we mark each tree edge at most once, so we can manually add $1$ to each edge, and only asking sum on path should be fast. In other words, we need a data structure (DS) that can add value at edge and take the sum on path - and such DS is a Fenwick tree (BIT) built on Euler tour of tree: it can add value at edge and ask a sum on path from $v$ to root. So we need to find LCA as well, since sum of path $(u, v)$ is equal to $sum(u) + sum(v) - 2 \cdot sum(LCA(u, v))$. As a result, complexity is $O((n + m) \log(n))$ with quite a low constant from LCA and BIT.
[ "data structures", "dsu", "graphs", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define x first #define y second typedef long long li; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out << "(" << p.x << ", " << p.y << ")"; } template<class A> ostream& operator <<(ostream& out, const vector<A> &v) { fore(i, 0, sz(v)) { if(i) out << " "; out << v[i]; } return out; } const int INF = int(1e9); const li INF64 = li(1e18); int n, q; vector< array<int, 3> > es; inline bool read() { if(!(cin >> n >> q)) return false; es.resize(q); fore (i, 0, q) { cin >> es[i][0] >> es[i][1] >> es[i][2]; es[i][0]--; es[i][1]--; } return true; } vector< vector<pt> > g; const int LOG = 19; vector<int> up[LOG]; vector<int> tin, tout; vector<int> xr; int T = 0; void dfs(int v, int p, int curXor) { tin[v] = T++; xr[v] = curXor; up[0][v] = p; fore (pw, 1, LOG) up[pw][v] = up[pw - 1][up[pw - 1][v]]; for (auto [to, w] : g[v]) { if (to == p) continue; dfs(to, v, curXor ^ w); } tout[v] = T; } void buildLCA() { fore (pw, 0, LOG) up[pw].resize(n); tin.assign(n, -1); tout.assign(n, -1); xr.assign(n, 0); T = 0; fore (v, 0, n) { if (tin[v] != -1) continue; dfs(v, v, 0); } } int isPar(int p, int v) { return tin[p] <= tin[v] && tout[v] <= tout[p]; } int lca(int u, int v) { if (isPar(u, v)) return u; if (isPar(v, u)) return v; for (int pw = LOG - 1; pw >= 0; pw--) { if (!isPar(up[pw][v], u)) v = up[pw][v]; } return up[0][v]; } vector<int> par, rk; void init(int n) { par.assign(n, 0); iota(par.begin(), par.end(), 0); rk.assign(n, 1); } int top(int v) { if (par[v] != v) return par[v] = top(par[v]); return v; } bool unite(int u, int v) { u = top(u); v = top(v); if (u == v) return false; if (rk[u] < rk[v]) swap(u, v); par[v] = u; rk[u] += rk[v]; return true; } vector<int> F; void inc(int pos, int val) { for(; pos < sz(F); pos |= pos + 1) F[pos] += val; } int sum(int pos) { int ans = 0; for(; pos >= 0; pos = (pos & (pos + 1)) - 1) ans += F[pos]; return ans; } void addOnPath(int v, int l) { while (v != l) { inc(tin[v], 1); inc(tout[v], -1); v = up[0][v]; } } inline void solve() { init(n); g.resize(n); vector<int> ans(q, -1); fore (i, 0, q) { int u = es[i][0]; int v = es[i][1]; int x = es[i][2]; if (unite(u, v)) { ans[i] = 1; g[u].emplace_back(v, x); g[v].emplace_back(u, x); } } buildLCA(); F.assign(2 * n + 5, 0); fore (i, 0, q) { if (ans[i] != -1) continue; ans[i] = 0; int u = es[i][0]; int v = es[i][1]; int x = es[i][2]; int xorPath = xr[u] ^ xr[v]; if ((xorPath ^ x) != 1) continue; int l = lca(u, v); int usedOnPath = sum(tin[u]) + sum(tin[v]) - 2 * sum(tin[l]); if (usedOnPath > 0) continue; ans[i] = 1; addOnPath(u, l); addOnPath(v, l); } for (int res : ans) cout << (res ? "YES" : "NO") << '\n'; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1556
A
A Variety of Operations
William has two numbers $a$ and $b$ initially both equal to \textbf{zero}. William mastered performing three different operations with them quickly. Before performing each operation some positive integer $k$ is picked, which is then used to perform one of the following operations: (note, that for each operation you can choose a \textbf{new} positive integer $k$) - add number $k$ to both $a$ and $b$, or - add number $k$ to $a$ and subtract $k$ from $b$, or - add number $k$ to $b$ and subtract $k$ from $a$. Note that after performing operations, numbers $a$ and $b$ may become negative as well. William wants to find out the minimal number of operations he would have to perform to make $a$ equal to his favorite number $c$ and $b$ equal to his second favorite number $d$.
Note, that after any of the operations, the parity of the expression $a - b$ does not change, so if the initial difference of the pair $c - d$ is odd, then it is impossible to get this pair. Now, note that if we can get a $(c, d)$ pair, then it can be obtained in no more than $2$ operations. To do this, consider three cases: $c = d = 0$ - in this case answer is $0$, because initial pair is $(0, 0)$. $c = d$ - in this case answer is $1$. For this, it is enough for us to use the operation of the first type with $k = c = d$. $c \neq d$ - in this case answer is $2$. For this we can use the operations of the first type with $k = \frac{c + d}{2}$. After that, it is enough for us to use either an operation of the second type with $k = c - \frac{|c - d|}{2}$ if $c > d$, or an operation of the third type with $k = d - \frac{|c - d|}{2}$ otherwise.
[ "math" ]
800
null
1556
B
Take Your Places!
William has an array of $n$ integers $a_1, a_2, \dots, a_n$. In one move he can swap two neighboring items. Two items $a_i$ and $a_j$ are considered neighboring if the condition $|i - j| = 1$ is satisfied. William wants you to calculate the minimal number of swaps he would need to perform to make it so that the array does not contain two neighboring items with the same parity.
Note that if the condition $|odd - even| > 1$ is satisfied, where $odd$ is the number of odd numbers, and $even$ is the number of even numbers, then it is impossible to get the required array. Now, note that it is enough to consider two cases and choose the minimum answer from these cases: The first element will be an odd number. The first element will be an even number. Now we will describe the general solution. Suppose we are now at position $i$ and we must put an element with parity $cur$ on it. Then, we need to find the first element with opposite parity $a_j$, where $i \le j$. After we have done this, it is enough to swap $a_i$ and $a_j$ and add $j - i$ to the answer. To quickly search for a suitable element, it is enough to use two pointers, which will point to the current available even and odd numbers.
[ "implementation" ]
1,300
null
1556
C
Compressed Bracket Sequence
William has a favorite bracket sequence. Since his favorite sequence is quite big he provided it to you as a sequence of positive integers $c_1, c_2, \dots, c_n$ where $c_i$ is the number of consecutive brackets "(" if $i$ is an odd number or the number of consecutive brackets ")" if $i$ is an even number. For example for a bracket sequence "((())()))" a corresponding sequence of numbers is $[3, 2, 1, 3]$. You need to find the total number of continuous subsequences (subsegments) $[l, r]$ ($l \le r$) of the original bracket sequence, which are regular bracket sequences. A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not.
Let's examine a compressed sequence and fix two indexes $l < r, l$ % $2 = 0, r$ % $2 = 1$. Note that it makes no sense to examine other indexes because the correct bracket sequence always begins with the opening bracket and ends with the closing one. Next, we can calculate the minimum bracket balance on the segment from $l + 1$ to $r - 1$. The minimum bracket balance is the minimum number of opening brackets that we must put before the sequence of brackets in order for it to be regular, provided that we can put any number of closing brackets at the end. Let's denote this number as $minBalance$, and denote the sum of $-c_{l + 1} + c_{l + 2} - c_{l + 2} + \dots$ as $balance$. The next observation is that if we fix the number of opening brackets taken from $c_l$, then we can count the number of brackets that we should take from $c_r$. Using these observations we can calculate the answer for $l..r$ using the following formula: $min(c_l, c_r-balance) - max(1, minBalance) + 1$. Note that this problem could also be solved in $O(n)$, but this was not required.
[ "brute force", "implementation" ]
1,800
null
1556
D
Take a Guess
\textbf{This is an interactive task} William has a certain sequence of integers $a_1, a_2, \dots, a_n$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $2 \cdot n$ of the following questions: - What is the result of a bitwise AND of two items with indices $i$ and $j$ ($i \neq j$) - What is the result of a bitwise OR of two items with indices $i$ and $j$ ($i \neq j$) You can ask William these questions and you need to find the $k$-th smallest number of the sequence. Formally the $k$-th smallest number is equal to the number at the $k$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $[5, 3, 3, 10, 1]$ $4$th smallest number is equal to $5$, and $2$nd and $3$rd are $3$.
To solve this problem, we can use the fact that $a+b=(a$ or $b) + (a$ and $b)$. Then we can determine the first $3$ numbers in $6$ operations using the sums $a_{01} = a_0 + a_1$, $a_{12} = a_1 + a_2$ and $a_{02} = a_0 + a_2$. Using the formula $a_1 = \frac{a_{01}+a_{12}-a_{02}}{2}$, $a_0 = a_{01} - a_1$ and $a_2 = a_{12} - a_1$. Knowing one of the numbers, it is quite simple to find all the other numbers using the same principle by using $2 \cdot n$ operations. Then we just need to sort the resulting array and output the k-th element.
[ "bitmasks", "constructive algorithms", "interactive", "math" ]
1,800
null
1556
E
Equilibrium
William has two arrays $a$ and $b$, each consisting of $n$ items. For some segments $l..r$ of these arrays William wants to know if it is possible to equalize the values of items in these segments using a balancing operation. Formally, the values are equalized if for each $i$ from $l$ to $r$ holds $a_i = b_i$. To perform a balancing operation an even number of indices must be selected, such that $l \le pos_1 < pos_2 < \dots < pos_k \le r$. Next the items of \textbf{array a} at positions $pos_1, pos_3, pos_5, \dots$ get incremented by one and the items of \textbf{array b} at positions $pos_2, pos_4, pos_6, \dots$ get incremented by one. William wants to find out if it is possible to equalize the values of elements in two arrays for each segment using some number of balancing operations, and what is the minimal number of operations required for that. Note that for each segment the operations are performed independently.
The first step to solving this problem is to create some array $C$, where $c_i = a_i - b_i$. Then we can select some elements from this array C and do operations $+1, -1, +1, -1 \dots$ for these elements for the corresponding elements. And the challenge is to make this array consist of zeros. It is argued that this can always be done if the following conditions are met: 1. no prefix with positive-sum and no suffix with negative 2. the sum of all elements is zero Let us prove the sufficiency of these conditions: we can find the smallest prefix with a negative sum and the smallest suffix with a positive one, do the operation with one $+1$ and one $-1$, and reduce the sum of the absolute values of the elements. Assertion: the minimum number of operations is the maximum modulus of the sum on the subsegment. This is a lower estimate, since on any segment, the sum changes by at most 1. Let us prove the upper bound by presenting a constructive solution. Let now the array of differences $c_1, c_2, \dots, c_n$, and the maximum modulus of the sum is $M$. Let's do the following: find the first negative number, there is $+1$, the first positive number after it, there is $-1$, and so on. Statement: the last operation will be $-1$, because otherwise, our last nonzero number is negative, which means it is a negative prefix. We can reformulate greed as follows: throw out all zeros, put $+1$ in the first element for each negative segment, and $-1$ for each positive one in the first element. Let us prove that on any subsegment with the sum $M$, it has decreased in absolute value. Without loss of generality, consider the segment $[l, r]$ with a positive-sum [the prefix corresponds to the suffix]. Consider again the array obtained by throwing out zeros. It is clear that our segment $[l, r]$ did not cut any segment of negative/positive ones, otherwise, it has no maximum sum. It is also clear that the first and last segments in $[l, r]$ are positive, so we have bet $-1$ more than $+1$.
[ "data structures", "dp", "greedy" ]
2,200
null
1556
F
Sports Betting
William is not only interested in trading but also in betting on sports matches. $n$ teams participate in each match. Each team is characterized by strength $a_i$. Each two teams $i < j$ play with each other exactly once. Team $i$ wins with probability $\frac{a_i}{a_i + a_j}$ and team $j$ wins with probability $\frac{a_j}{a_i + a_j}$. The team is called a winner if it directly or indirectly defeated all other teams. Team $a$ defeated (directly or indirectly) team $b$ if there is a sequence of teams $c_1$, $c_2$, ... $c_k$ such that $c_1 = a$, $c_k = b$ and team $c_i$ defeated team $c_{i + 1}$ for all $i$ from $1$ to $k - 1$. Note that it is possible that team $a$ defeated team $b$ and in the same time team $b$ defeated team $a$. William wants you to find the expected value of the number of winners.
Let $ALL$ be all teams, and $F(winners)$ be the probability that a set of $winners$ teams are winners, and the rest of $ALL \setminus winners$ teams are not. Then the answer will be the following value: $\sum_{winners \neq \varnothing, winners \subseteq ALL} F(winners) \cdot |winners|$ Let's define extra value: $P(winners)$ - the probability that all teams from the set $winners$ are reachable from each other, that is, they form a cycle. Then $F$ is calculated as follows: $F(winners) = P(winners) \cdot G(winners, ALL \setminus winners)$. This is explained as follows: the probability that the set $winners$ will be the set of winners is equal to the probability that the set $winners$ forms a cycle and there is no edge from the set $ALL \setminus winners$ to $winners$. Where $G(X, Y)$ denotes the probability that all teams from the set $X$ defeat all teams from the set $Y$ directly. More formally speaking, the probability that for every $x$ in $X$, and for every $y$ in $Y$, there is an edge from $x$ to $y$. It remains to learn how to count $P(winners)$. It is easy to see that this can be done using the inclusion-exclusion principle: $P(winners) = 1 - \sum_{sub \subset winners, sub \neq winners} P(sub) \cdot G(sub, winners \setminus sub)$ The formula is explained as follows: we need to know the probability that all teams from the set $winners$ are reachable to each other, initially we set this probability equal to $1$, then subtract all options when only some subset $sub$ of the set $winners$ is reachable to itself. $G(X, Y)$ is calculated as follows: $G(X, Y) = \prod_{x \in X, y \in Y} \frac{a_x}{a_x + a_y}$ Writing these formulas into the code in the simplest way, you can get a solution with asymptotics $O(3^{N} \cdot N^2)$. Since here $O(3^N)$ pairs $(winners, sub)$ exist, where $winners$ is the set of winners and $sub$ is its subset in the inclusion-exclusion formula. Also, for each such pair, you will have to calculate the value of $G(sub, winners \setminus sub)$ in $O(N^2)$. But it is possible to calculate $G(X, Y)$ faster. For example, you can notice that $G(X, Y) = \prod_ {x \in X} H(x, Y)$, where $H(x, Y)$ is the probability that the command $x$ defeated all teams from the set $Y$ directly. $H$ can be pre-calculated in advance for $O(2^N \cdot N)$, which will allow us to calculate $G(X, Y)$ in $O(N)$ instead of $O(N^2)$. In a similar way, you can learn how to calculate $G(X, Y)$ in $O(1)$, if you pre-calculate the following four values: $G_{left, left}(X, Y)$, $G_{left, right}(X, Y)$, $G_{right, left}(X, Y)$, $G_{right, right}(X, Y)$. Where $left, right$ is an arbitrary division of teams into two equal (or almost equal) sets, so that $||left| - |right|| \leq 1$ is satisfied. Where $G_{side_{from}, side_{to}}(X, Y) = G(X, Y)$, only for subsets such that $X \subseteq side_{from}, Y \subseteq side_{to}$. As a result: $G(X, Y) = \prod_{side_{from} \in \{ left, right \} } \prod_{side_{to} \in \{ left, right \} } G_{side_{from}, side_{to}}(X \cap side_{from}, Y \cap side_{to})$ Each of $G_{side_{from}, side_{to}}$ can be pre-calculated in $O(2^N \cdot N)$. Final asymptotics $O(3^N)$.
[ "bitmasks", "combinatorics", "dp", "graphs", "math", "probabilities" ]
2,500
null
1556
G
Gates to Another World
As mentioned previously William really likes playing video games. In one of his favorite games, the player character is in a universe where every planet is designated by a binary number from $0$ to $2^n - 1$. On each planet, there are gates that allow the player to move from planet $i$ to planet $j$ if the binary representations of $i$ and $j$ differ in exactly one bit. William wants to test you and see how you can handle processing the following queries in this game universe: - Destroy planets with numbers from $l$ to $r$ inclusively. These planets cannot be moved to anymore. - Figure out if it is possible to reach planet $b$ from planet $a$ using some number of planetary gates. It is guaranteed that the planets $a$ and $b$ are not destroyed.
Let's change the formulation of the problem: we will execute queries in reverse order, and assign a lifetime to each segment of blocked vertices. Lifetime - until what moment the segment is blocked. Note, if we look through the requests in reverse order, then for each segment it is possible to determine the moment of time after which the vertices from this segment cease to be blocked. Thus, the problem looks like this: given a graph that is an $n$-dimensional hypercube (each vertex has $n$ edges to adjacent vertices that differ from it by only one coordinate), and there are $m$ blocked vertex segments $[l_i \dots r_i]$ that live up to the time $t_i$. Consider the following fact: If we take an $n$-dimensional hypercube and sequences of vertices $0, 1, \dots, 2^{n-1} - 1$ and $2^{n-1}, 2^{n-1} + 1, \dots, 2^{n} - 1$, then the numbers in the corresponding positions from these two sequences are neighbours to each other, since they differ only in the most significant bit, that is, in the $2^{n-1}$ bit. For a better understanding, let's depict this for $n = 4$: $0000 - 1000$ $0001 - 1001$ $0010 - 1010$ $0011 - 1011$ $0100 - 1100$ $0101 - 1101$ $0110 - 1110$ $0111 - 1111$ Here $a - b$ denotes that $a$ is a neighbour of $b$, and $a$ is present in the first sequence, and $b$ in the second. For simplicity, we will only prohibit movement between a blocked vertex and an unblocked one. Let's learn how to get a "compressed" graph, each vertex of which would represent a connected subset of the vertices of the hypercube. Also, this set, which represents a vertex, is a set of consecutive vertices, that is, it is a segment. On each edge of this graph is written the time - when this edge begins to exist. Time makes sense, since an edge can be drawn between a vertex that represents a set of blocked vertices and a vertex that represents a set of unblocked vertices. And the time on this edge there will be a moment in time when the set of vertices is unblocked. Recall that now we are solving a problem in which the vertices are blocked until a certain moment in time. The answer to the reachability request is the reachability request for a given "compressed" graph. It is only necessary to correctly determine the reachability of which two vertices of the "compressed" graph we are interested in. Let's learn how to recursively build a given compressed graph. Input data for the construction of this graph are: $n$ - the dimension of the hypercube, $S = \{ (l_i, r_i) \}$ - the set of blocked vertices. If there are no segments worth blocking, then the compressed graph is one vertex, which is responsible for the connected set $\{0, 1, 2, \dots, 2^{n} - 1 \}$ of hypercube vertices. If there is one segment $(l_i, r_i) = (0, 2^{n} - 1)$, then the compressed graph is one vertex representing all vertices, and they are all blocked. Otherwise, we can divide the hypercube into two parts: by the most significant bit. That is, into two hypercubes of dimensions $2^{n-1}$. And each segment $l_i, r_i$ can go further, as input, either into two hypercubes, or into one of them. Having received compressed graphs from each of the two hypercubes, we can match the adjacent vertices of these hypercubes, as illustrated above. It is not difficult to combine two such graphs, since each vertex of the graph describes the set of vertices of the hypercube, and this set is a segment, therefore, if we have the vertices of the first and second graphs, $V_1$ and $V_2$, respectively, in ascending order of the segments for which they answer, then it is possible to combine these two graphs in $O(|V_1| + |V_2|)$ time, and create no more than $O(|V_1| + |V_2|)$ edges and obtain a new graph of size $|V_1| + |V_2|$. In total, the resulting graph will have a size of $n \times m$, and the final asymptotics will be $O(n^2 \times m \times ACK)$, where $ACK$ is the cost of the operation in the DSU. The DSU is needed to pass queries in reverse order and connect the edges at the right times when the edges begin to exist. The asymptotics is as follows, since each vertex of the graph may go through all $n$ layers of recursion (as you may have noticed, the solution procedure resembles divide and conquer) and at the same time create a new edge in each layer. And the graph has such a size, since each blocked segment in this procedure can be split into $n$ segments. For a better understanding, see the author's solution.
[ "bitmasks", "data structures", "dsu", "two pointers" ]
3,300
null
1556
H
DIY Tree
William really likes puzzle kits. For one of his birthdays, his friends gifted him a complete undirected edge-weighted graph consisting of $n$ vertices. He wants to build a spanning tree of this graph, such that for the first $k$ vertices the following condition is satisfied: the degree of a vertex with index $i$ does not exceed $d_i$. Vertices from $k + 1$ to $n$ may have any degree. William wants you to find the minimum weight of a spanning tree that satisfies all the conditions. A spanning tree is a subset of edges of a graph that forms a tree on all $n$ vertices of the graph. The weight of a spanning tree is defined as the sum of weights of all the edges included in a spanning tree.
Let's call the first $k$ vertices special. First of all, let's note that the number of different forests on $5$ vertices is at most $300$. It means that we can try all of them, one by one, as the set of all edges of the answer with both endpoints being the special vertices. Let $T$ be the set of chosen edges with both endpoints being the special vertices. With fixed $T$, only edges with zero or one endpoint at special vertices are left. From now on, we will only consider subsets of these edges. We will introduce two matroids: Matroid $A$ is defined as follows: A set of edges $E$ is independent for matroid $A$, if the set $E \cup T$ has no cycles. $A$ is a matroid, because: Deleting edges produces no cycles, so if $F$ is a superset of $E$ and $F$ is independent, then $E$ is also independent. If $|F| > |E|$, $F$ is independent and $E$ is independent, then from the graphic matroid there should be an edge in $T \cup F$ that connects connected components in $T \cup E$. This edge can't be from $T$, so there is an element $x \in F$, s. t. $E \cup \{x\}$ is also independent. A set of edges $E$ is independent for matroid $A$, if the set $E \cup T$ has no cycles. $A$ is a matroid, because: Deleting edges produces no cycles, so if $F$ is a superset of $E$ and $F$ is independent, then $E$ is also independent. If $|F| > |E|$, $F$ is independent and $E$ is independent, then from the graphic matroid there should be an edge in $T \cup F$ that connects connected components in $T \cup E$. This edge can't be from $T$, so there is an element $x \in F$, s. t. $E \cup \{x\}$ is also independent. Matroid $B$ is defined as follows. A set of edges $E$ is independent for matroid $B$, if in the set $E \cup T$ degrees of vertices $[1,2,\ldots,k]$ don't exceed $[d_1,d_2,\ldots,d_k]$, respectively. $B$ is a matroid, because: Deleting edges decreases degrees, so if $F$ is a superset of $E$ and $F$ is independent, then $E$ is also independent. If $|F| > |E|$, $F$ is independent and $E$ is independent, then one of the following statements is true. Either there is an edge with zero endpoints at special vertices in $F \setminus E$, and we can add it to $E$ preserving independence. Or there is some vertex $v \in \{1,2,\ldots,k\}$ that has larger degree in $F$ than in $E$, and we can take one of adjacent edges that are present in $F \setminus E$ and add it to $E$. Thus, there is an element $x \in F$, s. t. $E \cup \{x\}$ is also independent. Let's find the minimum weight base $E$ in the intersection of matroids $A$ and $B$. If it has enough edges, we can relax the answer with the total weight of edges in $E \cup T$. Also note that we are only interested in edges from $\{1, \ldots, k\} \times \{k+1,\ldots,n\}$ and in the MST of edges from $\{k+1,\ldots,n\}$, so we only have $O(nk)$ edges we need to consider. Total complexity is $O(\mathrm{exp}(k) \cdot \mathrm{poly}(n)))$, and it will easily fit into TL if your solution is efficient enough. A set of edges $E$ is independent for matroid $B$, if in the set $E \cup T$ degrees of vertices $[1,2,\ldots,k]$ don't exceed $[d_1,d_2,\ldots,d_k]$, respectively. $B$ is a matroid, because: Deleting edges decreases degrees, so if $F$ is a superset of $E$ and $F$ is independent, then $E$ is also independent. If $|F| > |E|$, $F$ is independent and $E$ is independent, then one of the following statements is true. Either there is an edge with zero endpoints at special vertices in $F \setminus E$, and we can add it to $E$ preserving independence. Or there is some vertex $v \in \{1,2,\ldots,k\}$ that has larger degree in $F$ than in $E$, and we can take one of adjacent edges that are present in $F \setminus E$ and add it to $E$. Thus, there is an element $x \in F$, s. t. $E \cup \{x\}$ is also independent. Let's find the minimum weight base $E$ in the intersection of matroids $A$ and $B$. If it has enough edges, we can relax the answer with the total weight of edges in $E \cup T$. Also note that we are only interested in edges from $\{1, \ldots, k\} \times \{k+1,\ldots,n\}$ and in the MST of edges from $\{k+1,\ldots,n\}$, so we only have $O(nk)$ edges we need to consider. Total complexity is $O(\mathrm{exp}(k) \cdot \mathrm{poly}(n)))$, and it will easily fit into TL if your solution is efficient enough.
[ "graphs", "greedy", "math", "probabilities" ]
3,300
null
1557
A
Ezzat and Two Subsequences
Ezzat has an array of $n$ integers \textbf{(maybe negative)}. He wants to split it into two \textbf{non-empty} subsequences $a$ and $b$, such that every element from the array belongs to exactly one subsequence, and the value of $f(a) + f(b)$ is the maximum possible value, where $f(x)$ is the average of the subsequence $x$. A sequence $x$ is a subsequence of a sequence $y$ if $x$ can be obtained from $y$ by deletion of several (possibly, zero or all) elements. The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence. For example, the average of $[1,5,6]$ is $(1+5+6)/3 = 12/3 = 4$, so $f([1,5,6]) = 4$.
The average of a group of numbers always has a value between the minimum and maximum numbers in that group. Since the average of a group of numbers always has a value between the minimum and maximum numbers in that group, it can be proved that the best approach to obtain the maximum sum of averages of two subsequences is to put the maximum number alone into one subsequence, and the rest of the numbers into the other subsequence. A proof by contradiction follows. Assume a sorted array, so $a_1 \le a_2 \le \ldots \le a_n$. Assume that there exists a bigger answer if you take the two greatest numbers (instead of only one) in one subsequence. Therefore, we need to prove that: $\sum_{i=1}^{n-1} a_i / (n - 1) + a_n < \sum_{i=1}^{n-2} a_i / (n - 2) + (a_{n-1} + a_n) / 2$ By simplifying the inequality: $a_n < 2 / (n - 1) \cdot \sum_{i=1}^{n-2} a_i / (n - 2) + (n - 3) / (n - 1) \cdot a_{n-1}$ Assume $avg_1 = \sum_{i=1}^{n-2} a_i / (n - 2)$, so $a_1 \le avg_1 \le a_{n-2}$ as stated at the beginning of the tutorial. The inequality becomes: $a_n < (2 \cdot avg_1 + (n - 3) \cdot a_{n-1}) / (n - 1)$ The right-hand side of the inequality is also an average $avg_2$, such that $avg_1 \le avg_2 \le a_{n-1}$ (which can be further simplified to $a_1 \le avg_2 \le a_{n-1}$). This means that $a_n$ is strictly less than $avg_2$. In other words, it states that $a_n$ is strictly less than a certain number between $a_1$ and $a_{n-1}$. This is a contradiction as we stated at the beginning of the proof that the array is sorted ($a_n \ge a_{n-1} \ge \ldots \ge a_1$). Summing things up, taking at least one number along with the maximum number will never yield a greater answer.
[ "brute force", "math", "sortings" ]
800
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> using namespace std; void run() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #else #endif } int main() { run(); cout << fixed << setprecision(10); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; i++) cin >> v[i]; int mx = v[0]; long long sum = 0; for (int i = 0; i < n; i++) { if (v[i] > mx) mx = v[i]; sum += v[i]; } cout << 1.0 * (sum - mx) / (n - 1) + mx << endl; } }
1557
B
Moamen and k-subarrays
Moamen has an array of $n$ \textbf{distinct} integers. He wants to sort that array in non-decreasing order by doing the following operations in order \textbf{exactly once}: - Split the array into exactly $k$ non-empty subarrays such that each element belongs to exactly one subarray. - Reorder these subarrays arbitrary. - Merge the subarrays in their new order. A sequence $a$ is a subarray of a sequence $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. Can you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above?
You can ignore the $k$ given in the input, try to find the minimum $k$ you need to sort the array (let call it $mnK$). If $mnK$ $\le$ $k$ then you can split some subarrays to make it equal $k$, so the answer is will be "YES". otherwise, the answer will be "NO". You need to split the array into the minimum number of subarrays such that each subarray is sorted. This problem can be solved for \textbf{at least} $k$ subarrays as it is easy to just add extra subarrays (if needed) to achieve \textbf{exactly} $k$ subarrays. To solve this problem, you need to know what are the numbers that can be grouped into the same subarray. This can be done by maintaining the sorted array along with the non-sorted array. As the numbers are distinct, we can iterate over the non-sorted array, and just add each element $a_i$ to the subarray ending in $a_{i - 1}$ IFF they follow each other in the sorted array, or start a new subarray if they do not follow each other. For example, if the (non-sorted) array is $[$ $2$, $3$, $-1$, $1$], the sorted array will be $[$ $-1$, $1$, $2$, $3$ $]$. If we iterate over the non-sorted array, we will add $2$ to a new subarray, then we will add $3$ to the same subarray as they follow each other in the sorted array. After that, we will start a new subarray at $-1$ as $-1$ and $3$ do not follow each other in the sorted array. Finally, we will add $1$ to the subarray containing $-1$. It should end up like this: { $[$ $2$, $3$ $]$, $[$ $-1$, $1$ $]$ }. Using this approach, you can get the smallest number of subarrays needed. If it is strictly greater than the given $k$, the answer is ''NO''. Otherwise, it is ''YES''.
[ "greedy", "sortings" ]
1,100
#include <bits/stdc++.h> using namespace std; #define endl "\n" void run() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #else #endif } int main() { run(); int t; cin >> t; while (t--) { int n, k; cin >> n >> k; vector<pair<int, int>> v(n); for (int i = 0; i < n; i++) { cin >> v[i].first; v[i].second = i; } sort(v.begin(), v.end()); int ans = 1; for (int i = 1; i < n; i++) if (v[i - 1].second + 1 != v[i].second) ans++; cout << (ans <= k ? "YES" : "NO") << endl; } }
1557
C
Moamen and XOR
Moamen and Ezzat are playing a game. They create an array $a$ of $n$ non-negative integers where every element is less than $2^k$. Moamen wins if $a_1 \,\&\, a_2 \,\&\, a_3 \,\&\, \ldots \,\&\, a_n \ge a_1 \oplus a_2 \oplus a_3 \oplus \ldots \oplus a_n$. Here $\&$ denotes the bitwise AND operation, and $\oplus$ denotes the bitwise XOR operation. Please calculate the number of winning for Moamen arrays $a$. As the result may be very large, print the value modulo $1\,000\,000\,007$ ($10^9 + 7$).
We don't care about the values in the array to know it's valid or not, we just need to know for every bit how many numbers have this bit on or off. Try to build the array from the most significant bit ($k-1$) to the least significant bit $0$ using dynamic programming. Can you optimize dynamic programming code with some combinatorics? From now on, I will use $And$ to describe the result of the bitwise AND operation over all the elements in the array, and $Xor$ to describe the result of the bitwise XOR operation over all the elements in the array. Let's call the array is valid if the value of $And$ $\ge$ $Xor$. We don't care about the values in the array. We just need to know, for every bit, the number of indices at which this bit is on or off. So let's build the array from the most significant bit ($k-1$) to the least significant bit ($0$) using dynamic programming and combinatorics optimization. Define an array $dp$ where $dp_{i, equal}$ $=$ the number of ways to build the array from the $i$-th bit to $0$-th bit. $equal$ is $true$ if $And$ $=$ $Xor$ in the previous bits, and $false$ if $And$ $>$ $Xor$ ($And$ $<$ $Xor$ is not a valid state). Our base case is $dp_{-1,0}$ $=$ $1$, and $dp_{-1,1}$ $=$ $1$. If $equal$ is $false$ at any moment, then you can choose any subset of indices to contain $1$ in the $i$-th bit. Therefore, $dp_{i,0}$ $=$ $2^n$ $\cdot$ $dp_{i-1,0}$. If $equal$ is $false$ at any moment, then you can choose any subset of indices to contain $1$ in the $i$-th bit. Therefore, $dp_{i,0}$ $=$ $2^n$ $\cdot$ $dp_{i-1,0}$. Now if $n$ is odd there are $2$ possible choices: You can make $i$-th bit $=$ $1$ in an even number of indices, then $And_i$ will be $0$ and $Xor_i$ will be $0$ too. You can make $i$-th bit $=$ $1$ in all indices, then $And_i$ will be $1$ and $Xor_i$ will be $1$ too. You Don't have any other valid choices. So $dp_{i,1}$ $=$ $dp_{i-1,1}$ $\cdot$ ({number of ways to choose number of indices from $n$} $+$ $1$). ($+1$ for the second choice). Now if $n$ is odd there are $2$ possible choices: You can make $i$-th bit $=$ $1$ in an even number of indices, then $And_i$ will be $0$ and $Xor_i$ will be $0$ too. You can make $i$-th bit $=$ $1$ in all indices, then $And_i$ will be $1$ and $Xor_i$ will be $1$ too. You Don't have any other valid choices. So $dp_{i,1}$ $=$ $dp_{i-1,1}$ $\cdot$ ({number of ways to choose number of indices from $n$} $+$ $1$). ($+1$ for the second choice). If $n$ is even there are $2$ possible choices: You can make $i$-th bit $=$ $1$ in an even number (less than $n$) of indices, then $And_i$ will be $0$ and $Xor_i$ will be $0$ also. You can make $i$-th bit $=$ $1$ in all indices, then $And_i$ will be $1$ and $Xor_i$ will be $0$. and now $equal$ will be $false$. You Don't have any other valid choices. So $dp_{i,1}$ $=$ $dp_{i-1,1}$ $\cdot$ (number of ways to choose number of indices from $n$ ) + $dp_{i-1,0}$. If $n$ is even there are $2$ possible choices: You can make $i$-th bit $=$ $1$ in an even number (less than $n$) of indices, then $And_i$ will be $0$ and $Xor_i$ will be $0$ also. You can make $i$-th bit $=$ $1$ in all indices, then $And_i$ will be $1$ and $Xor_i$ will be $0$. and now $equal$ will be $false$. You Don't have any other valid choices. So $dp_{i,1}$ $=$ $dp_{i-1,1}$ $\cdot$ (number of ways to choose number of indices from $n$ ) + $dp_{i-1,0}$. We can precalculate the factorial, to get $nCr$ in $\mathcal{O}(1)$, and then calculate the number of ways to choose an even number from $n$ before starting the $dp$. The total complexity will be $\mathcal{O}(k + n)$.
[ "bitmasks", "combinatorics", "dp", "math", "matrices" ]
1,700
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> #include <unordered_map> #include <unordered_set> using namespace std; #define endl "\n" #define ll long long void run() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #else #endif } const int N = 2e5 + 1; const int MOD = 1e9 + 7; ll fact[N], inv[N], invfact[N]; void factInverse() { fact[0] = inv[1] = fact[1] = invfact[0] = invfact[1] = 1; for (long long i = 2; i < N; i++) { fact[i] = (fact[i - 1] * i) % MOD; inv[i] = MOD - (inv[MOD % i] * (MOD / i) % MOD); invfact[i] = (inv[i] * invfact[i - 1]) % MOD; } } int add(int a, int b) { if ((a += b) >= MOD) a -= MOD; else if (a < 0) a += MOD; return a; } ll mul(int x, int y) { return (1LL * x * y) % MOD; } ll nCr(int n, int r) { if (r > n) return 0; return mul(mul(fact[n], invfact[r]), invfact[n - r]); } int mem[N][2], vis[N][2], test_id; int cntEven, _2pwn, n; int dp(int i, bool equal) { if (i < 0) return 1; int& rt = mem[i][equal]; if (vis[i][equal] == test_id) return rt; vis[i][equal] = test_id; if (equal == false) return rt = mul(_2pwn, dp(i - 1, 0)); if (n & 1) return rt = mul(dp(i - 1, 1), add(cntEven, 1)); return rt = add(mul(dp(i - 1, 1), cntEven), dp(i - 1, 0)); } int main() { run(); factInverse(); int t; cin >> t; while (t--) { test_id++; int k; cin >> n >> k; cntEven = 0; for (int i = 0; i < n; i += 2) cntEven = add(cntEven, nCr(n, i)); _2pwn = 1; for (int i = 0; i < n; i++) _2pwn = mul(_2pwn, 2); cout << dp(k - 1, 1) << endl; } }
1557
D
Ezzat and Grid
Moamen was drawing a grid of $n$ rows and $10^9$ columns containing only digits $0$ and $1$. Ezzat noticed what Moamen was drawing and became interested in the minimum number of rows one needs to remove to make the grid beautiful. A grid is beautiful if and only if for every two consecutive rows there is at least one column containing $1$ in these two rows. Ezzat will give you the number of rows $n$, and $m$ segments of the grid that contain digits $1$. Every segment is represented with three integers $i$, $l$, and $r$, where $i$ represents the row number, and $l$ and $r$ represent the first and the last column of the segment in that row. For example, if $n = 3$, $m = 6$, and the segments are $(1,1,1)$, $(1,7,8)$, $(2,7,7)$, $(2,15,15)$, $(3,1,1)$, $(3,15,15)$, then the grid is: Your task is to tell Ezzat the minimum number of rows that should be removed to make the grid beautiful.
Try to count the maximum number of rows that makes a beautiful grid, and remove the others. Can you get some dynamic programming formula, and then optimize it with some ranges data structures? We can use dynamic programming to get the maximum number of rows that make a beautiful grid. Define the 2d array, $dp$, where $dp_{i,j}$ $=$ maximum number of rows (from row $1$ to row $i$) that make a beautiful grid, and has $1$ in column $j$ at the last row I have in the biggest beautiful grid. the last row in the biggest beautiful grid is the not necessary to be $i$ Form the definition: $dp_{0,j}$ $=$ $0$. $dp_{0,j}$ $=$ $0$. $dp_{i,j}$ $=$ $1$ $+$ $\max_{k \in C_i}$ {$dp_{i-1,k}$} if $grid_{i,j}$ $=$ $1$. $dp_{i,j}$ $=$ $1$ $+$ $\max_{k \in C_i}$ {$dp_{i-1,k}$} if $grid_{i,j}$ $=$ $1$. Otherwise, if $grid_{i,j}$ $\neq$ $1$, then $dp_{i,j}$ $=$ $dp_{i-1,j}$ . Otherwise, if $grid_{i,j}$ $\neq$ $1$, then $dp_{i,j}$ $=$ $dp_{i-1,j}$ . where $C_i$ is that set of columns that contain $1$ in row $i$. As you know, the set $C_i$ contains the intervals, so we just search in some intervals for the maximum, or update some intervals in the previous layer in $dp$. We can do it faster using Segment tree. So the algorithm will be as follows: Define an array $prev$, where $prev_i$ $=$ the previous row of $i$ in which maximum beautiful grid end with $i$-th row. We will use it to get the rows that will not be removed. Define an array $prev$, where $prev_i$ $=$ the previous row of $i$ in which maximum beautiful grid end with $i$-th row. We will use it to get the rows that will not be removed. Build a segment tree of pairs ($value$, $index$) initially with { $0$ , $-1$ }. Build a segment tree of pairs ($value$, $index$) initially with { $0$ , $-1$ }. Then for each $i$ from $1$ to $n$: Get the maximum value in all the ranges $[l_j,r_j]$ that contains $1$ at the $i$-th row. Let's call it $mx$. Store $prev_{i}$ $=$ $mx.index$. Update all the ranges $[l_j,r_j]$ of this row like this: $seg_j$ $=$ $max($ $seg_j$ $,$ { $mx.value$ $+$ $1$ $,$ $i$ }). Finally, get the rows that have the maximum value using the $prev$ array, and remove the others. Then for each $i$ from $1$ to $n$: Get the maximum value in all the ranges $[l_j,r_j]$ that contains $1$ at the $i$-th row. Let's call it $mx$. Store $prev_{i}$ $=$ $mx.index$. Update all the ranges $[l_j,r_j]$ of this row like this: $seg_j$ $=$ $max($ $seg_j$ $,$ { $mx.value$ $+$ $1$ $,$ $i$ }). Finally, get the rows that have the maximum value using the $prev$ array, and remove the others. The total complexity will be $\mathcal{O}(n + m\log{}10^9)$ or $\mathcal{O}(n + m\log{}m)$ if you make a coordinate compression to the values.
[ "data structures", "dp", "greedy" ]
2,200
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> #include <unordered_map> #include <unordered_set> using namespace std; #define endl "\n" #define ll long long #define sz(s) (int)(s.size()) #define INF 0x3f3f3f3f3f3f3f3fLL #define all(v) v.begin(),v.end() #define watch(x) cout<<(#x)<<" = "<<x<<endl const int dr[]{ -1, -1, 0, 1, 1, 1, 0, -1 }; const int dc[]{ 0, 1, 1, 1, 0, -1, -1, -1 }; #if __cplusplus >= 201402L template<typename T> vector<T> create(size_t n) { return vector<T>(n); } template<typename T, typename ... Args> auto create(size_t n, Args ... args) { return vector<decltype(create<T>(args...))>(n, create<T>(args...)); } #endif void run() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); #else #endif } const pair<int, int> NIL = { 0,-1 }; struct segment_tree { #define LEFT (idx<<1) #define RIGHT (idx<<1|1) #define MID (start+end>>1) int n; vector<pair<int, int>> tree, lazy; segment_tree(int n) :n(n) { tree = lazy = vector<pair<int, int>>(n << 2, NIL); } void push_down(int idx, int start, int end) { if (lazy[idx] == NIL) return; tree[idx] = max(tree[idx], lazy[idx]); if (start != end) { lazy[LEFT] = max(lazy[LEFT], lazy[idx]); lazy[RIGHT] = max(lazy[RIGHT], lazy[idx]); } lazy[idx] = NIL; } void update(int idx, int start, int end, int l, int r, pair<int, int> p) { push_down(idx, start, end); if (r < start || end < l) return; if (l <= start && end <= r) { lazy[idx] = max(lazy[idx], p); push_down(idx, start, end); return; } update(LEFT, start, MID, l, r, p); update(RIGHT, MID + 1, end, l, r, p); tree[idx] = max(tree[LEFT], tree[RIGHT]); } pair<int, int> query(int idx, int start, int end, int l, int r) { push_down(idx, start, end); if (r < start || end < l) return NIL; if (l <= start && end <= r) return tree[idx]; return max(query(LEFT, start, MID, l, r), query(RIGHT, MID + 1, end, l, r)); } void update(int l, int r,pair<int,int> p) { update(1, 1, n, l, r, p); } pair<int, int> query(int l, int r) { return query(1, 1, n, l, r); } }; int main() { run(); int n, m; cin >> n >> m; vector<vector<pair<int, int>>> v(n); vector<int> id; while (m--) { int i, l, r; cin >> i >> l >> r; id.push_back(l); id.push_back(r); v[i - 1].push_back({ l,r }); } sort(all(id)); id.erase(unique(all(id)), id.end()); for (int i = 0; i < n; i++) for (auto& it : v[i]) { it.first = upper_bound(all(id), it.first) - id.begin(); it.second = upper_bound(all(id), it.second) - id.begin(); } segment_tree seg(id.size()); vector<int> prv(n, -1); for (int i = 0; i < n; i++) { pair<int, int> mx = NIL; for (auto& it : v[i]) mx = max(mx, seg.query(it.first, it.second)); prv[i] = mx.second; mx.first++; mx.second = i; for (auto& it : v[i]) seg.update(it.first, it.second, mx); } pair<int, int> p = seg.query(1, id.size()); vector<bool> vis(n); int cur = p.second; while (cur != -1) { vis[cur] = true; cur = prv[cur]; } cout << n - p.first << endl; for (int i = 0; i < n; i++) if (!vis[i]) cout << i + 1 << ' '; }
1557
E
Assiut Chess
This is an interactive problem. ICPC Assiut Community decided to hold a unique chess contest, and you were chosen to control a queen and hunt down the hidden king, while a member of ICPC Assiut Community controls this king. You compete on an $8\times8$ chessboard, the rows are numerated from top to bottom, and the columns are numerated left to right, and the cell in row $x$ and column $y$ is denoted as $(x, y)$. In one turn you can move the queen to any of the squares on the same horizontal line, vertical line, or any of the diagonals. For example, if the queen was on square ($4$, $5$), you can move to ($q_1$, $5$), ($4$, $q_1$), ($q_1$, $9-q_1$), or ($q_2$, $q_2+1$) where ($1 \le q_1 \le 8$, $q_1 \ne 4$, $1 \le q_2 \le 7$, $q_2 \ne 4$). Note that the queen \textbf{cannot} stay on its current cell. In one turn, the king can move "Right", "Left", "Up", "Down", "Down-Right", "Down-Left", "Up-Left", or "Up-Right" such that he doesn't get out of the board. The king \textbf{cannot} move into a cell that is on the same row, column or diagonal with the queen (including the position of the queen itself). For example, if the king was on square ($4$, $5$), he can move to ($4+k_1$, $5+k_2$) where ($-1 \le k_1,k_2 \le 1$, $(k_1, k_2) \ne (0, 0)$). At the start of the game, you should place the queen at any location on the board, and this is done once per game. After that the king is secretly placed at any cell different from the queen's location. You do not know the position of the king. Then, the king and the queen take turns with the king moving first. The king moves to one of the possible directions ("Right", "Down", "Up-Left", etc.), and you are only given the direction it moves to. After that, you should move your queen by declaring the square to which your queen will move. The game follows like this until you win the game or run out of moves. You win if the king has no valid moves. You lose if after $130$ moves of the queen the king still has valid moves.
Try to force the king to move into one of the corners down. If you put the queen in a row $x$, move the queen to the left of the row, then start swiping the row right, one square at a time. If you've visited all $8$ squares on the row and the king never made a vertical move, it means $|$ current king row $-$ current queen row $|$ $\ge 2$ (if the king were on row ($x + 1$\$x-1$), he would've been forced to move $1$ square (down\up) at some point). This is one of many possible solutions. We need to force the king to move into one of the four corners (bottom right or bottom left corner in this solution) to ensure that the king will be trapped (cannot move anymore). Place the queen on the top row. After the king makes a $1$ move, he should be below the queen's row. Suppose the queen is on the row $x$ with the king below it (row $x$ $+$ $i$ where $i$ > $0$). If $i$ $=$ $1$, we cannot move down to the next row as the king may move up and we will not be able to trap it. Otherwise, we can move down by one unit. To ensure that the king is not on the next row, scan the current row, $x$, by moving the queen from the leftmost column to the rightmost column one square at a time. Therefore, you can move the queen as follows: During the scan, if you have visited all $8$ squares of the current row and the king never made a vertical or diagonal move, it means that $i \ge 2$ and you can go down by one row. It is now guaranteed that the king is still below the queen. During the scan, if you have visited all $8$ squares of the current row and the king never made a vertical or diagonal move, it means that $i \ge 2$ and you can go down by one row. It is now guaranteed that the king is still below the queen. If the king were on row $x$ $+$ $1$, he would have been forced to move $1$ square down at some point. If he ever goes down, move the queen down by one row. If the king were on row $x$ $+$ $1$, he would have been forced to move $1$ square down at some point. If he ever goes down, move the queen down by one row. If the king moves up, start scanning the row again. This can only happen a limited number of times without the king moving into a check. If the king moves up, start scanning the row again. This can only happen a limited number of times without the king moving into a check. In total, the queen needs to apply step $2$ up to $8$ times. At each row, step $1$ needs to be applied, so it takes $8$ moves. Step $1$ also needs to be applied every time step $3$ is applied, which can happen at most $8$ times. In total, that is $8$ $\cdot$ $(8$ $+$ $8)$ $=$ $128$ moves.
[ "brute force", "constructive algorithms", "interactive" ]
2,800
#define _CRT_SECURE_NO_WARNINGS #include <bits/stdc++.h> #include <unordered_map> #include <unordered_set> using namespace std; //#define endl "\n" #define ll long long #define sz(s) (int)(s.size()) #define INF 0x3f3f3f3f3f3f3f3fLL #define all(v) v.begin(),v.end() #define watch(x) cout<<(#x)<<" = "<<x<<endl const int dr[]{ -1, -1, 0, 1, 1, 1, 0, -1 }; const int dc[]{ 0, 1, 1, 1, 0, -1, -1, -1 }; #if __cplusplus >= 201402L template<typename T> vector<T> create(size_t n) { return vector<T>(n); } template<typename T, typename ... Args> auto create(size_t n, Args ... args) { return vector<decltype(create<T>(args...))>(n, create<T>(args...)); } #endif void run() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE //freopen("input.txt", "r", stdin); #else #endif } const int N = 8, LIMIT_QUERIES = 130 + 1; int curY = 0, cnt = 0; string Move(int x, int y) { assert(++cnt <= LIMIT_QUERIES); cout << x << ' ' << y << endl; curY = y; string s; cin >> s; return s; } bool scanRow(int row) { string s; if (curY == 8) { for (int y = 7; y > 0; y--) { s = Move(row, y); if (s == "Done") return true; if (s.find("Up") != string::npos) return scanRow(row); if (s.find("Down") != string::npos) return false; } return false; } for (int y = (curY == 1 ? 2 : 1); y <= N; y++) { s = Move(row, y); if (s == "Done") return true; if (s.find("Up") != string::npos) return scanRow(row); if (s.find("Down") != string::npos) return false; } return false; } bool solve() { curY = 1, cnt = 0; string s; for (int row = 1; row <= N; row++) { s = Move(row, curY); if (s == "Done") return true; if (scanRow(row)) return true; } return false; } int main() { run(); int t; cin >> t; while (t--) { bool b = solve(); assert(b); } }
1558
A
Charmed by the Game
Alice and Borys are playing tennis. A tennis match consists of games. In each game, one of the players is serving and the other one is receiving. Players serve in turns: after a game where Alice is serving follows a game where Borys is serving, and vice versa. Each game ends with a victory of one of the players. If a game is won by the serving player, it's said that this player holds serve. If a game is won by the receiving player, it's said that this player breaks serve. It is known that Alice won $a$ games and Borys won $b$ games during the match. It is unknown who served first and who won which games. Find all values of $k$ such that exactly $k$ breaks could happen during the match between Alice and Borys in total.
First of all, we don't know who served first, but there are only two options, so let's just try both and unite the sets of $k$'s we get. Assume that Alice served first. Exactly $a+b$ games were played. If $a+b$ is even, both players served exactly $\frac{a+b}{2}$ times, and if $a+b$ is odd, Alice served one more time than Borys. The simplest way to consider both cases is to say that Alice served $p = \lceil \frac{a+b}{2} \rceil$ times, and Borys served $q = \lfloor \frac{a+b}{2} \rfloor$ times ($\lceil t \rceil$ denotes rounding up, and $\lfloor t \rfloor$ denotes rounding down). Let $x$ be the number of times Borys broke Alice's serve ($0 \le x \le p$), and let $y$ be the number of times Alice broke Borys' serve ($0 \le y \le q$). In this case, the number of games Alice won is $a = (p - x) + y$, and the number of games Borys won is $b = x + (q - y)$. We know neither $x$ nor $y$, but let's loop over $x = 0 \ldots p$. From $a = (p - x) + y$, we can calculate $y = a - (p - x)$. If $0 \le y \le q$, the values of $x$ and $y$ represent a valid scenario of the match with exactly $x + y$ breaks in total. The case when Borys served first is handled similarly. Analyzing the formulas further, we can find a "closed-form" solution: Let $d = \lfloor \frac{\lvert a-b \rvert}{2} \rfloor$. If $a + b$ is even, all possible values of $k$ are $d, d + 2, d + 4, \ldots, a + b - d$. If $a + b$ is odd, all possible values of $k$ are $d, d + 1, d + 2, \ldots, a + b - d$.
[ "brute force", "math" ]
1,300
null
1558
B
Up the Strip
\textbf{Note that the memory limit in this problem is lower than in others.} You have a vertical strip with $n$ cells, numbered consecutively from $1$ to $n$ from top to bottom. You also have a token that is initially placed in cell $n$. You will move the token up until it arrives at cell $1$. Let the token be in cell $x > 1$ at some moment. One shift of the token can have either of the following kinds: - Subtraction: you choose an integer $y$ between $1$ and $x-1$, inclusive, and move the token from cell $x$ to cell $x - y$. - Floored division: you choose an integer $z$ between $2$ and $x$, inclusive, and move the token from cell $x$ to cell $\lfloor \frac{x}{z} \rfloor$ ($x$ divided by $z$ rounded down). Find the number of ways to move the token from cell $n$ to cell $1$ using one or more shifts, and print it modulo $m$. Note that if there are several ways to move the token from one cell to another in one shift, all these ways are considered \textbf{distinct} (check example explanation for a better understanding).
This problem was inspired by Blogewoosh #4 a long time ago (Blogewoosh #8 when?). Pretty clearly, we are facing a dynamic programming problem. Let $f(x)$ be the number of ways to move from cell $x$ to cell $1$. Then, $f(1) = 1$, $f(x) = \sum \limits_{y=1}^{x-1} f(x-y) + \sum \limits_{z=2}^{x} f(\lfloor \frac{x}{z} \rfloor)$, and $f(n)$ is the answer to the problem. However, a straightforward implementation has $O(n^2)$ time complexity and is too slow. Let's look at the main formula for $f(x)$ again: $f(x) = \sum \limits_{y=1}^{x-1} f(x-y) + \sum \limits_{z=2}^{x} f(\lfloor \frac{x}{z} \rfloor)$. The first sum, $\sum \limits_{y=1}^{x-1} f(x-y)$, is easy to optimize: just maintain the sum of $f_1 \ldots f_{x-1}$ and recalculate it by adding $f(x)$. This takes just $O(1)$ time per cell. For the second sum, $\sum \limits_{z=2}^{x} f(\lfloor \frac{x}{z} \rfloor)$, note that $\lfloor \frac{x}{z} \rfloor$ can take at most $O(\sqrt{x})$ different values over $z \in [2; x]$. We can handle this sum as follows: Find the sum over all $z < \sqrt{x}$ directly. We only need to consider $z \ge \sqrt{x}$ now. For any such value, $\lfloor \frac{x}{z} \rfloor \le \sqrt{x}$. Let's loop over a cell $c \le \sqrt{x}$, for how many different values of $z$ it's true that $c = \lfloor \frac{x}{z} \rfloor$? By definition of the floor function, $c \le \frac{x}{z} < c+1$. Solving this inequality, we get $z \in [\lfloor \frac{x}{c+1} \rfloor + 1; \lfloor \frac{x}{c} \rfloor]$. The length of this segment gives us the coefficient of $f(c)$ in the sum. This gives us an $O(n \sqrt{n})$ solution which is enough for the subtask in Division 2. To get a faster solution, let $S(x)$ denote the multiset of cells where we can go to from cell $x$ (this multiset contains $2x-2$ values). How is $S(x+1)$ different from $S(x)$? $S(x+1)$ contains an extra occurrence of $x$ because we can subtract $1$ from $x+1$. $S(x+1)$ contains an extra occurrence of $1$ because we can divide $x+1$ by $x+1$. For each $i > 1$ that is a divisor of $x+1$, $S(x+1)$ contains an occurrence of $i$ that replaces an occurrence of $i-1$. We don't need to maintain $S(x)$ itself, but we can maintain the sum of $f(i)$ over all $i \in S(x)$ and recalculate this sum as we go from $x$ to $x+1$. The total number of changes to $S$ is limited by the total number of divisors of all numbers from $1$ to $n$, that is, $\frac{n}{1} + \frac{n}{2} + \ldots + \frac{n}{n} = O(n \log n)$. However, if implemented directly, we need to quickly find the divisors of each $x$, and we can only afford $O(n)$ memory due to the memory limit. We can achieve that by preparing a sieve of Eratosthenes, factorizing $x$ and generating all its divisors. A better way is do it the reverse way: once we find $f(c)$ for some $c$, let's traverse $x = 2c, 3c, \ldots$ and add $f(c) - f(c-1)$ to $f(x)$. This way the time complexity stays $O(n \log n)$ and the memory complexity is $O(n)$.
[ "brute force", "dp", "math", "number theory", "two pointers" ]
1,900
null
1558
C
Bottom-Tier Reversals
You have a permutation: an array $a = [a_1, a_2, \ldots, a_n]$ of distinct integers from $1$ to $n$. The length of the permutation $n$ is odd. You need to sort the permutation in increasing order. In one step, you can choose any prefix of the permutation with an odd length and reverse it. Formally, if $a = [a_1, a_2, \ldots, a_n]$, you can choose any odd integer $p$ between $1$ and $n$, inclusive, and set $a$ to $[a_p, a_{p-1}, \ldots, a_1, a_{p+1}, a_{p+2}, \ldots, a_n]$. Find a way to sort $a$ using no more than $\frac{5n}{2}$ reversals of the above kind, or determine that such a way doesn't exist. The number of reversals doesn't have to be minimized.
First of all, consider what happens when we reverse a prefix of odd length $p$. Elements $a_{p+1}$ to $a_n$ don't move at all, and for each $i$ from $1$ to $p$, $a_i$ moves to $a_{p-i+1}$. Note that $i$ and $p-i+1$ have the same parity: therefore, no element can ever change the parity of its position. In the final sorted permutation, we need to have $a_i = i$ for all $i$: that is, the parity of each element's position must match the parity of its value. This leads to the following necessary condition: for each $i \in [1, n]$, $a_i \bmod 2 = i \bmod 2$. If for any $i$ this doesn't hold, the permutation can not be sorted. It turns out this condition is also sufficient. Let's devise a procedure to sort a permutation of odd length $n$. If $a_n = n$ and $a_{n - 1} = n - 1$, we don't have to touch $a_{n-1}$ and $a_n$ ever again, and we can proceed to sorting a permutation of length $n-2$. Can we actually move $n$ and $n-1$ to their final positions with a simple sequence of steps? Indeed we can. Here is one way to do this in exactly $5$ steps: Let $a_x = n$ (note that $x$ is odd). Reverse a prefix of length $x$ to move $n$ to position $1$. Let $a_y = n-1$ (note that $y$ is even). Reverse a prefix of length $y-1$ to move $n$ to position $y-1$. Reverse a prefix of length $y+1$ to move $n-1$ to position $2$ and $n$ to position $3$. Reverse a prefix of length $3$ to move $n$ to position $1$ ($n-1$ stays at position $2$). Reverse a prefix of length $n$ to move $n$ to position $n$ and $n-1$ to position $n-1$, as desired. We can use this procedure $\frac{n-1}{2}$ times to first move $n$ and $n-1$ to their final positions, then $n-2$ and $n-3$, and so on. This solution requires exactly $\frac{5(n-1)}{2}$ steps.
[ "constructive algorithms", "greedy" ]
2,000
null
1558
D
Top-Notch Insertions
Consider the insertion sort algorithm used to sort an integer sequence $[a_1, a_2, \ldots, a_n]$ of length $n$ in non-decreasing order. For each $i$ in order from $2$ to $n$, do the following. If $a_i \ge a_{i-1}$, do nothing and move on to the next value of $i$. Otherwise, find the smallest $j$ such that $a_i < a_j$, shift the elements on positions from $j$ to $i-1$ by one position to the right, and write down the initial value of $a_i$ to position $j$. In this case we'll say that we performed an insertion of an element from position $i$ to position $j$. It can be noticed that after processing any $i$, the prefix of the sequence $[a_1, a_2, \ldots, a_i]$ is sorted in non-decreasing order, therefore, the algorithm indeed sorts any sequence. For example, sorting $[4, 5, 3, 1, 3]$ proceeds as follows: - $i = 2$: $a_2 \ge a_1$, do nothing; - $i = 3$: $j = 1$, insert from position $3$ to position $1$: $[3, 4, 5, 1, 3]$; - $i = 4$: $j = 1$, insert from position $4$ to position $1$: $[1, 3, 4, 5, 3]$; - $i = 5$: $j = 3$, insert from position $5$ to position $3$: $[1, 3, 3, 4, 5]$. You are given an integer $n$ and a list of $m$ integer pairs $(x_i, y_i)$. We are interested in sequences such that if you sort them using the above algorithm, exactly $m$ insertions will be performed: first from position $x_1$ to position $y_1$, then from position $x_2$ to position $y_2$, ..., finally, from position $x_m$ to position $y_m$. How many sequences of length $n$ consisting of (not necessarily distinct) integers between $1$ and $n$, inclusive, satisfy the above condition? Print this number modulo $998\,244\,353$.
First of all, note that the sequence of insertions uniquely determines where each element goes. For example, for $n = 5$ and a sequence of insertions $(3, 1), (4, 1), (5, 3)$, the initial sequence $[a_1, a_2, a_3, a_4, a_5]$ is always transformed into $[a_4, a_3, a_5, a_1, a_2]$, no matter what $a_i$ are. Thus, instead of counting the initial sequences, we might count the final sequences instead. Let the final sequence be $[b_1, b_2, \ldots, b_n]$. From its sortedness, we know that $b_i \le b_{i+1}$ for every $i \in [1; n-1]$. Consider a single iteration $i$ of the sorting algorithm. If $a_i \ge a_{i-1}$, no insertion occurs. This actually doesn't give us any extra information: we know that $a_i$ is placed later than $a_{i-1}$ in the final sequence anyway. What happens though if $a_i$ is inserted into position $j$? We know that $a_i < a_j$ and also, since $j$ is the smallest index with such property, $a_i \ge a_{j-1}$. Again, a non-strict inequality doesn't give us anything. However, knowing that $a_i < a_j$ is actually important. It turns out that we are interested in elements $a_i$ such that we have ever inserted an element right before $a_i$ during sorting. For every such element, we know that the previous element in the sorted order is strictly smaller. All other pairs of neighboring elements can either be equal, or the earlier one can be smaller. All in all, let $c$ be the number of indices $i \in [1; n-1]$ such that $b_i < b_{i+1}$ (for all the other values of $i$, $b_i \le b_{i+1}$). How many different sequences $b$ with integers from $1$ to $n$ satisfy this? This number can be shown to be equal to $\binom{2n-1-c}{n}$. (The proof can go as follows: for each $i$ such that $b_i \le b_{i+1}$, increase each of $b_{i+1}, b_{i+2}, \ldots, b_n$ by $1$. Now for every $i$ we have $b_i < b_{i+1}$, and the maximum possible value of an element increased to $n + (n-1-c)$. Thus, we have built a bijection from the sequences we are searching for to the sequences of $n$ distinct numbers between $1$ and $n + (n-1-c)$. The number of the latter sequences is clearly $\binom{2n-1-c}{n}$.) How to find $c$? It can be done by going through the insertions and maintaining a balanced binary search tree of your choice. However, implementation becomes simpler if we process the insertions in reverse order. Let's maintain a set $S$ of positions in the final sorted order that are not yet filled in. Initially, the set contains all integers from $1$ to $n$. For each insertion $(x_i, y_i)$ (in reverse order), let $p$ be the $y_i$-th smallest element of $S$, and let $q$ be the $(y_i+1)$-th smallest element of $S$. Since we insert $p$ before $q$, mark position $q$ as "a position such that we have ever inserted an element right before it" (which is important for calculating $c$). Then, erase $p$ from the set. As a data structure that can handle finding the $k$-th smallest element, we can use a balanced binary search tree, a segment tree, or binary search over Fenwick tree (in C++ we can also use a built-in policy-based data structure). Finally, to solve each test case in $O(m \log n)$ and not $O(n \log n)$, we can have a single data structure instance for solving all test cases, and roll back any changes we apply while solving each test case.
[ "combinatorics", "data structures" ]
2,600
null
1558
E
Down Below
In a certain video game, the player controls a hero characterized by a single integer value: power. On the current level, the hero got into a system of $n$ caves numbered from $1$ to $n$, and $m$ tunnels between them. Each tunnel connects two distinct caves. Any two caves are connected with at most one tunnel. Any cave can be reached from any other cave by moving via tunnels. The hero starts the level in cave $1$, and every other cave contains a monster. The hero can move between caves via tunnels. If the hero leaves a cave and enters a tunnel, he must finish his movement and arrive at the opposite end of the tunnel. The hero can use each tunnel to move in both directions. However, the hero \textbf{can not} use the same tunnel \textbf{twice in a row}. Formally, if the hero has just moved from cave $i$ to cave $j$ via a tunnel, he can not head back to cave $i$ immediately after, but he can head to any other cave connected to cave $j$ with a tunnel. It is known that at least two tunnels come out of every cave, thus, the hero will never find himself in a dead end even considering the above requirement. To pass the level, the hero must beat the monsters in all the caves. When the hero enters a cave for the first time, he will have to fight the monster in it. The hero can beat the monster in cave $i$ if and only if the hero's power is strictly greater than $a_i$. In case of beating the monster, the hero's power increases by $b_i$. If the hero can't beat the monster he's fighting, the game ends and the player loses. After the hero beats the monster in cave $i$, all subsequent visits to cave $i$ won't have any consequences: the cave won't have any monsters, and the hero's power won't change either. Find the smallest possible power the hero must start the level with to be able to beat all the monsters and pass the level.
Let's find the smallest possible initial power with binary search. Suppose the initial power is $p$. The main idea behind the solution is to maintain a set of caves where we have beaten all the monsters, and try to extend the set by finding "augmenting" paths. However, we can not just go in an arbitrary unvisited cave and pretend we add it to the set: since we are not allowed to turn back, it might happen that we can not move forward anymore because we don't have enough power. It's important that we must be able to reach any cave inside the set only going through caves belonging to the set itself. Initially, the set contains just cave $1$. What can an augmenting path look like? The path can start somewhere inside the set, go out of the set, follow a simple route visiting some new caves (and beating monsters inside them), and go back to a cave belonging to the set. For example, if caves $1$ and $2$ belong to the set, the route can look like $1 \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow 2$, and we can add caves $3$, $4$, and $5$ to the set. Alternatively, instead of going back to a cave from the set, the path might go into a cave belonging to the route. For example, if caves $1$ and $2$ belong to the set, the route can look like $1 \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow 6 \rightarrow 4$, and we can add caves $3$, $4$, $5$, and $6$ to the set. How do we find any augmenting path satisfying us? It turns out that we can use the following property. Suppose we have a path $v \rightarrow u_1 \rightarrow u_2 \rightarrow \ldots \rightarrow u_k \rightarrow x$ (where $v$ is the only cave belonging to the set) that we can follow and beat all the monsters in the caves we visit. Suppose that we have another such path $v' \rightarrow u'_1 \rightarrow u'_2 \rightarrow \ldots \rightarrow u'_{k'} \rightarrow x$. Suppose that following the former path, we arrive at $x$ with the same or higher power than following the latter path. In this case, notice that $v \rightarrow u_1 \rightarrow u_2 \rightarrow \ldots \rightarrow u_k \rightarrow x \rightarrow u'_{k'} \rightarrow \ldots \rightarrow u'_1 \rightarrow v'$ Thus, we can simply use BFS or DFS to find all reachable caves. Once we find a path leading back into the set, or we find two different paths leading into the same unvisited cave, we can build an augmenting path, extend the set, and start over, until the set contains all caves (in which case we can try to decrease the initial power level $p$) or until we can not find any augmenting path (in which case we must increase $p$). At each binary search iteration, we can have at most $n$ augmenting paths and we find each of them in $O(m)$. Thus, the time complexity of the solution is $O(nm \log{a_{max}})$.
[ "binary search", "dfs and similar", "graphs", "greedy", "meet-in-the-middle", "shortest paths" ]
3,000
null
1558
F
Strange Sort
You have a permutation: an array $a = [a_1, a_2, \ldots, a_n]$ of distinct integers from $1$ to $n$. The length of the permutation $n$ is odd. Consider the following algorithm of sorting the permutation in increasing order. A helper procedure of the algorithm, $f(i)$, takes a single argument $i$ ($1 \le i \le n-1$) and does the following. If $a_i > a_{i+1}$, the values of $a_i$ and $a_{i+1}$ are exchanged. Otherwise, the permutation doesn't change. The algorithm consists of iterations, numbered with consecutive integers starting with $1$. On the $i$-th iteration, the algorithm does the following: - if $i$ is odd, call $f(1), f(3), \ldots, f(n - 2)$; - if $i$ is even, call $f(2), f(4), \ldots, f(n - 1)$. It can be proven that after a finite number of iterations the permutation will be sorted in increasing order. After how many iterations will this happen for the first time?
Let's draw a wall of $n$ towers of cubes, with the $i$-th tower having height $a_i$. For example, for $a = [4, 5, 7, 1, 3, 2, 6]$ the picture will look as follows ($1$ stands for a cube): Note that applying $f(i)$ to the permutation (swapping $a_i$ and $a_{i+1}$ if $a_i > a_{i+1}$) is equivalent to applying $f(i)$ to each row of the above matrix independently (swapping cells $i$ and $i+1$ if the $i$-th cell is $1$ and the $i+1$-th cell is $0$). Also note that in the final state, when the permutation is $[1, 2, \ldots, n]$, each row of the matrix is sorted in non-descending order too ($0$'s go before $1$'s), and vice versa - if each row is sorted, the permutation is sorted as well. Thus, it's enough to find the number of iterations required to sort each row of the matrix, and the maximum of these numbers is the answer for the given permutation. The rows of the matrix are $b_i = [a_i \ge x]$ for $x = 1, 2, \ldots, n$. How to solve the problem for a sequence of $0$'s and $1$'s? We can assume that the instances of $0$'s don't change their relative order, and the same for $1$'s. Let the positions of zeros in the initial sequence be $1 \le p_1 < p_2 < \ldots < p_m \le n$. The $i$-th zero from the left is moving towards position $i$ in the sorted sequence. Let $s(i)$ be the number of steps it takes the $i$-th zero from the left to get to its final position $i$. If the $i$-th zero is already in position $i$, then $s(i) = 0$. Otherwise, if $i > 1$, note that $s(i) \ge s(i - 1) + 1$, because the $i$-th zero can only get to position $i$ after the $(i-1)$-th zero gets to position $i-1$. Moreover, let there be $k_i$ ones to the left of the $i$-th zero in the initial sequence. Then $s(i) \ge k_i + (p_i \bmod 2)$, because the $0$ has to swap with every $1$ to the left of it, and also the first iteration is useless if $p_i$ is odd. It turns out that $s(i) = \max(s(i - 1) + 1, k_i + (p_i \bmod 2))$ - the $i$-th zero either gets stuck into the $(i-1)$-th zero (and then $s_i = s(i - 1) + 1$), or consistently swaps with $1$'s on each iteration except for maybe the first (in which case $s_i = k_i + (p_i \bmod 2)$). We are interested in $s(m)$. Let the number of $0$'s at the start of the initial sequence be $t$. It can be seen that $s(m) = \max \limits_{i=t+1}^m (k_i + (p_i \bmod 2) + (m - i))$, and this is exactly the number of iterations required. Recall that we need to find the number of iterations for $n$ different binary sequences. However, these binary sequences are very similar to each other. Let's maintain the values of $(k_i + (p_i \bmod 2) + (m - i))$ for all zeros in a segment tree (and, say, $-\infty$ for positions containing ones). Start with the sequence $b_i = [a_i \ge x]$ for $x = 1$ - that is, a sequence of all ones. As we increase $x$ by one, a single $1$ in $b$ gets replaced with $0$. We can handle these changes using a segment tree with "range add" and "range max". The time complexity of the solution is $O(n \log n)$. (Another equivalent formula is: $s(m) = \max \limits_{i=l}^r c_1([b_1, b_2, \ldots, b_i]) + c_0([b_{i+1}, \ldots, b_n]) + (i \bmod 2) - 1$. Here $c_x(seq)$ is the number of $x$'s in $seq$; $l$ is the smallest position such that $c_1([b_1, b_2, \ldots, b_l]) > 0$; and $r$ is the largest position such that $c_0([b_{r+1}, \ldots, b_n]) > 0$. This formula can also be proven using induction. In short, consider this formula applied to the number of remaining iterations - the difference is that instead of $(i \bmod 2)$, we sometimes have $1 - (i \bmod 2)$, depending on the parity of the current iteration number. Consider all positions $i$ where the value is maximized. Then it can be shown that after one iteration the value for all such positions decreases by $1$: if the parity is incorrect, after one iteration the parity becomes correct; otherwise, observe that $b_i = 1$ and $b_{i+1} = 0$, which get swapped in the next iteration. Moreover, the value for all other positions has the same parity, increases by at most $1$, and thus doesn't become too big either.)
[ "data structures", "sortings" ]
3,300
null
1559
A
Mocha and Math
Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation. This day, Mocha got a sequence $a$ of length $n$. In each operation, she can select an arbitrary interval $[l, r]$ and for all values $i$ ($0\leq i \leq r-l$), replace $a_{l+i}$ with $a_{l+i} \,\&\, a_{r-i}$ at the same time, where $\&$ denotes the bitwise AND operation. This operation can be performed \textbf{any number of times}. For example, if $n=5$, the array is $[a_1,a_2,a_3,a_4,a_5]$, and Mocha selects the interval $[2,5]$, then the new array is $[a_1,a_2\,\&\, a_5, a_3\,\&\, a_4, a_4\,\&\, a_3, a_5\,\&\, a_2]$. Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?
We assume the answer is $x$. In its binary representation, one bit will be $1$ only if in all the $a_i$'s binary representation,this bit is $1$. Otherwise, we can use one operation to make this bit in $x$ become 0, which is a smaller answer. So we can set $x=a_1$ initially. Then we iterate over the sequence and make $x=x\& a_{i}$, the $x$ is the anwser finally.
[ "bitmasks", "constructive algorithms", "math" ]
900
#include<bits/stdc++.h> #define inf 0x3f3f3f3f #define maxm 100005 #define maxn 2005 #define PII pair<int, int> #define fi first #define se second typedef long long ll; typedef unsigned long long ull; using namespace std; const double pi = acos(-1); const int mod = 998244353; const double eps = 1e-10; const int N =1e2+10; int n; int a[N]; int main() { ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); //int a,b,c; int t; cin>>t; while(t--){ cin>>n; for(int i=1;i<=n;i++)cin>>a[i]; int res=a[1]; for(int i=2;i<=n;i++)res&=a[i]; cout<<res<<endl; } return 0; }
1559
B
Mocha and Red and Blue
As their story unravels, a timeless tale is told once again... Shirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to solve, so she wants you to solve them and tell her the answers. The puzzles are described as follow. There are $n$ squares arranged in a row, and each of them can be painted either red or blue. Among these squares, some of them have been painted already, and the others are blank. You can decide which color to paint on each blank square. Some pairs of adjacent squares may have the same color, which is imperfect. We define the imperfectness as the number of pairs of adjacent squares that share the same color. For example, the imperfectness of "BRRRBBR" is $3$, with "BB" occurred once and "RR" occurred twice. Your goal is to minimize the imperfectness and print out the colors of the squares after painting.
For a longest period of "?", it is optimized to paint either "RBRB..." or "BRBR...", so the imperfectness it made is only related to the colors of both sides of it. Choose the one with the lower imperfectness for each longest period of "?" in $O(n)$ is acceptable. More elegantly, if the square on the left or on the right of a "?" is painted, simply paint "?" with the different color from it. This can be proved to reach the minimum imperfectness by considering the parity.
[ "dp", "greedy" ]
900
#include <cstdio> using namespace std; const int N=105; int t,n,cnt; char s[N]; int main() { scanf("%d",&t); while (t--) { cnt=0; scanf("%d",&n); scanf("%s",s+1); for (int i=1;i<=n;i++) cnt+=(s[i]!='?'); if (!cnt) s[1]='R'; for (int i=2;i<=n;i++) if (s[i]=='?'&&s[i-1]!='?') s[i]=s[i-1]^('B'^'R'); for (int i=n-1;i;i--) if (s[i]=='?'&&s[i+1]!='?') s[i]=s[i+1]^('B'^'R'); printf("%s\n",s+1); } return 0; }
1559
C
Mocha and Hiking
The city where Mocha lives in is called Zhijiang. There are $n+1$ villages and $2n-1$ directed roads in this city. There are two kinds of roads: - $n-1$ roads are from village $i$ to village $i+1$, for all $1\leq i \leq n-1$. - $n$ roads can be described by a sequence $a_1,\ldots,a_n$. If $a_i=0$, the $i$-th of these roads goes from village $i$ to village $n+1$, otherwise it goes from village $n+1$ to village $i$, for all $1\leq i\leq n$. Mocha plans to go hiking with Taki this weekend. To avoid the trip being boring, they plan to go through every village \textbf{exactly once}. They can start and finish at any villages. Can you help them to draw up a plan?
If $a_1=1$, then the path $\Big[(n+1) \to 1 \to 2 \to \cdots \to n\Big]$ is valid. If $a_n=0$, then the path $\Big[1 \to 2 \to \cdots \to n \to (n+1) \Big]$ is valid. Otherwise, since $a_1=0 \land a_n=1$, there must exists an integer $i$ ($1 \le i < n$) where $a_i=0 \land a_{i+1}=1$, then the path $\Big[1 \to 2 \to \cdots \to i \to (n+1) \to (i+1) \to (i+2) \to \cdots n\Big]$ is valid. This is a step to prove that there always exists an Hamiltonian path in a tournament graph.
[ "constructive algorithms", "graphs" ]
1,200
#include <bits/stdc++.h> #define maxn 100086 using namespace std; int t, n; int a[maxn]; void solve(){ scanf("%d", &n); for(int i = 1;i <= n;i++) scanf("%d", &a[i]); if(a[1]){ printf("%d ", n + 1); for(int i = 1;i <= n;i++) printf("%d ", i); return; } for(int i = 1;i < n;i++){ if(!a[i] && a[i + 1]){ for(int j = 1;j <= i;j++) printf("%d ", j); printf("%d ", n + 1); for(int j = i + 1;j <= n;j++) printf("%d ", j); return; } } for(int i = 1;i <= n;i++) printf("%d ", i); printf("%d ", n + 1); } int main(){ scanf("%d", &t); while(t--) solve(), puts(""); }
1559
D1
Mocha and Diana (Easy Version)
\textbf{This is the easy version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.} A forest is an undirected graph without cycles (not necessarily connected). Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $1$ to $n$, and they would like to add edges to their forests such that: - After adding edges, both of their graphs are still forests. - They add the same edges. That is, if an edge $(u, v)$ is added to Mocha's forest, then an edge $(u, v)$ is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.
In the final situation, if one forest has more than one tree, we choose two trees from it, such as tree $A$ and tree $B$. Then we consider node $a$ in $A$ and node $b$ in $B$, they must be connected in another forest. We can easily find node $b$ is connected with all the nodes in $A$ and node $a$ is connected with all the nodes in $B$. So nodes in $A$ and $B$ are in the same tree in another forest. If we consider other trees, we can get the same conclusion. Hence nodes in another forest form only one tree. So we can enumerate every pair $(i, j)$ and check if this edge can be added. When the edge can be added, we can just add it. This can be done in the complexity of $O(n^2)$.
[ "brute force", "constructive algorithms", "dsu", "graphs", "greedy", "trees" ]
1,400
#include<bits/stdc++.h> #define maxn 2005 #define fi first #define se second #define PII pair<int, int> using namespace std; typedef long long ll; const ll mod = 10007; inline ll read(){ ll x = 0, f = 1;char ch = getchar(); while(ch > '9' || ch < '0'){if(ch == '-') f = -1;ch = getchar();} while(ch >= '0' && ch <= '9'){x = x * 10 + ch -'0';ch = getchar();} return x * f; } int n, m1, m2, f[2][maxn]; int getf(int id, int x){return x == f[id][x] ? x : f[id][x] = getf(id, f[id][x]);} vector<PII> ans; int main() { n = read(), m1 = read(), m2 = read(); for(int i = 1; i <= n; i++) f[0][i] = f[1][i] = i; for(int i = 1; i <= m1; i++){ int u = read(), v = read(); int fu = getf(0, u), fv = getf(0, v); f[0][fu] = fv; } for(int i = 1; i <= m2; i++){ int u = read(), v = read(); int fu = getf(1, u), fv = getf(1, v); f[1][fu] = fv; } for(int i = 1; i <= n; i++){ for(int j = i + 1; j <= n; j++){ if(getf(0, i) != getf(0, j) && getf(1, i) != getf(1, j)){ ans.push_back({i, j}); f[0][getf(0, i)] = getf(0, j); f[1][getf(1, i)] = getf(1, j); } } } printf("%d\n", ans.size()); for(auto i: ans) printf("%d %d\n", i.fi, i.se); return 0; }
1559
D2
Mocha and Diana (Hard Version)
\textbf{This is the hard version of the problem. The only difference between the two versions is the constraint on $n$. You can make hacks only if all versions of the problem are solved.} A forest is an undirected graph without cycles (not necessarily connected). Mocha and Diana are friends in Zhijiang, both of them have a forest with nodes numbered from $1$ to $n$, and they would like to add edges to their forests such that: - After adding edges, both of their graphs are still forests. - They add the same edges. That is, if an edge $(u, v)$ is added to Mocha's forest, then an edge $(u, v)$ is added to Diana's forest, and vice versa. Mocha and Diana want to know the maximum number of edges they can add, and which edges to add.
To have a clearer understanding, let's visualize the problem with a grid where each row is a component in the left forest and each column is a component in the right forest. For example, the cell (i,j) contains vertexes which belongs to $i^{th}$ component in the left forest and $j^{th}$ component in the right tree. (Some cells may be empty.) An operation corresponds to finding two filled cells in different rows and different columns, merging the two rows, and merging the two columns. Now we need to make operation rapidly. For each row, we maintain a set of the different columns with filled cells in this row. Symmetrically, for each column we maintain a set of the different rows with filled cells in this column. To merge two rows, we insert the elements of the smaller set into the larger set. The smaller set is now useless, and we delete it from every column in the set and insert the larger one. Since the data structure is symmetric, merging two columns is similar. Without loss of generality, assume there are fewer rows than columns. If there is a row whose set has more than 1 element, we can pick it and any other row, and find an operation we can make. Otherwise if all rows are singletons, then we know the sets are all disjoint because there are more columns than rows. So we can pick any two sets and make an operation, and then there's a set with more than 1 element. Maintaining which rows have sets with size more than 1 is not hard. For each operation, we need to output the corresponding vertex in the original two forest. Firstly, choose a vertex as the representative of each cell, because all vertexes in a cell can be seen as equivalent. Then, when merging two rows or columns, we just insert the representative vertexes at the same time. There can be at most $2n$ merge operations and the total complexity of them will be $O(n\log^2 n)$. This is because an element moves to a new row/column $O(\log n)$ times and each move is $O(\log n)$ time (using STL set in cpp). Overall, it's $O(n\log^2n)$time and $O(n\log n)$ space.
[ "brute force", "constructive algorithms", "dfs and similar", "dsu", "graphs", "greedy", "trees", "two pointers" ]
2,500
#include<bits/stdc++.h> using namespace std; #define N 100010 int fa1[N],fa2[N]; set<pair<int,int> > rows; set<int> row[N],col[N]; set<int>::iterator it; map<int,int> mp[N]; pair<int,int> Ans[N]; int getfa(int *fa,int x){ if (x==fa[x]){ return x; } return fa[x]=getfa(fa,fa[x]); } void Merge_row(int x,int y){ for (it=row[y].begin();it!=row[y].end();it++){ mp[x][*it]=mp[y][*it]; row[x].insert(*it); col[*it].erase(y); col[*it].insert(x); } } void Merge_col(int x,int y){ for (it=col[y].begin();it!=col[y].end();it++){ mp[*it][x]=mp[*it][y]; col[x].insert(*it); row[*it].erase(y); row[*it].insert(x); } } int main(){ int n,m1,m2,h=0,i; scanf("%d%d%d",&n,&m1,&m2); for (i=1;i<=n;i++){ fa1[i]=fa2[i]=i; } for (i=1;i<=m1;i++){ int x,y; scanf("%d%d",&x,&y); int p=getfa(fa1,x),q=getfa(fa1,y); fa1[p]=q; } for (i=1;i<=m2;i++){ int x,y; scanf("%d%d",&x,&y); int p=getfa(fa2,x),q=getfa(fa2,y); fa2[p]=q; } if (m1<m2){ swap(fa1,fa2); } for (i=1;i<=n;i++){ int p1=getfa(fa1,i),p2=getfa(fa2,i); mp[p1][p2]=i; row[p1].insert(p2); col[p2].insert(p1); } for (i=1;i<=n;i++){ if (getfa(fa1,i)==i){ rows.insert(make_pair(-row[i].size(),i)); } } while (rows.size()>1){ int x=rows.begin()->second; rows.erase(rows.begin()); int y=rows.begin()->second; rows.erase(rows.begin()); if (row[x].size()<row[y].size()){ swap(x,y); } it=row[x].begin(); int a=*it,b=*row[y].begin(); if (a==b){ a=*++it; } Ans[++h]=make_pair(mp[x][a],mp[y][b]); if (col[a].size()<col[b].size()){ swap(a,b); } Merge_row(x,y); Merge_col(a,b); rows.insert(make_pair(-row[x].size(),x)); } printf("%d\n",h); for (i=1;i<=h;i++){ printf("%d %d\n",Ans[i].first,Ans[i].second); } return 0; }
1559
E
Mocha and Stars
Mocha wants to be an astrologer. There are $n$ stars which can be seen in Zhijiang, and the brightness of the $i$-th star is $a_i$. Mocha considers that these $n$ stars form a constellation, and she uses $(a_1,a_2,\ldots,a_n)$ to show its state. A state is called mathematical if all of the following three conditions are satisfied: - For all $i$ ($1\le i\le n$), $a_i$ is an integer in the range $[l_i, r_i]$. - $\sum \limits _{i=1} ^ n a_i \le m$. - $\gcd(a_1,a_2,\ldots,a_n)=1$. Here, $\gcd(a_1,a_2,\ldots,a_n)$ denotes the greatest common divisor (GCD) of integers $a_1,a_2,\ldots,a_n$. Mocha is wondering how many different mathematical states of this constellation exist. Because the answer may be large, you must find it modulo $998\,244\,353$. Two states $(a_1,a_2,\ldots,a_n)$ and $(b_1,b_2,\ldots,b_n)$ are considered different if there exists $i$ ($1\le i\le n$) such that $a_i \ne b_i$.
We firstly ignore the constraint of $\gcd$, let $f([l_1,l_2,\ldots,l_n],[r_1,r_2,\ldots,r_n],M)$ be the number of integers $(a_1,a_2,\cdots,a_n)$ satisfy the following two conditions: For all $i$ ($1\le i\le n$), $a_i$ is an integer in the range $[l_i, r_i]$. $\sum \limits _{i=1} ^ n a_i \le m$. We can compute it in $O(nM)$ by Knapsack DP optimized by prefix-sums. Then we consider about the constraint of $\gcd$, let $\mu(n)$ be Mobius function, and $g(a_1,a_2,\ldots,a_n)$ be $1$ if $(a_1,a_2,\cdots,a_n)$ satisfies the two conditions we mentioned about (without the constraint of $\gcd$), otherwise it will be $0$. The answer we want is: $\begin{aligned} &\sum_{a_1=l_1}^{r_1}\sum_{a_2=l_2}^{r_2}\cdots\sum_{a_n=l_n}^{r_n}[\gcd(a_1,a_2,\ldots,a_n)=1]g(a_1,a_2,\ldots,a_n) \newline =&\sum_{a_1=l_1}^{r_1}\sum_{a_2=l_2}^{r_2}\cdots\sum_{a_n=l_n}^{r_n}g(a_1,a_2,\ldots,a_n)\sum_{d \mid \gcd(a_1,a_2,\ldots,a_n)}\mu(d) \newline =&\sum_{a_1=l_1}^{r_1}\sum_{a_2=l_2}^{r_2}\cdots\sum_{a_n=l_n}^{r_n}g(a_1,a_2,\ldots,a_n)\sum_{d\mid a_1,d\mid a_2,\ldots,d \mid a_n}\mu(d) \newline =&\sum_{d=1}^M\mu(d)\sum_{a_1=\lceil\frac{l_1}{d}\rceil}^{\lfloor\frac{r_1}{d}\rfloor}\sum_{a_2=\lceil\frac{l_2}{d}\rceil}^{\lfloor\frac{r_2}{d}\rfloor}\cdots\sum_{a_n=\lceil\frac{l_n}{d}\rceil}^{\lfloor\frac{r_n}{d}\rfloor}g(a_1d,a_2d,\ldots,a_nd) \newline \end{aligned}$ $\begin{aligned} \sum_{d=1}^M\mu(d)f\left(\left\lceil\dfrac{l_1}{d}\right\rceil,\left\lceil\dfrac{l_2}{d}\right\rceil,\ldots,\left\lceil\dfrac{l_n}{d}\right\rceil,\left\lfloor\dfrac{r_1}{d}\right\rfloor,\left\lfloor\dfrac{r_2}{d}\right\rfloor,\ldots,\left\lfloor\dfrac{r_n}{d}\right\rfloor,\left\lfloor\dfrac{M}{d}\right\rfloor\right) \end{aligned}$
[ "combinatorics", "dp", "fft", "math", "number theory" ]
2,200
#include <bits/stdc++.h> #define maxn 100086 using namespace std; const int p = 998244353; int n, m; int l[maxn], r[maxn]; int f[maxn], sum[maxn]; int cal(int d){ int M = m / d; f[0] = 1; for(int i = 1;i <= M;i++) f[i] = 0; for(int i = 1;i <= n;i++){ int L = (l[i] + d - 1) / d, R = r[i] / d; if(L > R) return 0; for(int j = 0;j <= M;j++) sum[j] = (f[j] + (j ? sum[j - 1] : 0)) % p; for(int j = 0;j <= M;j++){ f[j] = ((j - L >= 0 ? sum[j - L] : 0) + p - (j - R - 1 >= 0 ? sum[j - R - 1] : 0)) % p; } } int ans = 0; for(int i = 1;i <= M;i++) ans = (ans + f[i]) % p; return ans; } int prm[maxn], cnt, mu[maxn]; bool tag[maxn]; int main(){ scanf("%d%d", &n, &m); for(int i = 1;i <= n;i++) scanf("%d%d", &l[i], &r[i]); mu[1] = 1; for(int i = 2;i <= m;i++){ if(!tag[i]) prm[++cnt] = i, mu[i] = p - 1; for(int j = 1;j <= cnt && prm[j] * i <= m;j++){ tag[i * prm[j]] = true; if(i % prm[j]) mu[i * prm[j]] = (p - mu[i]) % p; else break; } } int ans = 0; for(int i = 1;i <= m;i++) ans = (ans + 1ll * mu[i] * cal(i)) % p; printf("%d", ans); }
1560
A
Dislike of Threes
Polycarp doesn't like integers that are divisible by $3$ or end with the digit $3$ in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too. Polycarp starts to write out the positive (greater than $0$) integers which he likes: $1, 2, 4, 5, 7, 8, 10, 11, 14, 16, \dots$. Output the $k$-th element of this sequence (the elements are numbered from $1$).
The solution is simple: let's create an integer variable (initially set to $0$) that will contain the number of considered liked integers. Let's iterate over all positive integers starting with $1$. Let's increase the variable only when the considered number is liked. If the variable is equal to $k$, let's stop the iteration and output the last considered number. Since the answer for $k = 1000$ is $x = 1666$, the count of considered numbers is at most $1666$ so the solution will work on the specified limitations fast enough.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int k; cin >> k; for (int i = 1; ; i++) { if (i % 3 == 0 || i % 10 == 3) continue; if (--k == 0) { cout << i << '\n'; break; } } } }
1560
B
Who's Opposite?
Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $1$. Each person is looking through the circle's center at the opposite person. \begin{center} {\small A sample of a circle of $6$ persons. The orange arrows indicate who is looking at whom.} \end{center} You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $a$ is looking at the person with the number $b$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $c$? If, for the specified $a$, $b$, and $c$, no such circle exists, output -1.
The person with the number $a$ looks at the person with the number $b$ so the count of people standing to the left of $a$ between $a$ and $b$ is equal to the count of people standing to the right of $a$ between $a$ and $b$. Therefore, both counts are equal to $\frac{n - 2}{2}$, hence $n$ must be a solution of the equation $\frac{n - 2}{2} = |a - b| - 1$. The only solution of the equation is $n = 2 \cdot |a - b|$. Let's check that in the circle of $n$ people can occur the numbers $a$, $b$ and $c$, i. e. let's check that $1 \le a, b, c \le n$. If it's false, there's no solution (output $-1$). Since the person with the number $d$ looks at the person with the number $c$, the condition $\frac{n - 2}{2} = |c - d| - 1$ must be met. Let's solve the equation for $d$. There are two solutions: $d_1 = c + \frac{n}{2}$; $d_2 = c - \frac{n}{2}$. We can output any of $d_i$ such that $1 \le d_i \le n$. It's easy to prove that exactly one of the solutions meets the condition.
[ "math" ]
800
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { int t; cin >> t; while (t--) { ll a, b, c; cin >> a >> b >> c; ll n = 2 * abs(a - b); if (a > n || b > n || c > n) cout << -1 << '\n'; else { ll d = n / 2 + c; while (d > n) d -= n; cout << d << '\n'; } } return 0; }
1560
C
Infinity Table
Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $1$, starting from the topmost one. The columns are numbered from $1$, starting from the leftmost one. Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $1$ and so on to the table as follows. \begin{center} {\small The figure shows the placement of the numbers from $1$ to $10$. The following actions are denoted by the arrows.} \end{center} The leftmost topmost cell of the table is filled with the number $1$. Then he writes in the table all positive integers beginning from $2$ sequentially using the following algorithm. First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above). After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on. A friend of Polycarp has a favorite number $k$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $k$.
Let's call a set of cells being filled from the topmost row to the leftmost column a layer. E. g. the $1$-st layer consists of the single number $1$, the $2$-nd layer consists of the numbers $2$, $3$ and $4$, the $3$-rd layer consists of the numbers $5$, $6$, $7$, $8$ and $9$, etc. The number of cells in layers forms an arithmetic progression. The first layer consists of $a_1 = 1$ cells, the $i$-th layer consists of $a_i = a_{i-1} + 2$ cells. The minimum number in the $i$-th layer $x_i$ is equal to the sum of sizes of all layers from the $1$-st to the $(i - 1)$-th plus $1$. Suppose that $k$ belongs to the $i$-th layer. Consider the value of $m = k - x_i + 1$. Polycarp fills exactly $i$ cells on the $i$-th layer before he starts filling the cells from the right to the left (i. e. while he goes down). Therefore, if $m \le i$, the number $k$ belongs to the $m$-th row and the $i$-th column. Otherwise, the number belongs to the $i$-th row and the $(i - (m - i))$-th column. Consider a way to find the coordinates of a given number $k$. Let's iterate by the layer number $i$ to which given the number belongs calculating the values of $a_i$ and $x_i$ (going to the next layer, let's calculate the next layer parameters as follows: $x_{i + 1} := x_i + a_i$; $a_{i + 1} := a_i + 2$). The iteration must be stopped if the layer number $i$ is such that $x_i \le k < x_{i + 1}$. Using the values of $i$ and $x_i$, we can calculate the given number's coordinates in the described way in $O(1)$. The total time of calculating the coodrinates for one given $k$ is $O(i_k)$ where $i_k$ is the number of the layer to which the given $k$ belongs. Let's represent the value of $x_i$ as $x_i = f(i)$: $x_i = 1 + \sum\limits_{j = 1}^{i - 1} a_j = 1 + \sum\limits_{j = 1}^{i - 1} (2j - 1) = 1 + \frac{1 + 2(i - 1) - 1}{2} \cdot (i - 1) = 1 + (i - 1)^2$. $1 + (i_k - 1)^2 = x_{i_k} \le k < x_{i_k + 1} = 1 + i_k^2$, hence $i_k \approx \sqrt(k)$. Therefore, the coordinates of one number $k$ may be calculated in $O(\sqrt{k})$. At the same time, as it follows from the formulas, the layer number $i_k$ can be calculated as follows: $i_k = \lceil \sqrt{k} \rceil$ (the square root of $k$ rounded up). To avoid accuracy problems, you can calculate the value using a loop.
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int k; cin >> k; int a = 1; int x = 1; int i = 1; while (k >= x + a) { x += a; a += 2; i += 1; } int m = k - x + 1; if (m <= i) cout << m << ' ' << i << '\n'; else cout << i << ' ' << (i - (m - i)) << '\n'; } }
1560
D
Make a Power of Two
You are given an integer $n$. In $1$ move, you can do one of the following actions: - erase any digit of the number (it's acceptable that the number before the operation has exactly one digit and after the operation, it is "empty"); - add one digit \textbf{to the right}. The actions may be performed in any order any number of times. Note that if, after deleting some digit from a number, it will contain leading zeroes, they will \textbf{not} be deleted. E.g. if you delete from the number $301$ the digit $3$, the result is the number $01$ (not $1$). You need to perform the \textbf{minimum} number of actions to make the number any power of $2$ (i.e. there's an integer $k$ ($k \ge 0$) such that the resulting number is equal to $2^k$). \textbf{The resulting number must not have leading zeroes}. E.g. consider $n=1052$. The answer is equal to $2$. First, let's add to the right one digit $4$ (the result will be $10524$). Then let's erase the digit $5$, so the result will be $1024$ which is a power of $2$. E.g. consider $n=8888$. The answer is equal to $3$. Let's erase any of the digits $8$ three times. The result will be $8$ which is a power of $2$.
Suppose we must turn $n$ into some specific number $x$. In this case, we can use the following greedy algorithm. Consider the string forms - $s_n$ and $s_x$ - of the numbers $n$ and $x$, respectively. Let's make a pointer $p_n$ pointing at the first character of the string $s_n$ and a pointer $p_x$ pointing at the first character of the string $s_x$. Let's initialize a variable $taken = 0$ in which we will store a number of selected characters. Until any of the pointers points at the place that is out of the corresponding string, let's do the following procedure: if the characters to which the pointers point are equal, we will take the character (increase $taken$ by $1$) and move both pointers $1$ character to the right, otherwise, the only action we must perform is to move $s_n$ $1$ character to the right. The variable $taken$ will contain after the whole process the length of the longest subsequence of $s_n$ equal to a prefix of $s_x$, i. e. the maximum number of original characters of $s_n$ that we will not erase. We must add to the resulting string all remaining characters of $s_x$ to turn it into $s_x$. Therefore, we must erase $|s_n| - taken$ digits and add $|s_x| - taken$ digits so the answer for this subproblem is $ans(n, x) = |s_n| + |s_x| - 2 \cdot taken$ where $|s|$ means the length of a string $s$. Suppose we have a set $X$ of powers of two such that it's enough to consider to get the problem's answer. The problem can be solved as follows: for each $x \in X$ let's calculate the answer for the subproblem described above and select the value of $\min\limits_{x \in X} ans(n,x)$ as the answer. What set of powers of two we can take? Suppose the number $n$ consists of no more than $9$ digits. The answer for each $n$ consisting of $d$ digits doesn't exceed $d + 1$, hence we can get this value by turning the number into $1$ in $d + 1$ move adding $1$ to the right of the number, and erasing all other $d$ digits. Suppose there's a number $x$ such that $ans(n, x) \le d$. So it consists of no more than $2 \cdot d$ digits - this value can be reached as follows: we must not erase any digit and add $d$ digits. Therefore, if $d \le 9$, each number $x$ such that $ans(n, x) \le d$ consists of no more than $18$ digits, hence $x < 10^{18}$. Suppose $n$ consists of more than $9$ digits. Then $n = 10^9$ because $n \le 10^9$ according to the input format. The answer for the number doesn't exceed $9$ - we can get this answer if we erase all $0$ from the number to turn it into $1$. Suppose there's a number $x$ such that $ans(n, x) \le 8$. This number can consist of no more than $18$ digits ($10$ digits of $n$ plus $8$ digits), hence $x < 10^{18}$. Therefore, it's enough to consider all powers of two that are less than $10^{18}$.
[ "greedy", "math", "strings" ]
1,300
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll P2LIM = (ll)2e18; int solve(string s, string t) { int tp = 0; int sp = 0; int taken = 0; while (sp < s.length() && tp < t.length()) { if(s[sp] == t[tp]) { taken++; tp++; } sp++; } return (int)s.length() - taken + (int)t.length() - taken; } vector<string> ts; int main() { for (ll p2 = 1; p2 <= P2LIM; p2 *= 2) ts.push_back(to_string(p2)); int t; cin >> t; while (t--) { string n; cin >> n; int ans = n.length() + 1; for (auto p2 : ts) ans = min(ans, solve(n, p2)); cout << ans << '\n'; } return 0; }
1560
E
Polycarp and String Transformation
Polycarp has a string $s$. Polycarp performs the following actions until the string $s$ is empty ($t$ is initially an empty string): - he adds to the right to the string $t$ the string $s$, i.e. he does $t = t + s$, where $t + s$ is a concatenation of the strings $t$ and $s$; - he selects an arbitrary letter of $s$ and removes from $s$ all its occurrences (\textbf{the selected letter must occur in the string $s$ at the moment of performing this action}). Polycarp performs this sequence of actions \textbf{strictly} in this order. Note that after Polycarp finishes the actions, the string $s$ will be empty and the string $t$ will be equal to some value (that is undefined and depends on the order of removing). E.g. consider $s$="abacaba" so the actions may be performed as follows: - $t$="abacaba", the letter 'b' is selected, then $s$="aacaa"; - $t$="abacabaaacaa", the letter 'a' is selected, then $s$="c"; - $t$="abacabaaacaac", the letter 'c' is selected, then $s$="" (the empty string). You need to restore the initial value of the string $s$ using only the final value of $t$ and find the order of removing letters from $s$.
Suppose it's given a string $t$ for which the answer exists. Consider the last non-empty value of $s$. Only $1$ letter occurs in the value and the letter is the last removed letter. At the same time, the value of $s$ is a suffix of $t$ so the last character of $t$ is the last removed letter. Consider the second-last non-empty value of $s$. It contains exactly $2$ distinct letters so that one of them is the last removed letter and the other is the second-last removed letter. The concatenation of the second-last and the last values of $s$ is a suffix of $t$ consisting only of the letters. Therefore, the letter which occurrence is the last of the occurrences of all letters except the last removed one is the second-last removed letter. Considering so other values, we are proving that the order of removing the letters is the order the last occurrences of the letters occur in the string $t$. Suppose $k$ is the number of the step in which some letter was removed, $c_k$ is the number of occurrences of the letter in the initial value of $s$. The letter occurs in exactly $k$ different values of $s$. In each of them, the letter occurs exactly $c_k$ times. So the letter occurs in $t$ exactly $d_k = k \cdot c_k$ times. Therefore, using the number of the step ($k$) in which the letter was removed and the number of the letter's occurrences in $t$ ($d_k$), let's calculate the number of the letter's occurrences in the string $s$: $c_k = \frac{d_k}{k}$. If $d_k$ isn't completely divisible by $k$, there's no solution. The sum of all $c_k$ of all letters occurring in $t$ is the length of the initial value of $s$. Since the initial value is a prefix of $t$, the possible answer is the prefix of $t$ having the length equal to the sum of all $c_k$. Before outputting the prefix, check that you can get from the supposed value of the string $s$ the string $t$. Checking it, you may use the algorithm from the statement. If the resulting string is equal to $t$, the answer is correct and must be outputted, otherwise, there's no solution.
[ "binary search", "implementation", "sortings", "strings" ]
1,800
#include <bits/stdc++.h> using namespace std; int cntsrc[26]; // don't forget to memset it but not cnt int* cnt = cntsrc - 'a'; // so cnt['a'] = cntsrc[0] and so on pair<string, string> decrypt(string s) { string order; reverse(s.begin(), s.end()); for (auto c : s) { if (!cnt[c]) order.push_back(c); cnt[c]++; } int m = order.length(); int originalLength = 0; for (int i = 0; i < m; i++) originalLength += cnt[order[i]] / (m - i); reverse(order.begin(), order.end()); return { string(s.rbegin(), s.rbegin() + originalLength), order }; } string encrypt(pair<string, string> p) { string result = p.first; for (auto c : p.second) { string temp; for (auto d : p.first) if (d != c) { temp.push_back(d); result.push_back(d); } p.first = temp; } return result; } int main() { int t; cin >> t; while (t--) { memset(cntsrc, 0, sizeof(cntsrc)); string s; cin >> s; auto ans = decrypt(s); auto check = encrypt(ans); if (check == s) cout << ans.first << ' ' << ans.second << '\n'; else cout << "-1\n"; } return 0; }
1560
F1
Nearest Beautiful Number (easy version)
It is a simplified version of problem F2. The difference between them is the constraints (F1: $k \le 2$, F2: $k \le 10$). You are given an integer $n$. Find the minimum integer $x$ such that $x \ge n$ and the number $x$ is $k$-beautiful. A number is called $k$-beautiful if its decimal representation having no leading zeroes contains no more than $k$ different digits. E.g. if $k = 2$, the numbers $3434443$, $55550$, $777$ and $21$ are $k$-beautiful whereas the numbers $120$, $445435$ and $998244353$ are not.
Suppose the number $n$ contains $m$ digits. The desired number $x$ isn't greater than the number consisting of $m$ digits $9$. This number is $1$-beautiful whereas any $1$-beautiful number is at the same time $k$-beautiful, so $x$ contains at most $m$ digits. At the same time, $x \ge n$ so $x$ contains at least $m$ digits. Therefore, the desired number contains exactly $m$ digits. Suppose $k = 1$. There are exactly $9$ $k$-beautiful numbers containing exactly $m$ digits. To get the answer fast, it's possible to consider all these numbers. Suppose $k = 2$. If $n$ is already $k$-beautiful, let's output it. Otherwise, let's initialize the answer by the value as if $k = 1$. Let's iterate two digits $a$ and $b$ such that $a < b$. Let's search for the answer by considering the strings consisting only of digits $a$ and $b$. Let's iterate a prefix of $n$ starting from the empty one so that the prefix will be the prefix of $x$. This prefix must contain only the digits $a$ and $b$. Consider the leftmost digit that doesn't belong to the prefix. Let's try to increase it. If the digit is less than $a$, a possible answer is a number such that it has the considered prefix and all other digits are equal to $a$. Let's update the answer by this number (i.e. if the found number is less than the best previously found answer, let's set the answer to the found number). If the considered digit is at least $a$ and is less than $b$, let's update the answer by the number such that it has the considered prefix, the digit $b$ follows the prefix, and all other digits are equal to $a$.
[ "binary search", "bitmasks", "brute force", "constructive algorithms", "dfs and similar", "greedy" ]
1,900
#include <bits/stdc++.h> using namespace std; string solve1(string n) { string res(n.length(), '9'); for (char c = '8'; c >= '0'; c--) { string t(n.length(), c); if (t >= n) res = t; } return res; } string solve2(string n) { string res = solve1(n); for(char a = '0'; a <= '9'; a++) for (char b = a + 1; b <= '9'; b++) { bool n_ok = true; for (int i = 0; i < n.length(); i++) { if (n[i] < b) { string t = n; if (t[i] < a) t[i] = a; else t[i] = b; for (int j = i + 1; j < n.length(); j++) t[j] = a; if (res > t) res = t; } if(n[i] != a && n[i] != b) { n_ok = false; break; } } if (n_ok) return n; } return res; } string solve() { string n; int k; cin >> n >> k; if (k == 1) return solve1(n); else return solve2(n); } int main() { int t; cin >> t; while (t--) cout << solve() << '\n'; return 0; }
1560
F2
Nearest Beautiful Number (hard version)
It is a complicated version of problem F1. The difference between them is the constraints (F1: $k \le 2$, F2: $k \le 10$). You are given an integer $n$. Find the minimum integer $x$ such that $x \ge n$ and the number $x$ is $k$-beautiful. A number is called $k$-beautiful if its decimal representation having no leading zeroes contains no more than $k$ different digits. E.g. if $k = 2$, the numbers $3434443$, $55550$, $777$ and $21$ are $k$-beautiful whereas the numbers $120$, $445435$ and $998244353$ are not.
Suppose the number $n$ contains $m$ digits and its decimal representation is $d_1d_2 \dots d_m$. The desired number $x$ isn't greater than the number consisting of $m$ digits $9$. This number is $1$-beautiful whereas any $1$-beautiful number is at the same time $k$-beautiful, so $x$ contains at most $m$ digits. At the same time, $x \ge n$ so $x$ contains at least $m$ digits. Therefore, the desired number contains exactly $m$ digits. Since we search for the minimum $x$, we need to minimize first of all the first digit, only then the second digit, etc. Therefore, we need to find a prefix of the decimal representation of $n$ such that is a prefix of the decimal representation of $x$. Let's do it greedily. Short solution, works in $O(m^2)$ Let's find the maximum prefix of $n$ such that contains no more than $k$ distinct numbers. Suppose the prefix has the length $p$. If $p = m$, then $n$ is already $k$-beautiful, let's output it. Otherwise, let's increase the prefix like a number by $1$, e.g. if $n = 1294$ and $p = 3$, then we increase $129$ by $1$, the resulting prefix is $130$. All other digits ($d_{p + 2}, d_{p + 3}, \dots, d_m$), let's set to zeroes (e.g. if $n = 1294$ and $p = 3$, then $n$ will be turned into $1300$). The answer for the old $n$ is the answer for the new $n$. To get the answer for the new $n$, let's start the described procedure once again preparing the new $n$. Long solution, works in $O(mk)$ Let's find the maximum prefix of $n$ such that contains no more than $k$ distinct numbers. It's possible to do using a $map$ in which for each digit (the key) the number of its occurrences in the prefix is stored. For an empty prefix, the $map$ is empty. If we increase the prefix length by $1$, we need to check that $map$ contains no more than $k$ keys and add a new key with the value $1$ or increase the value of an existing key. If the length of the found prefix is equal to the length of the whole decimal representation, the given number is already $k$-beautiful so the answer is $n$. Otherwise, the found prefix may not be a prefix of the desired number. Let's change the digits of the decimal representation of $n$ to turn it into the desired number $x$. Let's start the following procedure: suppose we consider a prefix with the length equal to $p$. First, let's find out, is it possible to increase the first element out of the prefix (i. e. $d_{p + 1}$). We need to do it because if we consider the length $p$, then the prefix with the length $p + 1$ cannot be unchanged so the element $d_{p + 1}$ must be changed whereas it cannot be decreased because, in this case, we will get the number which is less than $n$. If we can increase the element $d_{p + 1}$ so that the prefix with the length $p + 1$ has at most $k$ distinct digits, the only thing that is remained to do is to fill the remaining digits $d_{p + 2}, d_{p + 3}, \dots d_m$ somehow greedily and output the result. If we cannot increase the element $d_{p + 1}$, let's decrease the length of the considered prefix $p$ by $1$ updating the $map$ (let's decrease the value corresponding to the key $d_{p}$ by $1$, then, if it's equal to $0$, we remove the key $d_{p}$ from the $map$). Consider, how and under what conditions we can change $d_{p + 1}$ and the following digits: If $d_{p + 1} = 9$, it's impossible. Suppose the considered prefix contains less than $k$ distinct digits (the number of the keys in the $map$ is less than $k$). In this case, we can replace the digit $d_{p + 1}$ with the value $d_{p + 1} + 1$ so the prefix with the length $p + 1$ will not contain more than $k$ distinct elements because the prefix with the length $p$ doesn't contain more than $k - 1$ distinct elements. If the prefix with the length $p + 1$ still contains less than $k$ distinct numbers, let's replace the remaining digits ($d_{p + 2}$, $d_{p + 3}$, etc) with $0$. Otherwise, we can replace them with the minimum digit that occurs in the prefix with the length $p + 1$ (it may be $0$). Suppose the considered prefix contains exactly $k$ distinct digits. So let's find the minimum digit that occurs in the prefix with the length $p$ and is greater than $d_{p + 1}$. If such digit exists, let's replace $d_{p + 1}$ with it, and all following digits with the minimum digit that occurs in the prefix with the length $p + 1$. Otherwise, the element $d_{p + 1}$ cannot be increased. The converted by the procedure $n$ is the answer.
[ "bitmasks", "brute force", "constructive algorithms", "dfs and similar", "dp", "greedy" ]
2,100
#include <bits/stdc++.h> using namespace std; string solveFillingSuffix(string& n, char d, int from) { for (int i = from; i < n.length(); i++) n[i] = d; return n; } void decAt(map<char, int>& d, char c) { if (d.count(c)) { d[c]--; if (d[c] == 0) d.erase(c); } } string solve() { string n; int k; cin >> n >> k; map<char, int> d; int pref = 0; while (pref < n.length()) { if (d.count(n[pref])) { d[n[pref++]]++; continue; } if (d.size() == k) break; d[n[pref++]]++; } if (pref == n.length()) return n; while (true) { if (n[pref] == '9') { decAt(d, n[--pref]); continue; } if (d.size() < k) { d[++n[pref]]++; return solveFillingSuffix(n, d.size() < k ? '0' : d.begin()->first, pref + 1); } auto it = d.upper_bound(n[pref]); if (it == d.end()) { decAt(d, n[--pref]); continue; } n[pref] = it->first; return solveFillingSuffix(n, d.begin()->first, pref + 1); } } int main() { int t; cin >> t; while (t--) cout << solve() << '\n'; return 0; }
1561
A
Simply Strange Sort
You have a permutation: an array $a = [a_1, a_2, \ldots, a_n]$ of distinct integers from $1$ to $n$. The length of the permutation $n$ is odd. Consider the following algorithm of sorting the permutation in increasing order. A helper procedure of the algorithm, $f(i)$, takes a single argument $i$ ($1 \le i \le n-1$) and does the following. If $a_i > a_{i+1}$, the values of $a_i$ and $a_{i+1}$ are exchanged. Otherwise, the permutation doesn't change. The algorithm consists of iterations, numbered with consecutive integers starting with $1$. On the $i$-th iteration, the algorithm does the following: - if $i$ is odd, call $f(1), f(3), \ldots, f(n - 2)$; - if $i$ is even, call $f(2), f(4), \ldots, f(n - 1)$. It can be proven that after a finite number of iterations the permutation will be sorted in increasing order. After how many iterations will this happen for the first time?
The described sorting algorithm is similar to Odd-even sort. In this problem, it's enough to carefully implement the process described in the problem statement. Here is one sample implementation in C++: To estimate the complexity of this solution, we need to know the maximum number of iterations required to sort a permutation of length $n$. It turns out that this number is equal to exactly $n$, thus the complexity of the algorithm is $O(n^2)$. This is intuitive because the algorithm looks similar to bubble sort that requires $n$ iterations too, or you can directly check that sorting $[n, n-1, \ldots, 1]$ requires $n$ iterations and reason that "more sorted" sequences can't require more iterations than "less sorted" sequences, and $[n, n-1, \ldots, 1]$ is naturally the "least sorted" sequence of them all. For a formal proof see e.g. the linked Wikipedia page. The proof also follows from the editorial of problem F in Div. 1. If you have a simpler proof, please share in comments!
[ "brute force", "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main() { int tt; cin >> tt; while (tt–) { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } int ans = 0; while (!is_sorted(a.begin(), a.end())) { for (int i = ans % 2; i + 1 < n; i += 2) { if (a[i] > a[i + 1]) { swap(a[i], a[i + 1]); } } ans += 1; } cout << ans << endl; } return 0; }
1561
C
Deep Down Below
In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor. On the current level, the hero is facing $n$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $i$, he will have to fight $k_i$ monsters in a row: first a monster with armor $a_{i, 1}$, then a monster with armor $a_{i, 2}$ and so on, finally, a monster with armor $a_{i, k_i}$. The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order. Each time the hero beats a monster, the hero's power increases by $1$. Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.
Consider a single cave $i$. Suppose that the hero enters the cave with power $x$. To beat the first monster, $x$ has to be greater than $a_{i, 1}$. After that, the hero's power will increase to $x+1$, and to beat the second monster, $x+1$ has to be greater than $a_{i, 2}$. Continuing this reasoning, we can write down $k_i$ inequalities: $x > a_{i, 1}$; $x + 1 > a_{i, 2}$; $x + 2 > a_{i, 3}$; ... $x + (k_i - 1) > a_{i, k_i}$. Let $b_i = \max(a_{i, 1}, a_{i, 2} - 1, a_{i, 3} - 2, \ldots, a_{i, k_i} - (k_i - 1))$. The system of inequalities above is equivalent to a single inequality: $x > b_i$. Thus, the hero can enter cave $i$ with power $x$ if and only if $x > b_i$, and the hero's power will increase by $k_i$. Armed with this knowledge, can we determine the best order to visit the caves for the hero? It turns out it's always best to enter the caves in non-decreasing order of $b_i$. Indeed, if the hero can enter cave $i$, he should always do that because entering a cave never makes things worse. If the hero enters a cave with greater $b$ right before a cave with smaller $b$, he might enter these caves in reverse order as well. Let's sort the caves accordingly and assume $b_1 \le b_2 \le \ldots \le b_n$. What is the smallest power the hero can start the level with? We can use the same reasoning that we used for a single cave. Suppose the hero starts the level with power $x$. To enter the first cave, $x$ has to be greater than $b_1$. After that, the hero's power will increase to $x+k_1$, and to enter the second cave, $x+k_1$ has to be greater than $b_2$. Continuing this reasoning, we can write down $n$ inequalities: $x > b_1$; $x + k_1 > b_2$; $x + k_1 + k_2 > b_3$; ... $x + \sum \limits_{i=1}^{n-1} k_i > b_n$. Let $p = \max(b_1, b_2 - k_1, b_3 - (k_1 + k_2), \ldots, b_n - \sum \limits_{i=1}^{n-1} k_i)$. The system of inequalities above is equivalent to a single inequality: $x > p$. Thus, the answer to the problem is $p + 1$. Alternatively, instead of solving the inequalities, one can use binary search on $x$.
[ "binary search", "greedy", "sortings" ]
1,300
null
1562
A
The Miracle and the Sleeper
You are given two integers $l$ and $r$, $l\le r$. Find the largest possible value of $a \bmod b$ over all pairs $(a, b)$ of integers for which $r\ge a \ge b \ge l$. As a reminder, $a \bmod b$ is a remainder we get when dividing $a$ by $b$. For example, $26 \bmod 8 = 2$.
It's not hard to see that if $l \le \lfloor \frac{r}{2} \rfloor + 1$, then $r \bmod (\lfloor \frac{r}{2} \rfloor + 1) = \lfloor \frac{r-1}{2} \rfloor$. It can be shown that the maximal possible answer. At the same time, let the segment not contain number $\lfloor \frac{r}{2} \rfloor + 1$, that is, $l > \lfloor \frac{r}{2} \rfloor + 1$. Then we can show that the maximal answer is $r \bmod l = r-l$. Asymptotics: $O(1)$ per test case.
[ "greedy", "math" ]
800
#include <iostream> using namespace std; int l, r; void solve() { if (r < l * 2) { cout << r - l << endl; } else { cout << (r - 1) / 2 << endl; } } int main() { int t; cin >> t; while (t--) { cin >> l >> r; solve(); } }
1562
B
Scenes From a Memory
During the hypnosis session, Nicholas suddenly remembered a positive integer $n$, which \textbf{doesn't contain zeros in decimal notation}. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes \textbf{not prime}, that is, either composite or equal to one? For some numbers doing so is impossible: for example, for number $53$ it's impossible to delete some of its digits to obtain a not prime integer. However, \textbf{for all $n$ in the test cases of this problem, it's guaranteed that it's possible to delete some of their digits to obtain a not prime number}. Note that you cannot remove all the digits from the number. A prime number is a number that has no divisors except one and itself. A composite is a number that has more than two divisors. $1$ is neither a prime nor a composite number.
Let's show that if a number has three digits, you can always remove at least one from it to get a number that is not prime. This can be proved by a simple brute-force search of all numbers with three digits, but we'll try to do it without a brute-force search. In fact, if a number contains the digits '1', '4', '6', '8' or '9', then that one digit is the answer, because $1$, $4$, $6$, $8$ and $9$ are not prime numbers. Now let's see what happens if the number doesn't have those digits. Then, if the number has two identical digits, we have found an answer of size two - the number of two identical digits ($22$, $33$, $55$, or $77$) is divisible by $11$. Also, if the digits $2$ or $5$ are not at the beginning of the number, we again have found an answer of size two - the number of two digits ending in $2$ or $5$ is not prime. If none of the above cases worked, then we find that a three-digit number has one of the following values: $237$, $273$, $537$, $573$. It is not difficult to see that these numbers have two digits, which form a number, that is divisible by three. Thus, the maximum answer is two, that is, you can leave no more than two digits in the number. You can find these digits by considering the above cases, or you can just try. It can be shown that such a brute-force solution will work for $O(k)$. Asymptotics: $O(k)$ per test case. Try to prove that the author's solution works for $O(k)$ for one test case. Finding an answer consisting of one digit works in $O(k)$. Now let's see how long the loop takes to complete. Indeed, it is easy to see that once the pairs of indexes $(0,1)$, $(0,2)$, and $(1,2)$ are considered, an answer will always be found. This is so because in any number of three digits you can find an answer consisting of two digits (this was proved earlier). So this is equivalent to removing all but the first three digits, and then solving the problem for them (assuming that the length of the optimal answer is two). Try to think of a way to search index pairs and a test such that this search works for $O(k^2)$ per test case. Let's take the string \t{3737 \ldots 37} as a string. We will search pairs of indices in the following way: first we will search all pairs of indices with different parities, and then all pairs of indices with the same parity. It is easy to see that such a search will work for $O(k^2)$ for one test case, because all pairs of indices with different parity will give numbers $37$ and $73$, which are prime, and there are $O(k^2)$ such pairs.
[ "brute force", "constructive algorithms", "implementation", "math", "number theory" ]
1,000
#include <iostream> using namespace std; int n; string s; bool prime[100]; void solve() { for (int i = 0; i < n; i++) { if (s[i] == '1' || s[i] == '4' || s[i] == '6' || s[i] == '8' || s[i] == '9') { cout << 1 << endl; cout << s[i] << endl; return; } } for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (!prime[(s[i] - '0') * 10 + (s[j] - '0')]) { cout << 2 << endl; cout << s[i] << s[j] << endl; return; } } } exit(42); } int main() { for (int i = 2; i < 100; i++) { prime[i] = true; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { prime[i] = false; } } } int t; cin >> t; while (t--) { cin >> n; cin >> s; solve(); } }
1562
C
Rings
\begin{quote} {{\small Frodo was caught by Saruman. He tore a pouch from Frodo's neck, shook out its contents —there was a pile of different rings: gold and silver..."How am I to tell which is the One?!" the mage howled. "Throw them one by one into the Cracks of Doom and watch when Mordor falls!"}} \end{quote} Somewhere in a parallel Middle-earth, when Saruman caught Frodo, he only found $n$ rings. And the $i$-th ring was either gold or silver. For convenience Saruman wrote down a binary string $s$ of $n$ characters, where the $i$-th character was 0 if the $i$-th ring was gold, and 1 if it was silver. Saruman has a magic function $f$, which takes a binary string and returns a number obtained by converting the string into a binary number and then converting the binary number into a decimal number. For example, $f(001010) = 10, f(111) = 7, f(11011101) = 221$. Saruman, however, thinks that the order of the rings plays some important role. He wants to find $2$ pairs of integers $(l_1, r_1), (l_2, r_2)$, such that: - $1 \le l_1 \le n$, $1 \le r_1 \le n$, $r_1-l_1+1\ge \lfloor \frac{n}{2} \rfloor$ - $1 \le l_2 \le n$, $1 \le r_2 \le n$, $r_2-l_2+1\ge \lfloor \frac{n}{2} \rfloor$ - Pairs $(l_1, r_1)$ and $(l_2, r_2)$ are distinct. That is, at least one of $l_1 \neq l_2$ and $r_1 \neq r_2$ must hold. - Let $t$ be the substring $s[l_1:r_1]$ of $s$, and $w$ be the substring $s[l_2:r_2]$ of $s$. Then \textbf{there exists non-negative integer $k$, such that $f(t) = f(w) \cdot k$.} Here substring $s[l:r]$ denotes $s_ls_{l+1}\ldots s_{r-1}s_r$, and $\lfloor x \rfloor$ denotes rounding the number down to the nearest integer. Help Saruman solve this problem! It is guaranteed that under the constraints of the problem at least one solution exists.
Let us first consider the boundary case. Let a string (hereafter we will assume that the string length $n$) consists of only ones. Then we can output the numbers $1$ $n-1$ $2$ $n$ as the answer, since there will be the same substrings. Now let's figure out what to do in the other case. Let's call the substring [$1$ ... $\lfloor\frac{n}{2}\rfloor$] the left half of the string, and the substring [$\lfloor\frac{n}{2}\rfloor+1$ ... $n$] the right half of the string. Then there are two cases: There is $0$ in the left half of the row, and its position is $k$. Then we can take the numbers $k$ $n$ $k+1$ $n$ as the answer, since they are the same numbers, just the second number has an extra leading zero. There is $0$ in the right half of the row, and its position is $k$. Then you can take the numbers $1$ $k$ $1$ $k-1$ as the answer, since the second number - is the first number multiplied by two (multiplying by two in binary is equivalent to adding one zero to the right). Asymptotics: $O(n)$ per test case. Think about how the problem would be solved if any other number system was chosen, given all the previous conditions (the string consists of the digits $0$ and $1$, the string contains at least one one). The solution would not change in any way. In fact, in a number system with base $k$, adding a zero to the left side does not change the number (multiplication by $1$), but adding a zero to the right side increases the number $k$ times (multiplication by $k$). Think about how the problem would be solved if the condition sounded like this: \textit{it is necessary that $f(t)$ is divisible by $f(w)$. There are at least one one in the array. Zero is divisible by all numbers, but no number is divisible by zero. Zero is not divisible by zero.} In fact, the problem gets a little more complicated. For example, consider this test: \t{111000000}. In this case, we could not output $4$ $9$ $5$ $9$ because zero is not divisible by zero. We will perform the old solution, but check that we are not trying to divide zero by zero (if we divide something by zero, we will swap the numbers). And if the answer is not found, then either the whole left half of the string consists of zeros, or the whole right half. Let the leftmost unit have position $p1$, and the rightmost unit ~--- position $p2$. Then in the first case you can output $1$ $p2$ $2$ $p2$, and in the second case~--- $p1$ $n$ $p1$ $n-1$. It is not hard to see that such a solution will always find the answer. In fact, we can solve the problem even simpler: when we meet zero in the left half, we additionally check whether there is at least one one among the characters on the right. If there is, we print the answer, otherwise we move on. Similarly, when we encounter zero in the right half, we additionally check if there is at least one one among the characters on the left. We can show that this solution will also always find the answer. It is interesting that we have solved \textbf{a stronger version of the problem}, since the solution we obtained works correctly for the old problem as well.
[ "constructive algorithms", "math" ]
1,500
#include <iostream> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; bool solved = false; for (int i = 0; i < n; i++) { if (s[i] == '0') { solved = true; if (i >= n / 2) { cout << 1 << " " << i + 1 << " " << 1 << " " << i << endl; break; } else { cout << i + 2 << " " << n << " " << i + 1 << " " << n << endl; break; } } } if (!solved) { cout << 1 << " " << n - 1 << " " << 2 << " " << n << endl; } } }
1562
D1
Two Hundred Twenty One (easy version)
\textbf{This is the easy version of the problem. The difference between the versions is that the easy version does not require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.} Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine. The main element of this machine are $n$ rods arranged along one straight line and numbered from $1$ to $n$ inclusive. Each of these rods must carry an electric charge quantitatively equal to either $1$ or $-1$ (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero. More formally, the rods can be represented as an array of $n$ numbers characterizing the charge: either $1$ or $-1$. Then the condition must hold: $a_1 - a_2 + a_3 - a_4 + \ldots = 0$, or $\sum\limits_{i=1}^n (-1)^{i-1} \cdot a_i = 0$. Sparky charged all $n$ rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has $q$ questions. In the $i$th question Sparky asks: if the machine consisted only of rods with numbers $l_i$ to $r_i$ inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all. If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods. Help your friends and answer all of Sparky's questions!
Let's prove everything for a particular segment of length $n$. And at the end, we'll show how to quickly solve the problem for many segments. Let $n$ - the length of the segment, and let $a$ - the array corresponding to the segment ($a_i = 1$ if "+" is at the $i$th position in the segment, and $a_i = -1$ if "-" is at the $i$th position in the segment). Introduce a new array $b$, with $b_i$ being equal to the signed sum on the whole array if the $i$-th element was removed from it. Then: The parity of the length of the segment and the parity of the number of elements to be removed from it are the same. It is not difficult to show that $|b_i - b_{i+1}| = 0$ if $a_i = a_{i+1}$, or $|b_i - b_{i+1}| = 2$ otherwise. Proof of this fact: Let $a_i = a_{i+1}$. Then it is easy to see that when $a_i$ is removed, the segment will look exactly the same as when $a_{i+1}$ is removed. So $|b_i - b_{i+1}| = 0$. Now let $a_i \neq a_{i+1}$. Denote by $f(l,r)$ the sign-variable sum on the interval $l$ to $r$, taking into account the sign (i.e. if $l$ is odd, the first number is taken with the plus sign, otherwise with the minus sign). Then it is easy to see that $b_i = f(1,i-1) \pm a_{i+1} \mp f(i+2,n)$, and $b_{i+1} = f(1,i) \mp f(i+2,n)$. Hence, if we consider the two cases ($a_{i+1} = 1$ and $a_{i+1} = -1$), we see that $|b_i - b_{i+1}| = 2$. If $n$ is odd, then there exists such $k$ that $b_k = 0$. Let us prove this: If $b_1 = 0$ or $b_n = 0$, then the statement is proved. Now let $b_1 < 0$ and $b_n > 0$. Then, since the neighboring values in the array $b$ differ by no more than $2$, and all elements are even, then there is bound to be zero between the first and last element. The case $b_1 > 0, b_n < 0$ is proved similarly. If $n > 1$, then there cannot be such a case that $b_1 > 0$ and $b_n >0$, and there cannot be such a case that $b_1 < 0$ and $b_n < 0$. In fact, let the sign-variable sum of the whole segment be $s$. Then $b_1 = -s \pm 1$ and $b_n = s \pm 1$. Since $b_1$ and $b_n$ are even numbers, therefore either at least one of them is zero, or they are of different signs. Thus the final result is: if the sign-variable sum is already zero, output zero; otherwise, if the segment is of odd length, output $1$; otherwise, output $2$. To quickly determine the sign-variable sum, we use the prefix-sum. Asymptotics: $O(n + q)$ per test case.
[ "data structures", "dp", "math" ]
1,700
#include <iostream> using namespace std; int a[1000000 + 5], p[1000000 + 5]; int get_sum(int l, int r) { if (l > r) { return 0; } return (l % 2 == 1) ? p[r] - p[l - 1] : p[l - 1] - p[r]; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin>>t; while (t--) { int n, q; cin >> n >> q; string ss; cin >> ss; for (int i = 1; i <= n; i++) { a[i] = (ss[i - 1] == '+' ? 1 : -1); } p[0] = 0; for (int i = 1; i <= n; i++) { p[i] = p[i - 1] + (i % 2 == 1 ? a[i] : -a[i]); } for (int o = 0; o < q; o++) { int l, r; cin >> l >> r; if (get_sum(l, r) == 0) { cout << "0\n"; continue; } if ((r - l + 1) % 2 == 0) { cout << "2\n"; } else { cout << "1\n"; } } } }
1562
D2
Two Hundred Twenty One (hard version)
\textbf{This is the hard version of the problem. The difference between the versions is that the hard version does require you to output the numbers of the rods to be removed. You can make hacks only if all versions of the problem are solved.} Stitch likes experimenting with different machines with his friend Sparky. Today they built another machine. The main element of this machine are $n$ rods arranged along one straight line and numbered from $1$ to $n$ inclusive. Each of these rods must carry an electric charge quantitatively equal to either $1$ or $-1$ (otherwise the machine will not work). Another condition for this machine to work is that the sign-variable sum of the charge on all rods must be zero. More formally, the rods can be represented as an array of $n$ numbers characterizing the charge: either $1$ or $-1$. Then the condition must hold: $a_1 - a_2 + a_3 - a_4 + \ldots = 0$, or $\sum\limits_{i=1}^n (-1)^{i-1} \cdot a_i = 0$. Sparky charged all $n$ rods with an electric current, but unfortunately it happened that the rods were not charged correctly (the sign-variable sum of the charge is not zero). The friends decided to leave only some of the rods in the machine. Sparky has $q$ questions. In the $i$th question Sparky asks: if the machine consisted only of rods with numbers $l_i$ to $r_i$ inclusive, what minimal number of rods could be removed from the machine so that the sign-variable sum of charges on the remaining ones would be zero? \textbf{Also Sparky wants to know the numbers of these rods}. Perhaps the friends got something wrong, and the sign-variable sum is already zero. In that case, you don't have to remove the rods at all. If the number of rods is zero, we will assume that the sign-variable sum of charges is zero, that is, we can always remove all rods. Help your friends and answer all of Sparky's questions!
We will use the facts already obtained, given in the solution of problem D1. To quickly check the value of the sign-variable sum on the segment with deletion of one element, slightly modify the prefix-sum. We will not concentrate on this in detail; you can see how to make it in the solution. Now let's see how to search for a matching element inside an odd-length segment. We will do this with a binary search. Suppose initially $l = 1$, $r = n$, and we know that the numbers $b_1$ and $b_n$ are different signs, or one of them is zero. Now consider the following algorithm: Find $m$ equal to $\lfloor\frac{l+r}{2}\rfloor$. If $b_l = 0$, or $b_m = 0$, or $b_r = 0$, then the answer is found. Otherwise, either the numbers $b_l$ and $b_m$ have different signs, or the numbers $b_m$ and $b_r$ have different signs. In the first case, assign $r$ to $m$, in the second case, assign $l$ to $m$. This algorithm will stop sooner or later and produce an answer, since we know that the matching item exactly exists. This can be shown using the fact that $|b_i - b_{i+1}| \le 2$, and all $b_i$ are even. So finally we have the following solution: if the sign-variable sum is already zero, output zero; otherwise, if the segment is of odd length, search for a suitable element by the above algorithm; otherwise, take, for example, the left boundary of the segment as the first element to remove, and search for the second element using the above algorithm on the segment without a left element. Asymptotics: $O(n + q \cdot log(n))$ per test case. Is there a solution with asymptotics $O(n + q)$ for a single test case?
[ "data structures", "math" ]
2,200
#include <iostream> using namespace std; int a[1000000 + 5], p[1000000 + 5]; int get_sum(int l, int r) { if (l > r) { return 0; } return (l % 2 == 1) ? p[r] - p[l - 1] : p[l - 1] - p[r]; } int check_elimination(int l, int r, int m) { return ((m - l + 1) % 2 == 1) ? get_sum(l, m - 1) + get_sum(m + 1, r) : get_sum(l, m - 1) - get_sum(m + 1, r); } int get_sign(int m) { return m > 0 ? 1 : -1; } int calculate_odd_segment(int l, int r) { if (l == r) { return l; } int pos = 0; int lb = l; int rb = r; while (lb < rb) { int mb = (lb + rb) / 2; int lq = check_elimination(l,r,lb); int mq = check_elimination(l,r,mb); int rq = check_elimination(l,r,rb); if (lq == 0) { pos = lb; break; } if (mq == 0) { pos = mb; break; } if (rq == 0) { pos = rb; break; } if (get_sign(lq) == get_sign(mq)) { lb = mb; } else { rb = mb; } } return pos; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int t; cin>>t; while (t--) { int n, q; cin >> n >> q; string ss; cin >> ss; for (int i = 1; i <= n; i++) { a[i] = (ss[i - 1] == '+' ? 1 : -1); } p[0] = 0; for (int i = 1; i <= n; i++) { p[i] = p[i - 1] + (i % 2 == 1 ? a[i] : -a[i]); } for (int o = 0; o < q; o++) { int l, r; cin >> l >> r; if (get_sum(l, r) == 0) { cout << "0\n"; continue; } bool even = false; if ((r - l + 1) % 2 == 0) { even = true; l++; } int pos = calculate_odd_segment(l, r); if (even) { cout << "2\n" << l - 1 << " "<< pos << '\n'; } else { cout << "1\n" << pos << '\n'; } } } }
1562
E
Rescue Niwen!
\begin{quote} {{\small Morning desert sun horizonRise above the sands of time...}} \hfill {\small Fates Warning, "Exodus"} \end{quote} After crossing the Windswept Wastes, Ori has finally reached the Windtorn Ruins to find the Heart of the Forest! However, the ancient repository containing this priceless Willow light did not want to open! Ori was taken aback, but the Voice of the Forest explained to him that the cunning Gorleks had decided to add protection to the repository. The Gorleks were very fond of the "string expansion" operation. They were also very fond of increasing subsequences. Suppose a string $s_1s_2s_3 \ldots s_n$ is given. Then its "expansion" is defined as the sequence of strings $s_1$, $s_1 s_2$, ..., $s_1 s_2 \ldots s_n$, $s_2$, $s_2 s_3$, ..., $s_2 s_3 \ldots s_n$, $s_3$, $s_3 s_4$, ..., $s_{n-1} s_n$, $s_n$. For example, the "expansion" the string 'abcd' will be the following sequence of strings: 'a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'. To open the ancient repository, Ori must find the size of the largest increasing subsequence of the "expansion" of the string $s$. Here, strings are compared lexicographically. Help Ori with this task! A string $a$ is lexicographically smaller than a string $b$ if and only if one of the following holds: - $a$ is a prefix of $b$, but $a \ne b$; - 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$.
The constraints on the problem were chosen so that solutions slower than $O(n^2 \cdot log(n))$ would not get AC, or would get with difficulty. The solution could be, for example, to sort all substrings by assigning numbers to them, and then find the largest increasing subsequence in the resulting array. Let us describe the solution for $O(n^2)$. The most important thing required for the solution is to understand what the largest increasing subsequence should look like. Let $s$ - a string, and $n$ - the length of the string $s$. It can be shown that if the largest increasing subsequence has a substring [$l$ ... $r$], then it also has a substring [$l$ ... $n$]. I will not give a formal proof, I will only give the key idea. Let the increasing subsequence first have the string [$l_1$ ... $r_1$], and then the substring [$l_2$ ... $r_2$], with $r_1 \neq n$. It can be understood that if suffixes [$l_1$ ... $n$] and [$l_2$ ... $n$] have some common prefix, and it has already been included in the largest increasing subsequence, then we can <<drop>> the prefixes of the suffix [$l_1$ . . $n$], and instead of them write exactly the same suffix prefixes of [$l_2$ ... $n$], and the size of the increasing subsequence will not change, and the condition above will be satisfied. If, however, the suffixes [$l_1$ ... $n$] and [$l_2$ ... $n$] have no common prefix, then we could take the suffix itself [$l_2$ ... $n$] together with its prefixes, and the answer would only improve. Thus, the largest increasing subsequence looks like this: first comes some substring [$l_1$ ... $r_1$], followed by a substring [$l_1$ ... $r_1 + 1$], and so on, ending with the suffix [$l_1$ ... $n$]. After that comes some substring [$l_2$ ... $r_2$], followed by a substring [$l_2$ ... $r_2 + 1$], and so on, ending with the suffix [$l_2$ ... $n$], and so on. Moreover, knowing which suffixes are included in this subsequence, we can establish all other substrings. Indeed, let the suffixes [$l_1$ ... $n$] and [$l_2$ ... $n$] be included in the sequence, and $l_1$ < $l_2$. Then it is not difficult to see that the suffix prefixes [$l_2$ ... $n$] can be typed greedily, namely, to take all substring [$l_2$ ... $k$] such that they are larger than the suffix [$l_1$ ... $n$]. Note that if the substring [$l_2$ ... $m$] is larger than the suffix [$l_1$ ... $n$], then the substring [$l_2$ ... $m+1$] is also larger than the suffix [$l_1$ ... $n$]. And so, we can use the following algorithm to find out $r_2$, that is, to find out which suffix prefix [$l_2$ ... $n$] to start typing the subsequence. Let $d_{l_1,l_2}$ - be the size of the largest common prefix of suffixes [$l_1$ ... $n$] and [$l_2$ ... $n$]. Then it is easy to see that if the suffix [$l_2$ ... $n$] is larger than the suffix [$l_1$ ... $n$], then the appropriate $r_2$ is $d_{l_1,l_2} + l_2$, which means that you must start typing all substrings, starting from the one that differs from the largest common prefix of the two suffixes. So now we are left with two problems. The first is - you have to learn to quickly recognize the greatest common prefix of the two suffixes. The second is - to write a DP that would allow you to recognize the answer. Let's see how to solve the first problem. You can use different string algorties, such as a suffix array. Or we can write a simple DP that calculates an array $d$ of the largest common prefixes over $O(n^2)$. The transitions in this DP and its implementation can be seen in the author's solution code (lines 37-48). Now about the DP that calculates the answer. Let us use the facts above and do the following. Let $dp_i$ denote the size of the answer if the last substring in it is the suffix [$i$ ... $n$]. Let $dp_1 = n$, and then $dp_i = n - i + 1$. Now let's do the following. We will go through $i$ from $2$ to $n$, doing the following simple steps: for each $j$ from $1$ to $i-1$ ($j$ denotes the previous suffix in the answer) we will check how many substring of the suffix [$i$ ... $n$] we can take: if the suffix [$i$ ... $n$] is larger than the suffix [$j$ ... $n$], we calculate this number with the above described algorithm, using the $d$ array of largest common prefixes. Otherwise, we will not update, because the suffix [$i$ ... $n$] is less than or equal to the suffix [$j$ ... $n$], we cannot take it in response. It is not difficult to guess that the answer is maximal in all $dp_i$. Thus, the problem is solved using two uncomplicated dynamics. Asymptotics: $O(n^2)$ per test case. As far as I know, using trie, you can sort all substrings of a given string in $O(n^2)$. Also, as far as I know, in C++ programming language std::lower_bound works so fast that in an array of size $1.25 \cdot 10^7$ the same number of std::lower_bound operations is done in a little less than a second. It is also known that std::lower_bound can be used to write a search for the largest increasing subsequence in an array. The question is: can we use this to write a $O(n^2 \cdot log(n))$ solution that passes the tests?
[ "dp", "greedy", "string suffix structures", "strings" ]
2,500
#include <iostream> using namespace std; int16_t lcp[10000 + 5][10000 + 5]; int dp[10000 + 5]; bool is_greater(const string& s, int x, int y) { if (lcp[x][y] == static_cast<int>(s.size()) - x) { return false; } return s[x + lcp[x][y]] > s[y + lcp[x][y]]; } int get_score(const string& s, int x, int y) { if (is_greater(s, x, y)) { return dp[y] + static_cast<int>(s.size()) - x - lcp[x][y]; } return 0; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; if (s.size() != n) return 42; for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { lcp[i][j] = 0; } } for (int i = n - 1; i >= 0; i--) { for (int j = n - 1; j >= 0; j--) { if (i == j) { lcp[i][j] = n - i; } else if (s[i] != s[j]) { lcp[i][j] = 0; } else { lcp[i][j] = lcp[i + 1][j + 1] + 1; } } } int ans = n; dp[0] = n; for (int i = 1; i < n; i++) { dp[i] = n - i; for (int j = 0; j < i; j++) { dp[i] = max (dp[i], get_score(s, i, j)); } ans = max(ans, dp[i]); } cout << ans << '\n'; } }
1562
F
Tubular Bells
Do you know what tubular bells are? They are a musical instrument made up of cylindrical metal tubes. In an orchestra, tubular bells are used to mimic the ringing of bells. Mike has tubular bells, too! They consist of $n$ tubes, and each of the tubes has a length that can be expressed by a integer from $l$ to $r$ inclusive. It is clear that the lengths of all the tubes are different (it makes no sense to make the same tubes). It is also known that $r-l+1 = n$. Formally, we can say that Mike's tubular bells are described by a permutation $a$ of length $n$ that contains all numbers from $l$ to $r$ inclusive, with $a_i$ denoting the length of the $i$-th tube. You are offered an interesting task: to guess what Mike's instrument looks like. Simply, you must guess the permutation. Mike won't tell you $l$ or $r$. He will only tell you $n$, and will allow you to ask no more than $n + 5000$ queries. In each query, you name two positive integers $x$, $y$ such that $1 \le x, y \le n, x \neq y$. In response to this query, the program written by Mike will give you $\mathrm{lcm}(a_x, a_y)$, where $\mathrm{lcm}(c,d)$ denotes the least common multiple of $c$ and $d$. Solve Mike's problem!
As I know, there are simpler solutions to this problem, but I will describe my solution. We can assume the whole array is randomly permutated, because we can make queries by renumbering it. We also pre-calculate all prime numbers smaller than $200000$. Let us denote something: $n$ - the number of numbers in the array, $a$ - the array itself, $l$ - the smallest value in the array, $r$ - the largest value in the array. So let's look at three cases: $n < 100$. We use the following simple solution: find out the lcm of all pairs of numbers. The greatest of these values will give us the pair of numbers $r-1$ and $r$. It is easy to find out which number $r$ is: all pairs of lcms of this number with others will be divisible by $r$. Now exclude $r$ from the array, and exclude all pairwise lcms with it. The highest value will give us a pair $r-1$ and $r-2$. Repeat this algorithm until all numbers are found. $100 \le n < 10000$. Solve for $\lceil\frac{3n}{2}\rceil$ queries. We ask for lcms of pairs of numbers: the first with the second, the third with the fourth, etc. Now we will look for the maximal prime multiplier in each such lcm. We will do it by using pre-calculated prime numbers. Since the array is randomly permutated, this will work in a reasonable amount of time. When we will find a pair of numbers with the greatest prime number, we easily find out which of these two numbers is the greatest prime: ask the lcm of one of the numbers in the pair with any other number and check if that lcm contains that greatest prime number. Finding the largest prime number, we easily find out the remaining array: $a_i = lcm(a_i, p) / p$, where $p$ -that prime number. $10000 \le n \le 100000$. Let $c$ = $500$. This number is chosen so that $c^2 > 200000$. We will search the array for any prime number that is greater than $c$. Do the following: randomly ask pairs of numbers until we find one that has only two prime numbers in the factorization of the lcm, and both of these prime numbers are greater than $c$. Let it be $p_1$ and $p_2$. Then one of the numbers in the pair - $p_1$ and the other - $p_2$. To find out which number is which, let's ask the lcm of one of them with some numbers chosen at random, and check what all those lcms are divisible by. If they are all divisible by $p_1$, then the chosen number is $p_1$, otherwise it is $p_2$. The chance of us guessing wrong is extremely small, because it requires that all the chosen numbers are divisible by $p_2$, and the chance of that is negligible.We have found a prime number greater than $c$. Let it be $p$. Now we can find out all the numbers that are not divisible by $p$ and greater than $c$. To do this, we ask all the NOCs of the number $p$ and the other numbers. And now, if $lcm(p, a_i) / p > c$, then $a_i = lcm(p, a_i) / p$. This is because if $a_i$ is divisible by $p$, then $lcm(p, a_i) / p = a_i / p \le c$. If $a_i$ is not divisible by $p$, then by dividing the lcm by $p$ we will find $a_i$, since the number $p$ is prime. Find the largest prime among the found numbers, and use it to find the remaining numbers as described above. Since we only need to find all numbers divisible by $p$ and all numbers not exceeding $c$, such queries will be no more than $100000 / 500 + 500 = 700$. We have found a prime number greater than $c$. Let it be $p$. Now we can find out all the numbers that are not divisible by $p$ and greater than $c$. To do this, we ask all the NOCs of the number $p$ and the other numbers. And now, if $lcm(p, a_i) / p > c$, then $a_i = lcm(p, a_i) / p$. This is because if $a_i$ is divisible by $p$, then $lcm(p, a_i) / p = a_i / p \le c$. If $a_i$ is not divisible by $p$, then by dividing the lcm by $p$ we will find $a_i$, since the number $p$ is prime. Find the largest prime among the found numbers, and use it to find the remaining numbers as described above. Since we only need to find all numbers divisible by $p$ and all numbers not exceeding $c$, such queries will be no more than $100000 / 500 + 500 = 700$.
[ "interactive", "math", "number theory", "probabilities" ]
2,900
#include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <ctime> #include <random> using namespace std; #define int long long mt19937 rnd(time(NULL)); int swnmb[1000000+5]; int swnmbr[1000000+5]; int b[1000000+5]; bool p[1000000+5]; vector<int> primes; int get_lcm(int x, int y) { cout<<"? "<<swnmb[x]<<" "<<swnmb[y]<<endl; int u; cin>>u; return u; } int max_fact(int d) { for (int j=(int)primes.size()-1; j>=0; j--) { if (d%primes[j]==0) return primes[j]; } } vector<int> fact(int d) { vector<int> ans; for (auto j:primes) { if (d==1) break; while (d%j==0) { ans.push_back(j); d/=j; } } return ans; } bool is_prime(int d) { for (int j=0; j<(int)primes.size(); j++) { if (primes[j]>500) return true; if (d%primes[j]==0) return false; } return true; } int paired_get_lcm[100+5][100+5]; void solve_quadric(int n) { for (int i=1; i<=n; i++) { for (int j=i+1; j<=n; j++) { paired_get_lcm[i][j]=get_lcm(i,j); paired_get_lcm[j][i]=paired_get_lcm[i][j]; } } int m1=0; int m2=0; int mx=0; for (int i=1; i<=n; i++) { for (int j=i+1; j<=n; j++) { if (paired_get_lcm[i][j]>mx) { mx=paired_get_lcm[i][j]; m1=i; m2=j; } } } int u=0; for (int i=1; i<=200000; i++) { if (mx==i*(i+1)) { u=i+1; break; } } for (int i=1; i<=n; i++) { if (i==m1||i==m2) continue; if (paired_get_lcm[m1][i]%u!=0) { swap(m1,m2); break; } } b[m1]=u; int pos=m2; for (int v=u-1; v>u-n-1; v--) { int m0=0; int mx=0; for (int j=1; j<=n; j++) { if (b[j]!=0) continue; if (pos==j) continue; if (paired_get_lcm[pos][j]>mx) { mx=paired_get_lcm[pos][j]; m0=j; } } b[pos]=v; pos=m0; } b[pos]=u-n+1; } void solve_pair(int n) { int maxnum=0; int maxpos=0; int notmaxpos=0; for (int i=1; i<=n; i+=2) { int u; if (i!=n) u=get_lcm(i,i+1); else u=get_lcm(i-1,i); int w=max_fact(u); if (w>maxnum) { maxnum=w; maxpos=min(i+1,n); } else { notmaxpos=i; } } int cur=get_lcm(notmaxpos,maxpos); if (cur%maxnum!=0) { maxpos--; } b[maxpos]=maxnum; for (int i=1; i<=n; i++) { if (i==maxpos) continue; int u=get_lcm(i,maxpos)/maxnum; b[i]=u; } } void print_ans(int n) { cout<<"! "; for (int i=1; i<=n; i++) { cout<<b[swnmbr[i]]; if (i!=n) cout<<" "; } cout<<endl; } int32_t main() { for (int i=2; i<=200000; i++) { if (p[i]) continue; for (int j=i*i; j<=200000; j+=i) { p[j]=true; } primes.push_back(i); } int t; cin>>t; while (t--) { int n; cin>>n; for (int i=1; i<=n; i++) { swnmb[i]=0; swnmbr[i]=0; b[i]=0; } for (int i=1; i<=n; i++) { swnmb[i]=i; } for (int i=1; i<=n*5; i++) { swap(swnmb[rnd()%n+1], swnmb[rnd()%n+1]); } for (int i=1; i<=n; i++) { swnmbr[swnmb[i]]=i; } if (n<100) { solve_quadric(n); print_ans(n); continue; } if (n<10000) { solve_pair(n); print_ans(n); continue; } int t1=0; int t2=0; int pos1=0; int pos2=0; for (int i=1; i<=4000; i++) { int i1=rnd()%n+1; int i2=rnd()%n+1; while (i1 == i2) { i2=rnd()%n+1; } vector<int> f=fact(get_lcm(i1,i2)); if (f.size()==2&&f[0]>500&&f[1]>500) { bool first1=true; bool first2=true; for (int j=0; j<100; j++) { int t=rnd()%n+1; while (t==i1||t==i2) { t=rnd()%n+1; } if (get_lcm(i1,t)%f[0]!=0) { first1=false; break; } } for (int j=0; j<100; j++) { int t=rnd()%n+1; while (t==i1||t==i2) { t=rnd()%n+1; } if (get_lcm(i1,t)%f[1]!=0) { first2=false; break; } } if (first1&&first2) { bool second1=true; for (int j=0; j<100; j++) { int t=rnd()%n+1; while (t==i1||t==i2) { t=rnd()%n+1; } if (get_lcm(i2,t)%f[1]!=0) { second1=false; break; } } if (second1) { t2=f[0]*f[1]; t1=f[0]; } else { t2=f[0]*f[1]; t1=f[1]; } pos1=i2; pos2=i1; } else { if (!first1) { t1=f[1]; t2=f[0]; } else { t1=f[0]; t2=f[1]; } pos1=i1; pos2=i2; } b[pos1]=t1; b[pos2]=t2; int posf=0; int maxf=0; for (int j=1; j<=n; j++) { if (j==i1||j==i2) continue; int u=get_lcm(pos1,j); if (u/t1>500) { b[j]=u/t1; if (is_prime(b[j])) { if (b[j]>maxf) { maxf=b[j]; posf=j; } } } } for (int j=1; j<=n; j++) { if (b[j]!=0) continue; b[j]=get_lcm(posf,j)/b[posf]; } break; } } print_ans(n); } }
1566
A
Median Maximization
You are given two positive integers $n$ and $s$. Find the maximum possible median of an array of $n$ \textbf{non-negative} integers (not necessarily distinct), such that the sum of its elements is equal to $s$. A \textbf{median} of an array of integers of length $m$ is the number standing on the $\lceil {\frac{m}{2}} \rceil$-th (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting from $1$. For example, a median of the array $[20,40,20,50,50,30]$ is the $\lceil \frac{m}{2} \rceil$-th element of $[20,20,30,40,50,50]$, so it is $30$. There exist other definitions of the median, but in this problem we use the described definition.
Which numbers smaller than the median should be taken? Which numbers bigger than the median should be taken? Greedy algorithm. Let's consider the array of $n$ elements in non-decreasing order. We can make numbers before the median equal to zero, after that we have $m = \lfloor {\frac{n}{2}} \rfloor + 1$ numbers, which sum should be $n$ and the minimal of them (i.e. median value) should be maximized. To do so, it is enough to make all these numbers equal $\lfloor {\frac{s}{m}} \rfloor$, and then add what's left to the last number ($s \bmod m$). It's easy to see that such array matches all the conditions and it is impossible to make median greater. If it's possible to make the median element $m > 1$ then you can make it $m - 1$. It is possible to make the median element any number from $0$ to some $M$. We can use the binary search for the answer. Let's run a binary search for the answer. This will work because if the answer $M$ then we can decrease the median element by $d$ and add $d$ to the max element, so we can get any median element from $1$ to $M$, but we can't get more than $M$. In the binary search we will use the greedy technique. All numbers less than the median can be $0$ and all numbers from the median should be at least $M$. So there are $m = \lfloor {\frac{n}{2}} \rfloor + 1$ numbers and each of them should be at least $M$ and we find the $M$ using the binary search. Number $M$ is reachable if $M \cdot m \leq s$ because we can add $s - M \cdot m$ to the maximal number and the median will be $M$. Otherwise, the median element can not be $M$.
[ "binary search", "greedy", "math" ]
800
t = int(input()) for test in range(t): n, s = map(int, input().split()) L = 0 R = 10**10 while R - L > 1: M = (L + R) // 2 m = n // 2 + 1 if m * M <= s: L = M else: R = M print(L)
1566
B
MIN-MEX Cut
A binary string is a string that consists of characters $0$ and $1$. Let $\operatorname{MEX}$ of a binary string be the smallest digit among $0$, $1$, or $2$ that does not occur in the string. For example, $\operatorname{MEX}$ of $001011$ is $2$, because $0$ and $1$ occur in the string at least once, $\operatorname{MEX}$ of $1111$ is $0$, because $0$ and $2$ do not occur in the string and $0 < 2$. A binary string $s$ is given. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring — the whole string. A string $a$ is a substring of a string $b$ if $a$ can be obtained from $b$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. What is the \textbf{minimal} sum of $\operatorname{MEX}$ of all substrings pieces can be?
The answer is never greater than $2$. If a string consists only of $1$, then the answer is $0$. If all zeroes are consequent, then the answer is $1$. The answer is never greater than $2$, because $\text{MEX}$ of the whole string is not greater than $2$. The answer is $0$ only if there are no zeroes in the string. Now we need to understand, when the answer is $1$ or when it is $2$. The sum of $\text{MEX}$ is $1$ only if all zeroes create a single segment without ones. Then we can cut this segment out, its $\text{MEX}$ is $1$, everything else is ones, their total $\text{MEX}$ is $0$. If the zeroes do not create a single segment without ones, the there are two such zeroes that there is a $1$ between them. Then either these zeroes are in a single segment with the $1$, so total $\text{MEX}$ is not less than $2$ or these zeroes are in different segments and the answer is still not less then $2$.
[ "bitmasks", "constructive algorithms", "dp", "greedy" ]
800
t = int(input()) for test in range(t): s = input() zeroes = s.count('0') if zeroes == 0: print(0) continue first = s.find('0') last = s.rfind('0') if last - first + 1 == zeroes: print(1) else: print(2)
1566
C
MAX-MEX Cut
A binary string is a string that consists of characters $0$ and $1$. A bi-table is a table that has exactly two rows of equal length, each being a binary string. Let $\operatorname{MEX}$ of a bi-table be the smallest digit among $0$, $1$, or $2$ that does not occur in the bi-table. For example, $\operatorname{MEX}$ for $\begin{bmatrix} 0011\\ 1010 \end{bmatrix}$ is $2$, because $0$ and $1$ occur in the bi-table at least once. $\operatorname{MEX}$ for $\begin{bmatrix} 111\\ 111 \end{bmatrix}$ is $0$, because $0$ and $2$ do not occur in the bi-table, and $0 < 2$. You are given a bi-table with $n$ columns. You should cut it into any number of bi-tables (each consisting of consecutive columns) so that each column is in exactly one bi-table. It is possible to cut the bi-table into a single bi-table — the whole bi-table. What is the \textbf{maximal} sum of $\operatorname{MEX}$ of all resulting bi-tables can be?
You can cut out the columns with both $0$ and $1$. Now in each column there are only $0$ or only $1$. We only need to solve the problem for a string because the columns can be replaced by one digit (they consist of equal elements). Let's be greedy, to each zero we will "join" not more than one $1$. Let's solve the same problem but for a string: It's needed to cut a binary string into segments so that each its element is in exactly one segment and the sum of $\text{MEX}$ for all segments is maximal. Initially we will say that the string is cut into segments of length 1. Then the answer is the number of zeroes in the string. After that the answer is increased every time we merge a segment of $0$ with a segment of $1$. Each such merge increases the answer by $1$. Let's make the merges greedily, maximizing the number of merges. Let's consider the first zero. If the previous element is a $1$, let's merge them and consider the next zero. Else, if the next element is a $1$, let's merge them and consider the next zero. Else, the next element is a zero and we should consider it instead of the current zero the same way. By doing so we get the answer as the number of zeroes + the number of merges. Now let's solve the initial problem. We can cut out the columns that contain both $0$ and $1$, because their $\text{MEX}$ is already maximized and the answer will not become worse. Now we solve the problem for all remaining bi-tables independently. Each their column consists either only of $0$ or only of $1$ so both rows are equal. We will solve the problem for one row of each remaining bi-table as mentioned before and then sum up the values to get the answer. This problem could be solved in many ways using the dp. We will consider these solutions in short. Let's say that $dp_i$ - is the answer for a prefix until $i$. Then there are different approaches: We can calculate the dp values, iterating through all possible $\operatorname{MEX}$ values on the last segment. For example, if we want to make $\operatorname{MEX}$ equal $2$ on the last segment, then we need to find the closest $0$ and the closest $1$ to position $i$. Let it be $last_0$ and $last_1$. Then we should recalc the dp like this $dp_i = \max(dp_i, dp_{j-1} + 2)$, where $j = \min(last_0, last_1)$, because we take the shortest segment ending in $i$ which has both $0$ and $1$ and after that we add the answer for this segment and for prefix that ends in $j-1$. Another possible solution with dp is based on the fact that we should not take any segments with length more than $x$, where $x$ is some small number. We can just take some random big enough $x$ and not prove anything. There exists a solution which does not consider segments with length bigger than $5$.
[ "bitmasks", "constructive algorithms", "dp", "greedy" ]
1,000
#include<bits/stdc++.h> using namespace std; int mex(string s){ int fl=0; for(auto &nx : s){ if(nx=='0'){fl|=1;} else if(nx=='1'){fl|=2;} } if(fl==3){return 2;} if(fl==1){return 1;} return 0; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while(t>0){ t--; int n; string s1,s2; cin >> n >> s1 >> s2; vector<int> dp(n+1,0); for(int i=0;i<n;i++){ string s; for(int j=0;j<5;j++){ if(i+j>=n){break;} s.push_back(s1[i+j]); s.push_back(s2[i+j]); dp[i+j+1]=max(dp[i+j+1],dp[i]+mex(s)); } } cout << dp[n] << '\n'; } return 0; }
1566
D2
Seating Arrangements (hard version)
\textbf{It is the hard version of the problem. The only difference is that in this version $1 \le n \le 300$.} In the cinema seats can be represented as the table with $n$ rows and $m$ columns. The rows are numbered with integers from $1$ to $n$. The seats in each row are numbered with consecutive integers from left to right: in the $k$-th row from $m (k - 1) + 1$ to $m k$ for all rows $1 \le k \le n$. \begin{center} \begin{tabular}{|c||c||c||c||c|} \hline $1$ & $2$ & $\cdots$ & $m - 1$ & $m$ \ \hline \hline $m + 1$ & $m + 2$ & $\cdots$ & $2 m - 1$ & $2 m$ \ \hline \hline $2m + 1$ & $2m + 2$ & $\cdots$ & $3 m - 1$ & $3 m$ \ \hline \hline $\vdots$ & $\vdots$ & $\ddots$ & $\vdots$ & $\vdots$ \ \hline \hline $m (n - 1) + 1$ & $m (n - 1) + 2$ & $\cdots$ & $n m - 1$ & $n m$ \ \hline \end{tabular} {\small The table with seats indices} \end{center} There are $nm$ people who want to go to the cinema to watch a new film. They are numbered with integers from $1$ to $nm$. You should give exactly one seat to each person. It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. $i$-th person has the level of sight $a_i$. Let's define $s_i$ as the seat index, that will be given to $i$-th person. You want to give better places for people with lower sight levels, so for any two people $i$, $j$ such that $a_i < a_j$ it should be satisfied that $s_i < s_j$. After you will give seats to all people they will start coming to their seats. In the order from $1$ to $nm$, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The \textbf{inconvenience} of the person is equal to the number of occupied seats he or she will go through. Let's consider an example: $m = 5$, the person has the seat $4$ in the first row, the seats $1$, $3$, $5$ in the first row are already occupied, the seats $2$ and $4$ are free. The inconvenience of this person will be $2$, because he will go through occupied seats $1$ and $3$. Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).
Each person can be seated on some subsegment of places with people with the same level of sight. If $n=1$ we should seat people on the maximal possible place. The places available for some person may be a subsegment of a row or a suffix of a row + some full rows + a prefix of a row. Let's consider all seats in increasing order of their indices. For each seat we can consider the level of sight of a person that takes that seat. The considered sequence is non-decreasing. This means that people with the same level of sight should take consequent seats and for each level of sight $x$ we can determine which seats will be taken by people with level of sight $x$. Now we should find out how do people with level of sight $x$ sit in the cinema. For that $x$ we know that people with that level of sight should take places with indices from $l$ to $r$. Let's seat people with the same level of sight greedily. If all places from $l$ to $r$ are in the same row, then we should seat people in decreasing order of seat indices. Otherwise, these seats form a suffix of some row (maybe empty), some full rows (maybe zero), a prefix of some row (maybe empty). Firstly we need to seat people on the suffix in decreasing order of seat indices. This is not worse than other seatings, because the seats before that suffix may be taken in future and total inconvenience will increase. Seats on the prefix should be taken last of all in decreasing order of seat indices. This is not worse than other seatings, because if some people sit on that prefix then they will bother people on the right, increasing the total inconvenience. Full rows should be taken in decreasing order of seat indices, this does not increase the total inconvenience at all. So we should start by seating poeple on the suffix, then we should cover full rows and finally we should cover the prefix. In each case places should be taken in decreasing order of seat indices. The constraints for $m$ are low, so each time we want to seat someone we can consider all places in the row and find how many people increase our inconvenience.
[ "data structures", "greedy", "implementation", "sortings", "two pointers" ]
1,600
#include <bits/stdc++.h> #define long long long int using namespace std; // @author: pashka void solve_test() { int n, m; cin >> n >> m; vector<pair<int, int>> a(n * m); for (int i = 0; i < n * m; i++) { cin >> a[i].first; a[i].second = i; } sort(a.begin(), a.end()); for (int i = 0; i < n * m; i++) { a[i].second = -a[i].second; } int res = 0; for (int i = 0; i < n; i++) { sort(a.begin() + (m * i), a.begin() + (m * i + m)); for (int j = 0; j < m; j++) { for (int k = 0; k < j; k++) { if (a[i * m + k].second > a[i * m + j].second) res++; } } } cout <<res << "\n"; } int main() { ios::sync_with_stdio(false); int n; cin >> n; for (int i = 0; i < n; i++) { solve_test(); } return 0; }
1566
E
Buds Re-hanging
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex $v$ (different from root) is the previous to $v$ vertex on the shortest path from the root to the vertex $v$. Children of the vertex $v$ are all vertices for which $v$ is the parent. A vertex is a leaf if it has no children. We call a vertex a \textbf{bud}, if the following three conditions are satisfied: - it is not a root, - it has at least one child, and - all its children are leaves. You are given a rooted tree with $n$ vertices. The vertex $1$ is the root. In one operation you can choose any bud with all its children (they are leaves) and re-hang them to any other vertex of the tree. By doing that you delete the edge connecting the bud and its parent and add an edge between the bud and the chosen vertex of the tree. The chosen vertex cannot be the bud itself or any of its children. All children of the bud stay connected to the bud. What is the minimum number of leaves it is possible to get if you can make any number of the above-mentioned operations (possibly zero)?
Re-hanging a bud to a leaf decreases the total amount of leaves by $1$. Buds can be re-hanged that way so in the end there is only a root, buds that are connected to the root and leaves connected to the root or to the buds. Now the answer depends only on the total amount of vertices, on the amount of buds and on the fact whether there is a leaf connected to the root or not. If we re-hang a bud from its parent to the root, the amount of leaves either doesn't change (if the parent has other children), or increases by $1$. By doing that we don't make the answer worse, because if there are leaves except for bud's leaves, then we can re-hang the bud to some leaf, decreasing the amount of leaves by $1$. So let's re-hang all buds to the root, until there are no free buds left. Now we will assume that all buds are hung to the root, and their amount is $k$. The answer is either $n - 2 \cdot k$ if there is no leaf, hung to the root, or $n - 2 \cdot k - 1$ if there is a leaf, hung to the root. Why is it so? Initially, there are $n - k - 1$ leaves (total amount of nodes - the amount of buds - root). If there is a leaf, hung to the root, then we can hang a bud to it, then hang a bud to the previous bud's leaf, and keep doing so until we use all $k$ buds. Then there are $k$ re-hangs, each of them decreases the answer by $1$. So the final answer is $n - k - 1 - k = n - 2 \cdot k - 1$. If there is no leaves hung to the root, then we can hang a bud to another bud's leaf, then a bud to the previous bud's leaf, and so on until we use $k - 1$ buds. The final answer in this case is $n - k - 1 - (k - 1) = n - 2 \cdot k$. It is not possible to make the answer less, because each re-hang decreases the answer by \le 1 and each re-hang we make decreases it exactly by 1 and we use all re-hangs.
[ "constructive algorithms", "dfs and similar", "dp", "greedy", "trees" ]
2,000
#include <bits/stdc++.h> using namespace std; vector<vector<int>> g; vector<int> type; // -1 -- default, 0 -- root, 1 -- leaf, 2 -- bud void dfs(int v, int p) { bool leaves = false; for (auto to : g[v]) { if (to == p) continue; dfs(to, v); if (type[to] == 1) leaves = true; } if (v != p) { if (!leaves) type[v] = 1; else type[v] = 2; } } int main() { ios_base::sync_with_stdio(false); cout.tie(0); cin.tie(0); int T; cin >> T; while (T --> 0) { int n; cin >> n; g.assign(n, vector<int>()); type.assign(n, -1); for (int i = 0; i < n - 1; ++i) { int x, y; cin >> x >> y; --x; --y; g[x].emplace_back(y); g[y].emplace_back(x); } type[0] = 0; dfs(0, 0); bool root_leaf = false; for (auto v : g[0]) { if (type[v] == 1) { root_leaf = true; } } int k = 0; for (int i = 0; i < n; ++i) { k += (type[i] == 2); } cout << n - 2 * k - root_leaf << '\n'; } return 0; }
1566
F
Points Movement
There are $n$ points and $m$ segments on the coordinate line. The initial coordinate of the $i$-th point is $a_i$. The endpoints of the $j$-th segment are $l_j$ and $r_j$ — left and right endpoints, respectively. You can move the points. In one move you can move any point from its current coordinate $x$ to the coordinate $x - 1$ or the coordinate $x + 1$. The cost of this move is $1$. You should move the points in such a way that each segment is visited by at least one point. A point visits the segment $[l, r]$ if there is a moment when its coordinate was on the segment $[l, r]$ (including endpoints). You should find the minimal possible total cost of all moves such that all segments are visited.
If a segment already contains a point then it can be thrown out of the consideration. If there is a segment that contains some segment, we can save only the smaller one. If you already know which segments will be visited by some point, how you should calculate the answer for this point? For some segment, which points should visit it? Firstly, if a point has initially visited some segment, then we can throw it out of consideration. It means that all segments that cover at least one point can be thrown out. This can be done using the binary search for each segment separately. Secondly, if a segment $A$ is contained in a segment $B$ (i.e. $l_B \le l_A \le r_A \le r_B$), then a point that visited $A$ will visit $B$, too. It means that we should save only those segments that do not contain any other segments. This can be done using a Fenwick tree. Initially, all values in the tree are zeroes. We will consider the segments in decreasing order of $l$. Let's assume we are considering segment $i$. If there is an already considered segment $j$ $(r_j \le r_i)$, then segment $j$ is in segment $i$. It is so because $l_i \le l_j$ because of the considering order, so $l_i \le l_j \le r_j \le r_i$. To find the amount of such $j$ it is enough to find the amount of $1$ on a prefix until $r_i$ in the Fenwick tree. Now when we considered the segment $i$ we set $1$ in the Fenwick tree on position $r_i$. After that there are only segments that do not contain any other segments and they are not initially visited by any point. We will consider only these segments. Let's say that a segment is assigned to a point if that point visits this segment. Let's find out how to calculate the answer for one point if we already know the set of segments that are assigned to it. Let's consider the segments that are on the left to the point and say that the maximal distance from the point to these segments is $a$. In the same way let $b$ be the maximal distance from the point to the segments on the right. Then the answer for the point is $2\cdot min(a, b)+max(a, b)$. Now if a segment is between two neighbouring points, then it should be assigned to one of these points. (If a segment is to the left from the leftmost point or to the right from the rightmost point then it should be assigned to the leftmost point or to the rightmost point respectively). Now let's consider the segments between two neighbouring points. These segments are ordered by the left ends and by the right ends at the same time. Some prefix of these segments should be assigned to the left point, other segments (suffix) should be assigned to the right point. Now let's solve the problem using the dynamic programming. Let $dp[i][j]$ be the answer if we assigned the segments for first $i$ points and there are $j$ segments assigned to the $i$-th point that are to the right from it. There is a linear amount of dp states. Let's learn to calculate the dp. We will consider the dp states in increasing order of $i$ and, after that, $j$. Let $b$ be the distance from $i$-th point to $j$ segment after it. Then $dp[i][j]=\displaystyle\min_{0 \le k \le x} \Big(dp[i-1][k]+2\cdot min(b, a_{i, k})+max(b, a_{i, k})\Big)$, where $a_{i, k}$ - is the distance from $i$-th point to $(k+1)$-th segment after $(i-1)$-th point and $x$ is the amount of segments between points $i$ and $(i+1)$. But this is a quadratic dp. Now we can find out that for some prefix of segments after $(i-1)$-th point $a_{i, k}$ is greater than $b$ and for some suffix it is less than $b$. The length of that prefix may be found using the binary search or two pointers. For $k$ on that prefix the dp will be $dp[i-1][k] + x_i - r_{k+1}+2\cdot b$, and for $k$ on the suffix - $dp[i-1][k] + 2\cdot(x_i - r_{k+1})+b$. In these formulas everything except $b$ depends on $i$ and $k$. It means that we can calculate dp quickly using prefix and suffix minimums. The answer is $dp[n][x]$, where $x$ is the amount of segments to the right of the rightmost point.
[ "data structures", "dp", "greedy", "implementation", "sortings" ]
2,600
#include <bits/stdc++.h> using namespace std; #define pb emplace_back #define all(x) (x).begin(), (x).end() #define fi first #define se second #define pii pair<int, int> #define ll long long const long long INFLL = 1e18; const int INF = 1e9 + 1; struct segment_tree { vector<int> t; segment_tree(int n) { t.assign(4 * n, INF); } void mod(int v, int vl, int vr, int id, int val) { if (vr - vl == 1) { t[v] = min(t[v], val); return; } int vm = (vl + vr) / 2; if (id < vm) mod(2 * v + 1, vl, vm, id, val); else mod(2 * v + 2, vm, vr, id, val); t[v] = min(t[v], val); } int get(int v, int vl, int vr, int l, int r) { if (vl >= l && vr <= r) return t[v]; if (r <= vl || l >= vr) return INF; int vm = (vl + vr) / 2; return min(get(2 * v + 1, vl, vm, l, r), get(2 * v + 2, vm, vr, l, r)); } }; bool cmp(const pii &a, const pii &b) { return a.se - a.fi < b.se - b.fi; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vector<ll> a(n); for (auto &c : a) cin >> c; sort(all(a)); vector<pii> seg1(m); vector<int> dl; for (auto &c : seg1) { cin >> c.fi >> c.se; dl.pb(c.fi); } sort(all(dl)); dl.resize(unique(all(dl)) - dl.begin()); sort(all(seg1), cmp); map<int, int> ma; for (int i = 0; i < (int)dl.size(); i++) ma[dl[i]] = i; segment_tree tr((int)dl.size()); vector<pii> seg; for (auto &c : seg1) { int id = lower_bound(all(a), c.fi) - a.begin(); if (id < (int)a.size() && a[id] <= c.se) continue; if (tr.get(0, 0, dl.size(), ma[c.fi], dl.size()) <= c.se) continue; tr.mod(0, 0, dl.size(), ma[c.fi], c.se); seg.pb(c.fi, c.se); } m = seg.size(); sort(all(seg)); vector<vector<pii>> g(n + 1); int L = -1, R = m; while (R - L > 1) { int M = (L + R) / 2; if (seg[M].se < a[0]) L = M; else R = M; } for (int i = 0; i <= L; i++) g[0].pb(seg[i]); for (int i = 0; i < n; i++) { int RIGHT = INF; if (i + 1 < n) RIGHT = a[i + 1]; int id = upper_bound(all(seg), make_pair((int)a[i], (int)a[i])) - seg.begin(); if (id == m) continue; int L = id - 1, R = m; while (R - L > 1) { int M = (L + R) / 2; if (seg[M].se < RIGHT) L = M; else R = M; } for (int j = id; j <= L; j++) g[i + 1].pb(seg[j]); } vector<vector<ll>> dp(n), pr(n), suff(n); for (int i = 0; i < n; i++) { dp[i].resize(g[i + 1].size() + 1, INFLL); pr[i].resize(g[i + 1].size() + 1, INFLL); suff[i].resize(g[i + 1].size() + 1, INFLL); } for (int j = 0; j <= (int)g[1].size(); j++) { ll x = 0; if (g[0].size()) x = a[0] - g[0][0].se; ll y = 0; if (j) y = g[1][j - 1].fi - a[0]; dp[0][j] = 2 * min(x, y) + max(x, y); } for (int i = 1; i < n; i++) { for (int j = 0; j <= (int)g[i].size(); j++) { if (j > 0) pr[i - 1][j] = pr[i - 1][j - 1]; pr[i - 1][j] = min(pr[i - 1][j], dp[i - 1][j] - (j == (int)g[i].size() ? a[i] : g[i][j].se)); } for (int j = (int)g[i].size(); j >= 0; j--) { if (j + 1 <= (int)g[i].size()) suff[i - 1][j] = suff[i - 1][j + 1]; suff[i - 1][j] = min(suff[i - 1][j], dp[i - 1][j] - 2 * (j == (int)g[i].size() ? a[i] : g[i][j].se)); } int L = (int)g[i].size(); for (int j = 0; j <= (int)g[i + 1].size(); j++) { ll y = 0; if (j) y = g[i + 1][j - 1].fi - a[i]; while (L > 0 && a[i] - g[i][L - 1].se <= y) L--; if (L > 0) dp[i][j] = min(dp[i][j], 2 * y + a[i] + pr[i - 1][L - 1]); dp[i][j] = min(dp[i][j], y + 2 * a[i] + suff[i - 1][L]); } } cout << dp[n - 1].back() << "\n"; } return 0; }
1566
G
Four Vertices
You are given an undirected weighted graph, consisting of $n$ vertices and $m$ edges. Some queries happen with this graph: - Delete an existing edge from the graph. - Add a non-existing edge to the graph. At the beginning and after each query, you should find four \textbf{different} vertices $a$, $b$, $c$, $d$ such that there exists a path between $a$ and $b$, there exists a path between $c$ and $d$, and the sum of lengths of two shortest paths from $a$ to $b$ and from $c$ to $d$ is minimal. The answer to the query is the sum of the lengths of these two shortest paths. The length of the path is equal to the sum of weights of edges in this path.
The answer always consists either of three edges with common end or of two edges that don't have any common ends. To find the answer of the second type you can leave in the graph only those edges that are in the list of three smallest edges for both ends. Let's consider those cases when the minimal edge is in the answer or not in the answer. Observation: the answer always consists either of three edges that have one common end or of two edges that do not have any common ends. To find the answer of the first type it is enough to maintain three minimal edges for each vertex. To find the answer of the second type we will use this observation: we can leave in the graph only those edges that are in the set of three minimal edges for each their end. Let's prove that. Let's assume that the answer consists of two edges $(a, b)$ and $(c, d)$ and there are at least three edges $(a, a_1)$, $(a, a_2)$, $(a, a_3)$ less than $(a, b)$. Then the edge $(a, b)$ can be swapped by one of these edges because at least one of te integers $a_1$, $a_2$, $a_3$ is not equal to $c$ and $d$. Then we will maintain the set of all these edges. Now let's consider two cases. Let $(a, b)$ be the minimal edge. If it is in the answer then we need to find the minimal edge, that does not have any common vertices with $(a, b)$. In this case there are at most $6$ ``bad'' edges because the degrees of each vertex in the graph that consists only of remaining edges do not exceed $3$. It means that we have to consider $O(1)$ variants. If $(a, b)$ is not in the answer, then there are two edges in the answer that have vertices $a$ and $b$ as one of their ends. But there are at most $9$ such pairs of edges, so we have to consider only $O(1)$ variants. So the final answer is the minimum of answers of both types.
[ "constructive algorithms", "data structures", "graphs", "greedy", "implementation", "shortest paths" ]
3,100
#include<bits/stdc++.h> using namespace std; #define sz(a) (int) (a).size() const int N = 1e5; vector<pair<int, int>> g[N]; map<pair<int, int>, int> cost; set<pair<int, int>> a[N], b[N]; multiset<long long> dp; set<pair<int, pair<int, int>>> dp2; void solve() { auto minr = *dp2.begin(); long long ans = 1e18; if (sz(dp)) { ans = min(ans, *dp.begin()); } int v = minr.second.first, u = minr.second.second; auto it = dp2.begin(); for (int i = 0; i < 6 && it != dp2.end(); i++, it = next(it)) { auto res = *it; int v2 = res.second.first, u2 = res.second.second; if (v2 != v && v2 != u && u2 != v && u2 != u) { ans = min(ans, (long long) res.first + minr.first); } } for (auto [w, v2] : a[v]) { for (auto [w2, u2] : a[u]) { if (v2 != u2 && v2 != u && u2 != v) { ans = min(ans, (long long) w + w2); } } } cout << ans << '\n'; } void del(int v) { if (sz(a[v]) >= 3) { long long res = 0; for (auto [w, to] : a[v]) { res += w; } dp.erase(dp.find(res)); } for (auto [w, to] : a[v]) { if (dp2.find({w, {min(v, to), max(v, to)}}) != dp2.end()) { dp2.erase({w, {min(v, to), max(v, to)}}); } } } void upd(int v) { if (sz(a[v]) >= 3) { long long res = 0; for (auto [w, to] : a[v]) { res += w; } dp.insert(res); } for (auto [w, to] : a[v]) { if (a[to].find({w, v}) != a[to].end()) { dp2.insert({w, {min(v, to), max(v, to)}}); } } } void relax(int v) { while (sz(a[v]) && sz(b[v])) { auto A = *a[v].rbegin(), B = *b[v].begin(); if (A.first <= B.first) break; a[v].erase(A); b[v].erase(B); a[v].insert(B); b[v].insert(A); } while (sz(a[v]) < 3 && sz(b[v])) { auto B = *b[v].begin(); b[v].erase(B); a[v].insert(B); } } void erase(int v, int u, int w) { del(v); del(u); if (a[v].find({w, u}) != a[v].end()) { a[v].erase({w, u}); } else { b[v].erase({w, u}); } if (a[u].find({w, v}) != a[u].end()) { a[u].erase({w, v}); } else { b[u].erase({w, v}); } relax(v); relax(u); upd(v); upd(u); } void add(int v, int u, int w) { del(v); del(u); b[v].insert({w, u}); b[u].insert({w, v}); relax(v); relax(u); upd(v); upd(u); } signed main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int x, y, w; cin >> x >> y >> w; x--, y--; if (x > y) swap(x, y); cost[{x, y}] = w; g[x].push_back({w, y}); g[y].push_back({w, x}); } for (int i = 0; i < n; i++) { sort(g[i].begin(), g[i].end()); for (int j = 0; j < sz(g[i]); j++) { if (j <= 2) { a[i].insert(g[i][j]); } else { b[i].insert(g[i][j]); } } if (sz(a[i]) >= 3) { long long res = 0; for (auto [w, to] : a[i]) { res += w; } dp.insert(res); } } for (int i = 0; i < n; i++) { for (int j = 0; j < sz(g[i]); j++) { int v = g[i][j].second; if (j <= 2) { if (a[v].find({g[i][j].first, i}) != a[v].end()) { dp2.insert({g[i][j].first, {min(i, v), max(i, v)}}); } } } } int q; cin >> q; solve(); while (q--) { int t, v, u; cin >> t >> v >> u; v--, u--; if (v > u) swap(v, u); if (t == 0) { int w = cost[{v, u}]; erase(v, u, w); } else { int w; cin >> w; cost[{v, u}] = w; add(v, u, w); } solve(); } }
1566
H
Xor-quiz
\textbf{This is an interactive problem.} You are given two integers $c$ and $n$. The jury has a \textbf{randomly generated} set $A$ of distinct positive integers not greater than $c$ (it is generated from all such possible sets with equal probability). The size of $A$ is equal to $n$. Your task is to guess the set $A$. In order to guess it, you can ask at most $\lceil 0.65 \cdot c \rceil$ queries. In each query, you choose a single integer $1 \le x \le c$. As the answer to this query you will be given the bitwise xor sum of all $y$, such that $y \in A$ and $gcd(x, y) = 1$ (i.e. $x$ and $y$ are coprime). If there is no such $y$ this xor sum is equal to $0$. You can ask all queries at the beginning and you will receive the answers to all your queries. After that, you won't have the possibility to ask queries. You should find any set $A'$, such that $|A'| = n$ and $A'$ and $A$ have the same answers for all $c$ possible queries.
Numbers with the same set of prime divisors may be considered as the same numbers. The amount of distinct sets of prime divisors which multiplication does not exceed $C$ for such constraints does not exceed $\lceil 0.65 \cdot C \rceil$. How you should find the $xor$ of all numbers that have the same set of prime divisors? If you know the $xor$ of all numbers with the same set of prime divisors you can recover these numbers randomly. Let $f(x)$ be the multiplication of all prime divisors of $x$. Then let's make queries for all such $y$ that there is at least one such $x$, $1 \le x \le C$ and $f(x) = y$. For such constraints there will be at most $\lceil 0.65 \cdot C \rceil$ queries. Let's group all numbers by $f(x)$. All numbers in one group in any query will be considered together. Let $ans(x)$ be the answer for the query with number $x$ and $g(x)$ be the $xor$ of all number that are not coprime with $x$. Then $g(x)=ans(x) \oplus ans(1)$. Now let's find out how to calculate the $xor$ of all such $x$ that $f(x)$ is divisible by an arbitrary $y$. Let's take $xor$ of all $g(k)$ where $k$ is a divisor of $y$ greater than $1$. Let's prove that by doing that we will get the needed value. If $f(x)$ is divisible by $y$ then such $x$ will be considered $2^l - 1$ times, where $l$ is the amount of prime divisors of $y$. It means that $x$ will be contained in the final value. Now let's prove that there will be no unintended $x$ values. Let $f(x)$ be not divisible by $y$. It means that there is suche prime $p$ that $y$ is divisible by $p$ and $x$ is not divisible by $p$. Then for each divisor $a$ of $y$ that is divisible by $p$ we will assign $b=a/p$. Then such $x$ will be considered either for both $a$ and $b$ or for none of them. It means that it will be considered an even amount of times. Now to find the $xor$ of all numbers with an arbitrary $f(x)$ we need to consider all $x$ from $C$ to $1$ and make $f(x) = f(x) \oplus f(2x) \oplus f(3x) \oplus \ldots$. Now we only need to find $n$ distinct numbers from $1$ to $C$ such that $xor$ of numbers in each group is equal to a specific number. For each group of numbers with given $f(x)$ we will start the Gaussian elimination. Let $k$ be the size of a group and after the Gaussian elimination there are $b$ non-zero numbers. Then if $b=k$ there is a single way to obtain the needed $xor$. Else there are $2^{k-b}$ ways to obtain the needed $xor$. Now let's take some random sets of numbers with the needed $xor$ and calculate dp on these numbers to get take exactly $n$ numbers. If there are several ways we can choose any of them.
[ "constructive algorithms", "dp", "interactive", "math", "number theory" ]
3,200
#include <bits/stdc++.h> using namespace std; #define pb emplace_back #define all(x) (x).begin(), (x).end() #define fi first #define se second #define pii pair<int, int> #define ll long long #define ld long double const long long INFLL = 1e18; const int INF = 1e9 + 1; const int MAXC = 1e6; mt19937 gen(time(0)); vector<int> e(MAXC + 5); void precalc() { vector<int> p; for (int i = 2; i <= MAXC; i++) { if (e[i] == 0) { e[i] = i; p.pb(i); } for (int j = 0; j < (int)p.size() && p[j] * i <= MAXC && p[j] <= e[i]; j++) { e[p[j] * i] = p[j]; } } } int f(int x) { int ans = 1; vector<int> p; while (x > 1) { p.pb(e[x]); x /= e[x]; } for (int i = 0; i < (int)p.size(); i++) { if (i + 1 == (int)p.size() || p[i + 1] != p[i]) ans *= p[i]; } return ans; } void gauss(int need, vector<int> &lst, vector<int> &ans, vector<vector<int>> &sz, vector<vector<vector<int>>> &v) { int n = lst.size(); vector<bitset<20>> a(n); for (int i = 0; i < n; i++) a[i] = lst[i]; bitset<20> b = need; vector<bitset<260>> l(n); for (int i = 0; i < n; i++) l[i][i] = 1; int i = 0; vector<int> col(20, -1); int bas_sz = 0; for (int j = 0; j < 20 && i < n; j++) { int i1 = i; while (i1 < n && a[i1][j] == 0) i1++; if (i1 == n) continue; swap(a[i], a[i1]); swap(l[i], l[i1]); bas_sz++; col[j] = i; for (int i2 = i + 1; i2 < n; i2++) { if (a[i2][j]) { a[i2] ^= a[i]; l[i2] ^= l[i]; } } i++; } bitset<20> res; bitset<260> path; for (int j = 0; j < 20; j++) { if (res[j] != b[j] && col[j] == -1) { exit(0); } if (res[j] == b[j]) continue; res ^= a[col[j]]; path ^= l[col[j]]; } if (a.back().count() != 0) { for (int i = 0; i < n; i++) { if (path[i]) ans.pb(lst[i]); } return; } vector<int> diff_sz(300); sz.pb(); v.pb(); for (int it = 0; it < 100; it++) { bitset<260> now = path; for (int i = 0; i < n - bas_sz; i++) { if (gen() % 2) now ^= l[bas_sz + i]; } int now_sz = now.count(); if (diff_sz[now_sz]) continue; v.back().pb(); for (int i = 0; i < n; i++) { if (now[i]) v.back().back().pb(lst[i]); } diff_sz[now_sz] = 1; sz.back().pb(now_sz); } } vector<int> mem(2 * MAXC + 5, -1); int query(int x) { return mem[x]; } void solve(int n, int c) { vector<int> calc(c + 1); vector<vector<int>> total(c + 1); for (int x = 1; x <= c; x++) total[f(x)].pb(x); vector<int> need; for (int x = 1; x <= c; x++) { if (total[x].size()) need.pb(x); } cout << need.size() << " "; for (auto &c : need) cout << c << " "; cout << endl; for (auto &c : need) { int x; cin >> x; mem[c] = x; } int total_xor = query(1); for (int x = 1; x <= c; x++) { if (total[x].empty()) continue; for (int y = x; y <= c; y += x) calc[y] ^= (query(x) ^ total_xor); } calc[1] = total_xor; for (int x = c; x >= 1; x--) { if (total[x].empty()) continue; for (int y = 2 * x; y <= c; y += x) { if (total[y].size()) calc[x] ^= calc[y]; } } vector<int> ans; vector<vector<int>> sz; vector<vector<vector<int>>> v; for (int x = 1; x <= c; x++) { if (total[x].empty()) continue; gauss(calc[x], total[x], ans, sz, v); } vector<bitset<40000>> bag(sz.size() + 1); bag[0][0] = 1; for (int i = 1; i <= (int)sz.size(); i++) { for (auto &x : sz[i - 1]) { bag[i] |= (bag[i - 1] << x); } } int now = n - ans.size(); for (int i = (int)sz.size(); i >= 1; i--) { for (int j = 0; j < (int)sz[i - 1].size(); j++) { int x = sz[i - 1][j]; if (now - x >= 0 && bag[i - 1][now - x]) { now -= x; for (auto &y : v[i - 1][j]) ans.pb(y); break; } } } sort(all(ans)); for (auto &c : ans) cout << c << " "; cout << endl; } int main() { precalc(); int c, n; cin >> c >> n; solve(n, c); return 0; }
1567
A
Domino Disaster
Alice has a grid with $2$ rows and $n$ columns. She fully covers the grid using $n$ dominoes of size $1 \times 2$ — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino. Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!
If there is a vertical domino (either U or D) in the current slot, then the corresponding domino half in the other row must be a D or a U, respectively. Otherwise, we can just fill the rest of the row with copies of LR. Time complexity: $\mathcal{O}(n)$.
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; void solve() { int n; cin >> n; string s, res; cin >> s; for (int i = 0; i < n; i++) { if (s[i] == 'U') {res += 'D';} else if (s[i] == 'D') {res += 'U';} else {res += "LR"; i++;} } cout << res; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve(); cout << endl;} //solve(); }
1567
B
MEXor Mixup
Alice gave Bob two integers $a$ and $b$ ($a > 0$ and $b \ge 0$). Being a curious boy, Bob wrote down an array of \textbf{non-negative} integers with $\operatorname{MEX}$ value of all elements equal to $a$ and $\operatorname{XOR}$ value of all elements equal to $b$. What is the shortest possible length of the array Bob wrote? Recall that the $\operatorname{MEX}$ (Minimum EXcluded) of an array is the minimum non-negative integer that does \textbf{not} belong to the array and the $\operatorname{XOR}$ of an array is the bitwise XOR of all the elements of the array.
First consider the MEX condition: the shortest array with MEX $a$ is the array $[0, 1, \dots, a - 1]$, which has length $a$. Now we'll consider the XOR condition. Let the XOR of the array $[0, 1, \dots, a - 1]$ be $x$. We have three cases. Case 1: $x = b$. Then we don't need to add any elements to the array, so the answer is $a$. Case 2: $x \neq b$ and $x \oplus b \neq a$. Then we can add the element $x \oplus b$ to the array since $x \oplus b \neq a$, so the MEX will still be $a$. The XOR of the array will then be $x \oplus x \oplus b = b$. The answer is $a + 1$. Case 3: $x \neq b$ and $x \oplus b = a$. Then we cannot add the element $x \oplus b$ to the end of the array. We can just add $x \oplus b \oplus 1$ and $1$, so the XOR of the array will be $x \oplus x \oplus b \oplus 1 \oplus 1 = b$. The answer is $a + 2$. Time complexity: $\mathcal{O}(n)$ precomputation and $\mathcal{O}(1)$ per test case if you precalculate the XOR of the numbers from $0$ to $n-1$, or $\mathcal{O}(1)$ if you use the well-known formula for it.
[ "bitmasks", "greedy" ]
1,000
#include <bits/stdc++.h> using namespace std; const int MAX = 100007; const int MOD = 1000000007; void solve() { int a, b; cin >> a >> b; int pXor; if (a % 4 == 1) {pXor = a - 1;} else if (a % 4 == 2) {pXor = 1;} else if (a % 4 == 3) {pXor = a;} else {pXor = 0;} if (pXor == b) {cout << a << '\n';} else if ((pXor ^ b) != a) {cout << a + 1 << '\n';} else {cout << a + 2 << '\n';} } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} //solve(); }
1567
C
Carrying Conundrum
Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully — instead of carrying to the next column, she carries to the column two columns to the left. For example, the \textbf{regular} way to evaluate the sum $2039 + 2976$ would be as shown: However, Alice evaluates it as shown: In particular, this is what she does: - add $9$ and $6$ to make $15$, and carry the $1$ to the column two columns to the left, i. e. to the column "$0$ $9$"; - add $3$ and $7$ to make $10$ and carry the $1$ to the column two columns to the left, i. e. to the column "$2$ $2$"; - add $1$, $0$, and $9$ to make $10$ and carry the $1$ to the column two columns to the left, i. e. to the column above the plus sign; - add $1$, $2$ and $2$ to make $5$; - add $1$ to make $1$. Thus, she ends up with the incorrect result of $15005$.Alice comes up to Bob and says that she has added two numbers to get a result of $n$. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $n$. Note that pairs $(a, b)$ and $(b, a)$ are considered different if $a \ne b$.
Note that in every other column, the addition Alice performs is correct. Therefore, we can take our number, split it into alternating digits, and then find the answer. For example, consider $n = 12345$. We split it into alternating digits: $1\underline{2}3\underline{4}5 \to 135, 24$. Now the problem is equivalent to find the number of pairs of numbers which add to $135$ multiplied by the number of pairs of numbers which add to $24$. It's clear each pair works: for example, $45 + 90 = 135$ and $\underline{9} + \underline{15} = \underline{24}$, so $4\underline{9}5 + \underline{1}9\underline{5}0$ will be equal to $12345$ according to Alice. Now, how many ways are there to find a pair of non-negative integers whose sum is $n$? There are clearly $n+1$ ways: $n+0,(n-1)+1,(n-2)+2,\dots,0+n$. Therefore, suppose we split $n$ into two numbers $a$ and $b$. Then the answer will be $(a+1)(b+1)$, but we should subtract $2$ because those correspond to either the first or second number in the sum being $0$. As a result, the answer is $(a+1)(b+1)-2$. Time complexity: $\mathcal{O}(\log_{10}n) = \mathcal{O}(\log n)$.
[ "bitmasks", "combinatorics", "dp", "math" ]
1,600
#include <bits/stdc++.h> using namespace std; int dp[10][2][2]; void solve() { string s; cin>>s; int n=s.size(); for (int i=0;i<10;++i) for (int j=0;j<2;++j) for (int k=0;k<2;++k) dp[i][j][k]=0; dp[n][0][0]=1; for (int i=n-1;i>=0;--i) for (int j=0;j<10;++j) for (int k=0;k<10;++k) for (int l=0;l<2;++l) for (int m=0;m<2;++m) if ((j+k+l)%10==s[i]-'0') dp[i][m][(j+k+l)/10]+=dp[i+1][l][m]; cout<<dp[0][0][0]-2<<"\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin>>t; while (t--) solve(); return 0; }
1567
D
Expression Evaluation Error
On the board, Bob wrote $n$ positive integers in base $10$ with sum $s$ (i. e. in decimal numeral system). Alice sees the board, but accidentally interprets the numbers on the board as base-$11$ integers and adds them up (in base $11$). What numbers should Bob write on the board, so Alice's sum is as large as possible?
Let's greedily construct the largest possible sum for Alice, digit by digit. That is, the leftmost position should have the largest value possible, then the second-leftmost position, and so on. The maximum value of the leftmost digit of Alice's sum is clearly equal to the leftmost digit of the number $s$, since it cannot be larger. Similarly, the maximum possible value for the second-leftmost digit in Alice's sum cannot be larger than the corresponding digit in $s$, and so on. In general, Alice's sum cannot be larger than the number $s$ when interpreted as a base-11 number. So how can we maintain the sum of $s$ when we express it as a sum of $n$ numbers? The idea is to split $s$ into a sum of powers of $10$. For example, if $s=25$, and Bob writes down $[10, 10, 1, 1, 1, 1, 1]$. Then Alice will not have any carries, and so the answer will just be $s$ interpreted as a base-11 number. But what if we need to write down more numbers than the sum of the digits of $s$? Then, we're forced to split a power ten into units. When we split a power of $10$, it can be seen that we should split the smallest power of $10$ that isn't $1$ (call it $10^k$) as $10^{k-1}$ and $9 \cdot 10^{k-1}$. We can check all powers of $10$, and it can be shown that this is the best way to split. For example, if $s=21$ and $n=4$, then we do the following process: $[21]$ to $[20, 1]$ to $[10, 10, 1]$ to $[10, 9, 1, 1]$. If $s=110$ and $n=3$, we do the following process: $[110]$ to $[100, 10]$ to $[100, 9, 1]$. Note that, in this last case, splitting $10=9+1$ is better than splitting $100=90+10$, since the sum of $100_{11} + 9_{11} + 1_{11} = 10A_{11}$, and $90_{11} + 10_{11} + 1_{11} = A1_{11}$. Time complexity: $\mathcal{O}(n^2 \log_{10}(s))$ if you lazily iterate over all currently split numbers, or $\mathcal{O}(n \log{n} \log_{10}(s))$ if you use a priority queue.
[ "constructive algorithms", "greedy", "implementation", "math" ]
2,000
#include <bits/stdc++.h> using namespace std; const int MAX = 200007; const int MOD = 1000000007; long long split(long long n) { long long pow10 = 1; while (pow10 <= n) { if (pow10 == n) {return pow10 / 10;} pow10 *= 10; } return pow10 / 10; } bool isPow10(long long n) { long long pow10 = 1; while (pow10 <= n) { if (pow10 == n) {return true;} pow10 *= 10; } return false; } void solve() { long long s; int n; cin >> s >> n; vector<long long> curr; curr.push_back(s); for (int mv = 0; mv < n - 1; mv++) { long long x = -1; for (int i = 0; i < curr.size(); i++) { if (!isPow10(curr[i])) { x = curr[i]; curr.erase(curr.begin() + i); break; } } if (x == -1) { long long mn = 1000000000007ll; for (int i = 0; i < curr.size(); i++) { if (curr[i] != 1) { mn = min(mn, curr[i]); } } for (int i = 0; i < curr.size(); i++) { if (curr[i] == mn) { x = curr[i]; curr.erase(curr.begin() + i); break; } } } curr.push_back(split(x)); curr.push_back(x - split(x)); } for (auto i : curr) { cout << i << ' '; } cout << endl; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt; cin >> tt; for (int i = 1; i <= tt; i++) {solve();} // solve(); }
1567
E
Non-Decreasing Dilemma
Alice has recently received an array $a_1, a_2, \dots, a_n$ for her birthday! She is very proud of her array, and when she showed her friend Bob the array, he was very happy with her present too! However, soon Bob became curious, and as any sane friend would do, asked Alice to perform $q$ operations of two types on her array: - $1$ $x$ $y$: update the element $a_x$ to $y$ (set $a_x = y$). - $2$ $l$ $r$: calculate how many non-decreasing subarrays exist within the subarray $[a_l, a_{l+1}, \dots, a_r]$. More formally, count the number of pairs of integers $(p,q)$ such that $l \le p \le q \le r$ and $a_p \le a_{p+1} \le \dots \le a_{q-1} \le a_q$. Help Alice answer Bob's queries!
Note that if there exists a non-decreasing array of length $x$, then it contains $\frac{x(x+1)}{2}$ non-decreasing subarrays. Therefore, we can break our solution down to counting the lengths of the non-decreasing "chains" within the queried subarray. We can solve this problem using a data structure called a segment tree. On each node of this segment tree, we shall maintain four pieces of information: $\cdot$ the length of the longest non-decreasing prefix. $\cdot$ the length of the longest non-decreasing suffix. $\cdot$ a boolean flag denoting if the entire segment is non-decreasing. $\cdot$ the total number of nondecreasing subarrays not part of the longest prefix or suffix. I won't explain the merging process here (you can examine the implementation below), but it is not too complex. Using this, we can traverse the segment tree, from the left of our queried range to the right, while maintaining the number of non-decreasing subarrays in the prefix of the range and the length of the outgoing non-decreasing suffix to get our answer. Time complexity: $\mathcal{O}(q\log n)$.
[ "data structures", "divide and conquer", "math" ]
2,200
#include <bits/stdc++.h> #define ll long long using namespace std; const int N = 2e5+5; int a[N], k; ll seg[N*4][4], ans; /** Notes: 0: The total number of non-decreasing subarrays in this segment which are are not subarrays of the longest prefix/suffix of non-decreasing subarrays. 1: Length of longest non-decreasing prefix of this segment. 2: Length of longest non-decreasing suffix of this segment. 3: Denotes if this entire segment is nondecreasing (0/1). **/ ll f(int x) { return (1LL*x*(x+1))/2; } void calc(int i, int l, int r) { int m=l+(r-l)/2; if (seg[i*2+1][3]&&seg[i*2+2][3]) { if (a[m]>a[m+1]) { seg[i][0]=0; seg[i][1]=(r-l)/2+1; seg[i][2]=r-l-(r-l)/2; seg[i][3]=0; } else { seg[i][0]=0; seg[i][1]=0; seg[i][2]=0; seg[i][3]=1; } } else if (seg[i*2+1][3]) { if (a[m]>a[m+1]) { seg[i][0]=seg[i*2+2][0]+f(seg[i*2+2][1]); seg[i][1]=(r-l)/2+1; seg[i][2]=seg[i*2+2][2]; seg[i][3]=0; } else { seg[i][0]=seg[i*2+2][0]; seg[i][1]=(r-l)/2+1+seg[i*2+2][1]; seg[i][2]=seg[i*2+2][2]; seg[i][3]=0; } } else if (seg[i*2+2][3]) { if (a[m]>a[m+1]) { seg[i][0]=seg[i*2+1][0]+f(seg[i*2+1][2]); seg[i][1]=seg[i*2+1][1]; seg[i][2]=r-l-(r-l)/2; seg[i][3]=0; } else { seg[i][0]=seg[i*2+1][0]; seg[i][1]=seg[i*2+1][1]; seg[i][2]=r-l-(r-l)/2+seg[i*2+1][2]; seg[i][3]=0; } } else { if (a[m]>a[m+1]) { seg[i][0]=seg[i*2+1][0]+seg[i*2+2][0]+f(seg[i*2+1][2])+f(seg[i*2+2][1]); seg[i][1]=seg[i*2+1][1]; seg[i][2]=seg[i*2+2][2]; seg[i][3]=0; } else { seg[i][0]=seg[i*2+1][0]+seg[i*2+2][0]+f(seg[i*2+1][2]+seg[i*2+2][1]); seg[i][1]=seg[i*2+1][1]; seg[i][2]=seg[i*2+2][2]; seg[i][3]=0; } } } void build(int i, int l, int r) { if (l==r) { cin>>a[l]; seg[i][3]=1; return; } build(i*2+1,l,l+(r-l)/2); build(i*2+2,l+(r-l)/2+1,r); calc(i,l,r); } void update(int i, int l, int r, int x, int y) { if (l==r) { a[x]=y; return; } if (x<=l+(r-l)/2) update(i*2+1,l,l+(r-l)/2,x,y); else update(i*2+2,l+(r-l)/2+1,r,x,y); calc(i,l,r); } void query(int i, int l, int r, int qL, int qR) { if (r<qL||qR<l) return; if (qL<=l&&r<=qR) { if (seg[i][3]) { if (a[l-1]>a[l]) { ans+=f(k); k=r-l+1; } else k+=r-l+1; } else { if (a[l-1]>a[l]) ans+=seg[i][0]+f(k)+f(seg[i][1]); else ans+=seg[i][0]+f(k+seg[i][1]); k=seg[i][2]; } return; } query(i*2+1,l,l+(r-l)/2,qL,qR); query(i*2+2,l+(r-l)/2+1,r,qL,qR); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n,q,t,l,r; cin>>n>>q; build(0,1,n); while (q--) { cin>>t>>l>>r; if (t==1) update(0,1,n,l,r); else { ans=k=0; query(0,1,n,l,r); cout<<ans+f(k)<<"\n"; } } return 0; }
1567
F
One-Four Overload
Alice has an empty grid with $n$ rows and $m$ columns. Some of the cells are marked, and \textbf{no marked cells are adjacent to the edge of the grid}. (Two squares are adjacent if they share a side.) Alice wants to fill each cell with a number such that the following statements are true: - every unmarked cell contains either the number $1$ or $4$; - every marked cell contains the sum of the numbers in all \textbf{unmarked} cells adjacent to it (if a marked cell is not adjacent to any unmarked cell, this sum is $0$); - every marked cell contains a multiple of $5$. Alice couldn't figure it out, so she asks Bob to help her. Help Bob find any such grid, or state that no such grid exists.
Let's look at the numbers in the grid modulo $5$. $1$ and $4$ are $1$ and $-1$ modulo $5$, and by definition each marked cell must be $0$ modulo $5$. This means that each marked cell must have an even number of unmarked neighbors, and there must be an equal number of $1$s and $4$s among those neighbors. In other words, the problem is about two-coloring a grid so each marked square has the same number of red and blue neighbors. If each cell is adjacent to 2 or 4 unmarked cells, then they will form a graph whose faces are two-colorable (the proof of this is below), which will satisfy all conditions, since all cells adjacent to 2 unmarked cells will be adjacent to two cells on opposite faces. However, the tricky case is to deal with cells with 0 unmarked neighbors. The idea is to put a "mask" on top of the grid, which will also allow the cells with no unmarked neighbors to satisfy the condition while not interfering with already placed cells. That is, in the coloring terminology above, we will two color the grid, and then flip some cells according to the "mask" such that all cells with 2 or 4 unmarked neighbors still satisfy the condition, and all cells with 0 unmarked neighbors now satisfy the condition. We claim that we should flip all cells in all even-numbered columns; that is, the mask should contain columns alternately colored red and blue. Let's prove this works. There are four types of marked cells: a marked cell with no marked neighbors: all four neighbors are in same connected component, so none of them will be "flipped" with respect to the rest, and they will work: they will be the numbers $1,4,1,4$ by the mask. For this to hold true, when we make connected components, we need to DFS/BFS diagonally as well. a marked cell with only marked neighors: nothing to check. a marked cell with marked neighbors in the shape of an L tromino: again, these unmarked cells must be part of same connected component, so they will work: they will be the numbers $1$ and $4$ by the mask. For this to hold true, when we make connected components, we need to DFS/BFS diagonally as well. a marked cell with marked neighbors in the shape of an I tromino: then the cell on one side is necessarily in a different connected component than the other, so one will be flipped by the two-coloring, and they will be the right parities. It suffices to show that the graph formed by edges between connected components of unmarked cells is bipartite. Consider instead the graph formed by the marked cells, with an edge between orthogonally adjacent cells. Consider each connected component of this graph individually. By the condition all vertices have degree 0, 2, or 4, but none can have degree 0 because the graph is connected. Now by a theorem of Euler this graph must have a Eulerian cycle. Now we have a more general claim: the face-vertex dual of a Eulerian graph is bipartite. Suppose otherwise. Then the dual has some odd cycle. This means that some face of the dual must be bounded by an odd number of edges, since you can never "split" an odd cycle into only even ones. Also, the dual is planar, because our original graph is obviously planar (we are given an explicit planar embedding of it!). Now some face of the dual has an odd number of edges. This means that in the dual graph of the dual, some vertex has odd degree. But the dual graph of the dual is the original graph. So the original graph is both Eulerian and has odd degree, which is absurd. Finally, even though there are many connected components, it is clear that they do not interact: just set the infinite outside face to be one color, and the rest of the faces will be colored automatically. Therefore this graph is bipartite, so we can two-color as desired, and we are done. Time complexity: $\mathcal{O}(mn)$.
[ "2-sat", "constructive algorithms", "dfs and similar", "dsu", "graphs", "implementation" ]
2,700
#include <bits/stdc++.h> using namespace std; const int MAX = 507; char grid[MAX][MAX] = {}; bool vis[MAX][MAX] = {}; int val[MAX][MAX] = {}, res[MAX][MAX] = {}, color[MAX * MAX] = {}; set<int> graph[MAX * MAX] = {}; int ind = 0; void dfs(int x, int y) { vis[x][y] = true; vector<pair<int, int> > v; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { v.emplace_back(x + i, y + j); } } for (auto p : v) { if (!vis[p.first][p.second] && grid[p.first][p.second] == '.') { val[p.first][p.second] = ind; dfs(p.first, p.second); } } } int flip(int x) { return (x == 1 ? 4 : 1); } void solve() { // take input int n, m; cin >> n >> m; for (int i = 0; i <= n + 1; i++) { for (int j = 0; j <= m + 1; j++) { if (i == 0 || j == 0 || i == n + 1 || j == m + 1) {grid[i][j] = '!';} else {cin >> grid[i][j];} } } // check that all marked cells have proper degree for (int i = 2; i <= n - 1; i++) { for (int j = 2; j <= m - 1; j++) { int cnt = (grid[i - 1][j] == '.') + (grid[i + 1][j] == '.') + (grid[i][j - 1] == '.') + (grid[i][j + 1] == '.'); if (grid[i][j] == 'X' && cnt % 2 == 1) {cout << "NO" << endl; return;} } } // find connected components for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (grid[i][j] == '.' && !vis[i][j]) { ind++; val[i][j] = ind; dfs(i, j); } } } // build graph of connected components for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (grid[i][j] == 'X') { bool horz = (grid[i][j - 1] == '.' && grid[i][j + 1] == '.'); bool vert = (grid[i - 1][j] == '.' && grid[i + 1][j] == '.'); if (horz && (val[i][j - 1] != val[i][j + 1])) { graph[val[i][j - 1]].insert(val[i][j + 1]); graph[val[i][j + 1]].insert(val[i][j - 1]); } if (vert && (val[i - 1][j] != val[i + 1][j])) { graph[val[i - 1][j]].insert(val[i + 1][j]); graph[val[i + 1][j]].insert(val[i - 1][j]); } } } } // make bipartite coloring of graph queue<int> q; for (int i = 1; i <= ind; i++) { if (color[i] == 0) { q.push(i); color[i] = 1; while (!q.empty()) { int v = q.front(); q.pop(); for (int u : graph[v]) { if (color[u] == 0) {color[u] = (color[v] ^ 3); q.push(u);} else if (color[u] == color[v]) {cout << "NO" << endl; return;} } } } } // flip each cell appropriately, column by column for (int j = 1; j <= m; j++) { int curr = (j % 2 ? 4 : 1); res[1][j] = curr; int prev = color[val[1][j]]; for (int i = 2; i <= n; i++) { if (grid[i][j] == '.') { if (color[val[i][j]] != prev) {curr = flip(curr);} res[i][j] = curr; prev = color[val[i][j]]; } } } // find values of marked cells for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (grid[i][j] == 'X') { if (grid[i - 1][j] == '.') {res[i][j] += res[i - 1][j];} if (grid[i + 1][j] == '.') {res[i][j] += res[i + 1][j];} if (grid[i][j - 1] == '.') {res[i][j] += res[i][j - 1];} if (grid[i][j + 1] == '.') {res[i][j] += res[i][j + 1];} } } } // output the answer cout << "YES" << endl; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cout << res[i][j] << ' '; } cout << endl; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); solve(); }
1569
A
Balanced Substring
You are given a string $s$, consisting of $n$ letters, each letter is either 'a' or 'b'. The letters in the string are numbered from $1$ to $n$. $s[l; r]$ is a continuous substring of letters from index $l$ to $r$ of the string inclusive. A string is called balanced if the number of letters 'a' in it is equal to the number of letters 'b'. For example, strings "baba" and "aabbab" are balanced and strings "aaab" and "b" are not. Find any non-empty balanced substring $s[l; r]$ of string $s$. Print its $l$ and $r$ ($1 \le l \le r \le n$). If there is no such substring, then print $-1$ $-1$.
Any non-empty balanced string contains at least one letter 'a' and at least one letter 'b'. That implies that there's an 'a' adjacent to a 'b' somewhere in that string. Both strings "ab" and "ba" are balanced. Thus, any balanced string contains a balanced substring of length $2$. So the solution is to check all $n-1$ pairs of adjacent letters. If there exists a pair of different ones, print it. Overall complexity: $O(n)$ per testcase.
[ "implementation" ]
800
for _ in range(int(input())): n = int(input()) s = input() for i in range(n - 1): if s[i] != s[i + 1]: print(i + 1, i + 2) break else: print(-1, -1)
1569
B
Chess Tournament
A chess tournament will be held soon, where $n$ chess players will take part. Every participant will play one game against every other participant. Each game ends in either a win for one player and a loss for another player, or a draw for both players. Each of the players has their own expectations about the tournament, they can be one of two types: - a player wants not to lose any game (i. e. finish the tournament with \textbf{zero losses}); - a player wants to win at least one game. You have to determine if there exists an outcome for all the matches such that all the players meet their expectations. If there are several possible outcomes, print any of them. If there are none, report that it's impossible.
Since the chess players of the first type should not lose a single game, each game between two chess players of the first type should end in a draw (so that none of them gets defeated). And a game between a chess player of the first type and the second type should end either with a victory of the first or a draw. Therefore, for convenience, we will say that all games with a chess player of the first type end in a draw. Now there are only games between chess players of the second type left. If there are only $1$ or $2$ such players, then there is no answer. Otherwise, we can choose the following method: the $i$-th chess player of the second type wins against the $i+1$-th chess player of the second type, and the last one wins against the first; all remaining games are drawn.
[ "constructive algorithms" ]
1,000
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { int n; string s; cin >> n >> s; vector<int> id; for (int i = 0; i < n; ++i) if (s[i] == '2') id.push_back(i); int k = id.size(); if (k == 1 || k == 2) { cout << "NO\n"; continue; } vector<string> t(n, string(n, '=')); for (int i = 0; i < n; ++i) t[i][i] = 'X'; for (int i = 0; i < k; ++i) { int x = id[i], y = id[(i + 1) % k]; t[x][y] = '+'; t[y][x] = '-'; } cout << "YES\n"; for (int i = 0; i < n; ++i) cout << t[i] << '\n'; } }
1569
C
Jury Meeting
$n$ people gathered to hold a jury meeting of the upcoming competition, the $i$-th member of the jury came up with $a_i$ tasks, which they want to share with each other. First, the jury decides on the order which they will follow while describing the tasks. Let that be a permutation $p$ of numbers from $1$ to $n$ (an array of size $n$ where each integer from $1$ to $n$ occurs exactly once). Then the discussion goes as follows: - If a jury member $p_1$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. - If a jury member $p_2$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. - ... - If a jury member $p_n$ has some tasks left to tell, then they tell one task to others. Otherwise, they are skipped. - If there are still members with tasks left, then the process repeats from the start. Otherwise, the discussion ends. A permutation $p$ is nice if none of the jury members tell two or more of their own tasks in a row. Count the number of nice permutations. The answer may be really large, so print it modulo $998\,244\,353$.
Note that if there are at least two members with the maximum value of $a_i$, then any permutation is nice. Now let's consider the case when there is only one maximum. Let's find out when the permutation is nice. Let $x$ be the index of the jury member with the maximum number of tasks. Then, during the $a_x$-th discussion round, they will be the only one who will tell their task, because the other members of the jury have already told all their tasks. So during the $(a_x-1)$-th discussion round, there should be a jury member who tells a task after the $x$-th jury member. Let $k$ be the number of elements in the array $a$ equal to $a_x-1$. Then, if at least one of these $k$ jury members goes after the jury member $x$ in the permutation, then the permutation is nice. Using this, we will count the number of bad permutations. Let's fix the elements in the permutation that are not equal to $a_x$ or $a_x-1$, there are $n-k-1$ of them, then the number of ways is $A_n^{n-k-1} = \frac{n!}{(k+1)!}$. It remains to place $k+1$ elements so that the maximum is in the last position among them, there are $k!$ such ways. The total number of bad permutations is $\frac{n!k!}{(k+1)!}=\frac{n!}{k + 1}$. So the answer is $n! - \frac{n!}{k + 1}$.
[ "combinatorics", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { int n; cin >> n; vector<int> a(n); for (int &x : a) cin >> x; int mx = *max_element(a.begin(), a.end()); int cmx = count(a.begin(), a.end(), mx); int k = count(a.begin(), a.end(), mx - 1); int ans = 1, sub = 1; for (long long i = 1; i <= n; ++i) { ans = ans * i % MOD; if (i != k + 1) sub = sub * i % MOD; } if (cmx == 1) ans = (ans - sub + MOD) % MOD; cout << ans << '\n'; } }
1569
D
Inconvenient Pairs
There is a city that can be represented as a square grid with corner points in $(0, 0)$ and $(10^6, 10^6)$. The city has $n$ vertical and $m$ horizontal streets that goes across the whole city, i. e. the $i$-th vertical streets goes from $(x_i, 0)$ to $(x_i, 10^6)$ and the $j$-th horizontal street goes from $(0, y_j)$ to $(10^6, y_j)$. All streets are bidirectional. Borders of the city are streets as well. There are $k$ persons staying on the streets: the $p$-th person at point $(x_p, y_p)$ (so either $x_p$ equal to some $x_i$ or $y_p$ equal to some $y_j$, or both). Let's say that a pair of persons form an inconvenient pair if the shortest path from one person to another going only by streets is strictly greater than the Manhattan distance between them. Calculate the number of inconvenient pairs of persons (pairs $(x, y)$ and $(y, x)$ are the same pair). Let's recall that Manhattan distance between points $(x_1, y_1)$ and $(x_2, y_2)$ is $|x_1 - x_2| + |y_1 - y_2|$.
Firstly, let's look at some point $(x_i, y_i)$. Let's find closest to it vertical and horizontal lines. We will name the closest vertical lines from left and right as $lx$ and $rx$ (and $ly$ and $ry$ as closest horizontal lines). So, $lx \le x \le rx$ and $ly \le y \le ry$ (we can also note that either $lx = rx$ or $ly = ry$). Now, let's note that if for some other point $j$ $(x_j, y_j)$ either $lx < x_j < rx$ or $ly < y_j < ry$ then to reach $j$ from $i$ we must go reach either $lx$ or $rx$ (or, $ly$ or $ry$), so the shortest distance will be strictly greater than the Manhattan distance. If neither $lx < x_j < rx$ nor $ly < y_j < ry$, then we can show that it's always possible to find the shortest path equal to the Manhattan distance. As a result, for each point $(x_i, y_i)$ we should find the number of points $(x_j, y_j)$ such that $j < i$ and $lx < x_j < rx$ or $ly < y_j < ry$. The exception here is when $j$ lies on the same line as $i$, so we should not count such points. We can note that since either $lx = rx$ or $ly = ry$ there is no such point $j$ that $lx < x_j < rx$ and $ly < y_j < ry$ simultaneously, so we can calculate the pairs by $x$ and $y$ coordinates independently. Let's focus on $y$ coordinates (to calculate for $x$ coordinates, we can just swap all coordinates). Let's sort all points by $x$ coordinate. To get rid of the case when points $i$ and $j$ lies on the same vertical street, we can group them by $x$ coordinate and process by group (since we sorted by $x$, groups are just segments). There are no problems with the case when points lie on the same horizontal street, since then $ly = ry$ and there are no other $y_j$ with $ly < y_j < ry$. If we store for each horizontal line $y_j$ the number of point inside the interval $(y_i, y_{i + 1})$ then, when we need for point $i$ calculate the number of points $j$ with $j < i$ and $ly < y_j < ry$, we can just ask for value assigned to $ly$, because $ly$ and $ry$ are consecutive elements in the array $y$. So, we go through each group two times: first collecting answer, then updating values in appropriate $ly$-s. Note, that we can calculate $ly$ and $ry$ with binary search (using built-in functions). The resulting complexity is $O(n + m + k (\log{k} + \log{n} + \log{m}))$.
[ "binary search", "data structures", "implementation", "sortings", "two pointers" ]
1,900
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define sz(a) int((a).size()) #define all(a) (a).begin(), (a).end() #define x first #define y second typedef long long li; typedef pair<int, int> pt; template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) { return out << "(" << p.x << ", " << p.y << ")"; } template<class A> ostream& operator <<(ostream& out, const vector<A> &v) { fore(i, 0, sz(v)) { if(i) out << " "; out << v[i]; } return out; } const int INF = int(1e9); const li INF64 = li(1e18); int n, m, k; vector<int> x, y; vector<pt> ps; inline bool read() { if(!(cin >> n >> m >> k)) return false; x.resize(n); fore (i, 0, n) cin >> x[i]; y.resize(m); fore (i, 0, m) cin >> y[i]; ps.resize(k); fore (i, 0, k) cin >> ps[i].x >> ps[i].y; return true; } inline void solve() { li ans = 0; fore (_i, 0, 2) { vector<int> cntY(m, 0); sort(all(ps)); vector<pt> bord(k); int u = 0; while (u < k) { int v = u; while (v < k && ps[v].x == ps[u].x) v++; fore (i, u, v) { int r = int(lower_bound(all(y), ps[i].y) - y.begin()); int l = r; if (y[l] > ps[i].y) l--; assert(y[l] <= ps[i].y && ps[i].y <= y[r]); bord[i] = {l, r}; } fore (i, u, v) if (bord[i].x < bord[i].y) ans += cntY[bord[i].x]; fore (i, u, v) if (bord[i].x < bord[i].y) cntY[bord[i].x]++; u = v; } fore (i, 0, k) swap(ps[i].x, ps[i].y); swap(x, y); swap(n, m); } cout << ans << endl; } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); cout << fixed << setprecision(15); int t; cin >> t; while (t--) { read(); solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1569
E
Playoff Restoration
$2^k$ teams participate in a playoff tournament. The tournament consists of $2^k - 1$ games. They are held as follows: first of all, the teams are split into pairs: team $1$ plays against team $2$, team $3$ plays against team $4$ (exactly in this order), and so on (so, $2^{k-1}$ games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only $2^{k-1}$ teams remain. If only one team remains, it is declared the champion; otherwise, $2^{k-2}$ games are played: in the first one of them, the winner of the game "$1$ vs $2$" plays against the winner of the game "$3$ vs $4$", then the winner of the game "$5$ vs $6$" plays against the winner of the game "$7$ vs $8$", and so on. This process repeats until only one team remains. After the tournament ends, the teams are assigned places according to the tournament phase when they were eliminated. In particular: - the winner of the tournament gets place $1$; - the team eliminated in the finals gets place $2$; - both teams eliminated in the semifinals get place $3$; - all teams eliminated in the quarterfinals get place $5$; - all teams eliminated in the 1/8 finals get place $9$, and so on. For example, this picture describes one of the possible ways the tournament can go with $k = 3$, and the resulting places of the teams: After a tournament which was conducted by the aforementioned rules ended, its results were encoded in the following way. Let $p_i$ be the place of the $i$-th team in the tournament. The hash value of the tournament $h$ is calculated as $h = (\sum \limits_{i=1}^{2^k} i \cdot A^{p_i}) \bmod 998244353$, where $A$ is some given integer. Unfortunately, due to a system crash, almost all tournament-related data was lost. The only pieces of data that remain are the values of $k$, $A$ and $h$. You are asked to restore the resulting placing of the teams in the tournament, if it is possible at all.
There are exactly $2^k-1$ games in the tournament, each game has only two possible outcomes. So it's possible to bruteforce all $2^k-1$ possible ways the tournament could go if $k$ is not large. In fact, this solution is fast enough when $k < 5$, so if we somehow can handle the case $k = 5$, we will have a working solution. To handle $k = 5$, let's divide the teams into two groups: teams from $1$ to $16$ and teams from $17$ to $32$. There will be exactly $15$ matches in each group, and the winners of these two groups will play in the finals. The number of possible ways the games in a group can go is just $2^{15}$, so let's try to bruteforce all possible results in each group and somehow "merge" them into the results of the whole tournament. The main idea is to rewrite $h$ as $(h_1 + h_2) \bmod 998244353$, where $h_1 = (\sum \limits_{i=1}^{16} i \cdot A^{p_i}) \bmod 998244353$, and $h_2 = (\sum \limits_{i=17}^{32} i \cdot A^{p_i}) \bmod 998244353$, find all possible values for $h_1$ and $h_2$, and choose a pair of values that yields exactly the given value of $h$. We will handle two separate cases: the winner of the first group wins the whole tournament, or the winner of the second group wins the whole tournament. Suppose we are handling the first case (the second is symmetrical). By choosing the results of matches in the first group, we determine the places of the teams from the first group in the whole tournament: the winner of the first group gets place $1$, the team eliminated in the last match of the first group gets place $3$, and so on. It means that by choosing one of the $2^{15}$ possible results in the first group, we can calculate $h_1$. Let's bruteforce these $2^{15}$ combinations of results in the first group and store them in some data structure that allows to check whether some value of $h_1$ is achievable (in the model solution, it's a std::map which maps reachable values of $h_1$ to combinations of results that yield these values). Then, by choosing the results of matches in the second group, we can calculate $h_2$; so the remaining part of the solution is to bruteforce all $2^{15}$ possible results in the second group, calculate $h_2$ for them, and check that $h_1$ such that $(h_1 + h_2) \bmod 998244353 = h$ can be achieved by choosing the results in the first group. Don't forget to also handle the case when the team which wins in the first group loses in the finals (it is almost the same, but the winner in the first group gets place $2$ and the winner in the second group gets place $1$). The technique I've described here (instead of bruteforcing all possible variants, split the thing we try to bruteforce into two parts, bruteforce them separatedly, and then try to "merge" the parts) is called meet-in-the-middle and can be used to solve a large variety of problems.
[ "bitmasks", "brute force", "hashing", "implementation", "meet-in-the-middle" ]
2,600
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int binpow(int x, int y) { int z = 1; while(y) { if(y & 1) z = mul(z, x); x = mul(x, x); y >>= 1; } return z; } vector<int> evaluate(int n, int choice_mask) { int cur_place = n / 2 + 1; int cur_bit = n - 2; vector<int> p(n); vector<int> c(n); for(int i = 0; i < n; i++) c[i] = i; while(c.size() != 1) { vector<int> nc; for(int i = 0; i < c.size(); i += 2) { if(choice_mask & (1 << cur_bit)) { p[c[i]] = cur_place; nc.push_back(c[i + 1]); } else { p[c[i + 1]] = cur_place; nc.push_back(c[i]); } cur_bit--; } c = nc; cur_place /= 2; cur_place++; } p[c[0]] = 1; return p; } vector<int> adjust(int n, vector<int> p, bool winning) { for(int i = 0; i < n; i++) { if(p[i] == 1) { if(!winning) p[i]++; } else p[i] = p[i] * 2 - 1; } return p; } int get_hash(int n, vector<int> p, int A, bool partial = false, bool winning = false, int shift = 0) { if(partial) p = adjust(n, p, winning); int res = 0; for(int i = 0; i < n; i++) res = add(res, mul(add(i + 1, shift), binpow(A, p[i]))); return res; } int main() { int k, A, h; cin >> k >> A >> h; if(k <= 4) { for(int i = 0; i < (1 << ((1 << k) - 1)); i++) { vector<int> p = evaluate(1 << k, i); if(get_hash(1 << k, p, A) == h) { for(auto x : p) cout << x << " "; cout << endl; return 0; } } } else { int mask_left = -1; int mask_right = -1; bool left_win = false; for(int c = 0; c < 2; c++) { map<int, int> left_map; for(int i = 0; i < (1 << 16); i++) { vector<int> p = evaluate(16, i); int left_hash = get_hash(16, p, A, true, c == 0, 0); left_map[left_hash] = i; } for(int i = 0; i < (1 << 16); i++) { vector<int> p = evaluate(16, i); int right_hash = get_hash(16, p, A, true, c == 1, 16); int left_hash = add(h, MOD - right_hash); if(left_map.count(left_hash)) { mask_left = left_map[left_hash]; mask_right = i; left_win = (c == 0); } } } if(mask_left != -1) { vector<int> ans_left = evaluate(16, mask_left); vector<int> ans_right = evaluate(16, mask_right); ans_left = adjust(16, ans_left, left_win); ans_right = adjust(16, ans_right, !left_win); for(auto x : ans_left) cout << x << " "; for(auto x : ans_right) cout << x << " "; return 0; } } cout << -1 << endl; return 0; }
1569
F
Palindromic Hamiltonian Path
You are given a simple undirected graph with $n$ vertices, $n$ is even. You are going to write a letter on each vertex. Each letter should be one of the first $k$ letters of the Latin alphabet. A path in the graph is called Hamiltonian if it visits each vertex exactly once. A string is called palindromic if it reads the same from left to right and from right to left. A path in the graph is called palindromic if the letters on the vertices in it spell a palindromic string without changing the order. A string of length $n$ is good if: - each letter is one of the first $k$ lowercase Latin letters; - if you write the $i$-th letter of the string on the $i$-th vertex of the graph, there will exist a palindromic Hamiltonian path in the graph. Note that the path doesn't necesserily go through the vertices in order $1, 2, \dots, n$. Count the number of good strings.
Let's start with making some implications from the low constraints. What's the upper estimate on the number of answers? $12^{12}$. Too high, let's think of a better one. Using some combinatorics, we can normalize the answers in such a way that there are at most $12$-th Bell's number of them. The method basically defines the components of equal letters. Given a string, we write down the letters in it in the order they appear for the first time in the string and rename the first of them to 'a', the second one to 'b' and so on. Only $4 \cdot 10^6$ possible answers already. Hmm, but we should also have an even amount of each letter. That is the absolute lowest estimate, and it's equal to about $2 \cdot 10^6$. What does it exactly mean for a string to be good? There exists a path such that: there's a pair of equal letters that occupy the $1$-st and the $n$-th vertex in the path, a pair on the $2$-nd and $(n-1)$-th and so on. So for each of $2 \cdot 10^6$ possible answers, we want to determine if there's a way to split the groups of equal letters into pairs of equal letters such that there exists a path through these pairs. Such a path would mean building a palindrome from inside out. A quick estimation on a number of splittings into pairs. The first letter can be matched against $11$ other letters, the first among the unmatched ones - against $9$ other letters and so on. Thus, it's equal to $11 \cdot 9 \cdot ... \cdot 1 = 10395$. For each splitting into pairs, we can determine if there exists a path. That is a straightforward dynamic programming similar to a usual hamiltonian path search. It stores a mask of visited pairs and the last visited pair. For a transition, you want to either go from the first vertex of one pair to the first vertex of another one and from the second to the second, or the other way around. That would take $2^6 \cdot 6^2$ for each splitting. The only thing left is to propagate the results from the splitting into pairs to splitting into even sized components of equal letters. A splitting into pairs is a splitting into components of size $2$. Let that be a base case for the dp. For every splitting into components, find a component of size at least $4$ (we still have to split it into pairs) and separate it into a component of size $2$ (a pair) and the rest of the component. Moreover, a pair can always be chosen in such a way that one of its elements is the first element of the component. So there are $2 \cdot 10^6$ states and at most $11$ transitions from each of them. Maybe there's a more convenient way to store the states, but the one I found to be fast enough is hashing the state into a base-$6$ integer (since there are no more than $6$ components, numbered $0$ through $5$) and storing it in a map/hashmap.
[ "brute force", "dfs and similar", "dp", "graphs", "hashing" ]
3,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; vector<vector<char>> g; map<long long, bool> dp; void brute(int n, vector<int> &p){ int x = find(p.begin(), p.end(), -1) - p.begin(); if (x == int(p.size())){ vector<vector<char>> dp2(1 << n, vector<char>(n)); vector<int> pos1(n), pos2(n); forn(i, p.size()){ pos1[p[i]] = pos2[p[i]]; pos2[p[i]] = i; } forn(i, n) if (g[pos1[i]][pos2[i]]) dp2[1 << i][i] = true; forn(mask, 1 << n) forn(i, n) if (dp2[mask][i]){ forn(j, n) if (!((mask >> j) & 1)){ dp2[mask | (1 << j)][j] |= (g[pos1[i]][pos1[j]] && g[pos2[i]][pos2[j]]); dp2[mask | (1 << j)][j] |= (g[pos1[i]][pos2[j]] && g[pos2[i]][pos1[j]]); } } forn(i, n) if (dp2[(1 << n) - 1][i]){ long long num = 0; for (int x : p) num = num * 6 + x; dp[num] = true; break; } return; } for (int y = x + 1; y < int(p.size()); ++y) if (p[y] == -1){ p[x] = p[y] = n; brute(n + 1, p); p[x] = p[y] = -1; } } bool dfs(vector<int> p){ vector<int> used(int(p.size()), -1); int cnt = 0; forn(i, p.size()) if (used[p[i]] == -1) used[p[i]] = cnt++; long long num = 0; for (int& x : p){ x = used[x]; num = num * 6 + x; } if (dp.count(num)) return dp[num]; bool res = false; vector<int> cur(cnt); forn(i, p.size()) ++cur[p[i]]; forn(i, p.size()) if (cur[p[i]] > 2){ int x = p[i]; for (int j = i + 1; j < int(p.size()); ++j) if (p[j] == p[i]){ p[i] = p[j] = cnt; if (dfs(p)){ res = true; break; } p[i] = p[j] = x; } break; } return dp[num] = res; } void brute2(int n, vector<int> &p){ int x = find(p.begin(), p.end(), -1) - p.begin(); if (x == int(p.size())){ dfs(p); return; } forn(i, n + 1){ for (int y = x + 1; y < int(p.size()); ++y) if (p[y] == -1){ p[x] = p[y] = i; brute2(max(n, i + 1), p); p[x] = p[y] = -1; } } } int main() { int n, m, k; scanf("%d%d%d", &n, &m, &k); g.resize(n, vector<char>(n)); forn(_, m){ int v, u; scanf("%d%d", &v, &u); --v, --u; g[v][u] = g[u][v] = 1; } vector<int> cur(n, -1); brute(0, cur); brute2(0, cur); vector<long long> fact(k + 1); fact[0] = 1; for (int i = 1; i <= k; ++i) fact[i] = fact[i - 1] * i; long long ans = 0; for (auto it : dp) if (it.second){ long long num = it.first; long long mx = 1; while (num){ mx = max(mx, num % 6 + 1); num /= 6; } if (mx <= k){ ans += fact[k] / fact[k - mx]; } } printf("%lld\n", ans); return 0; }
1572
A
Book
You are given a book with $n$ chapters. Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list. Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter. Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.
There are two main solutions in this task. The first solution simulates the process of reading the book. Let $r_i$ be the number of chapters that need to be understood in order to understand $i$-th chapter. We will keep this array updated during the simulation. Now we will simulate the process by keeping a set of chapters that are ready to be understood. Suppose we have just understood chapter $x$. We will update array $r$ by iterating over all chapters that require $x$ to be understood. If some chapter becomes ready to be understood, we will insert it to the set. Then, we will lowerbound on our set to the next chapter that can be understood and when we hit the end, the answer increases by one and we come back to the beginning. The entire process runs in $O(n \log n)$. The second solution is more graph based. We will construct a graph, where there is a directed edge from $a$ to $b$ if chapter $b$ is needed to understand chapter $a$. This edge has weight $0$ if $a > b$ and $1$ otherwise. The answer is the length of the longest weighted path in this graph incremented by $1$. If there exists a cycle we should output $-1$. If the graph is a DAG, we can use toposort and a simple DP to calculate the answer. This solution works in $O(n)$
[ "binary search", "brute force", "data structures", "dp", "graphs", "implementation", "sortings" ]
1,800
null
1572
B
Xor of 3
You are given a sequence $a$ of length $n$ consisting of $0$s and $1$s. You can perform the following operation on this sequence: - Pick an index $i$ from $1$ to $n-2$ (inclusive). - Change all of $a_{i}$, $a_{i+1}$, $a_{i+2}$ to $a_{i} \oplus a_{i+1} \oplus a_{i+2}$ simultaneously, where $\oplus$ denotes the bitwise XOR operation Find a sequence of \textbf{at most} $n$ operations that changes all elements of $a$ to $0$s or report that it's impossible.We can prove that if there exists a sequence of operations of any length that changes all elements of $a$ to $0$s, then there is also such a sequence of length not greater than $n$.
If the xor of all numbers in the array equals $1$ it is impossible to make everything equal to $0$, since the parity of all numbers doesn't change after an operation. From now on we will assume that the xor of all numbers equals $0$. Lets consider the case when $n$ is odd. We can perform operations on positions $1, 3, ... n-4, n-2$. After this for every even $i$, $a_{i-1} = a_i$. Additionally, $a_n = a_{n-1} = a_{n-2} = 0$. Second one is true since the xor of all numbers equals $0$. Now we can perform operations on positions $n-4, n-6, ... 3, 1$. This will make the array equal to $0$. In the case of even $n$ we will find a prefix of odd length and even xor of numbers and call the above solution on it and its respective suffix. If there is no such prefix, the solution doesn't exist. Here is a proof of it. Assume that every prefix of odd length has an odd xor. This means that $a_1 = a_n = 1$ and for every even $i < n$, $a_i = a_{i+1}$. Consider an operation on an even position $i$ (odd is analogous). We know that $a_i = a_{i+1}$ so after this operation $a_i$ and $a_{i+1}$ will be set to $a_{i+2}$. This means that after every operation for every even $i < n$, $a_i = a_{i+1}$ still holds. Thus we will never be able to make $a_1$ equal to $0$ since performing an operation on it won't change it. Summing up, we perform no more than $n$ operations and our solution runs in $O(n)$
[ "brute force", "constructive algorithms", "greedy", "two pointers" ]
2,500
null
1572
C
Paint
You are given a $1$ by $n$ pixel image. The $i$-th pixel of the image has color $a_i$. For each color, the number of pixels of that color is \textbf{at most} $20$. You can perform the following operation, which works like the bucket tool in paint programs, on this image: - pick a color — an integer from $1$ to $n$; - choose a pixel in the image; - for all pixels connected to the selected pixel, change their colors to the selected color (two pixels of the same color are considered connected if all the pixels between them have the same color as those two pixels). Compute the minimum number of operations needed to make all the pixels in the image have the same color.
Firstly, we can notice that when we modify a segment of the form $[a, b, a]$ and change it to $[a, a, a]$ by performing the operation on the second element, as opposed to performing the operation first on the third element and then on the second element (like so $[a, b, a] \to [a, b, b] \to [a, a, a]$) we avoid using one unnecessary operation. In our solution we will try to maximize the number of operations that we didn't have to perform. Let $dp[i][j]$ be the maximum number of operations that we can avoid on the interval from $i$ to $j$, while making all of its elements have the same color. Then the answer to the problem will be $n-1-dp[1][n]$. For $i \ge j$ we have $dp[i][j] = 0$ and for $i < j$ $dp[i][j]$ will be the maximum of $dp[i + 1][j]$ and $\max(1 + dp[i + 1][k - 1] + dp[k][j])$ over $i< k\le j$ such that $a[i]=a[k]$. It's because we can either not save any operations on the $i$-th element and just take the answer from the interval $[i + 1, j]$ or we can save one operation while coloring the segment from $i$ to $k$ and take the answer from segments $[i+1, k-1]$ and $[k, j]$. Because each color occurs in $a$ at most $20$ times, we can calculate this $dp$ in $O(20n^2)$ which is also our final time complexity.
[ "dp", "greedy" ]
2,700
null
1572
D
Bridge Club
There are currently $n$ hot topics numbered from $0$ to $n-1$ at your local bridge club and $2^n$ players numbered from $0$ to $2^n-1$. Each player holds a different set of views on those $n$ topics, more specifically, the $i$-th player holds a positive view on the $j$-th topic if $i\ \&\ 2^j > 0$, and a negative view otherwise. Here $\&$ denotes the bitwise AND operation. You are going to organize a bridge tournament capable of accommodating at most $k$ pairs of players (bridge is played in teams of two people). You can select teams arbitrarily while each player is in at most one team, but there is one catch: two players cannot be in the same pair if they disagree on $2$ or more of those $n$ topics, as they would argue too much during the play. You know that the $i$-th player will pay you $a_i$ dollars if they play in this tournament. Compute the maximum amount of money that you can earn if you pair the players in your club optimally.
Let's make a graph in which the vertices are the players and there is an edge of weight $a_i + a_j$ between the $i$-th and the $j$-th player if they can play together. We can notice that the problem can then be solved by finding a matching of size at most $k$ with the biggest sum of weights in this graph. To solve this problem efficiently we can make the following observations: 1. The graph is bipartite. This stands from the fact that if two players disagree at exactly $1$ topic then the numbers of positive views that they hold have different parities. 2. We can limit ourselves to considering only the $(2n-1)(k-1) + 1$ edges with the biggest weights. We can prove this with a proof by contradiction. Firstly, we can notice that if we use a particular edge in the matching then we prohibit ourselves from using at most $2(n-1)$ other edges with each of the matched vertices being incident to exactly $n-1$ of those edges, because each vertex has degree $n$ in this graph. Now we can see that if we were to use an edge that's not one of those $(2n-1)(k-1)+1$ best ones, then we can just replace it with one of those best ones, because we know that at least one of them will not be prohibited. Combining those two observations we are left with a bipartite graph with $O(nk)$ edges and $O(nk)$ vertices in which we can find a matching with maximum cost and size at most $k$ with for example one of the standard min cost max flow algorithms (we can look for a matching of size $k$ because all edges have non-negative weights). The only problem that's left for us to solve is efficiently selecting those best edges. Because there are $O(n2^n)$ edges in total we cannot use a standard sorting algorithm as that would run in $O(n^2 2^n)$. Instead we can for example use the quick select algorithm which solves this problem in $O(n2^n)$. Our final time complexity is then $O(n2^n + nk^2\log(kn))$.
[ "flows", "graph matchings", "graphs", "greedy" ]
2,800
null
1572
E
Polygon
You are given a strictly convex polygon with $n$ vertices. You will make $k$ cuts that meet the following conditions: - each cut is a segment that connects two different nonadjacent vertices; - two cuts can intersect only at vertices of the polygon. Your task is to maximize the area of the smallest region that will be formed by the polygon and those $k$ cuts.
We are going to binary search the answer. Lets say that we want to check whether we can obtain $k+1$ regions with area of at least $w$. From now on a correct cut means a cut that will cut off a region with area of a least $w$. Lets consider some interval of vertices $(i, j)$. We will cut it off virtually using a cut from $i$ to $j$. We would like to know how many correct regions we can obtain by performing cuts only in this interval. The area next to the virtual cut is considered a leftover. Given two sets of correct cuts in this interval it's always optimal to choose the one with more cuts and if they have the same amount of cuts, the one with the bigger leftover. This observation leads us to a dynamic programming solution. Let $dp_{i, j}$ be a pair $(r_{i, j}, l_{i, j})$ where $r_{i, j}$ means the biggest amount of regions and $l_{i, j}$ the biggest leftover we can obtain by performing cuts in the interval $(i, j)$. To calculate this $dp$ we will iterate over all vertices $k$ such that $i < k < j$ and consider vertex $k$ as one of the vertices that are included in the leftover region. This is a simple transition from states $dp_{i, k}$ and $dp_{k, j}$. After we calculate our $dp$ state we can safely cut this interval off if $l_{i, j} \ge w$. Iff $r_{1, n} \ge k + 1$ the answer equals at least $w$. This solution runs in $O(n^3 \log(10^{16}))$.
[ "binary search", "dp", "geometry" ]
3,000
null
1572
F
Stations
There are $n$ cities in a row numbered from $1$ to $n$. The cities will be building broadcasting stations. The station in the $i$-th city has height $h_i$ and range $w_i$. It can broadcast information to city $j$ if the following constraints are met: - $i \le j \le w_i$, and - for each $k$ such that $i < k \le j$, the following condition holds: $h_k < h_i$. In other words, the station in city $i$ can broadcast information to city $j$ if $j \ge i$, $j$ is in the range of $i$-th station, and $i$ is strictly highest on the range from $i$ to $j$ (including city $j$).At the beginning, for every city $i$, $h_i = 0$ and $w_i = i$. Then $q$ events will take place. During $i$-th event one of the following will happen: - City $c_i$ will rebuild its station so that its height will be strictly highest among all stations and $w_{c_i}$ will be set to $g_i$. - Let $b_j$ be the number of stations that can broadcast information to city $j$. Print the sum of $b_j$ over all $j$ satisfying $l_i \le j \le r_i$. Your task is to react to all events and print answers to all queries.
We will maintain the array $b$ on a range add/sum segment tree. Queries are done then in $O(\log n)$ per query. Now lets focus on the station rebuilds. Lets maintain an array $w$, which means how far a station can broadcast information including the fact that some stations might block the signal. When a station is rebuild in city $c_i$ we need to perform a $min$ operation on interval $(1, c_i - 1)$ with value $c_i-1$. Next we have to set $w_{c_i}$ to $g_i$. These are all changes to array $w$ that happen during a single rebuild. Now we want to keep array $b$ up to date. We need to know what has been changed and a list of changes to array $w$ is all we need. When setting $w_{c_i}$ to $g_i$ we can add $1$ on interval $(c_i, g_i)$. This is fast enough to do with a single operation on array $b$, since we do this once for every rebuild. Lets say that $w_j$ was decreased as a result of the $min$ operation. To update array $b$ accordingly we should subtract 1 on interval $(c_i, w_j)$. Sadly, performing a subtraction on $b$ for every value in array $w$ that has changed during the $min$ operation one by one is too slow and we can't afford it. Thankfully, we can speed this up. First, we will think how to keep array $w$ updated. We can use segment tree beats to perform the $min$ operation. Recall that during the $min$ operation we get to know what elements and how many times have changed. This is traditionally used to update the sum over interval information. Now we are going to use it in a different way. Lets say that value $r$ was decreased $p$ times in a node where we perform a tag. To keep array $b$ updated we only need subrtact $p$ from interval $(c_i, r)$. Lets think about the complexity now. Segment tree beats with $min$ and $set$ $point$ operations run in amortized $O((n+q) \log n)$ meaning that we will perform at most this many changes on array $b$. This leads us to our total time complexity of $O((n+q) \log^2 n)$.
[ "data structures" ]
3,400
null
1573
A
Countdown
You are given a digital clock with $n$ digits. Each digit shows an integer from $0$ to $9$, so the whole clock shows an integer from $0$ to $10^n-1$. The clock will show leading zeroes if the number is smaller than $10^{n-1}$. You want the clock to show $0$ with as few operations as possible. In an operation, you can do one of the following: - decrease the number on the clock by $1$, or - swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show $0$.
Let $s$ be the sum of all digits. In one operation we can decrease $s$ by at most $1$ and we are finished iff $s = 0$. This leads us to a conclusion that it is always unoptimal to decrease the number on the clock, when the least significant digit shows $0$, since it will cost us at least $9$ more operations. Using this observation, the following strategy turns out to be optimal: if the least significant digit is positive, decrease the number by $1$ if the least significant digit equals $0$, swap it with some positive digit Let $p$ be the number of digits that are positive and aren't the least significant digit. Our answer will be $s + p$. This can be computed in $O(n)$.
[ "greedy" ]
800
null
1573
B
Swaps
You are given two arrays $a$ and $b$ of length $n$. Array $a$ contains each \textbf{odd} integer from $1$ to $2n$ in an arbitrary order, and array $b$ contains each \textbf{even} integer from $1$ to $2n$ in an arbitrary order. You can perform the following operation on those arrays: - choose one of the two arrays - pick an index $i$ from $1$ to $n-1$ - swap the $i$-th and the $(i+1)$-th elements of the chosen array Compute the minimum number of operations needed to make array $a$ lexicographically smaller than array $b$.For two different arrays $x$ and $y$ of the same length $n$, we say that $x$ is lexicographically smaller than $y$ if in the first position where $x$ and $y$ differ, the array $x$ has a smaller element than the corresponding element in $y$.
Since the array $a$ has odd numbers and array $b$ has even numbers, then they will differ at the first position no matter how we perform the operations. It follows that in order to make the first array lexicographically smaller than the second one we need to make the first element of $a$ smaller than the first element of $b$. To move the $i$-th element of an array to the first position we can perform the operation on elements $i - 1$, $i - 2$, ..., $2$, $1$, which is optimal. The answer is then the minimum of $i + j - 2$ over all $a_i$, $b_j$ such that $a_i < b_j$. Now we will think how to calculate this effectively. Let $p_i$ be the position of number $i$ in its respective sequence ($a$ for odd and $b$ for even). We will go through the numbers from biggest to smallest. Let $l$ be the position of the leftmost number in sequence $b$ that was already considered. If $i$ is even we will set $l$ to $min(l, p_i)$. If $i$ is odd we will set $answer$ to $min(answer, p_i + l)$. Our total time complexity is then $O(n)$.
[ "greedy", "math", "sortings" ]
1,400
null
1574
A
Regular Bracket Sequences
A bracket sequence is a string containing only characters "(" and ")". 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 (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not. You are given an integer $n$. Your goal is to construct and print \textbf{exactly $n$} different regular bracket sequences of length $2n$.
There are many ways to solve this problem. The model solution does the following thing: start with the sequence ()()()()...; merge the first $4$ characters into one sequence to get (())()()...; merge the first $6$ characters into one sequence to get ((()))()...; and so on.
[ "constructive algorithms" ]
800
t = int(input()) for i in range(t): n = int(input()) for j in range(n): print("()" * j + "(" * (n - j) + ")" * (n - j))
1574
B
Combinatorics Homework
You are given four integer values $a$, $b$, $c$ and $m$. Check if there exists a string that contains: - $a$ letters 'A'; - $b$ letters 'B'; - $c$ letters 'C'; - no other letters; - exactly $m$ pairs of adjacent equal letters (exactly $m$ such positions $i$ that the $i$-th letter is equal to the $(i+1)$-th one).
Let's start with a simple assumption. For some fixed values $a, b, c$, the values of $m$ that the answers exist for, make up a range. So there's the smallest possible number of adjacent equal pairs one can construct and the largest one - everything in-between exists as well. The largest number is simple - put all A's, then all B's, then all C's. So this value is $(a - 1) + (b - 1) + (c - 1)$. The smallest number is trickier. Let's instead investigate when it's equal to $0$. WLOG, assume $a \le b \le c$. Imagine the following construction. There are $c$ letters C which separate blocks of letters A and B. There are $c-1$ ($c+1$ if you consider the ones to the sides of all letters C, but we want the smallest value, so we shouldn't consider them) such blocks, thus it's possible that each block contains no more than one letter A and no more than one letter B. So letters A and B will never produce adjacent pairs. If there are empty blocks, then there are adjacent letters C. So the condition to still have no empty blocks is to have at least $c-1$ letters A and B in total. If $c - 1 > a + b$, then any extra letter C can only be put adjacent to another letter C, thus producing an extra pair (at least one extra pair, but since we are examining the lower bound, we can always do exactly one). That means that the lower bound is $c - 1 - (a + b)$. Now for the proof of the fact that every value in-between is also achievable. Since we have a construction for $m = 0$, let's try modifying it. Let's reduce the test to $m = 0$ the following way. While $m > 0$, decrease the count of the letter that appears the most by $1$ and decrease $m$ by $1$. Now build the string for $m = 0$ with the reduced values. After that put the letters back, placing them next to the last occurrence of the same letter (there is at least one occurrence of each letter, the proof is trivial). That increases $m$ by $1$ and the count of this letter by $1$. Thus, we'll return to the initial test. Overall complexity: $O(1)$ per testcase.
[ "combinatorics", "greedy", "math" ]
1,100
for _ in range(int(input())): a, b, c, m = map(int, input().split()) a, b, c = sorted([a, b, c]) print("YES" if c - (a + b + 1) <= m <= a + b + c - 3 else "NO")
1574
C
Slay the Dragon
Recently, Petya learned about a new game "Slay the Dragon". As the name suggests, the player will have to fight with dragons. To defeat a dragon, you have to kill it and defend your castle. To do this, the player has a squad of $n$ heroes, the strength of the $i$-th hero is equal to $a_i$. According to the rules of the game, exactly one hero should go kill the dragon, all the others will defend the castle. If the dragon's defense is equal to $x$, then you have to send a hero with a strength of at least $x$ to kill it. If the dragon's attack power is $y$, then the total strength of the heroes defending the castle should be at least $y$. The player can increase the strength of any hero by $1$ for one gold coin. This operation can be done any number of times. There are $m$ dragons in the game, the $i$-th of them has defense equal to $x_i$ and attack power equal to $y_i$. Petya was wondering what is the minimum number of coins he needs to spend to defeat the $i$-th dragon. Note that the task is solved \textbf{independently for each dragon} (improvements are not saved).
It is enough to consider two cases: whether we will increase the strength of the hero who will kill the dragon or not. If you do not increase the hero's strength, then you have to choose such $i$ that $a_i \ge x$. Obviously, among such $i$, you have to choose with the minimum value $a_i$, because the strength of defending heroes is equal to $\sum\limits_{j=1}^n a_j - a_i$. It remains to increase the total strength of the remaining heroes to $y$. So the required number of coins is equal to $\max(0, y - (\sum\limits_{j=1}^n a_j - a_i))$. If you increase the hero's strength, then you have to choose the maximum value of $a_i$, which is less than $x$. In this case, the required number of coins is $x - a_i$ to increase the strength of the hero who will kill the dragon, plus $\max(0, y - (\sum\limits_{j=1}^n a_j - a_i))$ to increase the strength of the defending heroes. To find the heroes with strength as close to $x$ as possible, you can use binary search (don't forget to sort the heroes beforehand).
[ "binary search", "greedy", "sortings", "ternary search" ]
1,300
#include <bits/stdc++.h> using namespace std; using li = long long; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<li> a(n); for (auto &x : a) cin >> x; sort(a.begin(), a.end()); li sum = accumulate(a.begin(), a.end(), 0LL); int m; cin >> m; while (m--) { li x, y; cin >> x >> y; int i = lower_bound(a.begin(), a.end(), x) - a.begin(); li ans = 2e18; if (i > 0) ans = min(ans, (x - a[i - 1]) + max(0LL, y - sum + a[i - 1])); if (i < n) ans = min(ans, max(0LL, y - sum + a[i])); cout << ans << '\n'; } }
1574
D
The Strongest Build
Ivan is playing yet another roguelike computer game. He controls a single hero in the game. The hero has $n$ equipment slots. There is a list of $c_i$ items for the $i$-th slot, the $j$-th of them increases the hero strength by $a_{i,j}$. The items for each slot are pairwise distinct and are listed in the increasing order of their strength increase. So, $a_{i,1} < a_{i,2} < \dots < a_{i,c_i}$. For each slot Ivan chooses exactly one item. Let the chosen item for the $i$-th slot be the $b_i$-th item in the corresponding list. The sequence of choices $[b_1, b_2, \dots, b_n]$ is called a build. The strength of a build is the sum of the strength increases of the items in it. Some builds are banned from the game. There is a list of $m$ pairwise distinct banned builds. It's guaranteed that there's at least one build that's not banned. What is the build with the maximum strength that is not banned from the game? If there are multiple builds with maximum strength, print any of them.
Consider the bruteforce solution. You start with a build that contains the most powerful item for each slot. In one move, you swap an item in some slot for the one that is the previous one by power. If a build is not banned, update the answer with its total power (banned builds can be stored in a set, maybe hashset if you hash carefully enough). Notice that if you reach some unbanned build in this bruteforce, it never makes sense to go further. The answer is already updated with this one, and all the lower ones have smaller power. If you code that bruteforce in a smart way (or just add memorization), you won't visit any build twice. How many states will you visit, though? Since you can only proceed if you are standing in a banned build, you will check around $m + mn$ builds. You can code it like that and get accepted. However, there's another way that's easier to code, in my opinion. The optimal answer can be one of only two types. Either it contains the last item of each slot. Or it's some banned build with one item swapped with the previous one. It's easy to see from the solution above. So you can check the first type, then iterate over the banned build and try swapping each slot in it, checking if the resulting build is banned or not. Overall complexity: $O(mn)$ or $O(mn \log m)$.
[ "binary search", "brute force", "data structures", "dfs and similar", "graphs", "greedy", "hashing", "implementation" ]
2,000
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; int n; vector<vector<int>> a; int m; vector<vector<int>> b; int main() { scanf("%d", &n); a.resize(n); forn(i, n){ int c; scanf("%d", &c); a[i].resize(c); forn(j, c) scanf("%d", &a[i][j]); } scanf("%d", &m); b.resize(m); forn(i, m){ b[i].resize(n); forn(j, n){ scanf("%d", &b[i][j]); --b[i][j]; } } sort(b.begin(), b.end()); vector<int> ult(n); forn(i, n) ult[i] = int(a[i].size()) - 1; if (!binary_search(b.begin(), b.end(), ult)){ forn(i, n) printf("%d ", ult[i] + 1); puts(""); return 0; } int mx = 0; vector<int> ans(n, -1); forn(i, m){ vector<int> tmp = b[i]; int sum = 0; forn(j, n) sum += a[j][tmp[j]]; forn(j, n) if (tmp[j] != 0){ --tmp[j]; if (!binary_search(b.begin(), b.end(), tmp) && sum - a[j][tmp[j] + 1] + a[j][tmp[j]] > mx){ mx = sum - a[j][tmp[j] + 1] + a[j][tmp[j]]; ans = tmp; } ++tmp[j]; } } forn(i, n){ printf("%d ", ans[i] + 1); } puts(""); }
1574
E
Coloring
A matrix of size $n \times m$, such that each cell of it contains either $0$ or $1$, is considered beautiful if the sum in every contiguous submatrix of size $2 \times 2$ is exactly $2$, i. e. every "square" of size $2 \times 2$ contains exactly two $1$'s and exactly two $0$'s. You are given a matrix of size $n \times m$. Initially each cell of this matrix is empty. Let's denote the cell on the intersection of the $x$-th row and the $y$-th column as $(x, y)$. You have to process the queries of three types: - $x$ $y$ $-1$ — clear the cell $(x, y)$, if there was a number in it; - $x$ $y$ $0$ — write the number $0$ in the cell $(x, y)$, \textbf{overwriting the number that was there previously (if any)}; - $x$ $y$ $1$ — write the number $1$ in the cell $(x, y)$, \textbf{overwriting the number that was there previously (if any)}. After each query, print the number of ways to fill the empty cells of the matrix so that the resulting matrix is beautiful. Since the answers can be large, print them modulo $998244353$.
For best understanding we replace the matrix with $0$ and $1$ with the matrix with black and white cells. At first let's consider matrix if there are two adjacent horizontal cell with same color (for example cells $(5, 5)$ and $(5, 6)$ are black). Then the cells $(4, 5)$, $(4, 6)$, $(6, 5)$ and $6, 6$ must have the opposite color (white); the cells $(3, 5)$, $(3, 6)$, $(7, 5)$ and $7, 6$ must have the same color (black) and so on. So, two adjacent horizontal cells generate the vertical strip of width two. Reciprocally two adjacent vertical cells generate the horizontal strip of width two. And if simultaneously there are horizontal strip and vertical strip then the answer is $0$ (because they contradict each other). If there are two cells of same color in the same row with even number of cells between them (for example $(2, 2)$ and $(2, 7)$ with four cells between them) then there is the vertical strip (because there are always two adjacent cells with same color between them). The same is correct for horizontal strips. Now let's consider how the matrix look if there are the vertical strip. It look like a chess board of size $n \times m$, but colors of some verticals are inverted. The same is correct if there are the horizontal strips. How we can quickly understand that there are two cells of same color in the same row with even number of cells between them? For this mentally color the matrix in a checkerboard pattern. And then one of this cells has the same color witch cells in chessboard, and the other has the opposite color witch cells in chessboard. For calculating the answer we have maintain to the following values: The color of each colored cell; The row and columns containing the cells of same color with even number of cells between them; And the number of row and columns containing at least one colored cell (for calculating the number of beautiful matrix).
[ "combinatorics", "constructive algorithms", "implementation", "math" ]
2,500
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = 1'000'009; int sum (int a, int b) { int res = a + b; if (res < 0) res += MOD; if (res >= MOD) res -= MOD; return res; } int n, m, k; map <pair <int, int>, char> c; int cntr[N][2], cntc[N][2]; int cntx[2]; set <int> badr, badc; set<int> ur, uc; int p2[N]; void upd2(int pos, int col, int add, int cnt[N][2], set <int> &bad, set<int> &u) { cnt[pos][col] += add; assert(cnt[pos][col] >= 0); if (cnt[pos][0] > 0 && cnt[pos][1] > 0){ if (!bad.count(pos)) bad.insert(pos); } else { if (bad.count(pos)) bad.erase(pos); } if (cnt[pos][0] > 0 || cnt[pos][1] > 0){ if (!u.count(pos)) u.insert(pos); } else { if (u.count(pos)) u.erase(pos); } } void upd(int x, int y, int t) { int col = (x & 1) ^ (y & 1); if (c.count({x, y})) { int ncol = col ^ c[{x, y}]; --cntx[ncol]; upd2(x, ncol, -1, cntr, badr, ur); upd2(y, ncol, -1, cntc, badc, uc); c.erase({x, y}); } if (t == -1) return; int ncol = col ^ t; ++cntx[ncol]; upd2(x, ncol, 1, cntr, badr, ur); upd2(y, ncol, 1, cntc, badc, uc); c[{x, y}] = t; } int main(){ p2[0] = 1; for (int i = 1; i < N; ++i) p2[i] = sum(p2[i - 1], p2[i - 1]); scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < k; ++i) { int x, y, t; scanf("%d %d %d", &x, &y, &t); --x, --y; upd(x, y, t); int res = 0; if(badr.size() > 0 && badc.size() > 0) { res = 0; } else if (badr.size() > 0) { assert(m - uc.size() >= 0); res = p2[m - uc.size()]; } else if (badc.size() > 0) { assert(n - ur.size() >= 0); res = p2[n - ur.size()]; } else { if (ur.size() == 0 && uc.size() == 0) res = sum(sum(p2[n], p2[m]), -2); else { assert(m - uc.size() >= 0); res = sum(res, p2[m - uc.size()]); assert(n - ur.size() >= 0); res = sum(res, p2[n - ur.size()]); if (cntx[0] == 0 || cntx[1] == 0) { assert(cntx[0] != 0 || cntx[1] != 0); res = sum(res, -1); } } } printf("%d\n", res); } return 0; }
1574
F
Occurrences
A subarray of array $a$ from index $l$ to the index $r$ is the array $[a_l, a_{l+1}, \dots, a_{r}]$. The number of occurrences of the array $b$ in the array $a$ is the number of subarrays of $a$ such that they are equal to $b$. You are given $n$ arrays $A_1, A_2, \dots, A_n$; the elements of these arrays are integers from $1$ to $k$. You have to build an array $a$ consisting of $m$ integers from $1$ to $k$ in such a way that, for \textbf{every} given subarray $A_i$, the number of occurrences of $A_i$ in the array $a$ is \textbf{not less} than the number of occurrences of each non-empty subarray of $A_i$ in $a$. Note that if $A_i$ doesn't occur in $a$, and no subarray of $A_i$ occurs in $a$, this condition is still met for $A_i$. Your task is to calculate the number of different arrays $a$ you can build, and print it modulo $998244353$.
What does the condition "the number of occurrences of $A_i$ in the array $a$ is not less than the number of occurrences of each non-empty subarray of $A_i$ in $a$" mean? First, if $A_i$ contains two (or more) equal elements, then any occurrence of $A_i$ introduces at least two occurrences of that element; so any element in $A_i$ is forbidden (it should not appear in the resulting array). Now let's consider an array $A_i$ such that every its element is unique. Every element of $A_i$ should be a part of an occurrence of $A_i$ in the array $a$. Let's rephrase this condition as follows: for each occurrence of $A_{i,j}$ in $a$, the next element in $a$ is $A_{i,j+1}$, and vice versa: for each occurrence of $A_{i,j+1}$ in $a$, the previous element in $a$ is $A_{i,j}$. Let's build a directed graph on $k$ vertices, where an arc from vertex $x$ to vertex $y$ means that each occurrence of $x$ should be followed by $y$, and each occurrence of $y$ should be preceded by $x$ (i. e. $x$ is followed by $y$ in some array $A_i$). Let's consider the weakly connected components in this graph. If we have at least one occurrence of some element from a component in $a$, it means that all other elements from this component occur in $a$ as well. Some integers from $1$ and $k$ are "bad" in a sense that we cannot uniquely determine which element should follow/precede them (in terms of graph theory, it means that the in-degree or out-degree of a vertex is at least $2$). Since by picking one element from a component, we will have to use all elements from a component, it means that if a component contains at least one "bad" element, the whole component will be "bad" - we cannot use any element from it. If a component is a cycle, no vertex has in-degree or out-degree greater than $1$, but the component is still "bad" since, if we include at least one element from $a$, we cannot finish the cycle - the array $a$ is not infinite, but the cycle is. Okay, the only "good" components are chains. When we use an element from a chain in $a$, all elements from this chain will be used in exactly the same order that they were in the chain; so, $a$ should consist of some chains linked together (chains may repeat, and some chains may be absent from $a$). We can write a solution with dynamic programming: let $dp_i$ be the number of ways to construct an array of length $i$ using these chains. The transitions are as follows: $dp_i = \sum\limits_{j=1}^{c} dp_{i - len_j}$, where $c$ is the number of chains, and $len_j$ is the length of the $j$-th chain. The number of chains is up to $k$, and the number of states in dynamic programming is $m + 1$, so the solution works in $O(mk)$, which is too slow. We can improve it with the following two facts: all chains of the same length are indistinguishable; there are $O(\sqrt{k})$ different lengths of chains. So, instead of iterating on the chains themselves in dynamic programming, we will iterate on the lengths of the chains (considering only lengths having at least one chain), and process all chains of the same length as one by introducing a multiplier in our dynamic programming: $dp_i = \sum \limits_{j=1}^{k} dp_{i - j} \cdot cnt_j$, where $cnt_j$ is the number of chains of length $j$. That way, our dynamic programming will work in $O(m \sqrt{k})$ if we skip the values of $j$ with $cnt_j = 0$.
[ "combinatorics", "dfs and similar", "dp", "dsu", "fft", "graphs" ]
2,700
#include <bits/stdc++.h> using namespace std; const int MOD = 998244353; int add(int x, int y) { x += y; while(x >= MOD) x -= MOD; while(x < 0) x += MOD; return x; } int mul(int x, int y) { return (x * 1ll * y) % MOD; } int main() { int n, m, k; scanf("%d %d %d", &n, &m, &k); vector<vector<int>> A(n); vector<int> bad_num(k); for(int i = 0; i < n; i++) { int c; scanf("%d", &c); A[i].resize(c); for(int j = 0; j < c; j++) { scanf("%d", &A[i][j]); A[i][j]--; } } for(int i = 0; i < n; i++) { if(set<int>(A[i].begin(), A[i].end()).size() != A[i].size()) { for(auto x : A[i]) bad_num[x] = 1; } } vector<vector<int>> nxt(k); vector<vector<int>> prv(k); for(int i = 0; i < n; i++) for(int j = 0; j + 1 < A[i].size(); j++) { nxt[A[i][j]].push_back(A[i][j + 1]); prv[A[i][j + 1]].push_back(A[i][j]); } for(int i = 0; i < k; i++) { sort(nxt[i].begin(), nxt[i].end()); sort(prv[i].begin(), prv[i].end()); nxt[i].erase(unique(nxt[i].begin(), nxt[i].end()), nxt[i].end()); prv[i].erase(unique(prv[i].begin(), prv[i].end()), prv[i].end()); } vector<int> used(k, 0); vector<int> cnt(k + 1, 0); for(int i = 0; i < k; i++) { if(used[i]) continue; queue<int> q; vector<int> comp; q.push(i); used[i] = 1; while(!q.empty()) { int z = q.front(); q.pop(); comp.push_back(z); for(auto x : nxt[z]) if(!used[x]) { used[x] = 1; q.push(x); } for(auto x : prv[z]) if(!used[x]) { used[x] = 1; q.push(x); } } bool bad = false; int cnt_beg = 0; for(auto x : comp) { if(prv[x].empty()) cnt_beg++; if(prv[x].size() > 1 || nxt[x].size() > 1 || bad_num[x]) bad = true; } bad |= (cnt_beg == 0); if(!bad) cnt[comp.size()]++; } vector<int> nonzero; for(int i = 1; i <= k; i++) if(cnt[i] > 0) nonzero.push_back(i); vector<int> dp(m + 1, 0); dp[0] = 1; for(int i = 1; i <= m; i++) for(auto x : nonzero) if(x <= i) dp[i] = add(dp[i], mul(cnt[x], dp[i - x])); printf("%d\n", dp[m]); return 0; }
1575
A
Another Sorting Problem
Andi and Budi were given an assignment to tidy up their bookshelf of $n$ books. Each book is represented by the book title — a string $s_i$ numbered from $1$ to $n$, each with length $m$. Andi really wants to sort the book lexicographically ascending, while Budi wants to sort it lexicographically descending. Settling their fight, they decided to combine their idea and sort it asc-desc-endingly, where \textbf{the odd-indexed characters will be compared ascendingly}, and \textbf{the even-indexed characters will be compared descendingly}. A string $a$ occurs before a string $b$ in asc-desc-ending order if and only if in the first position where $a$ and $b$ differ, the following holds: - if it is an odd position, the string $a$ has a letter that appears earlier in the alphabet than the corresponding letter in $b$; - if it is an even position, the string $a$ has a letter that appears later in the alphabet than the corresponding letter in $b$.
Observe that the even-indexed character of the string can be transformed from A-Z to Z-A. E.g. for the first example: AA \rightarrow AZ AB \rightarrow AY BB \rightarrow BY BA \rightarrow BZ AZ \rightarrow AA Now, you can use any known algorithms to sort the string as usual. You can sort it in linear time with trie, or std::sort in $O(nm \log n)$ time. Time Complexity : $O(nm)$ or $O(nm \log n)$
[ "data structures", "sortings", "strings" ]
1,100
null
1575
B
Building an Amusement Park
Mr. Chanek lives in a city represented as a plane. He wants to build an amusement park in the shape of a circle of radius $r$. The circle must \textbf{touch} the origin (point $(0, 0)$). There are $n$ bird habitats that can be a photo spot for the tourists in the park. The $i$-th bird habitat is at point $p_i = (x_i, y_i)$. Find the minimum radius $r$ of a park with \textbf{at least} $k$ bird habitats inside. A point is considered to be inside the park if and only if the distance between $p_i$ and the center of the park is less than or equal to the radius of the park. Note that the center and the radius of the park do not need to be integers. \textbf{In this problem, it is guaranteed that the given input always has a solution with $r \leq 2 \cdot 10^5$}.
We can binary search the answer $r$ in this case. Here, bird's habitats are referred as points. First of all, define a function $c(x)$ as the maximum number of points that can be covered with a circle of radius $x$ through the origin. Define the park as a circle with radius $x$ and $\theta$, in a polar coordinate representation. Observe that each points have a radial/angle segment of which the point $p_i$ will be inside the circle if and only if $\theta$ belongs to the radial segment of $[L_{p_{i}}, R_{p_{i}}]$, where $-\pi < L_{p_{i}}, R_{p_{i}} \leq \pi$. E.g for $x = 4$, Observe the $L_{p_{3}}$ for the $p_3 = (1, 5)$. The green radial segment $e$ represents the $[L_{p_{3}}, R_{p_{3}}]$. Now, to find the two end points $B_i$ and $C_i$ of the arc for each point $p_i$. Because the triangle that is made by those 3 points are an isosceles triangle, simply find the angle where the distance of $p_i$ and $B_i$ equals to $x$, that is $\Delta = \cos^{-1}\dfrac{||p_i||}{2r}$. Now the segment can be found by calculating the angle of $\tan^{-1}p_i \pm \Delta$. Do a radial sweep to find the maximum number of points. Time complexity is $O(n \log n \cdot \log(\text{MAX_R} \cdot \epsilon^{-1}))$. We can optimize the binary search part further, since we only need $\log(\epsilon^{-1})$ most significant digits. We can binary search the position of the first non-zero digit in $O(\log\log(\text{MAX_R}))$, then use a normal binary search with $O(\log(\epsilon^{-1}))$ steps. In practice, this improves the time by around a factor of 2. Time complexity: $O(n \log n \cdot \log(\text{MAX_R} \cdot \epsilon^{-1}))$ or $O(n \log n \cdot \log(\log(\text{MAX_R}) \cdot \epsilon^{-1}))$.
[ "binary search", "geometry" ]
2,300
null
1575
C
Cyclic Sum
Denote a cyclic sequence of size $n$ as an array $s$ such that $s_n$ is adjacent to $s_1$. The segment $s[r, l]$ where $l < r$ is the concatenation of $s[r, n]$ and $s[1, l]$. You are given an array $a$ consisting of $n$ integers. Define $b$ as the cyclic sequence obtained from concatenating $m$ copies of $a$. Note that $b$ has size $n \cdot m$. You are given an integer $k$ where $k = 1$ or $k$ is a prime number. Find the number of different segments in $b$ where the sum of elements in the segment is divisible by $k$. \textbf{Two segments are considered different if the set of indices of the segments are different}. For example, when $n = 3$ and $m = 2$, the set of indices for segment $s[2, 5]$ is $\{2, 3, 4, 5\}$, and for segment $s[5, 2]$ is $\{5, 6, 1, 2\}$. In particular, the segments $s[1, 6], s[2,1], \ldots, s[6, 5]$ are considered as the same segment. Output the answer modulo $10^9 + 7$.
Let a valid segment $[l, r]$ be a segment in $b$ where the sum of elements in the segment is divisible by $k$. We can try to solve a simpler problem: find the number of valid segments such that the right endpoint ends at $1$. That is, the valid segments $[l, 1]$ ($1 \leq l \leq n \cdot m$). Let $prefix(p) = \sum_{i=1}^{p} {b[i]}$ and $cnt$ be an array where the $cnt[i]$ denote the number of $p$ ($1 \leq p \leq n \cdot m$) such that $i \equiv prefix(p) \mod k$. Notice that the number of valid segment $[l, 1]$ is $cnt[prefix(n \cdot m) + b[1]]$. Furthermore, the number of valid segments $[l, 1 + x \cdot n]$ ($0 \leq x \leq m-1$) is the same as the number of valid segment $[l, 1]$. Thus, we only need to calculate the number of valid segments for $[l, r]$ with $1 \leq l \leq n \cdot m$ and $1 \leq r \leq n$, then multiply the final result by $m$. First we need to find the array $cnt$. Let $sum = prefix(n)$. When $sum \equiv 0 \mod k$, we can find $cnt$ in a straightforward manner. Now assume $sum \not\equiv 0 \mod k$. For a fixed $i$, let's try to find the contribution of $prefix(i + x \cdot n)$ for all $0 \leq x \leq m-1$ to $cnt$ at once. Observe that if one make a directed graph with $(i, \ (i + sum) \bmod k)$ for $0 \leq i < k$ as the edges, one will get a cycle of length $k$ (since $k$ is prime) as the result. To find the contribution of $prefix(i + x \cdot n)$, we can do a range add operation on this cycle. This can be done with offline prefix sums (prefix difference) in $O(k)$ total. Now that we have the array $cnt$, we can find the number of valid segments that ends at $1$ easily. To find valid segment that ends at index $2$, we can modify $cnt$ by adding $prefix(n \cdot m) + b[1]$ to the counter and removing $b[1]$. We do this for all $1 \leq r \leq n$. This solution is also applicable for arbitary $k$, albeit multiple cycles will be generated and must be handled separatedly. Time complexity: $O(n + k)$
[ "data structures", "fft", "number theory" ]
3,000
null