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
1030
B
Vasya and Cornfield
Vasya owns a cornfield which can be defined with two integers $n$ and $d$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $(0, d), (d, 0), (n, n - d)$ and $(n - d, n)$. \begin{center} {\small An example of a cornfield with $n = 7$ and $d = 2$.} \end{center} Vasya also knows that there are $m$ grasshoppers near the field (maybe even inside it). The $i$-th grasshopper is at the point $(x_i, y_i)$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside. Help Vasya! For each grasshopper determine if it is inside the field (including the border).
For each point $(x, y)$ let's look at values of two diagonals: $x + y$ and $x - y$. Borders of the cornfield, in fact, give limits to this values in the next way: $d \le x + y \le 2n - d$ and $-d \le x - y \le d$ - that's all we need to check. There is a picture below for the further explanation.
[ "geometry" ]
1,100
#include<bits/stdc++.h> using namespace std; int n, d; int m; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> d; cin >> m; for(int i = 0; i < m; ++i){ int x, y; cin >> x >> y; bool ok = true; if(!((x - y) <= d && (x - y) >= -d)) ok = false; if(!((x + y) <= n + n - d && (x + y) >= d)) ok = false; if(ok) puts("YES"); else puts("NO"); } return 0; }
1030
C
Vasya and Golden Ticket
Recently Vasya found a golden ticket — a sequence which consists of $n$ digits $a_1a_2\dots a_n$. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket $350178$ is lucky since it can be divided into three segments $350$, $17$ and $8$: $3+5+0=1+7=8$. Note that each digit of sequence should belong to \textbf{exactly} one segment. Help Vasya! Tell him if the golden ticket he found is lucky or not.
Let's iterate over all possible lengths $len$ of the first segment of the partition. Now, knowing this length, we also can calculate sum $S$ of each segment. Now we can form partition with greedy solution: starting from position $len + 1$ we will find maximal prefix (strictly, segment starting at $len + 1$) with sum lower or equal to $S$, cut it and again. If all formed segments have sums equal to $S$ then it's valid partition and answer is "YES". Otherwise, there is no valid length of the first segment, there is no valid partition, so answer is "NO".
[ "implementation" ]
1,300
#include<bits/stdc++.h> using namespace std; int n; string s; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> s; int sum = 0; for(int i = 0; i < n - 1; ++i){ sum += s[i] - '0'; bool ok = true; int pos = i + 1; int sum2 = 0; while(pos < n){ sum2 = s[pos++] - '0'; while(pos < n && sum2 + s[pos] - '0' <= sum){ sum2 += s[pos] - '0'; ++pos; } if(sum2 != sum) ok = false; } if(sum2 != sum) ok = false; if(ok){ puts("YES"); return 0; } } puts("NO"); return 0; }
1030
D
Vasya and Triangle
Vasya has got three integers $n$, $m$ and $k$. He'd like to find three integer points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$, such that $0 \le x_1, x_2, x_3 \le n$, $0 \le y_1, y_2, y_3 \le m$ and the area of the triangle formed by these points is equal to $\frac{nm}{k}$. Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.
Doubled area of any triangle with integer coordinates is always integer. That's why if $2 n m$ is not divisible by $k$ then there is no valid triangle. Otherwise, it's always possible to find required triangle. We will construct the answer with next algorithm. At first, if $k$ is even then divide it by $2$. Next, find $g = \gcd(k, n)$, where $\gcd(x, y)$ is greatest common divisor of $x$ and $y$. Denote $k' = \frac{k}{g}$ and assign $a = \frac{n}{g}$ as length of the first side. Next assign $b = \frac{m}{k'}$ as length of the second side. Now, if $k$ was odd we need to multiply one of the sides by $2$. If $a < n$ then $a = 2a$, otherwise $b = 2b$. $b$ still won't be greater than $m$ since if $a = n$ then $b$ was strictly lower than $m$. The answer is the triangle with vertices $(0, 0), (a, 0), (0, b)$. You can check that its area is equal to $\frac{nm}{k}$.
[ "geometry", "number theory" ]
1,800
#include<bits/stdc++.h> using namespace std; long long gcd(long long a, long long b){ return a? gcd(b % a, a) : b; } int main() { //freopen("input.txt", "r", stdin); long long n, m, k; cin >> n >> m >> k; bool isEven = k % 2 == 0; long long p = n * m; if(isEven) k /= 2; if(p % k != 0){ cout << "NO" << endl; return 0; } long long x = gcd(n, k); k /= x; long long a = n / x; x = gcd(m, k); k /= x; assert(k == 1); long long b = m / x; if(!isEven){ if(a < n) a += a; else{ assert(b < m); b += b; } } cout << "YES" << endl; cout << "0 0\n"; cout << 0 << ' ' << b << endl; cout << a << ' ' << 0 << endl; return 0; }
1030
E
Vasya and Good Sequences
Vasya has a sequence $a$ consisting of $n$ integers $a_1, a_2, \dots, a_n$. Vasya may pefrom the following operation: choose some number from the sequence and swap any pair of bits in its binary representation. For example, Vasya can transform number $6$ $(\dots 00000000110_2)$ into $3$ $(\dots 00000000011_2)$, $12$ $(\dots 000000001100_2)$, $1026$ $(\dots 10000000010_2)$ and many others. Vasya can use this operation any (possibly zero) number of times on any number from the sequence. Vasya names a sequence as good one, if, using operation mentioned above, he can obtain the sequence with bitwise exclusive or of all elements equal to $0$. For the given sequence $a_1, a_2, \ldots, a_n$ Vasya'd like to calculate number of integer pairs $(l, r)$ such that $1 \le l \le r \le n$ and sequence $a_l, a_{l + 1}, \dots, a_r$ is good.
Since we can swap any pair of bits in the number, so all we need to know is just the number of ones in its binary representation. Let create array $b_1, b_2, \dots , b_n$, where $b_i$ is number of ones in binary representation of $a_i$. Forget about array $a$, we will work with array $b$. Let's find a way to decide whether fixed segment is good or not. It can be proven that two conditions must be met. At first, sum of $b_i$ at this segment should be even. At second, maximal element should be lower or equal to the sum of all other elements. We will iterate over left borders of subsegments in descending order and for each left border $l$ calculate number of right borders $r$ such that $[l, r]$ is good. Let's, as first, "forget" about condition on maximum and calculate $cntAll(l)$ - number of right borders $r$, such that sum on segment $[l,r]$ is even and left border $l$ is fixed. We can calculate it by counting $S_0$ and $S_1$ - the number of suffixes of array with even sum of $b_i$ and number of suffixes with odd sum. If the current sum $\sum\limits_{i=l}^{n}{b_i}$ is even then $cntAll(l) = S_0$ since $\sum\limits_{i=l}^{r}{b_i} = \sum\limits_{i=l}^{n}{b_i} - \sum\limits_{i=r+1}^{n}{b_i}$. If $\sum\limits_{i=l}^{n}{b_i}$ is odd then $cntAll(l) = S_1$. Since we forgot about condition on maximum, some bad segments were counted. Since $a_i \le 10^{18}$ then $b_i < 61$. That's why if length of the segment $\ge 61$, condition on the maximum is always true. So, for a fixed $l$ we can iterate over all right borders in the $[l, l + 61]$ and subtract number of segments with even sum and too large maximum (since these segments were counted in the answer).
[ "bitmasks", "dp" ]
2,000
#include<bits/stdc++.h> using namespace std; const int N = int(3e5) + 9; int n; long long a[N]; int b[N]; int cnt[2][N]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; for(int i = 0; i <n; ++i){ cin >> a[i]; b[i] = __builtin_popcountll(a[i]); } long long res = 0; int sufSum = 0; cnt[0][n] = 1; for(int i = n - 1; i >= 0; --i){ int sum = 0, mx = 0; int lstJ = i; int add = 0; for(int j = i; j < n && j - i < 65; ++j){ sum += b[j]; mx = max(mx, b[j]); if(mx > sum - mx && sum % 2 == 0) --add; lstJ = j; } sufSum += b[i]; add += cnt[sufSum & 1][i + 1]; res += add; cnt[0][i] = cnt[0][i + 1]; cnt[1][i] = cnt[1][i + 1]; if(sufSum & 1) ++cnt[1][i]; else ++cnt[0][i]; } cout << res << endl; return 0; }
1030
F
Putting Boxes Together
There is an infinite line consisting of cells. There are $n$ boxes in some cells of this line. The $i$-th box stands in the cell $a_i$ and has weight $w_i$. All $a_i$ are distinct, moreover, $a_{i - 1} < a_i$ holds for all valid $i$. You would like to put together some boxes. Putting together boxes with indices in the segment $[l, r]$ means that you will move some of them in such a way that their positions will form some segment $[x, x + (r - l)]$. In one step you can move any box to a neighboring cell if it isn't occupied by another box (i.e. you can choose $i$ and change $a_i$ by $1$, all positions should remain distinct). You spend $w_i$ units of energy moving the box $i$ by one cell. You can move any box any number of times, in arbitrary order. Sometimes weights of some boxes change, so you have queries of two types: - $id$ $nw$ — weight $w_{id}$ of the box $id$ becomes $nw$. - $l$ $r$ — you should compute the minimum total energy needed to put together boxes with indices in $[l, r]$. Since the answer can be rather big, print the remainder it gives when divided by $1000\,000\,007 = 10^9 + 7$. Note that the boxes are not moved during the query, you only should compute the answer. \textbf{Note that you should minimize the answer, not its remainder modulo $10^9 + 7$. So if you have two possible answers $2 \cdot 10^9 + 13$ and $2 \cdot 10^9 + 14$, you should choose the first one and print $10^9 + 6$, even though the remainder of the second answer is $0$.}
Firstly, let's prove that it's always optimal to leave one of the boxes untouched. By contradiction: if all boxes will move, so some left part will move right and right part will move left. Let the total cost of shifting the whole left part by one be equal to $S_l$ and cost of the right part be $S_r$. We can replace the move of one of the parts by extra move of the other part, so we can change $\max(S_l, S_r)$ by $\min(S_l, S_r)$ - total cost doesn't increase - contradiction. Let $S(l, r) = \sum\limits_{i=l}^{r}{w_i}$. Then, secondly, let's prove that for some segment $[l, r]$ it's always optimal to choose untouched box $k$ such that $S(l, k-1) \le \frac{S(l, r)}{2}$, but $S(l, k) \ge \frac{S(l, r)}{2}$. Again: if it is not true then either $S(l,k - 1) > \frac{S(l, r)}{2}$ or $S(k+1, r) > \frac{S(l, r)}{2}$. And we again can replace either $S(l, k - 1)$ by $S(k, r)$ or $S(k + 1, r)$ by $S(l, k)$. Total cost is decreasing - contradiction. So, finally, all we need is to process the following queries: for given $[l, r]$ find maximum $k$ that $S(l, k-1) \le \frac{S(l, r)}{2}$, but $S(l, k) > \frac{S(l, r)}{2}$ ($>$ or $\ge$ doesn't really matter). It can be done with binary search + BIT in $O(\log^2 n)$ time or by "descending" down the Segment Tree in $O(\log n)$ time. Next part is how to calculate the answer for the known $k$. Since the cost of moving box $i$ to the right place is equal to $w_i (a_k - a_i - (k - i))$ if $i < k$ and $w_i (a_i - a_k - (i - k))$ otherwise so, if we shift from $a_i$ to $a_i - i$ then the cost to move all left indices are equal to $\sum\limits_{i=l}^{k-1}{w_i (a_k - a_i)} = a_k \cdot S(l, k-1) - \sum\limits_{i=l}^{k-1}{w_i a_i}$. The right part transforms in the same way. Since answer is modulo $10^9 + 7$ we can calculate $\sum\limits_{i=l}^{k-1}{(w_i a_i \mod 10^9 + 7)}$ using another BIT. Result complexity is $O(n \log n + q \log^2 n)$ or $O((n + q) \log n)$ (which isn't really faster in this task).
[ "data structures" ]
2,500
#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; 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) { out << "["; fore(i, 1, int(v.size())) { if(i) out << ", "; out << v[i]; } return out << "]"; } const int INF = int(1e9); const li INF64 = li(1e18); const int MOD = int(1e9) + 7; int norm(int a) { while(a >= MOD) a -= MOD; while(a < 0) a += MOD; return a; } int norm(const li &a) { return norm(int(a % MOD)); } int mul(int a, int b) { return int((a * 1ll * b) % MOD); } const int N = 300 * 1000 + 555; int n, q; int a[N], w[N]; inline bool read() { if(!(cin >> n >> q)) return false; fore(i, 0, n) assert(scanf("%d", &a[i]) == 1); fore(i, 0, n) assert(scanf("%d", &w[i]) == 1); return true; } li TW[4 * N], TAW[4 * N]; void addVAl(li T[4 * N], int v, int l, int r, int pos, int val) { if(l + 1 == r) { assert(l == pos); T[v] += val; return; } int mid = (l + r) >> 1; if(pos < mid) addVAl(T, 2 * v + 1, l, mid, pos, val); else addVAl(T, 2 * v + 2, mid, r, pos, val); T[v] = T[2 * v + 1] + T[2 * v + 2]; } li getSum(li T[4 * N], int v, int l, int r, int lf, int rg) { if(l == lf && r == rg) return T[v]; int mid = (l + r) >> 1; li ans = 0; if(lf < mid) ans += getSum(T, 2 * v + 1, l, mid, lf, min(mid, rg)); if(rg > mid) ans += getSum(T, 2 * v + 2, mid, r, max(lf, mid), rg); return ans; } int getNSum(li T[4 * N], int l, int r) { if(l >= r) return 0; return int(getSum(T, 0, 0, n, l, r) % MOD); } pair<int, li> getPos(int v, int l, int r, int lf, int rg, li val) { if(l == lf && r == rg) { if(TW[v] <= val) return make_pair(INF, TW[v]); if(l + 1 == r) return make_pair(l, 0); } int mid = (l + r) >> 1; int res = INF; li sum = 0; if(lf < mid) { auto cur = getPos(2 * v + 1, l, mid, lf, min(mid, rg), val); res = min(res, cur.x); sum += cur.y; } if(rg > mid && res == INF) { auto cur = getPos(2 * v + 2, mid, r, max(lf, mid), rg, val - sum); res = min(res, cur.x); sum += cur.y; } return make_pair(res, sum); } inline void solve() { fore(i, 0, n) { a[i] -= i; addVAl(TW, 0, 0, n, i, w[i]); addVAl(TAW, 0, 0, n, i, mul(a[i], w[i])); } fore(_, 0, q) { int x, y; assert(scanf("%d%d", &x, &y) == 2); if(x < 0) { x = -x - 1; addVAl(TW, 0, 0, n, x, -w[x]); addVAl(TAW, 0, 0, n, x, -mul(a[x], w[x])); w[x] = y; addVAl(TW, 0, 0, n, x, w[x]); addVAl(TAW, 0, 0, n, x, mul(a[x], w[x])); } else { x--; li sum = getSum(TW, 0, 0, n, x, y); int pos = getPos(0, 0, n, x, y, sum / 2).x; assert(x <= pos && pos < y); int ans = norm(mul(a[pos], getNSum(TW, x, pos)) - getNSum(TAW, x, pos)); ans = norm(ans + norm(getNSum(TAW, pos, y) - mul(a[pos], getNSum(TW, pos, y))) ); printf("%d\n", ans); } } } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); int tt = clock(); #endif cout << fixed << setprecision(15); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - tt << endl; tt = clock(); #endif } return 0; }
1030
G
Linear Congruential Generator
You are given a tuple generator $f^{(k)} = (f_1^{(k)}, f_2^{(k)}, \dots, f_n^{(k)})$, where $f_i^{(k)} = (a_i \cdot f_i^{(k - 1)} + b_i) \bmod p_i$ and $f^{(0)} = (x_1, x_2, \dots, x_n)$. Here $x \bmod y$ denotes the remainder of $x$ when divided by $y$. All $p_i$ are primes. One can see that with fixed sequences $x_i$, $y_i$, $a_i$ the tuples $f^{(k)}$ starting from some index will repeat tuples with smaller indices. Calculate the maximum number of different tuples (from all $f^{(k)}$ for $k \ge 0$) that can be produced by this generator, if $x_i$, $a_i$, $b_i$ are integers in the range $[0, p_i - 1]$ and can be chosen arbitrary. The answer can be large, so print the remainder it gives when divided by $10^9 + 7$
Each generator $f_i^{(k)}$ can be represented as functional graph so the number of different values equal to the legth of the cycle $c$ plus the length of pre-period $pp$. Generalizing on tuples leads to next observation: number of different tuples equals to $\max\limits_{i = 1..n}(pp_i) + \mathop{\text{lcm}}\limits_{i = 1..n}(c_i)$. ---- Some proof ---- Let's take a look at some generator $f_i$ to find out its possible $c_i$ and $pp_i$. If $a_i = 0$ then $f_i = x_i, b_i, b_i, b_i, \dots$. the $c_i = 1$ and $pp_i = 0$ or $pp_i = 1$. If $a_i = 1$ then $f_i^{(k)} = (x_i + (k - 1) b_i) \mod p_i$. Since $p_i$ is a prime then $c_i = 1$ or $c_i = p_i$ and $pp_i = 0$. If $a_i > 1$ then exists $a_i^{-1}$ and $(a_i - 1)^{-1}$, thus $pp_i = 0$. Since there is not pre-period we need to find minimal positive $k$ such that Since $p_i$ is a prime if $a \cdot b \equiv 0$ then $a \equiv 0$ or $b \equiv 0$. So if $(x_i + b_i \cdot (a_i - 1)^{-1}) \equiv 0$ and since it doesn't depend on $k$ then $k = 1$, so $c_i = 1$ and $pp_i = 0$. Otherwise, $(a_i^k - 1) \equiv 0$ and by Lagrange's theorem $k \mid (p_i - 1)$. Finally, since $p_i$ is a prime there exist $a_i$ such that $k = p_i - 1$. ---- End of some proof ---- At the end we can understand that only three cases are matter: $(c_i = 1, pp_i = 1)$, $(c_i = p_i, pp_i = 0)$ and $(c_i = p_i - 1, pp_i = 0)$. Here some greedy ideas works: it always optimal try at first $(p_i, 0)$, then $(p_i - 1, 0)$ and only then $(1, 1)$; we can process elements in the descending order. But there is one problem: since we maximaize $\max\limits_{i = 1..n}(pp_i) + \mathop{\text{lcm}}\limits_{i = 1..n}(c_i)$ then there are cases, where we can make $\max\limits_{i = 1..n}(pp_i) = 1$ without lowering $\mathop{\text{lcm}}\limits_{i = 1..n}(c_i)$. Here comes two approaches: The first solution (hard to prove correctness, the proven complexity): Let's add to some structure $p_i$ in non ascending order: let's maintain $\text{lcm}$ as pairs: maximal power of prime $a_j$ and number of maximums $cnt_j$ for each prime number up to $2 \cdot 10^6$ . For each $p_i$ we will try to add it as $p_i$ to the $\text{lcm}$. If this structure already have $p_i$ then we will add it as $p_i - 1$, so we need factorization of $p_i - 1$. After that we will iterate over all $p_i$ again and check "can we remove it from structure without decreasing $\text{lcm}$". We will check it in the next way: for index $i$ just check for each prime divisor $pd_j$ of $p_i - 1$ if it was added as $p_i - 1$ (or of $p_i$ if it was added as $p_i$) is it true that ($a_{pd_j}$ > power of $pd_j$) or ($a_{pd_j}$ = power of $pd_j$ and $cnt_{pd_j} > 1$). If we can remove some index $i$ so we can make $\max(pp_i) = 1$ - profit. Otherwise, it's impossible to get $\max(pp_i) = 1$. Here should be proof of correctness, but it is quite complicated (but I proved this solution to KAN and he agreed (hm, notorious coincidence)). At the end, we need factorization of all numbers up to $2 \cdot 10^6$ it can be done with Sieve of Eratosthenes if we will remember minimal divisor for each number. So, the result complexity is $O((n + MAX) \log(n))$. The second solution (the proven correctness, hard to prove the complexity): Let's maintain same structure for $\text{lcm}$ but with some modification: we don't need $cnt_j$ but for each prime we will have a flag $mark_j$ - does this prime is occupied by $p_i$ from the input. Now, let's get to know a way to add arbitrary prime $p_i$ from the input to this structure. Name this function as $insert(v)$. If the structure doesn't have $v$ - just add it (recalc $a_v$ and $mark_v$ flag). Otherwise, we'll move to $v - 1$ and for each prime divisor $pd_k$ of $v - 1$ we'll try to update $pd_k$ in the structure - final trick is next: if we update $pd_k$ which have $mark_{pd_k}$ we will unmark it call a $insert(pd_k)$ recursively. Now we can insert some $p_i$. We will at first find maximum $a_j$ for each prime. Then we will make $n$ quieries - calculate $\text{lcm}$ without $p_i$. This queries can be processed with dynamic connectivity. Final question is to evaluate number of operation done by $insert(v)$. We can limit it with number of prime divisors of all different primes we can reach from each $v$ up to $2 \cdot 10^6$. It was less than $D = 30$. So result complexity is $O(n \log(n) \cdot D)$. P.S.: Main correct is the second solution.
[ "number theory" ]
2,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 x first #define y second typedef long long li; typedef pair<int, int> pt; const int MOD = int(1e9) + 7; int mul(int a, int b) { return int(a * 1ll * b % MOD); } int binPow(int a, int k) { int ans = 1; while(k > 0) { if(k & 1) ans = mul(ans, a); a = mul(a, a); k >>= 1; } return ans; } const int M = 2000 * 1000 + 555; int minD[M]; vector<pt> ps[M]; inline void precalc() { iota(minD, minD + M, 0); fore(val, 2, M) { if(minD[val] < val) continue; for(li j = val * 1ll * val; j < M; j += val) minD[j] = min(minD[j], val); } fore(i, 2, M) { int v = i; ps[i].clear(); while(v > 1) { int md = minD[v]; if(ps[i].empty() || ps[i].back().x != md) ps[i].emplace_back(md, 0); ps[i].back().y++; v /= md; } } } int n; vector<int> p; inline bool read() { if(!(cin >> n)) return false; p.assign(n, 0); fore(i, 0, n) assert(scanf("%d", &p[i]) == 1); return true; } int a[M], cnt[M]; inline void solve() { sort(p.begin(), p.end(), greater<int>()); for(int& cp : p) { if(a[cp] == 0) { a[cp] = 1; cnt[cp] = 1; } else { cp--; for(auto np : ps[cp]) { if(a[np.x] < np.y) { a[np.x] = np.y; cnt[np.x] = 1; } else if(a[np.x] == np.y) cnt[np.x]++; } } } int add = 0; for(int cp : p) { bool un = false; for(auto np : ps[cp]) un |= (a[np.x] == np.y && cnt[np.x] == 1); if(!un) add = 1; } int lcm = 1; fore(i, 2, M) lcm = mul(lcm, binPow(i, a[i])); cout << (lcm + add) % MOD << endl; } int main(){ #ifdef _DEBUG freopen("input.txt", "r", stdin); int t = clock(); #endif cout << fixed << setprecision(10); precalc(); if(read()) { solve(); #ifdef _DEBUG cerr << "TIME = " << clock() - t << endl; #endif } return 0; }
1031
A
Golden Plate
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into $w\times h$ cells. There should be $k$ gilded rings, the first one should go along the edge of the plate, the second one — $2$ cells away from the edge and so on. Each ring has a width of $1$ cell. Formally, the $i$-th of these rings should consist of all bordering cells on the inner rectangle of size $(w - 4(i - 1))\times(h - 4(i - 1))$. \begin{center} {\small The picture corresponds to the third example.} \end{center} Your task is to compute the number of cells to be gilded.
The number of gilded cells in the first (outer) ring is the number of border cells, that is, $2(w + h) - 4$, in the second ring - the number of border cells of the center rectangle with side lengths 4 less, that is, $2(w - 4 + h - 4) - 4$, and so on. This sum can be calculated in a single loop.
[ "implementation", "math" ]
800
null
1031
B
Curiosity Has No Limits
When Masha came to math classes today, she saw two integer sequences of length $n - 1$ on the blackboard. Let's denote the elements of the first sequence as $a_i$ ($0 \le a_i \le 3$), and the elements of the second sequence as $b_i$ ($0 \le b_i \le 3$). Masha became interested if or not there is an integer sequence of length $n$, which elements we will denote as $t_i$ ($0 \le t_i \le 3$), so that for every $i$ ($1 \le i \le n - 1$) the following is true: - $a_i = t_i | t_{i + 1}$ (where $|$ denotes the bitwise OR operation) and - $b_i = t_i \& t_{i + 1}$ (where $\&$ denotes the bitwise AND operation). The question appeared to be too difficult for Masha, so now she asked you to check whether such a sequence $t_i$ of length $n$ exists. If it exists, find such a sequence. If there are multiple such sequences, find any of them.
Let's solve the problem for $0 \leq a_i, b_i, t_i \leq 1$, that is, for binary sequences. There are two options for $t_1$, the remaining part can be determined one number by one after this: If $t_1 = 0$ and $a_1 = 0$ and $b_1 = 0$ then $t_2$ = 0; If $t_1 = 0$ and $a_1 = 0$ and $b_1 = 1$ then there is no such $t_2$. If $t_1 = 0$ and $a_1 = 1$ and $b_1 = 0$ then $t_2$ = 1; If $t_1 = 0$ and $a_1 = 1$ and $b_1 = 1$ then $t_2$ = 1; If $t_1 = 1$ and $a_1 = 0$ and $b_1 = 0$ then there is no such $t_2$. If $t_1 = 1$ and $a_1 = 0$ and $b_1 = 1$ then there is no such $t_2$. If $t_1 = 1$ and $a_1 = 1$ and $b_1 = 0$ then $t_2$ = 0; If $t_1 = 1$ and $a_1 = 1$ and $b_1 = 1$ then $t_2$ = 1; One can similarly find all other $t_i$-s ($3 \leq i \leq n$) or get a contradiction. For bitwise operations from the statement one can solve the problem independently for every bit and restore the original sequence $t_1, t_2, \ldots, t_n$.
[]
1,500
null
1031
C
Cram Time
In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely. Lesha knows that today he can study for at most $a$ hours, and he will have $b$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $k$ in $k$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day. Thus, the student has to fully read several lecture notes today, spending at most $a$ hours in total, and fully read several lecture notes tomorrow, spending at most $b$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?
Consider any answer with maximal $n + m$. If we used numbers $d_1, d_2, \ldots, d_k$ ($d_i \gt n + m$), then we didn't use some numbers $h_1, h_2, \ldots, h_k$ ($h_i \leq n + m$). Replacing all $d_i$ by $h_i$ ($1 \leq i \leq k$) doesn't violate the restriction. That means that we can assume that the answer consists of all numbers from $1$ to $x$, and $x = n + m$. The sum of all numbers from $1$ to $x$ equals $\frac{x(x + 1)}{2}$. It's clear that the following inequality must hold: $\frac{x(x + 1)}{2} \leq a + b$. Let's find the maximal $x$ for which it's true. The answer can't exceed $x$, and we can build the answer for $x$ iteratively. Let's iterate over all lecture notes from $x$ to $1$, and on each step we put it into the first day if we can, otherwise if in the first day we have $w > 0$ free time then we put the lecture note $w < x$ to the first day. All other lecture notes can be read during the second day since the either there are none of them, or the first day is full and hence the second day contains a sufficient amount of hours to read'em all.
[ "greedy" ]
1,600
null
1031
D
Minimum path
You are given a matrix of size $n \times n$ filled with lowercase English letters. You can change no more than $k$ letters in this matrix. Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $2n - 1$. Find the lexicographically smallest string that can be associated with a path after changing letters in at most $k$ cells of the matrix. A string $a$ is lexicographically smaller than a string $b$, if the first different letter in $a$ and $b$ is smaller in $a$.
First, let's find the number of a-s in the beginning of the answer. To do this one can calculate dp[i][j] standing for the minimal number of non-a-s among all paths from the initial corner to (i, j). The number of a-s is simply the greatest $(i + j)$ among all pairs $(i, j)$ such that $dp[i][j]\le k$ (or $0$, if there are no). Consider all cells where we can go right after obtaining the prefix of a-s. Now we repeat the following: append the minimal symbol in these cells to the answer, choose those cells and go from them in both possible directions to obtain the new set of cells. One can see that the answer we obtain is indeed the required answer.
[ "greedy" ]
1,900
null
1031
E
Triple Flips
You are given an array $a$ of length $n$ that consists of zeros and ones. You can perform the following operation multiple times. The operation consists of two steps: - Choose three integers $1 \le x < y < z \le n$, that form an arithmetic progression ($y - x = z - y$). - Flip the values $a_x, a_y, a_z$ (i.e. change $1$ to $0$, change $0$ to $1$). Determine if it is possible to make all elements of the array equal to zero. If yes, print the operations that lead the the all-zero state. Your solution should not contain more than $(\lfloor \frac{n}{3} \rfloor + 12)$ operations. Here $\lfloor q \rfloor$ denotes the number $q$ rounded down. We can show that it is possible to make all elements equal to zero in no more than this number of operations whenever it is possible to do so at all.
This problem has a lot of solutions including those ones which are difficult to prove. Let's describe one of the author's solutions. We can find answer with bruteforce if size of array is rather small. For example we can check all combinations of arithmetic progressions with length equals to three. We can find by hand or bruteforce that for $3 \le n \le 7$ arrays with no solution exists but for $n = 8$ (and consequently for $n \ge 8$) we always can make all elements be equal to zero. We want solution with such steps: If $n$ is small just run bruteforce Else try to make all elements besides the first $k$ ($k \ge 8$) be equal to zero Run bruteforce on the first $k$ elements. How to make the second step? Let's try to make three last elements of array be equal to zero with only one operation. We can use previous elements. So if we have array $\dots, 0, 0, 1$ we can change values of the first, the fourth and the seventh elements from the end. But $\dots, 0, 1, 1$ is counter-example. Ok, let's try to make six last elements of array be equal to zero with two operations. We can check by hand or bruteforce that it can be done and $n \ge 11$ is enough. So we have such solution: Let $k$ is the number of first elements of array which we didn't try to make be equal to zero. In the start $k = n$ While $k \ge 11$ make $k$-th, $(k - 1)$-th,.., $(k - 5)$-th elements be equal to zero. Subtract 6 from $k$. If $k \le 10$ run bruteforce on the first $10$ elements or on the whole array if $n < 10$. How many operations will be done? In the second item the number of operations is less or equal than $2 \cdot \lfloor \frac{n}{6} \rfloor \le \lfloor \frac{n}{3} \rfloor$ In the third item the number of operations is less or equal than 6 (can be checked by hand or bruteforce) So the total number of operations is less or equal than $\lfloor \frac{n}{3} \rfloor + 6$, what is good enough.
[ "constructive algorithms" ]
2,600
null
1031
F
Familiar Operations
You are given two positive integers $a$ and $b$. There are two possible operations: - multiply one of the numbers by some prime $p$; - divide one of the numbers on its prime factor $p$. What is the minimum number of operations required to obtain two integers having the same number of divisors? You are given several such pairs, you need to find the answer for each of them.
Note that if $a = \prod\limits_{i=1}^{k} p_i ^ {x_i}$ then $d(a) = \prod\limits_{i=1}^{k}(x_i+1)$. This implies that we can map $a$ to vector $(x_1, x_2, \ldots, x_k)$, where $x_1 \ge x_2 \ge \ldots \ge x_k$, because the order of the powers doesn't matter. The operations correspond to adding 1 to some item or appending 1 to the end of the vector or decreasing 1 from some item and sorting the vector after that, erasing zeros. There are only 289 different such vectors for numbers up to $10^6$, so we need to calculate only 41616 distances. The first thought could be to just run Floyd-Warshall algorithm on these 289 vertices, which would fit in time. After that for each pair $(x, d)$ we can find the minimum number of operations needed to make with vector $x$ so that the generated number has $d$ divisors. To find the answer for $(x, y)$, we could simply iterate over all possible values of $d$. But there are some tricky cases. For example, for numbers $2^{19}$ and $2^2 3^6$ the answer is 1, because after multiplying the first number by 2 both numbers have 21 divisors. But the number $2^{20} > 10^6$, and the vector $(20)$ is not among these 289 vertices. So, we need to consider some other vectors too. Anyway, let's run this algorithm to see what could be the maximal distance between the two numbers up to $10^6$. It turns out that in 10 operations any two numbers can be led to have the same number of divisors when all numbers in the path don't exceed $10^6$ too. This means that each possible number in the optimal path satisfies $\sum\limits_{i=1}^{k} x_i < 30$, because for the numbers in the input this sum doesn't exceed 19, and there can be no more than 10 operations with each number. This condition gives us all vectors of powers necessary to consider as middle points for the pairs which can be in the input. There are 28629 such vectors. Now we run 289 bfs instances on the generated graph with the start in each possible vector from the input and build the same data structure for pairs $(x, d)$ as explained before, which allows us to find the answers for all vectors of numbers up to $10^6$. This solution works in 2.5s on cf servers, which is still too slow. But the thing is that we found answers for all pairs of the vectors from the input. So we can try to get rid of some unnecessary vertices and simply check if the sum of answers is unchanged. One of the possible speedups is to consider only vectors generating the number of divisors not more than some reasonable number. The maximum number of divisors of some necessary vector is 288, so magic constants like 300 or more will work. Another possible speedup is to decrease the border on the sum of powers from 30 to 22, which is precise.
[ "brute force", "graphs", "math" ]
2,800
null
1032
A
Kitchen Utensils
The king's birthday dinner was attended by $k$ guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils. All types of utensils in the kingdom are numbered from $1$ to $100$. It is known that every set of utensils is the same and consist of different types of utensils, although every particular type may appear in the set at most once. For example, a valid set of utensils can be composed of one fork, one spoon and one knife. After the dinner was over and the guests were dismissed, the king wondered what minimum possible number of utensils could be stolen. Unfortunately, the king has forgotten how many dishes have been served for every guest but he knows the list of all the utensils left after the dinner. Your task is to find the minimum possible number of stolen utensils.
Suppose we've found the minimum possible number $p$ of dishes served for each person. If the input contains utensils of $t$ types exactly, it's clear that the total number of utensils used is at least $p \cdot t \cdot k$ and the number of utensils stolen is at least $p \cdot t \cdot k - n$. Moreover, it's easy to construct an example with this exact number of stolen utensils having our $n$ objects served. It is also easy to note that the minimum $p$ is equal to the ratio of the maximum number of utensils of one type and the number of guests, rounded up.
[]
900
null
1032
B
Personalized Cup
At many competitions that have a word «cup» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner. The nameplate is to be rectangular and the text on it will be printed as a table of several rows and columns. Having some measurements done, the organizers have found out that the number $a$ of rows cannot be greater than $5$ while the number $b$ of columns cannot exceed $20$. Every cell of the table will contain either an asterisk («*») or a letter of user's handle. Furthermore, the organizers want the rows of the table to be uniform, which means that the number of asterisks used in different rows should differ by at most one (i.e. you can't have two asterisks in the first row and none in the second). The main goal, however, is to obtain the winner's handle precisely when reading the table from top to bottom and from left to right in every row (skipping asterisks). The organizers want for the nameplate to have as few rows as possible and among all valid tables with the minimum number of rows they want to choose the one that has the minimum number of columns. The winner is not yet determined so your task is to write a program that, given a certain handle, generates the necessary table.
Let's iterate over all possible pairs $(a, b)$ with $1 \leq a \leq 5$ and $1 \leq b \leq 20$ to find the optimal one satisfying the inequality $a \cdot b \geq |s|$. So now we need to place the characters of $s$ in the same relative order through the table. Possibly, several cells will remain unused, but we will distribute them over the table and place at most one asterisk in every row. One can show that we will have at most one asterisk in each row, because otherwise we would have been able to reduce the value of $b$.
[]
1,200
null
1032
C
Playing Piano
Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence $a_1, a_2, \ldots, a_n$ of key numbers: the more a number is, the closer it is to the right end of the piano keyboard. Paul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed. Let's denote the fingers of hand by numbers from $1$ to $5$. We call a fingering any sequence $b_1, \ldots, b_n$ of fingers numbers. A fingering is convenient if for all $1\leq i \leq n - 1$ the following holds: - if $a_i < a_{i+1}$ then $b_i < b_{i+1}$, because otherwise Paul needs to take his hand off the keyboard to play the $(i+1)$-st note; - if $a_i > a_{i+1}$ then $b_i > b_{i+1}$, because of the same; - if $a_i = a_{i+1}$ then $b_i\neq b_{i+1}$, because using the same finger twice in a row is dumb. \textbf{Please note that there is $\neq$, not $=$ between $b_i$ and $b_{i+1}$.} Please provide any convenient fingering or find out that there is none.
Let $dp[i][j]$ be $-1$ if we cannot play the first $i$ notes in such a way that the $i$-th note is played by the $j$-th finger, otherwise let this be the number of the previous finger in any of possible fingerings. This $dp$ can be easily calculated for about $5n\cdot 5$ operations.
[ "constructive algorithms", "dp" ]
1,700
null
1032
D
Barcelonian Distance
In this problem we consider a very simplified model of Barcelona city. Barcelona can be represented as a plane with streets of kind $x = c$ and $y = c$ for every integer $c$ (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points $(x, y)$ for which $ax + by + c = 0$. One can walk along streets, including the avenue. You are given two integer points $A$ and $B$ somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to $B$ from $A$.
One way is to handle some cases: intersect the line with the border of the bounding box of $(x_1, y_1)$ and $(x_2, y_2)$, and relax answer by some values depending on the mutual location of intersection points, as on the pics below. Another way is to intersect horizontal and vertical lines through $(x_1, y_1)$ and $(x_2, y_2)$, intersect them with the $ax + by + c = 0$ line, consider the obtained 6 points as vertices of a graph, add all horizontal and vertical edges in this graph, run Floyd/Ford-Bellman/Dijkstra algorithm.
[ "geometry", "implementation" ]
1,900
null
1032
E
The Unbearable Lightness of Weights
You have a set of $n$ weights. You know that their masses are $a_1$, $a_2$, ..., $a_n$ grams, but you don't know which of them has which mass. You can't distinguish the weights. However, your friend does know the mass of each weight. You can ask your friend to give you exactly $k$ weights with the total mass $m$ (both parameters $k$ and $m$ are chosen by you), and your friend will point to any valid subset of weights, if it is possible. You are allowed to make this query only once. Find the maximum possible number of weights you can reveal after this query.
Suppose the numbers $a_{1}, a_{2}, \ldots, a_{n}$ can have only up to two different values. Then we can unambiguously determine the masses of all the weights (e.g., suppose there are $t$ weights with a mass of $w$ each, then we can ask our friend about a set of $t$ weights with a total mass of $t \cdot w$; the only thing he can do is to return all the weights with the mass $w$, so we can reveal the masses of all the weights). If the masses of the weights have at least three different values then the only thing we can do is to determine several weights of the same mass (because if the friend tells us a set having distinct masses, we cannot distinguish them from one another; the same holds for the set of remaining weights). So we need to ask our friend such values $(k, m)$ that the only way to obtain the mass $m$ using $k$ weights is to take $k$ weights of mass $\frac{m}{k}$ each. So now we have reduced our problem to finding for every $w \leq \sum\limits_{i = 1}^{n} a_{i}$ and every number of weights $k \leq n$ the number of ways (regardless of the order of the weights) to obtain a mass of $w$ using precisely $k$ weights. This value $cnt(w, k)$ can be computed via a simple dynamic programming. Finally, the answer will be equal to the maximum such $k$ that for some $b$ there exist at least $k$ weights with mass $b$ each and the mass $k \cdot b$ can be obtained uniquely. One should note that it's sufficient to calculate, say, $\min(2, cnt(w, k))$ instead of $cnt(w, k)$ since the latter can be quite large.
[ "dp", "math" ]
2,100
null
1032
F
Vasya and Maximum Matching
Vasya has got a tree consisting of $n$ vertices. He wants to delete some (possibly zero) edges in this tree such that the maximum matching in the resulting graph is unique. He asks you to calculate the number of ways to choose a set of edges to remove. A matching in the graph is a subset of its edges such that there is no vertex incident to two (or more) edges from the subset. A maximum matching is a matching such that the number of edges in the subset is maximum possible among all matchings in this graph. Since the answer may be large, output it modulo $998244353$.
Firstly let's understand when the maximum matching in the tree is unique - and it is unique if and only if it's perfect (i. e. every vertex having at least one incident edge is saturated). So the problem is reduced to counting the number of ways to split the tree so that each component having size $2$ or more has a perfect matching. Let's use dynamic programming to do this. Let $dp_{v,0 \dots 2}$ be the number of ways to delete edges in the subtree of $v$ so that in this subtree every component is valid (if its size is more than $1$, then it has a perfect matching). The second parameter can take one of three values: $dp_{v,0}$ - $v$ can be used for the matching (but it's not necessary to do it). $dp_{v,1}$ - $v$ is already used in the matching. $dp_{v,2}$ - $v$ is not used in the matching yet, but we have to match it to some vertex. Then $dp_{v, 0} = \prod\limits_{to}{dp_{to, 0}} + \sum\limits_{to} (dp_{to, 1} \cdot \prod\limits_{to', to' \ne to}(dp_{to', 0} + dp_{to', 2}) )$, $dp_{v, 1} = \prod\limits_{to}(dp_{to, 0} + dp_{to, 2})$, $dp_{v, 2} = \sum\limits_{to} (dp_{to, 1} \cdot \prod\limits_{to', to' \ne to}(dp_{to', 0} + dp_{to', 2}) )$, where $to$ and $to'$ are children of $v$.
[ "dp", "trees" ]
2,400
null
1032
G
Chattering
There are $n$ parrots standing in a circle. Each parrot has a certain level of respect among other parrots, namely $r_i$. When a parrot with respect level $x$ starts chattering, $x$ neighbours to the right and to the left of it start repeating the same words in 1 second. Their neighbours then start repeating as well, and so on, until all the birds begin to chatter. You are given the respect levels of all parrots. For each parrot answer a question: if this certain parrot starts chattering, how many seconds will pass until all other birds will start repeating it?
Let us for a moment think that parrots stand in a line. We want to compute a series of values $r_{i, k}$ and $l_{i, k}$. $l_{i, k}$ is the index of the leftmost parrot that will chatter in $2^k$ seconds after the $i$-th parrot starts chattering. $r_{i, k}$ is defined similarly. Clearly, $l_{i, 0} = i - a_i$ and $r_{i, 0} = i + a_i$. We calculate $l_{i, k}$ using the values with lesser $k$. Precisely, $l_{i, k} = \min l_{t, k-1}$, where $t$ goes in range $[l_{i, k-1}, r_{i, k-1}]$. Explanation: the $i$-th parrot triggered some $t$-th parrot in $2^{k-1}$ seconds, then the $t$-th parrot triggered some other parrot in next $2^{k-1}$ seconds. Thus we want to find such $t$ that the leftmost parrot triggered by $t$ is minimum possible. We use a segment tree or a sparse table on the values of the $(k-1)$-th level to compute the value of the DP on the $k$-th level. The idea for the solution on a circle is essentially the same, but you must consider segments more carefully. One rather simple way to do it is to duplicate all the parrots, now numbering them $\dots, -2, -1, 0, 1, \dots, n-1, n, n+1, \dots$ such that the numbers with the same remainder modulo $n$ denote the same parrot. Then we can bound the values for $l_{i, k}$ and $r_{i, k}$ between $-n$ and $2n$. Now a range query over a circle transforms to a constant number of range queries over a segment. Time complexity: $O(n \log^2 n)$.
[]
2,900
null
1033
A
King Escape
Alice and Bob are playing chess on a huge chessboard with dimensions $n \times n$. Alice has a single piece left — a queen, located at $(a_x, a_y)$, while Bob has only the king standing at $(b_x, b_y)$. Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himself — he needs to march his king to $(c_x, c_y)$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, \textbf{she no longer moves any pieces around, and it is only Bob who makes any turns.} Bob will win if he can move his king from $(b_x, b_y)$ to $(c_x, c_y)$ \textbf{without ever getting in check}. Remember that a king can move to any of the $8$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.
Imagine a two-dimensional plane with origin positioned on the black queen. We notice that the queen partitions the board into up to four connected components, with each quadrant being one of them. The answer is thus "YES" if and only if the source king position and the target position are in the same quadrant. This condition can be checked in $\mathcal O(1)$ using few simple ifs. In case you prefer brute force over case analysis, it is also possible to construct the grid graph and find the connected components or use DFS to find the path. This runs in $\mathcal O(n^2)$.
[ "dfs and similar", "graphs", "implementation" ]
1,000
null
1033
B
Square Difference
Alice has a lovely piece of cloth. It has the shape of a \textbf{square} with a side of length $a$ centimeters. Bob also wants such piece of cloth. He would prefer a \textbf{square} with a side of length $b$ centimeters (where $b < a$). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to Bob. Now she is left with an ugly L shaped cloth (see pictures below). Alice would like to know whether the area of her cloth expressed in square centimeters is prime. Could you help her to determine it?
The task looks simple enough, but there is a problem. The number we want to check might be very large - it might not even fit into 64-bit integer. Checking primality for it certainly cannot be performed naively. However, the input is no ordinary number. It is of form $A^2 - B^2$, which can be expressed as $(A-B)(A+B)$. This is prime if and only if $A-B = 1$ and $A+B$ is a prime. Since $A + B$ is at most $2*10^{11}$, we can use trial division to check its primality. Complexity: $O(T \sqrt{A + B})$. Alternatively, you could cheat and use big integers and test primality using Miller-Rabin algorithm. With Java's BigInteger.isProbablePrime it's not too much work.
[ "math", "number theory" ]
1,100
null
1033
C
Permutation Game
After a long day, Alice and Bob decided to play a little game. The game board consists of $n$ cells in a straight line, numbered from $1$ to $n$, where each cell contains a number $a_i$ between $1$ and $n$. Furthermore, no two cells contain the same number. A token is placed in one of the cells. They take alternating turns of moving the token around the board, with Alice moving first. The current player can move from cell $i$ to cell $j$ only if the following two conditions are satisfied: - the number in the new cell $j$ must be strictly larger than the number in the old cell $i$ (i.e. $a_j > a_i$), and - the distance that the token travels during this turn must be a multiple of the number in the old cell (i.e. $|i-j|\bmod a_i = 0$). Whoever is unable to make a move, loses. For each possible starting position, determine who wins if they both play optimally. It can be shown that the game is always finite, i.e. there always is a winning strategy for one of the players.
The game is finite thanks to the first restriction on possible moves: the number on which the token lies must strictly increase with each turn. More importantly, this means that if we model the cells as vertices of a graph and create a directed edge between $i$ and $j$ if $i \rightarrow j$ is a valid move, the resulting graph will be acyclic. For each vertex we want to know whether it is losing or winning. A vertex is winning if and only if there exists an edge to a losing state. This is easily solved on a directed acyclic graph - we process the vertices in reverse topological ordering. Let $v$ denote the current vertex. We already know the outcome of the game for all vertices adjacent to $v$, hence it is easy to determine whether $v$ is winning. This process needs $\mathcal O(n + m)$ time, where $m$ is the number of edges in the graph. In general, this could be quadratic in $n$, but in this particular graph it's actually much less than that! Thanks to the second restriction on possible moves, there are at most $\lfloor \frac{n}{a_i} \rfloor$ possible moves from cell with $a_i$ written in it. As $a_i$ is a permutation, we have at most $\sum_{i=1}^{n} \lfloor \frac{n}{i} \rfloor$ potential edges, which is of order $\mathcal O(n \log n)$.
[ "brute force", "dp", "games" ]
1,600
null
1033
D
Divisors
You are given $n$ integers $a_1, a_2, \ldots, a_n$. Each of $a_i$ has between $3$ and $5$ divisors. Consider $a = \prod a_i$ — the product of all input integers. Find the number of divisors of $a$. As this number may be very large, print it modulo prime number $998244353$.
Given a prime factorisation $a = p_1^{e_1} \cdot p_2^{e_2} \cdot \dots \cdot p_k^{e_k}$, one can conclude that the number of divisors of $a$ is $\prod (e_i + 1)$. Note that we do not need to know the values of $p_i$. Can we perhaps find the exponents, without factorising all inputs? A number with between 3 and 5 divisors is of a form $pq$, $p^2$, $p^3$ or $p^4$, where $p$ and $q$ are primes. We can factorise numbers of all forms except the first easily. How about the rest? We can use Euclidean algorithm to find $gcd(a_i, a_j)$ for all pairs $a_i \neq a_j$. If $g \neq 1$, we can use it to factorise both $a_i$ and $a_j$. After this process, some $a_i$ all still left unfactorised. We can conclude that they do not share any prime factor with any other number (except the number itself if there are multiple copies). This means that it contributes to the factorisation with two prime factors of multiplicity 1. For all other prime factors, we simply calculate how many times they occur in all factorised $a_i$ combined. This combined, we can evaluate $\prod (e_i + 1)$. The time complexity is $O(n^2 \cdot \log \max a_i)$. Note that we can factorise all input using Pollard rho algorithm (which has unknown complexity, but it is presumed to be the square root of the smallest prime factor) in $\mathcal O(\sum \sqrt[\leftroot{-2}\uproot{2}4]{a_i})$. This looks good enough, but in practice is very slow and doesn't pass the TL by a large margin.
[ "interactive", "math", "number theory" ]
2,000
null
1033
E
Hidden Bipartite Graph
Bob has a simple undirected connected graph (without self-loops and multiple edges). He wants to learn whether his graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color) or not. As he is not very good at programming, he asked Alice for help. He does not want to disclose his graph to Alice, but he agreed that Alice can ask him some questions about the graph. The only question that Alice can ask is the following: she sends $s$ — a subset of vertices of the original graph. Bob answers with the number of edges that have both endpoints in $s$. Since he doesn't want Alice to learn too much about the graph, he allows her to ask no more than $20000$ questions. Furthermore, he suspects that Alice might introduce false messages to their communication channel, so when Alice finally tells him whether the graph is bipartite or not, she also needs to provide a proof — either the partitions themselves or a cycle of odd length. Your task is to help Alice to construct the queries, find whether the graph is bipartite.
Denote by $e(A)$ the number of edges in a vertex set $A$, and by $e(A,B)$ the number of edges between $A$ and $B$. Note that $e(A,B) = e(A \cup B) - e(A) - e(B)$ can be answered by three queries. Now we learn how to find an edge in this graph in logarithmic time. Given two sets $X$ and $Y$, such that $e(X,Y) \neq 0$, we can binary search on $X$, i.e. partition $X$ into disjoint $X_1$ and $X_2$ of roughly equal size. If $e(X_1, Y) \neq 0$, we continue to find an edge between $X_1$ and $Y$, otherwise certainly $e(X_2, Y) = e(X,Y) \neq 0$ and we can search for an edge between $X_2$ and $Y$. Once $|X| = 1$, we can do a similar binary search on $Y$. Finally, when both $|X| = 1$ and $|Y| = 1$ while $e(X,Y) \neq 0$, we have found an edge in graph G. How do we use the above construction? We can find a spanning tree of graph $G$, as follows. Start with $S = \{1\}$ and find an edge between $S$ and $V \setminus S$. We remember this edge, add its second endpoint to $S$ and repeat until $S = V$. Ugh! Next question? Once we have a spanning tree, the task is much easier. As the knowledge of a spanning tree on a bipartite graph uniquely identifies the partitions (using a simple DFS, for instance), we can use two queries to determine whether the graph is bipartite or not. If it is, we have already found the partition and can report it. Otherwise, we can use similar binary search to find an edge in one of the partitions. Again, we use DFS to find the required cycle of odd length. The total number of queries is roughly $6 N \log N$, as for each vertex, we perform two binary searches and each operation of binary search requires 3 queries. This totals up to 36000, which seems like too much. However, most of the time, one or two of the three queries have already been asked before and we can cache the answers. Furthermore, we can avoid asking queries of size 1 - we know that the answer is simply 0. With these optimisations, we can find out that the actual number of queries is actually around 17000 in the worst case.
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "interactive" ]
2,800
null
1033
F
Boolean Computer
Alice has a computer that operates on $w$-bit integers. The computer has $n$ \textbf{registers} for values. The current content of the registers is given as an array $a_1, a_2, \ldots, a_n$. The computer uses so-called "number gates" to manipulate this data. Each "number gate" takes two registers as inputs and calculates a function of the two values stored in those registers. Note that you can use the same register as both inputs. Each "number gate" is assembled from bit gates. There are six types of bit gates: AND, OR, XOR, NOT AND, NOT OR, and NOT XOR, denoted "A", "O", "X", "a", "o", "x", respectively. Each \textbf{bit gate} takes two bits as input. Its output given the input bits $b_1$, $b_2$ is given below: \begin{center} $\begin{matrix} b_1 & b_2 & A & O & X & a & o & x \\ 0 & 0 & 0 & 0 & 0 & 1 & 1 & 1 \\ 0 & 1 & 0 & 1 & 1 & 1 & 0 & 0 \\ 1 & 0 & 0 & 1 & 1 & 1 & 0 & 0 \\ 1 & 1 & 1 & 1 & 0 & 0 & 0 & 1 \\ \end{matrix}$ \end{center} To build a "number gate", one takes $w$ bit gates and assembles them into an array. A "number gate" takes two $w$-bit integers $x_1$ and $x_2$ as input. The "number gate" splits the integers into $w$ bits and feeds the $i$-th bit of each input to the $i$-th bit gate. After that, it assembles the resulting bits again to form an output word. For instance, for $4$-bit computer we might have a "number gate" "AXoA" (AND, XOR, NOT OR, AND). For two inputs, $13 = 1101_2$ and $10 = 1010_2$, this returns $12 = 1100_2$, as $1$ and $1$ is $1$, $1$ xor $0$ is $1$, not ($0$ or $1$) is $0$, and finally $1$ and $0$ is $0$. You are given a description of $m$ "number gates". For each gate, your goal is to report the number of register pairs for which the "number gate" outputs the number $0$. In other words, find the number of ordered pairs $(i,j)$ where $1 \leq i,j \leq n$, such that $w_k(a_i, a_j) = 0$, where $w_k$ is the function computed by the $k$-th "number gate".
First we count $C[i]$ the number of occurrences of $i$ in the input for each number between $0$ and $2^w - 1$. We can then notice that each bit gate $G$ maps between $1$ and $3$ two-bit patterns to $0$ (e.g. for xor gate, this is 00 and 11, for and gate this is 00, 01 and 10). This means that we can calculate the answer for each number gate in $\mathcal O(3^w)$, which yields $\mathcal O(m \cdot 3^w)$ algorithm, that is clearly too slow. How do we make this faster? There are at least two approaches. Interpret each binary input as if it were ternary. For instance, $11 = 1011_2 \approx 1011_3$. Consider two ternary numbers consisting only of digits $0$ and $1$ and their sum - e.g. $1001_3 + 1010_3 = 2011_3$. Since there are no carryovers, the $i$-th digit of the sum tells us how many of the two summands have the respective digit equal to $1$. In the example above, the most significant digit is $2$, and we can observe that both inputs have $1$ as the most significant digit.Each of the six binary gates in the output behaves identically on two bit patterns $01$ and $10$. It follows that each number gate $G$ can be expressed as some function $G'$, such that $G(i,j) = G'(i+j)$, i.e. the outcome of the number gate depends only on their sum. For example, the bit gate AND maps $0$, $1$ to $0$ and $2$ to $1$, the gate NOT XOR maps $0$ and $2$ to $1$ and $1$ to $0$. Furthermore, each gate maps between $1$ and $2$ digits to $0$. For each $G'$, there are thus at most $2^w$ values of $x$ such that $G'(x) = 0$, and those values can be found efficiently. To find the answer, we need to find for each $x \in [0, 3^w)$ how many pairs of inputs sum to $x$ in ternary. This amount is equal to the sum $\sum_{i+j = x} C[i] * C[j]$ where $C[i]$ is the number of occurrences of $i$ in the array $A$. This can be precomputed once, either by FFT in $\mathcal O(w \cdot 3^w)$ since it is a convolution, or by brute force in $\mathcal O(4^w)$. The latter has much better constant factor and is in fact slightly faster. Combined, this yields a $\mathcal O(n + w \cdot 3^w + m \cdot 2^w)$ algorithm. Each of the six binary gates in the output behaves identically on two bit patterns $01$ and $10$. It follows that each number gate $G$ can be expressed as some function $G'$, such that $G(i,j) = G'(i+j)$, i.e. the outcome of the number gate depends only on their sum. For example, the bit gate AND maps $0$, $1$ to $0$ and $2$ to $1$, the gate NOT XOR maps $0$ and $2$ to $1$ and $1$ to $0$. Furthermore, each gate maps between $1$ and $2$ digits to $0$. For each $G'$, there are thus at most $2^w$ values of $x$ such that $G'(x) = 0$, and those values can be found efficiently. To find the answer, we need to find for each $x \in [0, 3^w)$ how many pairs of inputs sum to $x$ in ternary. This amount is equal to the sum $\sum_{i+j = x} C[i] * C[j]$ where $C[i]$ is the number of occurrences of $i$ in the array $A$. This can be precomputed once, either by FFT in $\mathcal O(w \cdot 3^w)$ since it is a convolution, or by brute force in $\mathcal O(4^w)$. The latter has much better constant factor and is in fact slightly faster. Combined, this yields a $\mathcal O(n + w \cdot 3^w + m \cdot 2^w)$ algorithm. The second approach was suggested by arsijo. Let's introduce a wildcard in the bit patterns: e.g. $1?0?$ matches all of $1000$, $1001$, $1100$, $1101$. This can be found in $\mathcal O(w \cdot 3^w)$ from the array $C$ by substituting the bits with the wildcard bit by bit, and denote this array of counts by $D$.The zero values of each bit gate can be expressed as at most two bit patterns while using wildcards. For instance, the AND gate yields zero with $0?$ and $10$. With the help of the arrays $C$ and $D$, the answer for each number gate can be found in $\mathcal O(2^w)$. This also yields a $\mathcal O(n + w \cdot 3^w + m \cdot 2^w)$ algorithm. The zero values of each bit gate can be expressed as at most two bit patterns while using wildcards. For instance, the AND gate yields zero with $0?$ and $10$. With the help of the arrays $C$ and $D$, the answer for each number gate can be found in $\mathcal O(2^w)$. This also yields a $\mathcal O(n + w \cdot 3^w + m \cdot 2^w)$ algorithm.
[ "bitmasks", "brute force", "fft", "math" ]
2,800
null
1033
G
Chip Game
Alice and Bob decided to play one ultimate game. They have $n$ piles, the $i$-th pile initially contain $v_i$ chips. Alice selects a positive integer $a$ from interval $[1, m]$, and Bob selects a number $b$ the same way. Then the game starts. In her turn, Alice can select any pile containing at least $a$ chips, and remove exactly $a$ chips from it. Similarly, in his turn, Bob can choose any pile with at least $b$ chips, and remove exactly $b$ chips from it. If a player cannot make a move, he or she loses. If both players play optimally, the outcome ultimately depends on the choice of $a$ and $b$, and on the starting player. Consider a fixed pair $(a,b)$. There are four types of games: - \textbf{Alice} wins, regardless of who starts. - \textbf{Bob} wins, regardless of who starts. - If Alice starts, she wins. If Bob starts, he wins. We say that the \textbf{first} player wins. - If Alice starts, Bob wins. If Bob starts, Alice wins. We say that the \textbf{second} player wins. Among all choices of $a$ and $b$ (i.e. for each pair $(a, b)$ such that $1\leq a, b\leq m$), determine how many games are won by Alice (regardless of who starts), how many are won by Bob (regardless of who starts), how many are won by the first player, and how many are won by the second player.
Let's solve the task for a fixed tuple $(a, b)$. If $a = b$, this is a very simple symmetric game, where the parity of $\sum \lfloor \frac{v_i}{a} \rfloor$ determines the winner (regardless of the players' choices). Without loss of generality, let $a < b$ as the case where $a > b$ is symmetrical. It is obvious that Bob never has an advantage in this game. Furthermore, the game outcome doesn't change if we set $v'_i = v_i \mod (a + b)$. To see why this is true, consider a strategy $S'$ for a winning player in the modified game $G'$, and build strategy $S$ for the original game: If the winner takes first turn in $G'$, take the same first turn in $G$ - this is always valid as $v'_i \leq v_i$. If the loser's last turn was valid in the game $G'$, follow the strategy $S'$ in the game $G$. Again, this is valid as $v'_i \leq v_i$. If the loser's last turn was invalid in the game $G'$, this means that he reduced the state from $x_1 \cdot (a+b) + y_1$ to $(x_1-1) \cdot (a+b) + y_2$ for some $x_1 > 0$ and $0 \leq y_1 < y_2 < a + b$. The winner can play in the same pile to reduce it to $(x_1-1) \cdot (a+b) + y_1$, and the corresponding $v'_i$ doesn't change. In essence, these two moves are a no-op in the game $G'$. Let's break down the single pile games $P$ based on the number of chips modulo $a+b$: $0 \leq v'_i < a$: As neither Alice nor Bob can make a move, this is a zero game ($P = 0$). $a \leq v'_i < b$: Alice can take at least one move in this pile, and Bob none. This is a strictly positive game ($P > 0$). $b \leq v'_i < 2a$: If either of the players makes a move, it changes to a zero game. This is thus a fuzzy game ($P || 0$). Note that this interval may be empty. $\max(2a, b) \leq v'_i < a + b$: If Alice makes a move, she can turn this game into a positive game for her. Bob can turn this into a zero game. This is a fuzzy game ($P || 0$). As we see, there are no negative games. Hence, in the combined game, we can ignore the zero games in our calculation (type $1$) and if there is at least one positive game (type $2$), the game is won for Alice. If there is at least one game of type $4$ and Alice starts, or at least two games of type $4$, Alice can always play one of them to make herself a positive game, thus winning. Otherwise, it is always optimal to play in a game of type $3$ or $4$ if there is one, and the game is subsequently turned into a zero game. The parity of the number of these games thus determines whether the starting player wins or loses. For a fixed $(a, b)$, we are now able to determine the outcome of the game in $\mathcal O(n)$ time, leading to $\mathcal O(m^2n)$ total runtime, which is too slow. To make this faster, let's group the games by the sum $a + b$. For a fixed $v'_i$, define function $f(a)$ which tells us the type of the single-pile game based on the value of $a$ for this particular $v'_i$. We can see that this function is not arbitrary - we can partition the interval $[0, a+b)$ into constantly many intervals on which the function is constant (e.g. if $a \in (v'_i, a+b)$, this is a zero game. We simply collect all these intervals for all values of $v'_i$ and using a linear sweep determine the outcome of each game. This needs $\mathcal O(n \log n)$ for sorting and $\mathcal O(n)$ for the sweep. All combined, this yields a $\mathcal O(m n \log n)$ algorithm. Bonus: Can you get rid of the log factor?
[ "games" ]
3,500
null
1034
A
Enlarge GCD
Mr. F has $n$ positive integers, $a_1, a_2, \ldots, a_n$. He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers. But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward. Your task is to calculate the minimum number of integers you need to remove so that the greatest common divisor of the remaining integers is bigger than that of all integers.
First we divide all numbers by GCD of them. Then we should find a subset with maximum number of integers GCD of which is bigger than $1$. We can enumerate a prime $p$ that GCD of the remaining integers can be divided by. And the number of integers can be divided by $p$ is the maximum size of the subset. We can use Sieve of Euler to factor all integers in $O(m a x(a_{i})+\sum\log a_{i})$ time. Then we find the prime that can divide most integers. The answer is $n$ minus the number of integers can be divided by this prime. If all integers are $1$ (after dividing their GCD), there is no solution.
[ "number theory" ]
1,800
#include<bits/stdc++.h> using namespace std; #define MN 300000 #define MX 15000000 int a[MN+5],u[MX+5],p[MX+5],pn,s[MX+5]; int gcd(int x,int y){return y?gcd(y,x%y):x;} int main() { int n,i,j,g,x,ans=0; for(i=2;i<=MX;++i) { if(!u[i])u[i]=p[++pn]=i; for(j=1;i*p[j]<=MX;++j){u[i*p[j]]=p[j];if(i%p[j]==0)break;} } scanf("%d",&n); for(g=0,i=1;i<=n;++i)scanf("%d",&a[i]),g=gcd(g,a[i]); for(i=1;i<=n;++i)for(j=a[i]/g;j>1;)for(++s[x=u[j]];u[j]==x;)j/=u[j]; for(i=1;i<=MX;++i)ans=max(ans,s[i]); printf("%d",ans?n-ans:-1); }
1034
B
Little C Loves 3 II
Little C loves number «3» very much. He loves all things about it. Now he is playing a game on a chessboard of size $n \times m$. The cell in the $x$-th row and in the $y$-th column is called $(x,y)$. Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between which is exactly $3$. The Manhattan distance between two cells $(x_i,y_i)$ and $(x_j,y_j)$ is defined as $|x_i-x_j|+|y_i-y_j|$. He want to place as many chessmen as possible on the chessboard. Please help him find the maximum number of chessmen he can place.
Following the rules in the problem, the $1 \times 6$, $2 \times 4$, $2 \times 5$ and $3 \times 4$ grids full of chessmen can be easily constructed. Let the number denote the time when the chessman placed. Grids of $1 \times 6$ : 1 2 3 1 2 3 Grids of $2 \times 4$ : 1 2 3 4 3 4 1 2 Grids of $2 \times 5$ : 1 3 2 1 5 2 4 5 3 4 Grids of $3 \times 4$ : 1 3 4 2 5 2 1 5 6 4 3 6 Assume that $n \le m$. Consider the following cases: If $n = 1$, obviously the answer is $6\cdot\left[{\frac{m}{6}}\right]+2\cdot m a x((m\,\mathrm{mod}\,6)-3,0)$. If $n = 2$, only the $2 \times 2$, $2 \times 3$ and $2 \times 7$ grids cannot be completely constructed. The others can be constructed by using the $2 \times 4$, $2 \times 5$ and $2 \times 6$(constructed by two $1 \times 6$ grids) girds. You can write a brute force or enumerate all the possibilities by yourself. If you consider each grid from left to right and choose the grid it matched with, there are only several possible conditions. So I think it can be proved in several minutes :) If $n > 2$, the following things we can consider: We know that using the $2 \times 4$ and $3 \times 4$ grids we can construct the $4 \times x$($x > 2$) grid, and using several $1 \times 6$ grids we can construct the $6 \times x$($x > 2$) grid, so using the $4 \times x$ and $6 \times x$ grids we can construct the $x \times y$ grid while $x, y > 2$ and $y$ is an even number. Therefore we only need to consider the $n \times m$ grid that $n$ and $m$ are both odd numbers. Since $n \times m$ is an odd integer, we can place $nm - 1$ chessmen at most, so we try to reach the maximum. Then we can easily construct the $3 \times 3$, $3 \times 5$ and $5 \times 5$ grids that have only one empty grid. According to the above-mentioned conclusions, any $n \times m$ grids can be reduce to one of the three grids by using some $x \times y$($x$ or $y$ is even) grids. The maximum is reached. Grids of $3 \times 3$ : 1 2 3 3 0 4 4 1 2 Grids of $3 \times 5$ : 1 3 4 6 7 2 5 1 0 5 3 4 2 7 6 Grids of $5 \times 5$ : 1 2 3 1 2 3 4 5 6 4 5 6 7 8 9 10 8 9 12 7 11 12 10 11 0 It seems that the chessboard is a little bit big but you can match them arbitrarily and get correct solution with a big possibility :) This problem is a matching problem. And we found that two grids can be matched only if they have different parities of the sum of two coordinates. So it's actually a biparite graph matching problem :) So we can calculate the answer for all small $n$ and $m$. When $n = 1$ or $m = 1$, the answer is easy to get. Otherwise, we found that if $n$ or $m$ is big enough, the answer will be the maximum. So just keep the answers for small $n$ and $m$, you will get AC easily :)
[ "brute force", "constructive algorithms", "flows", "graph matchings" ]
2,200
#include<bits/stdc++.h> using namespace std; int main() { int n,m; scanf("%d%d",&n,&m); if(n>m)swap(n,m); if(n==1)printf("%d",m/6*3+max(m%6-3,0)<<1); else if(n==2)printf("%d",m==2?0:m==3?4:m==7?12:m<<1); else printf("%lld",1LL*n*m/2*2); }
1034
C
Region Separation
There are $n$ cities in the Kingdom of Autumn, numbered from $1$ to $n$. People can travel between any two cities using $n-1$ two-directional roads. This year, the government decides to separate the kingdom. There will be regions of different levels. The whole kingdom will be the region of level $1$. Each region of $i$-th level should be separated into several (at least two) regions of $i+1$-th level, unless $i$-th level is the last level. Each city should belong to exactly one region of each level and for any two cities in the same region, it should be possible to travel between them passing the cities in the same region only. According to research, for each city $i$, there is a value $a_i$, which describes the importance of this city. All regions of the same level should have an equal sum of city importances. Your task is to find how many plans there are to determine the separation of the regions that all the conditions are satisfied. Two plans are considered different if and only if their numbers of levels are different or there exist two cities in the same region of one level in one plan but in different regions of this level in the other plan. Since the answer may be very large, output it modulo $10^9+7$.
First, we try to find whether it's possible to separate the kingdom into $k$ regions of level-$2$ with the same sum of values. We calculate $S$, the sum of all the values, so each region should have sum $\mathbf{\Sigma}_{k}^{\infty}$. Let $s_{i}$ be the sum of values in the subtree of root $i$. We consider all the cities from the leaves to the root, when a subtree $i$ has sum $s_{i}={\frac{\mathrm{s}}{k}}$, separating it from the tree. We find that only the $i$ with $s_{i}\equiv0{\mathrm{~(mod~}}\frac{S}{k}){\mathrm{)}}$ will be considered. So there should be at least $k$ cities satisfying this condition. And if there exist such $k$ cities, we cut the edge to their father (if it is not the root), so the size of each connected part will be multiple of $\mathbf{\Sigma}_{k}^{\infty}$. Since all the values are positive, all the connected parts have size $\mathbf{\Sigma}_{k}^{\infty}$. So we just need to count how many cities $i$ with $s_{i}\equiv0{\mathrm{~(mod~}}\frac{\mathrm{s}}{k}\mathrm{)}$ there are. Let the equation be $\textstyle{\frac{a}{k}}={\frac{x}{k}}$, where $x$ is a positive integer, so $k$ should be a multiple of $\frac{S}{\operatorname{eqd}(S,s_{i})}$. Now we can use a simple dp with $O(n\log n)$ time to find whether it's possible to separate the kingdom into $k$ regions of level-$2$ for all the $k$. And it's not difficult to find that there can be $k_{i}$ regions of level-$i$ if and only if there can be $k_{i}$ regions of level-$2$ and $k_{i - 1}$ is a factor of $k_{i}$. Let $f_{i}$ be the number of plans with $i$ regions of the last level, and we enumerate the factors of $i$ to transform. So the total time of this solution is $O(n\ (\log n+\log10^{9}))$ (including the time to calculate the gcd).
[ "combinatorics", "dp", "number theory", "trees" ]
2,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define MN 1000000 #define MOD 1000000007 ll s[MN+5];int f[MN+5],p[MN+5],F[MN+5]; inline void rw(int&x,int y){if((x+=y)>=MOD)x-=MOD;} int main() { int n,i,j,ans=0; scanf("%d",&n); for(i=1;i<=n;++i)scanf("%lld",&s[i]); for(i=2;i<=n;++i)scanf("%d",&p[i]); for(i=n;i>1;--i)s[p[i]]+=s[i]; for(i=n;i;--i)if((s[i]=s[1]/__gcd(s[1],s[i]))<=n)++f[s[i]]; for(i=n;i;--i)for(j=i;(j+=i)<=n;)f[j]+=f[i]; for(F[1]=i=1;i<=n;++i)if(f[i]==i)for(rw(ans,F[j=i]);(j+=i)<=n;)rw(F[j],F[i]); printf("%d",ans); }
1034
D
Intervals of Intervals
Little D is a friend of Little C who loves intervals very much instead of number "$3$". Now he has $n$ intervals on the number axis, the $i$-th of which is $[a_i,b_i]$. Only the $n$ intervals can not satisfy him. He defines the value of an interval of intervals $[l,r]$ ($1 \leq l \leq r \leq n$, $l$ and $r$ are both integers) as the total length of the union of intervals from the $l$-th to the $r$-th. He wants to select exactly $k$ different intervals of intervals such that the sum of their values is maximal. Please help him calculate the maximal sum.
First we consider how to calculate the value of an interval of intervals $[l, r]$. We can consider intervals in order from $1$ to $n$ and, for each position on the axis, maintain a timestamp denoting the last time it was covered. When the $r$-th interval is taken into consideration, the timestamps for positions $[a_{r}, b_{r}]$ should all be updated to $r$. Right after that, the desired answer of a query $[l, r]$ is the number of positions whose timestamp is not smaller than $l$. We would like to, for each $r$, keep the desired answer for every $l$. To achieve this, when we change the timestamps of $k$ positions from $r'$ to $r$, the answers for $l$ in $[r' + 1, r]$ should each be increased by $k$. To do it fast, we can merge consecutive positions with the same timestamp into a segment, and use a balanced tree (e.g. std::set) to maintain the segments. $O(1)$ new segments appear when adding an interval, and when a segment is completely covered by later intervals, it will be deleted. By amortized analysis, the total number of balanced tree operations and the number of range modifications of answers (see above) are both $O(n)$. We spend $O(n\log n)$ time in this part. Now we consider how to get the answer. It's obvious that we will select the $k$ largest values. We can use binary search to find the minimum we finally select, i.e. we should, for several integers $x$, count how many values of $[l, r]$ are not smaller than $x$ and count the sum of these values by the way to get the answer. For each $i$, we will select all $[l, i]$'s such that their interval of intervals values is not smaller than $x$. As the value of $[l, r]$ is not smaller than $[l + 1, r]$ or $[l, r - 1]$, it's obvious that all $l$'s smaller than an integer $L_{i}$ will be taken and $L_{i + 1}$ will be not smaller than $L_{i}$. Now we can iterate $i$ from $1$ to $n$, maintaining the sum of values of $[l, i]$ ($1 \le l < L_{i}$) and the value of $[L_{i}, i]$ by maintaining the difference between the answers for $l$ and $l + 1$ (in this way we carry out a range increment in $O(1)$ time). Similar to the sliding-window method, we try to increase $L_{i}$ when $i$ changes to $i + 1$. Therefore, we spend $O(n)$ time for each $x$ we check with. Summing everything up, the total time complexity of this problem is $O(n\ (\log n+\log\operatorname*{max}b))$.
[ "binary search", "data structures", "two pointers" ]
3,500
#include<bits/stdc++.h> using namespace std; #define MN 300000 #define p make_pair #define pb push_back #define A first #define B second set< pair<int,int> > st; set< pair<int,int> >::iterator it,tt; vector< pair<int,int> > v[MN+5]; int f[MN+5]; int main() { int n,m,i,j,k,l,r,x,X,t2;long long s1,s2,S1,S2,t1; scanf("%d%d",&n,&m); st.insert(p(1,0));st.insert(p(1e9,0)); for(i=1;i<=n;++i) { scanf("%d%d",&l,&r); tt=(it=st.upper_bound(p(l,n)))--; v[i].pb(p(x=it->B,it->A-tt->A)); if(it->A<l)v[i].pb(p(x,l-it->A)); else st.erase(it); v[i].pb(p(i,r-l));st.insert(p(l,i)); while(tt->A<r)it=tt++,v[i].pb(p(x=it->B,it->A-tt->A)),st.erase(it); if(tt->A>r)v[i].pb(p(x,tt->A-r)),st.insert(p(r,x)); } for(l=1,r=1e9;l<=r;) { x=l+r>>1; memset(f,0,sizeof(f)); for(i=j=1,s1=s2=t1=t2=0;i<=n;++i) { for(k=0;k<v[i].size();++k) if(v[i][k].A<j)t1+=1LL*v[i][k].A*v[i][k].B; else t1+=1LL*(j-1)*v[i][k].B,t2+=v[i][k].B,f[v[i][k].A]+=v[i][k].B; while(j<=i&&t2>=x)t1+=t2,t2-=f[j++]; s1+=t1;s2+=j-1; } if(s2>=m)X=x,S1=s1,S2=s2,l=x+1;else r=x-1; } printf("%lld",S1-(S2-m)*X); }
1034
E
Little C Loves 3 III
Little C loves number «3» very much. He loves all things about it. Now he is interested in the following problem: There are two arrays of $2^n$ intergers $a_0,a_1,...,a_{2^n-1}$ and $b_0,b_1,...,b_{2^n-1}$. The task is for each $i (0 \leq i \leq 2^n-1)$, to calculate $c_i=\sum a_j \cdot b_k$ ($j|k=i$ and $j\&k=0$, where "$|$" denotes bitwise or operation and "$\&$" denotes bitwise and operation). It's amazing that it can be proved that there are exactly $3^n$ triples $(i,j,k)$, such that $j|k=i$, $j\&k=0$ and $0 \leq i,j,k \leq 2^n-1$. So Little C wants to solve this excellent problem (because it's well related to $3$) excellently. Help him calculate all $c_i$. Little C loves $3$ very much, so he only want to know each $c_i \& 3$.
If we only need to calculate $c_{i}=\sum a_{j}\cdot b_{k}$ ($j|k = i$), we can do these: Let $A_{i}=\sum a_{j},B_{i}=\sum b_{j}$ ($j|i = i$). Let $A_{i}=\sum a_{j},B_{i}=\sum b_{j}$ ($j|i = i$). Let $C_{i} = A_{i} \cdot Bi$, it can be found that $C_{i}=\sum c_{j}$ ($j|i = i$). Let $C_{i} = A_{i} \cdot Bi$, it can be found that $C_{i}=\sum c_{j}$ ($j|i = i$). So $c_{i}=C_{i}-\sum c_{j}$ ($j|i = i$ and $j \neq i$). So $c_{i}=C_{i}-\sum c_{j}$ ($j|i = i$ and $j \neq i$). To calculate $A_{i}$ fast ($B_{i}$ is the same), let $f(x, i)$ be the sum of $a_{j}$ which $j|i = i$ and the lower $x$ binary bits of $j$ is equal to $i$'s. So $f(n, i) = a_{i}$, $f(x - 1, i) = f(x, i)$ if $i&2^{x} = 0$ , $f(x - 1, i) = f(x, i) + f(x, i - 2^{x})$ if $i&2^{x} = 2^{x}$, and $A_{i} = f(0, i)$. We can calculate all $A_{i}$ and $B_{i}$ in $O(n \cdot 2^{n})$ time. Getting $c_{i}$ from $C_{i}$ is the inversion of getting $A_{i}$ from $a_{i}$. So we can use $f(x, i)$ once again. $f(x, i) = f(x - 1, i)$ if $i&2^{x} = 0$, $f(x, i) = f(x - 1, i) - f(x - 1, i - 2^{x})$ if $i&2^{x} = 2^{x}$. So we can get all $c_{i}$ in $O(n \cdot 2^{n})$ total time. But in this problem we need to calculate $c_{i}=\sum a_{j}\cdot b_{k}$ ($j|k = i$ and $j&k = 0$). In fact, there is a well-known algorithm for this problem. The main idea of this algorithm is consider the number of "$1$" binary bits. First, let $BC(x)$ be the number of "$1$" binary bits in $x$. Let $A(x,i)=\sum a_{j},B(x,i)=\sum b_{j}$ ($j|i = i$ and $BC(j) = x$). Then we calculate $C(x,i)=\sum A(y,i)\cdot B(z,i)$ ($y + z = x$), and $c(x,i)=C(x,i)-\sum c(x,j)$ ($j|i = i$ and $j \neq i$). So $c(x,i)=\sum a_{j}\cdot b_{k}$ ($j|k = i$ and $BC(j) + BC(k) = x$). Finally $c_{i}$ we need to calculate is equal to $c(BC(i), i)$, because if $j|k = i$ and $BC(j) + BC(k) = BC(i)$, $j&k$ must be $0$. This algorithm cost $O(n^{2} \cdot 2^{n})$ time. Unfortunately, it may be too slow in this problem. In this problem, we only need to calculate $c_{i}&3$, equal to $c_{i}$ modulo $4$. In fact, when the answer is modulo $p$, an arbitrary integer, my solution works. Let $A_{i}=\sum a_{j}\cdot p^{B C(j)}(j|i=i)$. Then we calculate $F_{i} = A_{i} \cdot B_{i}$, and $f_{i}=F_{i}-\sum f_{j}$ ($j|i = i$ and $j \neq i$). So $f_{i}=\sum a_{j}\cdot b_{k}\cdot p^{B C(j)+B C(i)}$ ($j|k = i$). If $j|k = i$, $BC(j) + BC(k) \ge BC(i)$. If $j|k = i$ and $j&k = 0$, $BC(j) + BC(k) = BC(i)$. We find that $c_{i}\equiv\frac{f_{i}}{p^{B C(i)}}\ \left(\mathrm{mod}\ p\right)$, because if $BC(j) + BC(k) > BC(i)$, $a_{j} \cdot b_{k} \cdot p^{BC(j) + BC(k) - BC(i)}$ can be divided by $p$. So the total time is $O(n \cdot 2^{n})$. A remainder problem is it can not be modulo $p$ when calculating in this algorithm, so the number may be very large. Fortunately, in this problem, $p$ is only $4$. We can use 128-bit integers or merge two 64-bit integers into one number when calculating. But in fact, we only care $\frac{f_{1}}{p P C(t)}$ modulo $p$, so we can let all number be modulo $p^{n + 1}$. Single 64-bit integer is enough.
[ "bitmasks", "dp", "math" ]
3,200
#include<cstdio> typedef long long ll; #define MN (1<<21) char A[MN+5],B[MN+5]; int s[MN+5];ll a[MN+5],b[MN+5]; int main() { int n,i,j; scanf("%d%s%s",&n,A,B); for(i=0;i<1<<n;++i)s[i]=s[i>>1]+((i&1)<<1),a[i]=(ll)(A[i]-'0')<<s[i],b[i]=(ll)(B[i]-'0')<<s[i]; for(i=0;i<n;++i)for(j=0;j<1<<n;++j)if(j&(1<<i))a[j]+=a[j^(1<<i)],b[j]+=b[j^(1<<i)]; for(i=0;i<1<<n;++i)a[i]*=b[i]; for(i=0;i<n;++i)for(j=0;j<1<<n;++j)if(j&(1<<i))a[j]-=a[j^(1<<i)]; for(i=0;i<1<<n;++i)putchar(((a[i]>>s[i])&3)+'0'); }
1036
A
Function Height
You are given a set of $2n+1$ integer points on a Cartesian plane. Points are numbered from $0$ to $2n$ inclusive. Let $P_i$ be the $i$-th point. The $x$-coordinate of the point $P_i$ equals $i$. The $y$-coordinate of the point $P_i$ equals zero (initially). Thus, initially $P_i=(i,0)$. The given points are vertices of a plot of a piecewise function. The $j$-th piece of the function is the segment $P_{j}P_{j + 1}$. In one move you can increase the $y$-coordinate of any point with odd $x$-coordinate (i.e. such points are $P_1, P_3, \dots, P_{2n-1}$) by $1$. Note that the corresponding segments also change. For example, the following plot shows a function for $n=3$ (i.e. number of points is $2\cdot3+1=7$) in which we increased the $y$-coordinate of the point $P_1$ three times and $y$-coordinate of the point $P_5$ one time: Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it). Let the height of the plot be the maximum $y$-coordinate among all initial points in the plot (i.e. points $P_0, P_1, \dots, P_{2n}$). The height of the plot on the picture above is 3. Your problem is to say which minimum possible height can have the plot consisting of $2n+1$ vertices and having an area equal to $k$. Note that it is unnecessary to minimize the number of moves. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $10^{18}$.
It is easy to see that the area of the plot is the sum of areas of all triangles in this plot. Each move increases area by one. We cannot obtain the answer less than $\lceil\frac{k}{n}\rceil$ but we always can obtain such an answer.
[ "math" ]
1,000
n, k = map(int, input().split()) print((k + n - 1) // n)
1036
B
Diagonal Walking v.2
Mikhail walks on a Cartesian plane. He starts at the point $(0, 0)$, and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point $(0, 0)$, he can go to any of the following points in one move: - $(1, 0)$; - $(1, 1)$; - $(0, 1)$; - $(-1, 1)$; - $(-1, 0)$; - $(-1, -1)$; - $(0, -1)$; - $(1, -1)$. If Mikhail goes from the point $(x1, y1)$ to the point $(x2, y2)$ in one move, and $x1 \ne x2$ and $y1 \ne y2$, then such a move is called a diagonal move. Mikhail has $q$ \textbf{queries}. For the $i$-th query Mikhail's target is to go to the point $(n_i, m_i)$ from the point $(0, 0)$ in \textbf{exactly} $k_i$ moves. Among all possible movements he want to choose one with the maximum number of diagonal moves. Your task is to find the maximum number of diagonal moves or find that it is impossible to go from the point $(0, 0)$ to the point $(n_i, m_i)$ in $k_i$ moves. Note that Mikhail \textbf{can} visit any point any number of times (even the destination point!).
There are several cases in this problem. If $n < m$ then let's swap them. Let $\%$ be the modulo operator. Firstly, if $n \% 2 \ne m \% 2$ then let's decrease $k$ and $n$ by one. Otherwise if $n \% 2 \ne k \% 2$ let's decrease $n$, $m$ by one and $k$ by two. Now if $k < n$ then the answer is -1, otherwise the answer is $k$. You can get more clear description of these cases if you will draw some cases on the paper.
[ "math" ]
1,600
q = int(input()) for i in range(q): n, m, k = map(int, input().split()) if (n < m): n, m = m, n if (n % 2 != m % 2): k -= 1 n -= 1 elif (n % 2 != k % 2): k -= 2 n -= 1 m -= 1 print(-1 if k < n else k)
1036
C
Classy Numbers
Let's call some positive integer classy if its decimal representation contains no more than $3$ non-zero digits. For example, numbers $4$, $200000$, $10203$ are classy and numbers $4231$, $102306$, $7277420000$ are not. You are given a segment $[L; R]$. Count the number of classy integers $x$ such that $L \le x \le R$. Each testcase contains several segments, for each of them you are required to solve the problem separately.
There are quite a few approaches to the problem. I'll describe the two of them which I actually implemented. First approach - combinatoric one: Problems of the form "count the number of beautiful numbers from $L$ to $R$" usually require counting the numbers on $[1; R]$ and $[1; L - 1]$ (or not inclusively $[1; R + 1)$ and $[1; L)$) and subtracting one from another. Let's try this thing here, counting $calc(R + 1) - calc(L)$ not inclusively. Let's fix some prefix of the upper border number. We want to calculate the amount of numbers having the same prefix but being smaller in the next digit. If we count it for all prefixes (including the empty one), we will get the answer. And that is pretty easy. Let the prefix include $k$ non-zero digits, the length of the suffix be $x$ and the digit after the chosen prefix is $d$. If $d$ is zero then there the result is obviously zero. Otherwise we can either put $0$ or any of the $(d - 1)$ non-zero digits. Then the formula is: $\sum \limits_{i = 0}^{3 - k} \binom{x - 1}{i} \cdot 9^i$ + $(d - 1) \cdot \sum \limits_{i = 0}^{3 - k - 1} \binom{x - 1}{i} \cdot 9^i$. We choose $i$ positions from the suffix to put non-zero digits in them (any digit from $1$ to $9$) and fill the rest with zeros. Overall complexity: $O(T \cdot \log n)$. Second approach - precalc one: This is a bit easier to implement. Actually, there are just about 700000 valid numbers, you can generate them all, put them into the array in sorted order and binary search for the given queries. Overall complexity: $O(T \cdot \log ANSCNT)$.
[ "combinatorics", "dp" ]
1,900
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; vector<long long> res; void brute(int pos, int cnt, long long cur){ if (pos == 18){ res.push_back(cur); return; } brute(pos + 1, cnt, cur * 10); if (cnt < 3) for (int i = 1; i <= 9; ++i) brute(pos + 1, cnt + 1, cur * 10 + i); } int main() { brute(0, 0, 0); res.push_back(1000000000000000000); int T; scanf("%d", &T); forn(i, T){ long long L, R; scanf("%lld%lld", &L, &R); printf("%d\n", int(upper_bound(res.begin(), res.end(), R) - lower_bound(res.begin(), res.end(), L))); } return 0; }
1036
D
Vasya and Arrays
Vasya has two arrays $A$ and $B$ of lengths $n$ and $m$, respectively. He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $[1, 10, 100, 1000, 10000]$ Vasya can obtain array $[1, 1110, 10000]$, and from array $[1, 2, 3]$ Vasya can obtain array $[6]$. Two arrays $A$ and $B$ are considered equal if and only if they have the same length and for each valid $i$ $A_i = B_i$. Vasya wants to perform some of these operations on array $A$, some on array $B$, in such a way that arrays $A$ and $B$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible. Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $A$ and $B$ equal.
Let's prove that next greedy solution works: each step we will find prefixes of minimal length of arrays $A$ and $B$ such that its sums are equal and we will cut them forming next block. If we will get valid partition in result so it is an optimal solution, otherwise there is no solution. Since length of prefix proportional to its sum, so prefixes are minimal since its sums are minimal. Let's prove this algorithm: let optimal solution have alternative partition. Since our solution cuts minimal possible prefixes, so (at some step) optimal solution cuts prefix with greater sum (and greater length). But this prefixes in optimal solutions contain smaller prefixes, found by greedy solution, so it can be divided on two parts - contradiction. So we can keep prefixes and increase one which have smaller sum. Result complexity is $O(n)$.
[ "greedy", "two pointers" ]
1,600
#include <bits/stdc++.h> using namespace std; const int N = 300 * 1000 + 9; int n, m; int a[N], b[N]; int main() { scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d", a + i); scanf("%d", &m); for(int i = 0; i < m; ++i) scanf("%d", b + i); long long sum = 0; for(int i = 0; i < n; ++i) sum += a[i]; for(int i = 0; i < m; ++i) sum -= b[i]; if(sum != 0){ puts("-1"); return 0; } int posa = 0, posb = 0; int res = 0; while(posa < n){ ++res; long long suma = a[posa++], sumb = b[posb++]; while(suma != sumb){ if(suma < sumb) suma += a[posa++]; else sumb += b[posb++]; } } printf("%d\n", res); return 0; }
1036
E
Covered Points
You are given $n$ segments on a Cartesian plane. Each segment's endpoints have integer coordinates. Segments can intersect with each other. No two segments lie on the same line. Count the number of distinct points with \textbf{integer coordinates}, which are covered by at least one segment.
I won't tell all the small geometric details, just cover some major points. The problem asks you the following thing. Sum up the total number of points covered by each segment and for each unique point subtract the number of segments covering it minus one. Let's reformulate it. For each segment add the number of points covered by it and subtract the number of points covered by it and by some already processed segment. The first part is easy. Segment covers exactly $GCD(|x1 - x2|, |y1 - y2|) + 1$ points with integer coordinates. The proof left to the reader as an exercise. The second part can be done in the following manner. Intersect the segment $i$ with all segments $j < i$, insert all the points of intersection into set and take its size. You can consider only integer points of intersection and use no floating-point numbers in your program. Overall complexity: $O(n^2 \log n)$.
[ "fft", "geometry", "number theory" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 1000 + 7; struct seg{ int x1, y1, x2, y2; seg(){}; }; struct line{ long long A, B, C; line(){}; line(seg a){ A = a.y1 - a.y2; B = a.x2 - a.x1; C = -A * a.x1 - B * a.y1; }; }; int n; seg a[N]; int get(seg a){ int dx = a.x1 - a.x2; int dy = a.y1 - a.y2; return __gcd(abs(dx), abs(dy)) + 1; } long long det(long long a, long long b, long long c, long long d){ return a * d - b * c; } bool in(int x, int l, int r){ if (l > r) swap(l, r); return (l <= x && x <= r); } bool inter(seg a, seg b, int& x, int& y){ line l1(a), l2(b); long long dx = det(l1.C, l1.B, l2.C, l2.B); long long dy = det(l1.A, l1.C, l2.A, l2.C); long long d = det(l1.A, l1.B, l2.A, l2.B); if (d == 0) return false; if (dx % d != 0 || dy % d != 0) return false; x = -dx / d; y = -dy / d; if (!in(x, a.x1, a.x2) || !in(y, a.y1, a.y2)) return false; if (!in(x, b.x1, b.x2) || !in(y, b.y1, b.y2)) return false; return true; } int main() { scanf("%d", &n); forn(i, n) scanf("%d%d%d%d", &a[i].x1, &a[i].y1, &a[i].x2, &a[i].y2); int ans = 0; int x, y; forn(i, n){ ans += get(a[i]); set<pair<int, int>> pts; forn(j, i) if (inter(a[i], a[j], x, y)) pts.insert({x, y}); ans -= pts.size(); } printf("%d\n", ans); return 0; }
1036
F
Relatively Prime Powers
Consider some positive integer $x$. Its prime factorization will be of form $x = 2^{k_1} \cdot 3^{k_2} \cdot 5^{k_3} \cdot \dots$ Let's call $x$ elegant if the greatest common divisor of the sequence $k_1, k_2, \dots$ is equal to $1$. For example, numbers $5 = 5^1$, $12 = 2^2 \cdot 3$, $72 = 2^3 \cdot 3^2$ are elegant and numbers $8 = 2^3$ ($GCD = 3$), $2500 = 2^2 \cdot 5^4$ ($GCD = 2$) are not. Count the number of elegant integers from $2$ to $n$. Each testcase contains several values of $n$, for each of them you are required to solve the problem separately.
Whoops, it seems, this problem can be done in a similar manner as in problem $C$. Firstly, is some number $x$ has $GCD$ of the prime powers not equal to $1$, then you can take root $GCD$'th power from it. That is the same as dividing all powers by $GCD$. Now it turned out, there are really a small amount of these numbers up to $10^{18}$ (if you take the squares out). Actually, our solution wasn't that. Let's count the answer using inclusion-exclusion principle. For this Mobius function can be used. The answer is: $\sum \limits_{i = 1}^{\infty} (\lfloor n^{\frac 1 i} \rfloor - 1) \cdot \mu_i$. The power part is the amount of numbers, which raised to the $i$-th power becomes less ot equal to $n$. This turns zero for like $60$ iterations on $i$ for any $n$ up to $10^{18}$. However, calculating each log as it is will lead to a $O(T \cdot \log^2 n)$ solution, which might be too slow. Let's process the queries in the decreasing order of $n$. $\sqrt n$ will be calculated naively each time (in $O(1)$ (or however complexity has the built-in function, $O(\log \log n)$ maybe) or $O(\log n)$). The rest powers will be initialized with their upper limits in the start (like $10^6$ for $3$, $10^3$ for $6$ and so on). Now proceeding to the next number will only decrease the current maximum number for each power. Subtract one until you reach the needed number and check in $\log n$. Overall complexity: $O(T \cdot (\log n + \log T))$.
[ "combinatorics", "math", "number theory" ]
2,400
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int K = 100; const int N = 100 * 1000 + 13; const long long INF64 = 3e18; int mu[K]; void precalc(){ static bool prime[K]; static int lst[K]; memset(prime, false, sizeof(prime)); forn(i, K) lst[i] = i; for (int i = 2; i < K; ++i){ if (lst[i] == i) mu[i] = 1; for (int j = 2 * i; j < K; j += i){ lst[j] = min(lst[j], lst[i]); if (lst[j] == lst[i]) mu[j] = 0; else mu[j] = -mu[i]; } } } int mx[K]; long long binpow(long long a, int b){ long long res = 1; while (b){ if (b & 1){ if (res < INF64 / a) res *= a; else return INF64; } if (b > 1){ if (a < INF64 / a) a *= a; else return INF64; } b >>= 1; } return res; } long long calc(long long n){ int pw = 63 - __builtin_clzll(n); for (int i = 3; i <= pw; ++i){ if (mu[i] == 0) continue; while (binpow(mx[i], i) > n) --mx[i]; } long long res = n - 1; for (int i = 2; i <= pw; ++i) res -= mu[i] * (mx[i] - 1); return res; } int get_sqrt(long long n){ int l = 1, r = 1000000000; while (l < r - 1){ int m = (l + r) / 2; if (m * 1ll * m <= n) l = m; else r = m; } return (r * 1ll * r <= n ? r : l); } long long ans[N]; int main() { precalc(); int T; scanf("%d", &T); vector<pair<long long, int>> q; forn(i, T){ long long n; scanf("%lld", &n); q.push_back({n, i}); } sort(q.begin(), q.end(), greater<pair<long long, int>>()); mx[3] = 1000000; mx[4] = 31622; mx[5] = 3981; for (int i = 6; i < K; ++i) mx[i] = 1000; forn(z, T){ long long n = q[z].first; mx[2] = get_sqrt(n); ans[q[z].second] = calc(n); } forn(i, T) printf("%lld\n", ans[i]); return 0; }
1036
G
Sources and Sinks
You are given an acyclic directed graph, consisting of $n$ vertices and $m$ edges. The graph contains no multiple edges and no self-loops. The vertex is called a source if it has no incoming edges. The vertex is called a sink if it has no outgoing edges. These definitions imply that some vertices can be both source and sink. The number of sources in the given graph is equal to the number of sinks in it, and each of these numbers doesn't exceed $20$. The following algorithm is applied to the graph: - if the graph has no sources and sinks then quit; - choose arbitrary source $s$, arbitrary sink $t$, add an edge from $t$ to $s$ to the graph and go to step $1$ (that operation pops $s$ out of sources and $t$ out of sinks). Note that $s$ and $t$ may be the same vertex, then a self-loop is added. At the end you check if the graph becomes strongly connected (that is, any vertex is reachable from any other vertex). Your task is to check that the graph becomes strongly connected no matter the choice of sources and sinks on the second step of the algorithm.
Since the graph is acyclic, then for every vertex there exists a path to some sink, and to every vertex there exists a path from some source. So our problem can be reduced to the following: check that after running our algorithm, all vertices from the initial set of sources and sinks belong to the same strongly connected component. Let $C$ be the number of sources (or sinks) in the initial graph. First of all, let's run DFS (or any other graph traversal) from every source to form a set of reachable sinks for every source. This part of solution has complexity of $O(C(n + m))$. If $X$ is some set of sources of the original graph, let $f(X)$ be the set of sinks such that every sink from $f(X)$ is reachable from at least one source from $X$. It's easy to see that there exists some set $X$ such that $|X| \ne 0$, $|X| \ne C$ and $|X| \ge |f(X)|$, then the answer is NO - if we connected the sinks from $f(X)$ with the sources from $X$, then any sink not belonging to $f(X)$ would be unreachable from any sink belonging to $f(X)$. Checking every possible set $X$ can be done in $O(C^2 2^C)$ or in $O(C 2^C)$. Let's prove that there is no such set $X$, then the answer is YES. Let $s$ be an arbitrary sink of the original graph. Also, if $S$ is some set of sinks, let $h(S)$ be the set of sources containing every source directly connected to some sink from $S$. We can use mathematical induction to prove that every source and every sink is reachable from $s$ in the resulting graph: Initially we state that $s$ is reachable from $s$ (quite obvious); If there is a set of sinks $S$ reachable from $s$, then either $|S| = C$ (and the whole graph is reachable from $s$), or the number of sinks reachable from $h(S)$ is at least $|S| + 1$, so some set of $|S| + 1$ sinks is reachable from $s$. So in fact checking every possible subset of sources is enough.
[ "bitmasks", "brute force", "dfs and similar" ]
2,700
#include <bits/stdc++.h> using namespace std; const int N = 1000043; vector<int> g[N]; vector<int> gt[N]; vector<int> src; vector<int> snk; int reach[20]; int used[N]; void dfs(int x) { if(used[x]) return; used[x] = 1; for(auto y : g[x]) dfs(y); } int main() { int n, m; scanf("%d %d", &n, &m); for(int i = 0; i < m; i++) { int x, y; scanf("%d %d", &x, &y); --x; --y; g[x].push_back(y); gt[y].push_back(x); } for(int i = 0; i < n; i++) { if(g[i].empty()) snk.push_back(i); if(gt[i].empty()) src.push_back(i); } int cnt = src.size(); for(int i = 0; i < cnt; i++) { memset(used, 0, sizeof used); dfs(src[i]); for(int j = 0; j < cnt; j++) if(used[snk[j]]) reach[i] ^= (1 << j); } bool ok = true; for(int mask = 0; mask < (1 << cnt); mask++) { int res = 0; for(int j = 0; j < cnt; j++) if(mask & (1 << j)) res |= reach[j]; int cnt1 = __builtin_popcount(mask); int cnt2 = __builtin_popcount(res); if(cnt2 < cnt1 || (cnt2 == cnt1 && cnt1 != 0 && cnt1 != cnt)) ok = false; } if(!ok) puts("NO"); else puts("YES"); }
1037
A
Packets
You have $n$ coins, each of the same value of $1$. Distribute them into packets such that any amount $x$ ($1 \leq x \leq n$) can be formed using some (possibly one or all) number of these packets. Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single $x$, however it may be reused for the formation of other $x$'s. Find the minimum number of packets in such a distribution.
The best possible way to distribute the coins is to create packets with coins $1, 2, 4, \ldots 2^k$ with maximum possible $k$ such that $2\cdot 2^k-1 \le n$. Using them, we can make all possible numbers which can be written using first $k+1$ bits in binary representation. For representing the remaining numbers, we must include $n-2\cdot 2^k+1$ remaining coins in one packets. Complexity: $O(LogN)$
[ "constructive algorithms", "greedy", "math" ]
1,300
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int k=1,z=0; while(true) { if(n>0) z++; else break; n-=k; k*=2; } cout<<z; return 0; }
1037
B
Reach Median
You are given an array $a$ of $n$ integers and an integer $s$. It is guaranteed that $n$ is odd. In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $s$. The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $6, 5, 8$ is equal to $6$, since if we sort this array we will get $5, 6, 8$, and $6$ is located on the middle position.
For changing the median of the array, sort the given array and then the best possible candidate for making median is the middle element, because it will be better to reduce the numbers before the middle element as they are smaller and increase the numbers after the middle element as they are larger. Complexity: $O(NLogN)$
[ "greedy" ]
1,300
#include<bits/stdc++.h> using namespace std; int main() { int n,S; cin>>n>>S; vector<int> a(n); for(int i=0;i<n;i++) cin>>a[i]; long long z=LLONG_MAX; sort(a.begin(),a.end()); long long fh=0,sh=0; for(int i=0;i<n/2;i++) { if(a[i]>S) fh+=a[i]-S; if(a[n-1-i]<S) sh+=S-a[n-1-i]; } cout<<fh+sh+abs(a[n/2]-S); return 0; }
1037
C
Equalize
You are given two binary strings $a$ and $b$ of the same length. You can perform the following two operations on the string $a$: - Swap any two bits at indices $i$ and $j$ respectively ($1 \le i, j \le n$), the cost of this operation is $|i - j|$, that is, the absolute difference between $i$ and $j$. - Select any arbitrary index $i$ ($1 \le i \le n$) and flip (change $0$ to $1$ or $1$ to $0$) the bit at this index. The cost of this operation is $1$. Find the minimum cost to make the string $a$ equal to $b$. It is not allowed to modify string $b$.
This can be seen that to minimize the cost, we should use the swap operation only when there are two consecutive positions(and with opposite values) to fix. For all other positions to fix, we can use the flip operation. Complexity: $O(N)$
[ "dp", "greedy", "strings" ]
1,300
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef pair<ll,int> pli; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vpii; typedef vector<pll> vpll; #define F first #define S second typedef vector<pli> vpli; #define hell 1000000007 #define mp make_pair #define pb push_back #define all(v) v.begin(),v.end() #define tests int t; cin>>t; while(t--) #define take(a,b,c) for(b=0;b<c;b++) scanf("%d",&a[b]); int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin>>n; string s,t; cin>>s>>t; int i=0; int ans=0; while(i<n) if(s[i]!=t[i]) { if(i+1<n&&s[i+1]!=t[i+1]&&s[i]!=s[i+1]) { ans++; i+=2; } else { ans++; i++; } } else i++; cout<<ans<<endl; return 0; }
1037
D
Valid BFS?
The BFS algorithm is defined as follows. - Consider an undirected graph with vertices numbered from $1$ to $n$. Initialize $q$ as a new queue containing only vertex $1$, mark the vertex $1$ as used. - Extract a vertex $v$ from the head of the queue $q$. - Print the index of vertex $v$. - Iterate in arbitrary order through all such vertices $u$ that $u$ is a neighbor of $v$ and is not marked yet as used. Mark the vertex $u$ as used and insert it into the tail of the queue $q$. - If the queue is not empty, continue from step 2. - Otherwise finish. Since the order of choosing neighbors of each vertex can vary, it turns out that there may be multiple sequences which BFS can print. In this problem you need to check whether a given sequence corresponds to some valid BFS traversal of the given tree \textbf{starting from vertex $1$}. The tree is an undirected graph, such that there is exactly one simple path between any two vertices.
We can store the neighbors of the nodes in their adjacency lists. After that, we can sort the adjacency lists of all the nodes in the order in which they are present in the input BFS Sequence. Now we can do the standard BFS traversal starting from node $1$ and check if this BFS traversal is same as the input BFS Sequence. If its not, the answer will be "No". Complexity: $O(NLogN)$
[ "dfs and similar", "graphs", "shortest paths", "trees" ]
1,700
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef pair<ll,int> pli; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<pii> vpii; typedef vector<pll> vpll; #define F first #define S second typedef vector<pli> vpli; #define hell 1000000007 #define mp make_pair #define pb push_back #define all(v) v.begin(),v.end() #define tests int t; cin>>t; while(t--) #define take(a,b,c) for(b=0;b<c;b++) cin>>a[b]; typedef long long ll; vector<int> ans,adj[200007]; bool vis[200007]; int inputorder[200007],relorder[200007]; bool cmp(int a,int b){ return relorder[a]<relorder[b]; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n,x,a,b,i,j; cin>>n; for(i=0;i<n-1;i++){ cin>>a>>b; adj[a].pb(b); adj[b].pb(a); } for(i=0;i<n;i++){ cin>>inputorder[i]; relorder[inputorder[i]]=i; } for(i=1;i<=n;i++) sort(all(adj[i]),cmp); queue<int> q; q.push(1); memset(vis,false,sizeof(vis)); while(!(q.empty())){ queue<int> temp; while(!(q.empty())){ int x= q.front(); q.pop(); ans.pb(x); vis[x]=true; for(j=0;j<adj[x].size();j++) if(vis[adj[x][j]]==false) temp.push(adj[x][j]); } q=temp; } for(i=0;i<n;i++) if(inputorder[i]!=ans[i]){ cout<<"No"; return 0;} cout<<"Yes"; return 0; }
1037
E
Trips
There are $n$ persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends. We want to plan a trip for every evening of $m$ days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold: - Either this person does not go on the trip, - Or at least $k$ of his friends also go on the trip. Note that the friendship is not transitive. That is, if $a$ and $b$ are friends and $b$ and $c$ are friends, it does not necessarily imply that $a$ and $c$ are friends. For each day, find the maximum number of people that can go on the trip on that day.
Scan the list of all the edges and create a set S of pair<int,int> (degree of node, id of node), now keep deleting elements from set till degree of smallest element of S is less than k, while deleting a node u, update the set S using adjacency list of u i.e. all elements v which are in S and adj(u) 1. delete (degree[v],v) 2. degree[v] = degree[v] - 1 3. insert(degree[v],v) Now iterate the edges scanned in reverse order and subtract the degree of nodes by 1 and update S as described above if both nodes of edge are in S. Take the size of S after each step as solution. Complexity: $O(NLogN)$
[ "graphs" ]
2,200
/* [ C O D E T I L L I N F I N I T Y ] */ #include <set> #include <map> #include <list> #include <ctime> #include <deque> #include <queue> #include <bitset> #include <vector> #include <list> #include <stack> #include <random> #include <string> #include <numeric> #include <utility> #include <iterator> #include <fstream> #include <iostream> #include <iomanip> #include <algorithm> #include <functional> #include <unordered_map> #include <unordered_set> #include <cmath> #include <cstring> #include <cstdio> #if !defined Header_DR #define Header_DR #pragma warning(disable:4996) #define intt long long #define cin user_input #define cout output #define pi 3.14159265358979323846 #define code_jam 0 #define code_chef 0 #define rep(i,a,b) for(long long i=a;i<b;i++) #define all(v) v.begin(),v.end() #define ve vector #define pb push_back #define srt(x) sort(x.begin(),x.end()) #define mod static_cast<long long> (998244353) #define sumx(x) accumulate(x.begin(),x.end(),0LL) #define endl "\n" #endif #ifdef _WIN32 #define getcx _getchar_nolock #endif #ifdef __unix__ #define getcx getchar_unlocked #endif #ifdef __APPLE__ #define getcx getchar_unlocked #endif #if!defined FAST_IO #undef cin #undef cout #define FAST_IO ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); #define cin user_input #define cout output #endif using namespace std; namespace Xrocks {} using namespace Xrocks; namespace Xrocks { class in {}user_input; class out {}output; in& operator >> (in& X, int &Y) { scanf("%d", &Y); return X; } in& operator >> (in& X, char *Y) { scanf("%s", Y); return X; } in& operator >> (in& X, float &Y) { scanf("%f", &Y); return X; } in& operator >> (in& X, double &Y) { scanf("%lf", &Y); return X; } in& operator >> (in& X, char &C) { scanf("%c", &C); return X; } in& operator >> (in& X, string &Y) { #undef cin cin >> Y; #define cin user_input return X; } in& operator >> (in& X, long long &Y) { scanf("%lld", &Y); return X; } template<typename T> in& operator >> (in& X, vector<T> &Y) { for (auto &x : Y) cin >> x; return X; } template<typename T> out& operator << (out& X, const T &Y) { #undef cout cout << Y; #define cout output return X; } template<typename T> out& operator << (out& X, vector<T> &Y) { for (auto &x : Y) cout << x << " "; return X; } out& operator <<(out& X, const int &Y) { printf("%d", Y); return X; } out& operator <<(out& X, const char &C) { printf("%c", C); return X; } out& operator <<(out& X, const string &Y) { printf("%s", Y.c_str()); return X; } out& operator <<(out& X, const long long &Y) { printf("%lld", Y); return X; } out& operator <<(out& X, const float &Y) { printf("%f", Y); return X; } out& operator <<(out& X, const double &Y) { printf("%lf", Y); return X; } out& operator <<(out& X, const char Y[]) { printf("%s", Y); return X; } template<typename T> T max(T A) { return A; } template<typename T, typename... args> T max(T A, T B, args... S) { return max(A > B ? A : B, S...); } template<typename T> T min(T A) { return A; } template<typename T, typename... args> T min(T A, T B, args... S) { return min(A < B ? A : B, S...); } template<typename T> void vectorize(int y, ve<T> &A) { A.resize(y); } template<typename T, typename... args> void vectorize(int y, ve<T> &A, args&&... S) { A.resize(y); vectorize(y, S...); } long long fast(long long a, long long b, long long pr) { if (b == 0) return 1 % pr; long long ans = 1 % pr; while (b) { if (b & 1) ans = (ans * a) % pr; b >>= 1; a = (a * a) % pr; } return ans; } int readInt() { int n = 0; // scanf("%d", &n); // return n; int ch = getcx(); int sign = 1; while (ch < '0' || ch > '9') { if (ch == '-')sign = -1; ch = getcx(); } while (ch >= '0' && ch <= '9') n = (n << 3) + (n << 1) + ch - '0', ch = getcx(); n = n * sign; return n; } long long readLong() { long long n = 0; //scanf("%lld",&n); //return n; int ch = getcx(); int sign = 1; while (ch < '0' || ch > '9') { if (ch == '-')sign = -1; ch = getcx(); } while (ch >= '0' && ch <= '9') n = (n << 3) + (n << 1) + ch - '0', ch = getcx(); n = n * sign; return n; } long long readBin() { long long n = 0; //scanf("%lld",&n); //return n; int ch = getcx(); int sign = 1; while (ch < '0' || ch > '1') { if (ch == '-')sign = -1; ch = getcx(); } while (ch >= '0' && ch <= '1') n = (n << 1) + (ch - '0'), ch = getcx(); return n; } long long inv_(long long val, long long pr = mod) { return fast(val, pr - 2, pr); } } class solve { public: solve() { int n, m, k; cin >> n >> m >> k; ve<pair<int, int> > Edges(m); ve<int> Ans(m); ve<int> degree(n); ve<ve<pair<int, int> > > adj(n); set<pair<int, int> > Good_set; ve<int> in_good_set(n, true); for (int i = 0; i<m; i++) { cin >> Edges[i].first >> Edges[i].second; Edges[i].first--; Edges[i].second--; adj[Edges[i].first].pb({ Edges[i].second,i }); adj[Edges[i].second].pb({ Edges[i].first,i }); degree[Edges[i].first]++; degree[Edges[i].second]++; } for (int i = 0; i<n; i++) { Good_set.insert({ degree[i],i }); } while (!Good_set.empty() && Good_set.begin()->first<k) { int node = Good_set.begin()->second; for (auto &y : adj[node]) { int x = y.first; if (in_good_set[x]) { Good_set.erase({ degree[x],x }); --degree[x]; Good_set.insert({ degree[x],x }); } } Good_set.erase({degree[node],node}); in_good_set[node] = false; } for (int i = m - 1; i >= 0; i--) { Ans[i] = Good_set.size(); int u = Edges[i].first, v = Edges[i].second; if (in_good_set[u] && in_good_set[v]) { Good_set.erase({ degree[u],u }); --degree[u]; Good_set.insert({ degree[u],u }); Good_set.erase({ degree[v],v }); --degree[v]; Good_set.insert({ degree[v],v }); while (!Good_set.empty() && Good_set.begin()->first<k) { int node = Good_set.begin()->second; for (auto &y : adj[node]) { int x = y.first; if (y.second >= i) continue; if (in_good_set[x]) { Good_set.erase({ degree[x],x }); --degree[x]; Good_set.insert({ degree[x],x }); } } Good_set.erase({degree[node],node}); in_good_set[node] = false; } } } for (int i = 0; i<m; i++) { cout << Ans[i] << "\n"; } } }; int32_t main() { int t = 1, i = 1; //freopen("C:\\Users\\Xenor\\Downloads\\B.in","r",stdin); //freopen("C:\\Users\\Xenor\\Downloads\\gb2.txt","w",stdout); if (code_chef || code_jam) scanf("%d", &t); while (t--) { if (code_jam) printf("Case #%d: ", i++); new solve; } #ifdef __unix__ cout << "\n"; #endif return 0; }
1037
F
Maximum Reduction
Given an array $a$ of $n$ integers and an integer $k$ ($2 \le k \le n$), where each element of the array is denoted by $a_i$ ($0 \le i < n$). Perform the operation $z$ given below on $a$ and print the value of $z(a,k)$ modulo $10^{9}+7$. \begin{verbatim} function z(array a, integer k): if length(a) < k: return 0 else: b = empty array ans = 0 for i = 0 .. (length(a) - k): temp = a[i] for j = i .. (i + k - 1): temp = max(temp, a[j]) append temp to the end of b ans = ans + temp return ans + z(b, k) \end{verbatim}
For each element $a[i]$, find maximum $r$ such that $a[i]>a[j]$ for every $i \leq j \leq r$ and minimum $l$ such that $a[i]>a[j]$ for every $l \leq j \leq i$. Now, let us count the no. of times $a[i]$ contributes to our answer, which can be calculated as (the no. of subsegments of length $k$ which contain $i$)+(the no. of subsegments of length $2*k$ which contain $i$) + ... + (the no. of subsegments of length $k*[n/k]$ which contain $i$) where each subsegment should be between $[l,r]$. Let $x=i-l , y=r-i , x<y$ then above sum can be represented as $k+2k+3k+4k \ldots nk (nk \le x) + x + x + x \ldots m$ times $(m=(x+y)/k-n) + x-k + x-2k + x-3k$ $\ldots$ until 0 which equals $k*n*(n+1)/2 + m*x + n*x - k*h*(h+1)/2$ where $n=x/k$, $m=(x+y)/k-n$, $h=x/k$. The last part is mostly mathematical with some case work. Complexity: $O(N)$
[ "combinatorics", "data structures", "math" ]
2,500
#include <bits/stdc++.h> #define pb push_back #define hell 1000000007 #define endl '\n' #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; int n,k,A[1000005],l[1000005],r[1000005],ans; int mul(int x,int y){ return (1LL*x*y)%hell; } void solve(){ cin>>n>>k; rep(i,0,n){ cin>>A[i]; } stack<int> s; s.push(0); l[0]=0; rep(i,1,n){ while(!s.empty() && A[s.top()]<A[i]){ s.pop(); } if(s.empty()) l[i]=0; else l[i]=s.top()+1; s.push(i); } while(!s.empty()) s.pop(); s.push(n-1); r[n-1]=n-1; for(int i=n-2;i>=0;--i){ while(!s.empty() && A[s.top()]<=A[i]){ s.pop(); } if(s.empty()) r[i]=n-1; else r[i]=s.top()-1; s.push(i); } rep(i,0,n){ int t1=(min(i-l[i],r[i]-i)-k)/(k-1)+1; if(min(i-l[i],r[i]-i)-k>=0){ int cur; if(t1%2){ cur=mul(A[i],t1); cur=mul(cur,(k+1LL*(t1-1)*(k-1)/2)%hell); } else{ cur=mul(A[i],t1/2); cur=mul(cur,(2*k+1LL*(t1-1)*(k-1))%hell); } ans=(ans+cur)%hell; } if(i-l[i]+1<=k){ int t2=(r[i]-i-k)/(k-1)+1; if(r[i]-i-k>=0){ int cur=mul(A[i],t2); ans=(ans+mul(cur,i-l[i]+1))%hell; } } else{ int ft=k+((i-l[i]-1)/(k-1))*(k-1); int t2=(r[i]-i-ft)/(k-1)+1; if(r[i]-i-ft>=0){ int cur=mul(A[i],t2); ans=(ans+mul(cur,i-l[i]+1))%hell; } } if(r[i]-i+1<=k){ int t3=(i-l[i]-k)/(k-1)+1; if(i-l[i]-k>=0){ int cur=mul(A[i],t3); ans=(ans+mul(cur,r[i]-i+1))%hell; } } else{ int ft=k+((r[i]-i-1)/(k-1))*(k-1); int t3=(i-l[i]-ft)/(k-1)+1; if(i-l[i]-ft>=0){ int cur=mul(A[i],t3); ans=(ans+mul(cur,r[i]-i+1))%hell; } } int d=max(i-l[i]+1,r[i]-i+1); if(d<=k){ int t4=(r[i]-l[i]+1-k)/(k-1)+1; if(r[i]-l[i]+1-k>=0){ int cur; if(t4%2){ cur=(mul(r[i]-l[i]+2,t4)-mul(t4,(k+1LL*(t4-1)*(k-1)/2)%hell)+hell)%hell; } else{ cur=(mul(r[i]-l[i]+2,t4)-mul(t4/2,(2*k+1LL*(t4-1)*(k-1))%hell)+hell)%hell; } ans=(ans+mul(A[i],cur))%hell; } } else{ int ft=k+((d-2)/(k-1))*(k-1); int t4=(r[i]-l[i]+1-ft)/(k-1)+1; if(r[i]-l[i]+1-ft>=0){ int cur; if(t4%2){ cur=(mul(r[i]-l[i]+2,t4)-mul(t4,(ft+1LL*(t4-1)*(k-1)/2)%hell)+hell)%hell; } else{ cur=(mul(r[i]-l[i]+2,t4)-mul(t4/2,(2*ft+1LL*(t4-1)*(k-1))%hell)+hell)%hell; } ans=(ans+mul(A[i],cur))%hell; } } } cout<<ans<<endl; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t=1; // cin>>t; while(t--) solve(); return 0; }
1037
G
A Game on Strings
Alice and Bob are playing a game on strings. Initially, they have some string $t$. In one move the first player selects the character $c$ present in $t$ and erases all it's occurrences in $t$, thus splitting $t$ into many smaller strings. The game then goes independently with each of the strings — to make the move player selects one of the strings and one of the characters there, deletes all occurrences and adds the remaining string back to the game. Alice always starts the game, and then Alice and Bob take turns making moves. The player who is unable to make a move (because there is no string left) loses. Alice and Bob used to always start with a string $s$, but recently they found out that this became too boring. Now before each game they choose two integers $l$ and $r$ such that $1 \le l \le r \le |s|$ and play the game with the string $s_{l} s_{l+1} s_{l+2} \ldots s_{r}$ instead. Given the string $s$ and integers $l$, $r$ for each game. Find who is going to win each game assuming they are smart and are playing optimally.
Say, we have a string $s$. For each character, say $c$, $s$ has $c$ at $k$ positions $(a_1,a_2,...,a_k)$. Now, if we calculate grundy for strings $s[a_i+1:a_(i+1)-1]$ for $1 \leq i < k$, and also for every prefix and suffix for such strings, we can calculate the result using grundy. For a query $[l,r]$, we can iterate on the character removed in first move, and the resultant grundy number can be calculated using range xor of the precomputed grundys. To precalculate grundys, we can compute grundy in sorted order of length and treat them as separate queries. Complexity: $O(26^{2} * N + 26 * Q)$
[ "games" ]
3,200
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; const int M = 1e5 + 239; const int alf = 26; int n, q; string s; int posr[alf][M], posl[alf][M], dpl[alf][M], dpr[alf][M], z[alf][M]; int k, kols[alf], id[M]; inline int gett_slow(int l, int r) { int mask = 0; for (int x = 0; x < alf; x++) { if (posr[x][l] > r) continue; int lf = posr[x][l]; int rf = posl[x][r]; int now = 0; for (int i = id[lf]; i < id[rf]; i++) now ^= z[x][i + 1]; if (l < lf) { if (dpr[x][l] == -1) dpr[x][l] = gett_slow(l, lf - 1); now ^= dpr[x][l]; } if (rf < r) { if (dpl[x][r] == -1) dpl[x][r] = gett_slow(rf + 1, r); now ^= dpl[x][r]; } if (now < alf) mask |= (1 << now); } for (int i = 0; i < alf; i++) if (((mask >> i) & 1) == 0) return i; return alf; } inline int gett_fast(int l, int r) { int mask = 0; for (int x = 0; x < alf; x++) { if (posr[x][l] > r) continue; int lf = posr[x][l]; int rf = posl[x][r]; int now = (z[x][id[lf]] ^ z[x][id[rf]]); if (l < lf) { if (dpr[x][l] == -1) dpr[x][l] = gett_fast(l, lf - 1); now ^= dpr[x][l]; } if (rf < r) { if (dpl[x][r] == -1) dpl[x][r] = gett_fast(rf + 1, r); now ^= dpl[x][r]; } if (now < alf) mask |= (1 << now); } for (int i = 0; i < alf; i++) if (((mask >> i) & 1) == 0) return i; return alf; } int main() { ios::sync_with_stdio(0); cin >> s; n = (int)s.size(); for (int i = 0; i < n; i++) { id[i] = kols[s[i] - 'a']; kols[s[i] - 'a']++; } for (int i = 0; i < alf; i++) posr[i][n] = n; for (int i = n - 1; i >= 0; i--) { for (int x = 0; x < alf; x++) posr[x][i] = posr[x][i + 1]; posr[s[i] - 'a'][i] = i; } for (int i = 0; i < alf; i++) posl[i][0] = -1; posl[s[0] - 'a'][0] = 0; for (int i = 1; i < n; i++) { for (int x = 0; x < alf; x++) posl[x][i] = posl[x][i - 1]; posl[s[i] - 'a'][i] = i; } memset(dpl, -1, sizeof(dpl)); memset(dpr, -1, sizeof(dpr)); memset(z, 0, sizeof(z)); vector<tuple<int, int, int> > seg; for (int x = 0; x < alf; x++) { vector<int> pos; for (int i = 0; i < n; i++) if (s[i] - 'a' == x) pos.push_back(i); for (int t = 0; t < (int)pos.size() - 1; t++) seg.push_back(make_tuple(pos[t + 1] - pos[t] - 1, pos[t], pos[t + 1])); } sort(seg.begin(), seg.end()); for (tuple<int, int, int> t : seg) { int l = get<1>(t); int r = get<2>(t); if (r == l + 1) continue; int x = gett_slow(l + 1, r - 1); z[s[r] - 'a'][id[r]] = x; } for (int x = 0; x < alf; x++) for (int i = 1; i < kols[x]; i++) z[x][i] ^= z[x][i - 1]; cin >> q; for (int i = 0; i < q; i++) { int l, r; cin >> l >> r; l--, r--; cout << (gett_fast(l, r) == 0 ? "Bob\n" : "Alice\n"); } return 0; }
1037
H
Security
Some programming website is establishing a secure communication protocol. For security reasons, they want to choose several more or less random strings. Initially, they have a string $s$ consisting of lowercase English letters. Now they want to choose $q$ strings using the following steps, and you are to help them. - A string $x$ consisting of lowercase English letters and integers $l$ and $r$ ($1 \leq l \leq r \leq |s|$) are chosen. - Consider all non-empty distinct substrings of the $s_l s_{l + 1} \ldots s_r$, that is all distinct strings $s_i s_{i+1} \ldots s_{j}$ where $l \le i \le j \le r$. Among all of them choose all strings that are lexicographically greater than $x$. - If there are no such strings, you should print $-1$. Otherwise print the lexicographically smallest among them. String $a$ is lexicographically less than string $b$, if either $a$ is a prefix of $b$ and $a \ne b$, or there exists such a position $i$ ($1 \le i \le min(|a|, |b|)$), such that $a_i < b_i$ and for all $j$ ($1 \le j < i$) $a_j = b_j$. Here $|a|$ denotes the length of the string $a$.
The solution does the following: 1. Build the suffix tree of the whole string (we can construct a suffix tree in $O(|S|log|S|)$ time using Suffix Array and LCP Array or in O($|S|$) using any well known algorithm like Ukkonen's algorithm). 2. Note that in a suffix tree, any path from root to leaf is a suffix of the given string. Since we have appended an additional character at the end of S, whose ascii value is smaller than all the literals of string $S$, we have $|S| + 1$ leaves in our suffix tree. 3. For example consider the suffix tree of $aabcaba$. It will look like image shown. 4. Create appropriate type segment tree for the leaves from left to right storing starting position of that leaves. i.e segment tree for $S = aabcaba$ is $[7, 6, 0, 4, 1, 5, 2, 3]$ (starting positions are using 0 based indexing for string S). 5. To answer the request $L R X$, start descending with this string in the suffix tree from root. To make the larger string we can end the descent process and go on the other edge (which contains a larger symbol), to do this we need to have at least one valid suffix in this subtree - Valid suffix: it's beginning $i$ should be $L \leq i$, $i \leq R$ and if you stand in the vertex of subtree with length $len$, then $i + len \leq R$, that is $i \leq R - len$. So the request is too see if any leaf in subtree of matching character from current node has at least on value $L \leq i \leq R-len$. The rest is to handle the descent, i.e for example if going to a node with match character from current node, in the middle if we encounter the character to be greater than corresponding character of X, then we will stop the descent process, or if the character of S is smaller than corresponding character of X, then we must ascend till we find a node having valid suffix and matching character greater than corresponding character of S. Complexity of the solution is $O(|x|log(n)*26)$ per request. Consider processing the query for $S = aabcaba$: 2 5 abca Modify for 0 based indexes i.e. 1 4 abca Matching character a, $1 \leq i \leq 5$: The node 3 matches with a, its subtree have leaves with [6,0,4,1] values and [1,4] are acceptable, so we can ascend. Matching character b, $1 \leq i \leq 4$: The node 6 matches with b, its subtree have leaves with [4,1] both are acceptable values for i, so we can ascend to node 6. Matching character c, $1 \leq i \leq 3$: The node 8 matches with c, has leaf with value 1, and it is valid, now we start matching subsequent characters to reach node 8, match c, $1 \leq i \leq2$ match a, $1 \leq i \leq1$ match $ , $1 \leq i \leq 0$ (can't match so start ascent process) Current node 6: No node with character > c exists, so move to its parent 3. Current node 3: No node with character > b exists, so move to its parent 1. Current node 1: Node 9 has starting character b, which is greater than a, also the subtree of node 9 contains leaves with values [5,2], $1 \leq i \leq 5$, so we can take b and print the currently traversed string so far. Complexity: $O(|x| * LogN * 26)$ per request.
[ "data structures", "string suffix structures" ]
3,200
#include <cstring> #include <vector> #include <algorithm> #include <map> #include <iostream> using namespace std; #define ve vector #define MaxN 500010 #pragma warning(disable:4996) /* Persistent segment tree */ int Slen=100001; const int SZ = MaxN * 21; int seg_tree[SZ], L_ptr[SZ], R_ptr[SZ], Next = 1; int add(int c, int l, int r, int pos) { if (l>pos || r < pos) return c; int ID = Next++; if (l == r) { seg_tree[ID] = seg_tree[c] + 1; return ID; } int mid = (l + r) >> 1; L_ptr[ID] = add(L_ptr[c], l, mid, pos); R_ptr[ID] = add(R_ptr[c], mid + 1, r, pos); seg_tree[ID] = seg_tree[L_ptr[ID]] + seg_tree[R_ptr[ID]]; return ID; } int find_sum(int l_tree_c, int r_tree_c, int l, int r, int qry_l, int qry_r) { if (qry_l > r || qry_r < l) return 0; if (l >= qry_l && r <= qry_r) { return seg_tree[r_tree_c] - seg_tree[l_tree_c]; } int mid = (l + r) >> 1; return find_sum(L_ptr[l_tree_c], L_ptr[r_tree_c], l, mid, qry_l, qry_r) + \ find_sum(R_ptr[l_tree_c], R_ptr[r_tree_c], mid + 1, r, qry_l, qry_r); } int find_first(int l_tree_c, int r_tree_c, int l, int r, int qry_l, int qry_r) { if (qry_l > r || qry_r < l || (seg_tree[r_tree_c] - seg_tree[l_tree_c]) == 0) return -1; if (l == r) { return l; } int mid = (l + r) >> 1; int val = find_first(L_ptr[l_tree_c], L_ptr[r_tree_c], l, mid, qry_l, qry_r); if (val == -1) return find_first(R_ptr[l_tree_c], R_ptr[r_tree_c], mid + 1, r, qry_l, qry_r); return val; } /*Standard Suffix array implementation*/ char T[MaxN], S[MaxN]; int n; int RA[MaxN], tempRA[MaxN]; int SA[MaxN], tempSA[MaxN]; int LCP[MaxN], Phi[MaxN], PLCP[MaxN]; int c[MaxN], cnt = 1; void countingSort(int k) { int i, sum, maxi = max(300, n); // up to 255 ASCII chars or length of n memset(c, 0, sizeof c); // clear frequency table for (i = 0; i < n; i++) // count the frequency of each integer rank c[i + k < n ? RA[i + k] : 0]++; for (i = sum = 0; i < maxi; i++) { int t = c[i]; c[i] = sum; sum += t; } for (i = 0; i < n; i++) // shuffle the suffix array if necessary tempSA[c[SA[i] + k < n ? RA[SA[i] + k] : 0]++] = SA[i]; for (i = 0; i < n; i++) // update the suffix array SA SA[i] = tempSA[i]; } void constructSA() { // this version can go up to 100000 characters int i, k, r; for (i = 0; i < n; i++) RA[i] = T[i]; // initial rankings for (i = 0; i < n; i++) SA[i] = i; // initial SA: {0, 1, 2, ..., n-1} for (k = 1; k < n; k <<= 1) { // repeat sorting process log n times countingSort(k); // actually radix sort: sort based on the second item countingSort(0); // then (stable) sort based on the first item tempRA[SA[0]] = r = 0; // re-ranking; start from rank r = 0 for (i = 1; i < n; i++) // compare adjacent suffixes tempRA[SA[i]] = // if same pair => same rank r; otherwise, increase r (RA[SA[i]] == RA[SA[i - 1]] && RA[SA[i] + k] == RA[SA[i - 1] + k]) ? r : ++r; for (i = 0; i < n; i++) // update the rank array RA RA[i] = tempRA[i]; if (RA[SA[n - 1]] == n - 1) break; // nice optimization trick } } void computeLCP() { int i, L; Phi[SA[0]] = -1; // default value for (i = 1; i < n; i++) // compute Phi in O(n) Phi[SA[i]] = SA[i - 1]; // remember which suffix is behind this suffix for (i = L = 0; i < n; i++) { // compute Permuted LCP in O(n) if (Phi[i] == -1) { PLCP[i] = 0; continue; } // special case while (T[i + L] == T[Phi[i] + L]) L++; // L increased max n times PLCP[i] = L; L = max(L - 1, 0); // L decreased max n times } for (i = 0; i < n; i++) // compute LCP in O(n) LCP[i] = PLCP[SA[i]]; // put the permuted LCP to the correct position } struct node { int lf, sp, depth; map<char, node*> M; node* parent; node() :lf(0), depth(0), parent(NULL), sp(0) {} /* sp = starting index of suffix in string depth = length of string from that suffix */ }*rt; node pool[MaxN * 2 + 4]; int CNT = 0; node& get_node() { return pool[CNT++]; } void split(node *&n, int id, int lcp) { node *x = n->parent; node *y = &get_node(); node *z = &get_node(); x->M[T[n->sp + x->depth]] = y; y->depth = lcp; y->sp = id; y->M[T[lcp + id]] = z; y->M[T[n->sp + lcp]] = n; y->parent = x; n->parent = y; z->depth = ::n - id; z->sp = id; z->parent = y; n = z; } void add(node *&n, int id, int lcp) { if (lcp == 0) { node *y = &get_node(); y->depth = ::n - id; y->sp = id; y->parent = rt; rt->M[T[id]] = y; n = y; return; } while (n->parent->depth > lcp) n = n->parent; if (n->parent->depth == lcp) { n = n->parent; node *y = &get_node(); y->depth = ::n - id; y->sp = id; y->parent = n; n->M[T[id + lcp]] = y; n = y; return; } split(n, id, lcp); } ve<int> start_idx(1 + MaxN * 2), end_idx(MaxN), tree_id(MaxN * 2 + 1); void dfs(node *n) { n->lf = cnt++; start_idx[n->lf] = n->lf; if (!(n->M.size())) tree_id[n->lf] = add(tree_id[n->lf - 1], 0, Slen, n->sp); else tree_id[n->lf] = tree_id[n->lf - 1]; for (auto &x : n->M) { dfs(x.second); } end_idx[n->lf] = cnt - 1; } /* 1 Exist 1.1 Exact match 1.2 Greater 2 Do not exist */ void climb_up_for_greater(node *cr, int L, int R) { int match = cr->depth; while (true) { match = cr->depth; if (cr->M.upper_bound(S[match]) == cr->M.end()) { if (cr == rt) break; cr = cr->parent; continue; } auto it = cr->M.upper_bound(S[match]); int start, end; int left_valid = -1; while (it != cr->M.end() && left_valid == -1) { start = it->second->lf, end = it->second->lf; left_valid = find_first(tree_id[start_idx[start] - 1], tree_id[end_idx[end]], 0, Slen, L, R - cr->depth); if (left_valid != -1) { break; } ++it; } if (left_valid == -1) { if (cr == rt) { break; } cr = cr->parent; continue; } for (int i = left_valid; i <= left_valid + match; i++) { putchar(T[i]); } putchar('\n'); return; } printf("-1\n"); } void query(int L, int R) { node *cr = rt; int match = 0; int Len = strlen(S); while (true) { if (cr->M.lower_bound(S[match]) == cr->M.end()) { climb_up_for_greater(cr, L, R); return; } auto it = cr->M.lower_bound(S[match]); int start, end; int left_valid = -1; while (it != cr->M.end() && left_valid == -1) { start = it->second->lf, end = it->second->lf; left_valid = find_first(tree_id[start_idx[start] - 1], tree_id[end_idx[end]], 0, Slen, L, R - cr->depth); if (left_valid != -1) { cr = it->second; break; } ++it; } if (left_valid == -1) { climb_up_for_greater(cr, L, R); return; } /* match till required characters are matched first mismatch < : climp_up_for_greater > : print and return exceeded Len print and return */ start = left_valid + match; while (match < Len && match < cr->depth && start <= R && T[start] == S[match]) ++match, ++start; if (match == cr->depth) continue; if (start > R) { cr = cr->parent; climb_up_for_greater(cr, L, R); return; } if (match == Len || T[start]>S[match]) { for (int i = left_valid; i <= start; i++) putchar(T[i]); putchar('\n'); return; } if (T[start] < S[match]) { cr = cr->parent; climb_up_for_greater(cr, L, R); return; } } } int main() { scanf("%s", T); n = strlen(T); T[n++] = '$'; // add terminating character constructSA(); computeLCP(); node *ty; rt = &get_node(); ty = rt; for (int i = 0; i < n; i++) { add(ty, SA[i], LCP[i]); } dfs(rt); int q; cin >> q; for (int i = 0; i < q; i++) { int L, R; scanf("%d%d%s", &L, &R, S); --L, --R; query(L, R); } return 0; }
1038
A
Equality
You are given a string $s$ of length $n$, which consists only of the first $k$ letters of the Latin alphabet. All letters in string $s$ are uppercase. A subsequence of string $s$ is a string that can be derived from $s$ by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD" are subsequences of "ABCDE", but "DEA" is not. A subsequence of $s$ called good if the number of occurences of each of the first $k$ letters of the alphabet is the same. Find the length of the longest good subsequence of $s$.
First we need to find the frequencies of the first $k$ alphabets in the string. Let the minimum frequency among these frequencies be $m$. Then we cannot select $m+1$ characters of one kind, and we can definitely select $m$ characters of each kind, hence the answer is given by $\mathrm{min}$(frequency of first $k$ characters) * $k$ Overall Complexity: $O(n)$
[ "implementation", "strings" ]
800
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" int n, k; string s; int f[26]; int32_t main() { IOS; cin>>n>>k>>s; for(auto &it:s) f[it-'A']++; int ans=f[0]; for(int i=0;i<k;i++) ans=min(ans, f[i]); ans*=k; cout<<ans; return 0; }
1038
B
Non-Coprime Partition
Find out if it is possible to partition the first $n$ positive integers into two \textbf{non-empty} disjoint sets $S_1$ and $S_2$ such that: \begin{center} $\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1$ \end{center} Here $\mathrm{sum}(S)$ denotes the sum of all elements present in set $S$ and $\mathrm{gcd}$ means thegreatest common divisor. Every integer number from $1$ to $n$ should be present in \textbf{exactly one} of $S_1$ or $S_2$.
There are many ways to solve this question. The easiest way perhaps was to note that the sum of first $n$ numbers is given by $\frac{n*(n+1) }{2}$, and one of $\frac{n}{2}$ or $\frac{n+1}{2}$ has to be an integer, suppose $k$. Then we can partition the numbers into two sets, one containing $k$ and the other containing the remaining integers, both of which will have $k$ as a common factor. Special Case: There is no answer for $n \le 2$ Overall Complexity: $O(n)$
[ "constructive algorithms", "math" ]
1,100
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N=1e5+5; int32_t main() { IOS; int n; cin>>n; if(n<=2) { cout<<"No"; return 0; } else { cout<<"Yes"<<endl; int k=(n%2==0)?(n/2):((n+1)/2); cout<<"1 "<<k<<endl; cout<<n-1<<" "; for(int i=1;i<=n;i++) { if(i==k) continue; cout<<i<<" "; } cout<<endl; } return 0; }
1038
C
Gambling
Two players A and B have a list of $n$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty). Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $\{1, 2, 2, 3\}$ in a list and you decided to choose $2$ for the next turn, only a single instance of $2$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally. Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.
This problem was greedy. First, it is obvious that both the players will try to either take their own maximum value or remove the opponent's maximum value. Hence, the arrays should be sorted and two pointers should be maintained to keep track of how many elements from each array have been counted/removed already. In every move, if the person has a choice to either take his own value $A$ or remove his opponent's value $B$, then he will make the choice dependent on the values of $A$ and $B$. In fact, it turns out that it is optimal just to select the choice with a greater number (in case of tie any will do). How to prove it? One can show by induction that it does the same as the dynamic programming of size $n^2$. However, there is a more nice way. Let's say that initially each player gets $0.5$ of all numbers in his list. This way when you choose a number from your own list you add the rest $0.5$ of it to the score. And when you remove the number from opponent's list you remove the $0.5$ of it from your opponent's score. Clearly, all moves become symmetrical to both players now! So each player can make a decision just based on which of the moves is greater. If $A \gt B$, then he will take his number. If $A \lt B$, he will discard the opponent's number $B$. If $A=B$, he can make either of the above moves, it will not make a difference. Complexity: $O(n \log n)$
[ "greedy", "sortings" ]
1,300
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N=1e5+5; int n; int a[N], b[N]; int32_t main() { IOS; cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=1;i<=n;i++) cin>>b[i]; sort(a+1, a+n+1); sort(b+1, b+n+1); reverse(a+1, a+n+1); reverse(b+1, b+n+1); int i=1, j=1, player=0, moves=0, asum=0, bsum=0; while(moves<2*n) { moves++; if(!player) { if(a[i]>=b[j]) { asum+=a[i]; i++; } else j++; } else { if(b[j]>=a[i]) { bsum+=b[j]; j++; } else i++; } player^=1; } cout<<asum-bsum; return 0; }
1038
D
Slime
There are $n$ slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it. Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists). When a slime with a value $x$ eats a slime with a value $y$, the eaten slime disappears, and the value of the remaining slime changes to $x - y$. The slimes will eat each other until there is only one slime left. Find the maximum possible value of the last slime.
For every slime, its value will either be added in the final answer or subtracted. Let us give each slime a sign $+$ or $-$ to denote whether its value will be added or subtracted. The key observation to solving the problem is that any combination of $+$ and $-$ is obtainable, except where all signs are $+$ or all are $-$ (exception n=1, where the answer is the value of the slime itself) If the array contains a combination of non-zero positive elements and non-zero negative elements, then we can simply add all their absolute values (since we can put $+$ in front of positive-valued slimes and $-$ in front of negative-valued slimes) However, if the array contains only positive-valued slimes, we put $-$ in front of the least valued slime and $+$ in front of all the others. Similarly, for negative-valued slimes, we put $+$ in front of minimum absolute valued slime. It could have also been solved with DP where we check if - sign has been taken or not, and + sign has been taken or not. ($4n$ states) Overall Complexity: $O(n)$
[ "dp", "greedy", "implementation" ]
1,800
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N=5e5+5; int n, minval=1e9, ans=0; int a[N]; bool checkpos=0, checkneg=0; int32_t main() { IOS; cin>>n; if(n==1) { int k; cin>>k; cout<<k; exit(0); } for(int i=1;i<=n;i++) { cin>>a[i]; minval=min(abs(a[i]), minval); checkpos|=(a[i]>=0); checkneg|=(a[i]<=0); ans+=abs(a[i]); } if(checkpos&&checkneg) cout<<ans; else cout<<ans-2*minval; return 0; }
1038
E
Maximum Matching
You are given $n$ blocks, each of them is of the form [color$_1$|value|color$_2$], where the block can also be flipped to get [color$_2$|value|color$_1$]. A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if the left color of the B is the same as the right color of the A and the right color of the B is the same as the left color of C. The value of the sequence is defined as the sum of the values of the blocks in this sequence. Find the maximum possible value of the valid sequence that can be constructed from the subset of the given blocks. The blocks from the subset can be reordered and flipped if necessary. Each block can be used at most once in the sequence.
Create a graph with $4$ nodes $1-4$ representing the colors. Then the value of a block serves as an edge between the two colors of that block. Then the question reduces to finding an euler tour in the graph with the maximum sum of edges traveled. An euler tour may not exist with all the given edges, so the question is: Which edges do we remove? One can note that there are $16$ types of edges. (Edges connecting 1 to 1, 1 to 2 and so on). There may be multiple edges of a specific type, however atmost 1 of it will be removed to form a valid euler tour. This is because if we have $2x + y$ edges between node $A$ and node $B$ where $0 \le y \le 1$, we can simply loop back and forth between $A$ and $B$ $x$ times to end up at the node we started from. Since there are only $16$ types of edges, we can use bitmask to iterate over all the possibilities, and checking whether an euler tour exists in the graph with the marked edges removed (if there are multiple edges between node $A$ and node $B$, we remove only one edge, the one with the least value). Refer to author's solution/any AC codes to see implementation details. Overall Complexity: $O(2^{16} \times n)$ Bonus: Can you solve this question in $O(n^2)$? How about $O(n)$?
[ "bitmasks", "brute force", "dfs and similar", "dp", "graphs" ]
2,400
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N=1005; const int M=16; struct data { int c1, c2, val, idx; bool operator<(data &b) { return val<b.val; } }; int n, sum=0, ans=0; bool ban[N], vis[N]; int cnt[M], taken[M]; data blocks[N]; vector<data> g[M], edges[M]; vector<int> path; int compress(int c1, int c2) { if(c1>c2) swap(c1, c2); return c1*4 + c2; } bool checker() { memset(cnt, 0, sizeof(cnt)); for(int i=1;i<path.size();i++) cnt[compress(path[i-1], path[i])]++; for(int i=0;i<M;i++) if(cnt[i]>taken[i]) return 0; return 1; } void euler(int u) { for(auto &it:g[u]) { int v=it.c2; int idx=it.idx; if(vis[idx]||ban[idx]) continue; taken[compress(u, v)]++; vis[idx]=1; sum+=it.val; euler(v); } path.push_back(u); } int32_t main() { IOS; cin>>n; for(int i=1;i<=n;i++) { int c1, val, c2; cin>>c1>>val>>c2; c1--; c2--; blocks[i]=(data){c1, c2, val, i}; g[c1].push_back((data){c1, c2, val, i}); g[c2].push_back((data){c2, c1, val, i}); edges[compress(c1, c2)].push_back(blocks[i]); } for(int i=0;i<M;i++) if(edges[i].size()) sort(edges[i].begin(), edges[i].end()); for(int mask=0;mask<(1<<M);mask++) { if(mask>>compress(0, 0)&1) continue; if(mask>>compress(1, 1)&1) continue; if(mask>>compress(2, 2)&1) continue; if(mask>>compress(3, 3)&1) continue; int check=0; memset(ban, 0, sizeof(ban)); for(int i=0;i<M;i++) { if(!(mask>>i & 1)) continue; if(edges[i].empty()) check=1; else ban[edges[i][0].idx]=1; } if(!check) continue; for(int i=0;i<4;i++) { memset(vis, 0, sizeof(vis)); path.clear(); sum=0; memset(taken, 0, sizeof(taken)); euler(i); if(checker()) ans=max(ans, sum); } } cout<<ans; return 0; }
1038
F
Wrap Around
You are given a binary string $s$. Find the number of distinct cyclical binary strings of length $n$ which contain $s$ as a substring. The cyclical string $t$ contains $s$ as a substring if there is some cyclical shift of string $t$, such that $s$ is a substring of this cyclical shift of $t$. For example, the cyclical string "000111" contains substrings "001", "01110" and "10", but doesn't contain "0110" and "10110". Two cyclical strings are called different if they differ from each other as strings. For example, two different strings, which differ from each other by a cyclical shift, are still considered \textbf{different} cyclical strings.
The idea was to solve the problem using Dynamic Programming. The constraints of the question were set low to allow even the most basic Dynamic Programming approaches to pass (see the author's solution to see an easy, but time-costly implementation). The solution idea was to use $2n^4$ DP with 4 states: $DP[A][B][C][D]$ $\\$ $A$ = Current matching suffix length of string ($n$) $\\$ $B$ = Length of string $t$ so far ($n$) $\\$ $C$ = Whether string $t$ contains $s$ as a substring (non-cyclical) so far ($2$) $\\$ $D$ = Length of the suffix of $t$ that is a prefix of $s$ ($n^2$) You can refer to AC codes for transitions. We may add more details by tomorrow. You can see author's code for an unoptimised approach, and to tester's code for an optimised solution. Overall Complexity: $O(n^4)$
[ "dp", "strings" ]
2,900
// 2018, Sayutin Dmitry. #include <bits/stdc++.h> using std::cin; using std::cout; using std::cerr; using std::vector; using std::map; using std::array; using std::set; using std::string; using std::pair; using std::make_pair; using std::min; using std::abs; using std::max; using std::unique; using std::sort; using std::generate; using std::reverse; using std::min_element; using std::max_element; #ifdef LOCAL #define LASSERT(X) assert(X) #else #define LASSERT(X) {} #endif template <typename T> T input() { T res; cin >> res; LASSERT(cin); return res; } template <typename IT> void input_seq(IT b, IT e) { std::generate(b, e, input<typename std::remove_reference<decltype(*b)>::type>); } #define SZ(vec) int((vec).size()) #define ALL(data) data.begin(),data.end() #define RALL(data) data.rbegin(),data.rend() #define TYPEMAX(type) std::numeric_limits<type>::max() #define TYPEMIN(type) std::numeric_limits<type>::min() #define pb push_back #define eb emplace_back const int max_n = 100; int64_t dp[max_n + 5][max_n + 5][max_n + 5]; vector<int> get_pi(const string& s) { vector<int> res(SZ(s), 0); for (int i = 1; i != SZ(s); ++i) { int k = res[i - 1]; while (k != -1 and s[i] != s[k]) k = (k == 0 ? -1 : res[k - 1]); res[i] = k + 1; } return res; } int64_t solve(const string& s, int n) { vector<int> pi = get_pi(s); vector<int> go[2]; go[0] = go[1] = vector<int>(SZ(s) + 1, -1); go[0][SZ(s)] = go[1][SZ(s)] = SZ(s); go[s[0] - '0'][0] = 1; go[(s[0] - '0') ^ 1][0] = 0; for (int i = 1; i != SZ(s); ++i) { int alp = s[i] - '0'; go[alp][i] = i + 1; go[alp ^ 1][i] = go[alp ^ 1][pi[i - 1]]; } // (state_fin, len, go(state_fin, cur_prefix), go(0, cur_prefix)) int64_t ans = 0; for (int state_fin = 0; state_fin <= SZ(s); ++state_fin) { for (int i = 0; i <= n; ++i) for (int j = 0; j <= SZ(s); ++j) for (int k = 0; k <= SZ(s); ++k) dp[i][j][k] = 0; auto next = [&](int i, int j, int k, int64_t val) { dp[i][j][k] += val; }; dp[0][state_fin][0] = 1; for (int len = 0; len < n; ++len) for (int st1 = 0; st1 <= SZ(s); ++st1) for (int st2 = 0; st2 <= SZ(s); ++st2) { next(len + 1, go[0][st1], go[0][st2], dp[len][st1][st2]); next(len + 1, go[1][st1], go[1][st2], dp[len][st1][st2]); } ans += dp[n][SZ(s)][state_fin]; } return ans; } int main() { std::iostream::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n = input<int>(); string s = input<string>(); cout << solve(s, n) << "\n"; return 0; }
1039
A
Timetable
There are two bus stops denoted A and B, and there $n$ buses that go from A to B every day. The shortest path from A to B takes $t$ units of time but some buses might take longer paths. Moreover, buses are allowed to overtake each other during the route. At each station one can find a sorted list of moments of time when a bus is at this station. We denote this list as $a_1 < a_2 < \ldots < a_n$ for stop A and as $b_1 < b_2 < \ldots < b_n$ for stop B. The buses always depart from A and arrive to B according to the timetable, but the order in which the buses arrive may differ. Let's call an order of arrivals valid if each bus arrives at least $t$ units of time later than departs. It is known that for an order to be valid the latest possible arrival for the bus that departs at $a_i$ is $b_{x_i}$, i.e. $x_i$-th in the timetable. In other words, for each $i$ there exists such a valid order of arrivals that the bus departed $i$-th arrives $x_i$-th (and all other buses can arrive arbitrary), but there is no valid order of arrivals in which the $i$-th departed bus arrives $(x_i + 1)$-th. Formally, let's call a permutation $p_1, p_2, \ldots, p_n$ valid, if $b_{p_i} \ge a_i + t$ for all $i$. Then $x_i$ is the maximum value of $p_i$ among all valid permutations. You are given the sequences $a_1, a_2, \ldots, a_n$ and $x_1, x_2, \ldots, x_n$, but not the arrival timetable. Find out any suitable timetable for stop B $b_1, b_2, \ldots, b_n$ or determine that there is no such timetable.
If there is at least one valid ordering $p$'s (and it surely exists since the $x$ is defined), then the ordering $p_i = i$ is also valid. Hence if for some $i$ doesn't hold $x_i \ge i$ then the answer is no. Also, from this follows that $b_i \ge a_i + t$. Otherwise, what it means that $x_i = c$? It means that there is an ordering $p$, in which the $i$-th bus comes as $c$, where the other buses will come then? It turns out, that the least restricting way to complete the ordering is following: $i \to c$, $i + 1 \to i$, $i + 2 \to i$, ..., $c \to c - 1$. Note that since ordering $p_i = i$, it is also allowed for $i$ to go to $c$ (it wouldn't be too fast), but we can doubt whether $i + 1 \to i$, $i + 2 \to i$ and etc are good. More over, since $x_i = c$ (not, say, $c + 1$), it must hold that $i + 1 \to i$, $i + 2 \to i$, ..., $c \to c - 1$ are "good" (not fast enough), but doesn't hold $c + 1 \to c$ (too fast). So for each $i$ we can use scanline to calculate whether it is good or not. And then we can restore $b$'s in negative order. What conditions must hold on $b$? $b_i \ge a_i + i$, and depending on whether some $i$ is good or not $b_i \ge a_{i + 1} + t$ or $b_i < a_{i + 1} + t$. We can go in reverse order and select the value of $b_i$ on the basis of the cases above. Also, since $b_i < b_{i + 1}$ if there are many options for $b_i$ it is best to select the largest of them.
[ "constructive algorithms", "data structures", "greedy", "math" ]
2,300
null
1039
B
Subway Pursuit
This is an interactive problem. In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI. The subway of the Metropolis is one line (regular straight line with no self-intersections) with $n$ stations, indexed consecutively from $1$ to $n$. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured. To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers $l$ and $r$ ($l \le r$), and then check, whether the train is located on a station with index between $l$ and $r$, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most $k$ stations away. Formally, if the train was at the station $x$ when the gadget was applied, then at the next application of the gadget the train can appear at any station $y$ such that $\max(1, x - k) \leq y \leq \min(n, x + k)$. Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan. After an examination of the gadget you found that it is very old and can hold no more than $4500$ applications, after which it will break and your mission will be considered a failure. Can you find the station with the train using no more than $4500$ applications of the gadgets?
Notice that we can make segment in which we are located small enough using binary search. Let $[l; r]$ be the last segment about which we knew for sure that train is in it (at the beginning it's $[1; n]$). Let $m = \frac{l + r}{2}$. Let's ask about segment $[l; m]$. If we receive answer <<YES>>, after this query train for sure will be in segment $[l - k; m + k]$, otherwise in $[m - k; r + k]$. So, after each query length of segment is divided by $2$ and increased by $2k$. After segment length becomes irreducible ($4k$), let's ask about some random station in this segment. If we guessed right, let's finish the program, otherwise make the binary search again. To get the OK let's make one more observation: for all binary searches except the first one initial segment can be made $[l - k; r + k]$ instead of $[1; n]$.
[ "binary search", "interactive", "probabilities" ]
2,100
null
1039
C
Network Safety
The Metropolis computer network consists of $n$ servers, each has an encryption key in the range from $0$ to $2^k - 1$ assigned to it. Let $c_i$ be the encryption key assigned to the $i$-th server. Additionally, $m$ pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms specifics, a data communication channel can only be considered safe if the two servers it connects have \textbf{distinct} encryption keys. The initial assignment of encryption keys is guaranteed to keep all data communication channels safe. You have been informed that a new virus is actively spreading across the internet, and it is capable to change the encryption key of any server it infects. More specifically, the virus body contains some unknown number $x$ in the same aforementioned range, and when server $i$ is infected, its encryption key changes from $c_i$ to $c_i \oplus x$, where $\oplus$ denotes the bitwise XOR operation. Sadly, you know neither the number $x$ nor which servers of Metropolis are going to be infected by the dangerous virus, so you have decided to count the number of such situations in which all data communication channels remain safe. Formally speaking, you need to find the number of pairs $(A, x)$, where $A$ is some (possibly empty) subset of the set of servers and $x$ is some number in the range from $0$ to $2^k - 1$, such that when all servers from the chosen subset $A$ and none of the others are infected by a virus containing the number $x$, all data communication channels remain safe. Since this number can be quite big, you are asked to find its remainder modulo $10^9 + 7$.
Consider a virus containing a fixed number $x$. Let's investigate two servers connected by a data communication channel, denoting their encryption keys equal as $a$ and $b$ respectively. Since $a \neq b$, it follows that $a \oplus x \neq b \oplus x$. Therefore, if the servers are infected simultaneously the channel remains safe. The same can be said if neither of the servers is infected. When the virus infects exactly one of the two servers the channel between them can cease to be safe only when $x = (a \oplus b)$ (since $a \oplus x = b$, it follows that $x = x \oplus (a \oplus a) = (x \oplus a) \oplus a = (a \oplus x) \oplus a = b \oplus a = a \oplus b$). Define $a \oplus b$ as the value of the respective data channel (connecting servers with keys $a$ and $b$). From this it can be inferred that all servers connected by a path of channels with value $x$ can only be infected simultaneously. Thus the answer when the parameter $x$ is fixed is equal to $2^q$, where $q$ is the number of connected components in a graph where servers are considered vertices and data channels with value x are considered edges. This value can be computed in time linearly proportional to the number of edges with value x. When processing the values which are not found on any edge separately this gives us a solution in total time O(E).
[ "dfs and similar", "dsu", "graphs", "math", "sortings" ]
2,200
null
1039
D
You Are Given a Tree
A tree is an undirected graph with exactly one simple path between each pair of vertices. We call a set of simple paths $k$-valid if each vertex of the tree belongs to no more than one of these paths (including endpoints) and each path consists of exactly $k$ vertices. You are given a tree with $n$ vertices. For each $k$ from $1$ to $n$ inclusive find what is the maximum possible size of a $k$-valid set of simple paths.
Let's examine a solution in $O(n^2)$ first. Introudce a dynamic programming on subtree, the dp of the vertex is the number of paths, which can be taken from the subtree and the maximum length of incomplete path, which ends exactly in vertex v. Notice that this dp can be maximised as pair - the more of complete paths than better, and if the number of complete paths coincides, then it's better to have the incomplete path as long as possible. This dp allows to get an answer in $O(n)$ for a single $k$ How to calculate this dp for a vertex? We need to sum the number of complete paths over all children and also either take one of the incomplete path of children and attach the current vertex to it or try to form a new path from two longest incomplete paths of children. It is possible to use $O(n^2)$ solution to get $O(n \sqrt(n) log)$ solution. Notice, that $f(k) \le \frac{n}{k}$. From this we get, that $f$ takes no more than $O(\sqrt(n))$ values. Indeed, there are values $f(1), f(2), \ldots f(\sqrt(n))$ and for all $m \ge \sqrt{n} f(m) \le \sqrt{n}$. To find the corresponding bounds we can use binary search - this way we get solution in $O(n \sqrt(n) log)$. This is already enough to get Accepted on codeforces, however I want to share some more insights about faster, $O(n \log^2(n))$ solution, it wasn't required to get OK, mostly because we found out that writing this solution is really complicated and making it work faster then sqrt-log solution is even more harder. The funny thing is that we can do a dynamic programming for all $k$ from $1$ to $n$ simultaneously. In fact, we will use cartesian tree (more precisely, it is better to have segment tree for efficiency). We will return from subtree of vertex $v$ structure of size size[v], containing the dp values for all $k$ from $1$ to size[v], where $size$ - it the size of the subtree. So we need to be able to merge results from subtrees. In particular, from the subtree dp's of sizes $s_1, \ldots, s_t$ ($s_1 \ge s_2 \ge \ldots \ge s_t$) we want to get $\sum s_i$. Let's take the result corresponding to $s_1$ as a basis, new-borned end can be appended naively. Also, more or less naively we can make the merge of prefix part of length $s_2$ (because this work "is paid" by the fact that we will not return the dp structure of size $s_2$). So we have to deal with a part from $s_2$ to $s_1$. In the structure we store pairs of numbers - how much complete paths, and the length of the incomplete path. Note that there are two types of relaxation - when we increase the number of complete paths and when we simply relax the length of incomplete path. Notice, that $f(k) \le \frac{n}{k}$, and hence $\sum f(k) = O(n \log(n))$. This way the number of transitions of first type is small and we can perform them naively, we just need to find all such transitions fast. We can maintain in the above mentioned data structure maximums on the segments and fast pull all such transitions. Other transitions can be handled with max= on a suffix and +1 on the whole data structure, the latter we store together with the instance of data structures and handle them when we merge one data structure into the other. The overall complexity is $O(n \log^2)$.
[ "data structures", "dp", "trees" ]
2,800
null
1039
E
Summer Oenothera Exhibition
While some people enjoy spending their time solving programming contests, Dina prefers taking beautiful pictures. As soon as Byteland Botanical Garden announced Summer Oenothera Exhibition she decided to test her new camera there. The exhibition consists of $l = 10^{100}$ Oenothera species arranged in a row and consecutively numbered with integers from $0$ to $l - 1$. Camera lens allows to take a photo of $w$ species on it, i.e. Dina can take a photo containing flowers with indices from $x$ to $x + w - 1$ for some integer $x$ between $0$ and $l - w$. We will denote such photo with $[x, x + w - 1]$. She has taken $n$ photos, the $i$-th of which (in chronological order) is $[x_i, x_i + w - 1]$ in our notation. She decided to build a time-lapse video from these photos once she discovered that Oenothera blossoms open in the evening. Dina takes each photo and truncates it, leaving its segment containing exactly $k$ flowers, then she composes a video of these photos keeping their original order and voilà, a beautiful artwork has been created! A scene is a contiguous sequence of photos such that the set of flowers on them is the same. The change between two scenes is called a cut. For example, consider the first photo contains flowers $[1, 5]$, the second photo contains flowers $[3, 7]$ and the third photo contains flowers $[8, 12]$. If $k = 3$, then Dina can truncate the first and the second photo into $[3, 5]$, and the third photo into $[9, 11]$. First two photos form a scene, third photo also forms a scene and the transition between these two scenes which happens between the second and the third photos is a cut. If $k = 4$, then each of the transitions between photos has to be a cut. Dina wants the number of cuts to be as small as possible. Please help her! Calculate the minimum possible number of cuts for different values of $k$.
Let's reconsider this task in terms of segments: we need to split sequence of photos-segments into minimum number of contiguous groups such that there exists a subsegment in each group of length $k$, which contains inside of each segment of the group. It's easy to see that if we move right edge of each segment to the left by $k$, it's required to find a single point which is inside of each segments of the group. Let's consider $k$ as the length of each segment. Next, it's always good to include in next group maximum number of segments until they have a on-empty intersection. Therefore, we have solution in $O(n \cdot q)$ - let's iterate through all segments. If we can add current segment to last group, we add it, else - we create a new group with single current segment. Furthermore, to find next group, we can use segment tree to perform it in $O(\log n)$. Let's store minimum and maximum values of $x_i$, then we descend the tree to find first segment such that maximum left edge is on the right of minimum left edge. For each $i$ and $x \le n^{1/3}$ let's calculate minimum length of segments such that group that starts at element $i$ contains at least next $x$ segments. Let's sort all requests in increasing order. We will answer requests in exactly this order. Let's maintain $p_i$ - length of group for current $k$, starting at element $i$ (but $p_i \le n^{1/3}$). There are $n^{4/3}$ events of changing this value at most. Let's also maintain values $log_i$ - minimum number of groups (and last element of last group) required to jump to element $x \ge i + n^{1/3}$ or to jump to element $x$ such that $p_x \ge n^{1/3}$. It's easy to see that when $p_i$ changes, only area of radius $O(n^{1/3})$ is changed for $long$. Therefore $long$ may be recalculated in $O(n^{5/3} \cdot \log n)$ in total. Now we can simulate requests: we jump using $long_i$ to the right at least on $n^{1/3}$, therefore there will be $O(q \cdot n^{2/3})$ jumps in total. The solution became $O(n^{5/3} \cdot \log n + n^{5/3})$ for $n = q$. Let's speed up the solution to $O(n^{5/3})$. Let's change the meaning of $long_i$ - we allow the last group to be not maximal. Therefore we are now allowed not to recalculate where exactly last maximal group ends. During simulation we need to perform request on segment tree to understand where exactly last maximal group ends. Now let's do the following: after jump $long_i$ we iterate through next elements and try to add it to last non-maximal group. If we already added more than $n^{2/3}$, let's perform a request on tree in $\log n$. Therefore the solution performs in $O(n^{5/3} + n^{4/3} \cdot \log n)$.
[ "data structures" ]
3,400
null
1040
A
Palindrome Dance
A group of $n$ dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future. On the day when the suits were to be bought, the director was told that the participants of the olympiad will be happy if the colors of the suits on the scene will form a palindrome. A palindrome is a sequence that is the same when read from left to right and when read from right to left. The director liked the idea, and she wants to buy suits so that the color of the leftmost dancer's suit is the same as the color of the rightmost dancer's suit, the 2nd left is the same as 2nd right, and so on. The director knows how many burls it costs to buy a white suit, and how many burls to buy a black suit. You need to find out whether it is possible to buy suits to form a palindrome, and if it's possible, what's the minimal cost of doing so. Remember that dancers can not change positions, and due to bureaucratic reasons it is not allowed to buy new suits for the dancers who already have suits, even if it reduces the overall spending.
Consider a pair of dancers located symmetrically with respect to the center of the stage. If they already have different suits, the answer is definitely "impossible". If they both have same suits, they are fine. If one of them doesn't have a suit, buy him a matching one. Finally, if both don't have suits, buy them two same suits of the cheaper color. Also, if $n$ is odd and the central dancer doesn't have a suit, buy him a cheaper one.
[ "greedy" ]
1,000
null
1040
B
Shashlik Cooking
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over. This time Miroslav laid out $n$ skewers parallel to each other, and enumerated them with consecutive integers from $1$ to $n$ in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number $i$, it leads to turning $k$ closest skewers from each side of the skewer $i$, that is, skewers number $i - k$, $i - k + 1$, ..., $i - 1$, $i + 1$, ..., $i + k - 1$, $i + k$ (if they exist). For example, let $n = 6$ and $k = 1$. When Miroslav turns skewer number $3$, then skewers with numbers $2$, $3$, and $4$ will come up turned over. If after that he turns skewer number $1$, then skewers number $1$, $3$, and $4$ will be turned over, while skewer number $2$ will be in the initial position (because it is turned again). As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all $n$ skewers with the minimal possible number of actions. For example, for the above example $n = 6$ and $k = 1$, two turnings are sufficient: he can turn over skewers number $2$ and $5$. Help Miroslav turn over all $n$ skewers.
The funny thing about this problem that it is entirely based on real facts, in the real life the $k$ was equal to $1$ and one skewer really turned two more. So it is easy to see, that answer is at least $\lceil \frac{n}{2k + 1} \rceil$ (because in smaller number of operations we wouldn't simply able to touch all skewers), where the $\lceil a \rceil$ denotes rounding up. Set's build an answer with exactly this number of operations. We will make our answer in such way, that each skewer belongs exactly to one operation. That is, we need to put segments of length $2k + 1$ over the array, such that the ends are touching and that the first and last segments don't pop out of the array too much. Let's define $x = \lceil \frac{n}{2k + 1} \rceil (2k + 1) - n$, $a = min(n, k)$, $b = x - a$. Note that $0 \le a, b \le k$ and $a + b = x$. Let's make segments described above in such way, that the first segments outweighs over the array exactly by $a$ and the last one exactly by $b$. Since $a, b \le k$ it follows, that the centre of this segments stays inside the array. Some example: $n = 7$, $k = 2$, $x = 3$, $a = 2$, $b = 1$ The answer is then as in follows: [#|#|@|@|@] [@|@|@|@|#], where @ denotes skewer, and one block of square brackets corresponds to one operation.
[ "dp", "greedy", "math" ]
1,300
null
1041
A
Heist
There was an electronic store heist last night. All keyboards which were in the store yesterday were numbered in ascending order from some integer number $x$. For example, if $x = 4$ and there were $3$ keyboards in the store, then the devices had indices $4$, $5$ and $6$, and if $x = 10$ and there were $7$ of them then the keyboards had indices $10$, $11$, $12$, $13$, $14$, $15$ and $16$. After the heist, only $n$ keyboards remain, and they have indices $a_1, a_2, \dots, a_n$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $x$ nor the number of keyboards in the store before the heist.
Let $x$ - the minimal number from the given numbers and $y$ - the maximal. So we consider that $x$ and $y$ were minimal and maximal keyboard numbers before the heist. All given numbers are distinct, so the answer is $y - x + 1 - n$ (initial number of the keyboards is $(y - x + 1)$ minus the remaining number of keyboards $n$).
[ "greedy", "implementation", "sortings" ]
800
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; int mn = 1e9, mx = 0; for (int i = 1; i <= n; i++){ int x; cin >> x; mn = min(mn, x); mx = max(mx, x); } cout << max(0, (mx-mn)-n+1); }
1041
B
Buying a TV Set
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than $a$ and screen height not greater than $b$. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is $w$, and the height of the screen is $h$, then the following condition should be met: $\frac{w}{h} = \frac{x}{y}$. There are many different TV sets in the shop. Monocarp is sure that for any pair of \textbf{positive integers} $w$ and $h$ there is a TV set with screen width $w$ and height $h$ in the shop. Monocarp isn't ready to choose the exact TV set he is going to buy. Firstly he wants to determine the optimal screen resolution. He has decided to try all possible variants of screen size. But he must count the number of pairs of \textbf{positive integers} $w$ and $h$, beforehand, such that $(w \le a)$, $(h \le b)$ and $(\frac{w}{h} = \frac{x}{y})$. In other words, Monocarp wants to determine the number of TV sets having aspect ratio $\frac{x}{y}$, screen width not exceeding $a$, and screen height not exceeding $b$. Two TV sets are considered different if they have different screen width or different screen height.
Firstly let's make $x$ and $y$ coprime. To do so, we calculate $g = gcd(x, y)$ and then divide both numbers by $g$. Then the pair $(w, h)$ is included in the answer if the following conditions are met: $w \le a$, $h \le b$, and there exists some positive integer $k$ such that $w = kx$ and $h = ky$. Furthermore, each such pair is uniquely determined by this integer $k$. So we can reduce our task to counting the number of positive integers $k$ such that $kx \le a$ and $ky \le b$, and that is just $min(\lfloor \frac{a}{x} \rfloor, \lfloor \frac{b}{y} \rfloor)$.
[ "math" ]
1,000
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll a, b, c, d; cin >> a >> b >> c >> d; ll gc = __gcd(c, d); c /= gc; d /= gc; cout << min(a/c, b/d); }
1041
C
Coffee Break
Recently Monocarp got a job. His working day lasts exactly $m$ minutes. During work, Monocarp wants to drink coffee at certain moments: there are $n$ minutes $a_1, a_2, \dots, a_n$, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute $a_i$, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least $d$ minutes pass between any two coffee breaks. Monocarp also wants to take these $n$ coffee breaks in a minimum possible number of \textbf{working} days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than $d$ minutes pass between the end of any working day and the start of the following working day. For each of the $n$ given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent.
Let put in set the pairs in the following format: $a_i$ - the time for $i$-th break and the number of this break in the input data. So, we got pairs sorted by $a_i$. While set contains elements we will determine the breaks, which should be done in a single day. For the next day the first break should be dine in the time, which is at the beginning of the set (let this time is $x$). So, next break should be done after at least $d$ minutes. We should find a pair in the set, where the first element not less than $x + d + 1$. It can be done with $lower\_bound$. In the same way, we can find the next breaks in this day. With help of the second elements of pairs, we can easily remember the answer days for breaks. Also, we should erase from set all considered pairs. If for some pair we cannot find the needed element, we should go to the next day.
[ "binary search", "data structures", "greedy", "two pointers" ]
1,600
#include <bits/stdc++.h> using namespace std; const int N = 200100; set<pair<int, int> > q; int ans[N], n, a[N], m, k; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m >> k; for (int i = 1; i <= n; i++){ cin >> a[i]; q.insert({a[i], i}); } int cnt = 0; while(!q.empty()){ ++cnt; int pos = q.begin()->second; ans[pos] = cnt; q.erase(q.begin()); while(true){ auto it = q.lower_bound({a[pos]+1+k, 0}); if (it == q.end()) break; pos = it->second; q.erase(it); ans[pos] = cnt; } } cout << cnt << "\n"; for (int i = 1; i <= n; i++) cout << ans[i] << ' '; }
1041
D
Glider
A plane is flying at a constant height of $h$ meters above the ground surface. Let's consider that it is flying from the point $(-10^9, h)$ to the point $(10^9, h)$ parallel with $Ox$ axis. A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to $Ox$ axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second. There are ascending air flows on certain segments, each such segment is characterized by two numbers $x_1$ and $x_2$ ($x_1 < x_2$) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along $Ox$ axis, covering one unit of distance every second. \begin{center} {\small If the glider jumps out at $1$, he will stop at $10$. Otherwise, if he jumps out at $2$, he will stop at $12$.} \end{center} Determine the maximum distance along $Ox$ axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is $0$.
At first, let's prove that it is always optimal to jump out at the beginning of any ascending air flows: if his point of jump is out of any air flow, he can move his point to $+1$ - answer will not decrease, in the same way, if his point of jump in some air flow but not in its beginning, he can move his point to $-1$. Next observation: height of glider is non-ascending function for the fixed point of jump, so we can for each optimal point of jump use binary search of the answer. Let glider jump out at position $x$ and we need to calculate its height at some position $y \ge x$, then height is equal to $h - (y - x) + sum(x,y)$, where $sum(x,y)$ is a total length of all flows of segment $[x, y]$ and can be calculated using prefix sums (yes, and $lower\_bound$). Result complexity - $O(n \log(10^9) \log(n))$ of time and $O(n)$ of memory. Of course, you can note that this task can be solved with two pointers technique, what is faster, but it is not necessary since built in $lower\_bound$ function is fast enough (unlike some $set$ or segment tree, which should be written optimally). On the other hand, java-users need to do some extra work by writing its own $lower\_bound$ function for $int[]$ since $binary\_search(List<>)$ will cause a slowdown.
[ "binary search", "data structures", "two pointers" ]
1,700
#include<bits/stdc++.h> using namespace std; #define fore(i, l, r) for(int i = int(l); i < int(r); i++) #define x first #define y second typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); const ld EPS = 1e-9; const int N = 200 * 1000 + 555; int n, h; pt a[N]; inline bool read() { if(!(cin >> n >> h)) return false; fore(i, 0, n) assert(scanf("%d%d", &a[i].x, &a[i].y) == 2); sort(a, a + n); return true; } int ps[N]; int getH(int lf, int rg) { int l = int(lower_bound(a, a + n, pt(lf, -1)) - a); int r = int(lower_bound(a, a + n, pt(rg, -1)) - a); int sum = ps[r] - ps[l]; if(l > 0) sum += max(0, a[l - 1].y - lf); assert(rg - lf - sum >= 0); return rg - lf - sum; } inline void solve() { ps[0] = 0; fore(i, 0, n) ps[i + 1] = ps[i] + (a[i].y - a[i].x); int ans = 0; fore(i, 0, n) { int lx = a[i].y + 1; int lf = -(h + 1), rg = lx; while(rg - lf > 1) { int mid = (lf + rg) / 2; if(getH(mid, lx) > h) lf = mid; else rg = mid; } assert(getH(rg, lx) == h); ans = max(ans, lx - rg); } cout << ans << endl; } int main() { if(read()) { solve(); } return 0; }
1041
E
Tree Reconstruction
Monocarp has drawn a tree (an undirected connected acyclic graph) and then has given each vertex an index. All indices are distinct numbers from $1$ to $n$. For every edge $e$ of this tree, Monocarp has written two numbers: the maximum indices of the vertices of the two components formed if the edge $e$ (and only this edge) is erased from the tree. Monocarp has given you a list of $n - 1$ pairs of numbers. He wants you to provide an example of a tree that will produce the said list if this tree exists. If such tree does not exist, say so.
First of all, if there exists some $b_i < n$, then the answer is clearly NO. Then let's consider that every $b_i = n$ and analyze only the values of $a_i$ (and furthermore, let's sort all values of $a_i$ beforehand). Suppose that we have constructed a tree satisfying all the requirements and rooted it at vertex $n$. Then for any $k$ such that $1 \le k \le n - 1$ there exist no more than $k$ subtrees containing only vertices with indices not exceeding $k$ (because there are no more than $k$ vertices that can be the roots of such subtrees). So, if for some constant $k$ the number of $a_i \le k$ is greater than $k$, then the answer is NO since it would imply that there are more than $k$ subtrees containing only values not greater then $k$. Now we consider only the case such that for every $k \in [1, n - 1]$ the number of $i$ such that $a_i \le k$ is not greater than $k$. In this case the answer is YES; let's prove it with an algorithm that constructs a tree meeting the constraints. Actually, we can always build a bamboo (a tree where no vertex has degree greater than $2$, or simply a path) according to these constraints. Let's put vertex $n$ at one of the ends of the bamboo and start building a bamboo from the other end. It's obvious that if we make some vertex $x$ a leaf, then the array $a$ will contain only values not less than $x$. So, if we consider values of $a_i$ to be sorted, then the leaf has index $a_1$. Then let's repeat the following process for every $i \in [2, n - 1]$: if $a_i > a_{i - 1}$, then let's use the vertex with index $a_i$ as the parent of the previous vertex; otherwise, let's find any index $j$ such that $j < a_i$ and index $j$ is not used yet, and use vertex with index $j$ as the parent of the previous vertex (there will be at least one such vertex since for every $k \in [1, n - 1]$ the number of $i$ such that $a_i \le k$ is not greater than $k$). It's easy to prove that the bamboo we construct in such a way meets the constraints given in the statement.
[ "constructive algorithms", "data structures", "graphs", "greedy" ]
1,900
#include<bits/stdc++.h> using namespace std; const int N = 200043; int cnt[N]; int main() { int n; scanf("%d", &n); for(int i = 0; i < n - 1; i++) { int x, y; scanf("%d %d", &x, &y); if(y != n) { puts("NO"); return 0; } cnt[x]++; } int cur = 0; for(int i = 1; i < n; i++) { cur += cnt[i]; if(cur > i) { puts("NO"); return 0; } } int last = -1; puts("YES"); set<int> unused; for(int i = 1; i < n; i++) unused.insert(i); for(int i = 1; i < n; i++) { if(cnt[i] > 0) { unused.erase(i); if(last != -1) printf("%d %d\n", last, i); last = i; cnt[i]--; } while(cnt[i] > 0) { printf("%d %d\n", last, *unused.begin()); last = *unused.begin(); cnt[i]--; unused.erase(unused.begin()); } } printf("%d %d\n", last, n); }
1041
F
Ray in the tube
You are given a tube which is reflective inside represented as two non-coinciding, but parallel to $Ox$ lines. Each line has some special integer points — positions of sensors on sides of the tube. You are going to emit a laser ray in the tube. To do so, you have to choose \textbf{two} integer points $A$ and $B$ on the first and the second line respectively (coordinates can be negative): the point $A$ is responsible for the position of the laser, and the point $B$ — for the direction of the laser ray. The laser ray is a ray starting at $A$ and directed at $B$ which will reflect from the sides of the tube (it doesn't matter if there are any sensors at a reflection point or not). A sensor will only register the ray if the ray hits exactly at the position of the sensor. \begin{center} {\small Examples of laser rays. Note that image contains two examples. The $3$ sensors (denoted by black bold points on the tube sides) will register the blue ray but only $2$ will register the red.} \end{center} Calculate the maximum number of sensors which can register your ray if you choose points $A$ and $B$ on the first and the second lines respectively.
At first, $y$ coordinates don't matter. Let $dx$ be signed difference between $x$ coordinates of $B$ and $A$, then on the first line all points with coordinates $x_A + dx \cdot (2k)$ will be chosen, and on the second line all points with coordinates $x_A + dx \cdot (2k + 1)$ will be chosen. Let's prove that it is always optimal to take $dx = 2^l$ where $l \ge 0$. Let $dx$ is not a power of two, then $dx = m \cdot 2^l$, where $m$ is odd. Note that $dx / m$ hits all points which is hitted by $dx$ that why answer will not decrease. So, we need to check only $dx = 2^l$, number of such $dx$ is equal to $O(\log(10^9))$. For the fixed $dx$ note that ray hits both points on the same line iff $x_1 \equiv x_2 \mod{(2 \cdot dx)}$. Analogically, the ray hits both points on the different lines iff $x_1 + dx \equiv x_2 \mod{(2 \cdot dx)}$. That's why we can split all point on the equivalent classes modulo $2 \cdot dx$ and take the size of the biggest class. We can do it by sort and two pointers or by $map$. Result complexity is $O(n \log{(10^9)} \log n)$ time and $O(n)$ memory.
[ "data structures", "divide and conquer", "dp", "math" ]
2,500
#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() typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); const ld EPS = 1e-9; const int N = 100 * 1000 + 555; int n[2], y[2]; int x[2][N]; inline bool read() { fore(k, 0, 2) { if(!(cin >> n[k] >> y[k])) return false; fore(i, 0, n[k]) assert(scanf("%d", &x[k][i]) == 1); } return true; } inline void solve() { int ans = 2; for(int dx = 1; dx < int(1e9); dx *= 2) { int mod = 2 * dx; map<int, int> cnt; int add[2] = {0, dx}; fore(k, 0, 2) { fore(i, 0, n[k]) cnt[(x[k][i] + add[k]) & (mod - 1)]++; } for(auto curAns : cnt) ans = max(ans, curAns.second); } cout << ans << endl; } int main() { if(read()) { solve(); } return 0; }
1042
A
Benches
There are $n$ benches in the Berland Central park. It is known that $a_i$ people are currently sitting on the $i$-th bench. Another $m$ people are coming to the park and each of them is going to have a seat on some bench out of $n$ available. Let $k$ be the maximum number of people sitting on one bench after additional $m$ people came to the park. Calculate the minimum possible $k$ and the maximum possible $k$. Nobody leaves the taken seat during the whole process.
The maximum value of $k$ should be determined in the following way: let's find the maximum number of people already sitting on the same bench (i. e. the maximum value in the array $a$). Let this number be $t$. Then if all additional $m$ people will seat on this bench, we will get the maximum value of $k$, so the answer is $t + m$. To determine the minimum value of $k$ let's perform $m$ operations. During each operation we put a new person on the bench currently having minimum number of people occupying it. The answer is the maximum number of people on the bench after we perform this operation for each of $m$ newcomers.
[ "binary search", "implementation" ]
1,100
#include <set> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <cassert> using namespace std; const int N = 100 + 13; int n, m; int a[N]; int main() { cin >> n >> m; for (int i = 0; i < n; i++) { cin >> a[i]; } int ans2 = *max_element(a, a + n) + m; for (int it = 0; it < m; it++) { int pos = -1; for (int i = 0; i < n; i++) { if (pos == -1 || a[i] < a[pos]) { pos = i; } } assert(pos != -1); a[pos]++; } int ans1 = *max_element(a, a + n); cout << ans1 << ' ' << ans2 << endl; }
1042
B
Vitamins
Berland shop sells $n$ kinds of juices. Each juice has its price $c_i$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it. Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.
Let's calculate the minimum cost of the juice containing only the vitamin "A", only the vitamin "B" and only the vitamin "C". Also let's calculate the minimum cost of the juice containing all three vitamins. If there is at least one juice containing only the vitamin "A", at least one juice containing only the vitamin "B" and at least one juice containing only the vitamin "C", let's update the answer with the sum of the corresponding minimum costs. If there is at least one juice containing all three vitamins, let's update the answer with its cost. Only one case remains - when Petya has to buy two juices. Let's iterate over all pairs of juices using nested loops. Let the index of the first juice we iterate be $a$, the index of the second juice be $b$. We have to check that the strings $s_a$ and $s_b$ contain all three letters "A", "B", "C" (i.e. these juices contain all the vitamins). If they do, let's update the answer with the value $c_a + c_b$.
[ "bitmasks", "brute force", "dp", "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; const int INF = 1e9; int n; map<string, int> was; inline void read() { cin >> n; for (int i = 0; i < n; i++) { int c; string s; cin >> c >> s; sort(s.begin(), s.end()); if (was.count(s) == 0) { was[s] = c; } else { was[s] = min(was[s], c); } } } inline int getC(string a, string b) { if (!was.count(a) || !was.count(b)) { return INF; } return was[a] + was[b]; } inline void solve() { int ans = INF; if (was.count("A") && was.count("B") && was.count("C")) { ans = was["A"] + was["B"] + was["C"]; } if (was.count("ABC")) { ans = min(ans, was["ABC"]); } ans = min(ans, getC("AB", "C")); ans = min(ans, getC("A", "BC")); ans = min(ans, getC("AC", "B")); ans = min(ans, getC("AB", "BC")); ans = min(ans, getC("AC", "BC")); ans = min(ans, getC("AC", "AB")); if (ans == INF) { ans = -1; } cout << ans << endl; } int main () { read(); solve(); }
1042
C
Array Product
You are given an array $a$ consisting of $n$ integers. You can perform the following operations with it: - Choose some positions $i$ and $j$ ($1 \le i, j \le n, i \ne j$), write the value of $a_i \cdot a_j$ into the $j$-th cell and \textbf{remove the number} from the $i$-th cell; - Choose some position $i$ and \textbf{remove the number} from the $i$-th cell (this operation can be performed \textbf{no more than once and at any point of time, not necessarily in the beginning}). The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations. Your task is to perform exactly $n - 1$ operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print \textbf{any} sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.
There are several cases in the problem. Let the number of zeroes in the array be $cntZero$ and the number of negative elements be $cntNeg$. Also let $maxNeg$ be the position of the maximum negative element in the array, or $-1$ if there are no negative elements in the array. Let the answer part be the product of all the numbers which will be in the answer and the removed part be the product of all the numbers which will be removed by the second type operation. The first case is the following: $cntZero = 0$ and $cntNeg = 0$. Then the answer part is the product of all the numbers in the array. The removed part is empty. The second case is the following: $cntNeg$ is odd. Then the answer part is the product of all the numbers in the array except all zeroes and $a_{maxNeg}$. The removed part is the product of all zeroes and $a_{maxNeg}$. And the third case is the following: $cntNeg$ is even. Then the answer part is the product of all the numbers in the array except all zeroes. The removed part is the product of all zeroes in the array (be careful in case $cntNeg = 0$ and $cntZero = n$). Be careful with printing the answer because my first solution printed $n$ operations instead of $n-1$ operations in case $cntZero = n$ or $cntZero = n-1$ and $cntNeg = 1$. And the funniest part of this problem is the checker. The first thing I thought was "Well, I want to write a fair checker on this problem". I did exactly that. What do we need? Split all the numbers in the array into two parts? Okay, let's write DSU to do that. What's next? Multiply $2 \cdot 10^5$ numbers from $1$ to $10^9$? Okay, let's use FFT and Divide and Conquer! And the last part is the comparing two numbers of length about $2 \cdot 10^6$. So writing this checker was pretty easy problem. But the coordinator didn't like that and I replaced it with very easy checker which uses some ideas from the solution. :(
[ "constructive algorithms", "greedy", "math" ]
1,700
#include <bits/stdc++.h> using namespace std; int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif int n; scanf("%d", &n); vector<int> a(n); for (int i = 0; i < n; ++i) scanf("%d", &a[i]); int cntneg = 0; int cntzero = 0; vector<int> used(n); int pos = -1; for (int i = 0; i < n; ++i) { if (a[i] == 0) { used[i] = 1; ++cntzero; } if (a[i] < 0) { ++cntneg; if (pos == -1 || abs(a[pos]) > abs(a[i])) pos = i; } } if (cntneg & 1) used[pos] = 1; if (cntzero == n || (cntzero == n - 1 && cntneg == 1)) { for (int i = 0; i < n - 1; ++i) printf("1 %d %d\n", i + 1, i + 2); return 0; } int lst = -1; for (int i = 0; i < n; ++i) { if (used[i]) { if (lst != -1) printf("1 %d %d\n", lst + 1, i + 1); lst = i; } } if (lst != -1) printf("2 %d\n", lst + 1); lst = -1; for (int i = 0; i < n; ++i) { if (!used[i]) { if (lst != -1) printf("1 %d %d\n", lst + 1, i + 1); lst = i; } } return 0; }
1042
D
Petya and Array
Petya has an array $a$ consisting of $n$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array. Now he wonders what is the number of segments in his array with the sum less than $t$. Help Petya to calculate this number. More formally, you are required to calculate the number of pairs $l, r$ ($l \le r$) such that $a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$.
Let's reformulate the problem. Now the problem is to calculate the difference between the prefix sums to the right border and to the left border instead of the sum on the segment. Let $pref[i] = \sum\limits_{j=1}^{i} a[j]$, a $pref[0] = 0$. Then the answer to the problem is $\sum\limits_{L=1}^{n}\sum\limits_{R=L}^{n} pref[R] - pref[L - 1] < t$. It's easy to see that the answer for the fixed $L$ is $\sum\limits_{R=L}^{n} pref[R] < t + pref[L - 1]$. We can calculate this formula using some data structure which allows us to get the number of elements less than given and set the value at some position. For example, segment tree or BIT (Fenwick tree).
[ "data structures", "divide and conquer", "two pointers" ]
1,800
#include <bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) using namespace std; const int N = 200 * 1000 + 13; int n; long long T; int a[N]; int f[N]; void upd(int x){ for (int i = x; i < N; i |= i + 1) ++f[i]; } int get(int x){ int res = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1) res += f[i]; return res; } int main() { scanf("%d%lld", &n, &T); forn(i, n) scanf("%d", &a[i]); vector<long long> sums(1, 0ll); long long pr = 0; forn(i, n){ pr += a[i]; sums.push_back(pr); } sort(sums.begin(), sums.end()); sums.resize(unique(sums.begin(), sums.end()) - sums.begin()); long long ans = 0; pr = 0; upd(lower_bound(sums.begin(), sums.end(), 0ll) - sums.begin()); forn(i, n){ pr += a[i]; int npos = upper_bound(sums.begin(), sums.end(), pr - T) - sums.begin(); ans += (i + 1 - get(npos - 1)); int k = lower_bound(sums.begin(), sums.end(), pr) - sums.begin(); upd(k); } printf("%lld\n", ans); return 0; }
1042
E
Vasya and Magic Matrix
Vasya has got a magic matrix $a$ of size $n \times m$. The rows of the matrix are numbered from $1$ to $n$ from top to bottom, the columns are numbered from $1$ to $m$ from left to right. Let $a_{ij}$ be the element in the intersection of the $i$-th row and the $j$-th column. Vasya has also got a chip. Initially, the chip is in the intersection of the $r$-th row and the $c$-th column (that is, in the element $a_{rc}$). Vasya performs the following process as long as possible: among all elements of the matrix having their value less than the value of the element with the chip in it, Vasya randomly and equiprobably chooses one element and moves his chip to this element. After moving the chip, he adds to his score the square of the Euclidean distance between these elements (that is, between the element in which the chip is now and the element the chip was moved from). The process ends when there are no elements having their values less than the value of the element with the chip in it. Euclidean distance between matrix elements with coordinates $(i_1, j_1)$ and $(i_2, j_2)$ is equal to $\sqrt{(i_1-i_2)^2 + (j_1-j_2)^2}$. Calculate the expected value of the Vasya's final score. It can be shown that the answer can be represented as $\frac{P}{Q}$, where $P$ and $Q$ are coprime integer numbers, and $Q \not\equiv 0~(mod ~ 998244353)$. Print the value $P \cdot Q^{-1}$ modulo $998244353$.
Let's iterate over all the elements of the matrix in order of increasing their values and calculate the expected value for these elements to solve the problem. Suppose that now we consider the element at intersection of the $R$-th row and the $C$-th column. Let the elements having value less than the value of the current element be $(r_1, c_1), (r_2, c_2), \dots , (r_k, c_k)$, where $r_i$ is the row of the $i$-th element and $c_i$ is the column of the $i$-th element. Then the expected value for the current element can be calculated as follows: $\frac{\sum\limits_{i=1}^{k}{(ev_i + (R - r_i)^2 + (C - c_i)^2)}}{k}$, where $ev_i$ is the expected value of the $i$-th element. We can rewrite the formula to the following form using equivalent transforms: $\frac{\sum\limits_{i=1}^{k}{ ev_i }}{k} + R^2 + C^2 + \frac{\sum\limits_{i=1}^{k}{ {r_i}^2 }}{k} + \frac{\sum\limits_{i=1}^{k}{ {c_i}^2 }}{k} - 2\frac{\sum\limits_{i=1}^{k}{ Rr_i }}{k} -2\frac{\sum\limits_{i=1}^{k}{ Cc_i }}{k}$. So we need to maintain five sums for the elements having value less than current element: sum of their values, sum of their row indices, sum of their column indices, sum of squares of their row indices and sum of squares of their column indices. We can maintain all these sums if we will iterate over all the elements continuously in order of increasing their values. It is also necessary to note that we need to process all the elements having equal values at once and recalculate all the sums right after calculating the expected values for these elements.
[ "dp", "math", "probabilities" ]
2,300
#include<bits/stdc++.h> using namespace std; const int MOD = 998244353; const int N = 1009; int mul(int a, int b){ return int(a * 1LL * b % MOD); } void upd(int &a, int b){ a += b; while(a >= MOD) a -= MOD; while(a < 0) a += MOD; } int bp(int a, int n){ int res = 1; for(; n > 0; n >>= 1){ if(n & 1) res = mul(res, a); a = mul(a, a); } return res; } int inv(int a){ int ia = bp(a, MOD - 2); assert(mul(a, ia) == 1); return ia; } int n, m; int a[N][N]; int dp[N][N]; int si, sj; int main() { //freopen("input.txt", "r", stdin); scanf("%d %d", &n, &m); for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j) scanf("%d", &a[i][j]); scanf("%d %d", &si, &sj); --si, --sj; vector <pair<int, pair<int, int> > > v; for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j) v.push_back(make_pair(a[i][j], make_pair(i, j))); sort(v.begin(), v.end()); int l = 0; int sumDP = 0, sumX = 0, sumY = 0, sumX2 = 0, sumY2 = 0; while(l < int(v.size())){ int r = l; while(r < int(v.size()) && v[r].first == v[l].first) ++r; int il = -1; if(l != 0) il = inv(l); for(int i = l; i < r; ++i){ int x = v[i].second.first, y = v[i].second.second; if(il == -1){ dp[x][y] = 0; continue; } upd(dp[x][y], mul(sumDP, il)); upd(dp[x][y], mul(x, x)); upd(dp[x][y], mul(y, y)); upd(dp[x][y], mul(sumX2, il)); upd(dp[x][y], mul(sumY2, il)); upd(dp[x][y], mul(mul(-x - x, sumX), il)); upd(dp[x][y], mul(mul(-y - y, sumY), il)); } for(int i = l; i < r; ++i){ int x = v[i].second.first, y = v[i].second.second; upd(sumDP, dp[x][y]); upd(sumX2, mul(x, x)); upd(sumY2, mul(y, y)); upd(sumX, x); upd(sumY, y); } l = r; } printf("%d\n", dp[si][sj]); return 0; }
1042
F
Leaf Sets
You are given an undirected tree, consisting of $n$ vertices. The vertex is called a leaf if it has exactly one vertex adjacent to it. The distance between some pair of vertices is the number of edges in the shortest path between them. Let's call some set of leaves beautiful if the maximum distance between any pair of leaves in it is less or equal to $k$. You want to split \textbf{all} leaves into \textbf{non-intersecting} beautiful sets. What is the minimal number of sets in such a split?
Let's use the following technique, which is pretty common for tree problems. Let the root of the tree be some none-leaf vertex. Run dfs from the root and let the vertex yield all the resulting sets in the optimal answer for its subtree. For each vertex you iterate over its children and merge the yielded sets. The first thing to notice is that you only need the deepest vertex from each set to check its mergeability. Let's call the distance between the vertex $v$ and the deepest vertex in some set $u$ in its subtree $d_u$. Now two sets $a$ and $b$ can be merged only if $d_a + d_b \le k$. Moreover, $d$ value of the resulting the set is $max(d_a, d_b)$. The time has come to reveal the merging process. We will heavily rely on a fact that the resulting $d$ doesn't change after merging. Let's merge the sets with the smallest $d$ to any other possible sets. Now we can deduce the small-to-large solution from it. Let the vertex yield the whole multiset of the depths of the resulting sets. Now take the child with the largest number of resulting sets and add all the values from the other children to its multiset. Then merge the maximum possible number of sets and yield the result. The size of set yielded by the root is the answer. The complexity of this solution is $O(n \cdot log^2{n})$, which still can be too slow. You can notice that if you have a pair of sets $a$ and $b$ such that $d_a \le d_b, d_a + d_b > k$, set $b$ will never affect the answer. If some set $c$ could later be merged with $b$, it can be with $a$ as well. Thus, you can erase set $b$ from the result and add $1$ to the answer. Then the vertex will always yield a single set. The solution mentioned above works in $O(n \log n)$ with this modification. This can later be modified a bit to a $O(n)$ solution but that is totally unnecessary and works about the same time as $O(n \log n)$. It still takes most of the time to read the input.
[ "data structures", "dfs and similar", "dsu", "graphs", "greedy", "sortings", "trees" ]
2,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()) const int N = 1000 * 1000 + 13; int n, k; vector<int> g[N]; int ans; int dfs(int v, int p = -1){ if (g[v].size() == 1) return 0; vector<int> cur; for (auto u : g[v]){ if (u == p) continue; cur.push_back(dfs(u, v) + 1); } int pos = -1; forn(i, sz(cur)) { if (cur[i] * 2 <= k && (pos == -1 || cur[pos] < cur[i])) pos = i; } if (pos == -1) { ans += sz(cur) - 1; return *min_element(cur.begin(), cur.end()); } int res = -1; forn(i, sz(cur)) { if (cur[pos] >= cur[i]) continue; if (cur[i] + cur[pos] <= k && (res == -1 || cur[i] < cur[res])) res = i; } forn(i, sz(cur)) ans += (cur[i] > cur[pos]); if (res != -1) --ans; return (res == -1 ? cur[pos] : cur[res]); } int main(){ scanf("%d%d", &n, &k); forn(i, n - 1) { int v, u; scanf("%d%d", &v, &u); --v, --u; g[v].push_back(u); g[u].push_back(v); } forn(i, n) { if (sz(g[i]) > 1) { dfs(i); break; } } printf("%d\n", ans + 1); return 0; }
1043
A
Elections
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are $n$ students in the school. Each student has exactly $k$ votes and is obligated to use all of them. So Awruk knows that if a person gives $a_i$ votes for Elodreip, than he will get exactly $k - a_i$ votes from this person. Of course $0 \le k - a_i$ holds. Awruk knows that if he loses his life is over. He has been speaking a lot with his friends and now he knows $a_1, a_2, \dots, a_n$ — how many votes for Elodreip each student wants to give. Now he wants to change the number $k$ to win the elections. Of course he knows that bigger $k$ means bigger chance that somebody may notice that he has changed something and then he will be disqualified. So, Awruk knows $a_1, a_2, \dots, a_n$ — how many votes each student will give to his opponent. Help him select the smallest winning number $k$. In order to win, Awruk needs to get strictly more votes than Elodreip.
We can observe that result cannot exceed $201$ - Awruk gets at least $101$ votes from one person and Elodreip cannot get more than $100$ votes from one person. So we can iterate over every possible integer from $1$ to $201$ and check if Awruk wins with $k$ set to this integer. We have to remember that $k$ - $a_{i}$ is always at least $0$, so we have to check this condition too. Complexity $O(n * M)$, where $M$ denotes maximum possible value of $a_{i}$. Try to solve it in $O(n)$.
[ "implementation", "math" ]
800
#include <bits/stdc++.h> using namespace std; int n; int mx = 0, sum = 0; int main(){ scanf("%d", &n); for(int i = 1; i <= n; ++i){ int a; scanf("%d", &a); mx = max(mx, a); sum += a; } sum *= 2; sum += n; sum /= n; printf("%d", max(sum, mx)); return 0; }
1043
B
Lost Array
Bajtek, known for his unusual gifts, recently got an integer array $x_0, x_1, \ldots, x_{k-1}$. Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array $a$ of length $n + 1$. As a formal description of $a$ says, $a_0 = 0$ and for all other $i$ ($1 \le i \le n$) $a_i = x_{(i-1)\bmod k} + a_{i-1}$, where $p \bmod q$ denotes the remainder of division $p$ by $q$. For example, if the $x = [1, 2, 3]$ and $n = 5$, then: - $a_0 = 0$, - $a_1 = x_{0\bmod 3}+a_0=x_0+0=1$, - $a_2 = x_{1\bmod 3}+a_1=x_1+1=3$, - $a_3 = x_{2\bmod 3}+a_2=x_2+3=6$, - $a_4 = x_{3\bmod 3}+a_3=x_0+6=7$, - $a_5 = x_{4\bmod 3}+a_4=x_1+7=9$. So, if the $x = [1, 2, 3]$ and $n = 5$, then $a = [0, 1, 3, 6, 7, 9]$. Now the boy hopes that he will be able to restore $x$ from $a$! Knowing that $1 \le k \le n$, help him and find all possible values of $k$ — possible lengths of the lost array.
First, let's observe that we can replace array $a_{i}$ with array $b_{i}$ = $a_{i}$ $-$ $a_{i - 1}$, because all we care about are differences between neighboring elements. Now, we can see that our lost array can have length $d$ if and only if for every $j$ such that $j$ $+$ $d$ $ \le $ $n$, $b_{j}$ $=$ $b_{j + d}$. So we can iterate over every possible $d$ from $1$ to $n$ and check if it is correct in $O(n)$. Complexity of whole algorithm is $O(n^{2})$.
[ "implementation" ]
1,200
#include <bits/stdc++.h> using namespace std; const int N = 1007; int n; int in[N]; bool ok(int d){ for(int i = 0; i + d < n; ++i) if(in[i + 1] - in[i] != in[i + d + 1] - in[i + d]) return false; return true; } int main(){ scanf("%d", &n); for(int i = 1; i <= n; ++i) scanf("%d", &in[i]); vector <int> res; for(int i = 1; i <= n; ++i) if(ok(i)) res.push_back(i); printf("%d\n", res.size()); for(int v: res) printf("%d ", v); return 0; }
1043
C
Smallest Word
IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting. Today, when IA looked at the fridge, she noticed that the word formed by magnets is really messy. "It would look much better when I'll swap some of them!" — thought the girl — "but how to do it?". After a while, she got an idea. IA will look at all prefixes with lengths from $1$ to the length of the word and for each prefix she will either reverse this prefix or leave it as it is. She will consider the prefixes in the fixed order: from the shortest to the largest. She wants to get the lexicographically smallest possible word after she considers all prefixes. Can you help her, telling which prefixes should be chosen for reversing? 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$.
Basically in problem we are given a word in which for every $i$ we can reverse prefix of first $i$ elements and we want to get the smallest lexicographically word. We will show that we can always achieve word in form $a^{j}b^{n - j}$. Let's say that we solved our problem for prefix of length $i$ and for this prefix we have word $a^{j}b^{i - j}$ (at the beginning it's just empty word). If our next letter is $b$ then we do nothing, because we will get word $a^{j}b^{i - j + 1}$ which is still the smallest lexicographically word. Otherwise we want to reverse prefix of length $i$, add letter $a$ and reverse prefix of length $i$ $+$ $1$, so we get a word $a^{j + 1}b^{i - j}$, which is still fine for us. There is still a problem - what if we have already reversed prefix $i$ and we just said that we will reverse it second time. But instead of reversing it second time, we can deny it's first reverse. Final complexity is $O(n)$.
[ "constructive algorithms", "greedy", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 1007; string s; bool write[N]; int main(){ cin >> s; for(int i = 1; i < s.size(); ++i) if(s[i] == 'a'){ write[i - 1] ^= 1; write[i] = 1; } for(int i = 0; i < s.size(); ++i) printf("%d%c", write[i], i + 1 == (int)s.size() ? '\n' : ' '); return 0; }
1043
D
Mysterious Crime
Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked $m$ neighbours of Ada about clients who have visited her in that unlucky day. Let's number the clients from $1$ to $n$. Each neighbour's testimony is a permutation of these numbers, which describes the order in which clients have been seen by the asked neighbour. However, some facts are very suspicious – how it is that, according to some of given permutations, some client has been seen in the morning, while in others he has been seen in the evening? "In the morning some of neighbours must have been sleeping!" — thinks Gawry — "and in the evening there's been too dark to see somebody's face...". Now he wants to delete some prefix and some suffix (both prefix and suffix can be empty) in each permutation, so that they'll be non-empty and equal to each other after that — some of the potential criminals may disappear, but the testimony won't stand in contradiction to each other. In how many ways he can do it? Two ways are called different if the remaining common part is different.
Deleting prefix and suffix is nothing more than taking a subarray. If subarray is common for all permutations then it has to appear in first permutation. We renumber all permutations such that first permutation is $1$, $2$, ..., $n$ $-$ $1$, $n$. Now for every $i$ in every permutation we count how long is subarray starting at $i$ which looks like $i$, $i$ $+$ $1$, ..., $i$ $+$ $k$. It can be easily done in $O(n)$ for one permutation with two pointers technique. Now for every element $i$ we compute $reach[i]$ equal the longest subarray starting in $i$ which looks like $i$, $i$ $+$ $1$, ..., $i$ $+$ $k$ and it apears in all subarrays. It is just minimum over previously calculated values for all permutations. Now we can see that our result is $\sum_{i=1}^{n}r e a c h[i]-i$. Final complexity $O(nm)$.
[ "brute force", "combinatorics", "math", "meet-in-the-middle", "two pointers" ]
1,700
#include <bits/stdc++.h> using namespace std; typedef long long int LL; const int N = 1e5 + 7; int n, m; int mn[N]; int ren[N]; int perm[15][N]; int main(){ scanf("%d %d", &n, &m); for(int i = 1; i <= m; ++i) for(int j = 1; j <= n; ++j) scanf("%d", &perm[i][j]); for(int i = 1; i <= n; ++i) ren[perm[1][i]] = i; for(int i = 1; i <= m; ++i) for(int j = 1; j <= n; ++j) perm[i][j] = ren[perm[i][j]]; for(int i = 1; i <= n; ++i) mn[i] = n; for(int i = 1; i <= m; ++i){ int cur = 1; for(int j = 1; j <= n; ++j){ if(cur < j) ++cur; while(cur < n && perm[i][cur + 1] == perm[i][cur] + 1) ++cur; mn[perm[i][j]] = min(mn[perm[i][j]], perm[i][cur]); } } LL res = 0; int now = 1; while(now <= n){ int cur = mn[now] - now + 1; res += 1LL * (cur + 1) * cur / 2LL; now = mn[now] + 1; } printf("%lld\n", res); return 0; }
1043
E
Train Hard, Win Easy
Zibi is a competitive programming coach. There are $n$ competitors who want to be prepared well. The training contests are quite unusual – there are two people in a team, two problems, and each competitor will code exactly one of them. Of course, people in one team will code different problems. Rules of scoring also aren't typical. The first problem is always an implementation problem: you have to implement some well-known algorithm very fast and the time of your typing is rated. The second one is an awful geometry task and you just have to get it accepted in reasonable time. Here the length and difficulty of your code are important. After that, Zibi will give some penalty points (possibly negative) for each solution and the final score of the team is the sum of them (the \textbf{less} the score is, the better). We know that the $i$-th competitor will always have score $x_i$ when he codes the first task and $y_i$ when he codes the second task. We can assume, that all competitors know each other's skills and during the contest distribute the problems in the way that minimizes their final score. Remember that each person codes exactly one problem in a contest. Zibi wants all competitors to write a contest with each other. However, there are $m$ pairs of people who really don't like to cooperate and they definitely won't write a contest together. Still, the coach is going to conduct trainings for all possible pairs of people, such that the people in pair don't hate each other. The coach is interested for each participant, what will be his or her sum of scores of all teams he trained in?
Let's compute result if there are no edges, we can add them later. If there are no edges then result for pair ($i$, $j$) is min($x_{i}$ $+$ $y_{j}$, $x_{j}$ $+$ $y_{i}$). First let's fix $i$ for which we want to compute result. Then calculate result with all pairs $j$ such that $x_{i}$ $+$ $y_{j}$ $ \le $ $x_{j}$ $+$ $y_{i}$. After some transformations we get that $x_{i}$ $-$ $y_{i}$ $ \le $ $x_{j}$ $-$ $y_{j}$. Similarly we have that $y_{i}$ $+$ $x_{j}$ $<$ $x_{i}$ $+$ $y_{j}$ if $x_{i}$ $-$ $y_{i}$ $>$ $y_{j}$ $-$ $x_{j}$. So let's sort over differences of $x_{i}$ $-$ $y_{i}$ and compute prefix sums of $x_{i}$ and suffix sums of $y_{i}$. Now we can compute for every $i$ result in $O(1)$. Then we can iterate over every edge ($u$, $v$) and subtract min($x_{u}$ $+$ $y_{v}$, $x_{v}$ $+$ $y_{u}$) from result of $u$ and $v$. Complexity $O(nlogn)$.
[ "constructive algorithms", "greedy", "math", "sortings" ]
1,900
#include <bits/stdc++.h> using namespace std; typedef long long int LL; #define st first #define nd second #define PII pair <int, int> const int N = 3e5 + 7; int n, m; PII diff[N]; int place[N]; vector <int> G[N]; LL ans[N]; int x[N], y[N]; LL pref[N], suf[N]; int main(){ scanf("%d %d", &n, &m); for(int i = 1; i <= n; ++i){ scanf("%d %d", &x[i], &y[i]); diff[i] = {y[i] - x[i], i}; } for(int i = 1; i <= m; ++i){ int u, v; scanf("%d %d", &u, &v); G[u].push_back(v); G[v].push_back(u); } sort(diff + 1, diff + n + 1); for(int i = 1; i <= n; ++i) place[diff[i].nd] = i; for(int i = 1; i <= n; ++i) pref[i] = pref[i - 1] + y[diff[i].nd]; for(int i = n; i >= 1; --i) suf[i] = suf[i + 1] + x[diff[i].nd]; for(int i = 1; i <= n; ++i){ int u = diff[i].nd; LL res = pref[i - 1] + suf[i + 1] + 1LL * (i - 1) * x[u] + 1LL * (n - i) * y[u]; for(int v: G[u]) res -= min(x[u] + y[v], x[v] + y[u]); ans[u] = res; } for(int i = 1; i <= n; ++i) printf("%lld ", ans[i]); return 0; }
1043
F
Make It One
Janusz is a businessman. He owns a company "Januszex", which produces games for teenagers. Last hit of Januszex was a cool one-person game "Make it one". The player is given a sequence of $n$ integers $a_i$. It is allowed to select any subset of them, and the score is equal to the greatest common divisor of selected elements. The goal is to take as little elements as it is possible, getting the score $1$. Now Janusz wonders, for given sequence, how much elements should the player choose?
First let's observe that if there exists valid subset then it's size is at most $7$ (because product of $7$ smallest primes is bigger then $3 * 10^{5}$). Let's define $dp[i][j]$ - number of ways to pick $i$ different elements such that their gcd is equal to $j$. We can use inclusion--exclusion principle to calculate it. Then $dp[i][j]$ = $\textstyle{\binom{-n i j}{i}}$ - $\sum_{k=2}^{\infty}d p[i][k*j]$, where $cnt_{j}$ denotes number of $a_{i}$ such that $j$ $|$ $a_{i}$. Because for $k * j$ $>$ $3 * 10^{5}$, $dp[i][k * j]$ $=$ $0$ we have to check only $k * j$ $ \le $ $3 * 10^{5}$. Our answer is the smallest $i$ such that $dp[i][1]$ is non-zero. Since $dp[i][j]$ can be quite big we should compute it modulo some big prime. Final complexity is $O(logM * (n + M))$, where M is equal to maximum of $a_{i}$.
[ "bitmasks", "combinatorics", "dp", "math", "number theory", "shortest paths" ]
2,500
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 7; int n; int cnt[N]; int roz[N]; int dist[N]; queue <int> Q; vector <int> dv[N]; int base(int a){ int ret = 1; while(a > 1){ if(ret%roz[a] != 0) ret *= roz[a]; a /= roz[a]; } return ret; } void getEdges(int u, int d){ vector <int> cur; vector <int> val; while(u > 1){ cur.push_back(roz[u]); u /= roz[u]; } for(int v: cur) u *= v; int T = 1 << (int)cur.size(); val.resize(T); for(int i = 0; i < T; ++i){ val[i] = u; for(int j = 0; j < (int)cur.size(); ++j) if(i & (1 << j)) val[i] /= cur[j]; } for(int i = 0; i < T; ++i){ int s = 0; for(int j = i; true; j = (j - 1) & i){ if(__builtin_popcount(i ^ j) & 1) s -= cnt[val[j]]; else s += cnt[val[j]]; if(j == 0) break; } assert(s >= 0); if(s && dist[val[i]] == -1){ dist[val[i]] = d; Q.push(val[i]); } } } int main(){ scanf("%d", &n); for(int i = 2; i < N; ++i){ if(roz[i] != 0) continue; for(int j = i; j < N; j += i) roz[j] = i; } for(int i = 1; i < N; ++i) for(int j = i; j < N; j += i) dv[j].push_back(i); for(int i = 1; i < N; ++i) dist[i] = -1; for(int i = 1; i <= n; ++i){ int a; scanf("%d", &a); a = base(a); if(dist[a] != -1) continue; dist[a] = 1; Q.push(a); for(int v: dv[a]) cnt[v]++; } while(!Q.empty()){ int u = Q.front(); Q.pop(); getEdges(u, dist[u] + 1); } printf("%d\n", dist[1]); return 0; }
1043
G
Speckled Band
Ildar took a band (a thin strip of cloth) and colored it. Formally, the band has $n$ cells, each of them is colored into one of $26$ colors, so we can denote each color with one of the lowercase letters of English alphabet. Ildar decided to take some segment of the band $[l, r]$ ($1 \le l \le r \le n$) he likes and cut it from the band. So he will create a new band that can be represented as a string $t = s_l s_{l+1} \ldots s_r$. After that Ildar will play the following game: he cuts the band $t$ into some new bands and counts the number of different bands among them. Formally, Ildar chooses $1 \le k \le |t|$ indexes $1 \le i_1 < i_2 < \ldots < i_k = |t|$ and cuts $t$ to $k$ bands-strings $t_1 t_2 \ldots t_{i_1}, t_{i_1 + 1} \ldots t_{i_2}, \ldots, {t_{i_{k-1} + 1}} \ldots t_{i_k}$ and counts the number of different bands among them. He wants to know the minimal possible number of different bands he can get under the constraint that at least one band repeats at least two times. The result of the game is this number. If it is impossible to cut $t$ in such a way, the result of the game is -1. Unfortunately Ildar hasn't yet decided which segment he likes, but he has $q$ segments-candidates $[l_1, r_1]$, $[l_2, r_2]$, ..., $[l_q, r_q]$. Your task is to calculate the result of the game for each of them.
Let's solve the problem for some string $s$ for any time. Let's say, that partition of string $s$ into $k$ strings $s_{1s}_{2}... s_{i1}, s_{i1 + 1}... s_{i2}, ..., {s_{ik - 1 + 1}}... s_{ik}$ is good if at least one pair of this strings are equal. We want to find a minimal possible number of different strings in all good partitions. It's easy to see, that the answer is $- 1$ if and only if all symbols in $s$ are different. And if we have two equal symbols $s_{i} = s_{j}$ ($i < j$) we can cut a string into strings $s_{1}... s_{i - 1}, s_{i}, s_{i + 1}... s_{j - 1}, s_{j}, s_{j + 1}... s_{n}$ and it is a good partition. In this partition there is at most $4$ different strings. So the answer can be $- 1$, $1$, $2$, $3$, $4$. The answer is $- 1$ if all symbols in $s$ are different (case $0$). The answer is $1$ if the string $s = aaa... a$, for some string $a$ (case $1$). The answer is $2$ if the string $s$ is $aab$, $aba$ or $baa$ for some strings $a$ and $b$ (case $2$). The answer is $3$ if the string $s$ is $baac$, $bcaa$ or $aabc$ for some strings $a$, $b$, $c$. In two last cases it's easy to see, that $|a| = 1$ (case $3$). To solve our problem let's build suffix array with lcp for string $s$. And let's find $lt_{i}$~--- minimal possible number $r$, such that $s_{is}_{i + 1}... s_{r}$ is a tandem (the string, that can be presented as $aa$ for some string $a$) and $rt_{i}$~--- maximal possible number $l$ such that $s_{ls}_{l + 1}... s_{i}$ is a tandem. This numbers can be found using Main and Lorentz algorithm for finding tandem repetitions in the string. Now we can solve query for segment $[l, r]$: \begin{itemize} \item Case $0$: if $r - l \ge 26$, there exists equal symbols, otherwise we can check it by $O(r - l)$; \item Case $1$: to check that $s[l... r] = aa... a$ we can see that $|a|$ is a divisor of $(r - l + 1)$ and $(r - l + 1) / |a|$ is a prime number (if we take a longest possible string $a$). So we should check only $O(log(n))$ lenghts of string $a$; \item Case $2$: $s = aab$ $\displaystyle{\hat{\mathbf{c}}}\,{\hat{\mathbf{-}}}$ $lt_{l} \le r$, $s = baa$ $\displaystyle{\hat{\mathbf{\omega}}}\,{\hat{\mathbf{\Lambda}}}$ $rt_{r} \ge l$. In the last case we should check, that $s[l... r]$ has a border. It's the most interesting part of the problem, let's solve it in the end; \item Case $3$: $s = abac$ $\displaystyle{\hat{\mathbf{\omega}}}\,{\hat{\mathbf{\Lambda}}}$ $s_{l}$ exists on $s_{l + 1}... s_{r}$ (can be done using prefix sums), $s = baca$ $\displaystyle{\hat{\mathbf{\omega}}}\,{\hat{\mathbf{-}}}$ $s_{r}$ exists on $s_{l}... s_{r - 1}$ (can be done using prefix sums). To check $s = baac$ we can check, that $lt_{i} \le r$ for some $l \le i \le r$, that can be done using minimum on segment in the array $lt$. \end{itemize} Now we should the hardest part of this problem~--- we have some segments $[l, r]$. For all of them, we should check that the border of $s[l... r]$ exists. Here I know two methods, that uses only suffix array. Easiest of them: We have segment $[l, r]$. Let's check for all lengths $b\leq{\sqrt{n}}$, that $s[l... (l + b - 1)] = s[(r - b + 1)... r]$. If we don't find border, if it exists, it's length $\geqslant{\sqrt{n}}$. Let's define $i$~--- maximal index $i$ such that $lcp(l, i) \ge r - i + 1$, and string $s[i... r]$ is a border of $s[l... r]$. So $l c p(l,i)>\sqrt{n}$. But it's easy to see, that the distance between $l$ and $i$ in suffix array $\leq{\sqrt{n}}$ , so we need to check only $O({\sqrt{n}})$ variants of $i$. Another method can check that border exists for all segments $[l, r]$ using offline algorithm by $O(q \cdot log(n)^{2})$ time. So the total complexity will be $O((n+q)\cdot{\sqrt{n}})$ or $O((n + q) \cdot log(n)^{2})$.
[ "data structures", "divide and conquer", "hashing", "string suffix structures", "strings" ]
3,500
#include <bits/stdc++.h> using namespace std; #define TIME (clock() * 1.0 / CLOCKS_PER_SEC) const int BIG = 1e9 + 239; const int M = 2 * 1e5 + 239; const int L = 19; const int A = 30; const int T = (1 << 19); const int two = 2; int flm[two][M]; inline void z_function(string &s, int c) { int n = s.length(); flm[c][0] = 0; int l = 0; int r = 0; for (int i = 1; i < n; i++) { flm[c][i] = min(flm[c][i - l], r - i); if (flm[c][i] < 0) flm[c][i] = 0; while (i + flm[c][i] < n && s[flm[c][i]] == s[i + flm[c][i]]) flm[c][i]++; if (i + flm[c][i] > r) { l = i; r = i + flm[c][i]; } } } int a[M], lcp[M], pos[M]; inline void suffix_array(string s) { s += (char)(31); int n = s.length(); vector<pair<char, int> > v; for (int i = 0; i < n; i++) v.push_back(make_pair(s[i], i)); sort(v.begin(), v.end()); vector<pair<int, int> > num; int last = 0; for (int i = 0; i < n - 1; i++) { num.push_back(make_pair(last, v[i].second)); if (v[i].first != v[i + 1].first) last++; } num.push_back(make_pair(last, v.back().second)); vector<int> u(n); for (int i = 0; i < n; i++) u[num[i].second] = num[i].first; int d = 1; vector<pair<pair<int, int>, int> > t; vector<vector<pair<int, int> > > h; while (d < n) { t.clear(); h.clear(); h.resize(n); for (int i = 0; i < n; i++) { int l = num[i].second - d; if (l < 0) l += n; h[u[l]].push_back(make_pair(num[i].first, l)); } for (int i = 0; i < n; i++) for (pair<int, int> r : h[i]) t.push_back(make_pair(make_pair(i, r.first), r.second)); last = 0; num.clear(); for (int i = 0; i < n - 1; i++) { num.push_back(make_pair(last, t[i].second)); if (t[i].first != t[i + 1].first) last++; } num.push_back(make_pair(last, t.back().second)); for (int i = 0; i < n; i++) u[num[i].second] = num[i].first; d <<= 1; } for (int i = 1; i < n; i++) a[i - 1] = num[i].second; } string s; inline void kasai() { int n = s.size(); suffix_array(s); for (int i = 0; i < n; i++) pos[a[i]] = i; int k = 0; for (int i = 0; i < n; i++) { if (pos[i] == n - 1) continue; while (s[i + k] == s[a[pos[i] + 1] + k] && a[pos[i] + 1] + k < n && i + k < n) k++; lcp[pos[i]] = k; k = max(0, k - 1); } } int n, lw[M], rw[M]; string prr, rvl; vector<int> open_l[M], close_l[M]; vector<int> open_r[M], close_r[M]; multiset<int> nw; inline void func(int l, int r) { if (r - l == 1) return; int mid = (l + r) >> 1; func(l, mid); func(mid, r); rvl = ""; for (int i = mid - 1; i >= l; i--) rvl += s[i]; z_function(rvl, 0); prr = ""; for (int i = mid; i < r; i++) prr += s[i]; prr += '#'; for (int i = l; i < mid; i++) prr += s[i]; z_function(prr, 1); for (int c = l; c < mid; c++) { int k1 = 0; if (c > l) k1 = flm[0][mid - c]; int k2 = flm[1][r - mid + 1 + c - l]; int len = mid - c; int lg = max(len - k2, 0); int rg = min(len - 1, k1); if (rg >= lg) { open_l[c - rg].push_back((2 * len)); close_l[c - lg].push_back((2 * len)); open_r[c - rg + 2 * len - 1].push_back((2 * len)); close_r[c - lg + 2 * len - 1].push_back((2 * len)); } } rvl = ""; for (int i = mid; i < r; i++) rvl += s[i]; z_function(rvl, 0); prr = ""; for (int i = mid - 1; i >= l; i--) prr += s[i]; prr += '#'; for (int i = r - 1; i >= mid; i--) prr += s[i]; z_function(prr, 1); for (int c = mid; c < r; c++) { int k1 = 0; if (c != r - 1) k1 = flm[0][c + 1 - mid]; int k2 = flm[1][r - c + mid - l]; int len = c - mid + 1; int lg = max(len - k2, 0); int rg = min(len - 1, k1); if (rg >= lg) { open_l[c + lg - 2 * len + 1].push_back((2 * len)); close_l[c + rg - 2 * len + 1].push_back((2 * len)); open_r[c + lg].push_back((2 * len)); close_r[c + rg].push_back((2 * len)); } } for (int i = l; i < r; i++) { for (int len : open_l[i]) nw.insert(len); if (!nw.empty()) lw[i] = min(lw[i], *nw.begin()); for (int len : close_l[i]) nw.erase(nw.lower_bound(len)); open_l[i].clear(); close_l[i].clear(); } for (int i = l; i < r; i++) { for (int len : open_r[i]) nw.insert(len); if (!nw.empty()) rw[i] = min(rw[i], *nw.begin()); for (int len : close_r[i]) nw.erase(nw.lower_bound(len)); open_r[i].clear(); close_r[i].clear(); } } int mn[L][M], st2[M], lc[L][M], kol[A][M]; inline int getmin(int l, int r) { int u = st2[r - l + 1]; return min(mn[u][l], mn[u][r - (1 << u) + 1]); } inline int gett(int l, int r) { if (l == r) return (n - l); l = pos[l]; r = pos[r]; if (l > r) swap(l, r); r--; int u = st2[r - l + 1]; return min(lc[u][l], lc[u][r - (1 << u) + 1]); } int q, mnp[M]; inline void init() { for (int i = 0; i < n; i++) mn[0][i] = lw[i]; for (int i = 0; i < n - 1; i++) lc[0][i] = lcp[i]; for (int i = 1; i < L; i++) for (int j = 0; j < n; j++) { int r = (j + (1 << (i - 1))); if (r >= n) { mn[i][j] = mn[i - 1][j]; continue; } mn[i][j] = min(mn[i - 1][j], mn[i - 1][r]); } for (int i = 1; i < L; i++) for (int j = 0; j < n - 1; j++) { int r = (j + (1 << (i - 1))); if (r >= n - 1) { lc[i][j] = lc[i - 1][j]; continue; } lc[i][j] = min(lc[i - 1][j], lc[i - 1][r]); } st2[1] = 0; for (int i = 2; i <= n; i++) { st2[i] = st2[i - 1]; if ((1 << (st2[i] + 1)) <= i) st2[i]++; } } int u, len; inline bool check(int l, int r) { for (int t = 1; t <= min(len, ((r - l + 1) / 2)); t++) if (gett(l, r - t + 1) >= t) return true; for (int i = max(0, pos[l] - len); i <= min(n - 1, pos[l] + len); i++) if (l < a[i] && a[i] <= r && gett(l, a[i]) >= r - a[i] + 1) return true; return false; } inline bool checkno(int l, int r) { if (r - l + 1 > 26) return false; vector<int> kol(26, 0); for (int x = l; x <= r; x++) { if (kol[s[x] - 'a'] > 0) return false; kol[s[x] - 'a']++; } return true; } inline bool try_kol(int l, int r, int p) { int len = (r - l + 1) / p; return (gett(l, l + len) >= (r - l + 1 - len)); } inline bool ison(int l, int r, char x) { return (kol[x - 'a'][r + 1] > kol[x - 'a'][l]); } inline int query(int l, int r) { if (checkno(l, r)) return -1; int len = (r - l + 1); while (len > 1) { int p = mnp[len]; if (try_kol(l, r, p)) return 1; while ((len % p) == 0) len /= p; } if (lw[l] <= r) return 2; if (rw[r] >= l) return 2; if (check(l, r)) return 2; if (ison(l + 1, r, s[l])) return 3; if (ison(l, r - 1, s[r])) return 3; if (getmin(l, r) <= r) return 3; return 4; } int main() { cin.sync_with_stdio(0); cin >> n >> s; memset(mnp, -1, sizeof(mnp)); for (int i = 2; i <= n; i++) if (mnp[i] == -1) for (int j = i; j <= n; j += i) if (mnp[j] == -1) mnp[j] = i; memset(kol[0], 0, sizeof(kol[0])); for (int i = 0; i < n; i++) { for (int x = 0; x < 26; x++) kol[x][i + 1] = kol[x][i]; kol[s[i] - 'a'][i + 1]++; } for (int i = 0; i < n; i++) { lw[i] = n + 1; rw[i] = n + 1; } func(0, n); for (int i = 0; i < n; i++) { if (lw[i] == n + 1) lw[i] = n; else lw[i] += (i - 1); if (rw[i] == n + 1) rw[i] = -1; else rw[i] = (i - rw[i] + 1); } kasai(); init(); cin >> q; for (int i = 0; i < n; i++) if (i * i >= n) { len = i + 3; break; } for (int i = 0; i < q; i++) { int l, r; cin >> l >> r; l--, r--; cout << query(l, r) << "\n"; } return 0; }
1044
A
The Tower is Going Home
On a chessboard with a width of $10^9$ and a height of $10^9$, the rows are numbered from bottom to top from $1$ to $10^9$, and the columns are numbered from left to right from $1$ to $10^9$. Therefore, for each cell of the chessboard you can assign the coordinates $(x,y)$, where $x$ is the column number and $y$ is the row number. Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates $(1,1)$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the \textbf{upper side} of the field (that is, in any cell that is in the row with number $10^9$). Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells: - Vertical. Each of these is defined by one number $x$. Such spells create an infinite blocking line between the columns $x$ and $x+1$. - Horizontal. Each of these is defined by three numbers $x_1$, $x_2$, $y$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $y$ and in columns from $x_1$ to $x_2$ inclusive. The peculiarity of these spells is that it is \textbf{impossible} for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells. \begin{center} {\small An example of a chessboard.} \end{center} Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $(r_0,c_0)$ into the cell $(r_1,c_1)$ only under the condition that $r_1 = r_0$ or $c_1 = c_0$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples). Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!
Observation 1. If we remove all the horizontal spells, than the rook can move straightforward up to the upper side of the field. So the only purpose of removing the vertical spells is to reduce the number of horizontal spells to be removed. Observation 2. If we want to remove the $i$-th vertical spell, then we should also remove all such vertical spells $j$, that $x_j<x_i$. It is obvious, because when we delete a vertical spell, we suppose that the rook would be able to outflank some horizontal spells by getting at rows that have greater number than $x_i$. If there remains at least one vertical spell $j$, such that $x_j<x_i$, than we will never be able to move to the rows with number greater than $x_j$, including $x_i$. Let's find some observations about the horizontal spells: Let's assume that we deleted $i$ vertical spells. It means, that the rook can move freely left and right at columns between $1$ and $x_{i+1}$ inclusive. Let's say that our rook is on the row $y$. If there is at least one cell which is located at row $y$ at any column between $1$ and $x_{i+1}$, that there is no blocking segment on the top of it, then the rook can move to this cell and move upwards into the row $y+1$. It means that if there is at least one gap in the blocking segments in row $y$ and in columns between $1$ and $x_{i+1}$ incluse, then there is no need to remove any of horizontal spells in the row. Observation 3. We care only about such horizontal spells, in which $x_1=1$. We have already proved, that we only care about such rows, that there are no gaps in blocking segments in them. If there is no such horizontal spell with $x_1 = 1$, it means that there is a gap in the row at column $1$. If there is such horizontal spell, then if there are more spells in that row, there would be a gap between any pair of neighbouring segments. Since we only care only about segments with $x_1 = 1$ and it is guaranteed that no horizontal segments share a common point, it means that we might not care about the $y$ of any horizontal spell, because there is no such pair of segments that both $x_1$ and $y$ of these are equal. So now while reading the descriptions of the horizontal spells, if the $x_1$ of $i$-th horizontal spell is not equal to $1$, we can ignore it. Otherwise, we add $x_2$ to some array. Now we can sort the array of $x_2$-s, and solve the task using the two-pointer technique. Here is the final algorithm: Add fake vertical spell with $x=10^9$. Sort all the vertical spells in ascending order. While reading the descriptions of the horizontal spells, we ignore ones with $x_1$ not equal to $1$. In other case, we add $x_2$ to the array. Sort the array of $x_2$-s in ascending order. Now we use the two pointer technique in the following way: we iterate $i$ from 0 to n - the number of vertical spells to be deleted and on each step we advance the pointer while the $x_2$ at which the pointer points is less then $x$ of the $(i+1)$-th vertical spell. Let's denote the position of the pointer as $p$. The number of horizontal spells, that we need to remove with $i$ vertical spells removed is $m-p+1$. Let's define the position of the pointer at $i$-th step as $p_i$. The answer to the problem in minival value of $i + m - p_i + 1$ among all $i$ from $0$ to $n$. Overall complexity $O(n \log n + m \log m)$
[ "binary search", "two pointers" ]
1,700
null
1044
B
Intersecting Subtrees
You are playing a strange game with Li Chen. You have a tree with $n$ nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you \textbf{independently} labeled the vertices from $1$ to $n$. Neither of you know the other's labelling of the tree. You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled $x_1, x_2, \ldots, x_{k_1}$ in \textbf{your labeling}, Li Chen's subtree consists of the vertices labeled $y_1, y_2, \ldots, y_{k_2}$ in \textbf{his labeling}. The values of $x_1, x_2, \ldots, x_{k_1}$ and $y_1, y_2, \ldots, y_{k_2}$ are known to both of you. \begin{center} {\small The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes.} \end{center} You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most $5$ questions, each of which is in one of the following two forms: - A x: Andrew will look at vertex $x$ in your labeling and tell you the number of this vertex in Li Chen's labeling. - B y: Andrew will look at vertex $y$ in Li Chen's labeling and tell you the number of this vertex in your labeling. Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.
I'll split this into two parts, first is the solution, second is why it works. The intended solution only uses two questions. Choose an arbitrary $y_j$, and ask "B y_j". Let the response be $R$. Find a node $x_i$ that is the closest to node $R$. This can be done with a BFS or DFS. Ask "A x_i". Let the response be $Q$. If $Q$ is one of $y_1,y_2,\ldots,y_{k_2}$, print "C x_i", otherwise, print "C -1". Here is why it works. Let's use the fact that if the two subtrees don't intersect, there is an edge in the tree such that if we cut the tree on this edge, it will split it into two components, each containing one of the subtrees. Suppose we did step 1 and we have $R$. Let's root our tree at $R$. There is a unique node $x_i$ that has lowest depth in this tree which we can find (given that $x_1,x_2,\ldots,x_{k_1}$ form a subtree). Now, we claim that the two subtrees intersect if and only if Li Chen owns a node that lies in the subtree rooted by $x_i$ (and in particular, we will show it is sufficient to only check node $x_i$). If none of Li Chen's nodes lie in the subtree rooted by $x_i$, then the edge $x_i$ to its parent cuts the tree into two components with one subtree completely lying in one component and the other in the second, so the two subtrees are disjoint. Otherwise, there is a node $W$ that is in Li Chen's subtree that lies in the subtree rooted by $x_i$. All nodes in the path of $R$ to $W$ must also belong to Li Chen's subtree, and in particular this includes node $x_i$, so the two trees intersect. This also shows we can just check if $x_i$ belongs in Li Chen's subtree by asking a question about it.
[ "dfs and similar", "interactive", "trees" ]
1,900
null
1044
C
Optimal Polygon Perimeter
You are given $n$ points on the plane. The polygon formed from all the $n$ points is \textbf{strictly convex}, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from $1$ to $n$, in clockwise order. We define the distance between two points $p_1 = (x_1, y_1)$ and $p_2 = (x_2, y_2)$ as their Manhattan distance: $$d(p_1, p_2) = |x_1 - x_2| + |y_1 - y_2|.$$ Furthermore, we define the perimeter of a polygon, as the sum of Manhattan distances between all adjacent pairs of points on it; if the points on the polygon are ordered as $p_1, p_2, \ldots, p_k$ $(k \geq 3)$, then the perimeter of the polygon is $d(p_1, p_2) + d(p_2, p_3) + \ldots + d(p_k, p_1)$. For some parameter $k$, let's consider all the polygons that can be formed from the given set of points, having \textbf{any} $k$ vertices, such that the polygon is \textbf{not} self-intersecting. For each such polygon, let's consider its perimeter. Over all such perimeters, we define $f(k)$ to be the maximal perimeter. Please note, when checking whether a polygon is self-intersecting, that the edges of a polygon are still drawn as straight lines. For instance, in the following pictures: In the middle polygon, the order of points ($p_1, p_3, p_2, p_4$) is not valid, since it is a self-intersecting polygon. The right polygon (whose edges resemble the Manhattan distance) has the same order and is not self-intersecting, but we consider edges as straight lines. The correct way to draw this polygon is ($p_1, p_2, p_3, p_4$), which is the left polygon. Your task is to compute $f(3), f(4), \ldots, f(n)$. In other words, find the maximum possible perimeter for each possible number of points (i.e. $3$ to $n$).
I will show 2 solutions, both of which work in $\mathcal{O}(n)$ time. First, it is not hard to notice that we can only consider polygons that are convex. Observation: For a convex polygon, the given definition of "polygon perimeter" is equivalent to the perimeter of the bounding rectangle (aligned with the axis), of our polygon. If we look at some convex polygon, and 4 values $max_x, min_x, max_y, min_y$ representing the maximal $x$ coordinate of a point, minimal $x$, maximal and minimal $y$, then the perimeter of the bounding rectangle is simply $2 * (max_x - min_x + max_y - min_y)$. This simple rephrase gives us a bonus, and crucial observation: It is enough for us to take 4 points from the input, such that the perimeter of their polygon is the maximal possible (and is equal to the perimeter of the polygon formed from $n$ points). We will consider these the extreme points. Note that after taking the extreme points, it does not matter which other points we take. So, this solves all $f(4), \ldots, f(n)$. We are left with $f(3)$ to compute (maximal triangle perimeter). Following are 2 solutions to do it: Solution 1: Let's show that the optimal triangle uses at least 2 of the extreme points. Imagine some optimal triangle, and its bounding rectangle. Notice that since each edge of the bounding rectangle must touch some vertex of the triangle (it is bounding after all), and we have 4 edges and 3 vertices, then there must be some vertex of the triangle that touches 2 edges of the rectangle (so it coincides with a rectangle vertex). If this is the case, we know that in comparison with the 2 other vertices, this vertex has "extremal" X and Y coordinates (minimal/maximal X, and minimal/maximal Y). Without loss of generality, assume this vertex has maximum X and Y. Then to optimize the perimeter, the other two vertices should have smallest possible X and smallest possible Y. We can pick these 2 vertices to be 2 of the extreme points (one with minimal X and one with minimal Y). So, this shows we just need to iterate over every adjacent pair of extreme vertices, and over all other points as the last vertex. This takes $\mathcal{O}(n)$. Solution 2: This solution is more general, and is an extension of the problem to find the 2 most distant points (manhattan distance). The triangle perimeter is an expression with 6 terms: $|x_1 - x_2| + |y_1 - y_2| + \ldots + |y_3 - y_1|$. We wish the maximize this expression, but the absolute value is troubling us. For each term, there are 2 cases: either it is positive, so the absolute value does nothing, or it is negative, so the absolute value negates it. In total, for the 6 terms we have $2^6 = 64$ options to place signs between them. We will call such option a setting. For any setting, the advantage now is that we can accumulate terms: For example the setting $++---+$, evaluates the expression to: $(2x_1 + 0y_1) + (-2x_2 - 2y_2) + (0x_3 + 2y_3)$ We solve every setting by its own, and over all settings we take the maximal answer. Please note, that this strategy only works to find the maximal value of the expression, not minimal. The proof of this is left as an exercise to the reader :) (I promise it is not difficult). Given 6 constants $c_1, c_2, ..., c_6$, we want to find 3 indicies $i < j < k$ to maximize: $c_1 * x_i + c_2 * y_i + ... + c_6 * y_k$. We define 3 arrays: $P_i = c_1 \cdot x_i + c_2 \cdot y_i$ $Q_i = c_3 \cdot x_i + c_4 \cdot y_i$ $R_i = c_5 \cdot x_i + c_6 \cdot y_i$ So this whole solution is $\mathcal{O}(n)$, with a constant of 64. In general, to compute $f(k)$ this solution takes $\mathcal{O}(n \cdot 4^k \cdot k)$ time, without any observations.
[ "dp", "geometry" ]
2,100
null
1044
D
Deduction Queries
There is an array $a$ of $2^{30}$ integers, indexed from $0$ to $2^{30}-1$. Initially, you know that $0 \leq a_i < 2^{30}$ ($0 \leq i < 2^{30}$), but you do not know any of the values. Your task is to process queries of two types: - 1 l r x: You are informed that the \textbf{bitwise xor} of the subarray $[l, r]$ (ends inclusive) is equal to $x$. That is, $a_l \oplus a_{l+1} \oplus \ldots \oplus a_{r-1} \oplus a_r = x$, where $\oplus$ is the bitwise xor operator. In some cases, the received update contradicts past updates. In this case, you should \textbf{ignore} the contradicting update (the current update). - 2 l r: You are asked to output the bitwise xor of the subarray $[l, r]$ (ends inclusive). If it is still impossible to know this value, considering all past updates, then output $-1$. Note that the queries are \textbf{encoded}. That is, you need to write an \textbf{online} solution.
First, let's learn how to handle information we have not recieved in updates. Let the function $W(l, r)$ be equal to the xor of the subarray $[l, r]$. Also, we define $W(l, r) = W(r, l)$. Assume 3 indicies $a \leq b \leq c$. There are 2 rules: $W(a, b) \oplus W(b + 1, c) = W(a, c)$. $W(a, c) \oplus W(b, c) = W(a, b - 1)$ (holds when $a < b$). These rules require a lot of conditions (and also plenty of $\pm$ 1). We can simplify them greatly: Let's index the borders between cells in our array (there are $2^{30} + 1$ of them). Now, instead of defining a subarray $[l, r]$ by its 2 endpoint cells, we will define a subarray by its 2 endpoint borders. Technically it just means, that we should increase $r$ by 1, and then we get the 2 end borders. From now I will assume that our input is given in such a way, that subarrays are defined by their borders (So I will not mention the addition of 1 to $r$). Notice that the function $W(l, r)$ is also affected by this. If we take a look at our rules again, they boil down to just 1 rule: $W(a, b) \oplus W(b, c) = W(a, c)$, for any 3 indicies $a,b,c$ ($a \leq b \leq c$ doesn't need to hold now, for instance $W(3, 5) \oplus W(5, 2) = W(3, 2)$). This transformation also shows an observation; Assume every border is a vertex in a graph, and every update $W(l, r) = x$ describes an undirected edge between the vertices $l, r$ with weight $x$. We let the distance between 2 nodes $a, b$ be the xor of edge weights on the path between them. Notice that this distance is equal to $W(a, b)$. In other words, an update adds an edge and a query asks for some distance. Another observation is that, we do not care about all the $2^{30} + 1$ nodes, but only about the ones we recieved in queries and updates. Moreover, their order is irrelevant, so we can do an online mapping of new nodes to the next free indicies. Thus, the number of nodes will be worstcase $\mathcal{O}(q)$. Claim: We can know the answer to some query $[l, r]$, if and only if there exists a path between the nodes $l, r$ (they are in the same connected component). //start spoiler of proof There will be some subset of edges we take, to form the xor between nodes $l$ and $r$. Assume every vertex has 2 states, on/off. Initially all vertices are off, and our current answer is $0$. When we take an edge we flip the state of its 2 ends, and xor our answer by its weight. Suppose at some moment of time the nodes with "on" state are {$x_0, x_1, x_2, ..., x_k$} (in sorted order). Observe that our current answer is equal to $W(x_0, x_1) \oplus W(x_2, x_3) \oplus \ldots \oplus W(x_{k-1}, x_k)$. This implies we want our subset of edges to end up having only the nodes {$l, r$} activated. We look at the connected components. Observe that in each connected component, the number of nodes activated at any time is even. If the nodes $l$ and $r$ are in different component, then in our final result we would want to have only 1 activated node in the component of $l$, and same with $r$, but this is impossible. //end spoiler of proof First, we need to know whether a query gives us 2 nodes that are in different components (to know whether the answer is $-1$ or not). For this we need to use the Union-Find structure. Also notice, that our Union-Find structure will only need to handle a forest of trees (if an update gives us an edge that creates a cycle, it means there is no contribution, so we ignore it). Provided that an answer does exist, we need to also handle finding a xor path between 2 nodes in a tree, and to support merging of trees. Generally to find a property over some path in a tree, it is common to use LCA or binary lifting. This turns out very difficult when we also need to merge trees (unless you insist on implementing Link-Cut/ETT). Fortunately, we can still abuse the xor operator. In some tree, mark $x_v$ as the xor of edges on the path from $v$ to some arbitrary root in the tree. The xor path between nodes ($u, v$) turns out to be $x_u \oplus x_v$. So we would like to maintain for each tree some arbitrary root and all those values. Notice that we can augment our Union-Find structure to support this as well: For each node $v$ in the structure, we maintain $p_v$ as its parent in the structure, and $x_v$ as the xor on the path from $v$ to $p_v$. Notice that $x_v$ can be easily updated together with $p_v$ during the $find()$ operation in the structure. To summarize, when we are given $W(l, r) = x$ in some update, we transform it to $W(p_l, p_r) = x \oplus x_l \oplus x_r$, and then we add the edge between the parents. Finally, the complexity is $\mathcal{O}(q \log{q})$, but this is only due to the online mapping if we use a regular map; You can use a hash table and get a running time of $\mathcal{O}(q \times \alpha(q))$, but I suggest being careful with a hash table (you may want to read this: https://codeforces.com/blog/entry/62393).
[ "data structures", "dsu" ]
2,400
null
1044
E
Grid Sort
You are given an $n \times m$ grid. Each grid cell is filled with a unique integer from $1$ to $nm$ so that each integer appears exactly once. In one operation, you can choose an arbitrary cycle of the grid and move all integers along that cycle one space over. Here, a cycle is any sequence that satisfies the following conditions: - There are at least four squares. - Each square appears at most once. - Every pair of adjacent squares, and also the first and last squares, share an edge. For example, if we had the following grid: We can choose an arbitrary cycle like this one: To get the following grid: In this particular case, the chosen cycle can be represented as the sequence $[1, 2, 3, 6, 5, 8, 7, 4]$, the numbers are in the direction that we want to rotate them in. Find any sequence of operations to sort the grid so that the array created by concatenating the rows from the highest to the lowest is sorted (look at the first picture above). Note you do not need to minimize number of operations or sum of cycle lengths. The only constraint is that the sum of all cycles lengths must not be greater than $10^5$. We can show that an answer always exists under the given constraints. Output any valid sequence of moves that will sort the grid.
The solution is more of a coding one than an algorithmic one. There are many different approaches, and it's important to be careful in how it is implemented. I'll explain one of the implementations. First, we can always move a particular block left, up, down, or right with an appropriate 2x2 square around it. Let's code some functions that let us do that for each direction. Next is to make sure that these moves don't mess up previous block spaces as we move blocks to the correct place. We can almost place blocks correctly in their spaces one by one in row major order, but there are some special cases. - We can do all blocks except the last two rows, which we'll handle separately (in paragraph below) - For each row, we can correctly place all blocks except the last one. The last one requires a bit more careful work, but is easy to handle if we have at least two free rows. For the last two rows, we can fill it in column by column from left to right. This is a similar startegy to fitting in the last column of the previous rows. We can almost do this except for the last 2x2 square. For the last 2x2 square, we can use the following sequence of moves to swap two blocks: Thus, we can shift the last block into the right position, then do at most three swaps (using the above sequence of moves) to fix the remaining blocks. The number of moves for this strategy can be computed and estimated to be about 50k in the worst case.
[ "implementation" ]
3,100
null
1044
F
DFS
Let $T$ be a tree on $n$ vertices. Consider a graph $G_0$, initially equal to $T$. You are given a sequence of $q$ updates, where the $i$-th update is given as a pair of two distinct integers $u_i$ and $v_i$. For every $i$ from $1$ to $q$, we define the graph $G_i$ as follows: - If $G_{i-1}$ contains an edge $\{u_i, v_i\}$, then remove this edge to form $G_i$. - Otherwise, add this edge to $G_{i-1}$ to form $G_i$. Formally, $G_i := G_{i-1} \triangle \{\{u_i, v_i\}\}$ where $\triangle$ denotes the set symmetric difference. Furthermore, it is guaranteed that $T$ is always a subgraph of $G_i$. In other words, an update never removes an edge of $T$. Consider a connected graph $H$ and run a depth-first search on it. One can see that the tree edges (i.e. the edges leading to a not yet visited vertex at the time of traversal) form a spanning tree of the graph $H$. This spanning tree is not generally fixed for a particular graph — it depends on the starting vertex, and on the order in which the neighbors of each vertex are traversed. We call vertex $w$ good if one can order the neighbors of each vertex in such a way that the depth-first search started from $w$ produces $T$ as the spanning tree. For every $i$ from $1$ to $q$, find and report the number of good vertices.
Let's consider an arbitrary run of DFS producing some tree. Let's root the tree at the starting vertex. It can be shown that on a directed graph, there are only two types of edges. The first are the tree edges (those are the ones that are used to visit a new vertex). The second are edges which, upon being traversed, lead to a vertex that was already visited. It can be shown that, in the rooted tree, those edges always connect a vertex with one of its ancestors. In other words, all the edges that are dynamically added to the tree must connect a vertex with one of their ancestors. This means that the staring vertex must not lie on the path connecting the two endpoints of such edge, or any of the vertices in some of the subtrees. For instance, on the second sample, the edge $\{2,4\}$ disallows the vertex $1$ from being the starting vertex, as it lies on the path from $2$ to $4$, and also vertex $6$. Each edge thus forbids a certain set of vertices from being the starting point. This yields a straightforward $\mathcal O(n^2)$ solution. To optimize it further, we can root the tree arbitrarily and renumber the vertices using their DFS visit times. When we do this, we notice that the set of a forbidden vertices for each edge is a union of at most three intervals of vertices. This lets us build an $\mathcal O(n \log n)$ solution using a segment tree. The operation is add a constant on interval, and then find the minimum on interval and the number of occurrences of said minimum. We add $1$ to forbid a vertex because of an edge, subtract $1$ to revert that when the edge is subsequently removed. The answer is the number of minimums on the whole tree if that minimum is $0$, and $0$ otherwise.
[ "data structures" ]
2,700
null
1047
A
Little C Loves 3 I
Little C loves number «3» very much. He loves all things about it. Now he has a positive integer $n$. He wants to split $n$ into $3$ positive integers $a,b,c$, such that $a+b+c=n$ and none of the $3$ integers is a multiple of $3$. Help him to find a solution.
If $n - 2$ is not a multiple of $3$, $a = 1, b = 1, c = n - 2$ is OK. Otherwise, $a = 1, b = 2, c = n - 3$ is OK.
[ "math" ]
800
#include<bits/stdc++.h> using namespace std; int main() { int n; scanf("%d",&n); if((n-2)%3)printf("1 1 %d",n-2); else printf("1 2 %d",n-3); }
1047
B
Cover Points
There are $n$ points on the plane, $(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$. You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
To cover a point $(x_{i}, y_{i})$, the length of the shorter side of the triangle should be at least $x_{i} + y_{i}$. So the answer is $max(x_{i} + y_{i})$.
[ "geometry", "math" ]
900
#include<bits/stdc++.h> using namespace std; int main() { int n,x,y,ans=0; scanf("%d",&n); while(n--)scanf("%d%d",&x,&y),ans=max(ans,x+y); printf("%d",ans); }
1051
A
Vasya And Password
Vasya came up with a password to register for EatForces — a string $s$. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits. But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin letter and at least one lowercase Latin letter. For example, the passwords "abaCABA12", "Z7q" and "3R24m" are valid, and the passwords "qwerty", "qwerty12345" and "Password" are not. A substring of string $s$ is a string $x = s_l s_{l + 1} \dots s_{l + len - 1} (1 \le l \le |s|, 0 \le len \le |s| - l + 1)$. $len$ is the length of the substring. Note that the empty string is also considered a substring of $s$, it has the length $0$. Vasya's password, however, may come too weak for the security settings of EatForces. He likes his password, so he wants to replace some its substring with another string of the same length in order to satisfy the above conditions. This operation should be performed \textbf{exactly} once, and \textbf{the chosen string should have the minimal possible length}. \textbf{Note that the length of $s$ should not change after the replacement of the substring, and the string itself should contain only lowercase and uppercase Latin letters and digits.}
There are just a few general cases in the task to consider: If the password $s$ is already valid, nothing has to be changed, just print $s$. Try to change exactly one character, iterate over all positions in $s$ and all three options for character (any digit, any lowercase or uppercase Latin letter). After the replacement the string is checked for the validity and printed if it turned out to be valid. We weren't able to replace a substring of length 0 or 1, then the answer is at least 2. We can obtain it in a following manner: replace the first two characters to "a1" if the third character is an uppercase Latin letter, to "A1" if the third character is a lowercase Latin letter and to "aA" if the third character is a digit.
[ "greedy", "implementation", "strings" ]
1,200
#include <bits/stdc++.h> using namespace std; string s; bool ok(string t){ int msk = 0; for(int i = 0; i < int(t.size()); ++i){ if(isupper(t[i])) msk |= 1; if(islower(t[i])) msk |= 2; if(isdigit(t[i])) msk |= 4; } return msk == 7; } int main() { //freopen("input.txt", "r", stdin); int t; cin >> t; for(int i = 0; i < t; ++i){ cin >> s; if(ok(s)){ cout << s << endl; continue; } bool fnd = false; for(int i = 0; i < int(s.size()); ++i){ string t = s; t[i] = '1'; if(ok(t)){ cout << t << endl; fnd = true; break; } t[i] = 'a'; if(ok(t)){ cout << t << endl; fnd = true; break; } t[i] = 'A'; if(ok(t)){ cout << t << endl; fnd = true; break; } } if(fnd) continue; if(isupper(s[2])){ s[0] = 'a'; s[1] = '1'; cout << s << endl; continue; } if(islower(s[2])){ s[0] = 'A'; s[1] = '1'; cout << s << endl; continue; } if(isdigit(s[2])){ s[0] = 'a'; s[1] = 'A'; cout << s << endl; continue; } } return 0; }
1051
B
Relatively Prime Pairs
You are given a set of all integers from $l$ to $r$ inclusive, $l < r$, $(r - l + 1) \le 3 \cdot 10^5$ and $(r - l)$ is always odd. You want to split these numbers into exactly $\frac{r - l + 1}{2}$ pairs in such a way that for each pair $(i, j)$ the greatest common divisor of $i$ and $j$ is equal to $1$. Each number should appear in exactly one of the pairs. Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.
Numbers with the difference of $1$ are always relatively prime. That's the only thing I should mention for this editorial. Overall complexity: $O(r - l)$.
[ "greedy", "math", "number theory" ]
1,000
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) int main() { long long l, r; scanf("%lld%lld", &l, &r); puts("YES"); forn(i, (r - l) / 2 + 1) printf("%lld %lld\n", l + i * 2, l + i * 2 + 1); }
1051
C
Vasya and Multisets
Vasya has a multiset $s$ consisting of $n$ integer numbers. Vasya calls some number $x$ nice if it appears in the multiset exactly once. For example, multiset $\{1, 1, 2, 3, 3, 3, 4\}$ contains nice numbers $2$ and $4$. Vasya wants to split multiset $s$ into two multisets $a$ and $b$ \textbf{(one of which may be empty)} in such a way that the quantity of nice numbers in multiset $a$ would be the same as the quantity of nice numbers in multiset $b$ (the quantity of numbers to appear exactly once in multiset $a$ and the quantity of numbers to appear exactly once in multiset $b$).
Write down all the numbers, which appear exactly once, let there be $k$ of them. If $k$ is even, put the first $\frac{k}{2}$ of them into the first multiset and put the other $\frac{k}{2}$ into the second multiset. All the other numbers (which appear more than once) also go into the first multiset. The only nice numbers will be the initial $k$, thus the answer is valid. If $k$ is odd and there is no number to appear more than twice, then the answer is "NO", as all the numbers to appear exactly twice don't change the difference of the amounts of the nice numbers at all. If there is a number to appear more than twice (let it be $x$), then let's firstly add $\lceil \frac{k}{2} \rceil$ of the numbers to appear exactly once to the first multiset, add $\lfloor \frac{k}{2} \rfloor$ others of them to the second multiset. Then the first occurrence of $x$ goes to the second multiset and all the other numbers go to the first multiset. It's easy to notice that multisets will contain equal number of the nice numbers after all the partitioning.
[ "brute force", "dp", "greedy", "implementation", "math" ]
1,500
#include <bits/stdc++.h> using namespace std; const int N = 109; int n; int a[N]; map<int, int> m; set <int> s[2]; int main() { int n; cin >> n; for(int i = 0; i < n; ++i){ cin >> a[i]; m[a[i]]++; } int pos = 0; for(auto p : m) if(p.second == 1){ s[pos].insert(p.first); pos = 1 - pos; } if(s[0].size() == s[1].size()){ string res(n, 'A'); for(int i = 0; i < n; ++i) if(s[1].count(a[i])) res[i] = 'B'; cout << "YES" << endl; for(auto c : res) cout << c; cout << endl; return 0; } else{ assert(int(s[0].size()) - 1 == int(s[1].size())); string res(n, 'A'); for(int i = 0; i < n; ++i) if(s[1].count(a[i])) res[i] = 'B'; int id = -1; for(auto p : m) if(p.second >= 3){ id = p.first; break; } if(id == -1){ cout << "NO" << endl; return 0; } bool flag = false; for(int i = 0; i < n; ++i){ if(a[i] == id) if(!flag){ flag = true; res[i] = 'B'; } } cout << "YES" << endl; for(auto c : res) cout << c; cout << endl; return 0; } return 0; }
1051
D
Bicolorings
You are given a grid, consisting of $2$ rows and $n$ columns. Each cell of this grid should be colored either black or white. Two cells are considered neighbours if they have a \textbf{common border} and share the same color. Two cells $A$ and $B$ belong to the same component if they are neighbours, or if there is a neighbour of $A$ that belongs to the same component with $B$. Let's call some bicoloring beautiful if it has exactly $k$ components. Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $998244353$.
The problem is about counting the number of some combinatoric objects. Thus, dynamic programming is always the answer. Let $dp[i][j][mask]$ be the number of beautiful bicolorings of the first $i$ columns such that $j$ components are already created and can't be modified and the colors of the $i$-th column are determined by $mask$ (its first bit is the color of the lower cell and its second bit the color of the upper cell). Component can be modified if the cell from the $i$-th column belongs to it. The initial states are $dp[0][0][mask] = 1$ for each $mask = 0..3$ and $dp[i][j][mask] = 0$ for any other state. You should iterate over the possible $nmask$ for the next column and recalculate the number of components. You can easily show that the current number of components and the last column is actually enough to get the new number of components. In my code I have some function $get(mask, nmask)$ to determine the added number of components while transitioning from $mask$ to $nmask$. These are just the couple of cases to handle carefully. Then all the transitions are: $dp[i + 1][j + get(mask, nmask)][nmask]$ += $dp[i][j][mask]$. However, the last column won't contain the answer as it is, the number of components will be incorrect. Let's add some dummy column $n + 1$ equal to $mask \oplus 3$ for each $mask$. This will add all the real component to the total number. So the answer is the sum of $dp[n][k - get(mask, mask \oplus 3)][mask]$ over all $mask = 0..3$. Overall complexity: $O(n^2 \cdot 4^m)$, where $m$ is the number of rows (2 for this problem).
[ "bitmasks", "dp" ]
1,700
#include <bits/stdc++.h> using namespace std; #define forn(i, n) for(int i = 0; i < int(n); i++) const int N = 1000 + 7; const int MOD = 998244353; int dp[N][2 * N][4]; int add(int a, int b){ return (a + b) % MOD; } bool full(int mask){ return (mask == 0 || mask == 3); } int get(int mask, int nmask){ int cnt = __builtin_popcount(mask ^ nmask); if (cnt == 0) return 0; if (cnt == 2) return (full(mask) ? 1 : 2); return (full(mask) ? 0 : 1); } int main() { int n, k; scanf("%d%d", &n, &k); forn(i, 4) dp[1][0][i] = 1; for (int i = 1; i < n; ++i){ forn(j, k + 1){ forn(mask, 4){ forn(nmask, 4){ dp[i + 1][j + get(mask, nmask)][nmask] = add(dp[i + 1][j + get(mask, nmask)][nmask], dp[i][j][mask]); } } } } int ans = 0; forn(mask, 4){ int nw = get(mask, mask ^ 3); if (k >= nw) ans = add(ans, dp[n][k - nw][mask]); } printf("%d\n", ans); }
1051
E
Vasya and Big Integers
Vasya owns three big integers — $a, l, r$. Let's define a partition of $x$ such a sequence of strings $s_1, s_2, \dots, s_k$ that $s_1 + s_2 + \dots + s_k = x$, where $+$ is a concatanation of strings. $s_i$ is the $i$-th element of the partition. For example, number $12345$ has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others. Let's call some partition of $a$ beautiful if each of its elements \textbf{contains no leading zeros}. Vasya want to know the number of beautiful partitions of number $a$, which has each of $s_i$ satisfy the condition $l \le s_i \le r$. Note that the comparison is the integer comparison, not the string one. Help Vasya to count the amount of partitions of number $a$ such that they match all the given requirements. The result can be rather big, so print it modulo $998244353$.
Let's use dynamic programming to solve the problem. Let $dp_x$ be the number of correct partitions for the long integer $a_x a_{x+1} \dots a_{n}$. It's easy to see that if we have two big integers without leading zeroes, we know the lengths of these integers, and these lengths are not equal, then we can determine which integer is greater in $O(1)$. We will calculate the answers in the following order: $dp_{|a|}, dp_{|a| - 1} \dots dp_1$. Suppose we want to calculate $dp_x$. Let $L$ be the minimum position such that the number $a_x a_x+1 \dots a_L$ meets the following condition: $l \le a_x a_x+1 \dots a_L \le r$. Let $R$ be the maximum position such that the number $a_x a_x+1 \dots a_R$ meets the following condition $l \le a_x a_x+1 \dots a_R \le r$. Initially let's consider $L = x + |l|$ and $R = x + |r|$. $L$ will be less if $a_x a_{x + 1} ... a_{x + |l|} < l$. $R$ will be less if $a_x a_{x + 1} ... a_{x + |r|} > r$. To determine which of the numbers $a_x a_{x + 1} ... a_{x + |l|}$ and $l$ is greater let's calculate z-function for the string $l + \# + a$, where $\#$ is any character that doesn't occur in $a$ and $l$. After calculating z-function we can easily find the first non-equal character in $a_x a_{x + 1} ... a_{x + |l|}$ and $l$, and this character will determine which number is greater. To compare $a_x a_{x + 1} ... a_{x + |r|}$ and $r$ we can act the same. All that's left is to set $dp_x$ to the sum of $dp$ values from $L$ to $R$. This can be done by maintaining suffix sums. There is a corner case, which applies when $a_x = 0$. If $l > 0$, then $dp_x = 0$ because we cannot afford any leading zeroes. Otherwise $dp_x = dp_{x + 1}$.
[ "binary search", "data structures", "dp", "hashing", "strings" ]
2,600
#include<bits/stdc++.h> using namespace std; #define sz(a) (int)(a.size()) const int N = int(1e6) + 9; const int MOD = 998244353; int n; string s, l, r; int dp[N]; int sumDP[N]; int sum(int a, int b){ a += b; if(a >= MOD) a -= MOD; return a; } vector <int> z_function(string s){ int n = sz(s); vector <int> z(n); for(int i = 1, l = 0, r = 0; i < n; ++i){ if(i <= r) z[i] = min(r - i + 1, z[i - l]); while(i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i]; if(i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } return z; } //s[pos..] ? t char cmp(vector <int> &zf, string &t, int pos){ int len = sz(t); assert(pos + len + 1 < sz(zf)); if(sz(s) - pos < len) return '<'; int x = zf[len + 1 + pos]; assert(x <= len); if(x == len) return '='; assert(pos + x < sz(s)); assert(s[pos + x] != t[x]); if(s[pos + x] < t[x]) return '<'; return '>'; } int main() { //freopen("input.txt", "r", stdin); ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> s >> l >> r; n = int(s.size()); vector <int> zl = z_function(l + "#" + s); vector <int> zr = z_function(r + "#" + s); sumDP[n] = dp[n] = 1; for(int i = n - 1; i >= 0; --i){ if(s[i] == '0'){ if(l == "0") dp[i] = dp[i + 1]; else dp[i] = 0; sumDP[i] = sum(dp[i], sumDP[i + 1]); continue; } int L = sz(l) + i; char cl = cmp(zl, l, i); if(cl == '<') ++L; int R = sz(r) + i; char cr = cmp(zr, r, i); if(cr == '>') --R; int cur = 0; if(L <= R && L <= n){ R = min(R, n); cur = sumDP[L]; if(R != n) cur = sum(cur, MOD - sumDP[R + 1]); } dp[i] = cur; sumDP[i] = sum(dp[i], sumDP[i + 1]); } cout << dp[0] << endl; return 0; }
1051
F
The Shortest Statement
You are given a weighed undirected \textbf{connected} graph, consisting of $n$ vertices and $m$ edges. You should answer $q$ queries, the $i$-th query is to find the shortest distance between vertices $u_i$ and $v_i$.
Firstly let's find any spanning tree and root it at any vertex. For each vertex we calculate the distance to the root (let it be $h_v$ for vertex $v$). There are no more than $21$ edges that don't belong to the tree. For each of these edges, let's run Dijkstra's algorithm from some vertex incident to this edge. Suppose we are answering a query $u$ $v$. If the shortest path between these vertices passes only along the edges of the tree, then it can be calculated by the formula $h_v + h_u - 2h_{lca(u, v)}$, where $lca(u, v)$ is the lowest common ancestor of vertices $u$ and $v$. You may use any fast enough algorithm you know to calculate $lca(u, v)$. Otherwise there exists at least one vertex such that we ran Dijkstra's algorithm from it, and it belongs to the shortest path. Just iterate on every vertex for which we ran Dijkstra and update the answer with the value of $d_u + d_v$, where $d_x$ is the shortest path to the vertex $x$ from the fixed vertex.
[ "graphs", "shortest paths", "trees" ]
2,400
#include <bits/stdc++.h> using namespace std; const int N = 300 * 1000 + 9; const int LOGN = 19; const int M = 21; const long long INF64 = 1e18; int n, m, q; vector <pair<int, int> > g[N]; int p[LOGN][N]; int tin[N], tout[N], T; long long h[N]; set <pair<int, int> > badEdges; long long d[M + M][N]; bool u[N]; void dfs(int v, int pr){ tin[v] = T++; p[0][v] = pr; u[v] = true; for(int i = 1; i < LOGN; ++i) p[i][v] = p[i - 1][ p[i - 1][v] ]; for(auto e : g[v]){ int to = e.first, len = e.second; if(!u[to]){ h[to] = h[v] + len; dfs(to, v); if(v < to) badEdges.erase(make_pair(v, to)); else badEdges.erase(make_pair(to, v)); } } tout[v] = T; } bool isAncestor(int a, int b){ return tin[a] <= tin[b] && tout[a] >= tout[b]; } int getLCA(int a, int b){ if(isAncestor(a, b)) return a; if(isAncestor(b, a)) return b; for(int i = LOGN - 1; i >= 0; --i) if(!isAncestor(p[i][a], b)) a = p[i][a]; return p[0][a]; } void dij(int st, long long d[N]){ set<pair<long long, int> > q; for(int i = 0; i < n; ++i) d[i] = INF64; d[st] = 0; q.insert(make_pair(d[st], st)); while(!q.empty()){ int v = q.begin()->second; q.erase(q.begin()); for(auto e : g[v]){ int to = e.first, len = e.second; if(d[to] > d[v] + len){ q.erase(make_pair(d[to], to)); d[to] = d[v] + len; q.insert(make_pair(d[to], to)); } } } } int main() { //freopen("input.txt", "r", stdin); scanf("%d %d", &n, &m); for(int i = 0; i < m; ++i){ int u, v, w; scanf("%d %d %d", &u, &v, &w); --u, --v; g[u].push_back(make_pair(v, w)); g[v].push_back(make_pair(u, w)); } for(int v = 0; v < n; ++v) for(auto e : g[v]) if(v < e.first) badEdges.insert(make_pair(v, e.first)); dfs(0, 0); int cpos = 0; for(auto e : badEdges) dij(e.first, d[cpos++]); scanf("%d", &q); for(int tc = 0; tc < q; ++tc){ int u, v; scanf("%d %d", &u, &v); --u, --v; int lca = getLCA(u, v); long long ans = h[u] + h[v] - 2 * h[lca]; for(int i = 0; i < badEdges.size(); ++i) ans = min(ans, d[i][u] + d[i][v]); printf("%lld\n", ans); } return 0; }
1051
G
Distinctification
Suppose you are given a sequence $S$ of $k$ pairs of integers $(a_1, b_1), (a_2, b_2), \dots, (a_k, b_k)$. You can perform the following operations on it: - Choose some position $i$ and \textbf{increase} $a_i$ by $1$. That can be performed only if there exists at least one such position $j$ that $i \ne j$ and $a_i = a_j$. The cost of this operation is $b_i$; - Choose some position $i$ and \textbf{decrease} $a_i$ by $1$. That can be performed only if there exists at least one such position $j$ that $a_i = a_j + 1$. The cost of this operation is $-b_i$. Each operation can be performed arbitrary number of times (possibly zero). Let $f(S)$ be minimum possible $x$ such that there exists a sequence of operations with total cost $x$, after which all $a_i$ from $S$ are pairwise distinct. Now for the task itself ... You are given a sequence $P$ consisting of $n$ pairs of integers $(a_1, b_1), (a_2, b_2), \dots, (a_n, b_n)$. All $b_i$ are pairwise distinct. Let $P_i$ be the sequence consisting of the first $i$ pairs of $P$. Your task is to calculate the values of $f(P_1), f(P_2), \dots, f(P_n)$.
Let's firstly try to come up with some naive solution. Suppose we have a list $S$ and want to calculate $f(S)$ for it. Let's sort this list, comparing the pairs by their values of $a_i$, and then process them one-by-one. We will divide this list into some parts (we will call them components) with the following process: when processing the first pair in the sorted order, let's iterate on the next pairs (also in the sorted order) and add them to the first pair's component until the following condition is met: $a_y - a_x > y - x$, where $x$ is the index of the first pair we added, and $y$ is the index of the pair we are currently trying to add to $x$'s component (remember that we consider all these pairs in the sorted order). What is the meaning of this condition? $a_y - a_x \le y - x$ means that the number of pairs between $x$ and $y$ (including these two) is not less that the number of integers in $[a_x, a_y]$ - and while this condition is met, we can use the first operation in order to make a pair having $a_i = z$ for every $z \in [x, y]$. And the first time when the condition $a_y - a_x > y - x$ is met, we obviously cannot "expand" the segment in such a way. It means that the $a$-value of $y$ will always be greater than $a$-value of $x$, and $y$ won't belong to the same component with $x$ (and will start creating its own component instead). These components we form have one special property. Suppose we "expanded" the component so that there are no two equal values of $a_i$ in it. Then we may reorder the pairs in this component as we wish (to do so, we may "contract" the component using the second operation, and then "expand" it again). Of course, the best course of action is to sort the pairs in the component by their values of $b_i$ in descending order. After doing this for every component, we will obtain an optimal configuration such that all values of $a_i$ are distinct, and it's easy to calculate the answer. Okay, now we need to do it fast. The following will help us: DSU; Some implicit logarithmic data structure (the operations we need are "count the sum of elements less than $x$" and "count the number of elements greater than $y$"; your implementation might use other operations); Small-to-large merging. DSU will help us maintain the components. A data structre will be built for each component containing the values of $b_i$ in it; it will help us to maintain the sum of $opt(i) b_i$, where $opt(i)$ is the optimal index of $b_i$ in this component. Depending on your implementation, you may or may not need to store the minimum value of $a_i$ in the component. When inserting some element having $b_i = b$ into some component, the elements having $b_i > b$ don't change their position, the new element will be added right after them, and the remaining elements will be shifted to the right; so the sum of $opt(i) b_i$ can be maintained if we query the number of elements greater than $b$ and the sum of elements less than $b$. Okay, but we still don't know how we create the components and how we determine if two components are to merge. We will keep these components in "expanded" form; that is, when processing a pair $(a_i, b_i)$, let's find the leftmost unoccupied position after $a_i$ (or $a_i$, if it is not occupied) and occupy it with the new pair, creating a new component for it. If the newly occupied index is $pos$, let's try to merge new component with components occupying $pos - 1$ and $pos + 1$ (if there are any); to merge two components, do the required operations in DSU and unite the data structures built in these components with small-to-large method. All this works in $O(n \log^2 n)$, the most time-consuming part is merging the data structures.
[ "data structures", "dsu", "greedy" ]
2,900
#include <bits/stdc++.h> using namespace std; #define x first #define y second typedef long long li; mt19937 rnd(time(NULL)); struct node { int x; int y; li sum; int siz; node* l; node* r; node() {}; node(int x, int y, li sum, int siz, node* l, node* r) : x(x), y(y), sum(sum), siz(siz), l(l), r(r) {}; }; typedef node* treap; typedef pair<treap, treap> ptt; int getSiz(treap t) { return (t ? t->siz : 0); } li getSum(treap t) { return (t ? t->sum : 0); } treap fix(treap t) { if(!t) return t; t->sum = getSum(t->l) + t->x + getSum(t->r); t->siz = getSiz(t->l) + 1 + getSiz(t->r); return t; } ptt split(treap t, int l) { t = fix(t); if(!t) return make_pair(t, t); if(t->x < l) { auto z = split(t->r, l); t->r = z.x; return make_pair(fix(t), z.y); } else { auto z = split(t->l, l); t->l = z.y; return make_pair(z.x, fix(t)); } } treap merge(treap a, treap b) { a = fix(a); b = fix(b); if(!a) return b; if(!b) return a; if(a->y > b->y) { a->r = merge(a->r, b); return fix(a); } else { b->l = merge(a, b->l); return fix(b); } } struct comp { li cur_sum; int beg; li treap_sum; treap t; void upd() { cur_sum = treap_sum + beg * 1ll * getSum(t); } void insert(int bi) { ptt p = split(t, bi); treap_sum += getSum(p.x) + getSiz(p.y) * 1ll * bi; t = merge(p.x, merge(new node(bi, rnd(), bi, 1, NULL, NULL), p.y)); upd(); } void fill_treap(treap t) { if(!t) return; insert(t->x); fill_treap(t->l); fill_treap(t->r); } }; comp merge(comp a, comp b) { if(getSiz(a.t) < getSiz(b.t)) swap(a, b); a.beg = min(a.beg, b.beg); a.fill_treap(b.t); delete b.t; a.upd(); return a; } set<int> free_pos; const int N = 400043; int p[N]; int siz[N]; comp cc[N]; li start_sum = 0; li end_sum = 0; int get(int x) { return (p[x] == x ? x : (p[x] = get(p[x]))); } void merge(int x, int y) { x = get(x); y = get(y); if(x == y) return; if(siz[x] < siz[y]) swap(x, y); end_sum -= cc[x].cur_sum; end_sum -= cc[y].cur_sum; p[y] = x; siz[x] += siz[y]; cc[x] = merge(cc[x], cc[y]); end_sum += cc[x].cur_sum; } void process(int ai, int bi) { start_sum += ai * 1ll * bi; int pos = *free_pos.lower_bound(ai); free_pos.erase(pos); siz[pos] = 1; p[pos] = pos; cc[pos].beg = pos; cc[pos].insert(bi); end_sum += cc[pos].cur_sum; if(!free_pos.count(pos - 1)) merge(pos, pos - 1); if(!free_pos.count(pos + 1)) merge(pos, pos + 1); printf("%lld\n", end_sum - start_sum); } int main() { #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n; scanf("%d", &n); for(int i = 0; i < N; i++) free_pos.insert(i); for(int i = 0; i < n; i++) { int a, b; scanf("%d %d", &a, &b); process(a, b); } return 0; }
1053
E
Euler tour
Euler is a little, cute squirrel. When the autumn comes, he collects some reserves for winter. The interesting fact is that Euler likes to collect acorns in a specific way. A tree can be described as $n$ acorns connected by $n - 1$ branches, such that there is exactly one way between each pair of acorns. Let's enumerate the acorns from $1$ to $n$. The squirrel chooses one acorn (not necessary with number $1$) as a start, and visits them in a way called "Euler tour" (see notes), collecting each acorn when he visits it for the last time. Today morning Kate was observing Euler. She took a sheet of paper and wrote down consecutive indices of acorns on his path. Unfortunately, during her way to home it started raining and some of numbers became illegible. Now the girl is very sad, because she has to present the observations to her teacher. "Maybe if I guess the lacking numbers, I'll be able to do it!" she thought. Help her and restore any valid Euler tour of some tree or tell that she must have made a mistake.
First let's try to find some conditions whether it is possible to recover correct euler tour. Of course for every euler tour $a_i$ $\neq$ $a_{i+1}$ and $a_1$ $=$ $a_{2n-1}$ (because we start and finish in root). Moreover if there exist four index $i_1$ $<$ $i_2$ $<$ $i_3$ $<$ $i_4$ such that $a_{i_1}$ $=$ $a_{i_3}$ and $a_{i_2}$ $=$ $a_{i_4}$ and $a_{i_1}$ $\neq$ $a_{i_2}$ than answer is $NO$ (because vertex is an ancestor of another o there is no relation between them). There is one more tricky condition - parity of positions of all occurences of element $x$ is the same. Also, between two equal elements with distance $2k$ there can be at most $k$ distinct elements. It turns out that those conditions are sufficient - we will prove it by constructing an answer. So first let's observe that if we have to equal elements it means that there is subtree between them - we can solve it independently from the rest of a tree and then forget about this subtree. So as long as we have two equal elements $i$ $<$ $j$ than we can first solve euler tour between them and then delete elements $i+1,i+2...,j$. So now we want to solve euler tour where no element occur more than once. Let's say that this tour has length $2k-1$ then if we have less than $k$ elements we can replace any $0$ with any unused elements. Now if there are three elements in a row with values $x,y,0$ or $0,y,x$ than we can replace them with $x,y,x$ and forget about it. If we get rid of all triplets like this than we have tour in form of $a_1,0,a_2,0,...,0,a_k$. It's easy to observe that we can replace every $0$ with our root (subtree's root). There is a special case when we don't have any root (if solving for whole tree), than we have to find any vertex which can be root and then solve our problem. Straightforward implementation will be $O(n^2)$ but it can be easily reduced to $O(nlogn)$ and it can be even reduced to $O(n)$, but $O(nlogn)$ was enough to be accepted. More details about reducing $O(n^2)$ to $O(n)$ in code.
[ "constructive algorithms", "trees" ]
3,500
#include <bits/stdc++.h> using namespace std; #define st first #define nd second #define PII pair <int, int> const int N = 1e6 + 7; int n; int in[N]; int ans[N]; bool used[N]; vector <int> unused; int cnt; deque <PII> cur; vector <PII> getEqual; set <int> S; vector <int> place[N]; vector <pair <int, int> > order; bool check(){ if(in[1] != 0 && in[n + n - 1] != 0 && in[1] != in[n + n - 1]) return false; for(int i = 1; i + 1 < n + n; ++i) if(in[i] == in[i + 1] && in[i] != 0) return false; for(int i = 1; i < n + n; ++i){ if(in[i] == 0) continue; if(place[in[i]].size() == 0) order.push_back({i, in[i]}); place[in[i]].push_back(i); } for(int i = 1; i <= n; ++i) for(int j = 1; j < place[i].size(); ++j) if(place[i][j]%2 != place[i][j - 1]%2) return false; S.insert(n + n); sort(order.begin(), order.end()); for(auto v: order){ auto it = S.lower_bound(v.first); if(*it < place[v.second].back()) return false; for(int c: place[v.second]) S.insert(c); } return true; } inline int get(){ if(unused.size() == 0){ puts("no"); exit(0); } int ret = unused.back(); unused.pop_back(); return ret; } void go(){ deque <PII> help; while(help.size() + cur.size() >= 3){ if(help.size() < 3){ help.push_back(cur.front()); cur.pop_front(); continue; } PII v1 = help.back(); help.pop_back(); PII v2 = help.back(); help.pop_back(); PII v3 = help.back(); help.pop_back(); if(v1.st == 0 && v2.st != 0 && v3.st != 0){ ans[v1.nd] = v3.st; help.push_back(v3); } else{ help.push_back(v3); help.push_back(v2); help.push_back(v1); } if(cur.size() == 0) break; help.push_back(cur.front()); cur.pop_front(); } while(help.size()){ cur.push_back(help.front()); help.pop_front(); } } void solve(int root){ int need = (cur.size() + 1) / 2 - cnt; if(need < 0){ puts("no"); exit(0); } deque <PII> help; while(cur.size()){ auto v = cur.front(); cur.pop_front(); if(need > 0 && v.st == 0){ --need; v.st = get(); ans[v.nd] = v.st; } help.push_back(v); } while(help.size()){ cur.push_front(help.front()); help.pop_front(); } go(); if(root == -1 && cur.back().st == 0){ root = cur.front().st; ans[cur.back().nd] = root; cur.pop_front(); cur.pop_back(); solve(root); return; } reverse(cur.begin(), cur.end()); go(); while(cur.size() > 0){ auto v = cur.front(); cur.pop_front(); if(v.st == 0) ans[v.nd] = root; } } int main(){ scanf("%d", &n); for(int i = 1; i < n + n; ++i){ scanf("%d", &in[i]); used[in[i]] = true; } if(!check()){ puts("no"); return 0; } if(in[1] != 0) in[n + n - 1] = in[1]; else if(in[n + n - 1] != 0) in[1] = in[n + n - 1]; for(int i = 1; i <= n; ++i){ if(!used[i]) unused.push_back(i); used[i] = false; } for(int i = 1; i < n + n; ++i) ans[i] = in[i]; for(int i = 1; i < n + n; ++i){ if(in[i] == 0){ getEqual.push_back({in[i], i}); continue; } if(used[in[i]]){ cnt = 0; while(getEqual.back().st != in[i]){ if(getEqual.back().st > 0){ ++cnt; used[getEqual.back().st] = false; } cur.push_front(getEqual.back()); getEqual.pop_back(); } solve(in[i]); continue; } getEqual.push_back({in[i], i}); used[in[i]] = true; } cnt = 0; while(getEqual.size()){ if(getEqual.back().st > 0){ ++cnt; used[getEqual.back().st] = false; } cur.push_front(getEqual.back()); getEqual.pop_back(); } solve(-1); puts("yes"); for(int i = 1; i < n + n; ++i) printf("%d%c", ans[i], i == n + n - 1 ? '\n' : ' '); return 0; }
1054
A
Elevator or Stairs?
Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor $x$, Egor on the floor $y$ (not on the same floor with Masha). The house has a staircase and an elevator. If Masha uses the stairs, it takes $t_1$ seconds for her to walk between adjacent floors (in each direction). The elevator passes between adjacent floors (in each way) in $t_2$ seconds. The elevator moves with doors closed. The elevator spends $t_3$ seconds to open or close the doors. We can assume that time is not spent on any action except moving between adjacent floors and waiting for the doors to open or close. If Masha uses the elevator, it immediately goes directly to the desired floor. Coming out of the apartment on her floor, Masha noticed that the elevator is now on the floor $z$ and has closed doors. Now she has to choose whether to use the stairs or use the elevator. If the time that Masha needs to get to the Egor's floor by the stairs is \textbf{strictly} less than the time it will take her using the elevator, then she will use the stairs, otherwise she will choose the elevator. Help Mary to understand whether to use the elevator or the stairs.
The time needed if we use stairs is $|x - y| \cdot t_1$. The time needed if we use elevator is $|z - x| \cdot t_2 + |x - y| \cdot t_2 + 3 \cdot t_3$. We can simply compute this values and compare them. Time complexity: $O(1)$.
[ "implementation" ]
800
#include <bits/stdc++.h> using namespace std; int x, y, z, t1, t2, t3; int main() { cin >> x >> y >> z >> t1 >> t2 >> t3; if (abs(z - x) * t2 + abs(x - y) * t2 + 3 * t3 <= abs(x - y) * t1) cout << "YES"; else cout << "NO"; return 0; }
1054
B
Appending Mex
Initially Ildar has an empty array. He performs $n$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest \textbf{non-negative} integer not presented in the multiset. For example, the mex of the multiset $[0, 2, 3]$ is $1$, while the mex of the multiset $[1, 2, 1]$ is $0$. More formally, on the step $m$, when Ildar already has an array $a_1, a_2, \ldots, a_{m-1}$, he chooses some subset of indices $1 \leq i_1 < i_2 < \ldots < i_k < m$ (possibly, empty), where $0 \leq k < m$, and appends the $mex(a_{i_1}, a_{i_2}, \ldots a_{i_k})$ to the end of the array. After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $a_1, a_2, \ldots, a_n$ the minimum step $t$ such that he has definitely made a mistake on at least one of the steps $1, 2, \ldots, t$, or determine that he could have obtained this array without mistakes.
Ildar has written an array correctly if there exists numbers $0, 1, \ldots, a_i-1$ to the left of $a_i$ for all $i$. This is equivalent to $a_i \leq max(-1, a_1, a_2, \ldots, a_{i-1}) + 1$ for all $i$. If this condition is false for some $i$ we made a mistake. So the solution is to check that $a_i \leq max(-1, a_1, a_2, \ldots, a_{i-1}) + 1$ in the increasing order of $i$. If it is false $i$ is answer. If it is always true answer is $-1$. Time complexity: $O(n)$.
[ "implementation" ]
1,000
#include <bits/stdc++.h> using namespace std; int n, a, m; int main() { ios::sync_with_stdio(0); cin >> n; m = -1; for (int i = 0; i < n; i++) { cin >> a; if (a > m + 1) { cout << i + 1; return 0; } m = max(m, a); } cout << -1; return 0; }
1054
C
Candies Distribution
There are $n$ children numbered from $1$ to $n$ in a kindergarten. Kindergarten teacher gave $a_i$ ($1 \leq a_i \leq n$) candies to the $i$-th child. Children were seated in a row in order from $1$ to $n$ from left to right and started eating candies. While the $i$-th child was eating candies, he calculated two numbers $l_i$ and $r_i$ — the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively. Formally, $l_i$ is the number of indices $j$ ($1 \leq j < i$), such that $a_i < a_j$ and $r_i$ is the number of indices $j$ ($i < j \leq n$), such that $a_i < a_j$. Each child told to the kindergarten teacher the numbers $l_i$ and $r_i$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $l$ and $r$ determine whether she could have given the candies to the children such that all children correctly calculated their values $l_i$ and $r_i$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.
Let's note that for any $i$, the value of $(l_i + r_i)$ is equal to the number of children who got more candies than $i$-th. So, $(n - l_i - r_i)$ is equal to the number of children who got less or equal number of candies than $i$-th (including himself). So, if there exists an array $a$ satisfying the conditions, then its numbers are ordered exactly as well as the numbers in the array $(n - l_i - r_i)$ (if the numbers at two positions are equal in one of the arrays, then they are equal in the other; if in one of the arrays at one position the number is less than the number at the other position, it is true for the other array). Also $1 \leq (n - l_i - r_i) \leq n$ for any $i$. Thus, if there exists an array $a$ satisfying the conditions, then the array $a_i = (n - l_i-r_i)$ also satisfies the conditions. So, you just need to take the array ai=(n-li-ri) and check it. If it satisfies conditions, the answer is this array, otherwise, there are no such arrays at all. The check can be performed using a trivial algorithm that works for O(n2) time. Time complexity: O(n2).
[ "constructive algorithms", "implementation" ]
1,500
#include <bits/stdc++.h> using namespace std; const int M = 1010; int n, a[M], l[M], r[M]; int main() { cin >> n; for (int i = 0; i < n; i++) cin >> l[i]; for (int i = 0; i < n; i++) cin >> r[i]; for (int i = 0; i < n; i++) a[i] = (n - l[i] - r[i]); for (int i = 0; i < n; i++) for (int j = 0; j < i; j++) l[i] -= (a[j] > a[i]); for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) r[i] -= (a[j] > a[i]); for (int i = 0; i < n; i++) if (l[i] != 0 || r[i] != 0) { cout << "NO\n"; return 0; } cout << "YES\n"; for (int i = 0; i < n; i++) cout << a[i] << " "; return 0; }
1054
D
Changing Array
At a break Vanya came to the class and saw an array of $n$ $k$-bit integers $a_1, a_2, \ldots, a_n$ on the board. An integer $x$ is called a $k$-bit integer if $0 \leq x \leq 2^k - 1$. Of course, Vanya was not able to resist and started changing the numbers written on the board. To ensure that no one will note anything, Vanya allowed himself to make only one type of changes: choose an index of the array $i$ ($1 \leq i \leq n$) and replace the number $a_i$ with the number $\overline{a_i}$. We define $\overline{x}$ for a $k$-bit integer $x$ as the $k$-bit integer such that all its $k$ bits differ from the corresponding bits of $x$. Vanya does not like the number $0$. Therefore, he likes such segments $[l, r]$ ($1 \leq l \leq r \leq n$) such that $a_l \oplus a_{l+1} \oplus \ldots \oplus a_r \neq 0$, where $\oplus$ denotes the bitwise XOR operation. Determine the maximum number of segments he likes Vanya can get applying zero or more operations described above.
We need to maximize the number of segments with XOR-sum of its elements not equal to 0. Let's note that the total number of segments is (n+12)=n \cdot (n+1)/2 so we need to minimize the number of segments with XOR-sum of its elements equal to 0. Let's call such segments bad. Consider the prefix XOR sums of array a. Let's define pi=a1 \oplus \dots \oplus ai for any 0 \le i \le n. Note that the segment [l,r] is bad if prl-1=prr. How does an array p changes in a single operation with an array a? Let's note that \bar x=x \oplus (2k-1). If we do operation with the element i then in array p all elements pj (j \ge i) will change to pj \oplus (2k-1) or \bar pj. So after all operations, element of p will be either equal to itself before operations or will be equal to itself before operations but with all changed bits. But p0=0 still. On the other hand. Suppose that there are some changes of this kind in the array p. Let's prove that we could make some operations in the array a so that p will be changed and became exactly the same. To prove this, note that ai=pi-1 \oplus pi, so all values of ai have either not changed or have changed to numbers with all changed bits. So let's just assume that we are changing the array p (all its elements except the element with index 0), not the array a. Let's note that two numbers x and y can become equal after all operations with them if they are equal or x= \bar y. So we can replace pi with min(pi, \bar pi) for any i in the array p. The answer will be the same if we do this. But it will be impossible to get equal numbers from different numbers in the new array. Let's calculate for each number c the number of its occurrences in the array p and denote it for k. Some of this k numbers we can leave equal to c, and some of them we change to \bar c. Let's change 0 \le a \le k numbers. Then we want to minimize the number of pairs of equal numbers, which is (k-a+12)+(a+12). To do this, we need to change and not change the approximately equal number of numbers, that is, the minimum is reached at a= \lfloor k/2 \rfloor . It can be proved simply. So we should divide the numbers this way for any c and sum the answers. For each number c, the number of its occurrences in the array can be calculated using the sorting algorithm or the std::map structure into the C++ language. Time complexity: O(n \cdot log(n)).
[ "greedy", "implementation" ]
1,900
#include <bits/stdc++.h> using namespace std; typedef long long ll; int n, k; ll gett(int k) { return ((ll)k * (ll)(k - 1)) / 2LL; } int main() { cin.sync_with_stdio(0); cin >> n >> k; int a = 0; ll ans = 0; map<int, int> kol; kol[0] = 1; for (int i = 1; i <= n; i++) { int b; cin >> b; a ^= min(b, (1 << k) - 1 - b); kol[a]++; } for (pair<int, int> t : kol) { ans += gett(t.second / 2); ans += gett((t.second + 1) / 2); } cout << gett(n + 1) - ans; return 0; }
1054
E
Chips Puzzle
Egor came up with a new chips puzzle and suggests you to play. The puzzle has the form of a table with $n$ rows and $m$ columns, each cell can contain several black or white chips placed in a row. Thus, the state of the cell can be described by a string consisting of characters '0' (a white chip) and '1' (a black chip), possibly empty, and the whole puzzle can be described as a table, where each cell is a string of zeros and ones. The task is to get from one state of the puzzle some other state. To do this, you can use the following operation. - select 2 different cells $(x_1, y_1)$ and $(x_2, y_2)$: the cells must be in the same row or in the same column of the table, and the string in the cell $(x_1, y_1)$ must be non-empty; - in one operation you can move the last character of the string at the cell $(x_1, y_1)$ to the beginning of the string at the cell $(x_2, y_2)$. Egor came up with two states of the table for you: the initial state and the final one. It is guaranteed that the number of zeros and ones in the tables are the same. Your goal is with several operations get the final state from the initial state. Of course, Egor does not want the number of operations to be very large. Let's denote as $s$ the number of characters in each of the tables (which are the same). Then you should use no more than $4 \cdot s$ operations.
Our usual operation - is to move the last character of a string in one cell to the beginning of a string in another cell. If we do the reverse operation - to move the first character of a string in one cell to the end of a string in another cell, then it's like we will do our operation for reversed strings and at the end, we will reverse them again. Let's learn how to bring a table to a fixed one for \le 2 \cdot s operations. After that, to solve our problem, we can bring the initial state to a fixed and final state (we should reverse all the strings in it) to a fixed. After that, if you reverse the second order of operations and add to the first, we get the solution to the problem. Our fixed table is a table in which the cell (2,1) contains all 1 and the cell (1,2) contains all 0. How to make this table from any table using \le 2 \cdot s operations? First, we move all the characters of the first column and the first row to the cell (1,1). Next, let's move all the characters of the rectangle with angles of (2,2) and (n,m) to the first column if it is 1, and to the first row if it is 0. This will take \le s operations. Next, let's move all the characters in the first column (except the (1,1)) into the (2,1) cell and all the characters in the first row (except the (1,1) cell) into the (1,2) cell. Finally, let's move the symbols of (1,1) to (2,1) if it is 1 or (1,2) if it is 0. Time complexity: O(s). Bonus: What is the minimum constant c you can get so that the algorithm always performs \le c \cdot s operations? (c may depends on n, m)
[ "constructive algorithms", "implementation", "math" ]
2,400
#include <bits/stdc++.h> using namespace std; const int two = 2; const int N = 310; const int S = 200100; int n, m; string s[two][N][N]; int k[two]; tuple<int, int, int, int> ans[two][S]; queue<char> in[N][N]; void func(int c) { k[c] = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { while (!in[i][j].empty()) in[i][j].pop(); for (int x = (int)s[c][i][j].size() - 1; x >= 0; x--) in[i][j].push(s[c][i][j][x]); } for (int i = 1; i < m; i++) while (!in[0][i].empty()) { ans[c][k[c]] = make_tuple(0, i, 0, 0); in[0][0].push(in[0][i].front()); in[0][i].pop(); k[c]++; } for (int i = 1; i < n; i++) while (!in[i][0].empty()) { ans[c][k[c]] = make_tuple(i, 0, 0, 0); in[0][0].push(in[i][0].front()); in[i][0].pop(); k[c]++; } while (!in[0][0].empty()) { if (in[0][0].front() == '0') { ans[c][k[c]] = make_tuple(0, 0, 0, 1); in[0][1].push(in[0][0].front()); in[0][0].pop(); k[c]++; } else { ans[c][k[c]] = make_tuple(0, 0, 1, 0); in[1][0].push(in[0][0].front()); in[0][0].pop(); k[c]++; } } for (int i = 1; i < n; i++) for (int j = 1; j < m; j++) while (!in[i][j].empty()) { if (in[i][j].front() == '0') { ans[c][k[c]] = make_tuple(i, j, 0, j); in[0][j].push(in[i][j].front()); in[i][j].pop(); k[c]++; } else { ans[c][k[c]] = make_tuple(i, j, i, 0); in[i][0].push(in[i][j].front()); in[i][j].pop(); k[c]++; } } for (int i = 2; i < m; i++) while (!in[0][i].empty()) { ans[c][k[c]] = make_tuple(0, i, 0, 1); in[0][1].push(in[0][i].front()); in[0][i].pop(); k[c]++; } for (int i = 2; i < n; i++) while (!in[i][0].empty()) { ans[c][k[c]] = make_tuple(i, 0, 1, 0); in[0][1].push(in[i][0].front()); in[i][0].pop(); k[c]++; } } int main() { ios::sync_with_stdio(0); cin >> n >> m; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> s[0][i][j]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> s[1][i][j]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) reverse(s[1][i][j].begin(), s[1][i][j].end()); func(0); func(1); reverse(ans[1], ans[1] + k[1]); cout << (k[0] + k[1]) << "\n"; for (int i = 0; i < k[0]; i++) cout << get<0>(ans[0][i]) + 1 << " " << get<1>(ans[0][i]) + 1 << " " << get<2>(ans[0][i]) + 1 << " " << get<3>(ans[0][i]) + 1 << "\n"; for (int i = 0; i < k[1]; i++) cout << get<2>(ans[1][i]) + 1 << " " << get<3>(ans[1][i]) + 1 << " " << get<0>(ans[1][i]) + 1 << " " << get<1>(ans[1][i]) + 1 << "\n"; return 0; }
1054
F
Electric Scheme
Pasha is a young technician, nevertheless, he has already got a huge goal: to assemble a PC. The first task he has to become familiar with is to assemble an electric scheme. The scheme Pasha assembled yesterday consists of several wires. Each wire is a segment that connects two points on a plane with integer coordinates within the segment $[1, 10^9]$. There are wires of two colors in the scheme: - red wires: these wires are horizontal segments, i.e. if such a wire connects two points $(x_1, y_1)$ and $(x_2, y_2)$, then $y_1 = y_2$; - blue wires: these wires are vertical segments, i.e. if such a wire connects two points $(x_1, y_1)$ and $(x_2, y_2)$, then $x_1 = x_2$. Note that if a wire connects a point to itself, it may be blue, and it can be red. Also, in Pasha's scheme no two wires of the same color intersect, i.e. there are no two wires of same color that have common points. The imperfection of Pasha's scheme was that the wires were not isolated, so in the points where two wires of different colors intersect, Pasha saw sparks. Pasha wrote down all the points where he saw sparks and obtained a set of $n$ distinct points. After that he disassembled the scheme. Next morning Pasha looked at the set of $n$ points where he had seen sparks and wondered how many wires had he used. Unfortunately, he does not remember that, so he wonders now what is the smallest number of wires he might have used in the scheme. Help him to determine this number and place the wires in such a way that in the resulting scheme the sparks occur in the same places.
Let's reduce this problem to the problem of finding the minimum vertex cover in a bipartite graph. We need to build the following graph: in one part all horizontal segments between adjacent points by x from the set of points having the same y, in the other part all vertical segments between adjacent points by y from the set of points having the same x. We will make an edge between segments from different parts if they intersect strictly by internal point. It can be proved that the answer is equal to (the number of distinct x in the set) + (the number of distinct y in the set) + (the maximum matching in this graph). To prove this, you need to understand how the answer looks like. In any case, for any x from the set there will be \ge 1 vertical segment, with x1=x2=x and for any y from the set there will be \ge 1 horizontal segment, with y1=y2=y. If we draw such segments, some of them will intersect at a point that not from the set. In this case, we will have to cut some of these segments. At the same time, we want to cut as little number of segments as possible (cutting - erase part of the segment between adjacent points on this segment's horizontal/vertical). We can see, that all erased segments form a vertex cover (in the graph we built). But if you erase the segments from the minimum vertex cover, you will get the answer, and this answer will have the smallest size. So, it is necessary to find the minimum vertex cover in the constructed bipartite graph. This can be done by the standard algorithm uses O(V \cdot E)=O(n3) time. We can prove that E \le n2/4 and on practice it works very fast even for n=1000. Time complexity: O(n3). Bonus: how to solve this problem faster than for O(n3)? (if you don't need to find segments, only their number)
[ "flows", "graph matchings" ]
2,700
#include <bits/stdc++.h> using namespace std; const int M = 1010; int n; vector<pair<int, int> > pt; vector<int> vx, vy; vector<int> gx[M], gy[M]; vector<tuple<int, int, int> > sh, sv; int pa[M], pb[M], ln, lm; vector<int> v[M]; bool used[M], used1[M]; vector<int> dx[M], dy[M]; bool dfs(int p) { used[p] = true; for (int i : v[p]) { if (pb[i] == -1 || (!used[pb[i]] && dfs(pb[i]))) { pa[p] = i; pb[i] = p; return true; } } return false; } void dfs_set(int p) { used[p] = true; for (int i : v[p]) { used1[i] = true; if (pb[i] != -1 && !used[pb[i]]) dfs_set(pb[i]); } } void kuhn() { memset(pa, -1, sizeof(pa)); memset(pb, -1, sizeof(pb)); for (int i = 0; i < ln; i++) { memset(used, 0, sizeof(used)); if (dfs(i)) continue; } memset(used, 0, sizeof(used)); memset(used1, 0, sizeof(used1)); for (int i = 0; i < ln; i++) if (pa[i] == -1) dfs_set(i); for (int i = 0; i < ln; i++) used[i] = (!used[i]); } int main() { ios::sync_with_stdio(0); cin >> n; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; vx.push_back(x); vy.push_back(y); pt.push_back(make_pair(x, y)); } sort(vx.begin(), vx.end()); vx.resize(unique(vx.begin(), vx.end()) - vx.begin()); sort(vy.begin(), vy.end()); vy.resize(unique(vy.begin(), vy.end()) - vy.begin()); for (int i = 0; i < n; i++) { pt[i].first = lower_bound(vx.begin(), vx.end(), pt[i].first) - vx.begin(); pt[i].second = lower_bound(vy.begin(), vy.end(), pt[i].second) - vy.begin(); } for (int i = 0; i < n; i++) { gx[pt[i].first].push_back(pt[i].second); gy[pt[i].second].push_back(pt[i].first); } for (int i = 0; i < n; i++) sort(gx[i].begin(), gx[i].end()); for (int i = 0; i < n; i++) sort(gy[i].begin(), gy[i].end()); for (int y = 0; y < n; y++) if ((int)gy[y].size() > 1) for (int i = 0; i < (int)gy[y].size() - 1; i++) sh.push_back(make_tuple(gy[y][i], gy[y][i + 1], y)); for (int x = 0; x < n; x++) if ((int)gx[x].size() > 1) for (int i = 0; i < (int)gx[x].size() - 1; i++) sv.push_back(make_tuple(gx[x][i], gx[x][i + 1], x)); sort(sh.begin(), sh.end()); sort(sv.begin(), sv.end()); ln = sh.size(); lm = sv.size(); for (int i = 0; i < ln; i++) for (int j = 0; j < lm; j++) { if (!(get<0>(sh[i]) < get<2>(sv[j]) && get<2>(sv[j]) < get<1>(sh[i]))) continue; if (!(get<0>(sv[j]) < get<2>(sh[i]) && get<2>(sh[i]) < get<1>(sv[j]))) continue; v[i].push_back(j); } kuhn(); for (int y = 0; y < n; y++) if ((int)gy[y].size() >= 1) dy[y].push_back(gy[y][0]); for (int x = 0; x < n; x++) if ((int)gx[x].size() >= 1) dx[x].push_back(gx[x][0]); for (int i = 0; i < ln; i++) if (used[i]) { dy[get<2>(sh[i])].push_back(get<0>(sh[i])); dy[get<2>(sh[i])].push_back(get<1>(sh[i])); } for (int i = 0; i < lm; i++) if (used1[i]) { dx[get<2>(sv[i])].push_back(get<0>(sv[i])); dx[get<2>(sv[i])].push_back(get<1>(sv[i])); } for (int y = 0; y < n; y++) if ((int)gy[y].size() >= 1) dy[y].push_back(gy[y].back()); for (int x = 0; x < n; x++) if ((int)gx[x].size() >= 1) dx[x].push_back(gx[x].back()); int ans = 0; for (int y = 0; y < n; y++) ans += (int)dy[y].size(); ans /= 2; cout << ans << "\n"; for (int y = 0; y < n; y++) for (int i = 0; i < (int)dy[y].size(); i += 2) cout << vx[dy[y][i]] << " " << vy[y] << " " << vx[dy[y][i + 1]] << " " << vy[y] << "\n"; ans = 0; for (int x = 0; x < n; x++) ans += (int)dx[x].size(); ans /= 2; cout << ans << "\n"; for (int x = 0; x < n; x++) for (int i = 0; i < (int)dx[x].size(); i += 2) cout << vx[x] << " " << vy[dx[x][i]] << " " << vx[x] << " " << vy[dx[x][i + 1]] << "\n"; return 0; }